- PyTorch 教程
- PyTorch - 首頁
- PyTorch - 簡介
- PyTorch - 安裝
- 神經網路的數學基礎
- PyTorch - 神經網路基礎
- 機器學習通用工作流程
- 機器學習與深度學習
- 實現第一個神經網路
- 神經網路到功能模組
- PyTorch - 術語
- PyTorch - 載入資料
- PyTorch - 線性迴歸
- PyTorch - 卷積神經網路
- PyTorch - 迴圈神經網路
- PyTorch - 資料集
- PyTorch - 卷積網路簡介
- 從頭開始訓練卷積網路
- PyTorch - 卷積網路中的特徵提取
- PyTorch - 卷積網路的視覺化
- 使用卷積網路進行序列處理
- PyTorch - 詞嵌入
- PyTorch - 遞迴神經網路
- PyTorch 有用資源
- PyTorch - 快速指南
- PyTorch - 有用資源
- PyTorch - 討論
PyTorch - 線性迴歸
在本章中,我們將重點關注使用 TensorFlow 實現線性迴歸的基本示例。邏輯迴歸或線性迴歸是一種監督機器學習方法,用於對有序離散類別進行分類。我們本章的目標是構建一個模型,使用者可以透過該模型預測預測變數與一個或多個自變數之間的關係。
這兩個變數之間的關係被認為是線性的,即如果 y 是因變數,x 被認為是自變數,那麼兩個變數的線性迴歸關係將類似於下面提到的等式 -
Y = Ax+b
接下來,我們將設計一個線性迴歸演算法,使我們能夠理解下面給出的兩個重要概念 -
- 成本函式
- 梯度下降演算法
線性迴歸的示意圖如下所示
解釋結果
$$Y=ax+b$$
a 的值為斜率。
b 的值為y 截距。
r 是相關係數。
r2 是相關係數。
線性迴歸方程的圖形檢視如下所示 -
使用 PyTorch 實現線性迴歸使用以下步驟 -
步驟 1
使用以下程式碼匯入建立 PyTorch 中的線性迴歸所需的必要包 -
import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation import seaborn as sns import pandas as pd %matplotlib inline sns.set_style(style = 'whitegrid') plt.rcParams["patch.force_edgecolor"] = True
步驟 2
使用可用的資料集建立一個單一的訓練集,如下所示 -
m = 2 # slope c = 3 # interceptm = 2 # slope c = 3 # intercept x = np.random.rand(256) noise = np.random.randn(256) / 4 y = x * m + c + noise df = pd.DataFrame() df['x'] = x df['y'] = y sns.lmplot(x ='x', y ='y', data = df)
步驟 3
使用 PyTorch 庫實現線性迴歸,如下所示 -
import torch
import torch.nn as nn
from torch.autograd import Variable
x_train = x.reshape(-1, 1).astype('float32')
y_train = y.reshape(-1, 1).astype('float32')
class LinearRegressionModel(nn.Module):
def __init__(self, input_dim, output_dim):
super(LinearRegressionModel, self).__init__()
self.linear = nn.Linear(input_dim, output_dim)
def forward(self, x):
out = self.linear(x)
return out
input_dim = x_train.shape[1]
output_dim = y_train.shape[1]
input_dim, output_dim(1, 1)
model = LinearRegressionModel(input_dim, output_dim)
criterion = nn.MSELoss()
[w, b] = model.parameters()
def get_param_values():
return w.data[0][0], b.data[0]
def plot_current_fit(title = ""):
plt.figure(figsize = (12,4))
plt.title(title)
plt.scatter(x, y, s = 8)
w1 = w.data[0][0]
b1 = b.data[0]
x1 = np.array([0., 1.])
y1 = x1 * w1 + b1
plt.plot(x1, y1, 'r', label = 'Current Fit ({:.3f}, {:.3f})'.format(w1, b1))
plt.xlabel('x (input)')
plt.ylabel('y (target)')
plt.legend()
plt.show()
plot_current_fit('Before training')
生成的圖形如下所示 -
廣告