1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

pythonで単回帰分析の回帰係数を算出

Last updated at Posted at 2020-02-07

単回帰分析の回帰係数の算出

単回帰分析の回帰係数の算出のコードを作ったので, 宜しければ, 使ってください!

ライブラリのインポート

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

データセットの例(test.csv)

Column 1 Column 2
2.2 71
4.1 81
5.5 86
1.9 72
3.4 77
2.6 73
4.2 80
3.7 81
4.9 85
3.2 74

データの読み込み


dataset = pd.read_csv('test.csv')

列の取り出し

Xを説明変数, yを目的変数として, 列をそれぞれ取り出します。


X = dataset.iloc[:, :-1].values #Indepand variable
y = dataset.iloc[:, 1].values #Depand variable

平均の計算


# Calculate Mean
Sum_X = sum(X)
N_X = len(X)
Mean_X = Sum_X / N_X

Sum_y = sum(y)
N_y = len(y)
Mean_y = Sum_y / N_y

偏差の計算


# Calcuate Deviation
Devi_X = []

for Row_X in X:
    Devi_X.append(Row_X - Mean_X)

Devi_y = []

for Row_y in y:
    Devi_y.append(Row_y - Mean_y)

Xとyの偏差をかける

# Multiply Deviation X and y

counter = 0
MD_Xy = []
while counter < len(Devi_X):
    MD_Xy_Value = Devi_X[counter] * Devi_y[counter]
    MD_Xy.append(MD_Xy_Value)
    counter += 1

Xとyの偏差をかけたものを合計する


# Sum of Multiply Deviation X and y
SMD_Xy = sum(MD_Xy)

偏差の平方

# Squares of Calcuate Deviation
Sq_Devi_X = []

for DX in Devi_X:
    Sq_Devi_X.append(DX * DX)

Sq_Devi_y = []

for Dy in Devi_y:
    Sq_Devi_y.append(Dy * Dy)

偏差の平方和


# Sum of Squares of Calcuate Deviation
SSX = sum(Sq_Devi_X)

SSy = sum(Sq_Devi_y)

回帰係数の計算


# Calculate Regression paramator
betaOne = SMD_Xy / SSX
betaZero = Mean_y - betaOne * Mean_X
1
4
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
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?