Python:如何正确调用方法?

时间:2016-05-07 19:54:05

标签: python-2.7 class methods scikit-learn logistic-regression

我有这堂课:

class Tumor(object):
    """
    Wrapper for the tumor data points.

    Attributes:
        idNum = ID number for the tumor (is unique) (int)
        malignant = label for this tumor (either 'M' for malignant 
                    or 'B' for benign) (string)
        featureNames = names of all features used in this Tumor 
                       instance (list of strings)
        featureVals = values of all features used in this Tumor
                       instance, same order as featureNames (list of floats)
    """
    def __init__(self, idNum, malignant, featureNames, featureVals):
        self.idNum = idNum
        self.label = malignant
        self.featureNames = featureNames
        self.featureVals = featureVals
    def distance(self, other):
        dist = 0.0
        for i in range(len(self.featureVals)):
            dist += abs(self.featureVals[i] - other.featureVals[i])**2
        return dist**0.5
    def getLabel(self):
        return self.label
    def getFeatures(self):
        return self.featureVals
    def getFeatureNames(self):
        return self.featureNames
    def __str__(self):
        return str(self.idNum) + ', ' + str(self.label) + ', ' \
               + str(self.featureVals)

我试图在我的代码中稍后在另一个函数中使用它的实例:

def train_model(train_set):
    """
    Trains a logistic regression model with the given dataset

    train_set (list): list of data points of type Tumor

    Returns a model of type sklearn.linear_model.LogisticRegression
            fit to the training data
    """
    tumor = Tumor()
    features = tumor.getFeatures()
    labels = tumor.getLabel()
    log_reg = sklearn.linear_model.LogisticRegression(train_set)
    model = log_reg.fit(features, labels)

    return model

但是,当我测试代码时,我一直收到此错误:

TypeError: __init__() takes exactly 5 arguments (1 given)

据我所知,当我在train_model中创建Tumor实例时,我没有使用这五个参数,但我该怎么办呢?

1 个答案:

答案 0 :(得分:0)

__init__(或__new__的参数,如果您正在使用它),可以预测,您可以在train_model中创建实例:

tumor = Tumor(idNum, malignant, featureNames, featureVals)

当然,你实际上需要所有这些的值,因为它们都是必需的参数。

但是,您不需要包含self,因为第一个参数会自动处理。