本文已收錄于Pytorch系列專欄: Pytorch入門與實踐 專欄旨在詳解Pytorch,精煉地總結重點,面向入門學習者,掌握Pytorch架構,為資料分析,機器學習及深度學習的代碼能力打下堅實的基礎。免費訂閱,持續更新。
張量變換
1.torch.reshape
torch.reshape(input,shape)
功能:變換張量形狀
注意事項:當張量在記憶體中是連續時,新張量與 input 共享資料記憶體
- input : 要變換的張量
- shape 新張量的形狀
code:
t = torch.randperm(8)
t_reshape = torch.reshape(t, (-1, 2, 2)) # -1表示該次元不用關心,是由其他幾個次元計算而來的
print("t:{}\nt_reshape:\n{}".format(t, t_reshape))
t[0] = 1024
print("t:{}\nt_reshape:\n{}".format(t, t_reshape))
print("t.data 記憶體位址:{}".format(id(t.data)))
print("t_reshape.data 記憶體位址:{}".format(id(t_reshape.data)))
改變其中一個數,另一個張量随之改變,可見是記憶體共享的。
t:tensor([5, 4, 2, 6, 7, 3, 1, 0])
t_reshape:
tensor([[[5, 4],
[2, 6]],
[[7, 3],
[1, 0]]])
t:tensor([1024, 4, 2, 6, 7, 3, 1, 0])
t_reshape:
tensor([[[1024, 4],
[ 2, 6]],
[[ 7, 3],
[ 1, 0]]])
t.data 記憶體位址:2030792110712
t_reshape.data 記憶體位址:2030792110712
2.torch.transpose
torch.transpose(input, dim0, dim1)
功能:交換張量的兩個次元
- input : 要變換的張量
- dim0 要交換的次元
- dim1 要交換的次元
code
# torch.transpose
t = torch.rand((2, 3, 4))
t_transpose = torch.transpose(t, dim0=1, dim1=2) # c*h*w h*w*c
print("t shape:{}\nt_transpose shape: {}".format(t.shape, t_transpose.shape))
t shape:torch.Size([2, 3, 4])
t_transpose shape: torch.Size([2, 4, 3])
3.torch.t()
torch.t(input)
功能:2 維張量轉置,對矩陣而言,等價于torch.transpose(input, 0, 1)
4.torch.squeeze()
torch.squeeze(input, dim=None, out=None)
功能:壓縮長度為 1 的次元(軸)
- dim : 若為 None ,移除所有長度為 1 的軸;若指定次元,當且僅當該軸長度為 1 時,可以被移除;
5.torch.unsqueeze()
torch.usqueeze(input, dim, out=None)
功能:
- 依據dim 擴充次元
- dim : 擴充的次元, 這個次元就是1了
張量的數學運算
1.加減乘除
- torch.add()
功能:逐元素計算 input+alpha × othertorch.add(input, alpha=1, other, out=None)
- input : 第一個張量
- alpha : 乘項因子
- other : 第二個張量
- torch.addcdiv()加法集合除法
-
torch.addcmul()加法集合乘法
torch.addcmul(input, value=1, tensor1, tensor2,out= None)
- torch.sub()
- torch.mul()
code:
t_0 = torch.randn((3, 3))
t_1 = torch.ones_like(t_0)
t_add = torch.add(t_0, 10, t_1)
print("t_0:\n{}\nt_1:\n{}\nt_add_10:\n{}".format(t_0, t_1, t_add))
t_0:
tensor([[ 0.6614, 0.2669, 0.0617],
[ 0.6213, -0.4519, -0.1661],
[-1.5228, 0.3817, -1.0276]])
t_1:
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
t_add_10:
tensor([[10.6614, 10.2669, 10.0617],
[10.6213, 9.5481, 9.8339],
[ 8.4772, 10.3817, 8.9724]])
Process finished with exit code 0
2.對數,指數,幂函數
- torch.log(input, out=None)
- torch,log10(input, out=None)
- torch.log2(input, out=None)
- torch.exp(input, out=None)
- torch.pow(input, out=None)
3.三角函數
- torch.abs(input, out=None)
- torch.acos(input, out=None)
- torch.cosh(input, out=None)
- torch.cos(input, out=None)
- torch.asin(input, out=None)
- torch.atan(input, out=None)
- torch.atan2(input, other, out=None)
應用:線性回歸
線性回歸是分析一個變量與另外一(多)個變量之間關系的方法。
因變量:y
自變量 x
關系 :線性 y =wx + b
分析:求解 w b
求解步驟
- 确定模型 Model:y = wx + b
- 選擇損失函數 MSE:
-
求解梯度并更新 w,b
w = w-LR * w.grad
b = b-LR * w.grad
code:
import torch
import matplotlib.pyplot as plt
torch.manual_seed(10)
lr = 0.05
# Create training data
x = torch.rand(20, 1) * 10 # x data (tensor), shape=(20, 1)
y = 2*x + (5 + torch.randn(20, 1)) # y data (tensor), shape=(20, 1)
# Build Linear Regression Parameters
# Initialize w and b, where w is initialized to a normal distribution and b is initialized to 0
# Automatic differentiation is required, so set requires grad to True.
w = torch.randn((1), requires_grad=True)
b = torch.zeros((1), requires_grad=True)
for iteration in range(1000):
# forward propagation
wx = torch.mul(w, x)
y_pred = torch.add(wx, b)
# Calculate MSE loss
loss = (0.5 * (y - y_pred) ** 2).mean()
# backpropagation
loss.backward()
# update parameters
b.data.sub_(lr * b.grad)
w.data.sub_(lr * w.grad)
# zeroing out the gradient of a tensor
w.grad.zero_()
b.grad.zero_()
# Draw
if iteration % 20 == 0:
plt.scatter(x.data.numpy(), y.data.numpy())
plt.plot(x.data.numpy(), y_pred.data.numpy(), 'r-', lw=5)
plt.text(2, 20, 'Loss=%.4f' % loss.data.numpy(), fontdict={'size': 20, 'color': 'red'})
plt.xlim(1.5, 10)
plt.ylim(8, 28)
plt.title("Iteration: {}\nw: {} b: {}".format(iteration, w.data.numpy(), b.data.numpy()))
plt.pause(0.5)
if loss.data.numpy() < 1:
break
可以看到,經過不斷地疊代之後。逐漸收斂,當Loss值小于1時停止疊代。