| 42 | * - Generating random text using the LSTM model. |
| 43 | */ |
| 44 | export class LSTMTextGenerator { |
| 45 | /** |
| 46 | * Constructor of NeuralNetworkTextGenerator. |
| 47 | * |
| 48 | * @param {TextData} textData An instance of `TextData`. |
| 49 | */ |
| 50 | constructor(textData) { |
| 51 | this.textData_ = textData; |
| 52 | this.charSetSize_ = textData.charSetSize(); |
| 53 | this.sampleLen_ = textData.sampleLen(); |
| 54 | this.textLen_ = textData.textLen(); |
| 55 | } |
| 56 | |
| 57 | /** |
| 58 | * Create LSTM model from scratch. |
| 59 | * |
| 60 | * @param {number | number[]} lstmLayerSizes Sizes of the LSTM layers, as a |
| 61 | * number or an non-empty array of numbers. |
| 62 | */ |
| 63 | createModel(lstmLayerSizes) { |
| 64 | this.model = model.createModel( |
| 65 | this.sampleLen_, this.charSetSize_, lstmLayerSizes); |
| 66 | } |
| 67 | |
| 68 | /** |
| 69 | * Compile model for training. |
| 70 | * |
| 71 | * @param {number} learningRate The learning rate to use during training. |
| 72 | */ |
| 73 | compileModel(learningRate) { |
| 74 | model.compileModel(this.model, learningRate); |
| 75 | } |
| 76 | |
| 77 | /** |
| 78 | * Train the LSTM model. |
| 79 | * |
| 80 | * @param {number} numEpochs Number of epochs to train the model for. |
| 81 | * @param {number} examplesPerEpoch Number of epochs to use in each training |
| 82 | * epochs. |
| 83 | * @param {number} batchSize Batch size to use during training. |
| 84 | * @param {number} validationSplit Validation split to be used during the |
| 85 | * training epochs. |
| 86 | */ |
| 87 | async fitModel(numEpochs, examplesPerEpoch, batchSize, validationSplit) { |
| 88 | let batchCount = 0; |
| 89 | const batchesPerEpoch = examplesPerEpoch / batchSize; |
| 90 | const totalBatches = numEpochs * batchesPerEpoch; |
| 91 | let t = new Date().getTime(); |
| 92 | |
| 93 | onTrainBegin(); |
| 94 | const callbacks = { |
| 95 | onBatchEnd: async (batch, logs) => { |
| 96 | // Calculate the training speed in the current batch, in # of |
| 97 | // examples per second. |
| 98 | const t1 = new Date().getTime(); |
| 99 | const examplesPerSec = batchSize / ((t1 - t) / 1e3); |
| 100 | t = t1; |
| 101 | onTrainBatchEnd(logs, ++batchCount / totalBatches, examplesPerSec); |
nothing calls this directly
no outgoing calls
no test coverage detected