Python RandomForest - Unknown label Error

北慕城南 提交于 2019-11-30 11:19:37
Gurupad Hegde

When you are passing label (y) data to rf.fit(X,y), it expects y to be 1D list. Slicing the Panda frame always result in a 2D list. So, conflict raised in your use-case. You need to convert the 2D list provided by pandas DataFrame to a 1D list as expected by fit function.

Try using 1D list first:

Y_train = list(train.P1.values)

If this does not solve the problem, you can try with solution mentioned in MultinomialNB error: "Unknown Label Type":

Y_train = np.asarray(train['P1'], dtype="|S6")

So your code becomes,

colsRes = ['P1']
X_train = train.drop(colsRes, axis = 1)
Y_train = np.asarray(train['P1'], dtype="|S6")
rf = RandomForestClassifier(n_estimators=100)
rf.fit(X_train, Y_train)
N. Wouda

According to this SO post, Classifiers need integer or string labels.

You could consider switching to a regression model instead (that might better suit your data, as each datum appears to be a float), like so:

X_train = train.drop('P1', axis=1)
Y_train = train['P1']
rf = RandomForestRegressor(n_estimators=100)
rf.fit(X_train.as_matrix(), Y_train.as_matrix())

may be a tad late to the party but I just got this error and solved it by making sure my y variable was type(int) using

 y = df['y_variable'].astype(int) 

before doing a train test split, also like others have said you problem seems better fit with a RFReg rather then RF

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!