Home > Back-end >  Object not found while trying to write a pickle file
Object not found while trying to write a pickle file

Time:06-18

I am trying to do cancer detection using Random Vector Forest. I am trying to make a pickle file by using the command pickle.dump(forest,open("model.pkl","wb") .But I am getting a name error

NameError                                 Traceback (most recent call last)
c:\Users\hp\newtest\pcancer.ipynb Cell 6' in <cell line: 1>()
----> 1 pickle.dump(forest,open("model.pkl","wb"))

NameError: name 'forest' is not defined

This is my source code for detection:

import numpy as np
import pandas as pd
import warnings as wr
#Ignoring warnings
from sklearn.exceptions import UndefinedMetricWarning
wr.filterwarnings("ignore", category=UndefinedMetricWarning)
import pickle

df=pd.read_csv('Prostate_cancer_data.csv')
print(df.head(10))
print(df.shape)
print(df.isna().sum())


df=df.dropna(axis=1)#Drop the column with empty data
df=df.drop(['id'],axis=1)


#Encoding first column
from sklearn.preprocessing import LabelEncoder
labelencoder_X=LabelEncoder() 
df.iloc[:,0]=labelencoder_X.fit_transform(df.iloc[:,0].values)

#Splitting data for dependence
X=df.iloc[:,1:].values
Y=df.iloc[:,0].values

#Train-Test split
from sklearn.model_selection import train_test_split
X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.25,random_state=1)
 

#Standard scaling
from sklearn.preprocessing import StandardScaler
sc=StandardScaler()
X_train=sc.fit_transform(X_train)
X_test=sc.fit_transform(X_test)



from sklearn.ensemble import RandomForestClassifier
def models(X_train,Y_train):

    #Random forest classifier
    forest=RandomForestClassifier(n_estimators=10,criterion='entropy',random_state=0)
    forest.fit(X_train,Y_train)

    print("Random Forest:",forest.score(X_train,Y_train))

    return forest

    print("Accuracy")
    model=models(X_train,Y_train)

CodePudding user response:

model=models(X_train,Y_train) 

this part of code is not indented in order. so its a local declaration and action as a recursive call

CodePudding user response:

There is indentation problem in the last section of your code. This is correctly indented code and when you create a pickle file you'll write model object in it not the forest as forest is returned in object named model

from sklearn.ensemble import RandomForestClassifier
def models(X_train,Y_train):

    #Random forest classifier
    forest=RandomForestClassifier(n_estimators=10,criterion='entropy',random_state=0)
    forest.fit(X_train,Y_train)

    print("Random Forest:",forest.score(X_train,Y_train))

    return forest

print("Accuracy")
model=models(X_train,Y_train)
pickle.dump(model,open("model.pkl","wb"))
  • Related