【问题标题】:Linear regression with matplotlib / numpy使用 matplotlib / numpy 进行线性回归
【发布时间】:2011-05-27 05:32:22
【问题描述】:

我正在尝试在我生成的散点图上生成线性回归,但是我的数据是列表格式,并且我可以找到的所有使用 polyfit 的示例都需要使用 arangearange 虽然不接受列表。我已经搜索了有关如何将列表转换为数组的高低搜索,但似乎没有什么清楚的。我错过了什么吗?

接下来,我怎样才能最好地使用我的整数列表作为polyfit 的输入?

这是我正在关注的 polyfit 示例:

from pylab import * 

x = arange(data) 
y = arange(data) 

m,b = polyfit(x, y, 1) 

plot(x, y, 'yo', x, m*x+b, '--k') 
show() 

【问题讨论】:

标签: python numpy matplotlib linear-regression curve-fitting


【解决方案1】:

arange 生成列表(嗯,numpy数组);输入help(np.arange) 了解详情。您无需在现有列表中调用它。

>>> x = [1,2,3,4]
>>> y = [3,5,7,9] 
>>> 
>>> m,b = np.polyfit(x, y, 1)
>>> m
2.0000000000000009
>>> b
0.99999999999999833

我应该补充一点,我倾向于在这里使用poly1d,而不是写出“m*x+b”和更高阶的等价物,所以我的代码版本看起来像这样:

import numpy as np
import matplotlib.pyplot as plt

x = [1,2,3,4]
y = [3,5,7,10] # 10, not 9, so the fit isn't perfect

coef = np.polyfit(x,y,1)
poly1d_fn = np.poly1d(coef) 
# poly1d_fn is now a function which takes in x and returns an estimate for y

plt.plot(x,y, 'yo', x, poly1d_fn(x), '--k') #'--k'=black dashed line, 'yo' = yellow circle marker

plt.xlim(0, 5)
plt.ylim(0, 12)

【讨论】:

    【解决方案2】:

    George's answer 与 matplotlib 的 axline 完美结合,绘制了一条无限线。

    from scipy.stats import linregress
    import matplotlib.pyplot as plt
    
    reg = linregress(x, y)
    plt.axline(xy1=(0, reg.intercept), slope=reg.slope, linestyle="--", color="k")
    

    【讨论】:

      【解决方案3】:

      这段代码:

      from scipy.stats import linregress
      
      linregress(x,y) #x and y are arrays or lists.
      

      列出以下内容:

      坡度:浮动
      回归线的斜率
      拦截:浮动
      回归线的截距
      右值:浮动
      相关系数
      p 值:浮动
      假设检验的双边 p 值,其原假设是斜率为零
      标准错误:浮动
      估计的标准误

      Source

      【讨论】:

        【解决方案4】:
        import numpy as np
        import matplotlib.pyplot as plt 
        from scipy import stats
        
        x = np.array([1.5,2,2.5,3,3.5,4,4.5,5,5.5,6])
        y = np.array([10.35,12.3,13,14.0,16,17,18.2,20,20.7,22.5])
        gradient, intercept, r_value, p_value, std_err = stats.linregress(x,y)
        mn=np.min(x)
        mx=np.max(x)
        x1=np.linspace(mn,mx,500)
        y1=gradient*x1+intercept
        plt.plot(x,y,'ob')
        plt.plot(x1,y1,'-r')
        plt.show()
        

        使用这个..

        【讨论】:

        • 这并没有增加解决问题的新方法 - 已经建议in this popular answer
        • 你想把生成的列表转换成数组吗?
        • 我不想要任何具体的东西,这不是我的问题。我只是说重复一个已经确定的答案并不是真正的 SO 正在寻找的东西。请阅读我发布的链接。
        • @AleenaRehman 我尝试将 pd DataFrame 列转换为 np.array。元素之间没有逗号,并且 np.polyfit 显示错误。
        【解决方案5】:

        另一个快速而肮脏的答案是,您可以使用以下方法将列表转换为数组:

        import numpy as np
        arr = np.asarray(listname)
        

        【讨论】:

          【解决方案6】:

          线性回归是开始人工智能的一个很好的例子

          这是一个使用 Python 进行多元线性回归的机器学习算法的好例子:

          ##### Predicting House Prices Using Multiple Linear Regression - @Y_T_Akademi
              
          #### In this project we are gonna see how machine learning algorithms help us predict house prices. Linear Regression is a model of predicting new future data by using the existing correlation between the old data. Here, machine learning helps us identify this relationship between feature data and output, so we can predict future values.
          
          import pandas as pd
          
          ##### we use sklearn library in many machine learning calculations..
          
          from sklearn import linear_model
          
          ##### we import out dataset: housepricesdataset.csv
          
          df = pd.read_csv("housepricesdataset.csv",sep = ";")
          
          ##### The following is our feature set:
          ##### The following is the output(result) data:
          ##### we define a linear regression model here: 
          
          reg = linear_model.LinearRegression()
          reg.fit(df[['area', 'roomcount', 'buildingage']], df['price'])
          
          # Since our model is ready, we can make predictions now:
          # lets predict a house with 230 square meters, 4 rooms and 10 years old building..
          
          reg.predict([[230,4,10]])
          
          # Now lets predict a house with 230 square meters, 6 rooms and 0 years old building - its new building..
          reg.predict([[230,6,0]])
          
          # Now lets predict a house with 355 square meters, 3 rooms and 20 years old building 
          reg.predict([[355,3,20]])
          
          # You can make as many prediction as you want.. 
          reg.predict([[230,4,10], [230,6,0], [355,3,20], [275, 5, 17]])
          

          我的数据集如下:

          【讨论】:

            【解决方案7】:
            from pylab import * 
            
            import numpy as np
            x1 = arange(data) #for example this is a list
            y1 = arange(data) #for example this is a list 
            x=np.array(x) #this will convert a list in to an array
            y=np.array(y)
            m,b = polyfit(x, y, 1) 
            
            plot(x, y, 'yo', x, m*x+b, '--k') 
            show()
            

            【讨论】:

            • 我明白了,你写了一些cmets,但你应该考虑添加几句解释,这会增加你的答案的价值;-)
            • 请注意,虽然代码 sn-p 可以 本身是一个有用的答案,但最好为未来的读者留下一些评论,说明为什么这可以解决问题。谢谢!
            • @blue-phoenox 好吧,我认为这里的人是天才,但我想我下次会解释..
            猜你喜欢
            • 2018-02-03
            • 1970-01-01
            • 2016-04-19
            • 2016-07-21
            • 2018-07-31
            • 2023-03-05
            • 2022-08-14
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多