应用多元统计分析第四章基于最小二乘估计线性回归分析python代码

题目如下:

应用多元统计分析第四章基于最小二乘估计线性回归分析python代码_第1张图片

最小二乘法估计参数,代码如下:

import pandas as pd
import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from sklearn import linear_model

def stdError_func(y_test, y):
  return np.sqrt(np.mean((y_test - y) ** 2))


def R2_1_func(y_test, y):
  return 1 - ((y_test - y) ** 2).sum() / ((y.mean() - y) ** 2).sum()


def R2_2_func(y_test, y):
  y_mean = np.array(y)
  y_mean[:] = y.mean()
  return 1 - stdError_func(y_test, y) / stdError_func(y_mean, y)




filename = "C:\\Users\\西门吹牛\\Desktop\\水泥数据.xlsx"
df= pd.read_excel(filename,usecols=[0,1,2,3])
x = df.values
df1=pd.read_excel(filename,usecols=[4])
y = df1.values
cft = linear_model.LinearRegression()
print(x.shape)
cft.fit(x, y) #

print("model coefficients", cft.coef_)
print("model intercept", cft.intercept_)


predict_y =  cft.predict(x)
strError = stdError_func(predict_y, y)
R2_1 = R2_1_func(predict_y, y)
R2_2 = R2_2_func(predict_y, y)
score = cft.score(x, y) ##sklearn中自带的模型评估,与R2_1逻辑相同

print('strError={:.2f}, R2_1={:.2f},  R2_2={:.2f}, clf.score={:.2f}'.format( strError,R2_1,R2_2,score))

 运行结果如图:

应用多元统计分析第四章基于最小二乘估计线性回归分析python代码_第2张图片

 

你可能感兴趣的:(笔记,应用多元统计分析,线性回归,python,回归)