使用 matplotlib/numpy 进行线性回归 [英] Linear regression with matplotlib / numpy

查看:51
本文介绍了使用 matplotlib/numpy 进行线性回归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to generate a linear regression on a scatter plot I have generated, however my data is in list format, and all of the examples I can find of using polyfit require using arange. arange doesn't accept lists though. I have searched high and low about how to convert a list to an array and nothing seems clear. Am I missing something?

接下来,如何最好地使用我的整数列表作为 polyfit 的输入?

Following on, how best can I use my list of integers as inputs to the polyfit?

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

here is the polyfit example I am following:

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() 

推荐答案

arange 生成 列表(好吧,numpy 数组);输入 help(np.arange) 获取详细信息.您无需在现有列表中调用它.

arange generates lists (well, numpy arrays); type help(np.arange) for the details. You don't need to call it on existing lists.

>>> 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";和更高阶的等价物,所以我的代码版本看起来像这样:

I should add that I tend to use poly1d here rather than write out "m*x+b" and the higher-order equivalents, so my version of your code would look something like this:

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)

这篇关于使用 matplotlib/numpy 进行线性回归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆