我正在尝试使用从这个笔记本中下载的保存模型来预测分数值
https://www.kaggle.com/paoloripamonti/twitter-sentiment-analysis/
它包含4个保存的模型,分别是:
- encoder.pkl
- model.h5
- model.w2v
- tokenizer.pkl
我正在使用model.h5,我的代码如下:
from keras.models import load_model
model = load_model('model.h5')
# 预测结果
result = model.predict("HI my name is @")
但它无法进行预测。
我认为错误的原因是我需要先进行分词和编码,但我不知道如何使用多个保存的模型来实现这一点。
有谁能指导我如何使用上述笔记本中提到的保存模型来预测值和分数吗?
回答:
在将文本输入模型之前,应该先进行预处理,以下是最简工作脚本(改编自 https://www.kaggle.com/paoloripamonti/twitter-sentiment-analysis/):
import time
import pickle
from keras.preprocessing.sequence import pad_sequences
from keras.models import load_model
model = load_model('model.h5')
tokenizer = pickle.load(open('tokenizer.pkl', "rb"))
SEQUENCE_LENGTH = 300
decode_map = {0: "NEGATIVE", 2: "NEUTRAL", 4: "POSITIVE"}
POSITIVE = "POSITIVE"
NEGATIVE = "NEGATIVE"
NEUTRAL = "NEUTRAL"
SENTIMENT_THRESHOLDS = (0.4, 0.7)
def decode_sentiment(score, include_neutral=True):
if include_neutral:
label = NEUTRAL
if score <= SENTIMENT_THRESHOLDS[0]:
label = NEGATIVE
elif score >= SENTIMENT_THRESHOLDS[1]:
label = POSITIVE
return label
else:
return NEGATIVE if score < 0.5 else POSITIVE
def predict(text, include_neutral=True):
start_at = time.time()
# 分词文本
x_test = pad_sequences(tokenizer.texts_to_sequences([text]), maxlen=SEQUENCE_LENGTH)
# 预测
score = model.predict([x_test])[0]
# 解码情感
label = decode_sentiment(score, include_neutral=include_neutral)
return {"label": label, "score": float(score),
"elapsed_time": time.time()-start_at}
predict("hello")
测试:
predict("hello")
其输出:
{'elapsed_time': 0.6313169002532959, 'label': 'POSITIVE', 'score': 0.9836862683296204}