线性回归判断能否与预测实现python

#判断适合不适合做回归分析==========================================================================
# 导入库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sklearn
from sklearn.linear_model import LinearRegression

# 读取数据
data = pd.read_excel('data1.xlsx')
X = data.iloc[:, :-1].values # 特征, 取所有行,但是不要最后一列,就是只取第一列
y = data.iloc[:, -1].values # 响应变量,取最后一列

# 绘制散点图
plt.scatter(X[:,0], y)
plt.xlabel('X1')
plt.ylabel('y')
plt.show()

# 计算相关系数
corr = np.corrcoef(X[:,0], y)[0, 1]
print('相关系数为:', corr)

# 拟合模型
model = LinearRegression()
model.fit(X, y)

# 输出R方值
R2 = model.score(X, y)
print('R方值为:', R2)

#预测=======================================================================================
#导入库
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
# 读取数据
data = pd.read_excel('data1.xlsx')
X = data.iloc[:, :-1].values # 特征
y = data.iloc[:, -1].values # 响应变量
# 拟合模型
model = LinearRegression()
model.fit(X, y)
# 预测未来值
future_data = np.array([[63]])
future_pred = model.predict(future_data)
# 计算置信度和置信区间
y_pred = model.predict(X)
mse = mean_squared_error(y, y_pred)
rmse = np.sqrt(mse)
n = len(y)
k = len(X[0])
alpha = 0.05 # 置信度水平
t_value = 2.064 # 自由度为n-k-1,置信度为95%时的t值
s = np.sqrt(mse / (n - k - 1))
se = s * np.sqrt(np.dot(np.dot(future_data, np.linalg.inv(np.dot(X.T, X))), future_data.T) + 1)
confidence_interval = t_value * se
lower_bound = future_pred - confidence_interval
upper_bound = future_pred + confidence_interval
# 输出结果
print('未来值预测为:', future_pred)
print('置信区间为:', lower_bound, '-', upper_bound)
print('置信度为95%的误差范围为:', rmse * t_value)

你可能感兴趣的:(算法,线性回归,python,机器学习)