音樂網(wǎng)站的設計與開發(fā)可以免費網(wǎng)絡推廣網(wǎng)站
sigmoid函數(shù)
def sigmoid(x):return 1.0 / (1+np.exp((-x)))
定義最小平方和損失函數(shù)
loss = torch.nn.MSELoss()
線性回歸編程
如果不加噪音就成了正常的線性函數(shù)了,所以要加噪音。
torch.normal(0, 0.01, y.shape)
torch.normal(0, 0.01, y.shape)是一個用于生成服從正態(tài)分布的張量的函數(shù)。其中,0代表均值,0.01代表標準差,y.shape表示生成的張量的形狀與y相同。具體而言,該函數(shù)會生成一個張量,其元素值是從均值為0、標準差為0.01的正態(tài)分布中隨機采樣得到的。
y.reshape((-1, 1))
y.reshape((-1, 1))是將張量y進行形狀重塑的操作。通過該操作,可以將y轉換為一個列向量,其中每個元素保持不變。
在PyTorch中,使用reshape函數(shù)對張量進行形狀調(diào)整。參數(shù)(-1, 1)表示將y重塑為一個列向量,其中-1表示自動計算此維度的大小,而1表示列的維度大小為1。
y.reshape((-1, 1))將返回一個形狀調(diào)整后的新張量,而原始的y張量保持不變。
手動實現(xiàn)線性回歸
pip install d2l==0.17.6
import randomimport torch
from d2l import torch as d2ldef synthetic_data(w,b,num_examples):# 生成大小為(0,1),num_examples行,len(w)列的數(shù)據(jù)x , 此處是(1000,2)X = torch.normal(0,1,(num_examples,len(w)))# y = X*w + by = torch.matmul(X,w) + b# y 加上噪音y += torch.normal(0,0.01,y.shape)return X,y.reshape((-1,1))'''隨機(小批量)梯度下降'''
def data_iter(batch_size,features,labels):num_examples = features.shape[0]'''生成0-999'''indices = list(range(num_examples))'''打亂0-999'''random.shuffle(indices)'''0-999中每次取一個batch_size'''for i in range(0,num_examples,batch_size):'''設置一個batch的索引'''batch_indices = torch.tensor(indices[i:min(i+batch_size,num_examples)])yield features[batch_indices],labels[batch_indices]def plot_img(features,labels):# 創(chuàng)建一個畫板d2l.set_figsize()# 畫一個散點圖 (numpy格式的x,y,散點的像素大小)d2l.plt.scatter(features[:, 1].detach().numpy(), labels.detach().numpy(), 1)# 展示圖像d2l.plt.show()true_w = torch.tensor([2,-3.4])
true_b = 4.2
features,labels = synthetic_data(true_w,true_b,1000)# 畫圖顯示特征和標簽
# plot_img(features,labels)batch_size = 10
for X,y in data_iter(batch_size,features,labels):print(X,'\n',y)break# 初始化模型參數(shù), w是個列,形狀為兩行1列,值符合0,0.01的分布
w = torch.normal(0,0.01,size=(2,1),requires_grad=True)
b = torch.zeros(1,requires_grad=True)# 定義線性函數(shù)
def linreg(X,w,b):return torch.matmul(X,w)+b# 定義損失函數(shù)
def squared_loss(y_hat,y):return (y_hat - y.reshape(y_hat.shape)) ** 2 /2# 定義優(yōu)化函數(shù)
def sgd(params,lr,batch_size):'''小批量隨機梯度下降'''with torch.no_grad():for param in params:'''參數(shù) = 參數(shù) - 1/batch_size * -學習率 * 梯度'''param -= lr * param.grad / batch_size'''一個參數(shù)一個梯度,該下一個參數(shù)了比如是w2,所以要梯度清零'''param.grad.zero_()# 開始訓練,定義參數(shù)和網(wǎng)絡
lr = 0.03
num_epochs = 10
net = linreg
loss = squared_lossfor epoch in range(num_epochs):for X,y in data_iter(batch_size,features,labels):y_hat = net(X,w,b)L = loss(y_hat,y)# 計算的是每個樣本的損失,所以要求和L.sum().backward()# 更新參數(shù)sgd([w,b],lr,batch_size)with torch.no_grad():# w,b已經(jīng)經(jīng)過上面的更新函數(shù)更新過了,用更新后的w,b代入公式 計算損失train_L = loss(net(features,w,b),labels)print(f'epoch {epoch+1}, loss {float(train_L.mean()):f}')