Tensorflow入门实战 P03-天气识别

目录

1、完整代码

2、运行结果

2.1 查看20张图片

2.2 程序运行

2.3 运行结果

3、小结

① 代码运行过程中有报错:

② 修改代码如下:

③ 分析原因:


​​​​​本篇文章中,使用的天气数据集,还是之前pytorch里面用的数据集,只是更换了使用的语言为tensorflow。

1、完整代码

import tensorflow as tf
import os,  pathlib
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
from tensorflow import keras
from keras import layers,models

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")

# 导入数据
data_dir = "/Users/MsLiang/Documents/mySelf_project/pythonProject_pytorch/learn_demo/P_model/p03_weather/weather_photos"
data_dir = pathlib.Path(data_dir)
# 查看数据
image_count = len(list(data_dir.glob('*/*.jpg')))
print('图片总数为:', image_count)

roses = list(data_dir.glob('sunrise/*.jpg'))
print(roses[0])
im = Image.open(str(roses[0])).convert('RGB')
# im.show()   # 显示图片


# 数据预处理
# 1、加载数据
batch_size = 32
img_height = 180
img_width = 180
"""
    关于image_dataset_from_directory()的详细介绍可以参考文章:https://mtyjkh.blog.csdn.net/article/details/117018789
"""
# 训练数据
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)

"""
关于image_dataset_from_directory()的详细介绍可以参考文章:https://mtyjkh.blog.csdn.net/article/details/117018789
"""
# 验证数据
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)

# 我们可以通过class_names 输出数据集的标签。标签将按照字母对应于目录名称。
class_names = train_ds.class_names
print('标签名称:', class_names)   # ['cloudy', 'rain', 'shine', 'sunrise']


# 可视化数据
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)   # (32, 180, 180, 3)
    print(labels.shape)  # (32,)
    break

# 配置数据集
AUTOTUNE = tf.data.AUTOTUNE
train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)   # 训练集
val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)  # 验证集


# 构建卷积神经网络
num_classes = 4

"""
关于卷积核的计算不懂的可以参考文章:https://blog.csdn.net/qq_38251616/article/details/114278995

layers.Dropout(0.4) 作用是防止过拟合,提高模型的泛化能力。
在上一篇文章花朵识别中,训练准确率与验证准确率相差巨大就是由于模型过拟合导致的

关于Dropout层的更多介绍可以参考文章:https://mtyjkh.blog.csdn.net/article/details/115826689
"""

model = models.Sequential([
    keras.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.AveragePooling2D((2, 2)),  # 池化层1,2*2采样
    layers.Conv2D(32, (3, 3), activation='relu'),  # 卷积层2,卷积核3*3
    layers.AveragePooling2D((2, 2)),  # 池化层2,2*2采样
    layers.Conv2D(64, (3, 3), activation='relu'),  # 卷积层3,卷积核3*3
    layers.Dropout(0.3),  # 让神经元以一定的概率停止工作,防止过拟合,提高模型的泛化能力。

    layers.Flatten(),  # Flatten层,连接卷积层与全连接层
    layers.Dense(128, activation='relu'),  # 全连接层,特征进一步提取
    layers.Dense(num_classes)  # 输出层,输出预期结果
])

# model.summary()  # 打印网络结构

# 编译
# 设置优化器
opt = tf.keras.optimizers.Adam(learning_rate=0.001)

model.compile(optimizer=opt,
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])


# 训练模型
epochs = 10

history = model.fit(
  train_ds,
  validation_data=val_ds,
  epochs=epochs
)


# 模型评估
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']

loss = history.history['loss']
val_loss = history.history['val_loss']

epochs_range = range(epochs)

plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')

plt.subplot(1, 2, 2)
plt.plot(epochs_range, loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()

2、运行结果

2.1 查看20张图片

2.2 程序运行

2.3 运行结果

3、小结

① 代码运行过程中有报错:

AttributeError: module 'keras.layers' has no attribute 'experimental'

② 修改代码如下:

③ 分析原因:

出现上述问题是因为Keras的版本所导致的

新版本的keras中,keras.layers.experimental 已经被移除了。

方法1:更新keras版本

方法2:

import tensorflow as tf
from tensorflow import keras

# 使用tf.keras替代keras
if hasattr(keras.layers,"experimental"):
    keras.backend.clear_session()
    from tensorflow.keras import layers
else:
    from keras import layers

上述代码会检测你的Keras版本是否含有keras.layers.experimental 模块,如果有则清除当前session,然后导入tensorflow.keras.layers 模块。如果没有,则导入keras.layers 模块。通过这样的方式,就可以避免使用keras.layers.experimental 模块而引发的错误。

相关推荐

  1. 洛谷入门——P1567 统计天数

    2024-06-09 20:00:03       21 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-09 20:00:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-09 20:00:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-09 20:00:03       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-09 20:00:03       20 阅读

热门阅读

  1. 在 Linux 使用 cron 定时执行任务的注意事项

    2024-06-09 20:00:03       9 阅读
  2. Linux_第五章_实验案例:用户和文件权限管理

    2024-06-09 20:00:03       14 阅读
  3. Linux fallocate工具用于预分配或释放文件空间的块

    2024-06-09 20:00:03       12 阅读
  4. 新增菜品——后端SpringBoot

    2024-06-09 20:00:03       10 阅读
  5. python手动搭建transformer,并实现自回归推理

    2024-06-09 20:00:03       12 阅读
  6. 如何实现观察者模式和发布-订阅模式?

    2024-06-09 20:00:03       11 阅读
  7. 关于 Git 的几个使用技巧

    2024-06-09 20:00:03       8 阅读
  8. 速盾:网站重生之我开了高防cdn

    2024-06-09 20:00:03       12 阅读
  9. 贪心算法 之 股票 跳跃游戏1and2

    2024-06-09 20:00:03       9 阅读
  10. flink学习-处理函数

    2024-06-09 20:00:03       12 阅读
  11. k8s面试题大全,保姆级的攻略哦(二)

    2024-06-09 20:00:03       10 阅读