【问题标题】:NameError: name 'classifier' is not definedNameError:名称“分类器”未定义
【发布时间】:2018-09-01 07:31:33
【问题描述】:

我是机器学习的新手。我试图在数据集上进行预测,但是当我运行程序时,它给了我以下错误:

NameError: name 'classifier' is not defined 

这是我的代码:

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'

【问题讨论】:

  • 这是意料之中的。您还没有在任何地方定义分类器
  • 您必须为此目的加载已保存的分类器

标签: python-3.x tensorflow machine-learning keras prediction


【解决方案1】:

您正在使用classifier 进行预测。但是classifier 没有定义。这就是错误所在。

要解决这个问题,您必须拥有针对您的特定问题进行训练的已保存 keras 模型。如果你有这个,你可以加载它并进行预测。

以下代码显示了如何加载模型。

from keras.models import load_model

classifier = load_model('path_to_your_model')

加载模型后,您可以使用它进行预测。

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】:

在开始将层添加到模型之前,您必须指定一个“空”版本。

您可以通过在代码上方添加以下行来简单地修复此错误:

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

#empty model
classifier = Sequential()

然后继续指定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))

【讨论】:

    猜你喜欢
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    • 2021-09-22
    相关资源
    最近更新 更多