-
Notifications
You must be signed in to change notification settings - Fork 0
/
thetraining.html
286 lines (234 loc) · 8.77 KB
/
thetraining.html
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
<html>
<head>
<!-- Load TensorFlow.js -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.12.0"> </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/p5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/addons/p5.dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/addons/p5.sound.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/nicolaspanel/numjs@0.15.1/dist/numjs.min.js"></script>
</head>
<body>
<form>
Texto:<br>
<input type="text" id="texto" name="texto"><br>
<button id="Button" type="button" onclick="pred()">Start</button>
<p id="out"> out here </p>
</form>
Select file to read <input type="file" onchange="loadFile(this)">
<pre id="data"></pre>
</body>
</html>
<script type="text/javascript">
var char_indices;
var indices_char =
{"0": "\n", "1": "", "2": " ", "3": "!", "4": "\U0022", "5": "&", "6": "'", "7": "(",
"8": ")", "9": ",", "10": "-", "11": ".", "12": "0", "13": "1", "14": "2", "15": "3", "16": "4","17":
"5", "18": "6", "19": "7", "20": "8", "21": "9", "22": ":", "23": ";", "24": "?", "25": "[", "26": "]",
"27": "a", "28": "b", "29": "c", "30": "d", "31": "e", "32": "f",
"33": "g", "34": "h", "35": "i", "36": "j", "37": "k", "38": "l", "39": "m", "40": "n", "41": "o",
"42": "p", "43": "q", "44": "r", "45": "s", "46": "t", "47": "u", "48": "v", "49": "w", "50": "x",
"51": "y", "52": "z", "53": "ï", "54": "\u2013", "55": "\u2014", "56": "\u2018"
, "57": "\u2019", "58": "\u201c", "59": "\u201d", "60": "\u2026"};
var txt;
function loadFile(o)
{
var fr = new FileReader();
fr.onload = function(e)
{
showDataFile(e, o);
};
fr.readAsText(o.files[0]);
}
function showDataFile(e, o)
{ txt = e.target.result
devText();
//document.getElementById("data").innerText = e.target.result;
}
var INPUT_LENGTH= 20 ;
var CHARS_TO_GENERATE = 200;
var DIVERSITY = 0.5;
var modelo;
var flag =false;
async function preload(){
}
async function devText(){
var maxlen=20;
var step =3;
var sentences = [];
var next_chars = [];
var chars;
txt = txt.toLowerCase();
var texto = Array.from(txt);
console.log("corpus len "+txt.length);
var inran = txt.length-maxlen;
console.log("txtlen "+txt.length);
console.log("Inran"+inran);
for (let i = 0; i<inran; i+=step) {
let tmp = txt.slice(i, i+maxlen);
let tmp2 = txt[i+maxlen];
sentences.push(tmp);
next_chars.push(tmp2);
//sentences.push(texto[i+maxlen]);
//sentences.push(texto.slice(i,i+maxlen));
//next_chars[i] =next_chars[i] +txt[i+maxlen];
}
console.log('Number of sequences'+sentences.length);
console.log('Sentence 0 '+sentences[0]);
console.log('Next_chars 0 '+next_chars[0]);
chars =texto.filter(onlyUnique);
//chars =sentences.filter(onlyUnique);
chars = chars.sort();
console.log('The chars: '+chars);
char_indices = chars;
var dict = [];
for (let i = 0;i<chars.length;i++) {
dict[i] = chars[i];
}
console.log(dict);
var charlen = chars.length;
//Create the architecture of the model
const themodel = tf.sequential();
themodel.add(tf.layers.lstm({units:12, inputShape: [maxlen, charlen]}));
themodel.add(tf.layers.dense({units: charlen, activation: 'softmax'}));
var optimizer = tf.train.rmsprop (learningRate = 0.01);
themodel.compile({optimizer: optimizer, loss: 'categoricalCrossentropy'});
themodel.summary();
//Vectorization
console.log("Vectorization");
//var x = tf.zeros([sentences.length,maxlen,charlen],'float32');
//var y = tf.zeros([sentences.length,charlen],'float32');
var x = tf.fill([sentences.length,maxlen,charlen],0);
var y = tf.fill([sentences.length,charlen],0);
var buffer = tf.buffer ([sentences.length,maxlen,charlen]);
var buffery = tf.buffer ([sentences.length,charlen]);
console.log("t index is: "+char_indices.indexOf('t'));
/*
for (let i = 0;i<sentences.length;i++) {
let sentence = sentences[i];
for (let t=0;t<sentence.length;t++) {
caracter = sentence[t];
let holder = char_indices.indexOf(caracter);
x[i, t, holder] = 1;
}
y[i, char_indices.indexOf(next_chars[i])] = 1
}
*/
const sequencesBuffer = tf.buffer([sentences.length,maxlen,charlen]);
const labelsBuffer = tf.buffer([sentences.length,charlen]);
for (let i = 0; i < sentences.length; ++i) {
let sentence = sentences[i];
for (let j = 0; j < sentence.length; ++j) {
caracter = sentence[j];
sequencesBuffer.set(1, i, j, char_indices.indexOf(caracter));
}
labelsBuffer.set(1, i, char_indices.indexOf(next_chars[i]));
}
console.log("kaka "+sequencesBuffer.get(0,0,0));
const pop = sequencesBuffer.toTensor();
const lalay = labelsBuffer.toTensor();
console.log("char_indices "+char_indices);
const opts={
epochs: 1,
batchSize: 60
}
console.log("Training model...");
themodel.fit(pop,lalay,opts).then(async results=>{
modelo = themodel;
console.log(results.history.loss);
console.log("Saving model...");
const saveResults = await themodel.save('downloads://trainedInJS');
saveModel();
pred();
});
}
async function saveModel(){
console.log("Completed!");
}
function sample(prediction) {
return tf.tidy(() => {
prediction = prediction.log();
const diversity = tf.scalar(DIVERSITY);
prediction = prediction.div(diversity);
prediction = prediction.exp();
prediction = prediction.div(prediction.sum());
prediction = prediction.mul(tf.randomUniform(prediction.shape));
return prediction.argMax();
});
}
function generateExampleBeginIndices_() {
// Prepare beginning indices of examples.
this.exampleBeginIndices_ = [];
for (let i = 0;i < this.textLen_ - this.sampleLen_ - 1; i += this.sampleStep_) {
this.exampleBeginIndices_.push(i);
}
// Randomly shuffle the beginning indices.
tf.util.shuffle(this.exampleBeginIndices_);
this.examplePosition_ = 0;
}
async function pred(){
//var word = document.getElementById('texto').value;
var word = txt.slice(5,20);
for(var i =0;i<CHARS_TO_GENERATE;i++){
const indexTensor = tf.tidy(() => {
const input = this.convert(word);
const prediction = modelo.predict(input).squeeze();
return sample(prediction);
})
const index = await indexTensor.data();
indexTensor.dispose();
word += indices_char[index];
document.getElementById('texto').innerHTML= word;
console.log(word);
await tf.nextFrame();
}
//modelo.layers[0].getWeights()[1].print();
}
/**
* Converts sentence to Tensor for feeding into model.
*/
function convert(sentence) {
var char_indices2 = {"\n": 0, "": 1, " ": 2, "!": 3, "\U0022": 4, "&": 5, "'": 6, "(": 7, ")": 8, ",": 9,
"-": 10, ".": 11, "0": 12, "1": 13, "2": 14, "3": 15, "4": 16, "5": 17, "6": 18, "7": 19, "8": 20,
"9": 21, ":": 22, ";": 23, "?": 24, "[": 25, "]": 26, "a": 27, "b": 28, "c": 29, "d": 30, "e": 31,
"f": 32, "g": 33, "h": 34, "i": 35, "j": 36, "k": 37, "l": 38, "m": 39, "n": 40, "o": 41, "p": 42,
"q": 43, "r": 44, "s": 45, "t": 46, "u": 47, "v": 48, "w": 49, "x": 50, "y": 51, "z": 52, "ï": 53,
"\u2013": 54, "\u2014": 55, "\u2018": 56,"\u2019": 57,"\u201c": 58,"\u201d": 59,"\u2026": 60}
sentence = sentence.toLowerCase();
sentence = sentence.split('').filter(x => x in char_indices2).join('');
if (sentence.length < INPUT_LENGTH) {
sentence = sentence.padStart(INPUT_LENGTH);
} else if (sentence.length > INPUT_LENGTH) {
sentence = sentence.substring(sentence.length - INPUT_LENGTH);
}
const buffer = tf.buffer([1, INPUT_LENGTH, Object.keys(indices_char).length]);
for (let i = 0; i < INPUT_LENGTH; i++) {
let char = sentence.charAt(i);
buffer.set(1, 0, i, char_indices.indexOf(char));
//buffer.set(1, 0, i, char_indices[char]);
}
const input = buffer.toTensor();
return input;
}
//UTILS
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
function range(start, stop, step) {
if (typeof stop == 'undefined') {
// one param defined
stop = start;
start = 0;
}
if (typeof step == 'undefined') {
step = 1;
}
if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) {
return [];
}
var result = [];
for (var i = start; step > 0 ? i < stop : i > stop; i += step) {
result.push(i);
}
return result;
};
</script>