Skip to content

Commit 7cb7645

Browse files
committed
docs(demo): 使用示例
1 parent 749fca0 commit 7cb7645

File tree

2 files changed

+79
-1
lines changed

2 files changed

+79
-1
lines changed

docs/示例.md

+77
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
2+
# 使用示例
3+
4+
使用`PyNet`非常简单,类似`PyTorch`实现方式
5+
6+
* 第一步:创建数据集并进行预处理
7+
* 第二步:创建网络模型对象
8+
* 第三步:创建评价函数对象
9+
* 第四步: 创建优化器对象
10+
* 第五步:创建求解器对象,设置训练参数,训练
11+
* 第六步:打印和绘制训练结果
12+
13+
`examples/2_nn_mnist.py`为例
14+
15+
## 头文件加载
16+
17+
```
18+
import pynet
19+
import pynet.models as models
20+
import pynet.optim as optim
21+
import pynet.nn as nn
22+
from pynet.vision.data import mnist
23+
from pynet.vision import Draw
24+
```
25+
26+
## 创建数据集并进行预处理
27+
28+
```
29+
data_path = '/home/zj/data/decompress_mnist'
30+
31+
x_train, x_test, y_train, y_test = mnist.load_mnist(data_path, shuffle=True, is_flatten=True)
32+
33+
x_train = x_train / 255 - 0.5
34+
x_test = x_test / 255 - 0.5
35+
36+
data = {
37+
'X_train': x_train,
38+
'y_train': y_train,
39+
'X_val': x_test,
40+
'y_val': y_test
41+
}
42+
```
43+
44+
## 创建网络模型对象
45+
46+
```
47+
model = models.TwoLayerNet(num_in=784, num_hidden=200, num_out=10)
48+
```
49+
50+
## 创建评价函数对象
51+
52+
```
53+
criterion = nn.CrossEntropyLoss()
54+
```
55+
56+
## 创建优化器对象
57+
58+
```
59+
optimizer = optim.SGD(model.params)
60+
```
61+
62+
## 创建求解器对象,设置训练参数,训练
63+
64+
```
65+
solver = pynet.Solver(model, data, criterion, optimizer, batch_size=128, num_epochs=10)
66+
solver.train()
67+
```
68+
69+
## 打印和绘制训练结果
70+
71+
```
72+
plt = Draw()
73+
plt(solver.loss_history)
74+
plt.multi_plot((solver.train_acc_history, solver.val_acc_history), ('train', 'val'),
75+
title='准确率', xlabel='迭代/次', ylabel='准确率')
76+
print('best_train_acc: %f; best_val_acc: %f' % (solver.best_train_acc, solver.best_val_acc))
77+
```

mkdocs.yml

+2-1
Original file line numberDiff line numberDiff line change
@@ -34,4 +34,5 @@ nav:
3434
- 网络层: 网络层.md
3535
- 网络模型: 网络模型.md
3636
- 求解器: 求解器.md
37-
- 数据集: 数据集.md
37+
- 数据集: 数据集.md
38+
- 使用示例: 示例.md

0 commit comments

Comments
 (0)