-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmin-word-lstm.js
270 lines (208 loc) · 6.67 KB
/
min-word-lstm.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
const tf = require('@tensorflow/tfjs-node');
const _ = require('lodash');
function readData() {
const fs = require('fs');
const filename = process.argv[2];
const dataRaw = fs.readFileSync(filename, 'utf8');
let head = dataRaw.indexOf('***')
head = dataRaw.indexOf('***', head + 3) + 3;
let tail = dataRaw.indexOf('***', head);
const data = dataRaw.substring(head, tail).trim();
console.log(data.substr(0, 30));
console.log('***');
console.log(data.substr(-30));
const characters = data.split('');
let currenWord = null;
const words = [];
for (let ch of characters) {
if (isLetter(ch)) {
if (!currenWord) {
currenWord = [];
}
currenWord.push(ch.toLowerCase());
} else if (isSpace(ch)) {
if (currenWord) {
words.push(currenWord.join(''));
currenWord = null;
}
} else { //isSimbol
if (currenWord) {
words.push(currenWord.join(''));
currenWord = null;
}
if (!isNumber(ch)) {
words.push(ch);
}
}
}
return words;
}
function isLetter(ch) {
return ch.toLowerCase() != ch.toUpperCase();
}
function isSpace(ch) {
return /\s/.test(ch);
}
function isNumber(ch) {
return /\d/.test(ch);
}
function createWordMap(wordArray){
const countedWordObject = wordArray.reduce((acc, cur, i) => {
if (acc[cur] === undefined) {
acc[cur] = 1
} else {
acc[cur] += 1
}
return acc
}, {})
const arraOfshit = []
for (let key in countedWordObject) {
arraOfshit.push({ word: key, occurence: countedWordObject[key] })
}
const wordMap = _.sortBy(arraOfshit, 'occurence').reverse().map((e, i) => {
e['code'] = i
return e
})
return wordMap
}
// return a word
function fromSymbol(wordMap, symbol){
const object = wordMap.filter(e => e.code === symbol)[0]
return object.word
}
// return a symbol
function toSymbol(wordMap, word){
const object = wordMap.filter(e => e.word === word)[0]
return object.code
}
// return onehot vector, for compare with probability distribution vector
function encode(symbol){
// console.log(symbol)
return tf.tidy(() => {
const symbolTensor1d = tf.tensor1d(symbol, 'int32')
return tf.oneHot(symbolTensor1d, wordMapLength)
})
}
// return a symbol
function decode(probDistVector){
// It could be swithced to tf.argMax(), but I experiment with values below treshold.
const probs = probDistVector.softmax().dataSync()
const maxOfProbs = _.max(probs)
const probIndexes = []
for (let prob of probs) {
if (prob > (maxOfProbs - 0.3)) {
probIndexes.push(probs.indexOf(prob))
}
}
return probIndexes[_.random(0, probIndexes.length - 1)]
}
// sample shape: [batch, sequence, feature], here is [1, number of words, 1]
function predict(model, samples){
return model.predict(samples)
}
function loss(labels, predictions){
return tf.losses.softmaxCrossEntropy(labels, predictions).mean();
}
const inputText = readData();
const preparedDataforTestSet = inputText;
// preparing data
const wordMap = createWordMap(inputText)
const wordMapLength = Object.keys(wordMap).length
console.log(`
Number of unique words: ${wordMapLength}
Length of examined text: ${preparedDataforTestSet.length}
`)
const numIterations = 2000//0;
const learning_rate = 0.001;
const rnn_hidden = 64;
const examinedNumberOfWord = 6;
const endOfSeq = preparedDataforTestSet.length - (examinedNumberOfWord + 1);
const optimizer = tf.train.rmsprop(learning_rate);
let stop_training = false
// building the model
const wordVector = tf.input({ shape: [examinedNumberOfWord, 1] });
const cells = [
tf.layers.lstmCell({ units: rnn_hidden }),
tf.layers.lstmCell({ units: rnn_hidden }),
];
const rnn = tf.layers.rnn({ cell: cells, returnSequences: false });
const rnn_out = rnn.apply(wordVector);
const output = tf.layers.dense({ units: wordMapLength, useBias: true }).apply(rnn_out)
const model = tf.model({ inputs: wordVector, outputs: output });
// performance could be improved if toSymbol the whole set
// then random select from encodings not from array of string
const getSamples = () => {
const startOfSeq = _.random(0, endOfSeq, false)
const retVal = preparedDataforTestSet.slice(startOfSeq, startOfSeq + (examinedNumberOfWord + 1))
return retVal
}
const train = async (numIterations) => {
let lossCounter = null
for (let iter = 0; iter < numIterations; iter++) {
let labelProbVector
let lossValue
let pred
let losse
let samplesTensor
const samples = getSamples().map(s => {
return toSymbol(wordMap, s)
})
labelProbVector = encode(samples.splice(-1))
if (stop_training) {
stop_training = false
break
}
// optimizer.minimize is where the training happens.
// The function it takes must return a numerical estimate (i.e. loss)
// of how well we are doing using the current state of
// the variables we created at the start.
// This optimizer does the 'backward' step of our training process
// updating variables defined previously in order to minimize the
// loss.
lossValue = optimizer.minimize(() => {
// Feed the examples into the model
samplesTensor = tf.tensor(samples, [1, examinedNumberOfWord, 1])
pred = predict(model, samplesTensor);
losse = loss(labelProbVector, pred);
return losse
}, true);
if (lossCounter === null) {
lossCounter = lossValue.dataSync()[0]
}
lossCounter += lossValue.dataSync()[0]
if (iter % 100 === 0 && iter > 50) {
const lvdsy = lossCounter / 100
lossCounter = 0
console.log(`
--------
Step number: ${iter}
The average loss is (last 100 steps): ${lvdsy}
Number of tensors in memory: ${tf.memory().numTensors}
--------`)
}
// Use tf.nextFrame to not block the browser.
//await tf.nextFrame();
pred.dispose()
labelProbVector.dispose()
lossValue.dispose()
losse.dispose()
samplesTensor.dispose()
}
}
const learnToGuessWord = async () => {
console.log('TRAINING START')
await train(numIterations);
console.log('TRAINING IS OVER')
const symbolCollector = _.shuffle(getSamples()).map(s => {
return toSymbol(wordMap, s)
})
for (let i = 0; i < 30; i++) {
const predProbVector = predict(model, tf.tensor(symbolCollector.slice(-examinedNumberOfWord), [1, examinedNumberOfWord, 1]))
symbolCollector.push(decode(predProbVector));
}
const generatedText = symbolCollector.map(s => {
return fromSymbol(wordMap, s)
}).join(' ')
console.log(generatedText)
}
learnToGuessWord();