You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Streamlit部署GRU模型时遇RuntimeError事件循环问题求助

部署GRU模型到Streamlit时遇到RuntimeError错误

尝试用Streamlit部署GRU模型,持续出现以下错误:

RuntimeError: There is no current event loop in thread 'ScriptRunner.scriptThread'

相关代码

import streamlit as st
import pickle
import numpy as np
from keras.models import load_model


model = (open('gru.pkl','rb'))

def predict_Airpassengers(timestamp): 
    input=np.int(timestamp)
    prediction = model.predict(input)
    print(Prediction)
    return Prediction


def main():
    st.title("Air Passengers Predictor")
    st.header('Enter the timestamp:')
    timestamp = st.number_input('timestamp:', min_value=1, max_value=1000, value=1)
    output=""
    if st.button("Predict Passengers"):
        output = predict_Airpassengers(timestamp)
        st.success('The output is ;'.format(output))
if __name__=='__main__':
     main()

错误回溯信息

RuntimeError: There is no current event loop in thread 'ScriptRunner.scriptThread'.
Traceback:
File "c:\users\user\anaconda3\lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 563, in _run_script
    exec(code, module.__dict__)
File "C:\Users\user\anaconda3\Lib\site-packages\ipykernel_launcher.py", line 16, in <module>
    app.launch_new_instance()
File "C:\Users\user\anaconda3\lib\site-packages\traitlets\config\application.py", line 844, in launch_instance
    app.initialize(argv)
File "C:\Users\user\anaconda3\lib\site-packages\traitlets\config\application.py", line 87, in inner
    return method(app, *args, **kwargs)
File "C:\Users\user\anaconda3\lib\site-packages\ipykernel\kernelapp.py", line 582, in initialize
    self.init_kernel()
File "C:\Users\user\anaconda3\lib\site-packages\ipykernel\kernelapp.py", line 439, in init_kernel
    shell_stream = ZMQStream(self.shell_socket)
File "C:\Users\user\anaconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 115, in __init__
    self.io_loop = io_loop or IOLoop.current()
File "C:\Users\user\anaconda3\lib\site-packages\zmq\eventloop\ioloop.py", line 116, in current
    loop = ioloop.IOLoop.current(*args, **kwargs)
File "c:\users\user\anaconda3\lib\site-packages\tornado\ioloop.py", line 263, in current
    loop = asyncio.get_event_loop()
File "c:\users\user\anaconda3\lib\asyncio\events.py", line 639, in get_event_loop
    raise RuntimeError('There is no current event loop in thread %r.'

问题修复方案

1. 修正模型加载方式

原代码仅打开了模型文件,未完成加载操作。根据模型保存方式选择对应加载方法:

# 若为Keras原生保存的h5模型
model = load_model('gru.h5')
# 若为pickle序列化的模型
model = pickle.load(open('gru.pkl','rb'))

同时用Streamlit缓存装饰器缓存模型,避免重复加载引发线程问题:

@st.cache_resource
def load_gru_model():
    return load_model('gru.h5')  # 根据实际模型格式调整

model = load_gru_model()

2. 修正变量名大小写不一致

函数内print(Prediction)和return Prediction中的变量名应为小写prediction,与前面定义的变量保持一致。

3. 调整模型输入格式

Keras模型的predict方法需要接收批量数组,不能直接传入单个整数。根据模型训练时的输入形状调整,例如:

def predict_Airpassengers(timestamp): 
    # 假设模型输入形状为(样本数, 时间步长),转换为(1,1)的批量输入
    input_data = np.array([[timestamp]])
    prediction = model.predict(input_data)
    print(prediction)
    return prediction

4. 修正Streamlit提示文本格式化

原代码的st.success占位符错误,修改为正确的格式化方式:

st.success(f'The output is {output}')

5. 解决事件循环问题

如果上述修改后仍有事件循环错误,可在预测函数中手动创建事件循环:

import asyncio

def predict_Airpassengers(timestamp): 
    try:
        loop = asyncio.get_event_loop()
    except RuntimeError:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
    
    input_data = np.array([[timestamp]])
    prediction = model.predict(input_data)
    return prediction

内容的提问来源于stack exchange,提问作者Benedict Odhiambo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 20:11:26