-
Notifications
You must be signed in to change notification settings - Fork 119
/
tf_model.js
93 lines (81 loc) · 2.54 KB
/
tf_model.js
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/**
* Description.
* Developing model Architecture.
* Compiling and fitting the model with training data.
* Save and Load model.
**/
const tf = require('@tensorflow/tfjs-node');
const config = require('./config');
const configTrain = config.trainConfig;
/**
* create tfjs model architecture.
* @param {tensor} input_ - input tensor.
* @return {tensor} model - Model architecture.
**/
function createModel(input_){
const model = tf.sequential();
model.add(tf.layers.reshape({inputShape:[input_[0].length],
targetShape: [input_[0].length, 1]}));
model.add(tf.layers.lstm({units: 50, returnSequences: true}));
model.add(tf.layers.dropout(0.20));
model.add(tf.layers.lstm({units: 50, returnSequences: true}));
model.add(tf.layers.dropout(0.25));
model.add(tf.layers.lstm({units: 50, returnSequences: true}));
model.add(tf.layers.dropout(0.20));
model.add(tf.layers.lstm({units: 50}));
model.add(tf.layers.dropout(0.25));
model.add(tf.layers.dense({units: 1}));
return model;
}
/**
* compute loss and error at the end of every batch.
* @param {integer} batch - batch number.
* @param {dict} logs - computed loss and error estimated by loss functions.
**/
function onBatchEnd(batch, logs) {
console.log({"loss":logs.loss, "mse": logs.mse, "mae": logs.mae});
}
/**
* Save model weight.
* @param {tensor} model - trained model.
**/
async function saveModel(model){
const savedModel = await model.save('file://'+ configTrain.modelDir);
console.log("Model weights saved.");
}
/**
* train model.
*@param {tensor} model - tfjs model to be trained.
*@param {Array} X - model input.
*@param {Array} y - target to prediction.
**/
async function train(model, X, y){
// prepare the model for training
model.compile({
optimizer: tf.train.adam(),
loss: 'meanSquaredError',
metrics: ['mse','mae'],
});
// train model
await model.fit(
tf.tensor(X),
tf.tensor(y),
{
epochs: configTrain.epoch,
batchSize: configTrain.batchSize,
callbacks: {onBatchEnd}
}
);
// save model
saveModel(model);
}
/**
* Load Model weight and predict output.
* @param {Array} test_data - input data for model to predict.
* @return {Array} - Predicted output.
**/
async function processModel(test_data){
const model = await tf.loadLayersModel('file://'+configTrain.modelDir+'/model.json');
return model.predict(tf.tensor(test_data))
}
module.exports = { createModel, onBatchEnd, train, saveModel, processModel}