-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathtrainAI.js
More file actions
51 lines (46 loc) · 1.5 KB
/
trainAI.js
File metadata and controls
51 lines (46 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const Fs = require("fs");
const tf = require("@tensorflow/tfjs-node");
const use = require("@tensorflow-models/universal-sentence-encoder")
const trainAI = async () => {
var data = JSON.parse(Fs.readFileSync("./Convo/Dataset.json"));
var trainingData = [];
for (let [key, value] of Object.entries(data)) {
value.patterns.forEach(msg => {
trainingData.push({ type: key, message: msg })
})
}
var sentenceEncoder = await use.load();
var sentences = trainingData.map(t => t.message.toLowerCase());
var xTrain = await sentenceEncoder.embed(sentences);
var yTrain = tf.tensor2d(
trainingData.map(t => [t.type == "greeting" ? 1 : 0, t.type == "goodbye" ? 1 : 0, t.type == "insult" ? 1 : 0, t.type == "compliment" ? 1 : 0])
)
const model = tf.sequential();
model.add(
tf.layers.dense({
inputShape: [xTrain.shape[1]],
activation: "softmax",
units: 4
})
)
model.compile({
loss: "categoricalCrossentropy",
optimizer: tf.train.adam(0.001),
metrics: ["accuracy"]
});
const onBatchEnd = (batch, logs) => {
console.log('Accuracy', logs.acc);
}
// Train Model
await model.fit(xTrain, yTrain, {
batchSize: 32,
validationSplit: 0.1,
shuffle: true,
epochs: 300,
callbacks: { onBatchEnd }
}).then(info => {
console.log('Final accuracy', info.history.acc);
});
return model;
}
module.exports = trainAI;