簡體   English   中英

list' 對象不能在 RandomForest 代碼中解釋為整數

[英]list' object cannot be interpreted as an integer in RandomForest code

我使用了機器學習書中的以下代碼

from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import mglearn
X,y =make_moons(n_samples=100,noise=0.25,random_state=3)
X_train,X_test,y_train,y_test =train_test_split(X,y,stratify=y,random_state=42)
#sketch random forest
forest =RandomForestClassifier(n_estimators=5,random_state=2)
forest.fit(X_train,y_train)

#draw random forest
fix, axes =plt.subplots(2,3,figsize=(20,10))
for i,(ax,tree) in enumerate(list(zip(axes.ravel())),forest.estimators_):
    ax.set_title("tree{}".format(i))
    mglearn.plots.plot_tree_partition(X_train,y_train,tree,ax=ax)
mglearn.plots.plot_2d_separator(forest, X_train, fill=True, ax=axes[-1, -1],alpha=.4)
axes[-1, -1].set_title("Random Forest")
mglearn.discrete_scatter(X_train[:, 0], X_train[:, 1], y_train)

它說以下錯誤:

TypeError: 'list' object cannot be interpreted as an integer

我知道在 python3 中,對於 zip 有必要的 list 命令,所以在書中最初是這樣寫的

for i, (ax, tree) in enumerate(zip(axes.ravel(), forest.estimators_)):

我已經添加了 list 命令,但它仍然向我顯示這個錯誤,你能幫我澄清一下是什么問題嗎?

enumerate(list(zip(axes.ravel())),forest.estimators_)

forest.estimators_在您的list(zip())調用之外,並被視為enumerate的第二個參數,從文檔中,它表示起始索引。 由於forest.estimators_是一個列表,這將失敗,因為需要一個整數。

你要寫的意思是:

enumerate(list(zip(axes.ravel(), forest.estimators_)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM