MCPcopy Create free account
hub / github.com/tensorflow/tfjs-examples / generateData

Function generateData

addition-rnn-webworker/worker.js:112–152  ·  view source on GitHub ↗

* Generate examples. * * Each example consists of a question, e.g., '123+456' and and an * answer, e.g., '579'. * * @param digits Maximum number of digits of each operand of the * @param numExamples Number of examples to generate. * @param invert Whether to invert the strings in the question.

(digits, numExamples, invert)

Source from the content-addressed store, hash-verified

110 * @returns The generated examples.
111 */
112function generateData(digits, numExamples, invert) {
113 const digitArray = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
114 const arraySize = digitArray.length;
115
116 const output = [];
117 const maxLen = digits + 1 + digits;
118
119 const f = () => {
120 let str = '';
121 while (str.length < digits) {
122 const index = Math.floor(Math.random() * arraySize);
123 str += digitArray[index];
124 }
125 return Number.parseInt(str);
126 };
127
128 const seen = new Set();
129 while (output.length < numExamples) {
130 const a = f();
131 const b = f();
132 const sorted = b > a ? [a, b] : [b, a];
133 const key = sorted[0] + '`' + sorted[1];
134 if (seen.has(key)) {
135 continue;
136 }
137 seen.add(key);
138
139 // Pad the data with spaces such that it is always maxLen.
140 const q = `${a}+${b}`;
141 const query = q + ' '.repeat(maxLen - q.length);
142 let ans = (a + b).toString();
143 // Answer can be of maximum size `digits + 1`.
144 ans += ' '.repeat(digits + 1 - ans.length);
145
146 if (invert) {
147 throw new Error('invert is not implemented yet');
148 }
149 output.push([query, ans]);
150 }
151 return output;
152}
153
154function convertDataToTensors(data, charTable, digits) {
155 const maxLen = digits + 1 + digits;

Callers 1

constructorMethod · 0.70

Calls 1

fFunction · 0.70

Tested by

no test coverage detected