NameError: name 'classifier' is not defined

别来无恙 提交于 2019-12-13 23:44:04

问题


I am new to machine learning. I was trying to predict on a dataset but when I run the program it give me following error:

NameError: name 'classifier' is not defined 

Here is my code:

import numpy as np
from keras.preprocessing import image
test_image = image.load_img('dataset/single_prediction/1.jpg', target_size = (64, 64))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = classifier.predict(test_image)
training_set.class_indices
if result[0][0] == 1:
  prediction = 'nsfw'
else:
  prediction = 'sfw'

回答1:


You are using classifier to make predictions. But the classifier is not defined. That is what the error is.

To solve this, You must have the saved keras model that is trained for your specific problem with it. If you have that, you can load it and make predictions.

Below code shows how you can load the model.

from keras.models import load_model

classifier = load_model('path_to_your_model')

After the model is loaded you can use that to make predictions like you do.

import numpy as np
from keras.preprocessing import image
test_image = image.load_img('dataset/single_prediction/1.jpg', target_size = (64, 64))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = classifier.predict(test_image)
training_set.class_indices
if result[0][0] == 1:
  prediction = 'nsfw'
else:
  prediction = 'sfw'



回答2:


You have to specify an 'empty' version, before you start adding the layers into the model.

You can simply fix this error by adding this line above your code:

import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.models import load_model

#empty model
classifier = Sequential()

Then continue with specifying like:

#add layers, start with hidden layer and first deep layer
classifier.add(Dense(output_dim=15, init="uniform", activation='relu',input_dim = 15))
classifier.add(Dropout(rate=0.1))


来源:https://stackoverflow.com/questions/52125954/nameerror-name-classifier-is-not-defined

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