用PyTorch實現多層網路

2021-09-26 03:03:19 字數 4086 閱讀 6318

【task4(2天)】用pytorch實現多層網路

1.引入模組,讀取資料

2.構建計算圖(構建網路模型)

3.損失函式與優化器

4.開始訓練模型

5.對訓練的模型**結果進行評估

參考:import torch

import torchvision

import torchvision.transforms as transforms

import matplotlib.pyplot as plt

import numpy as np

from torch.autograd import variable

import torch.nn as nn

import torch.nn.functional as f

import torch.optim as optim

transform = transforms.compose([transforms.totensor(), transforms.normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

trainset = torchvision.datasets.cifar10(root=』./data』, train=true, download=true, transform=transform)

trainloader = torch.utils.data.dataloader(trainset, batch_size=4, shuffle=true, num_workers=0)

testset = torchvision.datasets.cifar10(root=』./data』, train=false, download=true, transform=transform)

testloader = torch.utils.data.dataloader(testset, batch_size=4, shuffle=false, num_workers=0)

classes = (『plane』, 『car』, 『bird』, 『cat』, 『deer』, 『dog』, 『frog』, 『horse』, 『ship』, 『truck』)

def imshow(img):

img = img/2 +0.5

nping = img.numpy()

plt.imshow(np.transpose(nping, (1, 2, 0)))

plt.show()

dataiter = iter(trainloader)

images, labels = dataiter.next()

imshow(torchvision.utils.make_grid(images))

print(』 『.join(』%5s』 % classes[labels[j]] for j in range(4)))

#自定義網路,繼承torch.nn.module類

class net(nn.module):

definit(self):

super(net, self).init()

self.conv1 = nn.conv2d(3, 6, 5)

self.pool = nn.maxpool2d(2, 2)

self.conv2 = nn.conv2d(6, 16, 5)

self.fc1 = nn.linear(1655, 120)

self.fc2 = nn.linear(120, 84)

self.fc3 = nn.linear(84, 10)

def forward(self, x):

x = self.pool(f.relu(self.conv1(x)))

x = self.pool(f.relu(self.conv2(x)))

x = x.view(-1, 16*5*5)

x = f.relu(self.fc1(x))

x = f.relu(self.fc2(x))

x = self.fc3(x)

return x

net = net()

criterion = nn.crossentropyloss()

optimizer = optim.sgd(net.parameters(), lr=0.001, momentum=0.9)

#開始訓練

for epoch in range(10):

running_loss = 0.0

for i, data in enumerate(trainloader, 0):

inputs, labels = data

inputs, labels = variable(inputs), variable(labels)

optimizer.zero_grad()

outputs = net(inputs)

loss = criterion(outputs, labels)

loss.backward()

optimizer.step()

running_loss += loss.item()

if i % 2000 == 1999:

print('[%d, %5d] loss: %.3f' % (epoch+1, i+1, running_loss/2000))

running_loss = 0.0

print(『finished training』)

dataiter2 = iter(testloader)

images, labels = dataiter2.next()

imshow(torchvision.utils.make_grid(images))

print('groundtruth: 『, 』 『.join(』%5s』 % classes[labels[j]] for j in range(4)))

outputs = net(variable(images))

_, predicted = torch.max(outputs.data, 1)

print('prediced: 『, 』 『.join(』%5s』 % classes[predicted[j]] for j in range(4)))

correct = 0

total = 0

for data in testloader:

images, labels = data

outputs = net(variable(images))

_, predicted = torch.max(outputs.data, 1)

total += labels.size(0)

correct += (predicted == labels).sum()

print(『accuracy of the network on the 10000 test images: %d %%』 % (100*correct/total))

class_correct = list(0. for i in range(10))

class_total = list(0. for i in range(10))

for data in testloader:

images, labels = data

outputs = net(variable(images))

_, predicted = torch.max(outputs.data, 1)

c = (predicted==labels).squeeze().numpy()

for i in range(4):

label = labels[i]

class_correct[label] += c[i]

class_total[label] += 1

for i in range(10):

print(class_total[i], class_correct[i])

print(『accuracy of %5s : %.2f %%』 % (classes[i], 100*class_correct[i]/class_total[i]))

pytorch 實現多層網路

import torch import torch.nn as nn import torch.nn.init as init import torch.nn.functional as f import math 讀取資料集 pima indians diabetes資料集 import pand...

Task4 用PyTorch實現多層網路

1.引入模組,讀取資料 2.構建計算圖 構建網路模型 3.損失函式與優化器 4.開始訓練模型 5.對訓練的模型 結果進行評估 1 import torch.nn.functional as f 2import torch.nn.init as init 3import torch 4from tor...

Pytorch學習筆記 五 多層神經網路

本次設計乙個簡單的三層神經網路模型。上一章學習了乙個線性的分類模型。但如果資料集無法用一條線 乙個面進行分類呢?此時神經網路就有用武之地了。但是本次實驗還是用的上次的資料集,有效果就行 import torch import numpy as np o data 讀取資料 with open dat...