首页 > 解决方案 > 使用 SALib 在 Python 中的敏感性分析错误

问题描述

使用 python 执行敏感性分析之后,我收到一个错误。

我的代码如下:

from SALib.sample import saltelli
from SALib.analyze import sobol

def ls(X):
    # column 0 = demand, column 1 =  bookings, column 2 = inventory
    return max(X[:,0] - X[:,1] - X[:,2])

problem = {'num_vars': 3,
           'names': ['demand', 'bookings', 'inventory'],
           'bounds': [[0, 1250],
                     [0, 11000],
                     [0, 120000]]
           } 

# Generate samples
param_values = saltelli.sample(problem, 10000000, calc_second_order=False)

# Run model
Y = ls(param_values)

# Perform analysis
Si = sobol.analyze(problem, Y)

我收到以下错误。RuntimeError:模型输出文件中的样本数不正确。确认 calc_second_order 与采样期间使用的选项匹配。

当我查看https://github.com/SALib/SALib/blob/master/SALib/analyze/sobol.py时, 我看到:

if calc_second_order and Y.size % (2 * D + 2) == 0:
        N = int(Y.size / (2 * D + 2))
    elif not calc_second_order and Y.size % (D + 2) == 0:
        N = int(Y.size / (D + 2))
    else:
        raise RuntimeError("""
        Incorrect number of samples in model output file.
        Confirm that calc_second_order matches option used during 
sampling.""")

但是,这并不能真正帮助我解决错误。它与 saltelli.sample() 中的第二个参数有关吗?

标签: python-3.x

解决方案


有两个问题。首先,当它应该是一个长度等于 中的行数的向量时,该函数ls()返回一个值param_values。其次,saltelli.sample()and中的默认假设sobol.analyze()是 have calc_second_order=True,因此False在这两种情况下都需要将其设置为。这是一些运行的示例代码,但您可能必须调整ls()函数以满足您的要求。

from SALib.sample import saltelli
from SALib.analyze import sobol

def ls(X):
    # column 0 = demand, column 1 =  bookings, column 2 = inventory
    # modified to return a vector (max was returning max value of vector)
    return (X[:,0] - X[:,1] - X[:,2])

problem = {'num_vars': 3,
           'names': ['demand', 'bookings', 'inventory'],
           'bounds': [[0, 1250],
                     [0, 11000],
                     [0, 120000]]
           } 

# Generate samples
param_values = saltelli.sample(problem, 10000000, calc_second_order=False)

# Run model
Y = ls(param_values)

# Perform analysis
Si = sobol.analyze(problem, Y,calc_second_order=False)

推荐阅读