#pic_center =400x
系列文章:
文章目录
- 一元回归
- 核心代码
- 数据读取
- 无表头,列名 .csv格式
- 多元回归
一元回归 核心代码
# 一元线性回归
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
x = np.array([100, 110, 120, 130, 140, 150, 160, 170, 180, 190])
y = np.array([45, 51, 54, 61, 66, 70, 74, 78, 85, 89])
a, b = 0,0;
def fitted_line(x):
return a*x+b
def linear_regression(x, y, cl=0.9):
"""
linear regression函数y = ax + b
cl为置信水平
alpha为显著性水平
"""
data = pd.DataFrame({'x': x, 'y': y}).sort_values(by='x')
x = np.asarray(data['x'])
y = np.asarray(data['y'])
alpha = 1 - cl
print('置信水平: {}% C.L.n'.format(100 * cl))
print('显著性水平alpha: {}n'.format(alpha))
a, b = np.polyfit(x, y, deg=1)
print('斜率: {}n'.format(a))
print('截距: {}n'.format(b))
Sxx = np.sum((x - np.mean(x)) ** 2)
Syy = np.sum((y - np.mean(y)) ** 2)
Sxy = np.sum((x - np.mean(x)) * (y - np.mean(y)))
dof = len(x) - 2
print('自由度: {}n'.format(dof))
sigma = np.sqrt((Syy - a * Sxy) / dof)
print('sigma的无偏估计: {}n'.format(sigma))
R_sq = a * Sxy / Syy
print('拟合优度R² : {}n'.format(R_sq))
t_value = stats.t.isf(alpha / 2, dof)
print('t值: {}n'.format(t_value))
if np.abs(a) / sigma * np.sqrt(Sxx) >= t_value:
print('t检验: 线性回归效果显著n')
else:
print('t检验: 线性回归效果不显著n')
print('斜率的置信区间: {}% C.L.n[{}, {}]n'.format(
100 * cl,
a - t_value * sigma / np.sqrt(Sxx),
a + t_value * sigma / np.sqrt(Sxx)))
print('截距的置信区间: {}% C.L.n[{}, {}]n'.format(
100 * cl,
b - t_value * sigma * np.sqrt(1. / len(x) + np.mean(x) ** 2 / Sxx),
b + t_value * sigma * np.sqrt(1. / len(x) + np.mean(x) ** 2 / Sxx)))
print('回归函数的函数值的点估计和置信区间: {}% C.L.n下区间端点: {}n上区间端点: {}n'.format(100 * cl,
fitted_line(x) - t_value * sigma * np.sqrt(
1. / len(x) + (x - np.mean(x)) ** 2 / Sxx),
fitted_line(x) + t_value * sigma * np.sqrt(
1. / len(x) + (x - np.mean(x)) ** 2 / Sxx)))
print('观测值的点预测和预测区间: {}% C.L.n下区间端点: {}n上区间端点: {}n'.format(100 * cl,
fitted_line(x) - t_value * sigma * np.sqrt(
1. + 1. / len(x) + (x - np.mean(x)) ** 2 / Sxx),
fitted_line(x) + t_value * sigma * np.sqrt(
1. + 1. / len(x) + (x - np.mean(x)) ** 2 / Sxx)))
fig = plt.figure()
ax = fig.add_subplot()
ax.scatter(x, y, s=1, c='k', )
ax.plot(x, fitted_line(x), lw=1, label='Linear regression')
ax.fill_between(x,
fitted_line(x) - t_value * sigma * np.sqrt(1. / len(x) + (x - np.mean(x)) ** 2 / Sxx),
fitted_line(x) + t_value * sigma * np.sqrt(1. / len(x) + (x - np.mean(x)) ** 2 / Sxx),
alpha=0.3,
label=r'Confidence limit'.format(100 * cl))
ax.set_xlabel('$x$')
ax.set_ylabel('$y$')
ax.legend()
fig.savefig('Linear regression.png', dpi=300)
linear_regression(x,y)
Python实现一元线性回归
数据读取 无表头,列名 .csv格式value_array = np.genfromtxt("./datasets/test.csv", delimiter=',')
print(value_array)
x = value_array[0]
y = value_array[1]
print(x)
print(type(x))
print(y)
.csv文件数据直接读取为numpy array
Python读取csv文件,并加载其中的几行几列
python去读csv文件,以及numpy的ndarray与pandas的series和dataframe之间互转
多元回归statsmodel官方
python statsmodel 回归结果提取(R方 T值 P-value)



