生活随笔
收集整理的這篇文章主要介紹了
使用Pytorch处理多维特征的输入
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
下圖這個預測一個人在一年之后得糖尿病的概率的例子,這個時候我們的輸入將會有很多的指標。你可以把它看成是我們體檢的各種值。最后一排的外代表了他是否會得糖尿病。
那么多維的特征輸入應該怎么辦呢?我們就需要把每一個特征x付以相應的權重。在進行邏輯回歸時,把每一個維度的x乘相應的權值的和加上一個偏置量,送入sigema函數進行二分類,就像這樣:
?當然在真正編程的時候是以矩陣乘法的形式進行運算的,也就是一次能算多個樣本的值,具體的推導過程大家可以看劉老師的教學視頻,這里就不寫了。根據數據集,我們需要構造一個從八維到一維的計算圖,就是這樣:
import numpy as np
import torch
from torch import nnxy=np.loadtxt("CIFAdata/diabetes.csv.gz",delimiter=",",dtype=np.float32)
x_data=torch.from_numpy(xy[:,:-1])
print(x_data)
#[-1] 表示要拿出一個矩陣
y_data=torch.from_numpy(xy[:,[-1]])
print(y_data)class Model(nn.Module):def __init__(self):##構造函數super(Model, self).__init__()#8維轉為6維self.linear1 = torch.nn.Linear(8,6)self.linear2 = torch.nn.Linear(6, 4)self.linear3 = torch.nn.Linear(4, 1)#激活函數# self.active=torch.nn.ReLU()#因為他里邊也沒有權重需要更新,所以要一個就行了,單純的算個數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 x
model=Model()##實例化模型criterion=torch.nn.BCELoss(size_average=True)
#model.parameters()會掃描module中的所有成員,
# 如果成員中有相應權重,那么都會將結果加到要訓練的參數集合上
optimizer=torch.optim.SGD(model.parameters(),lr=0.1)for epoch in range(100):y_pred=model(x_data)loss=criterion(y_pred,y_data)print(epoch,loss.item())#反向傳播optimizer.zero_grad()loss.backward()#Updataoptimizer.step()# 如果想查看某些層的參數,以神經網絡的第一層參數為例,可按照以下方法進行。
# 第一層的參數:
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)
總結
以上是生活随笔為你收集整理的使用Pytorch处理多维特征的输入的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。