刚学pytorch为了熟悉这个库写了一个网络出来,但是发现不训练
#下载数据集cifar10
import torchvision
import torchvision.transforms as transforms
batch_size = 1000
transform = transforms.Compose([transforms.ToTensor() , transforms.Normalize((0.5,0.5,0.5) , (0.5,0.5,0.5))])
#下载
transdown = torchvision.datasets.CIFAR10(root="./data" , download=True , train=True , transform = transform)
trainloader = torch.utils.data.DataLoader(transdown , batch_size= batch_size , shuffle = True)
testdown = torchvision.datasets.CIFAR10(root="./data" , download=True , train=False , transform = transform)
testloader = torch.utils.data.DataLoader(testdown , batch_size = batch_size , shuffle = False)
#数据可视化
# import numpy as np
# import matplotlib.pyplot as plt
#
# data = iter(trainloader)
# datas , labels = data.next()
#
# def imshow(datas):
# npdata = datas.numpy()
# plt.imshow(np.transpose(npdata , (1,2,0)))
# plt.show()
#
# datass = datas[0:4,:]
# imshow(torchvision.utils.make_grid(datass))
#
# #看数据是哪个类别
# print([labels[i] for i in range(4)])
import torch.nn as nn
import torch.nn.functional as F
#构建网络
class net(nn.Module):
def __init__(self):
super().__init__()
#两层卷积
self.conv1 = nn.Conv2d(3,6,5)
self.pool1 = nn.MaxPool2d(2,2)
self.conv2 = nn.Conv2d(6,16,5)
self.pool2 = nn.MaxPool2d(2, 2)
#两层线性层
self.liner1 = nn.Linear(16*5*5,120)
self.liner2 = nn.Linear(120,84)
self.liner3 = nn.Linear(84,10)
def forward(self , x):
x = self.pool1(F.sigmoid(self.conv1(x)))
x = self.pool2(F.sigmoid(self.conv2(x)))
x = x.view(-1,self.data(x))
#进入线性层
x = F.sigmoid(self.liner1(x))
x = F.sigmoid(self.liner2(x))
x = self.liner3(x)
return x
def data(self , x):
size = x.size()[1:]
num_faeature = 1
for s in size:
num_faeature *= s
return num_faeature
#
netall = net()
print(netall)
# #训练网络
#
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
netall =netall.to(device)
#定义训练次数
epoch = 2
#定义损失函数
lossfunc = nn.MSELoss()
#定义优化器采用梯度下降优化器
import torch.optim as optims
#定义学习率
lr = 0.1
#定义动量,带动量的随机梯度下降
m = 0.9
opti = optims.SGD(netall.parameters() , lr = lr , momentum=m)
#开始训练
for i in range(epoch):
train_loss = 0.0
num_correct = 0
num_total = 0
for ii , data in enumerate(trainloader, 0):
#把data放入cuda
images ,labels = data
#print(images)
images , labels = images.to(device) , labels.to(device)
#print(labels.size())
#梯度清零
images = images.to(torch.float32)
labels = labels.to(torch.float32)
out = netall(images)
#print(out.size())
out_new = out.transpose(1, 0).contiguous()
loss = lossfunc(out_new , labels)
loss.backward()
opti.step()
#计算损失
train_loss += loss.item()
_, pre = torch.max(out , 1)
num_correct += (pre == labels).sum().item()
num_total += batch_size
#计算正确率
# print(ii)
#print(pre.size())
if (ii+1)%2 == 0:
print("[epoch is %d, the number of images is %d , loss is %f]" % (i , (ii+1) , train_loss/2000))
train_loss = 0.0
print("acc is %d %%" % (100*(num_correct/num_total)))
num_correct =0
num_total = 0
print("finish train")
path = "./model.pth"
torch.save(netall.state_dict() , path)
#预测正确率,首先导入模型
correct = 0
netall.load_state_dict(torch.load(path))
with torch.no_grad():
for data , labels in testloader:
data , labels = data.to(device) , labels.to(device)
output = netall(data)
_, pre = torch.max(output , 1)
print(pre)
print(labels)
correct += (pre == labels).sum().item()
print(correct)
print("acc = %d %%" % (100*(correct/10000)))
然后中间网络的输出out我如果不transpose他说我唯独不对