将斜率乘以X列表时键入Error

问题描述 投票:0回答:2

以下是我遇到的问题:

线性回归 - 给定16对价格(作为因变量)和相应的需求(作为自变量),使用线性回归工具估计最佳拟合线性线。

Price Demand
127 3420
134 3400
136 3250
139 3410
140 3190
141 3250
148 2860
149 2830 
151 3160
154 2820
155 2780
157 2900
159 2810
167 2580
168 2520
171 2430

这是我的代码:

from pylab import *
from numpy import *
from scipy.stats import *


x = [3420, 3400, 3250, 3410, 3190, 3250, 2860, 2830, 3160, 2820, 2780, 2900, 2810, 2580, 2520, 2430]
    np.asarray(x,dtype= np.float64)

y = [127, 134, 136 ,139, 140, 141, 148, 149, 151, 154, 155, 157, 159, 167, 168, 171]
np.asarray(y, dtype= np.float64)

slope,intercept,r_value,p_value,slope_std_error = stats.linregress(x,y)

y_modeled = x*slope+intercept

plot(x,y,'ob',markersize=2)
plot(x,y_modeled,'-r',linewidth=1)
show() 

这是我得到的错误:

Traceback (most recent call last):

  File "<ipython-input-48-0a0274c24b19>", line 13, in <module>
    y_modeled = x*slope+intercept

TypeError: can't multiply sequence by non-int of type 'numpy.float64'
python python-2.7 numpy linear-regression
2个回答
1
投票

你没有在这里将Python列表转换为numpy数组:

x = [3420, 3400, 3250, 3410, 3190, 3250, 2860, 2830, 3160, 2820, 2780, 2900, 2810, 2580, 2520, 2430]
np.asarray(x,dtype= np.float64)

np.asarray返回一个numpy数组,但不修改原始数组。你可以这样做:

x = [3420, 3400, 3250, 3410, 3190, 3250, 2860, 2830, 3160, 2820, 2780, 2900, 2810, 2580, 2520, 2430]
x = np.asarray(x, dtype=np.float64)

与Python列表乘法的工作方式相比,numpy数组乘法的工作方式有很大差异。看这里:

>>> 3 * np.array([1, 2, 3])
array([3, 6, 9])

>>> 3 * [1, 2, 3]
[1, 2, 3, 1, 2, 3, 1, 2, 3]

在你的情况下,你试图做后者(列表乘法),但你乘以一个浮点数,它不能工作,这就是错误所说的。


1
投票

首先,[i *斜率+ x中的i截距]是列表理解,您将把列表“x”中的每个数字乘以斜率并将其添加到拦截中。然后,您将列表“x”的新值传递给np.asarray(),以将列表转换为numpy数组。

Y_modeled=np.asarray([i*slope+intercept for i in x], dtype=np.float64)
© www.soinside.com 2019 - 2024. All rights reserved.