(
inputVocabSize, outputVocabSize, inputLength, outputLength)
| 66 | * @return {tf.Model} A compiled model instance. |
| 67 | */ |
| 68 | export function createModel( |
| 69 | inputVocabSize, outputVocabSize, inputLength, outputLength) { |
| 70 | const embeddingDims = 64; |
| 71 | const lstmUnits = 64; |
| 72 | |
| 73 | const encoderInput = tf.input({shape: [inputLength]}); |
| 74 | const decoderInput = tf.input({shape: [outputLength]}); |
| 75 | |
| 76 | let encoder = tf.layers.embedding({ |
| 77 | inputDim: inputVocabSize, |
| 78 | outputDim: embeddingDims, |
| 79 | inputLength, |
| 80 | maskZero: true |
| 81 | }).apply(encoderInput); |
| 82 | encoder = tf.layers.lstm({ |
| 83 | units: lstmUnits, |
| 84 | returnSequences: true |
| 85 | }).apply(encoder); |
| 86 | |
| 87 | const encoderLast = new GetLastTimestepLayer({ |
| 88 | name: 'encoderLast' |
| 89 | }).apply(encoder); |
| 90 | |
| 91 | let decoder = tf.layers.embedding({ |
| 92 | inputDim: outputVocabSize, |
| 93 | outputDim: embeddingDims, |
| 94 | inputLength: outputLength, |
| 95 | maskZero: true |
| 96 | }).apply(decoderInput); |
| 97 | decoder = tf.layers.lstm({ |
| 98 | units: lstmUnits, |
| 99 | returnSequences: true |
| 100 | }).apply(decoder, {initialState: [encoderLast, encoderLast]}); |
| 101 | |
| 102 | let attention = tf.layers.dot({axes: [2, 2]}).apply([decoder, encoder]); |
| 103 | attention = tf.layers.activation({ |
| 104 | activation: 'softmax', |
| 105 | name: 'attention' |
| 106 | }).apply(attention); |
| 107 | |
| 108 | const context = tf.layers.dot({ |
| 109 | axes: [2, 1], |
| 110 | name: 'context' |
| 111 | }).apply([attention, encoder]); |
| 112 | const decoderCombinedContext = |
| 113 | tf.layers.concatenate().apply([context, decoder]); |
| 114 | let output = tf.layers.timeDistributed({ |
| 115 | layer: tf.layers.dense({ |
| 116 | units: lstmUnits, |
| 117 | activation: 'tanh' |
| 118 | }) |
| 119 | }).apply(decoderCombinedContext); |
| 120 | output = tf.layers.timeDistributed({ |
| 121 | layer: tf.layers.dense({ |
| 122 | units: outputVocabSize, |
| 123 | activation: 'softmax' |
| 124 | }) |
| 125 | }).apply(output); |
no test coverage detected