能给我一份可以运行的LSTM神经网络的代码吗
时间: 2024-05-08 09:18:53 浏览: 6
当然可以,以下是一份基于Python和TensorFlow框架的简单LSTM神经网络代码示例:
```python
import tensorflow as tf
# 设置模型参数
n_input = 28
n_steps = 28
n_hidden = 128
n_classes = 10
# 定义输入输出和权重变量
x = tf.placeholder(tf.float32, [None, n_steps, n_input])
y = tf.placeholder(tf.float32, [None, n_classes])
weights = tf.Variable(tf.random_normal([n_hidden, n_classes]))
biases = tf.Variable(tf.random_normal([n_classes]))
# 定义LSTM网络
lstm_cell = tf.contrib.rnn.LSTMCell(n_hidden, forget_bias=1.0)
outputs, state = tf.nn.dynamic_rnn(lstm_cell, x, dtype=tf.float32)
last_output = tf.transpose(outputs, [1, 0, 2])[-1]
pred = tf.matmul(last_output, weights) + biases
# 定义损失函数和优化器
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
optimizer = tf.train.AdamOptimizer().minimize(cost)
# 运行模型
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
# 在训练集上训练模型
for epoch in range(num_epochs):
avg_cost = 0.
total_batch = int(mnist.train.num_examples/batch_size)
for i in range(total_batch):
batch_x, batch_y = mnist.train.next_batch(batch_size)
batch_x = batch_x.reshape((batch_size, n_steps, n_input))
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y})
avg_cost += c / total_batch
print("Epoch:", '%d' % (epoch+1), "cost=", "{:.3f}".format(avg_cost))
print("Optimization Finished!")
# 在测试集上评估模型性能
pred_label = tf.argmax(pred, 1)
true_label = tf.argmax(y, 1)
accuracy = tf.reduce_mean(tf.cast(tf.equal(pred_label, true_label), tf.float32))
print("Test Accuracy:", accuracy.eval({x: mnist.test.images.reshape((-1, n_steps, n_input)), y: mnist.test.labels}))
```
请将以上代码保存为lstm.py,并确保在运行代码前已安装TensorFlow和MNIST数据集。