卷积神经网络cnn python代码
时间: 2023-05-19 10:07:22 浏览: 131
以下是一个简单的卷积神经网络的 Python 代码示例:
```python
import tensorflow as tf
# 定义卷积神经网络
def cnn_model_fn(features, labels, mode):
# 输入层
input_layer = tf.reshape(features["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 和 池化层 #2
conv2 = tf.layers.conv2d(
inputs=pool1,
filters=64,
kernel_size=[5, 5],
padding="same",
activation=tf.nn.relu)
pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)
# 全连接层
pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])
dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu)
dropout = tf.layers.dropout(
inputs=dense, rate=0.4, training=mode == tf.estimator.ModeKeys.TRAIN)
# 输出层
logits = tf.layers.dense(inputs=dropout, units=10)
predictions = {
# 生成预测结果
"classes": tf.argmax(input=logits, axis=1),
"probabilities": tf.nn.softmax(logits, name="softmax_tensor")
}
if mode == tf.estimator.ModeKeys.PREDICT:
return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)
# 计算损失函数
loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)
# 配置训练操作
if mode == tf.estimator.ModeKeys.TRAIN:
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
train_op = optimizer.minimize(loss=loss, global_step=tf.train.get_global_step())
return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)
# 配置评估操作
eval_metric_ops = {
"accuracy": tf.metrics.accuracy(
labels=labels, predictions=predictions["classes"])}
return tf.estimator.EstimatorSpec(
mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)
```
这是一个用 TensorFlow 实现的简单的卷积神经网络,用于 MNIST 手写数字识别任务。它包括两个卷积层、两个池化层和一个全连接层。
阅读全文