python学习—简单线性回归模型

初学线性回归,个人表示比较蒙,做下笔记,供自己回看

1.加载需要的模块

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
plt.rcParams["font.sans-serif"] = "Simhei"

2.读取显示数据

data = pd.read_excel("data/LinearRegression.xlsx")
data
>>>>>
	ID	visitors	sales
0	1   	3  	    10
1	2	    5	    31
2	3	    8	    45
3	4		8		50
4	5		14		75
5	6		15		85
6	7		16		109
7	8		18		117
8	9		22		138
9	10		24		145

3.画出data数据散点图

plt.scatter(x=data.visitors,y=data.sales,c="r",marker="o",edgecolors="b")
plt.xlabel("访客量")
plt.ylabel("销售额")
plt.title("访客量和销售额散点图")

在这里插入图片描述
4.简单线性回归模型

#特征,访客数量
x = data.visitors.values.reshape(-1,1)
#目标,销售额
y = data.sales.values.reshape(-1,1)
#模型
model = LinearRegression().fit(x,y)
#斜率,轴距
print("斜率:{:.2f},轴距为{:.2f}".format(model.coef_[0,0],model.intercept_[0]))
print("类似于一次函数y={:.2f}x{:.2f}".format(model.coef_[0,0],model.intercept_[0]))

>>>>>>>>>>>>>>>>>>>>>>>>>
>print的输出结果
斜率:6.45,轴距为-5.30
类似于一次函数y=6.45x-5.30
>>>>>>>>>>>>>>>>>>>>>>>>>

5.画出模型的拟合线

x1 = x
y1 = model.predict(x)
plt.scatter(x=data.visitors,y=data.sales,c="r",marker="o",edgecolors="b")
plt.plot(x1,y1,linewidth=3)
plt.xlabel("访客量")
plt.ylabel("销售额")
plt.title("模型拟合线")
plt.savefig("out/2.png",dpi=100)

在这里插入图片描述
6.预测

#预测客流量为100时候的销售额
Sales = model.predict([[100]])
print("预测客流量为100时候销售额为:{:.2f}".format(Sales[0,0]))

>>>>>>>>>>>>>>
>print的输出结果
预测客流量为100时候销售额为:639.82
>>>>>>>>>>>>>>

7.拟合优度

model.score(x,y)

>>>>>>>
0.9806125530325467
>>>>>>>
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,关于Python构建简单线性回归模型,可以按照以下步骤进行: 1. 导入所需的库 在使用Python构建简单线性回归模型时,我们需要导入一些常用的库,如numpy和pandas用于数据处理,matplotlib用于数据可视化,以及sklearn用于模型构建和评估。 ```python import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error, r2_score ``` 2. 导入数据 在构建线性回归模型之前,我们需要先导入数据。这里我们可以使用pandas库中的read_csv函数读取CSV格式的数据文件。 ```python data = pd.read_csv('data.csv') ``` 3. 数据预处理 在导入数据之后,我们需要进行数据预处理,以便于后续模型的构建和评估。这里我们可以使用numpy库中的reshape函数将数据转换为二维数组,并使用pandas库中的dropna函数删除缺失值。 ```python x = np.array(data['x']).reshape(-1, 1) y = np.array(data['y']).reshape(-1, 1) x = x[~np.isnan(y)] y = y[~np.isnan(y)] ``` 4. 数据可视化 在进行数据预处理之后,我们可以使用matplotlib库中的scatter函数将数据可视化。 ```python plt.scatter(x, y) plt.xlabel('x') plt.ylabel('y') plt.show() ``` 5. 模型构建 在数据可视化之后,我们可以使用sklearn库中的LinearRegression类构建线性回归模型,并使用fit函数拟合数据。 ```python model = LinearRegression() model.fit(x, y) ``` 6. 模型评估 在模型构建之后,我们可以使用sklearn库中的mean_squared_error和r2_score函数对模型进行评估。 ```python y_pred = model.predict(x) mse = mean_squared_error(y, y_pred) r2 = r2_score(y, y_pred) print('Mean Squared Error:', mse) print('R2 Score:', r2) ``` 完整代码如下: ```python import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error, r2_score # 导入数据 data = pd.read_csv('data.csv') # 数据预处理 x = np.array(data['x']).reshape(-1, 1) y = np.array(data['y']).reshape(-1, 1) x = x[~np.isnan(y)] y = y[~np.isnan(y)] # 数据可视化 plt.scatter(x, y) plt.xlabel('x') plt.ylabel('y') plt.show() # 模型构建 model = LinearRegression() model.fit(x, y) # 模型评估 y_pred = model.predict(x) mse = mean_squared_error(y, y_pred) r2 = r2_score(y, y_pred) print('Mean Squared Error:', mse) print('R2 Score:', r2) ``` 希望这个简单的教程能够帮助你构建线性回归模型
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值