利用python写一段人工神经网络进行图像分类的代码
时间: 2024-01-11 22:04:31 浏览: 73
好的,以下是利用Python编写人工神经网络进行图像分类的代码:
```Python
import numpy as np
import tensorflow as tf
# 导入数据集
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
# 数据预处理
x_train = x_train.reshape(x_train.shape[0], -1) / 255.
x_test = x_test.reshape(x_test.shape[0], -1) / 255.
y_train = tf.keras.utils.to_categorical(y_train, num_classes=10)
y_test = tf.keras.utils.to_categorical(y_test, num_classes=10)
# 定义神经网络模型
model = tf.keras.Sequential([
tf.keras.layers.Dense(128, input_dim=784, activation='relu'),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# 训练模型
model.fit(x_train, y_train, epochs=10, batch_size=32, validation_data=(x_test, y_test))
# 测试模型
loss, acc = model.evaluate(x_test, y_test)
print("准确率:{:5.2f}%,损失值:{}".format(acc*100, loss))
```
希望这个代码可以帮助你。现在请问,你还有什么其它问题吗?
阅读全文