Andrew
Andrew

Reputation: 3613

Trying to port a tensorflow python to javascript

I'm trying to port this python code to javascript, I'm getting very different results in my js script so I wanted to make sure that my dense layers are correct:

Python

let trainValues = // data source
let trainLabels = // data source

model = tf.keras.models.Sequential([
  tf.keras.layers.Dense(24, activation=tf.nn.relu),
  tf.keras.layers.Dense(2, activation=tf.nn.softmax)
])

model.compile(optimizer='adam',
  loss='sparse_categorical_crossentropy',
  metrics=['accuracy'])


model.fit(x=trainValues, y=trainLabels, epochs=5)

Node.js

let trainValues = // data source
let trainLabels = // data source

const model = tf.sequential();
model.add(tf.layers.dense({inputShape: [24], units: 24, activation: 'relu'}));
model.add(tf.layers.dense({units: 1, activation: 'softmax'}));
model.compile({
    loss: tf.losses.softmaxCrossEntropy,
    optimizer: tf.train.adam(),
    metrics: ['accuracy']
});

trainValues = tf.tensor2d(trainValues);
trainLabels = tf.tensor1d(trainLabels);

await model.fit(trainValues, trainLabels, {
    epochs: 5
});

Upvotes: 1

Views: 266

Answers (1)

Thomas Dondorf
Thomas Dondorf

Reputation: 25280

Your second dense layers seem to have a different number of units (2 in python, 1 in JavaScript).

In addition, your loss functions are different (sparse_categorical_crossentropy in python, softmaxCrossEntropy in JavaScript). Instead of providing one of the tf.losses.* functions, you can simply pass a string here (as defined here).

To have an identical model in JavaScript the code should look like this:

const model = tf.sequential();
model.add(tf.layers.dense({inputShape: [24], units: 24, activation: 'relu'}));
model.add(tf.layers.dense({units: 2, activation: 'softmax'}));
model.compile({
    loss: 'sparseCategoricalCrossentropy',
    optimizer: tf.train.adam(),
    metrics: ['accuracy']
});

I'm assuming that the number of input units is 24 and that you correctly handled the data.

Upvotes: 1

Related Questions