Streamlit部署Heroku后调用scipy.io.mmread触发ValueError问题
本地正常的Streamlit应用部署Heroku后读取scipy矩阵触发ValueError
问题描述
本地运行无报错的Streamlit应用,部署到Heroku后执行co_occurrence_matrix = scipy.io.mmread("./database/matrix.mtx")时,触发ValueError: not enough values to unpack (expected 5, got 2)错误。
已排查项
- 矩阵创建代码本地验证正常:
smatrix = scipy.sparse.csr_matrix(matrix) scipy.isspmatrix(smatrix) # 返回True scipy.io.mmwrite("./database/matrix.mtx",smatrix)
- 本地与Heroku的Python及依赖库版本完全一致,requirements.txt由
pip freeze生成 - .mtx文件已同步到Git,
git status显示为最新状态 - .mtx文件通过Git LFS上传
- Heroku部署流程无报错,仅应用运行时触发错误
完整错误栈
File "/app/.heroku/python/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 565, in _run_script exec(code, module.__dict__) File "/app/main.py", line 4, in <module> from gorsellestirme_util import set_bg, Plotter, matrix, word_list, main_df File "/app/gorsellestirme_util.py", line 30, in <module> matrix, word_list, main_df = matrix_reader() File "/app/.heroku/python/lib/python3.9/site-packages/streamlit/runtime/legacy_caching/caching.py", line 625, in wrapped_func return get_or_create_cached_value() File "/app/.heroku/python/lib/python3.9/site-packages/streamlit/runtime/legacy_caching/caching.py", line 609, in get_or_create_cached_value return_value = non_optional_func(*args, **kwargs) File "/app/gorsellestirme_util.py", line 12, in matrix_reader co_occurrence_matrix = mmread("./database/matrix.mtx") File "/app/.heroku/python/lib/python3.9/site-packages/scipy/io/_mmio.py", line 77, in mmread return MMFile().read(source) File "/app/.heroku/python/lib/python3.9/site-packages/scipy/io/_mmio.py", line 438, in read self._parse_header(stream) File "/app/.heroku/python/lib/python3.9/site-packages/scipy/io/_mmio.py", line 502, in _parse_header self.__class__.info(stream) File "/app/.heroku/python/lib/python3.9/site-packages/scipy/io/_mmio.py", line 234, in info mmid, matrix, format, field, symmetry =
解决方案
这个错误是因为Heroku上的.mtx文件格式异常,scipy解析文件头时无法提取预期的5个字段,只拿到2个。结合你用Git LFS上传的情况,核心原因大概率是Heroku未正确拉取实际矩阵文件,只获取了LFS指针文件。
修复步骤:
- 给Heroku安装Git LFS插件:
heroku plugins:install heroku-lfs - 为你的Heroku应用启用LFS:
heroku lfs:enable -a 你的应用名称 - 重新推送LFS文件到Heroku:
git lfs push heroku main - 重新部署应用:
git push heroku main
额外排查点(若上述步骤无效):
- 检查Heroku上的文件内容:执行
heroku run cat ./database/matrix.mtx,如果输出是类似version https://git-lfs.github.com/spec/v1的指针内容,说明LFS拉取失败。 - 验证本地
.gitattributes配置:确保文件中有一行:*.mtx filter=lfs diff=lfs merge=lfs -text - 重新提交文件:
git rm --cached ./database/matrix.mtx git add ./database/matrix.mtx git commit -m "重新提交LFS矩阵文件" git push heroku main
内容的提问来源于stack exchange,提问作者sophophobia
相关产品推荐
相关产品推荐

