首页 > 编程语言 >Python 线性回归(y=ax+b)

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

时间:2024-02-28 13:59:38浏览次数:30  
标签:datafile plt linear Python regr predict paramter 线性 ax

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

(1)数据集如下:

 (2)预测值:feet=500

 1 # -*- coding:utf-8 -*-
 2 import matplotlib.pyplot as plt
 3 import pandas as pd
 4 from sklearn import linear_model
 5 import os
 6 os.chdir("/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_outcome = regr.predict(predict_value) # 预测值
23     return regr.intercept_,regr.coef_,predict_outcome # 返回截距、斜率、预测结果
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)样本以及拟合的直线

标签:datafile,plt,linear,Python,regr,predict,paramter,线性,ax
From: https://www.cnblogs.com/ybqjymy/p/18040120

相关文章

  • C++ 点的线性拟合 y(x)=ax+b
    一、简单分析点的线性拟合是一般实验数据处理最常用的方法。下面考虑一个用n个数据点拟合成直线的问题,直线模型为y(x)=ax+b这个问题称为线性回归。设变量y随自变量x变化,给定n组观测数据(xi,yi),用直线来拟合这些点,其中a,b是直线的斜率和截距,称为回归系数。为确定......
  • 使用矩池云 Docker 虚拟机安装VNC、Conda、Python及CUDA
    矩池云虚拟机支持Docker使用,但是由于虚拟机目前不支持启动时传递环境变量来设置VNC、Jupyterlab连接密码,所以我们没有创建相关基础镜像(设置固定密码容易泄漏),下面给大家介绍手动安装使用VNC、Jupyterlab、CUDA等步骤,以便支持使用OpenGL等功能的使用,开启更完善和强大的功能体......
  • python基础-函数
    一、参数示例deffun(a,b=0,*args,**kwargs):"""指定收集参数的固定形式,*+指定的位置参数名,惯例*args,自定义*position都行,**+指定的关键字参数名,惯例**kwargs,需要注意的是,在函数体内调用时不要混淆*的含义,*+数据序列,指展开序列,取其中的值,而想使用传入的......
  • Python面向对象,类属性,实例属性,类方法,实例方法,静态方法的区别及用法详解
    一.前言在Python的面向对象编程中,类属性和实例属性是两个不同的概念,它们在作用域和使用方式上有所区别。在Python中的面向对象编程中有三种方法:实例方法、类方法和静态方法,它们之间的差异主要体现在参数传递和调用方式上。二.面向对象-类属性和实例属性1.区别在Pyth......
  • Python: Star unpacking expressions in for statements
    今天发现在Python3.11版本中一个很不错的新特性,可以在for循环中使用unpacking,这意味着可以更灵活地组合迭代对象。ls=[1,2,34]foriin1,2,3,*ls,789:print(i)"""1231234789"""其实我第一次知道for循环中可以使用x,y,z这样的结构,想想也是......
  • Python语言Numpy包之Meshgrid 函数
    Meshgrid函数的基本用法在Numpy的官方文章里,meshgrid函数的英文描述也显得文绉绉的,理解起来有些难度。可以这么理解,meshgrid函数用两个坐标轴上的点在平面上画网格。用法:[X,Y]=meshgrid(x,y)[X,Y]=meshgrid(x)与[X,Y]=meshgrid(x,x)是等同的[X,Y,Z]......
  • Python scipy.ndimage.find_objects用法及代码示例
    用法scipy.ndimage.find_objects(input,max_label=0)在标记数组中查找对象。参数:input:整数数组包含由不同标签定义的对象的数组。值为0的标签将被忽略。max_label:整数,可选要在输入中搜索的最大标签。如果没有给出max_label,则返回所有对象的位置。object_slices:元组......
  • 基于Python GDAL为长时间序列遥感图像绘制时相变化曲线图
      本文介绍基于Python中gdal模块,对大量多时相栅格图像,批量绘制像元时间序列折线图的方法。  首先,明确一下本文需要实现的需求:现有三个文件夹,其中第一个文件夹存放了某一研究区域原始的多时相栅格遥感影像数据(每一景遥感影像对应一个时相,文件夹中有多景遥感影像),每一景遥感影像......
  • python-获取当前目录路径的几个方法
     1、fromos.pathimportabspath,dirnameprint(abspath(__file__))__file__ 是一个特殊的变量,它表示当前脚本的文件名(带有路径)。abspath() 是一个函数,它返回指定文件或目录的绝对路径。因此,这行代码将打印出当前脚本的绝对路径。print(dirname(abspath(__file__)......
  • Python函数每日一讲 - 一文让你彻底明白hasattr函数的使用
    引言在Python编程中,经常会遇到需要判断对象是否具有某个属性的情况。这时候就可以用到Python内置函数hasattr()。本文将深入探讨hasattr()函数的使用方法及其在实际编程中的应用。语句概览hasattr()函数用于检查对象是否具有指定的属性,返回一个布尔值。其语法如下:hasattr(......