类型错误:绘制线性回归

时间:2015-02-25 16:57:02

标签: python numpy

Python新手,尝试绘制两个列表的线性回归。这就是我到目前为止所做的:

#!/usr/bin/python

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from numpy import arange,array,ones#,random,linalg
from pylab import plot,show
from scipy import stats
from sys import argv

a = argv[1]
b = argv[2]

list1 = open(a)
list2 = open(b)

xi = list1.read().splitlines()
y = list2.read().splitlines()

slope, intercept, r_value, p_value, std_err = stats.linregress(xi,y)

print 'r value', r_value

line = slope*xi+intercept
plot(xi,line,'r-',xi,y,'o')
plt.savefig('myfig')

我收到以下错误:

Traceback (most recent call last):
  File "plot.py", line 21, in <module>
    slope, intercept, r_value, p_value, std_err = stats.linregress(xi,y)
  File "/export/apps/Python/2.7.2-CentOS6.0/lib/python2.7/site-packages/scipy/stats/stats.py", line 3007, in linregress                                                                                         
    xmean = np.mean(x,None)                                                                             
  File "/export/apps/Python/2.7.2-CentOS6.0/lib/python2.7/site-packages/numpy/core/fromnumeric.py", line 2727, in mean                                                                                          
    out=out, keepdims=keepdims)                                                                         
  File "/export/apps/Python/2.7.2-CentOS6.0/lib/python2.7/site-packages/numpy/core/_methods.py", line 66, in _mean                                                                                              
    ret = umr_sum(arr, axis, dtype, out, keepdims)                                                      
TypeError: cannot perform reduce with flexible type 

1 个答案:

答案 0 :(得分:1)

我的猜测是,将字符串列表传递给linregress并不是犹太教。首先尝试将它们转换为浮点数:

xi = [float(xk) for xk in xi]
y = [float(yk) for yk in y]
slope, intercept, r_value, p_value, std_err = stats.linregress(xi,y)

根据xiy中的内容,您可能必须首先删除一些空字符串,否则请清理输入。