| 18 | const tf = require('@tensorflow/tfjs'); |
| 19 | |
| 20 | class CharacterTable { |
| 21 | /** |
| 22 | * Constructor of CharacterTable. |
| 23 | * @param chars A string that contains the characters that can appear |
| 24 | * in the input. |
| 25 | */ |
| 26 | constructor(chars) { |
| 27 | this.chars = chars; |
| 28 | this.charIndices = {}; |
| 29 | this.indicesChar = {}; |
| 30 | this.size = this.chars.length; |
| 31 | for (let i = 0; i < this.size; ++i) { |
| 32 | const char = this.chars[i]; |
| 33 | if (this.charIndices[char] != null) { |
| 34 | throw new Error(`Duplicate character '${char}'`); |
| 35 | } |
| 36 | this.charIndices[this.chars[i]] = i; |
| 37 | this.indicesChar[i] = this.chars[i]; |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | /** |
| 42 | * Convert a string into a one-hot encoded tensor. |
| 43 | * |
| 44 | * @param str The input string. |
| 45 | * @param numRows Number of rows of the output tensor. |
| 46 | * @returns The one-hot encoded 2D tensor. |
| 47 | * @throws If `str` contains any characters outside the `CharacterTable`'s |
| 48 | * vocabulary. |
| 49 | */ |
| 50 | encode(str, numRows) { |
| 51 | const buf = tf.buffer([numRows, this.size]); |
| 52 | for (let i = 0; i < str.length; ++i) { |
| 53 | const char = str[i]; |
| 54 | if (this.charIndices[char] == null) { |
| 55 | throw new Error(`Unknown character: '${char}'`); |
| 56 | } |
| 57 | buf.set(1, i, this.charIndices[char]); |
| 58 | } |
| 59 | return buf.toTensor().as2D(numRows, this.size); |
| 60 | } |
| 61 | |
| 62 | encodeBatch(strings, numRows) { |
| 63 | const numExamples = strings.length; |
| 64 | const buf = tf.buffer([numExamples, numRows, this.size]); |
| 65 | for (let n = 0; n < numExamples; ++n) { |
| 66 | const str = strings[n]; |
| 67 | for (let i = 0; i < str.length; ++i) { |
| 68 | const char = str[i]; |
| 69 | if (this.charIndices[char] == null) { |
| 70 | throw new Error(`Unknown character: '${char}'`); |
| 71 | } |
| 72 | buf.set(1, n, i, this.charIndices[char]); |
| 73 | } |
| 74 | } |
| 75 | return buf.toTensor().as3D(numExamples, numRows, this.size); |
| 76 | } |
| 77 |
nothing calls this directly
no outgoing calls
no test coverage detected