首页 > 解决方案 > 如何用线性回归拟合负数据?

问题描述

我想拟合我的数据并提取它们的斜率。我使用线性回归。我的数据是一组包含负值的时钟偏移值。这是我的代码:

from scipy import stats
import scipy
import matplotlib.pyplot as plt
plt.style.use('ggplot')
x= [1549808191, 1549808192, 1549808196, 1549808201, 1549808202, 1549808206, 1549808207, 1549808214, 1549808215, 1549808221, 1549808226, 1549808267, 1549808272, 1549808290, 1549808304, 1549808315, 1549808324, 1549808332, 1549808355, 1549808395, 1549808396]
y= ['7', '0', '0', '0', '-2', '4', '-3', '2', '0', '-1', '0', '-2', '-1', '-1','2', '-2', '1', '0', '0', '-1', '-2']
print(x)
print(y)
plt.plot(x,y,'o-')
plt.show()
slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(x, y)
print(slope)

在此处输入图像描述 但是,它给了我这个错误:

    ret = umr_sum(arr, axis, dtype, out, keepdims)
TypeError: cannot perform reduce with flexible type

那么如何解决这个错误呢?线性回归是用此类数据提取拟合参数的最佳方法吗?

标签: pythonlinear-regression

解决方案


问题似乎来自scipy.stats.linregress(x, y)您执行拟合的位置,因为您的y值是字符串。您可以使用它们将它们转换为整数类型,map并且事情按预期工作

# import commands here 
plt.style.use('ggplot')
x= [1549808191, 1549808192, 1549808196, 1549808201, 1549808202, 1549808206, 1549808207, 1549808214, 1549808215, 1549808221, 1549808226, 1549808267, 1549808272, 1549808290, 1549808304, 1549808315, 1549808324, 1549808332, 1549808355, 1549808395, 1549808396]
y= ['7', '0', '0', '0', '-2', '4', '-3', '2', '0', '-1', '0', '-2', '-1', '-1','2', '-2', '1', '0', '0', '-1', '-2']

plt.plot(x,y,'o-')
plt.show()
slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(x, list(map(int, y)))
print("The slope is %s" %slope)

# The slope is -0.009607415773244879

在此处输入图像描述


推荐阅读