tensorflow.js
model training
csv file
machine learning
data preprocessing

How to train a tensorflow.js model using a csv file?

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

Training a TensorFlow.js model from a CSV file usually means building a dataset pipeline, converting rows into tensors, and fitting a model with fitDataset. The workflow is easier in Node.js because local file access is straightforward, but the same ideas apply in browser-based projects after data loading. The key is to separate three concerns clearly: reading the CSV, mapping rows into features and labels, and defining a model whose input shape matches the data.

Read The CSV As A Dataset

TensorFlow.js provides tf.data.csv, which turns a CSV source into a streaming dataset. In Node.js, a local file path is typically prefixed with file://.

javascript
1const tf = require("@tensorflow/tfjs-node");
2
3function loadCsv() {
4  return tf.data.csv("file://./data/iris.csv", {
5    columnConfigs: {
6      species: { isLabel: true }
7    }
8  });
9}

The columnConfigs option marks which column should be treated as the label. Everything else becomes part of the feature object.

Map Rows Into Tensors

tf.data.csv does not automatically hand you model-ready tensors for every use case. You usually map each row into an xs tensor and a ys tensor.

javascript
1const tf = require("@tensorflow/tfjs-node");
2
3function buildDataset() {
4  const labelMap = {
5    setosa: 0,
6    versicolor: 1,
7    virginica: 2
8  };
9
10  return tf.data.csv("file://./data/iris.csv", {
11    columnConfigs: {
12      species: { isLabel: true }
13    }
14  }).map(({ xs, ys }) => {
15    const featureValues = Object.values(xs).map(Number);
16    const classIndex = labelMap[ys.species];
17
18    return {
19      xs: tf.tensor1d(featureValues),
20      ys: tf.oneHot(classIndex, 3)
21    };
22  }).batch(16);
23}

This example converts string labels into integer class IDs before one-hot encoding. That conversion step matters because tf.oneHot expects numeric indices.

Define A Model That Matches The CSV

The model input width must match the number of feature columns produced by the dataset mapping step.

javascript
1const tf = require("@tensorflow/tfjs-node");
2
3function buildModel() {
4  const model = tf.sequential();
5
6  model.add(tf.layers.dense({
7    inputShape: [4],
8    units: 16,
9    activation: "relu"
10  }));
11
12  model.add(tf.layers.dense({
13    units: 3,
14    activation: "softmax"
15  }));
16
17  model.compile({
18    optimizer: tf.train.adam(0.01),
19    loss: "categoricalCrossentropy",
20    metrics: ["accuracy"]
21  });
22
23  return model;
24}

If your CSV has six numeric feature columns, inputShape must be [6]. Mismatched shapes are one of the most common reasons training fails.

Train With fitDataset

Once the dataset and model are ready, training is straightforward.

javascript
1async function train() {
2  const dataset = buildDataset();
3  const model = buildModel();
4
5  await model.fitDataset(dataset, {
6    epochs: 20
7  });
8
9  await model.save("file://./model-output");
10}
11
12train().catch(console.error);

fitDataset is a good choice when the source data is already in a tf.data.Dataset pipeline. It avoids manually collecting the whole CSV into a single in-memory tensor.

Add Validation And Repeatability

For real work, it helps to include shuffling and a validation split. With CSV-backed datasets, a common pattern is to shuffle the mapped dataset and create separate training and validation sources.

javascript
const trainingDataset = buildDataset().shuffle(150);

If you need a true validation dataset, you usually prepare separate files or split records before training. TensorFlow.js does not automatically infer a safe validation split from a streamed dataset.

Browser And Node.js Are Different Environments

The same model code can run in the browser, but local CSV loading is different. In a browser application, you usually fetch the CSV over HTTP or let the user choose a file, then parse it before building tensors or a dataset. In Node.js, using tfjs-node with a local file is much simpler for experimentation.

So if the question is specifically about training from a CSV file on disk, Node.js is usually the most direct answer.

Preprocessing Still Matters

Reading from CSV is not the same as having clean training data. Before training, confirm that:

  • numeric columns are really numeric,
  • missing values are handled,
  • label values are consistent,
  • categorical feature columns are encoded properly,
  • feature order is stable.

TensorFlow.js makes ingestion convenient, but it does not protect you from data quality problems.

Common Pitfalls

  • Forgetting to mark the label column with isLabel.
  • Passing string labels directly into tf.oneHot without mapping them to integers first.
  • Using the wrong inputShape for the number of feature columns.
  • Training on unbatched rows, which is slower and harder to tune.
  • Assuming browser code can read local CSV files the same way Node.js can.

Summary

  • Use tf.data.csv to load CSV data into a TensorFlow.js dataset.
  • Map rows into explicit feature tensors and encoded label tensors.
  • Match the model inputShape to the number of feature columns.
  • Train with fitDataset once batching and label conversion are correct.
  • Prefer Node.js for local CSV-file workflows because file access is simpler.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.