我正在做一本有关决策树的练习。
我复制粘贴了整个代码,并给了我NameError:未定义名称'dtc'
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
df = pd.read_csv('https://raw.githubusercontent.com/uiuc-cse/data-fa14/gh-pages/data/iris.csv')
#print(df.describe())
#print(df.dtypes)
df['petal_width'].plot.hist()
#plt.show()
all_inputs = df[['sepal_length', 'sepal_width', 'petal_length', 'petal_width']].values
all_classes = df['species'].values
(train_inputs, test_inputs, train_classes, test_classes) = train_test_split(all_inputs, all_classes, train_size=0.7, random_state=1)
classifier = DecisionTreeClassifier()
classifier.fit(train_inputs, train_classes)
print("Accuracy: ", dtc.score(test_inputs, test_classes))
有人可以帮助我理解为什么会发生此错误吗?
答案 0 :(得分:0)
Alex,您需要正确检查变量。您已将classifier
声明为DecisionTreeClassifier
的变量,但最后使用的是dtc
。将dtc
替换为classifier
:
print("Accuracy: ", classifier.score(test_inputs, test_classes))