当前位置: 首页 > 网络知识

Python 线性回归(y=ax+b)

时间:2026-01-29 09:26:39

线性回归主要是拟合一个函数,能预测一个新的样本:

(1)数据集如下:

(2)预测值:feet=500

1 # * coding:utf8 * 2 import matplotlib.pyplot as plt 3 import pandas as pd 4 fr sklearn import linear_model 5 import os 6 oshdir("/Users/xxx/PycharmProjects/dataset/") 7 filename = "input_data.xlsx" 8 datafile = pd.read_excel(filename, index_col=u'ID') 9 # 获取数据 10 def get_data(datafile): 11 x_paramter = [] 12 y_paramter = [] 13 for feet,price in zip(datafile['feet'],datafile['price']): 14 x_paramter.append([float(feet)]) 15 y_paramter.append(float(price)) 16 return x_paramter,y_paramter 17 # 线性回归模型 18 def linear_model_main(x_paramter,y_paramter,predict_value): 19 # 创建线性回归对象 20 regr = linear_model.LinearRegression() 21 regr.fit(x_paramter,y_paramter) # 建立模型 22 predict_outce = regr.predict(predict_value) # 预测值 23 return regr.intercept_,regroef_,predict_outce # 返回截距、斜率、预测结果 24 # 显示线性拟合模型的结果 25 def show_linear_line(x_paramter,y_paramter): 26 regr = linear_model.LinearRegression() 27 regr.fit(x_paramter,y_paramter) 28 plt.scatter(x_paramter,y_paramter,color="blue") 29 x_new = [[0],[500]] # x轴长 30 plt.plot(x_new,regr.predict(x_new),color="red",linewidth=2) 31 plt.xlabel(u'Feet',color="green") 32 plt.ylabel(u'Price',color="green") 33 # plt.plot(label=u'数据图') 34 # plt.xticks(()) 35 # plt.yticks(()) 36 plt.ylim(2000,20000) 37 plt.xlim(0,500) 38 plt.show() 39 def main(): 40 X,Y = get_data(datafile) 41 print('X:',X) 42 print('Y:',Y) 43 predictvalue = [[500]] 44 intercept,coefficient,predict_value = linear_model_main(X,Y,predictvalue) 45 print("截距:",intercept) # b ( y=ax+b ) 46 print("斜率:",coefficient) # a 47 print("预测值:",predict_value) # y 48 show_linear_line(X,Y) 49 main()

(3)输出:

(4)样本以及拟合的直线



上一篇:Qt 常见数据结构详解:从基本框架到实际应用
下一篇:Qt QList的用法
python
  • 英特尔与 Vertiv 合作开发液冷 AI 处理器
  • 英特尔第五代 Xeon CPU 来了:详细信息和行业反应
  • 由于云计算放缓引发扩张担忧,甲骨文股价暴跌
  • Web开发状况报告详细介绍可组合架构的优点
  • 如何使用 PowerShell 的 Get-Date Cmdlet 创建时间戳
  • 美光在数据中心需求增长后给出了强有力的预测
  • 2027服务器市场价值将接近1960亿美元
  • 生成式人工智能的下一步是什么?
  • 分享在外部存储上安装Ubuntu的5种方法技巧
  • 全球数据中心发展的关键考虑因素
  • 英特尔与 Vertiv 合作开发液冷 AI 处理器

    英特尔第五代 Xeon CPU 来了:详细信息和行业反应

    由于云计算放缓引发扩张担忧,甲骨文股价暴跌

    Web开发状况报告详细介绍可组合架构的优点

    如何使用 PowerShell 的 Get-Date Cmdlet 创建时间戳

    美光在数据中心需求增长后给出了强有力的预测

    2027服务器市场价值将接近1960亿美元

    生成式人工智能的下一步是什么?

    分享在外部存储上安装Ubuntu的5种方法技巧

    全球数据中心发展的关键考虑因素