簡體   English   中英

NameError:未定義名稱“分類器”

[英]NameError: name 'classifier' is not defined

我是機器學習的新手。 我試圖對數據集進行預測,但是當我運行該程序時,它給了我以下錯誤:

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'

您正在使用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'

在開始將層添加到模型之前,您必須指定一個“空”版本。

您可以通過在代碼上方添加以下行來簡單地修復此錯誤:

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

#empty model
classifier = Sequential()

然后繼續指定如下:

#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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM