当前位置:网站首页>pytorch tear CNN
pytorch tear CNN
2022-08-10 22:41:00 【Python ml】
import torch
from torch.utils.data import DataLoader  # We want to load the data sets of
from torchvision import transforms  # The raw data processing
from torchvision import datasets  # pytorchVery thoughtful for us directly the data set
import torch.nn.functional as F  # 激活函数
import torch.optim as optim
import matplotlib.pyplot as plt
batch_size = 64
# We get the picture ispillow,We want to convert him to training model cantensorThat is the format of the tensor
transform = transforms.Compose([transforms.ToTensor()])
# 加载训练集,pytorchVery thoughtful for us directly the data set,注意,Even if you don't have to download the data sets
# 数据下载
train_dataset = datasets.MNIST(root='E:/data/cnn', train=True, download=True, transform=transform)
# 数据打包
train_loader = DataLoader(dataset=train_dataset, shuffle=True, batch_size=batch_size)
# Same way to load the test set
test_dataset = datasets.MNIST(root='E:/data/cnn', train=False, download=True, transform=transform)
test_loader = DataLoader(dataset=test_dataset, shuffle=False, batch_size=batch_size)
# Next we look at the model is how to do
class Net(torch.nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        # Defines our first used convolution layer,Because image input channel for1,第一个参数就是1
        # The output channel for10,kernel_size是卷积核的大小,这里定义的是5x5的
        self.conv1 = torch.nn.Conv2d(1, 10, kernel_size=5)
        # Understand the definition of the above,The following are you sure you can understand
        self.conv2 = torch.nn.Conv2d(10, 20, kernel_size=5)
        # To define a pooling layer
        self.pooling = torch.nn.MaxPool2d(2)
        # Finally we did classification using linear layer
        self.fc = torch.nn.Linear(320, 10)
    # The following is the process of calculation
    def forward(self, x):
        # Flatten data from (n, 1, 28, 28) to (n, 784)
        batch_size = x.size(0)  # 这里面的0是xThe size of the first1个参数,自动获取batch大小
        # 输入x经过一个卷积层,After a pooling layer,最后用relu做激活
        x = F.relu(self.pooling(self.conv1(x)))
        # Go through the above process
        x = F.relu(self.pooling(self.conv2(x)))
        # In order to give us the final linear layer of a fully connected with
        # We are going to take a two-dimensional picture(Actually here is processed)20x4x4Tensor into a d
        x = x.view(batch_size, -1)  # flatten
        # 经过线性层,Sure he is0~9The probability of each number
        x = self.fc(x)
        return x
model = Net()  # 实例化模型
# Moved the computing andGPU
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model.to(device)
# 定义一个损失函数,We model to calculate the output value and standard value of the gap between
criterion = torch.nn.CrossEntropyLoss()
# 定义一个优化器,Training model zha training,就靠这个,He would reverse the changes to the corresponding layer weights
optimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.5)  # lr为学习率
def train(epoch):
    running_loss = 0.0
    for batch_idx, data in enumerate(train_loader, 0):  # 每次取一个样本
        inputs, target = data
        inputs, target = inputs.to(device), target.to(device)
        # 优化器清零
        optimizer.zero_grad()
        # Forward to calculate the
        outputs = model(inputs)
        # 计算损失
        loss = criterion(outputs, target)
        # 反向求梯度
        loss.backward()
        # 更新权重
        optimizer.step()
        # Add up losses
        running_loss += loss.item()
        # 每300Output the data
        if batch_idx % 300 == 299:
            print('[%d, %5d] loss: %.3f' % (epoch + 1, batch_idx + 1, running_loss / 2000))
            running_loss = 0.0
def CNN_test():
    correct = 0
    total = 0
    with torch.no_grad():  # 不用算梯度
        for data in test_loader:
            inputs, target = data
            inputs, target = inputs.to(device), target.to(device)
            outputs = model(inputs)
            # We take the highest probability that count as the output
            _, predicted = torch.max(outputs.data, dim=1)
            total += target.size(0)
            # 计算正确率
            correct += (predicted == target).sum().item()
    print('Accuracy on test set: %d %% [%d/%d]' % (100 * correct / total, correct, total))
    return correct / total
if __name__ == '__main__':
    print("开始训练")
    epoch_list = []
    acc_list = []
    for epoch in range(10):
        print("epoch:%d" % epoch)
        train(epoch)
        acc = CNN_test()
        epoch_list.append(epoch)
        acc_list.append(acc)
    plt.plot(epoch_list, acc_list)
    plt.ylabel('accuracy')
    plt.xlabel('epoch')
    plt.show()
边栏推荐
- IM 即时通讯开发如何设计图片文件的服务端存储架构
- 学会开会|成为有连接感组织的重要技能
- ASCII, Unicode and UTF-8
- RTL8721DM 双频WIFI + 蓝牙5.0 物联网(IoT)应用
- 【开源教程5】疯壳·开源编队无人机-飞控固件烧写
- LeetCode Daily 2 Questions 01: Reverse Strings (both 1200) Method: Double Pointer
- win系统下pytorch深度学习环境安装
- Use Cloudreve to build a private cloud disk
- shell编程之免交互
- “数据引擎”开启前装规模量产新赛道,「智协慧同」崭露头角
猜你喜欢
 - c语言之 练习题1 大贤者福尔:魔法数,神奇的等式 
 - Power system power flow calculation (Newton-Raphson method, Gauss-Seidel method, fast decoupling method) (Matlab code implementation) 
 - Redis Performance Impact - Asynchronous Mechanisms and Response Latency 
 - Use Cloudreve to build a private cloud disk 
 - 威纶通触摸屏如何在报警的同时,显示出异常数据的当前值? 
 - 链表相加(二) 
 - 这款可视化工具神器,更直观易用!太爱了 
 - 2021IDEA创建web工程 
 - shell编程之正则表达式与文本处理器 
 - 2022年8月10日:使用 ASP.NET Core 为初学者构建 Web 应用程序--使用 ASP.NET Core 创建 Web UI(没看懂需要再看一遍) 
随机推荐
- 异常的了解 
- virtual address space 
- Thread State 详解 
- pytorch手撕CNN 
- shell脚本循环语句for、while语句 
- 阿里云新增三大高性能计算解决方案,助力生命科学行业快速发展 
- 使用 Cloudreve 搭建私有云盘 
- Translating scientific and technological papers, how to translate from Russian to Chinese 
- 这款可视化工具神器,更直观易用!太爱了 
- How to secure users in LDAP directory service? 
- 【640. Solving Equations】 
- Addition of linked lists (2) 
- 新一代网络安全防护体系的五个关键特征 
- 过滤器 
- 合并k个已排序的链表 
- geemap的详细安装步骤及环境配置 
- win系统下pytorch深度学习环境安装 
- 美味石井饭菜 
- LeetCode Daily Question (1573. Number of Ways to Split a String) 
- Nodes in the linked list are flipped in groups of k