Pytorch实战 | P3 天气图片识别(深度学习实践pytorch)

一、我的环境:

● 语言环境:Python3.8
● 编译器:pycharm
● 深度学习环境:Pytorch
● 数据来源:链接: https://pan.baidu.com/s/1SEfd8mvWt7BpzmWOeaIRkQ 提取码: gdie

二、主要代码实现

1、main.py

# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import torch.utils.data
from model import *

from handle import *

# 一、数据处理 headle.py
# 1、加载数据
path = './data/'
headle = Handle(path)
total_data = headle.handle()

# 2、划分数据集
train_size = int(0.8 * len(total_data))  # 80%用来做训练数据
test_size = len(total_data) - train_size  # 20%用来做测试数据

train_dataset, test_dataset = torch.utils.data.random_split(total_data, [train_size, test_size])  # 按比例随机划分数据

batch_size = 32

train_dl = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_dl = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=True)

for X, y in test_dl:
    print("Shape of X [N, C, H, W]: ", X.shape)
    print("Shape of y: ", y.shape, y.dtype)
    break
# 二、网络构建 model().__init__ model.forward()
# 三、模型训练 model.train()
device = "cuda" if torch.cuda.is_available() else "cpu"
print("Using {} device".format(device))
model = Network_bn().to(device)
# 1、设置模型参数
loss_fn = nn.CrossEntropyLoss()  # 损失函数
learn_rate = 1e-4  # 学习率
opt = torch.optim.SGD(model.parameters(), lr=learn_rate)
# 2、训练函数 model.train1()
# 3、测试函数 model.test1()
# 4、模型训练
epochs = 20
train_loss = []
train_acc = []
test_loss = []
test_acc = []

for epoch in range(epochs):
    model.train()
    epoch_train_acc, epoch_train_loss = model.train1(train_dl, model, loss_fn, opt, device)

    model.eval()
    epoch_test_acc, epoch_test_loss = model.test(test_dl, model, loss_fn, device)

    train_loss.append(epoch_train_loss)
    train_
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值