Skip to content

Commit b2178e2

Browse files
author
Morvan Zhou
committed
move files
0 parents  commit b2178e2

26 files changed

+1681
-0
lines changed

README.md

+90
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
<p align="center">
2+
<a href="http://pytorch.org/" target="_blank">
3+
<img width="40%" src="https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/logo.png" style="max-width:100%;">
4+
</a>
5+
</p>
6+
7+
---
8+
9+
<br>
10+
11+
# pyTorch Tutorials
12+
13+
In these tutorials for pyTorch, we will build our first Neural Network and try to build some advanced Neural Network architectures developed recent years.
14+
15+
All methods mentioned below have their video and text tutorial in Chinese. Visit [莫烦 Python](https://morvanzhou.github.io/tutorials/) for more.
16+
If you speak Chinese, you can watch my [Youtube channel](https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg) as well.
17+
18+
19+
* pyTorch basic
20+
* [torch and numpy](https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/201_torch_numpy.py)
21+
* [Variable](https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/202_variable.py)
22+
* [Activation](https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/203_activation.py)
23+
* Build your first network
24+
* [Regression](https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/301_regression.py)
25+
* [Classification](https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/302_classification.py)
26+
* [An easy way](https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/303_build_nn_quickly.py)
27+
* [Save and reload](https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/304_save_reload.py)
28+
* [Train on batch](https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/305_batch_train.py)
29+
* [Optimizers](https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/306_optimizer.py)
30+
* Advanced neural network
31+
* [CNN](https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/401_CNN.py)
32+
* [RNN-Classification](https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/402_RNN_classifier.py)
33+
* [RNN-Regression](https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/403_RNN_regressor.py)
34+
* [AutoEncoder](https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/404_autoencoder.py)
35+
* [DQN Reinforcement Learning](https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/405_DQN_Reinforcement_learning.py)
36+
* Others (WIP)
37+
* [Why torch dynamic](https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/501_why_torch_dynamic_graph.py)
38+
* [Train on GPU](https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/502_GPU.py)
39+
* [Dropout](https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/503_dropout.py)
40+
* [Batch Normalization](https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/504_batch_normalization.py)
41+
42+
### [Regression](https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/301_regression.py)
43+
44+
<a href="https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/301_regression.py">
45+
<img class="course-image" src="https://morvanzhou.github.io/static/results/torch/1-1-2.gif">
46+
</a>
47+
48+
### [Classification](https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/302_classification.py)
49+
50+
<a href="https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/302_classification.py">
51+
<img class="course-image" src="https://morvanzhou.github.io/static/results/torch/1-1-3.gif">
52+
</a>
53+
54+
### [RNN](https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/403_RNN_regressor.py)
55+
56+
<a href="https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/403_RNN_regressor.py">
57+
<img class="course-image" src="https://morvanzhou.github.io/static/results/torch/4-3-1.gif" >
58+
</a>
59+
60+
### [Autoencoder](https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/404_autoencoder.py)
61+
62+
<a href="https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/403_RNN_regressor.py">
63+
<img class="course-image" src="https://morvanzhou.github.io/static/results/torch/4-4-1.gif" >
64+
</a>
65+
66+
<a href="https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/403_RNN_regressor.py">
67+
<img class="course-image" src="https://morvanzhou.github.io/static/results/torch/4-4-2.gif" >
68+
</a>
69+
70+
### [Dropout](https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/503_dropout.py)
71+
<a href="https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/503_dropout.py">
72+
<img class="course-image" src="https://morvanzhou.github.io/static/results/torch/5-3-1.gif" >
73+
</a>
74+
75+
### [Batch Normalization](https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/504_batch_normalization.py)
76+
<a href="https://github.com/MorvanZhou/tutorials/blob/master/pytorchTUT/504_batch_normalization.py">
77+
<img class="course-image" src="https://morvanzhou.github.io/static/results/torch/5-4-2.gif" >
78+
</a>
79+
80+
# Donation
81+
82+
*If this does help you, please consider donating to support me for better tutorials. Any contribution is greatly appreciated!*
83+
84+
<div >
85+
<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_donations&amp;business=morvanzhou%40gmail%2ecom&amp;lc=C2&amp;item_name=MorvanPython&amp;currency_code=AUD&amp;bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted">
86+
<img style="border-radius: 20px; box-shadow: 0px 0px 10px 1px #888888;"
87+
src="https://www.paypalobjects.com/webstatic/en_US/i/btn/png/silver-pill-paypal-44px.png"
88+
alt="Paypal"
89+
height="auto" ></a>
90+
</div>

logo.png

3.95 KB
Loading

tutorial-contents/201_torch_numpy.py

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
"""
2+
Know more, visit 莫烦Python: https://morvanzhou.github.io/tutorials/
3+
My Youtube Channel: https://www.youtube.com/user/MorvanZhou
4+
5+
Dependencies:
6+
torch: 0.1.11
7+
numpy
8+
"""
9+
import torch
10+
import numpy as np
11+
12+
# details about math operation in torch can be found in: http://pytorch.org/docs/torch.html#math-operations
13+
14+
# convert numpy to tensor or vise versa
15+
np_data = np.arange(6).reshape((2, 3))
16+
torch_data = torch.from_numpy(np_data)
17+
tensor2array = torch_data.numpy()
18+
print(
19+
'\nnumpy array:', np_data, # [[0 1 2], [3 4 5]]
20+
'\ntorch tensor:', torch_data, # 0 1 2 \n 3 4 5 [torch.LongTensor of size 2x3]
21+
'\ntensor to array:', tensor2array, # [[0 1 2], [3 4 5]]
22+
)
23+
24+
25+
# abs
26+
data = [-1, -2, 1, 2]
27+
tensor = torch.FloatTensor(data) # 32-bit floating point
28+
print(
29+
'\nabs',
30+
'\nnumpy: ', np.abs(data), # [1 2 1 2]
31+
'\ntorch: ', torch.abs(tensor) # [1 2 1 2]
32+
)
33+
34+
# sin
35+
print(
36+
'\nsin',
37+
'\nnumpy: ', np.sin(data), # [-0.84147098 -0.90929743 0.84147098 0.90929743]
38+
'\ntorch: ', torch.sin(tensor) # [-0.8415 -0.9093 0.8415 0.9093]
39+
)
40+
41+
# mean
42+
print(
43+
'\nmean',
44+
'\nnumpy: ', np.mean(data), # 0.0
45+
'\ntorch: ', torch.mean(tensor) # 0.0
46+
)
47+
48+
# matrix multiplication
49+
data = [[1,2], [3,4]]
50+
tensor = torch.FloatTensor(data) # 32-bit floating point
51+
# correct method
52+
print(
53+
'\nmatrix multiplication (matmul)',
54+
'\nnumpy: ', np.matmul(data, data), # [[7, 10], [15, 22]]
55+
'\ntorch: ', torch.mm(tensor, tensor) # [[7, 10], [15, 22]]
56+
)
57+
# incorrect method
58+
data = np.array(data)
59+
print(
60+
'\nmatrix multiplication (dot)',
61+
'\nnumpy: ', data.dot(data), # [[7, 10], [15, 22]]
62+
'\ntorch: ', tensor.dot(tensor) # this will convert tensor to [1,2,3,4], you'll get 30.0
63+
)

tutorial-contents/202_variable.py

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
"""
2+
Know more, visit 莫烦Python: https://morvanzhou.github.io/tutorials/
3+
My Youtube Channel: https://www.youtube.com/user/MorvanZhou
4+
5+
Dependencies:
6+
torch: 0.1.11
7+
"""
8+
import torch
9+
from torch.autograd import Variable
10+
11+
# Variable in torch is to build a computational graph,
12+
# but this graph is dynamic compared with a static graph in Tensorflow or Theano.
13+
# So torch does not have placeholder, torch can just pass variable to the computational graph.
14+
15+
tensor = torch.FloatTensor([[1,2],[3,4]]) # build a tensor
16+
variable = Variable(tensor, requires_grad=True) # build a variable, usually for compute gradients
17+
18+
print(tensor) # [torch.FloatTensor of size 2x2]
19+
print(variable) # [torch.FloatTensor of size 2x2]
20+
21+
# till now the tensor and variable seem the same.
22+
# However, the variable is a part of the graph, it's a part of the auto-gradient.
23+
24+
t_out = torch.mean(tensor*tensor) # x^2
25+
v_out = torch.mean(variable*variable) # x^2
26+
print(t_out)
27+
print(v_out) # 7.5
28+
29+
v_out.backward() # backpropagation from v_out
30+
# v_out = 1/4 * sum(variable*variable)
31+
# the gradients w.r.t the variable, d(v_out)/d(variable) = 1/4*2*variable = variable/2
32+
print(variable.grad)
33+
'''
34+
0.5000 1.0000
35+
1.5000 2.0000
36+
'''
37+
38+
print(variable) # this is data in variable format
39+
"""
40+
Variable containing:
41+
1 2
42+
3 4
43+
[torch.FloatTensor of size 2x2]
44+
"""
45+
46+
print(variable.data) # this is data in tensor format
47+
"""
48+
1 2
49+
3 4
50+
[torch.FloatTensor of size 2x2]
51+
"""
52+
53+
print(variable.data.numpy()) # numpy format
54+
"""
55+
[[ 1. 2.]
56+
[ 3. 4.]]
57+
"""

tutorial-contents/203_activation.py

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
"""
2+
Know more, visit 莫烦Python: https://morvanzhou.github.io/tutorials/
3+
My Youtube Channel: https://www.youtube.com/user/MorvanZhou
4+
5+
Dependencies:
6+
torch: 0.1.11
7+
matplotlib
8+
"""
9+
import torch
10+
import torch.nn.functional as F
11+
from torch.autograd import Variable
12+
import matplotlib.pyplot as plt
13+
14+
# fake data
15+
x = torch.linspace(-5, 5, 200) # x data (tensor), shape=(100, 1)
16+
x = Variable(x)
17+
x_np = x.data.numpy() # numpy array for plotting
18+
19+
# following are popular activation functions
20+
y_relu = F.relu(x).data.numpy()
21+
y_sigmoid = F.sigmoid(x).data.numpy()
22+
y_tanh = F.tanh(x).data.numpy()
23+
y_softplus = F.softplus(x).data.numpy()
24+
# y_softmax = F.softmax(x) softmax is a special kind of activation function, it is about probability
25+
26+
27+
# plt to visualize these activation function
28+
plt.figure(1, figsize=(8, 6))
29+
plt.subplot(221)
30+
plt.plot(x_np, y_relu, c='red', label='relu')
31+
plt.ylim((-1, 5))
32+
plt.legend(loc='best')
33+
34+
plt.subplot(222)
35+
plt.plot(x_np, y_sigmoid, c='red', label='sigmoid')
36+
plt.ylim((-0.2, 1.2))
37+
plt.legend(loc='best')
38+
39+
plt.subplot(223)
40+
plt.plot(x_np, y_tanh, c='red', label='tanh')
41+
plt.ylim((-1.2, 1.2))
42+
plt.legend(loc='best')
43+
44+
plt.subplot(224)
45+
plt.plot(x_np, y_softplus, c='red', label='softplus')
46+
plt.ylim((-0.2, 6))
47+
plt.legend(loc='best')
48+
49+
plt.show()

tutorial-contents/301_regression.py

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
"""
2+
Know more, visit 莫烦Python: https://morvanzhou.github.io/tutorials/
3+
My Youtube Channel: https://www.youtube.com/user/MorvanZhou
4+
5+
Dependencies:
6+
torch: 0.1.11
7+
matplotlib
8+
"""
9+
import torch
10+
from torch.autograd import Variable
11+
import torch.nn.functional as F
12+
import matplotlib.pyplot as plt
13+
14+
torch.manual_seed(1) # reproducible
15+
16+
x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1) # x data (tensor), shape=(100, 1)
17+
y = x.pow(2) + 0.2*torch.rand(x.size()) # noisy y data (tensor), shape=(100, 1)
18+
19+
# torch can only train on Variable, so convert them to Variable
20+
x, y = Variable(x), Variable(y)
21+
22+
# plt.scatter(x.data.numpy(), y.data.numpy())
23+
# plt.show()
24+
25+
26+
class Net(torch.nn.Module):
27+
def __init__(self, n_feature, n_hidden, n_output):
28+
super(Net, self).__init__()
29+
self.hidden = torch.nn.Linear(n_feature, n_hidden) # hidden layer
30+
self.predict = torch.nn.Linear(n_hidden, n_output) # output layer
31+
32+
def forward(self, x):
33+
x = F.relu(self.hidden(x)) # activation function for hidden layer
34+
x = self.predict(x) # linear output
35+
return x
36+
37+
net = Net(n_feature=1, n_hidden=10, n_output=1) # define the network
38+
print(net) # net architecture
39+
40+
optimizer = torch.optim.SGD(net.parameters(), lr=0.5)
41+
loss_func = torch.nn.MSELoss() # this is for regression mean squared loss
42+
43+
plt.ion() # something about plotting
44+
plt.show()
45+
46+
for t in range(100):
47+
prediction = net(x) # input x and predict based on x
48+
49+
loss = loss_func(prediction, y) # must be (1. nn output, 2. target)
50+
51+
optimizer.zero_grad() # clear gradients for next train
52+
loss.backward() # backpropagation, compute gradients
53+
optimizer.step() # apply gradients
54+
55+
if t % 5 == 0:
56+
# plot and show learning process
57+
plt.cla()
58+
plt.scatter(x.data.numpy(), y.data.numpy())
59+
plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=5)
60+
plt.text(0.5, 0, 'Loss=%.4f' % loss.data[0], fontdict={'size': 20, 'color': 'red'})
61+
plt.pause(0.1)
62+
63+
plt.ioff()
64+
plt.show()

0 commit comments

Comments
 (0)