写一个图像分类的卷积神经网络代码
时间: 2023-04-01 12:01:39 浏览: 109
以下是一个简单的图像分类的卷积神经网络代码,仅供参考:
```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
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)
# 全连接层
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=.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=.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)
# 加载 MNIST 数据集
mnist = tf.contrib.learn.datasets.load_dataset("mnist")
# 创建 Estimator
mnist_classifier = tf.estimator.Estimator(
model_fn=cnn_model_fn, model_dir="/tmp/mnist_convnet_model")
# 配置训练和评估操作
train_input_fn = tf.estimator.inputs.numpy_input_fn(
x={"x": mnist.train.images},
y=mnist.train.labels.astype(int),
batch_size=100,
num_epochs=None,
shuffle=True)
mnist_classifier.train(
input_fn=train_input_fn,
steps=20000,
hooks=None)
eval_input_fn = tf.estimator.inputs.numpy_input_fn(
x={"x": mnist.test.images},
y=mnist.test.labels.astype(int),
num_epochs=1,
shuffle=False)
eval_results = mnist_classifier.evaluate(input_fn=eval_input_fn)
print(eval_results)
```
这个代码实现了一个简单的卷积神经网络模型,用于对 MNIST 数据集中的手写数字进行分类。具体实现过程可以参考代码中的注释。
阅读全文