Reputation: 1
I am trying the below code for random forest classifier. Even though I have defined but getting NameError. Please help
def RFC_model(randomState, X_train, X_test, y_train, y_test):
rand_forest = RandomForestClassifier()
rand_forest.fit(X_train, y_train)
forest_test_predictions = rand_forest.predict(X_test)
print(accuracy_score(y_test, forest_test_predictions))
X_train, X_test, y_train, y_test = train_test_split(df_encoded.drop(['success'],axis='columns').values,
df_encoded.success,
test_size=0.2)
RFC_model(42, X_train, X_test, y_train, y_test)
0.994045375744328
rand_forest.feature_importances_.round(3)
NameError Traceback (most recent call last)
<ipython-input-40-974786899b7f> in <module>
1 #importance of features rounded to nearest 3 decimals
----> 2 rand_forest.feature_importances_.round(3)
NameError: name 'rand_forest' is not defined
Upvotes: 0
Views: 408
Reputation: 994
You are defining the variable rand_forest
locally in the scope of the RFC_model
function. Once the function finishes executing, the object is destroyed, so you cannot access it. You can solve this by returning the rand_forest
object:
def RFC_model(randomState, X_train, X_test, y_train, y_test):
rand_forest = RandomForestClassifier()
rand_forest.fit(X_train, y_train)
forest_test_predictions = rand_forest.predict(X_test)
print(accuracy_score(y_test, forest_test_predictions))
return rand_forest
X_train, X_test, y_train, y_test = train_test_split(df_encoded.drop(['success'],axis='columns').values,
df_encoded.success,
test_size=0.2)
rand_forest = RFC_model(42, X_train, X_test, y_train, y_test)
rand_forest.feature_importances_.round(3)
Upvotes: 1