初次在pycharm中安装pytorch踩了不少坑,做一个记录进行总结。
一,安装pycharm的过程就不写了,首先打开官网https://pytorch.org/,根据自己的实际需要选择版本:
其中CUDA版本号查询方法如下:
1.打开NVIDIA控制面板
2.打开系统信息
3.点击组件查看,版本号10.2
4.复制此段代码:
pip install torch===1.6.0 torchvision===0.7.0 -f https://download.pytorch.org/whl/torch_stable.html
在pycharm终端执行该段代码
1.6.0版本又一个多G,慢慢等待
5.下载完毕之后本以为没问题了结果报错:ERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: 'C:\\Users
经关一系列的尝试和baidu,最终找到了一个解决方法,在pip install 后面加上--user,以上安装代码改为
pip install --user torch===1.6.0 torchvision===0.7.0 -f https://download.pytorch.org/whl/torch_stable.html
最后安装成功
6.最后在别人的博客里面找到了一个测试代码:
```
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable
# Training settings
batch_size= 64
# MNIST Dataset
train_dataset= datasets.MNIST(root='./mnist_data/',
train=True,
transform=transforms.ToTensor(),
download=True)
test_dataset= datasets.MNIST(root='./mnist_data/',
train=False,
transform=transforms.ToTensor())
# Data Loader (Input Pipeline)
train_loader= torch.utils.data.DataLoader(dataset=train_dataset,
batch_size=batch_size,
shuffle=True)
test_loader= torch.utils.data.DataLoader(dataset=test_dataset,
batch_size=batch_size,
shuffle=False)
class Net(nn.Module):
def __init__(self):
super(Net,self).__init__()
self.l1= nn.Linear(784,520)
self.l2= nn.Linear(520,320)
self.l3= nn.Linear(320,240)
self.l4= nn.Linear(240,120)
self.l5= nn.Linear(120,10)
def forward(self,x):
# Flatten the data (n, 1, 28, 28) --> (n, 784)
x= x.view(-1,784)
x= F.relu(self.l1(x))
x= F.relu(self.l2(x))
x= F.relu(self.l3(x))
x= F.relu(self.l4(x))
return F.log_softmax(self.l5(x))
#return self.l5(x)
model= Net()
optimizer= optim.SGD(model.parameters(),lr=0.01,momentum=0.5)
def train(epoch):
# 每次输入barch_idx个数据
for batch_idx, (data, target)in enumerate(train_loader):
data, target= Variable(data), Variable(target)
optimizer.zero_grad()
output= model(data)
# loss
loss= F.nll_loss(output, target)
loss.backward()
# update
optimizer.step()
if batch_idx% 100 == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx* len(data),len(train_loader.dataset),
100. * batch_idx/ len(train_loader), loss.item()))
def test():
test_loss= 0
correct= 0
# 测试集
for data, targetin test_loader:
data, target= Variable(data,volatile=True), Variable(target)
output= model(data)
# sum up batch loss
test_loss+= F.nll_loss(output, target).item()
# get the index of the max
#pred = output.data.max(1, keepdim=True)[1]
pred= output.data.max(1)[1]
correct+= pred.eq(target.data.view_as(pred)).cpu().sum()
test_loss/= len(test_loader.dataset)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct,len(test_loader.dataset),
100. * correct/ len(test_loader.dataset)))
for epochin range(1,6):
train(epoch)
test()
```
测试结果: