Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

python - Keras: .predict returns percentages instead of classes

I am building a model with 3 classes: [0,1,2] After training, the .predict function returns a list of percentages instead. I was checking the keras documentation but could not figure out, what I did wrong. .predict_classes is not working anymore, and I did not have this problem with previous classifiers. I already tried different activation functions (relu, sigmoid etc.) If I understand correctly, the number inDense(3...) defines the amount of classes.

outputs1=Dense(3,activation='softmax')(att_out) 
model1=Model(inputs1,outputs1)
model1.summary()
model1.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=['accuracy'])
model1.fit(x=text_pad,y=train_y,batch_size=batch_size,epochs=epochs,verbose=1,shuffle=True) 

y_pred = model1.predict(test_text_matrix)

Output example:

[[0.34014237 0.33570153 0.32415614]
 [0.34014237 0.33570153 0.32415614]
 [0.34014237 0.33570153 0.32415614]
 [0.34014237 0.33570153 0.32415614]
 [0.34014237 0.33570153 0.32415614]]

Output I want:

[1,2,0,0,0,1,2,0]

Thank you for any ideas.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You did not do anything wrong, predict has always returned the output of the model, for a classifier this has always been probabilities per class.

predict_classes is only available for Sequential models, not for Functional ones.

But there is an easy solution, you just need to take the argmax on the last dimension and you will get class indices:

y_probs = model1.predict(test_text_matrix)
y_pred  = np.argmax(y_probs, axis=-1)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...