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

Function writeEmbeddingMatrixAndLabels

sentiment/embedding.js:65–118  ·  view source on GitHub ↗
(
    model, prefix, wordIndex, indexFrom)

Source from the content-addressed store, hash-verified

63 * @param {number} indexFrom The basevalue of the integer indices.
64 */
65export async function writeEmbeddingMatrixAndLabels(
66 model, prefix, wordIndex, indexFrom) {
67 tf.util.assert(
68 prefix != null && prefix.length > 0,
69 `Null, undefined or empty path prefix`);
70
71 const embed = extractEmbeddingMatrix(model);
72
73 const numWords = embed.shape[0];
74 const embedDims = embed.shape[1];
75 const embedData = await embed.data();
76
77 // Write the ebmedding matrix to file.
78 let vectorsStr = '';
79 let index = 0;
80 for (let i = 0; i < numWords; ++i) {
81 for (let j = 0; j < embedDims; ++j) {
82 vectorsStr += embedData[index++].toFixed(5);
83 if (j < embedDims - 1) {
84 vectorsStr += '\t';
85 } else {
86 vectorsStr += '\n';
87 }
88 }
89 }
90
91 const vectorsFilePath = `${prefix}_vectors.tsv`;
92 writeFileSync(vectorsFilePath, vectorsStr, {encoding: 'utf-8'});
93 console.log(
94 `Written embedding vectors (${numWords} * ${embedDims}) to: ` +
95 `${vectorsFilePath}`);
96
97 // Collect and write the word labels.
98 const indexToWord = {};
99 for (const word in wordIndex) {
100 indexToWord[wordIndex[word]] = word;
101 }
102
103 let labelsStr = '';
104 for(let i = 0; i < numWords; ++i) {
105 if (i >= indexFrom) {
106 labelsStr += indexToWord[i - indexFrom];
107 } else {
108 labelsStr += 'not-a-word';
109 }
110 labelsStr += '\n';
111 }
112
113 const labelsFilePath = `${prefix}_labels.tsv`;
114 writeFileSync(labelsFilePath, labelsStr, {encoding: 'utf-8'});
115 console.log(
116 `Written embedding labels (${numWords}) to: ` +
117 `${labelsFilePath}`);
118}

Callers 2

embedding_test.jsFile · 0.90
mainFunction · 0.90

Calls 1

extractEmbeddingMatrixFunction · 0.85

Tested by

no test coverage detected