python写卷积神经网络
时间: 2023-10-31 17:57:42 浏览: 116
TensorFlow 中的卷积神经网络用于从频 域 重建磁共振图像 MRI-CNN python
5星 · 资源好评率100%
要使用Python编写卷积神经网络,你可以使用深度学习库例如TensorFlow或PyTorch。下面是一个用TensorFlow编写卷积神经网络的示例代码:
```python
import tensorflow as tf
# 定义卷积神经网络模型
def conv_net(x):
# 输入层
input_layer = tf.reshape(x, [-1, 28, 28, 1]) # 将输入的图像数据reshape为合适的形状
# 卷积层
conv1 = tf.layers.conv2d(inputs=input_layer, filters=32, kernel_size=[5, 5], activation=tf.nn.relu)
# 池化层
pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)
# 卷积层
conv2 = tf.layers.conv2d(inputs=pool1, filters=64, kernel_size=[5, 5], activation=tf.nn.relu)
# 池化层
pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)
# 全连接层
flatten = tf.layers.flatten(pool2) # 将池化层的输出展平为一维向量
dense = tf.layers.dense(inputs=flatten, units=1024, activation=tf.nn.relu)
# 输出层
logits = tf.layers.dense(inputs=dense, units=10)
return logits
# 使用卷积神经网络进行手写数字识别
def handwritten_digit_recognition():
# 加载手写数字数据集
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
# 数据预处理
x_train = x_train / 255.0
x_test = x_test / 255.0
# 定义占位符
x = tf.placeholder(tf.float32, [None, 28, 28])
y = tf.placeholder(tf.int32, [None])
# 构建模型
logits = conv_net(x)
# 定义损失函数
loss_op = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=y))
# 优化器
optimizer = tf.train.AdamOptimizer(learning_rate=0.001)
train_op = optimizer.minimize(loss_op)
# 准确率评估
correct_pred = tf.equal(tf.argmax(logits, 1), tf.cast(y, tf.int64))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# 创建会话并训练模型
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
# 训练参数设置
num_epochs = 10 # 迭代次数
batch_size = 128 # 每批次样本数量
for epoch in range(num_epochs):
num_batches = x_train.shape // batch_size
for batch in range(num_batches):
batch_x = x_train
阅读全文