用TensorFlow搭建cifar10神经网络
时间: 2023-07-04 21:22:23 浏览: 102
好的,下面是使用TensorFlow搭建cifar10神经网络的步骤:
1. 导入必要的库
```
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
```
2. 加载cifar10数据集
```
(x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()
```
3. 对数据进行预处理
```
x_train = x_train.astype("float32") / 255.0
x_test = x_test.astype("float32") / 255.0
```
4. 定义模型
```
model = keras.Sequential(
[
layers.Conv2D(32, (3, 3), activation="relu", input_shape=(32, 32, 3)),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Conv2D(64, (3, 3), activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Flatten(),
layers.Dense(10),
]
)
```
5. 编译模型
```
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
```
6. 训练模型
```
history = model.fit(x_train, y_train, epochs=10, validation_data=(x_test, y_test))
```
7. 评估模型
```
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print("Test accuracy:", test_acc)
```
以上就是搭建cifar10神经网络的步骤。
阅读全文