pytorch開發環境搭建(win10)
上一篇(pytorch開發環境搭建(win10) )完成了pytorch環境搭建
本篇就來介紹第一個pytorch程序及
我的是windows環境,開發工具Pycharm
一、新建工程
工程名:pytorch-test
畫紅圈的選中
點擊creat 創建
二、創建pytorch測試文件
創建test-one.py文件
詳細 代碼如下
#!~/anaconda3/bin/python
# _*_ coding:UTF-8 _*_
from __future__ import print_function
from itertools import count
import numpy as np
import torch
import torch.autograd
import torch.nn.functional as F
from torch.autograd import Variable
import matplotlib.pyplot as plt
random_state = 5000
torch.manual_seed(random_state)
poly_degree = 4
W_target = torch.randn(poly_degree, 1) * 5
b_target = torch.randn(1) * 5
def make_features(x):
"""
創建一個特徵矩陣結構爲[x, x^2, x^3, x^4].
"""
x = x.unsqueeze(1)
return torch.cat([x ** i for i in range(1, poly_degree + 1)], 1)
def f(x):
"""近似函數"""
return x.mm(W_target) + b_target[0]
def poly_desc(W, b):
"""生成多項式描述內容"""
result = 'y = '
for i, w in enumerate(W):
result += '{:+.2f} x^{} '.format(w, len(W) - i)
result += '{:+.2f}'.format(b[0])
return result
def get_batch(batch_size=32):
"""創建類似(x, f(x))批數據"""
random = torch.from_numpy(np.sort(torch.randn(batch_size)))
x = make_features(random)
y = f(x)
return Variable(x), Variable(y)
# 聲明模型
fc = torch.nn.Linear(W_target.size(0), 1)
for batch_idx in count(1):
# 獲取數據
batch_x, batch_y = get_batch()
# 重製求導
fc.zero_grad()
# 前向傳播
output = F.smooth_l1_loss(fc(batch_x), batch_y)
loss = output.item()
# 後向傳播
output.backward()
# 應用導數
for param in fc.parameters():
param.data.add_(-0.1 * param.grad.data)
# 停止條件
if loss < 1e-3:
plt.cla()
plt.scatter(batch_x.data.numpy()[:, 0], batch_y.data.numpy()[:, 0], label='real curve', color='b')
plt.plot(batch_x.data.numpy()[:, 0], fc(batch_x).data.numpy()[:, 0], label='fitting curve', color='r')
plt.title('$Y=W^T*X+b$')
plt.legend()
plt.savefig('1.png')
plt.show()
break
print('Loss: {:.6f} after {} batches'.format(loss, batch_idx))
print('==> Learned function:\t' + poly_desc(fc.weight.data.view(-1), fc.bias.data))
print('==> Actual function:\t' + poly_desc(W_target.view(-1), b_target))
運行文件
結果如下
這是個經典線性函數
此處創建了一些隨機訓練樣本,使其符合經典函數Y=MTX+b Y=M^TX+bY=M
T
X+b分佈,再增加一點噪聲處理使得樣本出現一定的偏差。然後創建一個線性迴歸的模型,在訓練過程中對訓練樣本進行反向傳播,求導後根據指定的損失邊界結束訓練。
上圖白色就是線性迴歸的結果