python神经网络程序
时间: 2023-10-19 13:23:24 浏览: 43
以下是一个简单的Python神经网络程序,用于分类手写数字图像:
```python
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 加载MNIST数据集
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# 创建神经网络模型
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
# 定义损失函数和优化器
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
# 开始训练模型
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
# 评估模型的准确率
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print("Accuracy:", sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
```
此程序使用TensorFlow库实现一个简单的全连接神经网络,用于分类手写数字图像。MNIST数据集包含60,000个训练图像和10,000个测试图像,每个图像都是28x28像素的灰度图像。程序将每个图像展平为784维向量,然后使用softmax回归模型计算每个数字的概率。通过梯度下降优化器最小化交叉熵损失函数来训练模型。最后,程序使用测试集评估模型的准确性。