我尝试使用 python 中图像数据的模式来可视化决策树,而不使用 graphviz 使用 DecisionTreeClassifier 但我不断收到错误
sklearn.exceptions.NotFittedError: This DecisionTreeClassifier instance is not
fitted yet. Call 'fit' with appropriate arguments before using this estimator.
即使我在 google colab 和 VScode 中尝试,它仍然出现错误。我的数据集只有 2 列:ModusH 和 Index。
这是我的数据集示例 数据集
这是代码:
datapisang= pd.read_csv('DataModusdiperbaiki.csv')
X= datapisang[['ModusH']]
Y= datapisang[['Index']]
X_train, X_test, Y_train, Y_test = train_test_split(X, Y)
# Model
DT_model= DecisionTreeClassifier()
DT_model.fit(X_train,Y_train)
DT_model.print_tree()
data = [Modus_citra] # Mode Image
hasilprediksi = DT_model.predict([data])
fn = ['ModusH']
cn = ['Index']
fig, axes = plt.subplots(nrows = 1,ncols = 1,figsize = (4,4), dpi=300)
tree.plot_tree(DT_model,
feature_names = fn,
class_names=cn,
filled = True);
fig.savefig('imagename.png')
我尝试获得可视化效果,但即使使用 graphviz,每次也会出错。怎么解决这个问题?
您应该按照以下方式进行操作,如文档
所示from sklearn.datasets import load_iris
from sklearn import tree
clf = tree.DecisionTreeClassifier(random_state=0)
iris = load_iris()
clf = clf.fit(iris.data, iris.target)
tree.plot_tree(clf)
我尝试通过创建一个新的数据框来重新生成您的情况;这是解决方案:
df = pd.DataFrame(np.random.randint(0,100,size=(100, 1)), columns=["ModusH"])
df['Index'] = np.random.choice( a=[0, 1, 2,3,4],size=df.shape[0])
clf = tree.DecisionTreeClassifier(random_state=0)
clf = clf.fit(df.ModusH.to_numpy().reshape(-1, 1), df.Index)
tree.plot_tree(clf)