卷积神经网络python代码
时间: 2023-10-13 19:04:53 浏览: 78
卷积神经网络模型Python代码.txt
以下是一个简单的卷积神经网络的Python代码示例:
```python
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
# 定义卷积神经网络模型
model = Sequential([
Conv2D(filters=32, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1)),
MaxPooling2D(pool_size=(2, 2)),
Flatten(),
Dense(units=128, activation='relu'),
Dense(units=10, activation='softmax')
])
# 编译模型
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# 加载数据集
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 数据预处理
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
x_train = x_train / 255.0
x_test = x_test / 255.0
y_train = tf.keras.utils.to_categorical(y_train, 10)
y_test = tf.keras.utils.to_categorical(y_test, 10)
# 训练模型
model.fit(x_train, y_train, epochs=5, validation_data=(x_test, y_test))
# 评估模型
test_loss, test_acc = model.evaluate(x_test, y_test)
print('Test accuracy:', test_acc)
```
此代码中,我们首先定义了一个卷积神经网络模型,该模型使用了一些常见的层,包括卷积层、池化层、Flatten层和全连接层。然后,我们编译模型,指定优化器、损失函数和评估指标。接下来,我们加载MNIST数据集,并对其进行预处理,将像素值标准化并将标签进行one-hot编码。最后,我们使用训练集训练模型,并使用测试集评估模型的准确性。
阅读全文