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

使用scipy.optimize.minimize做非线性最小二乘回归遇两类错误求助

解决非线性最小二乘回归中的ValueError与Overflow问题

先拆解你遇到的两个问题根源,再给出针对性的修正方案:

错误原因分析

1. ValueError: setting an array element with a sequence

scipy.optimize.minimize是用来最小化标量目标函数的(比如残差平方和这类单个数值),但你的lsq函数返回的是一个和total长度一致的数组p,完全不符合minimize的输入要求。优化过程中尝试将这个数组赋值给需要单个数值的变量,就触发了这个错误。

2. overflow encountered in power

你的公式10^(a*(total**(b-1)))中,当total取大值(比如57、28)且b>1时,total^(b-1)会急剧增大,再乘以a*100后,指数会变得极大,计算10^这个超大数会超出Python浮点数的表示范围,导致溢出。

修正方案

1. 替换优化函数:用least_squares替代minimize

scipy.optimize.least_squares是专门为非线性最小二乘拟合设计的,它接受返回残差数组(模型预测值与实际观测值的差值)的函数,会自动计算残差平方和并完成优化,完美匹配你的场景。

2. 修正目标函数与数值计算逻辑

  • 去掉参数的*100缩放:这会大幅降低指数的大小,避免溢出;
  • 处理大指数的极端情况:用np.where判断,当指数过大时直接将p设为1(因为此时1/(10^指数)趋近于0,p≈1);
  • 补充观测因变量:最小二乘拟合需要你提供和total对应的实际观测值(假设为y_obs,你需要替换成自己的真实数据),函数返回残差数组。

修正后的完整代码

import numpy as np
from scipy.optimize import least_squares

# 你的total数据
total = np.array([ 1, 2, 1, 1, 1, 5, 5, 5, 1, 1, 3, 1, 1, 1, 2, 1, 16, 5, 8, 1, 2, 1, 16, 2, 1, 1, 1, 2, 1, 4, 1, 5, 2, 3, 1, 1, 5, 3, 1, 3, 26, 3, 1, 16, 4, 1, 3, 1, 1, 1, 5, 22, 1, 7, 1, 2, 1, 5, 3, 1, 9, 1, 2, 2, 9, 2, 1, 16, 13, 1, 1, 1, 1, 7, 1, 1, 1, 8, 1, 1, 2, 1, 1, 2, 1, 28, 1, 2, 1, 1, 57, 10, 1, 1, 11, 2, 20, 2, 1, 21, 19, 1, 2, 3, 6, 15, 10, 10, 23, 2, 1, 10, 18, 5, 3, 13, 1, 1, 1, 1, 1, 2, 5, 3, 23, 6, 1, 7, 2, 15, 1, 19, 6, 7, 6, 1, 8, 13, 1, 27, 4, 4, 15, 1, 1, 2, 1, 1, 2, 1, 1], dtype=np.int64)

# 替换成你的实际观测因变量(必须和total长度一致)
y_obs = np.random.rand(len(total))  # 示例数据,请替换为真实数据

def residual(arg):
    a, b = arg
    # 计算指数,避免极端值导致溢出
    exponent = a * (total ** (b - 1))
    # 当指数大于30时,10^exponent已超出浮点数范围,直接取p=1
    p = np.where(exponent > 30, 1.0, 1 - 1 / np.power(10, exponent))
    # 返回残差:模型预测值 - 观测值
    return p - y_obs

# 初始猜测值
guesses = np.array([0.05, 1.0])
# 执行最小二乘拟合
res = least_squares(residual, guesses)

# 输出结果
print("优化状态消息:", res.message)
print("最优参数a, b:", res.x)
print("初始猜测的残差平方和:", np.sum(residual(guesses)**2))
print("优化后的残差平方和:", np.sum(residual(res.x)**2))

额外说明

如果你的拟合目标不是基于观测值的残差,而是要最小化某个其他数组相关的指标,需要明确目标函数的定义,但核心逻辑还是要确保用合适的优化函数:least_squares处理数组残差,minimize处理标量目标。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:09:25