python-3.x - Object() 不带参数
问题描述
尝试执行下面的代码时,我得到“TypeError:Question() 不带参数”(其中 Question 是 Question 类的对象)。
我正在使用 jupyter notebook 并检查了我的大部分缩进,类 Question 有 2 个属性,我有一个 init 方法......
问题与下面的函数 find_best_split(rows) 有关。
class Question:
def __init__(self, column, value):
self.column = column
self.value = value
def match(self, example):
val = example[self.column]
if is_numeric(val):
return val >= self.value
else:
return val == self.value
def __repr__(self):
condition = "=="
if is_numeric(self.value):
condition = ">="
return "Is %s %s %s?" % (header[self.column], condition, str(self.value))
def partition(rows, question):
true_rows, false_rows = [], []
for row in rows:
if question.match(row):
true_rows.append(row)
else:
false_rows.append(row)
return true_rows, false_rows
` 错误指向这个函数,具体是“question = Question(col, val)”
def find_best_split(rows):
best_gain = 0
best_question = None
current_uncertainty = gini(rows)
n_features = len(rows[0]) -1 # number of columns
for col in range(n_features):
values = set([row[col] for row in rows]) # unique values in the column
for val in values: #now for each value
question = Question(col, val)
# trying to split the data set
true_rows, false_rows = partition(rows, question)
# skips this split if it doesn't divide the data set.
if len(true_rows) == 0 or len(false_rows) == 0:
continue
# calculate the information gain from this split
gain = info_gain(true_rows, false_rows, current_uncertainty)
# you can use > instead of >= below but I wanted the data set to look a certain way for this example.
if gain >= best_gain:
best_gain, best_question = gain, question
return best_gain, best_quesiton
`
class Decision_Node:
def __init__(self, question, true_branch, false_branch):
self.question = question
self.true_branch = true_branch
self.false_branch = false_branch
def build_tree(rows):
gain, question = find_best_split(rows)
if gain == 0:
return Leaf(rows)
true_rows, false_rows = partition(rows, question)
true_branch = build_tree(true_rows)
false_branch = build_tree(false_rows)
return Decision_Node(question, true_branch, false_branch)
if __name__ == '__main__':
my_tree = build_tree(training_data)
print_tree(my_tree)
# Evaluate
testing_data = [
["Green", 3, "Mango"],
["Yellow", 4, "Mango"],
["Red", 2, "Grape"],
["Red", 1, "Grape"],
["Yellow", 3, "Lemon"],
]
for row in testing_data:
print ("Actual: %s. Predicted: %s" % (row[-1], print_leaf(classify(row, my_tree))))
解决方案
推荐阅读
- php - cPanel 使用 Laravel 5.4 在生产环境中发送电子邮件
- python - pycodestyle 检索结果而不打印它们
- node.js - 如何在 Dockerfile 中编译 typescript
- c# - 应用内购买问题。当前不存在名称“DependencyService”
- vba - 如何删除Word表格单元格的回车结束?
- ios - Swift - 使用 Realm 存储分页数据的好方法?
- log4net - EventLogAppender:有问题的“修复”属性
- javascript - 为 Google Charts 条形图数据解析 Json
- java - 在 Flink 中从 Kafka 聚合数据的问题
- r - 密度热图计算