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

自定义Scipy分布缺失_shape_info导致stats.fit报错的解决咨询

解决Scipy自定义分布无法用stats.fit拟合的问题

问题根源

stats.fit需要自定义分布提供形状参数的元数据,你的affine_distribution_gen类未实现_shape_info方法,导致无法获取参数约束信息,触发报错。

解决方案1:实现_shape_info方法

在自定义分布类中添加_shape_info方法,返回形状参数的元信息,让stats.fit能够识别参数的取值范围等约束。

修改后的完整代码:

from scipy import stats
import numpy as np

class affine_distribution_gen(stats.rv_continuous):
    def _argcheck(self, c):
        return 0 <= c <= 2
    
    def _pdf(self, x, c):
        return (2 - 2 * c) * x + c

    def _cdf(self, x, c):
        return x * (c + x + c * x)
    
    def _shape_info(self):
        # 定义形状参数c的元信息:名称、非数组类型、取值范围[0,2](闭区间)
        return [stats._distn_infrastructure._ShapeInfo(
            name="c",
            isarray=False,
            domain=(0, 2),
            domain_closed=(True, True)
        )]

创建分布实例并执行拟合:

# 初始化分布(固定区间[0,1])
affine = affine_distribution_gen(name='affine', a=0, b=1)

# 生成测试数据(实际使用时替换为你的真实数据)
data = affine.rvs(c=0.5, size=1000)

# 调用stats.fit拟合参数
fit_result = stats.fit(affine, data, {'c': (0, 2)})
print(fit_result)

解决方案2:使用rv_continuous自带的fit方法

如果不想额外实现元数据方法,可以直接使用rv_continuous类自带的fit方法,通过floc和fscale固定位置、尺度参数(因为你的分布定义在[0,1],无需拟合这两个参数):

from scipy import stats

class affine_distribution_gen(stats.rv_continuous):
    def _argcheck(self, c):
        return 0 <= c <= 2
    
    def _pdf(self, x, c):
        return (2 - 2 * c) * x + c

    def _cdf(self, x, c):
        return x * (c + x + c * x)

# 初始化分布
affine = affine_distribution_gen(name='affine', a=0, b=1)

# 生成测试数据(替换为你的真实数据)
data = affine.rvs(c=0.5, size=1000)

# 拟合参数,固定loc=0、scale=1
fit_params = affine.fit(data, floc=0, fscale=1)
print(f"拟合得到的c参数:{fit_params[0]}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 12:22:32