卷积神经网络python实现
时间: 2023-05-16 08:06:33 浏览: 157
可以使用Python中的TensorFlow或PyTorch等深度学习框架来实现卷积神经网络。以下是一个简单的Python实现示例:
```
import numpy as np
import tensorflow as tf
# 定义卷积神经网络模型
def conv_net(x, n_classes):
# 输入层
input_layer = tf.reshape(x, [-1, 28, 28, 1])
# 卷积层1
conv1 = tf.layers.conv2d(inputs=input_layer, filters=32, kernel_size=[5, 5], padding="same", activation=tf.nn.relu)
# 池化层1
pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)
# 卷积层2
conv2 = tf.layers.conv2d(inputs=pool1, filters=64, kernel_size=[5, 5], padding="same", activation=tf.nn.relu)
# 池化层2
pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)
# 全连接层
fc1 = tf.layers.dense(inputs=tf.reshape(pool2, [-1, 7 * 7 * 64]), units=1024, activation=tf.nn.relu)
# 输出层
logits = tf.layers.dense(inputs=fc1, units=n_classes)
return logits
# 加载MNIST数据集
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
# 定义输入和输出
x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, 10])
# 定义超参数
learning_rate = 0.001
num_steps = 2000
batch_size = 128
display_step = 100
# 构建模型
logits = conv_net(x, 10)
# 定义损失函数和优化器
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op)
# 定义评估模型的准确率
correct_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# 初始化变量
init = tf.global_variables_initializer()
# 开始训练模型
with tf.Session() as sess:
sess.run(init)
for step in range(1, num_steps+1):
batch_x, batch_y = mnist.train.next_batch(batch_size)
sess.run(train_op, feed_dict={x: batch_x, y: batch_y})
if step % display_step == 0 or step == 1:
loss, acc = sess.run([loss_op, accuracy], feed_dict={x: batch_x, y: batch_y})
print("Step " + str(step) + ", Minibatch Loss= " + "{:.4f}".format(loss) + ", Training Accuracy= " + "{:.3f}".format(acc))
print("Optimization Finished!")
# 评估模型
print("Testing Accuracy:", sess.run(accuracy, feed_dict={x: mnist.test.images[:256], y: mnist.test.labels[:256]}))
```
这个示例实现了一个简单的卷积神经网络来对MNIST手写数字数据集进行分类。
阅读全文