生活随笔
收集整理的這篇文章主要介紹了
PyTorch深度学习实践07
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
07multiple dimension input.py
比如下圖這個預測一個人在一年之后得糖尿病的概率的例子,這個時候我們的輸入將會有很多的指標。你可以把它看成是我們體檢的各種值。最后一排的外代表了他是否會得糖尿病。
import os
os.environ
["KMP_DUPLICATE_LIB_OK"]="TRUE"import numpy as np
import torch
import matplotlib.pyplot as plt
xy
=np.loadtxt
('diabetes.csv',delimiter
=',',dtype
=np.float32
)x_data
=torch.from_numpy
(xy
[:,:-1
])
y_data
=torch.from_numpy
(xy
[:,
[-1
]])
class Model
(torch.nn.Module
):def __init__
(self
):super
(Model, self
).__init__
()self.linear1
=torch.nn.Linear
(8,6
)self.linear2
=torch.nn.Linear
(6,4
)self.linear3
=torch.nn.Linear
(4,1
)self.sigmoid
=torch.nn.Sigmoid
()def forward
(self,x
):x
= self.sigmoid
(self.linear1
(x
))x
= self.sigmoid
(self.linear2
(x
))x
= self.sigmoid
(self.linear3
(x
))return xmodel
=Model
()
layer1_weight
= model.linear1.weight.data
layer1_bias
= model.linear1.bias.data
print
("layer1_weight", layer1_weight
)
print
("layer1_weight.shape", layer1_weight.shape
)
print
("layer1_bias", layer1_bias
)
print
("layer1_bias.shape", layer1_bias.shape
)
'''
layer1_weight tensor([[ 0.1053, 0.1716, 0.1981, 0.1613, -0.1268, 0.1843, -0.3029, -0.1547],[-0.2075, -0.2407, -0.1529, -0.2438, 0.3339, -0.3276, 0.0095, -0.1153],[ 0.1969, 0.0073, -0.1312, -0.1668, 0.2570, -0.2317, 0.2036, 0.0433],[ 0.1871, 0.3029, 0.2014, 0.2805, 0.0691, -0.0206, 0.3492, -0.2535],[-0.0884, 0.2787, -0.0073, -0.1533, -0.0399, -0.1590, 0.2161, 0.3270],[-0.2526, -0.1705, -0.0183, 0.2450, -0.1937, -0.1331, -0.0771, 0.0410]])
layer1_weight.shape torch.Size([6, 8])
layer1_bias tensor([ 1.6963e-02, 2.0659e-01, -3.1528e-01, -2.0308e-01, -1.4773e-04,-3.5623e-02])
layer1_bias.shape torch.Size([6])'''
criterion
=torch.nn.BCELoss
(reduction
='mean')
optimizer
=torch.optim.SGD
(model.parameters
(),lr
=0.1
)epoch_list
=[]
loss_list
=[]for epoch
in range
(1000
):y_pre
=model
(x_data
)loss
=criterion
(y_pre,y_data
)print
(epoch,loss.item
())epoch_list.append
(epoch
)loss_list.append
(loss.item
())optimizer.zero_grad
()loss.backward
()optimizer.step
()plt.plot
(epoch_list,loss_list
)
plt.xlabel
('epoch')
plt.ylabel
('loss')
plt.show
()
訓練10000 趨于收斂 w在0.4左右
訓練1000 趨于收斂 w在0.6左右
總結
以上是生活随笔為你收集整理的PyTorch深度学习实践07的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。