Skip to main content
 首页 » 编程设计

python之在 TensorflowJS 中构建神经网络

2024年09月07日29lhb25

我用 nodejs 和 TensorflowJS 构建了一个聊天机器人。

我的代码基于 This tutorial

我在“翻译”神经网络构建时遇到了麻烦。

来自:

# Build neural network 
net = tflearn.input_data(shape=[None, len(train_x[0])]) 
net = tflearn.fully_connected(net, 8) 
net = tflearn.fully_connected(net, 8) 
net = tflearn.fully_connected(net, len(train_y[0]), activation='softmax') 
net = tflearn.regression(net) 
 
# Define model and setup tensorboard 
model = tflearn.DNN(net, tensorboard_dir='tflearn_logs') 
# Start training (apply gradient descent algorithm) 
model.fit(train_x, train_y, n_epoch=1000, batch_size=8, show_metric=True) 
model.save('model.tflearn')  

到目前为止我得到了这个:

  // Build neural network: 
  const model = tf.sequential(); 
  model.add(tf.layers.dense({units: training.length, activation: 'relu', inputShape: [train_x[0].length]})); 
  model.add(tf.layers.dense({units: train_y[0].length, activation: 'linear'})); 
  model.compile({optimizer: 'sgd', loss: 'meanSquaredError'}); 

关键是我不能用我的 JS 代码“预测”。

I got this erro

And this is my xs

完整代码 https://github.com/ran-j/ChatBotNodeJS/blob/master/routes/index.js#L184

不同的是Expected dense_Dense1_input to have shape "a" but got array with shape "b" ,因为它是 python 的“翻译”,而不是使用创建神经网络的错误

train_x[0].length = 48 
train_y[0].length = 9 

我在预测模型时出错。

请您参考如下方法:

试试这个:

var model = tf.sequential(); 
model.add(tf.layers.dense({ 
    units: 8, 
    inputShape: [null, train_x[0].length] 
})); 
model.add(tf.layers.dense({ 
    units: 8 
})); 
model.add(tf.layers.dense({ 
    units: train_y[0].length 
    activation: 'softmax' 
})); 
 
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'}); 
 
await model.fit(x_tensor, y_tensor, { 
    epochs: 1000, 
    batchSize: 8 
})