Pytorch-linear-regression

提供:Dev Guides
移動先:案内検索

PyTorch-線形回帰

この章では、TensorFlowを使用した線形回帰の実装の基本的な例に焦点を当てます。 ロジスティック回帰または線形回帰は、順序離散カテゴリの分類のための教師あり機械学習アプローチです。 この章の目標は、ユーザーが予測変数と1つ以上の独立変数との関係を予測できるモデルを構築することです。

これらの2つの変数間の関係は線形と見なされます。つまり、yが従属変数であり、xが独立変数と見なされる場合、2つの変数の線形回帰関係は以下の式のようになります-

Y = Ax+b

次に、以下に示す2つの重要な概念を理解できる線形回帰のアルゴリズムを設計します。

  • コスト関数
  • 勾配降下アルゴリズム

線形回帰の概略図を以下に示します

結果の解釈

Y = ax + b

  • a の値は勾配です。
  • b の値は* y-インターセプト*です。
  • r は*相関係数*です。
  • _r ^ 2 ^ _ は*相関係数*です。

線形回帰の方程式のグラフィカルなビューは以下に記載されています-

結果の解釈

次の手順は、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')

生成されたプロットは次のとおりです-

プロット生成