本文整理汇总了Python中keras.layers.SimpleRNN方法的典型用法代码示例。如果您正苦于以下问题:Python layers.SimpleRNN方法的具体用法?Python layers.SimpleRNN怎么用?Python layers.SimpleRNN使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类keras.layers
的用法示例。
在下文中一共展示了layers.SimpleRNN方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _build_model
# 需要导入模块: from keras import layers [as 别名]
# 或者: from keras.layers import SimpleRNN [as 别名]
def _build_model(self, num_features, num_actions, max_history_len):
"""Build a keras model and return a compiled model.
:param max_history_len: The maximum number of historical turns used to
decide on next action"""
from keras.layers import Activation, Masking, Dense, SimpleRNN
from keras.models import Sequential
n_hidden = 8 # size of hidden layer in RNN
# Build Model
batch_input_shape = (None, max_history_len, num_features)
model = Sequential()
model.add(Masking(-1, batch_input_shape=batch_input_shape))
model.add(SimpleRNN(n_hidden, batch_input_shape=batch_input_shape))
model.add(Dense(input_dim=n_hidden, output_dim=num_actions))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
logger.debug(model.summary())
return model
示例2: test_tiny_sequence_simple_rnn_random
# 需要导入模块: from keras import layers [as 别名]
# 或者: from keras.layers import SimpleRNN [as 别名]
def test_tiny_sequence_simple_rnn_random(self):
np.random.seed(1988)
input_dim = 2
input_length = 4
num_channels = 3
# Define a model
model = Sequential()
model.add(SimpleRNN(num_channels, input_shape=(input_length, input_dim)))
# Set some random weights
model.set_weights(
[np.random.rand(*w.shape) * 0.2 - 0.1 for w in model.get_weights()]
)
# Test the keras model
self._test_model(model)
示例3: test_tiny_seq2seq_rnn_random
# 需要导入模块: from keras import layers [as 别名]
# 或者: from keras.layers import SimpleRNN [as 别名]
def test_tiny_seq2seq_rnn_random(self):
np.random.seed(1988)
input_dim = 2
input_length = 4
num_channels = 3
# Define a model
model = Sequential()
model.add(
SimpleRNN(
num_channels,
input_shape=(input_length, input_dim),
return_sequences=True,
)
)
# Set some random weights
model.set_weights(
[np.random.rand(*w.shape) * 0.2 - 0.1 for w in model.get_weights()]
)
# Test the keras model
self._test_model(model)
示例4: test_rnn_seq
# 需要导入模块: from keras import layers [as 别名]
# 或者: from keras.layers import SimpleRNN [as 别名]
def test_rnn_seq(self):
np.random.seed(1988)
input_dim = 11
input_length = 5
# Define a model
model = Sequential()
model.add(
SimpleRNN(20, input_shape=(input_length, input_dim), return_sequences=False)
)
# Set some random weights
model.set_weights(
[np.random.rand(*w.shape) * 0.2 - 0.1 for w in model.get_weights()]
)
# Test the keras model
self._test_model(model)
示例5: test_medium_no_sequence_simple_rnn_random
# 需要导入模块: from keras import layers [as 别名]
# 或者: from keras.layers import SimpleRNN [as 别名]
def test_medium_no_sequence_simple_rnn_random(self):
np.random.seed(1988)
input_dim = 10
input_length = 1
num_channels = 10
# Define a model
model = Sequential()
model.add(SimpleRNN(num_channels, input_shape=(input_length, input_dim)))
# Set some random weights
model.set_weights(
[np.random.rand(*w.shape) * 0.2 - 0.1 for w in model.get_weights()]
)
# Test the keras model
self._test_model(model)
示例6: test_merge_mask_3d
# 需要导入模块: from keras import layers [as 别名]
# 或者: from keras.layers import SimpleRNN [as 别名]
def test_merge_mask_3d():
rand = lambda *shape: np.asarray(np.random.random(shape) > 0.5, dtype='int32')
# embeddings
input_a = layers.Input(shape=(3,), dtype='int32')
input_b = layers.Input(shape=(3,), dtype='int32')
embedding = layers.Embedding(3, 4, mask_zero=True)
embedding_a = embedding(input_a)
embedding_b = embedding(input_b)
# rnn
rnn = layers.SimpleRNN(3, return_sequences=True)
rnn_a = rnn(embedding_a)
rnn_b = rnn(embedding_b)
# concatenation
merged_concat = legacy_layers.merge([rnn_a, rnn_b], mode='concat', concat_axis=-1)
model = models.Model([input_a, input_b], [merged_concat])
model.compile(loss='mse', optimizer='sgd')
model.fit([rand(2, 3), rand(2, 3)], [rand(2, 3, 6)])
示例7: test_keras_import
# 需要导入模块: from keras import layers [as 别名]
# 或者: from keras.layers import SimpleRNN [as 别名]
def test_keras_import(self):
model = Sequential()
model.add(LSTM(64, return_sequences=True, input_shape=(10, 64)))
model.add(SimpleRNN(32, return_sequences=True))
model.add(GRU(10, kernel_regularizer=regularizers.l2(0.01),
bias_regularizer=regularizers.l2(0.01), recurrent_regularizer=regularizers.l2(0.01),
activity_regularizer=regularizers.l2(0.01), kernel_constraint='max_norm',
bias_constraint='max_norm', recurrent_constraint='max_norm'))
model.build()
json_string = Model.to_json(model)
with open(os.path.join(settings.BASE_DIR, 'media', 'test.json'), 'w') as out:
json.dump(json.loads(json_string), out, indent=4)
sample_file = open(os.path.join(settings.BASE_DIR, 'media', 'test.json'), 'r')
response = self.client.post(reverse('keras-import'), {'file': sample_file})
response = json.loads(response.content)
layerId = sorted(response['net'].keys())
self.assertEqual(response['result'], 'success')
self.assertGreaterEqual(len(response['net'][layerId[1]]['params']), 7)
self.assertGreaterEqual(len(response['net'][layerId[3]]['params']), 7)
self.assertGreaterEqual(len(response['net'][layerId[6]]['params']), 7)
# ********** Embedding Layers **********
示例8: test_simple_rnn
# 需要导入模块: from keras import layers [as 别名]
# 或者: from keras.layers import SimpleRNN [as 别名]
def test_simple_rnn(self):
"""
Test the conversion of a simple RNN layer.
"""
from keras.layers import SimpleRNN
# Create a simple Keras model
model = Sequential()
model.add(SimpleRNN(32, input_dim=32, input_length=10))
input_names = ["input"]
output_names = ["output"]
spec = keras.convert(model, input_names, output_names).get_spec()
self.assertIsNotNone(spec)
# Test the model class
self.assertIsNotNone(spec.description)
self.assertTrue(spec.HasField("neuralNetwork"))
# Test the inputs and outputs
self.assertEquals(len(spec.description.input), len(input_names) + 1)
self.assertEquals(input_names[0], spec.description.input[0].name)
self.assertEquals(32, spec.description.input[1].type.multiArrayType.shape[0])
self.assertEquals(len(spec.description.output), len(output_names) + 1)
self.assertEquals(output_names[0], spec.description.output[0].name)
self.assertEquals(32, spec.description.output[0].type.multiArrayType.shape[0])
self.assertEquals(32, spec.description.output[1].type.multiArrayType.shape[0])
# Test the layer parameters.
layers = spec.neuralNetwork.layers
layer_0 = layers[0]
self.assertIsNotNone(layer_0.simpleRecurrent)
self.assertEquals(len(layer_0.input), 2)
self.assertEquals(len(layer_0.output), 2)
示例9: test_tiny_no_sequence_simple_rnn_random
# 需要导入模块: from keras import layers [as 别名]
# 或者: from keras.layers import SimpleRNN [as 别名]
def test_tiny_no_sequence_simple_rnn_random(self):
np.random.seed(1988)
input_dim = 10
input_length = 1
num_channels = 1
# Define a model
model = Sequential()
model.add(SimpleRNN(num_channels, input_shape=(input_length, input_dim)))
# Set some random weights
model.set_weights([np.random.rand(*w.shape) for w in model.get_weights()])
# Test the keras model
self._test_model(model)
示例10: test_lstm_td
# 需要导入模块: from keras import layers [as 别名]
# 或者: from keras.layers import SimpleRNN [as 别名]
def test_lstm_td(self):
np.random.seed(1988)
input_dim = 2
input_length = 4
num_channels = 3
# Define a model
model = Sequential()
model.add(
SimpleRNN(
num_channels,
return_sequences=True,
input_shape=(input_length, input_dim),
)
)
model.add(TimeDistributed(Dense(5)))
# Set some random weights
model.set_weights(
[np.random.rand(*w.shape) * 0.2 - 0.1 for w in model.get_weights()]
)
# Test the keras model
self._test_model(model)
# Making sure that giant channel sizes get handled correctly
示例11: test_simple_rnn
# 需要导入模块: from keras import layers [as 别名]
# 或者: from keras.layers import SimpleRNN [as 别名]
def test_simple_rnn(self):
"""
Test the conversion of a simple RNN layer.
"""
from keras.layers import SimpleRNN
# Create a simple Keras model
model = Sequential()
model.add(SimpleRNN(32, input_shape=(10, 32)))
input_names = ["input"]
output_names = ["output"]
spec = keras.convert(model, input_names, output_names).get_spec()
self.assertIsNotNone(spec)
# Test the model class
self.assertIsNotNone(spec.description)
self.assertTrue(spec.HasField("neuralNetwork"))
# Test the inputs and outputs
self.assertEquals(len(spec.description.input), len(input_names) + 1)
self.assertEquals(input_names[0], spec.description.input[0].name)
self.assertEquals(32, spec.description.input[1].type.multiArrayType.shape[0])
self.assertEquals(len(spec.description.output), len(output_names) + 1)
self.assertEquals(output_names[0], spec.description.output[0].name)
self.assertEquals(32, spec.description.output[0].type.multiArrayType.shape[0])
self.assertEquals(32, spec.description.output[1].type.multiArrayType.shape[0])
# Test the layer parameters.
layers = spec.neuralNetwork.layers
layer_0 = layers[0]
self.assertIsNotNone(layer_0.simpleRecurrent)
self.assertEquals(len(layer_0.input), 2)
self.assertEquals(len(layer_0.output), 2)
示例12: test_Bidirectional_trainable
# 需要导入模块: from keras import layers [as 别名]
# 或者: from keras.layers import SimpleRNN [as 别名]
def test_Bidirectional_trainable():
# test layers that need learning_phase to be set
x = Input(shape=(3, 2))
layer = wrappers.Bidirectional(layers.SimpleRNN(3))
_ = layer(x)
assert len(layer.trainable_weights) == 6
layer.trainable = False
assert len(layer.trainable_weights) == 0
layer.trainable = True
assert len(layer.trainable_weights) == 6
示例13: test_temporal_classification_functional
# 需要导入模块: from keras import layers [as 别名]
# 或者: from keras.layers import SimpleRNN [as 别名]
def test_temporal_classification_functional():
'''
Classify temporal sequences of float numbers
of length 3 into 2 classes using
single layer of GRU units and softmax applied
to the last activations of the units
'''
np.random.seed(1337)
(x_train, y_train), (x_test, y_test) = get_test_data(num_train=200,
num_test=20,
input_shape=(3, 4),
classification=True,
num_classes=2)
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
inputs = layers.Input(shape=(x_train.shape[1], x_train.shape[2]))
x = layers.SimpleRNN(8)(inputs)
outputs = layers.Dense(y_train.shape[-1], activation='softmax')(x)
model = keras.models.Model(inputs, outputs)
model.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
history = model.fit(x_train, y_train, epochs=4, batch_size=10,
validation_data=(x_test, y_test),
verbose=0)
assert(history.history['acc'][-1] >= 0.8)