简单线性回归、多元线性回归及相关绘图

import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import seaborn as sns

plt.rcParams['font.sans-serif'] = ['KaiTi', 'SimHei', 'FangSong']  # 汉字字体,优先使用楷体,如果找不到楷体,则使用黑体
plt.rcParams['font.size'] = 12  # 字体大小
plt.rcParams['axes.unicode_minus'] = False  # 正常显示负号

df = pd.read_csv("...//data2.csv")

# 简单线性回归
reg = LinearRegression()
reg.fit(df[["xxx"]],df[["yyy"]])
reg.coef_


# 两个变量关系的散点图
plt.title("xxx vs yyy")
plt.xlabel("xxx")
plt.ylabel("yyy")
plt.scatter(df["xxx"],df["yyy"])
plt.savefig("xxx vs yyy.png", dpi = 40)

# 切片
y = df.iloc[:, 4]
y=y*10

x = df.iloc[:,0:4]



pair_fig = sns.pairplot(df, x_vars=["xx1","xx2", "xx3"], y_vars="yyy", kind="reg", height=5, aspect=0.7)
pair_fig.savefig("yyy vs xxxs",dpi=600)

# 随机分训练集和测试集
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)


clf = LinearRegression()
# clf = LinearRegression(fit_intercept=False) 这样将设置为无截距
# 拟合模型
clf.fit(x_train, y_train)
# 利用测试集中的x预测y
clf.predict(x_test)
# 评估模型r^2 得分
clf.score(x_test, y_test)
# 多元线性回归 计算得到的系数
clf.coef_

posted on   Glovesize  阅读(884)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示