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

Function train_model

sentiment/python/imdb.py:95–155  ·  view source on GitHub ↗

Train a model for IMDB sentiment classification. Args: model_type: Type of the model to train, as a `str`. vocabulary_size: Vocabulary size. embedding_size: Embedding dimensions. x_train: An int array of shape `(num_examples, max_len)`: index-encoded sentences. y_train:

(model_type,
                vocabulary_size,
                embedding_size,
                x_train,
                y_train,
                x_test,
                y_test,
                epochs,
                batch_size)

Source from the content-addressed store, hash-verified

93
94
95def train_model(model_type,
96 vocabulary_size,
97 embedding_size,
98 x_train,
99 y_train,
100 x_test,
101 y_test,
102 epochs,
103 batch_size):
104 """Train a model for IMDB sentiment classification.
105
106 Args:
107 model_type: Type of the model to train, as a `str`.
108 vocabulary_size: Vocabulary size.
109 embedding_size: Embedding dimensions.
110 x_train: An int array of shape `(num_examples, max_len)`: index-encoded
111 sentences.
112 y_train: An int array of shape `(num_examples,)`: labels for the sentences.
113 x_test: Same as `x_train`, but for test.
114 y_test: Same as `y_train`, but for test.
115 epochs: Number of epochs to train the model for.
116 batch_size: Batch size to use during trainng.
117
118 Returns:
119 The trained model instance.
120
121 Raises:
122 ValueError: on invalid model type.
123 """
124
125 model = tf.keras.Sequential()
126 model.add(tf.keras.layers.Embedding(vocabulary_size, embedding_size))
127 if model_type == 'bidirectional_lstm':
128 # TODO(cais): Uncomment the following once bug b/74429960 is fixed.
129 # model.add(tf.keras.layers.Embedding(
130 # vocabulary_size, 128, input_length=maxlen))
131 # model.add(tf.keras.layers.Bidirectional(
132 # tf.keras.layers.LSTM(64))
133 # model.add(tf.keras.layers.Dropout(0.5))
134 raise NotImplementedError()
135 elif model_type == 'cnn':
136 model.add(tf.keras.layers.Dropout(0.2))
137 model.add(tf.keras.layers.Conv1D(250,
138 3,
139 padding='valid',
140 activation='relu',
141 strides=1))
142 model.add(tf.keras.layers.GlobalMaxPooling1D())
143 model.add(tf.keras.layers.Dense(250, activation='relu'))
144 elif model_type == 'lstm':
145 model.add(tf.keras.layers.LSTM(128))
146 else:
147 raise ValueError("Invalid model type: '%s'" % model_type)
148 model.add(tf.keras.layers.Dense(1, activation='sigmoid'))
149
150 model.compile('adam', 'binary_crossentropy', metrics=['accuracy'])
151 model.fit(x_train, y_train,
152 batch_size=batch_size,

Callers 1

mainFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected