Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
chenyuntc committed Sep 1, 2018
1 parent 6d265f0 commit c8aa4bb
Show file tree
Hide file tree
Showing 13 changed files with 41 additions and 33 deletions.
19 changes: 13 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
这是书籍《深度学习框架PyTorch:入门与实践》的对应代码,但是也可以作为一个独立的PyTorch入门指南和教程。

## 更新说明
已更新到**pytorch 0.4.1 (不是0.4.0)**
已更新到**pytorch 0.4.1 (不是0.4.0)**
已更新到**pytorch 0.4.1 (不是0.4.0)**

当前版本的代码是基于pytorch 0.4.1, 如果想使用旧版的 请 `git checkout v0.2` 或者 `git checkout v0.3`。旧版代码有更好的python2/python3 兼容,CPU/GPU兼容测试。 新版的代码未经过完整测试,已在GPU和python3 下测试通过。但是理论上在python2和CPU上不应该有太多的问题。

## 内容

Expand Down Expand Up @@ -31,17 +37,18 @@

**不是必要的**,这个仓库包含书中50%以上的文字内容,90%以上的代码,尤其是前几章入门内容,几乎是完全保留了书中的讲解内容。读者即使不买书也能正常使用本教程。

如果你觉得纸质书的优势吸引你,不妨小破费一笔,支持一下作者这大半年来的工作。同时为了尽可能的方便读者,笔者还专门开通腾讯云的服务,用以保存教程中用到的部分模型,预处理的数据和部分大文件。
~~如果你觉得纸质书的优势吸引你,不妨小破费一笔,支持一下作者这大半年来的工作。同时为了尽可能的方便读者,笔者还专门开通腾讯云的服务,用以保存教程中用到的部分模型,预处理的数据和部分大文件。~~
书中的部分内容已经过时,以此仓库内容为准。

## 代码说明

- 教程代码同时在Python2和Python3下测试通过
- 实战部分代码还同时在GPU和CPU环境下测试通过
- ~~所有的代码都是基于最新版的PyTorch 0.2.0~~,本人承诺会至少维护代码更新兼容到PyTorch `0.4`
- 代码主要在python3下测试得到最终结果,python2暂未测试。v0.2和v0.3 分支的代码同时经过严格测试支持python2/python3
- 实战部分代码同时在GPU和CPU环境下测试通过
- 代码已更新兼容到PyTorch `0.4.1`, 后续会考虑兼容 `v1.0`,但暂无确切时间点。

目前前五章的代码已经更新到PyTorch 0.3.0 , 如果你想在PyTorch 0.2.0下运行,请
如果你想在PyTorch 0.2.0或0.3下运行,请
```
git checkout v0.2
git checkout v0.2 # v0.3
```

如果有任何不当,或者有待改进的地方,欢迎读者开issue讨论,或者提交pull request。
Expand Down
4 changes: 2 additions & 2 deletions chapter10-图像描述(Image Caption)/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

## 1 下载数据

本次实验的数据来自于[AI Challenger图像描述](https://challenger.ai/competition/caption/)。 请下载对应的训练数据。如果你只是想测试看看效果,可以跳过这一步。
本次实验的数据来自于[AI Challenger图像描述](https://challenger.ai/competition/caption/)。 请下载对应的训练数据(ai_challenger_caption_train_20170902.zip)。如果你只是想测试看看效果,可以跳过这一步。 读者还可以从[MEGA](https://mega.nz/#!fP4TSJ6I!mgG_HSXqi1Kgg5gvwYArUnuRNgcDqpd8qoj09e0Yg10)下载数据

## 2 环境配置

Expand Down Expand Up @@ -59,7 +59,7 @@ python main.py train
# img_path='/mnt/ht/aichallenger/raw/ai_challenger_caption_train_20170902/caption_train_images_20170902/'
img_feature_path = 'results.pth' # 所有图片的features,20w*2048的向量
scale_size = 300
img_size = 256
img_size = 224
batch_size=8
shuffle = True
num_workers = 4
Expand Down
2 changes: 1 addition & 1 deletion chapter10-图像描述(Image Caption)/utils/beam_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ def beam_search(self, rnn_input, initial_state=None):
def get_topk_words(embeddings, state):
output, new_states = self.rnn(embeddings, state)
output = self.classifier(output.squeeze(0))
logprobs = log_softmax(output)
logprobs = log_softmax(output, dim=1)
logprobs, words = logprobs.topk(self.beam_size, 1)
return words.data, logprobs.data, new_states

Expand Down
6 changes: 3 additions & 3 deletions chapter6-实战指南/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@


## 数据下载
-[kaggle比赛官网](https://www.kaggle.com/c/dogs-vs-cats/data) 下载所需的数据
-[kaggle比赛官网](https://www.kaggle.com/c/dogs-vs-cats/data) 下载所需的数据;或者直接从此下载[训练集](http://pytorch-1252820389.file.myqcloud.com/data/dogcat/train.zip)[测试集](http://pytorch-1252820389.file.myqcloud.com/data/dogcat/test1.zip)
- 解压并把训练集和测试集分别放在一个文件夹中


Expand All @@ -29,7 +29,7 @@ python -m visdom.server

```
# 在gpu0上训练,并把可视化结果保存在visdom 的classifier env上
python main.py train --train-data-root=./data/train --use-gpu=True --env=classifier
python main.py train --train-data-root=./data/train --use-gpu --env=classifier
```


Expand All @@ -41,5 +41,5 @@ python main.py help
## 测试

```
python main.py test --data-root=./data/test --device='cpu' --batch-size=256 --load-path='checkpoints/squeezenet.pth'
python main.py test --data-root=./data/test --batch-size=256 --load-path='checkpoints/squeezenet.pth'
```
2 changes: 1 addition & 1 deletion chapter6-实战指南/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def _parse(self, kwargs):
warnings.warn("Warning: opt has not attribut %s" % k)
setattr(self, k, v)

opt.device = device=t.device('cuda') if opt.use_gpu else t.device('cpu')
opt.device =t.device('cuda') if opt.use_gpu else t.device('cpu')


print('user config:')
Expand Down
4 changes: 2 additions & 2 deletions chapter6-实战指南/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ def test(**kwargs):
for ii,(data,path) in tqdm(enumerate(test_dataloader)):
input = data.to(opt.device)
score = model(input)
probability = t.nn.functional.softmax(score)[:,0].detach().tolist()
probability = t.nn.functional.softmax(score,dim=1)[:,0].detach().tolist()
# label = score.max(dim = 1)[1].detach().tolist()

batch_results = [(path_,probability_) for path_,probability_ in zip(path,probability) ]
batch_results = [(path_.item(),probability_) for path_,probability_ in zip(path,probability) ]

results += batch_results
write_csv(results,opt.result_file)
Expand Down
8 changes: 4 additions & 4 deletions chapter7-GAN生成动漫头像/README.MD
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ Usage: python main.py FUNCTION --key=value,--key2=value2 ..

- 训练
```bash
python main.py train --nogpu --vis=False
python main.py train --gpu --vis=False
```

- 生成图片
Expand Down Expand Up @@ -94,13 +94,13 @@ python main.py generate --nogpu --vis=False \
### 兼容性测试
train
- [x] GPU
- [x] CPU
- [x] Python2
- [] CPU
- [] Python2
- [x] Python3

test:

- [x] GPU
- [x] CPU
- [x] Python2
- [] Python2
- [x] Python3
2 changes: 1 addition & 1 deletion chapter7-GAN生成动漫头像/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ def train(**kwargs):
vis.plot('errord', errord_meter.value()[0])
vis.plot('errorg', errorg_meter.value()[0])

if epoch % opt.save_every == 0:
if (epoch+1) % opt.save_every == 0:
# 保存模型、图片
tv.utils.save_image(fix_fake_imgs.data[:64], '%s/%s.png' % (opt.save_path, epoch), normalize=True,
range=(-1, 1))
Expand Down
7 changes: 4 additions & 3 deletions chapter8-风格迁移(Neural Style)/README.MD
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ python main.py train --use-gpu --data-root=data --batch-size=2
- 生成图片

读者可以[点此](http://pytorch-1252820389.cosbj.myqcloud.com/transformer.pth)下载预训练的模型`transformer.pth`
建议下载一张高清的图片,这样风格迁移的效果会比较好。
```bash
python main.py stylize --model-path='transformer.pth' \
--content-path='amber.jpg'\
Expand Down Expand Up @@ -75,13 +76,13 @@ python main.py stylize --model-path='transformer.pth' \
### 兼容性测试
train
- [x] GPU
- [x] CPU
- [x] Python2
- [] CPU
- [] Python2
- [x] Python3

test:

- [x] GPU
- [x] CPU
- [x] Python2
- [] Python2
- [x] Python3
2 changes: 2 additions & 0 deletions chapter8-风格迁移(Neural Style)/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ def train(**kwargs):
# 损失网络 Vgg16
vgg = Vgg16().eval()
vgg.to(device)
for param in vgg.parameters():
param.requires_grad = False

# 优化器
optimizer = t.optim.Adam(transformer.parameters(), opt.lr)
Expand Down
4 changes: 1 addition & 3 deletions chapter8-风格迁移(Neural Style)/transformer_net.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,16 +79,14 @@ class UpsampleConvLayer(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride, upsample=None):
super(UpsampleConvLayer, self).__init__()
self.upsample = upsample
if upsample:
self.upsample_layer = nn.Upsample(scale_factor=upsample)
reflection_padding = int(np.floor(kernel_size / 2))
self.reflection_pad = nn.ReflectionPad2d(reflection_padding)
self.conv2d = nn.Conv2d(in_channels, out_channels, kernel_size, stride)

def forward(self, x):
x_in = x
if self.upsample:
x_in = self.upsample_layer(x_in)
x_in = t.nn.functional.interpolate(x_in, scale_factor=self.upsample)
out = self.reflection_pad(x_in)
out = self.conv2d(out)
return out
Expand Down
8 changes: 4 additions & 4 deletions chapter9-神经网络写诗(CharRNN)/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ python main.py gen --model-path='checkpoints/tang_199.pth' \
--start-words='深度学习' \
--prefix-words='江流天地外,山色有无中。' \
--acrostic=True\
--nouse-gpu # 或者 --use-gpu=False
--nouse-gpu
深居不可见,浩荡心亦同。度年一何远,宛转三千雄。学立万里外,诸夫四十功。习习非吾仕,所贵在其功。
```

Expand All @@ -82,15 +82,15 @@ python2 main.py gen --model-path='model.pth'
### 兼容性测试
train
- [x] GPU
- [x] CPU
- [x] Python2
- [] CPU
- [] Python2
- [x] Python3

test:

- [x] GPU
- [x] CPU
- [x] Python2
- [] Python2
- [x] Python3


Expand Down
6 changes: 3 additions & 3 deletions chapter9-神经网络写诗(CharRNN)/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def generate(model, start_words, ix2word, word2ix, prefix_words=None):
w = results[i]
input = input.data.new([word2ix[w]]).view(1, 1)
else:
top_index = output.data[0].topk(1)[1][0]
top_index = output.data[0].topk(1)[1][0].item()
w = ix2word[top_index]
results.append(w)
input = input.data.new([top_index]).view(1, 1)
Expand Down Expand Up @@ -101,7 +101,7 @@ def gen_acrostic(model, start_words, ix2word, word2ix, prefix_words=None):

for i in range(opt.max_gen_len):
output, hidden = model(input, hidden)
top_index = output.data[0].topk(1)[1][0]
top_index = output.data[0].topk(1)[1][0].item()
w = ix2word[top_index]

if (pre_word in {u'。', u'!', '<START>'}):
Expand Down Expand Up @@ -173,7 +173,7 @@ def train(**kwargs):
vis.plot('loss', loss_meter.value()[0])

# 诗歌原文
poetrys = [[ix2word[_word] for _word in data_[:, _iii]]
poetrys = [[ix2word[_word] for _word in data_[:, _iii].tolist()]
for _iii in range(data_.shape[1])][:16]
vis.text('</br>'.join([''.join(poetry) for poetry in poetrys]), win=u'origin_poem')

Expand Down

0 comments on commit c8aa4bb

Please sign in to comment.