Published
Edited
Aug 13, 2020
1 fork
11 stars
Insert cell
md`# Learning to predict Iris species using TF.js and Danfo.js


* Code for danfo.js from: https://observablehq.com/@visnup/hello-danfo-js
* Code for TF.js from: https://www.tensorflow.org/js/guide/train_models
`
Insert cell
dfd = require('danfojs@0.0.15/dist/index.min.js').catch(() => window.dfd)
Insert cell
df.loc({columns: ["sepal_width", "sepal_length"]}).head().tensor.toString()
Insert cell
print(df.loc({columns: ["sepal_width", "sepal_length"]}).head())
Insert cell
df.columns.slice(0, -1)
Insert cell
X = df.loc({columns: df.columns.slice(0, -1)}).tensor
Insert cell
df["species"]
Insert cell
encoder = new dfd.LabelEncoder()
Insert cell
y = {
encoder.fit(df["species"].values);
const y = encoder.transform(df["species"].values)
console.log(encoder);
return y.tensor
}
Insert cell
X.shape[1]
Insert cell
training_stats = {
return {
loss: 0,
accuracy: 0
}
}
Insert cell
// Train for 5 epochs with batch size of 32.
model.fit(X, y, {
epochs: 5,
batchSize: 32,
callbacks: {onBatchEnd: (batch, logs) => {
training_stats.accuracy = logs.acc;
training_stats.loss = logs.loss;
console.log('Accuracy', logs.acc);
}}
}).then(info => {
console.log('Final accuracy', info.history.acc);
});
Insert cell
model.predict(tf.randomNormal([3, 4])).toString()
Insert cell
model = {
// Define a model for linear regression.
const model = tf.sequential({
layers: [
tf.layers.dense({inputShape: [X.shape[1]], units: 32, activation: 'relu'}),
tf.layers.dense({units: 3, activation: 'softmax'}),
]
});

// Prepare the model for training: Specify the loss and the optimizer.
model.compile({
optimizer: 'sgd',
loss: 'sparseCategoricalCrossentropy',
metrics: ['accuracy']
});
return model
}
Insert cell
df = dfd.read_csv('https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/639388c2cbc2120a14dcf466e85730eb8be498bb/iris.csv')
Insert cell
print(df.head())
Insert cell
import {print} from "@visnup/hello-danfo-js"
Insert cell
tf = require('@tensorflow/tfjs')
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more