【问题标题】:Getting AttributeError: sqrt in vq.whiten获取 AttributeError:vq.whiten 中的 sqrt
【发布时间】:2012-11-09 03:21:03
【问题描述】:

我无法使用来自scipy.clustervq.whiten 来规范化我的数据。我传入了一个 numpy 数组,其中缺失的特征值用每个特征的平均值填充。

卡住的那一行是:

data = scipy.cluster.vq.whiten(self.imputed)

这是我用来替换缺失数据的代码。

imputed = np.array([self.masked[:,i].filled(self.masked[:,i].mean()) 
                   for i in range(np.shape(self.masked)[1])])
self.imputed = np.transpose(imputed)

我确信这部分也有更好的方法,除了它似乎破坏了我的代码这一事实。这似乎是一种丑陋的方式,这通常意味着 Python 有更好的方式。

我尝试减少发送到 whiten 的数组的数量,但无论我在 Traceback 中得到什么。

Traceback (most recent call last):
  File "C:\Users\jamie.bull\workspace\Metadata\src\draft_workflow.py", line 87, in <module>
    dataset.cluster()
  File "C:\Users\jamie.bull\workspace\Metadata\src\draft_workflow.py", line 59, in cluster
    data = scipy.cluster.vq.whiten(self.imputed)
  File "C:\Enthought\Python27\lib\site-packages\scipy\cluster\vq.py", line 131, in whiten
    std_dev = std(obs, axis=0)
  File "C:\Enthought\Python27\lib\site-packages\numpy\core\fromnumeric.py", line 2467, in std
    return std(axis, dtype, out, ddof)
AttributeError: sqrt

集群在相同的数据集上运行良好,没有任何丢失的数据,所以我不知道下一步该尝试什么。

编辑: 我尝试使用以下方法打印出imputed 中每个项目的类型,用于完整数据集和缺少数据的数据集:

for item in imputed:
    print type(item)

两者之间的区别在于,当没有调用均值替换和转置的版本时,每一行都有一个numpy.ndarray,而被均值替换的版本每列都有一个。

【问题讨论】:

  • 你能显示更多的回溯吗?
  • 已编辑以显示完整的 Traceback。我很确定问题在于我如何创建imputed。我推出了一个 1D numpy 数组的数组,而我想要的是一个 2D numpy 数组。
  • 是的,您正在设置推算为一维数组,这将打破vq.whiten。我建议摆脱列表理解 ([a for b in c]) 并只做一个循环来替换您丢失的数据。
  • 已修复。显然我只需要将 dtype 设置为浮动。感谢您的帮助,@tiago

标签: python numpy scipy cluster-analysis


【解决方案1】:

我现在已经解决了这个问题,所以我会把答案放在这里以供未来迷失的灵魂使用。问题是当原始数据存储为numpy.float64 时,我的平均替换是用floats 替换缺失值。

解决方案是运行列表推导并通过将dtype 设置为np.float64 来遵循它。看来whiten 不喜欢接收混合数据类型。

另外,为了解决列表解析后不得不转置的丑陋问题,我重新发现了np.column_stack()。现在的工作函数是:

def mean_impute(self):
    imputed = np.column_stack(self.masked[:,i].filled(self.masked[:,i].mean()) 
               for i in range(np.shape(self.masked)[1]))
    self.imputed = np.array(imputed, dtype=np.float64)

编辑添加

很久以前,但我想我会在这里更新。我现在将使用 pandas 进行数据处理,并在这种情况下使用 pandasfill_na()

OP 中的违规行可以替换为:

imputed = self.masked.fillna(self.masked.mean())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    • 1970-01-01
    • 1970-01-01
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多