先备案 做网站,关键对话,网页设计大赛策划案,做网站用哪种编程语言CNN#xff08;练习数据集#xff09; 1.导包#xff1a;2.导入数据集#xff1a;3. 使用image_dataset_from_directory()将数据加载tf.data.Dataset中#xff1a;4. 查看数据集中的一部分图像#xff0c;以及它们对应的标签#xff1a;5.迭代数据集 train_ds#xff0… CNN练习数据集 1.导包2.导入数据集3. 使用image_dataset_from_directory()将数据加载tf.data.Dataset中4. 查看数据集中的一部分图像以及它们对应的标签5.迭代数据集 train_ds以便查看第一批图像和标签的形状6.使用TensorFlow的ImageDataGenerator类来创建一个数据增强的对象7.将数据集缓存到内存中加快速度8. 通过卷积层和池化层提取特征再通过全连接层进行分类9.打印网络结构10.设置优化器定义了训练轮次和批量大小11.训练数据集12.画出图像13.评估您的模型在验证数据集的性能14.输出在验证集上的预测结果和真实值的对比15.输出可视化报表 在网上寻找一个新的数据集自己进行训练
1.导包
import pandas as pd
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
from tensorflow.keras.optimizers import Adam
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn.preprocessing import LabelBinarizer
import matplotlib.pyplot as plt
import pickle
import pathlib
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers, models输出结果
2.导入数据集
# 定义超参数
data_dir D:\JUANJI
data_dir pathlib.Path(data_dir)
image_count len(list(data_dir.glob(*/*.jpg)))
print(图片总数为, image_count)
batch_size 30
img_height 180
img_width 180输出结果
3. 使用image_dataset_from_directory()将数据加载tf.data.Dataset中
# 使用image_dataset_from_directory()将数据加载到tf.data.Dataset中
train_ds tf.keras.preprocessing.image_dataset_from_directory(data_dir,validation_split0.2, # 验证集0.2subsettraining,seed123,image_size(img_height, img_width),batch_sizebatch_size)val_ds tf.keras.preprocessing.image_dataset_from_directory(data_dir,validation_split0.2,subsetvalidation,seed123,image_size(img_height, img_width),batch_sizebatch_size)输出结果
4. 查看数据集中的一部分图像以及它们对应的标签
class_names train_ds.class_names
print(class_names)# 可视化
plt.figure(figsize(16, 8))
for images, labels in train_ds.take(1):for i in range(16):ax plt.subplot(4, 4, i 1)# plt.imshow(images[i], cmapplt.cm.binary)plt.imshow(images[i].numpy().astype(uint8))plt.title(class_names[labels[i]])plt.axis(off)
plt.show()输出结果
5.迭代数据集 train_ds以便查看第一批图像和标签的形状
for image_batch, labels_batch in train_ds:print(image_batch.shape)print(labels_batch.shape)break输出结果
6.使用TensorFlow的ImageDataGenerator类来创建一个数据增强的对象
aug ImageDataGenerator(rotation_range30, width_shift_range0.1,height_shift_range0.1, shear_range0.2, zoom_range0.2,horizontal_flipTrue, fill_modenearest)
x aug.flow(image_batch, labels_batch)
AUTOTUNE tf.data.AUTOTUNE输出结果:
7.将数据集缓存到内存中加快速度
train_ds train_ds.cache().shuffle(1000).prefetch(buffer_sizeAUTOTUNE)
val_ds val_ds.cache().prefetch(buffer_sizeAUTOTUNE)输出结果
8. 通过卷积层和池化层提取特征再通过全连接层进行分类
# 为了增加模型的泛化能力增加了Dropout层并将最大池化层更新为平均池化层
num_classes 3
model models.Sequential([layers.experimental.preprocessing.Rescaling(1./255,input_shape(img_height,img_width, 3)),layers.Conv2D(32, (3, 3), activationrelu),layers.MaxPooling2D((2, 2)),layers.Conv2D(64, (3, 3), activationrelu),layers.MaxPooling2D((2, 2)),layers.Conv2D(128, (3, 3), activationrelu),layers.MaxPooling2D((2, 2)),layers.Conv2D(256, (3, 3), activationrelu),layers.MaxPooling2D((2, 2)),layers.Flatten(),layers.Dense(512, activationrelu),layers.Dense(num_classes)
])输出结果
9.打印网络结构
model.summary()输出结果
10.设置优化器定义了训练轮次和批量大小
# 设置优化器
opt tf.keras.optimizers.Adam(learning_rate0.001)model.compile(optimizeropt,losstf.keras.losses.SparseCategoricalCrossentropy(from_logitsTrue),metrics[accuracy])EPOCHS 100
BS 5输出结果
11.训练数据集
# 训练网络
# model.fit 可同时处理训练和即时扩充的增强数据。
# 我们必须将训练数据作为第一个参数传递给生成器。生成器将根据我们先前进行的设置生成批量的增强训练数据。
for images_train, labels_train in train_ds:continue
for images_test, labels_test in val_ds:continue
history model.fit(xaug.flow(images_train,labels_train, batch_sizeBS),validation_data(images_test,labels_test),
steps_per_epoch1,epochsEPOCHS)
输出结果
12.画出图像
# 画出训练精确度和损失图
N np.arange(0, EPOCHS)
plt.style.use(ggplot)
plt.figure()
plt.plot(N, history.history[loss], labeltrain_loss)
plt.plot(N, history.history[val_loss], labelval_loss)
plt.plot(N, history.history[accuracy], labeltrain_acc)
plt.plot(N, history.history[val_accuracy], labelval_acc)
plt.title(Aug Training Loss and Accuracy)
plt.xlabel(Epoch #)
plt.ylabel(Loss/Accuracy)
plt.legend(locupper right) # legend显示位置
plt.show()输出结果
13.评估您的模型在验证数据集的性能
test_loss, test_acc model.evaluate(val_ds, verbose2)
print(test_loss, test_acc)输出结果
14.输出在验证集上的预测结果和真实值的对比
# 优化2 输出在验证集上的预测结果和真实值的对比
pre model.predict(val_ds)
for images, labels in val_ds.take(1):for i in range(4):ax plt.subplot(1, 4, i 1)plt.imshow(images[i].numpy().astype(uint8))plt.title(class_names[labels[i]])plt.xticks([])plt.yticks([])# plt.xlabel(pre: class_names[np.argmax(pre[i])] real: class_names[labels[i]])plt.xlabel(pre: class_names[np.argmax(pre[i])])print(pre: str(class_names[np.argmax(pre[i])]) real: class_names[labels[i]])
plt.show()输出结果
15.输出可视化报表
print(labels_test)
print(labels)
print(pre)
print(class_names)
from sklearn.metrics import classification_report
# 优化1 输出可视化报表
print(classification_report(labels_test,pre.argmax(axis1),
target_namesclass_names))输出结果