【问题标题】:How to use model.predict in keras?如何在keras中使用model.predict?
【发布时间】:2020-11-09 16:50:27
【问题描述】:

在为句子分类任务训练我的模型后,我正在使用 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)

但是输出好像是一个数组,

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

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

【问题讨论】:

    标签: python-3.x tensorflow keras nlp


    【解决方案1】:

    为您的模型添加一些层。要获得 [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)
    

    【讨论】:

    • 它正在工作,但是假设,我有情绪分类任务,我想将其评为0 表示消极,1 表示积极。我应该如何使用训练/测试模型,以便根据它进行预测。在您的示例中,它只是根据概率预测01
    • 您可以将 0 映射为负值,将 1 映射为正值。这是你的意思吗?
    • 不不,在我们的示例中看到这里,我们在没有任何事先培训/测试的情况下进行预测。所以这只是简单的预测。如果我想根据我训练的句子进行预测怎么办。就像在训练中一样,我已经训练了我的数据,现在我想用它来预测不在数据集中的新句子。
    • 在火车上拟合后,您必须使用相同的拟合模型进行预测。记得操作相同的预处理。我用一个例子编辑了它。不要忘记投票并接受作为答案;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 2020-10-24
    • 1970-01-01
    • 2018-10-23
    • 2020-05-11
    相关资源
    最近更新 更多