繁体   English   中英

如何在 keras 中使用 model.predict?

[英]How to use model.predict in keras?

在训练我的 model 进行句子分类任务后,我正在使用 keras model.predict 我的代码是

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)

但是 output 似乎是一个数组,

[[1. 2. 3. 4. 5.]
 [1. 2. 3. 6. 7.]]

我正在处理带有 2 个标签的句子分类任务。 所以我想将这些句子预测为01 而是得到一个 numpy 阵列。 我如何编码以使其预测这两个标签之一?

为您的 model 添加一些层。 要获得 [0,1] 中的概率,请使用 sigmoid 作为最后一次激活

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)

暂无
暂无

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

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