- 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
- 🍖 原作者:K同学啊
目标
- 读取天气图片,按文件夹分类
- 搭建CNN网络,保存网络模型并加载模型
- 使用保存的模型预测真实天气
具体实现
(一)环境
语言环境:Python 3.10
编 译 器: PyCharm
框 架: Pytorch 2.5.1
(二)具体步骤
1. 通用文件Utils.py
import torch
# 第一步:设置GPU
def USE_GPU():
if torch.cuda.is_available():
print('CUDA is available, will use GPU')
device = torch.device("cuda")
else:
print('CUDA is not available. Will use CPU')
device = torch.device("cpu")
return device
2. 模型代码
import os
from torchinfo import summary
from Utils import USE_GPU
import pathlib
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision
from torchvision import datasets
device = USE_GPU()
# 导入数据
data_dir = './data/weather_photos/'
data_dir = pathlib.Path(data_dir)
data_paths = list(data_dir.glob('*'))
# print(data_paths)
classNames = [str(path).split("\\")[2] for path in data_paths]
print(classNames)
# 查看一下图片
image_folder = './data/weather_photos/cloudy'
# 获取image_folder下的所有图片
image_files = [f for f in os.listdir(image_folder) if f.endswith((".jpg", ".png", ".jpeg"))]
#创建matplotlib图像
fig, axes = plt.subplots(3, 8, figsize=(16, 6))
for ax, img_file in zip(axes.flat, image_files):
img_path = os.path.join(image_folder, img_file)
img = Image.open(img_path)
ax.imshow(img)
ax.axis('off')
plt.tight_layout()
plt.title(image_folder, loc='center')
# plt.show()