python - 如何使用多个保存的模型进行预测?
问题描述
我正在尝试从这个笔记本下载的保存模型中预测得分值
https://www.kaggle.com/paoloripamonti/twitter-sentiment-analysis/
它包含4个保存的模型,即:
- 编码器.pkl
- 模型.h5
- 模型.w2v
- 分词器.pkl
我正在使用 model.h5 我的代码是:
from keras.models import load_model
s_model = load_model('model.h5')
#predict the result
result = model.predict("HI my name is Mansi")
但它无法预测。
我认为错误是因为我必须先对其进行标记和编码,但我不知道如何使用多个保存的模型来做到这一点。
任何人都可以指导我如何使用上面笔记本中提到的保存模型来预测值和分数。
解决方案
在输入模型之前应该对文本进行预处理,以下是最小的工作脚本(改编自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()
# Tokenize text
x_test = pad_sequences(tokenizer.texts_to_sequences([text]), maxlen=SEQUENCE_LENGTH)
# Predict
score = model.predict([x_test])[0]
# Decode sentiment
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}
推荐阅读
- c# - ListView 中的意外边距
- sql-server - 将多个特殊字符替换为单个破折号
- html - css:显示一个减半的基于字体的图标
- python-3.6 - 使用 pydrill storage_update() 创建 Apache Drill 存储
- laravel - 如何使用 lat long 计算 laravel 中的距离
- javascript - Scrollspy 不工作 Bootstrap 4
- javascript - 2 种类型的 textarea 值
- google-app-engine - 如何限制在 GCP App Engine 下运行的网站可以从企业网络访问?
- c# - 按名称获取营销列表 ID
- java - Java Arrays.fill() 函数在主线程上过早执行?