1

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
});

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.