- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个类似于以下内容的数据框,我们将其称为“df”:
id value time
a 1 1
a 1.5 2
a 2 3
a 2.5 4
b 1 1
b 1.5 2
b 2 3
b 2.5 4
我正在这个数据帧上通过Python中的“id”运行各种回归。一般来说,这需要按“id”进行分组,然后对这些分组应用一个函数来计算回归。
我正在 Scipy 的统计库中使用 2 种类似的回归技术:
Theil-Sen 估计器:
( https://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.stats.mstats.theilslopes.html )
西格尔估计器:
(https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.siegelslopes.html)。
这两者都接收相同类型的数据。因此,除了实际使用的技术之外,计算它们的函数应该是相同的。
对于 Theil-Sen,我编写了以下函数以及将应用于该函数的 groupby 语句:
def theil_reg(df, xcol, ycol):
model = stats.theilslopes(ycol,xcol)
return pd.Series(model)
out = df.groupby('id').apply(theil_reg, xcol='time', ycol='value')
但是,我收到以下错误,我一直很难理解如何解决该错误:
ValueError: could not convert string to float: 'time'
实际变量time是一个numpy浮点对象,所以它不是一个字符串。这让我相信 stats.theilslopes
函数无法识别 time 是数据帧中的一列,而是使用“time”作为函数的字符串输入。
但是,如果是这种情况,那么这似乎是 stats.theilslopes
包中的一个错误,需要由 Scipy 解决。我相信这种情况的原因是因为与上面完全相同的函数,但使用 siegelslopes 包,工作得很好,并提供了我期望的输出,它们本质上是使用相同的输入进行相同的估计。
在 Siegel 上执行以下操作:
def siegel_reg(df, xcol, ycol):
model = stats.siegelslopes(ycol,xcol)
return pd.Series(model)
out = df.groupby('id').apply(siegel_reg, xcol='time',ycol='value')
不会产生任何关于时间变量的错误,并根据需要进行回归。
有人知道我是否在这里遗漏了一些东西吗?如果是这样,我将不胜感激任何想法,或者如果不是,任何关于如何使用 Scipy 解决这个问题的想法。
编辑:这是我运行此脚本时显示的完整错误消息:
ValueError Traceback (most recent call last)
C:\Anaconda\lib\site-packages\pandas\core\groupby\groupby.py in apply(self, func, *args, **kwargs)
688 try:
--> 689 result = self._python_apply_general(f)
690 except Exception:
C:\Anaconda\lib\site-packages\pandas\core\groupby\groupby.py in _python_apply_general(self, f)
706 keys, values, mutated = self.grouper.apply(f, self._selected_obj,
--> 707 self.axis)
708
C:\Anaconda\lib\site-packages\pandas\core\groupby\ops.py in apply(self, f, data, axis)
189 group_axes = _get_axes(group)
--> 190 res = f(group)
191 if not _is_indexed_like(res, group_axes):
C:\Anaconda\lib\site-packages\pandas\core\groupby\groupby.py in f(g)
678 with np.errstate(all='ignore'):
--> 679 return func(g, *args, **kwargs)
680 else:
<ipython-input-506-0a1696f0aecd> in theil_reg(df, xcol, ycol)
1 def theil_reg(df, xcol, ycol):
----> 2 model = stats.theilslopes(ycol,xcol)
3 return pd.Series(model)
C:\Anaconda\lib\site-packages\scipy\stats\_stats_mstats_common.py in
theilslopes(y, x, alpha)
221 else:
--> 222 x = np.array(x, dtype=float).flatten()
223 if len(x) != len(y):
ValueError: could not convert string to float: 'time'
During handling of the above exception, another exception occurred:
ValueError Traceback (most recent call last)
<ipython-input-507-9a199e0ce924> in <module>
----> 1 df_accel_correct.groupby('chart').apply(theil_reg, xcol='time',
ycol='value')
C:\Anaconda\lib\site-packages\pandas\core\groupby\groupby.py in apply(self, func, *args, **kwargs)
699
700 with _group_selection_context(self):
--> 701 return self._python_apply_general(f)
702
703 return result
C:\Anaconda\lib\site-packages\pandas\core\groupby\groupby.py in _python_apply_general(self, f)
705 def _python_apply_general(self, f):
706 keys, values, mutated = self.grouper.apply(f,
self._selected_obj,
--> 707 self.axis)
708
709 return self._wrap_applied_output(
C:\Anaconda\lib\site-packages\pandas\core\groupby\ops.py in apply(self, f, data, axis)
188 # group might be modified
189 group_axes = _get_axes(group)
--> 190 res = f(group)
191 if not _is_indexed_like(res, group_axes):
192 mutated = True
C:\Anaconda\lib\site-packages\pandas\core\groupby\groupby.py in f(g)
677 def f(g):
678 with np.errstate(all='ignore'):
--> 679 return func(g, *args, **kwargs)
680 else:
681 raise ValueError('func must be a callable if args or '
<ipython-input-506-0a1696f0aecd> in theil_reg(df, xcol, ycol)
1 def theil_reg(df, xcol, ycol):
----> 2 model = stats.theilslopes(ycol,xcol)
3 return pd.Series(model)
C:\Anaconda\lib\site-packages\scipy\stats\_stats_mstats_common.py in theilslopes(y, x, alpha)
220 x = np.arange(len(y), dtype=float)
221 else:
--> 222 x = np.array(x, dtype=float).flatten()
223 if len(x) != len(y):
224 raise ValueError("Incompatible lengths ! (%s<>%s)" % (len(y), len(x)))
ValueError: could not convert string to float: 'time'
更新2:在函数中调用df后,我收到以下错误消息:
ValueError Traceback (most recent call last)
C:\Anaconda\lib\site-packages\pandas\core\groupby\groupby.py in apply(self, func, *args, **kwargs)
688 try:
--> 689 result = self._python_apply_general(f)
690 except Exception:
C:\Anaconda\lib\site-packages\pandas\core\groupby\groupby.py in _python_apply_general(self, f)
706 keys, values, mutated = self.grouper.apply(f, self._selected_obj,
--> 707 self.axis)
708
C:\Anaconda\lib\site-packages\pandas\core\groupby\ops.py in apply(self, f, data, axis)
189 group_axes = _get_axes(group)
--> 190 res = f(group)
191 if not _is_indexed_like(res, group_axes):
C:\Anaconda\lib\site-packages\pandas\core\groupby\groupby.py in f(g)
678 with np.errstate(all='ignore'):
--> 679 return func(g, *args, **kwargs)
680 else:
<ipython-input-563-5db69048f347> in theil_reg(df, xcol, ycol)
1 def theil_reg(df, xcol, ycol):
----> 2 model = stats.theilslopes(df[ycol],df[xcol])
3 return pd.Series(model)
C:\Anaconda\lib\site-packages\scipy\stats\_stats_mstats_common.py in theilslopes(y, x, alpha)
248 sigma = np.sqrt(sigsq)
--> 249 Ru = min(int(np.round((nt - z*sigma)/2.)), len(slopes)-1)
250 Rl = max(int(np.round((nt + z*sigma)/2.)) - 1, 0)
ValueError: cannot convert float NaN to integer
During handling of the above exception, another exception occurred:
ValueError Traceback (most recent call last)
<ipython-input-564-d7794bd1d495> in <module>
----> 1 correct_theil = df_accel_correct.groupby('chart').apply(theil_reg, xcol='time', ycol='value')
C:\Anaconda\lib\site-packages\pandas\core\groupby\groupby.py in apply(self, func, *args, **kwargs)
699
700 with _group_selection_context(self):
--> 701 return self._python_apply_general(f)
702
703 return result
C:\Anaconda\lib\site-packages\pandas\core\groupby\groupby.py in _python_apply_general(self, f)
705 def _python_apply_general(self, f):
706 keys, values, mutated = self.grouper.apply(f, self._selected_obj,
--> 707 self.axis)
708
709 return self._wrap_applied_output(
C:\Anaconda\lib\site-packages\pandas\core\groupby\ops.py in apply(self, f, data, axis)
188 # group might be modified
189 group_axes = _get_axes(group)
--> 190 res = f(group)
191 if not _is_indexed_like(res, group_axes):
192 mutated = True
C:\Anaconda\lib\site-packages\pandas\core\groupby\groupby.py in f(g)
677 def f(g):
678 with np.errstate(all='ignore'):
--> 679 return func(g, *args, **kwargs)
680 else:
681 raise ValueError('func must be a callable if args or '
<ipython-input-563-5db69048f347> in theil_reg(df, xcol, ycol)
1 def theil_reg(df, xcol, ycol):
----> 2 model = stats.theilslopes(df[ycol],df[xcol])
3 return pd.Series(model)
C:\Anaconda\lib\site-packages\scipy\stats\_stats_mstats_common.py in theilslopes(y, x, alpha)
247 # Find the confidence interval indices in `slopes`
248 sigma = np.sqrt(sigsq)
--> 249 Ru = min(int(np.round((nt - z*sigma)/2.)), len(slopes)-1)
250 Rl = max(int(np.round((nt + z*sigma)/2.)) - 1, 0)
251 delta = slopes[[Rl, Ru]]
ValueError: cannot convert float NaN to integer
但是,两列中都没有空值,并且两列都是 float 。对这个错误有什么建议吗?
最佳答案
本质上,您将列名称的字符串值(不是任何值实体)传递到方法中,但 slopes 调用需要 numpy 数组(或可以强制转换为数组的 pandas 系列)。具体来说,您尝试此调用时未引用 df,因此出现错误:
model = stats.theilslopes('value', 'time')
只需在调用中引用df:
model = stats.theilslopes(df['value'], df['time'])
model = stats.theilslopes(df[ycol], df[xcol])
<小时/>
关于跨包的不同结果并不意味着 Scipy 存在错误。包运行不同的实现。仔细阅读文档以了解如何调用方法。可能,您引用的另一个包允许数据输入作为调用内的参数,并且命名字符串引用如下所示的列:
slopes_call(y='y_string', x='x_string', data=df)
一般来说,Python 对象模型始终需要对调用和对象的显式命名引用,并且不假定上下文。
关于python - 在 Python 中运行 Theil-Sen 回归时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56500036/
[在此处输入图像描述][1]我正在努力弄清楚回归是否是我需要走的路线,以便解决我当前使用 Python 的挑战。这是我的场景: 我有一个 195 行 x 25 列的 Pandas Dataframe
我想训练回归模型(不是分类),其输出是连续数字。 假设我有输入变量 X,其范围在 -70 到 70 之间。我有输出变量 Y,其范围在 -5 到 5 之间。X 有 39 个特征,Y 有 16 个特征,每
我想使用神经网络逼近 sinc 函数。这是我的代码: import tensorflow as tf from keras.layers import Dense from keras.models
我对 postgres 表做了一些更改,我想将其恢复到以前的状态。没有数据库的备份。有办法吗?比如,postgres 会自动拍摄快照并将其存储在某个地方,还是原始数据会永远丢失? 最佳答案 默认情况下
我有大约 100 个 7x7 因变量矩阵(所以有 49 个因变量)。我的自变量是时间。我正在做一个物理项目,我应该通过求解 ODE 得到一个矩阵函数(矩阵的每个元素都是时间的函数)。我使用了 nump
我之前曾被告知——出于完全合理的原因——当结果变量为二元变量时(即是/否、真/假、赢/输等),不应运行 OLS 回归。但是,我经常阅读经济学/其他社会科学方面的论文,其中研究人员对二元变量运行 OLS
您好,我正在使用生命线包进行 Cox 回归。我想检查非二元分类变量的影响。有内置的方法吗?或者我应该将每个类别因子转换为一个数字?或者,在生命线中使用 kmf fitter,是否可以对每个因素执行此操
作为后续 this question ,我拟合了具有定量和定性解释变量之间相互作用的多元 Logistic 回归。 MWE如下: Type |z|) (Intercept) -0.65518
我想在单个动物园对象中的多对数据系列上使用 lm 执行滚动回归。 虽然我能够通过以下代码对动物园对象中的一对数据系列执行滚动回归: FunLm seat time(seat) seat fm
是否有一种简单的方法可以在 R 中拟合多元回归,其中因变量根据 Skellam distribution 分布? (两个泊松分布计数之间的差异)?比如: myskellam <- glm(A ~ B
包含各种特征和回归目标(称为 qval)的数据集用于训练 XGBoost 回归器。该值 qval 介于 0 和 1 之间,应具有以下分布: 到目前为止,还不错。但是,当我使用 xgb.save_mod
这有效: felm(y ~ x1 + x2 | fe1 + fe2 | 0 | , data = data) 我想要: fixedeffects = "fe1 + fe2" felm(y ~ x1
这有效: felm(y ~ x1 + x2 | fe1 + fe2 | 0 | , data = data) 我想要: fixedeffects = "fe1 + fe2" felm(y ~ x1
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 我们不允许提问寻求书籍、工具、软件库等的推荐。您可以编辑问题,以便用事实和引用来回答。 关闭 7 年前。
我刚刚开始使用 R 进行统计分析,而且我还在学习。我在 R 中创建循环时遇到问题。我有以下案例,我想知道是否有人可以帮助我。对我来说,这似乎是不可能的,但对你们中的一些人来说,这只是小菜一碟。我有不同
是否可以在 sklearn 中使用或不使用(即仅使用截距)预测器来运行回归(例如逻辑回归)?这似乎是一个相当标准的类型分析,也许这些信息已经在输出中可用。 我发现的唯一相关的东西是sklearn.sv
假设我对一些倾斜的数据分布执行 DNN 回归任务。现在我使用平均绝对误差作为损失函数。 机器学习中的所有典型方法都是最小化平均损失,但对于倾斜来说这是不恰当的。从实际角度来看,最好尽量减少中值损失。我
我正在对公寓特征进行线性回归分析,然后预测公寓的价格。目前,我已经收集了我所在城市 13000 套公寓的特征。我有 23-25 个特征,我不确定在公寓价格预测中拥有如此多的特征是否正常。 我有以下功能
我是 ML 新手,对 catboost 有疑问。所以,我想预测函数值(例如 cos | sin 等)。我回顾了一切,但我的预测始终是直线 是否可能,如果可能,我该如何解决我的问题 我很高兴收到任何评论
我目前已经为二进制类实现了概率(至少我这么认为)。现在我想扩展这种回归方法,并尝试将其用于波士顿数据集。不幸的是,我的算法似乎被卡住了,我当前运行的代码如下所示: from sklearn impor
我是一名优秀的程序员,十分优秀!