← Back to list

Titanic Survival Prediction using Danfo.js and TensorFlow.js

Introducing danfo.js: a Pandas-like library for JavaScript developers

Rising Odegua in Heartbeat · 2020-08-25 13:21 · 209 claps · 4.1 min read
#danfojs #tensorflowjs #javascript #machine-learning #heartbeat
Open on Medium ↗
Wiki topics: ML · Machine Learning EDU · Education & Learning 🌐 · Web Development 📚 · Books & Reading

Titanic Survival Prediction using Danfo.js and TensorFlow.js

‌Above, you wrote an async function because loading the dataset over the internet takes a few seconds, depending on your network. Inside the async function, you pass in the URL of the Titanic dataset to the read_csv function.

Next, you’ll perform some basic data pre-processing. The ctypes attribute returns the column data types:

df.ctypes.print()

From the data types table above, you’ll notice that there are two strong columns. The first is the Name column which contains the names of each passenger. From the head of the dataset you printed above, you’ll confirm that each name has a title. So you can extract these titles from the names, and this can serve as a new feature.

[embed]

In the code above, you’re calling the [apply](/@jsdata/s/danfojs/~/drafts/-MErV-qDPB_82CDD-utq/api-reference/series/series.apply) function in the Name column. The parameter to the [apply](/@jsdata/s/danfojs/~/drafts/-MErV-qDPB_82CDD-utq/api-reference/series/series.apply) function is a function that gets called on each element of the column. This function can be any JavaScript function.

So what exactly is the function doing? Well, it’s basically slicing each name and extracting the title. And finally, you’re using the result to replace the original name column. When you’re done, your output becomes:

‌You’ll notice we now have titles in place of names. You can easily one-hot encode this feature:

[embed]

In code cell above, you’re label encoding the Sex and Name columns. You loop over each column name, fit the encoder to the column, transform it, and finally reassign it to the DataFrame. The output is shown below:

‌Next, you’ll split the data, separating the features from the labels. In this task, you’re trying to predict the survival of a passenger. The Survival column is the first in the DataFrame, so you’ll use [iloc](/@jsdata/s/danfojs/~/drafts/-MErV-qDPB_82CDD-utq/api-reference/dataframe/danfo.dataframe.iloc) to subset the DataFrame:

let Xtrain,ytrain;
Xtrain = df.iloc({ columns: [`1:`] })
ytrain = df['Survived']

‌Next, you’ll scale the data using [MinMaxScaler](/@jsdata/s/danfojs/~/drafts/-MErV-qDPB_82CDD-utq/api-reference/general-functions/danfo.minmaxscaler). It’s important to scale your data before model training, as this will affect that process.

[embed]

‌In the code cell above, first, you created an instance from the MinMaxScaler class. Next, you fit the training data and finally, you transformed it. The output from the scaler is a DataFrame of the same size as the values scaled.

‌The full code for the load_process_data function becomes:

[embed]

Model building with TensorFlow.js‌

In this section, you’ll build a simple classification model using TensorFlow.js. If you’re not familiar with TensorFlow.js, you can start here.

Create a simple function called get_model. This will construct and return a model when called.

[embed]

‌In the code cell above, you’ve created a neural network with 4 layers. Note the input shape—this should be the same as your column numbers. Also, note that you used a sigmoid activation function in the output layer. This is because you’re working on a binary classification problem.

Next, you’ll create a function called train:

[embed]

‌This function calls the load_process_data function to retrieve training data as tensors and also calls the get_model to retrieve the model. Next, you compile the model by specifying an optimizer, a loss function, and a metric to report.

‌Next, you call the fit function on the model by passing the training data and labels (tensors), specifying a batch size, number of epochs, validation split size, and also a callback function to track training progress.

The training progress is printed to the console at the end of each epoch. Below is the full code snippet for loading data to start training your model:

[embed]

In your terminal, run the script with Node:

node app.js

This runs the script and displays the training progress after each epoch, as shown below:

‌After 15 epochs, we’ve reached an accuracy of about 83%. This can definitely be improved, but for the sake of simplicity, we’ll stop here.

Conclusion

‌In this tutorial, you’ve seen how to use danfo.js with TensorFlow.js to load and process data, as well as train a neural network, all in JavaScript. This is similar to the Pandas-TensorFlow packages in Python.

‌You’ll also notice that danfo.js provides a similar API as Pandas and can easily be picked up by Python developers.

‌As an extra task, you can try to do more feature engineering using danfo.js and try to improve the accuracy of your model.

‌Go danfo! 😎

Some important links:

[embed]Danfo.js Documentation danfo.js is an open-source, JavaScript library providing high-performance, intuitive, and easy-to-use data structures…danfo.jsdata.org

[embed]opensource9ja/danfojs danfo.js is an open-source, JavaScript library providing high performance, intuitive, and easy to use data structures…github.com

And that’s it! If you have questions, comments, or additions, don’t hesitate to use the comment section below.

Bye for now, and happy learning.

Connect with me on **Twitter.**

Connect with me on **LinkedIn.**

Editor’s Note: Heartbeat is a contributor-driven online publication and community dedicated to providing premier educational resources for data science, machine learning, and deep learning practitioners. We’re committed to supporting and inspiring developers and engineers from all walks of life.

Editorially independent, Heartbeat is sponsored and published by Comet, an MLOps platform that enables data scientists & ML teams to track, compare, explain, & optimize their experiments. We pay our contributors, and we don’t sell ads.

If you’d like to contribute, head on over to our call for contributors. You can also sign up to receive our weekly newsletters (Deep Learning Weekly and the Comet Newsletter), join us on Slack, and follow Comet on Twitter and LinkedIn for resources, events, and much more that will help you build better ML models, faster.


메타데이터
post_id
89b80fbe31d1
slug
titanic-survival-prediction-using-danfo-js-and-tensorflow-js-89b80fbe31d1
url
https://heartbeat.comet.ml/titanic-survival-prediction-using-danfo-js-and-tensorflow-js-89b80fbe31d1
canonical_url
https://heartbeat.comet.ml/titanic-survival-prediction-using-danfo-js-and-tensorflow-js-89b80fbe31d1
author_url
https://medium.com/@risingdeveloper
status
ok
fetched_at
2026-07-18 00:16:15