PyTorch基础(part4)
原创
文章标签 pytorch python 人工智能 数据 常用代码 文章分类 PyTorch 人工智能
©著作权归作者所有:来自51CTO博客作者GoatGui的原创作品,请联系作者获取转载授权,否则将追究法律责任
学习笔记,仅供参考,有错必纠
文章目录
PyTorch 基础
MNIST数据识别
常用代码
from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = 'all'
导包
import torchfrom torch import nn,optimimport numpy as npimport matplotlib.pyplot as pltfrom torch.autograd import Variablefrom torchvision import datasets, transformsfrom torch.utils.data import DataLoader
载入数据
train_dataset = datasets.MNIST(root = './data/', train = True, transform = transforms.ToTensor(), download = True) test_dataset = datasets.MNIST(root = './data/', train = False, transform = transforms.ToTensor(), download = True)
Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gzDownloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz to ./data/MNIST\raw\train-images-idx3-ubyte.gz31.0%IOPub message rate exceeded.The notebook server will temporarily stop sending outputto the client in order to avoid crashing it.To change this limit, set the config variable--NotebookApp.iopub_msg_rate_limit
.89.6%IOPub message rate exceeded.The notebook server will temporarily stop sending outputto the client in order to avoid crashing it.To change this limit, set the config variable--NotebookApp.iopub_msg_rate_limit
.100.0%Extracting ./data/MNIST\raw\t10k-images-idx3-ubyte.gz to ./data/MNIST\rawDownloading http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gzDownloading http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz to ./data/MNIST\raw\t10k-labels-idx1-ubyte.gz112.7%Extracting ./data/MNIST\raw\t10k-labels-idx1-ubyte.gz to ./data/MNIST\raw
batch_size = 64train_loader = DataLoader(dataset = train_dataset, batch_size = batch_size, shuffle = True)test_loader = DataLoader(dataset = test_dataset, batch_size = batch_size, shuffle = True)
for i, data in enumerate(train_loader): inputs, labels = data print("批次:", i) print("输入数据的形状:", inputs.shape) print("标签的形状:", labels.shape) break
批次: 0输入数据的形状: torch.Size([64, 1, 28, 28])标签的形状: torch.Size([64])
torch.Size([64, 1, 28, 28]) 中:
- 64代表包含的样本数;
- 1代表通道数,如果图像为黑白图像,那么通道数为1,如果图像为彩色图像,那么通道数为3;
- 最后两个数值28, 28表示图像的尺寸.
len(train_loader)
938
labels
tensor([9, 3, 8, 1, 1, 3, 0, 4, 7, 4, 8, 4, 6, 4, 8, 5, 0, 0, 2, 0, 1, 6, 8, 3, 3, 6, 6, 5, 0, 6, 7, 0, 5, 3, 8, 3, 2, 5, 9, 9, 1, 5, 4, 3, 8, 3, 1, 3, 1, 7, 8, 6, 5, 3, 9, 4, 2, 7, 0, 1, 9, 1, 0, 0])
定义网络结构
class MyNet(nn.Module): def __init__(self): super(MyNet, self).__init__() self.fc1 = nn.Linear(784, 10) self.softmax = nn.Softmax(dim = 1) def forward(self, x): x = x.view(x.size()[0], -1) x = self.fc1(x) out = self.softmax(x) return out
LR = 0.5model = MyNet()mse_loss = nn.MSELoss()optimizer = optim.SGD(model.parameters(), lr = LR)
def train(): for i, data in enumerate(train_loader): inputs, labels = data out = model(inputs) labels = labels.reshape(-1, 1) one_hot = torch.zeros(inputs.shape[0], 10).scatter(1, labels, 1) loss = mse_loss(out, one_hot) optimizer.zero_grad() loss.backward() optimizer.step()
def test(): correct = 0 for i, data in enumerate(test_loader): inputs, labels = data out = model(inputs) _, predicted = torch.max(out, 1) correct += (predicted == labels).sum() print("Test Acc:{0}".format(correct.item()/len(test_dataset)))
for epoch in range(10): print("epoch:", epoch) train() test()
epoch: 0Test Acc:0.8882epoch: 1Test Acc:0.9epoch: 2Test Acc:0.9078epoch: 3Test Acc:0.911epoch: 4Test Acc:0.9145epoch: 5Test Acc:0.9159epoch: 6Test Acc:0.9168epoch: 7Test Acc:0.9179epoch: 8Test Acc:0.9184epoch: 9Test Acc:0.9195
- 赞
- 收藏
- 评论
- *举报
上一篇:PyTorch基础(part3)
Original: https://blog.51cto.com/u_15181342/5354744
Author: GoatGui
Title: PyTorch基础(part4)
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/517636/
转载文章受原作者版权保护。转载请注明原作者出处!