脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python实现线性回归算法

python实现线性回归算法

2021-10-15 10:56Jepson2017 Python

这篇文章主要为大家详细介绍了python实现线性回归算法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文用python实现线性回归算法,供大家参考,具体内容如下

?
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
32
33
34
35
36
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 11 19:25:11 2019
"""
 
from sklearn import datasets, linear_model # 引用 sklearn库,主要为了使用其中的线性回归模块
 
# 创建数据集,把数据写入到numpy数组
import numpy as np  # 引用numpy库,主要用来做科学计算
import matplotlib.pyplot as plt   # 引用matplotlib库,主要用来画图
data = np.array([[152,51],[156,53],[160,54],[164,55],
                 [168,57],[172,60],[176,62],[180,65],
                 [184,69],[188,72]])
 
# 打印出数组的大小
print(data.shape)
 
# TODO 1. 实例化一个线性回归的模型
model=linear_model.LinearRegression()
# TODO 2. 在x,y上训练一个线性回归模型。 如果训练顺利,则regr会存储训练完成之后的结果模型
x,y=data[:,0].reshape(-1,1),data[:,1]
regr=model.fit(x,y)
 
# TODO 3. 画出身高与体重之间的关系
plt.scatter(x,y,color="red")
 
# 画出已训练好的线条
plt.plot(x, regr.predict(x), color='blue')
 
# 画x,y轴的标题
plt.xlabel('height (cm)')
plt.ylabel('weight (kg)')
plt.show() # 展示
 
# 利用已经训练好的模型去预测身高为163的人的体重
print ("Standard weight for person with 163 is %.2f"% regr.predict([[163]]))

python实现线性回归算法

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/d1240673769/article/details/103483765

延伸 · 阅读

精彩推荐