公司做網(wǎng)站有問題怎么維權(quán)滄州百度推廣總代理
介紹:
在線性神經(jīng)網(wǎng)絡(luò)中,線性回歸是一種常見的任務(wù),用于預(yù)測一個連續(xù)的數(shù)值輸出。其目標(biāo)是根據(jù)輸入特征來擬合一個線性函數(shù),使得預(yù)測值與真實值之間的誤差最小化。
線性回歸的數(shù)學(xué)表達(dá)式為:
y = w1x1 + w2x2 + ... + wnxn + b其中,y表示預(yù)測的輸出值,x1, x2, ..., xn表示輸入特征,w1, w2, ..., wn表示特征的權(quán)重,b表示偏置項。
訓(xùn)練線性回歸模型的目標(biāo)是找到最優(yōu)的權(quán)重和偏置項,使得模型預(yù)測的輸出與真實值之間的平方差(即損失函數(shù))最小化。這一最優(yōu)化問題可以通過梯度下降等優(yōu)化算法來解決。
線性回歸在深度學(xué)習(xí)中也被廣泛應(yīng)用,特別是在淺層神經(jīng)網(wǎng)絡(luò)中。在深度學(xué)習(xí)中,通過將多個線性回歸模型組合在一起,可以構(gòu)建更復(fù)雜的神經(jīng)網(wǎng)絡(luò)結(jié)構(gòu),以解決更復(fù)雜的問題。
?手動生成數(shù)據(jù)集:
%matplotlib inline
import torch
from d2l import torch as d2l
import random#"""生成y=Xw+b+噪聲"""
def synthetic_data(w, b, num_examples): #生成num_examples個樣本X = d2l.normal(0, 1, (num_examples, len(w)))#隨機x,長度為特征個數(shù),權(quán)重個數(shù)y = d2l.matmul(X, w) + b#y的函數(shù)y += d2l.normal(0, 0.01, y.shape)#加上0~0.001的隨機噪音return X, d2l.reshape(y, (-1, 1))#返回true_w = d2l.tensor([2, -3.4])#初始化真實w
true_b = 4.2#初始化真實bfeatures, labels = synthetic_data(true_w, true_b, 1000)#隨機一些數(shù)據(jù)
print(features)
print(labels)
顯示數(shù)據(jù)集:
print('features:', features[0],'\nlabel:', labels[0])'''
features: tensor([ 2.1714, -0.6891])
label: tensor([10.8673])
'''d2l.set_figsize()
d2l.plt.scatter(d2l.numpy(features[:, 1]), d2l.numpy(labels), 1);
讀取小批量數(shù)據(jù)集:
#每次抽取一批量樣本
def data_iter(batch_size, features, labels):#步長、特征、標(biāo)簽num_examples = len(features)#特征個數(shù)indices = list(range(num_examples))random.shuffle(indices)# 這些樣本是隨機讀取的,沒有特定的順序,打亂順序for i in range(0, num_examples, batch_size):#隨機訪問,步長為batch_sizebatch_indices = d2l.tensor(indices[i: min(i + batch_size, num_examples)])yield features[batch_indices], labels[batch_indices]
定義模型:
#定義模型
def linreg(X, w, b): """線性回歸模型"""return d2l.matmul(X, w) + b
定義損失函數(shù):
#定義損失和函數(shù)
def squared_loss(y_hat, y): #@save"""均方損失"""return (y_hat - d2l.reshape(y, y_hat.shape)) ** 2 / 2
定義優(yōu)化算法(小批量隨機梯度下降):
#定義優(yōu)化算法 """小批量隨機梯度下降"""
def sgd(params, lr, batch_size): #參數(shù)、lr學(xué)習(xí)率、with torch.no_grad():for param in params:param -= lr * param.grad / batch_sizeparam.grad.zero_()
模型訓(xùn)練:
#訓(xùn)練
lr = 0.03#學(xué)習(xí)率
num_epochs = 3#數(shù)據(jù)掃三遍
net = linreg#模型
loss = squared_loss#損失函數(shù)
#初始化模型參數(shù)
w = torch.normal(0, 0.01, size=(2,1), requires_grad=True)#權(quán)重
b = torch.zeros(1, requires_grad=True)#b全賦為0for epoch in range(num_epochs):for X, y in data_iter(batch_size, features, labels):#拿出一批量x,yl = loss(net(X, w, b), y) # X和y的小批量損失,實際的和預(yù)測的# 因為l形狀是(batch_size,1),而不是一個標(biāo)量。l中的所有元素被加到一起,# 并以此計算關(guān)于[w,b]的梯度l.sum().backward()sgd([w, b], lr, batch_size) # 使用參數(shù)的梯度更新參數(shù)with torch.no_grad():train_l = loss(net(features, w, b), labels)print(f'epoch {epoch + 1}, loss {float(train_l.mean()):f}')
'''
epoch 1, loss 0.037302
epoch 2, loss 0.000140
epoch 3, loss 0.000048
'''print(f'w的估計誤差: {true_w - d2l.reshape(w, true_w.shape)}')
print(f'b的估計誤差: {true_b - b}')
'''
w的估計誤差: tensor([0.0006, 0.0001], grad_fn=<SubBackward0>)
b的估計誤差: tensor([-0.0003], grad_fn=<RsubBackward1>)
'''print(w)
'''
tensor([[ 1.9994],[-3.4001]], requires_grad=True)
'''print(b)
'''
tensor([4.2003], requires_grad=True)
'''