赞
踩
往期精彩内容:
来自专栏:机器学习与深度学习算法推荐
import tensorflow as tf
gpus = tf.config.list_physical_devices("GPU")
if gpus:
gpu0 = gpus[0] #如果有多个GPU,仅使用第0个GPU
tf.config.experimental.set_memory_growth(gpu0, True) #设置GPU显存用量按需使用
tf.config.set_visible_devices([gpu0],"GPU")
import matplotlib.pyplot as plt
import numpy as np
import os
import PIL
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers,models
import pathlib
dataset_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
data_dir = tf.keras.utils.get_file(fname = 'flower_photos', # 下载到本地后的文件名称
origin = dataset_url, # 数据集(Dataset)的URL路径;
untar = True, # 是否解压文件
cache_dir= 'DL-100-days')
data_dir = pathlib.Path(data_dir)
data_dir
PosixPath('/tmp/.keras/datasets/flower_photos')
image_count = len(list(data_dir.glob('*/*.jpg')))
print("图片总数为:",image_count)
roses = list(data_dir.glob('roses/*'))
PIL.Image.open(str(roses[1]))
使用image_dataset_from_directory
方法将磁盘中的数据加载到tf.data.Dataset
中
batch_size = 32
img_height = 180
img_width = 180
train_ds = tf.keras.preprocessing.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset="training",
seed=123,
image_size=(img_height, img_width),
batch_size=batch_size)
Found 3670 files belonging to 5 classes.
Using 2936 files for training.
val_ds = tf.keras.preprocessing.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset="validation",
seed=123,
image_size=(img_height, img_width),
batch_size=batch_size)
Found 3670 files belonging to 5 classes.
Using 734 files for validation.
我们可以通过class_names输出数据集的标签。标签将按字母顺序对应于目录名称。
class_names = train_ds.class_names
print(class_names)
['daisy', 'dandelion', 'roses', 'sunflowers', 'tulips']
plt.figure(figsize=(20, 10))
for images, labels in train_ds.take(1):
for i in range(20):
ax = plt.subplot(5, 10, i + 1)
plt.imshow(images[i].numpy().astype("uint8"))
plt.title(class_names[labels[i]])
plt.axis("off")
for image_batch, labels_batch in train_ds:
print(image_batch.shape)
print(labels_batch.shape)
break
(32, 180, 180, 3)
(32,)
Image_batch
是形状的张量(32,180,180,3)。这是一批形状180x180x3的32张图片(最后一维指的是彩色通道RGB)。Label_batch
是形状(32,)的张量,这些标签对应32张图片prefetch()
功能详细介绍:CPU 正在准备数据时,加速器处于空闲状态。相反,当加速器正在训练模型时,CPU 处于空闲状态。因此,训练所用的时间是 CPU 预处理时间和加速器训练时间的总和。prefetch()
将训练步骤的预处理和模型执行过程重叠到一起。当加速器正在执行第 N 个训练步时,CPU 正在准备第 N+1 步的数据。这样做不仅可以最大限度地缩短训练的单步用时(而不是总用时),而且可以缩短提取和转换数据所需的时间。如果不使用prefetch()
,CPU 和 GPU/TPU 在大部分时间都处于空闲状态:
使用prefetch()
可显著减少空闲时间:
AUTOTUNE = tf.data.AUTOTUNE
train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)
val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)
卷积神经网络(CNN)的输入是张量 (Tensor) 形式的 (image_height, image_width, color_channels)
,包含了图像高度、宽度及颜色信息。不需要输入batch size
。color_channels 为 (R,G,B) 分别对应 RGB 的三个颜色通道(color channel)。在此示例中,我们的 CNN 输入,fashion_mnist 数据集中的图片,形状是 (28, 28, 1)
即灰度图像。我们需要在声明第一层时将形状赋值给参数input_shape
。
num_classes = 5
model = models.Sequential([
layers.experimental.preprocessing.Rescaling(1./255, input_shape=(img_height, img_width, 3)),
layers.Conv2D(16, (3, 3), activation='relu', input_shape=(img_height, img_width, 3)), # 卷积层1,卷积核3*3
layers.MaxPooling2D((2, 2)), # 池化层1,2*2采样
layers.Conv2D(32, (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(128, activation='relu'), # 全连接层,特征进一步提取
layers.Dense(num_classes) # 输出层,输出预期结果
])
model.summary() # 打印网络结构
Model: "sequential_1"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
rescaling_1 (Rescaling) (None, 180, 180, 3) 0
_________________________________________________________________
conv2d_3 (Conv2D) (None, 178, 178, 16) 448
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 89, 89, 16) 0
_________________________________________________________________
conv2d_4 (Conv2D) (None, 87, 87, 32) 4640
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 43, 43, 32) 0
_________________________________________________________________
conv2d_5 (Conv2D) (None, 41, 41, 64) 18496
_________________________________________________________________
flatten_1 (Flatten) (None, 107584) 0
_________________________________________________________________
dense_2 (Dense) (None, 128) 13770880
_________________________________________________________________
dense_3 (Dense) (None, 5) 645
=================================================================
Total params: 13,795,109
Trainable params: 13,795,109
Non-trainable params: 0
_________________________________________________________________
在准备对模型进行训练之前,还需要再对其进行一些设置。以下内容是在模型的编译步骤中添加的:
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
history = model.fit(
train_ds,
validation_data=val_ds,
epochs=10
)
Epoch 1/10
92/92 [==============================] - 9s 29ms/step - loss: 1.7851 - accuracy: 0.3435 - val_loss: 1.0564 - val_accuracy: 0.5640
Epoch 2/10
92/92 [==============================] - 1s 11ms/step - loss: 1.0037 - accuracy: 0.5867 - val_loss: 1.0490 - val_accuracy: 0.5708
Epoch 3/10
92/92 [==============================] - 1s 11ms/step - loss: 0.8206 - accuracy: 0.6746 - val_loss: 0.9763 - val_accuracy: 0.6158
Epoch 4/10
92/92 [==============================] - 1s 12ms/step - loss: 0.6061 - accuracy: 0.7864 - val_loss: 0.9745 - val_accuracy: 0.6158
Epoch 5/10
92/92 [==============================] - 1s 12ms/step - loss: 0.3319 - accuracy: 0.8929 - val_loss: 1.2550 - val_accuracy: 0.6076
Epoch 6/10
92/92 [==============================] - 1s 11ms/step - loss: 0.1607 - accuracy: 0.9473 - val_loss: 1.4897 - val_accuracy: 0.6172
Epoch 7/10
92/92 [==============================] - 1s 11ms/step - loss: 0.0864 - accuracy: 0.9757 - val_loss: 1.5388 - val_accuracy: 0.6226
Epoch 8/10
92/92 [==============================] - 1s 12ms/step - loss: 0.0621 - accuracy: 0.9818 - val_loss: 2.0122 - val_accuracy: 0.6008
Epoch 9/10
92/92 [==============================] - 1s 11ms/step - loss: 0.0390 - accuracy: 0.9893 - val_loss: 1.9353 - val_accuracy: 0.6267
Epoch 10/10
92/92 [==============================] - 1s 11ms/step - loss: 0.0061 - accuracy: 0.9995 - val_loss: 2.1597 - val_accuracy: 0.6335
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(val_ds, verbose=2)
从上面可以看出随着迭代次数的增加,训练准确率与验证准确率之间的差距逐步增加,这是由于过拟合导致.
print("验证准确率为:",test_acc)
验证准确率为: 0.6035422086715698
[0.5, 1])
plt.legend(loc='lower right')
plt.show()
test_loss, test_acc = model.evaluate(val_ds, verbose=2)
[外链图片转存中…(img-fF61lXFP-1700232748127)]
从上面可以看出随着迭代次数的增加,训练准确率与验证准确率之间的差距逐步增加,这是由于过拟合导致.
print("验证准确率为:",test_acc)
验证准确率为: 0.6035422086715698
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。