-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathTextGeneration.java
More file actions
executable file
·306 lines (274 loc) · 8.67 KB
/
Copy pathTextGeneration.java
File metadata and controls
executable file
·306 lines (274 loc) · 8.67 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
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
package datasets;
import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import autodiff.Graph;
import datastructs.DataSequence;
import datastructs.DataSet;
import datastructs.DataStep;
import util.Util;
import loss.LossSoftmax;
import matrix.Matrix;
import model.LinearUnit;
import model.Model;
import model.Nonlinearity;
public class TextGeneration extends DataSet {
public static int reportSequenceLength = 100;
public static boolean singleWordAutocorrect = false;
public static boolean reportPerplexity = true;
private static Map<String, Integer> charToIndex = new HashMap<>();
private static Map<Integer, String> indexToChar = new HashMap<>();
private static int dimension;
private static double[] vecStartEnd;
private static final int START_END_TOKEN_INDEX = 0;
private static Set<String> words = new HashSet<>();
public static List<String> generateText(Model model, int steps, boolean argmax, double temperature, Random rng) throws Exception {
List<String> lines = new ArrayList<>();
Matrix start = new Matrix(dimension);
start.w[START_END_TOKEN_INDEX] = 1.0;
model.resetState();
Graph g = new Graph(false);
Matrix input = start.clone();
String line = "";
for (int s = 0; s < steps; s++) {
Matrix logprobs = model.forward(input, g);
Matrix probs = LossSoftmax.getSoftmaxProbs(logprobs, temperature);
if (singleWordAutocorrect) {
Matrix possible = Matrix.ones(dimension, 1);
try {
possible = singleWordAutocorrect(line);
}
catch (Exception e) {
//TODO: still may be some lingering bugs, so don't constrain by possible if a problem occurs. Fix later..
}
double tot = 0;
//remove impossible transitions
for (int i = 0; i < probs.w.length; i++) {
probs.w[i] *= possible.w[i];
tot += probs.w[i];
}
//normalize to sum of 1.0 again
for (int i = 0; i < probs.w.length; i++) {
probs.w[i] /= tot;
}
for (int i = 0; i < probs.w.length; i++) {
if (probs.w[i] > 0 && possible.w[i] == 0) {
throw new Exception("Illegal transition");
}
}
}
int indxChosen = -1;
if (argmax) {
double high = Double.NEGATIVE_INFINITY;
for (int i = 0; i < probs.w.length; i++) {
if (probs.w[i] > high) {
high = probs.w[i];
indxChosen = i;
}
}
}
else {
indxChosen = Util.pickIndexFromRandomVector(probs, rng);
}
if (indxChosen == START_END_TOKEN_INDEX) {
lines.add(line);
line = "";
input = start.clone();
g = new Graph(false);
model.resetState();
input = start.clone();
}
else {
String ch = indexToChar.get(indxChosen);
line += ch;
for (int i = 0; i < input.w.length; i++) {
input.w[i] = 0;
}
input.w[indxChosen] = 1.0;
}
}
if (line.equals("") == false) {
lines.add(line);
}
return lines;
}
private static Matrix singleWordAutocorrect(String sequence) throws Exception {
/*
* This restricts the output of the RNN to being composed of words found in the source text.
* It makes no attempts to account for probabilities in any way.
*/
sequence = sequence.replace("\"\n\"", " ");
if (sequence.equals("") || sequence.endsWith(" ")) { //anything is possible after a space
return Matrix.ones(dimension, 1);
}
String[] parts = sequence.split(" ");
String lastPartialWord = parts[parts.length-1].trim();
if (lastPartialWord.equals(" ") || lastPartialWord.contains(" ")) {
throw new Exception("unexpected");
}
List<String> matches = new ArrayList<>();
for (String word : words) {
if (word.startsWith(lastPartialWord)) {
matches.add(word);
}
}
if (matches.size() == 0) {
throw new Exception("unexpected, no matches for '"+lastPartialWord+"'");
}
Matrix result = new Matrix(dimension);
boolean hit = false;
for (String match : matches) {
if (match.length() < lastPartialWord.length()) {
throw new Exception("How is match shorter than partial word?");
}
if (lastPartialWord.equals(match)) {
result.w[charToIndex.get(" ")] = 1.0;
result.w[START_END_TOKEN_INDEX] = 1.0;
continue;
}
String nextChar = match.charAt(lastPartialWord.length()) + "";
result.w[charToIndex.get(nextChar)] = 1.0;
hit = true;
}
if (hit == false) {
result.w[charToIndex.get(" ")] = 1.0;
result.w[START_END_TOKEN_INDEX] = 1.0;
}
return result;
}
public static String sequenceToSentence(DataSequence sequence) {
String result = "\"";
for (int s = 0; s < sequence.steps.size() - 1; s++) {
DataStep step = sequence.steps.get(s);
int index = -1;
for (int i = 0; i < step.targetOutput.w.length; i++) {
if (step.targetOutput.w[i] == 1) {
index = i;
break;
}
}
String ch = indexToChar.get(index);
result += ch;
}
result += "\"\n";
return result;
}
public TextGeneration(String path) throws Exception {
System.out.println("Text generation task");
System.out.println("loading " + path + "...");
File file = new File(path);
List<String> lines = Files.readAllLines(file.toPath(), Charset.defaultCharset());
Set<String> chars = new HashSet<>();
int id = 0;
charToIndex.put("[START/END]", id);
indexToChar.put(id, "[START/END]");
id++;
System.out.println("Characters:");
System.out.print("\t");
for (String line : lines) {
for (int i = 0; i < line.length(); i++) {
String[] parts = line.split(" ");
for (String part : parts) {
words.add(part.trim());
}
String ch = line.charAt(i) + "";
if (chars.contains(ch) == false) {
System.out.print(ch);
chars.add(ch);
charToIndex.put(ch, id);
indexToChar.put(id, ch);
id++;
}
}
}
dimension = chars.size() + 1;
vecStartEnd = new double[dimension];
vecStartEnd[START_END_TOKEN_INDEX] = 1.0;
List<DataSequence> sequences = new ArrayList<>();
int size = 0;
for (String line : lines) {
List<double[]> vecs = new ArrayList<>();
vecs.add(vecStartEnd);
for (int i = 0; i < line.length(); i++) {
String ch = line.charAt(i) + "";
int index = charToIndex.get(ch);
double[] vec = new double[dimension];
vec[index] = 1.0;
vecs.add(vec);
}
vecs.add(vecStartEnd);
DataSequence sequence = new DataSequence();
for (int i = 0; i < vecs.size() - 1; i++) {
sequence.steps.add(new DataStep(vecs.get(i), vecs.get(i+1)));
size++;
}
sequences.add(sequence);
}
System.out.println("Total unique chars = " + chars.size());
System.out.println(size + " steps in training set.");
training = sequences;
lossTraining = new LossSoftmax();
lossReporting = new LossSoftmax();
inputDimension = sequences.get(0).steps.get(0).input.w.length;
int loc = 0;
while (sequences.get(0).steps.get(loc).targetOutput == null) {
loc++;
}
outputDimension = sequences.get(0).steps.get(loc).targetOutput.w.length;
}
@Override
public void DisplayReport(Model model, Random rng) throws Exception {
System.out.println("========================================");
System.out.println("REPORT:");
if (reportPerplexity) {
System.out.println("\ncalculating perplexity over entire data set...");
double perplexity = LossSoftmax.calculateMedianPerplexity(model, training);
System.out.println("\nMedian Perplexity = " + String.format("%.4f", perplexity));
}
double[] temperatures = {1, 0.75, 0.5, 0.25, 0.1};
for (double temperature : temperatures) {
if (TextGeneration.singleWordAutocorrect) {
System.out.println("\nTemperature "+temperature+" prediction (with single word autocorrect):");
}
else {
System.out.println("\nTemperature "+temperature+" prediction:");
}
List<String> guess = TextGeneration.generateText(model, reportSequenceLength, false, temperature, rng);
for (int i = 0; i < guess.size(); i++) {
if (i == guess.size()-1) {
System.out.println("\t\"" + guess.get(i) + "...\"");
}
else {
System.out.println("\t\"" + guess.get(i) + "\"");
}
}
}
if (TextGeneration.singleWordAutocorrect) {
System.out.println("\nArgmax prediction (with single word autocorrect):");
}
else {
System.out.println("\nArgmax prediction:");
}
List<String> guess = TextGeneration.generateText(model, reportSequenceLength, true, 1.0, rng);
for (int i = 0; i < guess.size(); i++) {
if (i == guess.size()-1) {
System.out.println("\t\"" + guess.get(i) + "...\"");
}
else {
System.out.println("\t\"" + guess.get(i) + "\"");
}
}
System.out.println("========================================");
}
@Override
public Nonlinearity getModelOutputUnitToUse() {
return new LinearUnit();
}
}