python - 如何用线性回归拟合负数据?
问题描述
我想拟合我的数据并提取它们的斜率。我使用线性回归。我的数据是一组包含负值的时钟偏移值。这是我的代码:
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
那么如何解决这个错误呢?线性回归是用此类数据提取拟合参数的最佳方法吗?
解决方案
问题似乎来自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
推荐阅读
- c++ - C ++ / Boost :: Propery_Tree - 是否可以使用名称中的点来获取ini配置值
- angular - 离子生成页面:找不到 NgModule
- android - 将图标添加到 TabItems
- c++ - 如何设置 Visual Studio 2017 以正确识别 Optix 项目中的 Cuda 代码
- python - opencv(cv2)在我的代码中检测运动的问题
- assembly - 为什么 .COM 程序中只有一个段,用于程序代码和堆栈?
- java - 使用expandAroundCenter函数的最长回文子串(LeetCode)解决方案,不是O(n ^ 3)吗?
- c - 我的程序无法正确输出行
- javascript - 文件何时完成流式传输到 AWS S3 上传 api 的事件侦听器?
- javascript - Console.log 不等待承诺