LoginSignup
0
2

More than 5 years have passed since last update.

単回帰分析

Last updated at Posted at 2018-11-26

pythonで単回帰分析したときのメモ

気づき

回帰分析とはある変数から、もう一方の変数を予測するためのもの
似たものに、「相関係数」というものがあるが、2変数の関係の強さを数量で示すものなのでそもそもの目的が違う
単回帰分析とは、一つの目的変数を1つの説明変数で予測する。具体的には、Y=aX+bのa(回帰係数)とb(切片)を求める。
求め方:最小二乗法
最小二乗法とは回帰式との誤差を最小にするという方法

a = (xとyの共分散)/(xの分散)
b = yの平均値 - a(xの平均値)

決定係数:回帰式の説明力を示す指標(1-0の値をとり、1に近いほど説得力がある)

参照URL

単回帰分析とは
https://www.albert2005.co.jp/knowledge/statistics_analysis/multivariate_analysis/single_regression
例題
https://algorithm.joho.info/machine-learning/python-scikit-learn-regression-single/
相関係数と回帰係数
https://www.study-channel.com/2015/07/correlation-regression.html

data.csv
"x1","x2","x3"
45,17.5,30
38,17.0,25
41,18.5,20
34,18.5,30
59,16.0,45
47,19.0,35
35,19.5,25
43,16.0,35
54,18.0,35
52,19.0,40
LinerRegression.py
import pandas as pd
import numpy as np
from sklearn import linear_model
import matplotlib.pyplot as plt

def main():
    # pandasの関数read_csvを使ってcsvを読み込む
    data = pd.read_csv("data.csv", sep=",")
    # scikit-learnにある関数を呼んでくる
    clf = linear_model.LinearRegression()
    # # 説明変数に"x1"のデータを使用
    # loc[] で dataにあるラベルx1の値をとる
    # as_matrix で arrayにキャスト
    X = data.loc[:, ['x1']].as_matrix()
    # # 目的変数に"x2"のデータを使用
    Y = data['x2'].as_matrix()
    # # 単回帰分析をかける
    clf.fit(X, Y)
    # 回帰係数
    a = clf.coef_
    # 切片
    b = clf.intercept_
    # 決定係数
    r = clf.score(X, Y)
    # # 出力
    print("回帰係数:", a)
    print("切片:", b)
    print("決定係数:", r)

    # データのプロット
    plt.plot(X, Y, "o")
    # x軸の設定
    fig_x = np.linspace(30, 60, 30)
    # グラフyの定義
    fig_y = a*fig_x + b
    # 直線の描画
    plt.plot(fig_x, fig_y, "r-")
    # 表示
    plt.show()

if __name__ == "__main__":
    main()
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2