您的位置:首页 > 文旅 > 旅游 > 张家口网站建设价格_建设网站需要注意什么_怎么做网络推广优化_关键词排名优化公司哪家好

张家口网站建设价格_建设网站需要注意什么_怎么做网络推广优化_关键词排名优化公司哪家好

2025/5/18 3:16:05 来源:https://blog.csdn.net/roc_ever/article/details/147545317  浏览:    关键词:张家口网站建设价格_建设网站需要注意什么_怎么做网络推广优化_关键词排名优化公司哪家好
张家口网站建设价格_建设网站需要注意什么_怎么做网络推广优化_关键词排名优化公司哪家好

项目目标

通过构建卷积神经网络(CNN),让模型学会识别图片中是什么物体。我们将使用 CIFAR-10 数据集,它包含 10 类:飞机、汽车、鸟、猫、鹿、狗、青蛙、马、船和卡车。

🛠️ 开发环境与依赖
安装依赖(用命令行运行):

pip install tensorflow matplotlib numpy

推荐使用 Jupyter Notebook,方便边学边运行,也可以用 VS Code、PyCharm 等编辑器。

第一步:导入库

#python
import tensorflow as tf
from tensorflow.keras import layers, models
import matplotlib.pyplot as plt
import numpy as np

这些库的作用:
tensorflow:用于构建和训练神经网络。
matplotlib:用于可视化图片和训练过程。
numpy:用于处理数组和数据操作。

第二步:加载和预处理数据

#python
#加载 CIFAR-10 数据集
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()#归一化处理:将像素值从 0~255 映射到 0~1,提高模型训练效果
x_train = x_train / 255.0
x_test = x_test / 255.0# CIFAR-10 类别名
class_names = ['飞机', '汽车', '鸟', '猫', '鹿', '狗', '青蛙', '马', '船', '卡车']

第三步:查看数据

#pythonplt.figure(figsize=(10, 2))
for i in range(10):plt.subplot(1, 10, i + 1)plt.xticks([]); plt.yticks([])plt.imshow(x_train[i])plt.xlabel(class_names[y_train[i][0]])
plt.show()

这一部分可以帮你初步理解数据的样子和类别。

第四步:构建 CNN 模型

#pythonmodel = models.Sequential([layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),layers.MaxPooling2D((2, 2)),layers.Conv2D(64, (3, 3), activation='relu'),layers.MaxPooling2D((2, 2)),layers.Conv2D(64, (3, 3), activation='relu'),layers.Flatten(),layers.Dense(64, activation='relu'),layers.Dense(10)  # 输出层:10个类
])model.summary()  # 查看模型结构

📌 注解:

Conv2D 是卷积层,能提取图像的边缘、角点等特征。

MaxPooling2D 是池化层,用于降维。

Flatten 把多维数据展平成一维。

Dense 是全连接层,用于分类决策。

第五步:编译和训练模型

#pythonmodel.compile(optimizer='adam',loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),metrics=['accuracy'])history = model.fit(x_train, y_train, epochs=10, validation_data=(x_test, y_test))

💡 小贴士:

adam 是一种优化器,适合初学者使用。

SparseCategoricalCrossentropy 适合标签是整数而不是 one-hot 的分类任务。

第六步:训练过程可视化

#pythonplt.plot(history.history['accuracy'], label='训练准确率')
plt.plot(history.history['val_accuracy'], label='验证准确率')
plt.xlabel('Epoch'); plt.ylabel('Accuracy')
plt.legend(); plt.grid()
plt.show()

这个图能直观看到模型是否在过拟合或欠拟合。

第七步:评估模型

#python
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print(f'测试准确率:{test_acc:.2f}')

第八步:预测和展示结果

#pythonprobability_model = models.Sequential([model, layers.Softmax()])
predictions = probability_model.predict(x_test)#展示前5张图片及其预测结果
for i in range(5):plt.imshow(x_test[i])plt.title(f"预测:{class_names[np.argmax(predictions[i])]} / 实际:{class_names[y_test[i][0]]}")plt.axis('off')plt.show()

第九步:保存与加载模型

#python
#保存模型
model.save('cifar10_cnn_model.h5')#加载模型
new_model = tf.keras.models.load_model('cifar10_cnn_model.h5')

🔄 扩展建议

训练猫狗二分类模型(用 Kaggle 的数据集)。
加 BatchNormalization、Dropout 提升泛化能力。
使用更强的预训练模型如 MobileNet、ResNet。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com