我有这个类:
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的实例时,我没有使用这五个参数,但我该怎么做呢?
__init__
(或__new__
,如果您正在使用它)的参数可以预见地转到您在train_model:中创建实例的位置
tumor = Tumor(idNum, malignant, featureNames, featureVals)
当然,您实际上需要所有这些的值,因为它们都是必需的参数。
但是,您不需要包含self
,因为第一个参数是自动处理的。