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

Class CharacterTable

addition-rnn/index.js:28–107  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

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

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected