T2打卡——彩色图片分类

1.导入数据:

python 复制代码
#设置gpu
import tensorflow as tf
gpus=tf.config.list_physical_devices('GPU')
if gpus:
    #如果有多个gpu仅使用第一个
    gpu0=gpus[0]
    #设置gpu显存用量按需使用
    tf.config.experimental.set_memory_growth(gpu0,True)
    tf.config.set_visible_devices([gpu0],'GPU')
#导入数据
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt

(train_images, train_labels), (test_images, test_labels) =datasets.cifar10.load_data()

2.数据预处理

python 复制代码
#归一化数据
tarin_images,test_images=train_images/155.0,test_images/255.0
train_images.shape,test_images.shape,train_labels.shape,test_labels.shape

3.数据可视化

python 复制代码
class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer','dog', 'frog', 'horse', 'ship', 'truck']
plt.figure(figsize=(20,10))
for i in range(20):
    plt.subplot(5,10,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(train_images[i],cmap=plt.cm.binary)
    plt.xlabel(class_names[train_labels[i][0]])
plt.show

4.建立模型

python 复制代码
model = models.Sequential([
    layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)), #卷积层1,卷积核3*3
    layers.MaxPooling2D((2, 2)),                   #池化层1,2*2采样
    layers.Conv2D(64, (3, 3), activation='relu'),  #卷积层2,卷积核3*3
    layers.MaxPooling2D((2, 2)),                   #池化层2,2*2采样
    layers.Conv2D(64, (3, 3), activation='relu'),  #卷积层3,卷积核3*3
    
    layers.Flatten(),                      #Flatten层,连接卷积层与全连接层
    layers.Dense(64, activation='relu'),   #全连接层,特征进一步提取
    layers.Dense(10)                       #输出层,输出预期结果
])

model.summary()

5.训练模型

python 复制代码
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

history=model.fit(train_images,train_labels,epochs=10,validation_data=(test_images,test_labels))

6.预测数据及模型评估

python 复制代码
import numpy as np
pre=model.predict(test_images)
print(class_names[np.argmax(pre[1])])

import matplotlib.pyplot as plt

plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label = 'val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0.5, 1])
plt.legend(loc='lower right')
plt.show()

test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)

print(test_acc)

知识总结:

池化层对提取到的特征信息进行降维,一方面使特征图变小,简化网络计算复杂度;另一方面进行特征压缩,提取主要特征,增加平移不变性,减少过拟合风险。但其实池化更多程度上是一种计算性能的一个妥协,强硬地压缩特征的同时也损失了一部分信息,所以现在的网络比较少用池化层或者使用优化后的如SoftPool。

池化层包括最大池化层(MaxPooling)和平均池化层(AveragePooling),均值池化对背景保留更好,最大池化对纹理提取更好)。同卷积计算,池化层计算窗口内的平均值或者最大值。

相关推荐
强盛小灵通专卖员6 分钟前
DL00291-联邦学习以去中心化锂离子电池健康预测模型完整实现
人工智能·机器学习·深度强化学习·核心期刊·导师·小论文·大论文
Hello123网站14 分钟前
多墨智能-AI一键生成工作文档/流程图/思维导图
人工智能·流程图·ai工具
有Li1 小时前
CLIK-Diffusion:用于牙齿矫正的临床知识感知扩散模型|文献速递-深度学习人工智能医疗图像
人工智能·深度学习·文献·医学生
大唐荣华1 小时前
视觉语言模型(VLA)分类方法体系
人工智能·分类·机器人·具身智能
即兴小索奇1 小时前
AI应用商业化加速落地 2025智能体爆发与端侧创新成增长引擎
人工智能·搜索引擎·ai·商业·ai商业洞察·即兴小索奇
NeilNiu1 小时前
开源AI工具Midscene.js
javascript·人工智能·开源
nju_spy2 小时前
机器学习 - Kaggle项目实践(4)Toxic Comment Classification Challenge 垃圾评论分类问题
人工智能·深度学习·自然语言处理·tf-idf·南京大学·glove词嵌入·双头gru
计算机sci论文精选2 小时前
CVPR 2025 | 具身智能 | HOLODECK:一句话召唤3D世界,智能体的“元宇宙练功房”来了
人工智能·深度学习·机器学习·计算机视觉·机器人·cvpr·具身智能
ezl1fe2 小时前
RAG 每日一技(十八):手写SQL-RAG太累?LangChain的SQL智能体(Agent)前来救驾!
数据库·人工智能·后端
我星期八休息2 小时前
大模型 + 垂直场景:搜索/推荐/营销/客服领域开发新范式与技术实践
大数据·人工智能·python