写在前面:在阅读动手学深度学习pytorch时,发现里面使用了一个叫做d2lzh_pytorch的包,当时尝试了各种各样的方法总是会出一些问题,现记录我自己的解决方法。
1、先下载d2lzh_pytoch包
传送门:d2lzh_pytorch.zip
我使用的是pycharm,然后我直接把该包拖入到同一个pycharm文件夹下即可成功使用
(ps:我试过在pycharm里面直接下载,但是它只有d2lzh包,而不是d2lzh_pytorch包,而且导入后也会有各种各样的问题。。)
2、下载tqdm
pip install tqdm -i https://pypi.tuna.tsinghua.edu.cn/simple
3、下载torchtext
pip install -i https://pypi.doubanio.com/simple/ torchtext
4、复现ALEXNET
代码如下:
import torch
import time
from torch import nn, optim
import torchvision
import sys
# sys.path.append("..")
import d2lzh_pytorch as d2l
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class AlexNet(nn.Module):
def __init__(self):
super(AlexNet, self).__init__()
self.conv = nn.Sequential(
nn.Conv2d(1, 96, 11, 4),
nn.ReLU(),
nn.MaxPool2d(3, 2),
nn.Conv2d(96, 256, 5, 1, 2),
nn.ReLU(),
nn.MaxPool2d(3, 2),
nn.Conv2d(256, 384, 3, 1, 1),
nn.ReLU(),
nn.Conv2d(384, 384, 3, 1, 1),
nn.ReLU(),
nn.Conv2d(384, 256, 3, 1, 1),
nn.ReLU(),
nn.MaxPool2d(3, 2)
)
self.fc = nn.Sequential(
nn.Linear(256 * 5 * 5, 4096),
nn.ReLU(),
nn.Dropout(0.5),
nn.Linear(4096, 4096),
nn.ReLU(),
nn.Dropout(0.5),
nn.Linear(4096, 10),
)
def forward(self, img):
feature = self.conv(img)
output = self.fc(feature.view(img.shape[0], -1))
return output
net = AlexNet()
# print(net)
def load_data_fashion_mnist(batch_size, resize=None, root='~/Datasets/FashionMNIST'):
trans = []
if resize:
trans.append(torchvision.transforms.Resize(size=resize))
trans.append(torchvision.transforms.ToTensor())
transform = torchvision.transforms.Compose(trans)
mnist_train = torchvision.datasets.FashionMNIST(root=root, train=True, download=True, transform=transform)
mnist_test = torchvision.datasets.FashionMNIST(root=root, train=False, download=True, transform=transform)
train_iter = torch.utils.data.DataLoader(mnist_train, batch_size=batch_size, shuffle=True, num_workers=4)
test_iter = torch.utils.data.DataLoader(mnist_test, batch_size=batch_size, shuffle=False, num_workers=4)
return train_iter, test_iter
batch_size = 128
train_iter, test_iter = load_data_fashion_mnist(batch_size, resize=224)
lr, num_epochs = 0.001, 5
optimizer = torch.optim.Adam(net.parameters(), lr=lr)
d2l.train_ch5(net, train_iter, test_iter, batch_size, optimizer, device, num_epochs)
训练结果如下:
就可以愉快的使用d2lzh_pytorch包,然后继续阅读动手学深度学习啦。