写一个神经网络分类模型
时间: 2023-05-11 14:05:56 浏览: 56
好的,我可以为您提供一个神经网络分类模型的代码示例:
```python
import tensorflow as tf
# 定义神经网络模型
def neural_network_model(data):
# 定义输入层
input_layer = tf.reshape(data, [-1, input_size])
# 定义第一个隐藏层
hidden_layer_1 = {'weights': tf.Variable(tf.random_normal([input_size, n_nodes_hl1])),
'biases': tf.Variable(tf.random_normal([n_nodes_hl1]))}
layer_1 = tf.add(tf.matmul(input_layer, hidden_layer_1['weights']), hidden_layer_1['biases'])
layer_1 = tf.nn.relu(layer_1)
# 定义第二个隐藏层
hidden_layer_2 = {'weights': tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])),
'biases': tf.Variable(tf.random_normal([n_nodes_hl2]))}
layer_2 = tf.add(tf.matmul(layer_1, hidden_layer_2['weights']), hidden_layer_2['biases'])
layer_2 = tf.nn.relu(layer_2)
# 定义输出层
output_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl2, n_classes])),
'biases': tf.Variable(tf.random_normal([n_classes]))}
output = tf.add(tf.matmul(layer_2, output_layer['weights']), output_layer['biases'])
return output
# 定义训练神经网络的函数
def train_neural_network(x):
prediction = neural_network_model(x)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y))
optimizer = tf.train.AdamOptimizer().minimize(cost)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for epoch in range(n_epochs):
epoch_loss = 0
for _ in range(int(mnist.train.num_examples / batch_size)):
epoch_x, epoch_y = mnist.train.next_batch(batch_size)
_, c = sess.run([optimizer, cost], feed_dict={x: epoch_x, y: epoch_y})
epoch_loss += c
print('Epoch', epoch, 'completed out of', n_epochs, 'loss:', epoch_loss)
correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
print('Accuracy:', accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))
# 定义神经网络的参数
input_size = 784
n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_classes = 10
batch_size = 100
n_epochs = 10
# 加载 MNIST 数据集
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
# 训练神经网络
x = tf.placeholder('float', [None, input_size])
y = tf.placeholder('float')
train_neural_network(x)
```
这是一个使用 TensorFlow 实现的简单的神经网络分类模型,可以用于 MNIST 手写数字识别任务。