rnn的一个实例代码
时间: 2024-09-18 20:16:48 浏览: 38
wangluosheji_reachf4v_矢量数据_RNN循环神经网络代码实例_
RNN(循环神经网络)在深度学习中常用于序列数据的建模。以下是一个使用Python和Keras库实现简单LSTM(长短期记忆网络)的例子,它会预测下一个字符在给定文本序列的情况下:
```python
from keras.models import Sequential
from keras.layers import LSTM, Dense
import numpy as np
# 假设我们有训练数据(每个样本是一个单词,编码成整数)
data = "your_text_sequence"
chars = sorted(list(set(data)))
char_to_int = dict((c, i) for i, c in enumerate(chars))
# 将文本转换为数字序列
sequences = list()
for i in range(0, len(data) - maxlen, step):
sequence_in = data[i:i + maxlen]
sequence_out = data[i + maxlen]
sequences.append([char_to_int[char] for char in sequence_in])
# 转换为数组格式并归一化
X, y = np.zeros((len(sequences), maxlen, len(chars)), dtype=np.bool), np.zeros((len(sequences), len(chars)))
for i, seq in enumerate(sequences):
for t, char in enumerate(seq):
X[i, t, char] = 1
y[i, char_to_int[sequence_out]] = 1
# 构建模型
model = Sequential()
model.add(LSTM(128, input_shape=(maxlen, len(chars))))
model.add(Dense(len(chars), activation='softmax'))
# 编译和训练模型
model.compile(loss='categorical_crossentropy', optimizer='adam')
model.fit(X, y, epochs=100, batch_size=64)
阅读全文