如何在类中运行numpy日志

问题描述 投票:-1回答:3

我是编写python类的新手。基本上,我正在尝试编写一个将在sklearn管道中使用的类。该类需要通过修改某些现有属性将两个属性添加到现有数据框。

  1. 新属性将是现有列的日志转换,以及
  2. 两个其他属性的乘积相乘。这是我有的:

码:

import BaseEstimator and TransformerMixIn
from sklearn.base import BaseEstimator, TransformerMixin

population_ix, A_PM10_ix, A_PM25_ix = 15, 2, 3

class CombinedAttributes(BaseEstimator, TransformerMixin):
    def __init__(self):
        pass
    def fit(self, X, y=None):
        return self
    def transform(self, X, y=None):
        log_pop = np.log(X[:,population_ix])
        pm = X[:, A_PM10_ix] * X[:,A_PM25_ix]
        return np.c_[X, log_pop, pm]

attr_adder = CombinedAttributes()
env_extra_attribs = attr_adder.transform(environment.values)

这是我收到的错误消息:

AttributeError                            Traceback (most recent call last)
<ipython-input-66-e138b3c2e517> in <module>()
      1 attr_adder = CombinedAttributes()
----> 2 env_extra_attribs = attr_adder.transform(environment.values)

<ipython-input-65-e4aac1c1930b> in transform(self, X, y)
     11         return self
     12     def transform(self, X, y=None):
---> 13         log_pop = np.log(X[:,population_ix])
     14         pm = X[:, A_PM10_ix] * X[:,A_PM25_ix]
     15         return np.c_[X, log_pop, pm]

AttributeError: 'float' object has no attribute 'log'</code>

我的问题是如何让日志转换在此工作。

另外,我也不是100%确定如何在init def中包含pass语句。同样,这是全新的,我很难找到我能理解的教程。

任何帮助将不胜感激,谢谢,

python python-3.x numpy
3个回答
1
投票

错误消息基本上说你试图调用.log()方法是一个float的对象。由于你只在对象np上这样做,我认为你不小心在某处覆盖了导入的模块np。您没有提供所有代码,特别是没有提供MCVE,所以我只能猜测您在执行代码之前可能已经分配了np

我建议您扫描代码以获取此类代码或以其他方式在您的问题中提供代码或创建一个显示问题的MCVE,以便我们可以重现它。


1
投票

看起来你用float值“覆盖”了导入的numpy模块。搜索您的代码,例如:

np = 5.4

或任何其他种类的np =。另外,请确保使用import numpy as np正确导入numpy,并且不包含来自未知/自编模块的任何已加星标的导入,例如from module_name import *。如果该模块中包含任何名为np的变量,这可能会“覆盖”您的numpy模块导入。

通常,您应该避免使用from module_name import *导入模块。这几乎总会造成麻烦。


0
投票

我怀疑environment.values或函数内部的X是一个对象dtype数组。

In [195]: x = np.array([1.2, 2.3], object)
In [196]: np.sqrt(x)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-196-0b43c7e80401> in <module>()
----> 1 np.sqrt(x)

AttributeError: 'float' object has no attribute 'sqrt'
In [197]: (x+x)/2
Out[197]: array([1.2, 2.3], dtype=object)
In [198]: np.log(x)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-198-de666c833898> in <module>()
----> 1 np.log(x)

AttributeError: 'float' object has no attribute 'log'

我在最近的另一个答案AttributeError: 'Series' object has no attribute 'sqrt'中详细说明了这一点

© www.soinside.com 2019 - 2024. All rights reserved.