-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathtrain.ts
94 lines (76 loc) · 1.88 KB
/
train.ts
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
94
import * as tf from '@tensorflow/tfjs';
import {
IParams,
IImageData,
IArgs,
} from './types';
const defaultLayers = ({ classes }: { classes: number }) => {
return [
tf.layers.flatten({inputShape: [7, 7, 256]}),
tf.layers.dense({
units: 100,
activation: 'relu',
kernelInitializer: 'varianceScaling',
useBias: true
}),
tf.layers.dense({
units: classes,
kernelInitializer: 'varianceScaling',
useBias: false,
activation: 'softmax'
})
];
};
const getBatchSize = (batchSize?: number, xs?: tf.Tensor) => {
if (batchSize) {
return batchSize;
}
if (xs !== undefined) {
return Math.floor(xs.shape[0] * 0.4) || 1;
}
return undefined;
};
const getModel = (pretrainedModel: tf.Model, data: IImageData, classes: number, params: IParams, args: IArgs) => {
if (args.trainingModel) {
if (typeof args.trainingModel === 'function') {
return args.trainingModel(data, classes, params);
}
return args.trainingModel;
}
const model = tf.sequential({
layers: defaultLayers({ classes }),
});
const optimizer = tf.train.adam(0.0001);
model.compile({
optimizer,
loss: 'categoricalCrossentropy',
metrics: ['accuracy'],
});
return model;
};
const train = async (pretrainedModel: tf.Model, data: IImageData, classes: number, params: IParams, args: IArgs) => {
const {
xs,
ys,
} = data;
if (xs === undefined || ys === undefined) {
throw new Error('Add some examples before training!');
}
// const batch = data.nextTrainBatch(BATCH_SIZE);
const model = getModel(pretrainedModel, data, classes, params, args);
const batchSize = getBatchSize(params.batchSize, xs);
const history = await model.fit(
xs,
ys,
{
...params,
batchSize,
epochs: params.epochs || 20,
},
);
return {
model,
history,
};
};
export default train;