如何在keras中使用model.predict? [英] How to use model.predict in keras?
本文介绍了如何在keras中使用model.predict?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在为句子分类任务训练我的模型之后,我正在使用keras model.predict
.我的代码是
I am using keras model.predict
after training my model for a sentence classification task. My code is
import numpy as np
model = Sequential()
l = ['Hello this is police department', 'hello this is 911 emergency']
tokenizer = Tokenizer()
tokenizer.fit_on_texts(l)
X = tokenizer.texts_to_sequences(l)
X = np.array(X)
a = model.predict(X)
print(a)
但是输出似乎是一个数组,
But the output seems to be an array,
[[1. 2. 3. 4. 5.]
[1. 2. 3. 6. 7.]]
我正在处理带有2个标签的句子分类任务.所以我想将这些句子预测为0
或1
.但是取而代之的是获取一个numpy数组.如何编码以预测这两个标签之一?
I am working on a sentence classification task with 2 labels. So I wanted to predict these sentences as 0
or 1
. But instead getting a numpy array. How do I code such that it predicts one of these two labels?
推荐答案
为您的模型添加一些图层.要获得[0,1]中的概率,请使用Sigmoid作为最后一次激活
add some layer to your model. to get probabilities in [0,1] use sigmoid as last activation
from sklearn.preprocessing import LabelEncoder
maxlen = 10
X_train = ['Hello this is police department',
'hello this is 911 emergency',
'asdsa sadasd',
'asnxas asxkx',
'kas',
'jwxxxx']
y_train = ['positive','negative','positive','negative','positive','negative']
label_enc = LabelEncoder()
label_enc.fit(y_train)
tokenizer = tf.keras.preprocessing.text.Tokenizer()
tokenizer.fit_on_texts(X_train)
X_train = tokenizer.texts_to_sequences(X_train)
X_train = tf.keras.preprocessing.sequence.pad_sequences(X_train, maxlen=maxlen)
y_train = label_enc.transform(y_train)
model = Sequential()
model.add(Dense(1, activation='sigmoid', input_shape=(maxlen,)))
model.compile('adam', 'binary_crossentropy')
model.fit(X_train,y_train, epochs=3)
### PREDICT NEW UNSEEN DATA ###
X_test = ['hello hSDAS', '911 oaoad']
X_test = tokenizer.texts_to_sequences(X_test)
X_test = tf.keras.preprocessing.sequence.pad_sequences(X_test, maxlen=maxlen)
a = (model.predict(X_test)>0.5).astype(int).ravel()
print(a)
reverse_pred = label_enc.inverse_transform(a.ravel())
print(reverse_pred)
这篇关于如何在keras中使用model.predict?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文