简体   繁体   English

Keras model.predict()仅给出一个预测

[英]Keras model.predict() giving only one prediction

I trained a model, it shows all 4 predictions and saved it in json format. 我训练了一个模型,它显示了所有4个预测并将其保存为json格式。 When I try to load it and do the prediction, it shows only one prediction. 当我尝试加载它并进行预测时,它仅显示一个预测。 What could be going on? 可能会发生什么?

My code: 我的代码:

test = pd.read_csv('./Data/test.tsv', sep="\t")
from nltk.tokenize import word_tokenize
from nltk import FreqDist
from nltk.stem import SnowballStemmer,WordNetLemmatizer
stemmer=SnowballStemmer('english')
lemma=WordNetLemmatizer()
from string import punctuation
import re
testing = test.Phrase.apply(lambda x: x.lower())
tokenizer = Tokenizer(num_words= 10000)
X_test = tokenizer.texts_to_sequences(testing.values)

X_test = sequence.pad_sequences(X_test, maxlen=48)
json_file = open('model1.json', 'r')
loaded_model_json = json_file.read()    
json_file.close()
loaded_model = model_from_json(loaded_model_json)

# Load weights into new model
loaded_model.load_weights('model1.h5') 
loaded_model.compile(loss='categorical_crossentropy',
                     optimizer=Adam(lr=0.001),
                     metrics=['accuracy'])

prediction = model.predict_classes(X_test,verbose=1)
model.summary()#while training
Layer (type)                 Output Shape              Param #   
=================================================================
embedding_1 (Embedding)      (None, None, 100)         1373200   
_________________________________________________________________
lstm_1 (LSTM)                (None, None, 64)          42240     
_________________________________________________________________
lstm_2 (LSTM)                (None, 32)                12416     
_________________________________________________________________
dense_1 (Dense)              (None, 5)                 165       
=================================================================
Total params: 1,428,021
Trainable params: 1,428,021
Non-trainable params: 0
print(X_test.shape)
(66292, 48)

If I understand your issue correctly the problem is here: predict_classes will return you the final predicted label, not probabilities. 如果我正确理解了您的问题,那么问题就出在这里: predict_classes将为您返回最终的预测标签,而不是概率。 It will return one of four labels which has the highest probability. 它将返回概率最高的四个标签之一。 If you want the probabilities for each class, you should probably use predict_proba or predict which are same, eg: 如果需要每个类的概率,则可能应该使用predict_probapredict相同的概率,例如:

prediction = model.predict(X_test,verbose=1)

错误已解决,无法正确调整测试值。在以下命令中删除错误

tokenizer.fit_on_texts(testing.values)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM