5. 采集函数指南#

5.1. 简介#

采集函数是贝叶斯优化的核心。它们通过平衡探索(在不确定区域采样)和利用(在当前最佳点附近采样)来决定下一步在哪里采样。

5.2. 可用的采集函数#

5.2.1. 期望提升 (EI)#

最流行的采集函数,自然地平衡探索和利用。

数学公式:

EI(x) = (μ(x) - f*) * Φ(Z) + σ(x) * φ(Z)
where Z = (μ(x) - f*) / σ(x)

用法:

from Bgolearn import BGOsampling
import numpy as np
import pandas as pd

# Create sample data
def create_test_function():
    """Create a test optimization problem."""
    np.random.seed(42)
    X = np.random.uniform(-3, 3, (20, 2))
    y = -(X[:, 0]**2 + X[:, 1]**2) + 0.1 * np.random.randn(20)  # Negative quadratic with noise
    return pd.DataFrame(X, columns=['x1', 'x2']), pd.Series(y)

# Generate candidates
def create_candidates():
    x1 = np.linspace(-3, 3, 50)
    x2 = np.linspace(-3, 3, 50)
    X1, X2 = np.meshgrid(x1, x2)
    candidates = np.column_stack([X1.ravel(), X2.ravel()])
    return pd.DataFrame(candidates, columns=['x1', 'x2'])

X_train, y_train = create_test_function()
X_candidates = create_candidates()

# Initialize and fit
optimizer = BGOsampling.Bgolearn()
model = optimizer.fit(X_train, y_train, X_candidates, min_search=False)

# Expected Improvement
ei_values, next_point = model.EI()
print(f"EI selected point: {next_point}")
print(f"EI values range: [{ei_values.min():.4f}, {ei_values.max():.4f}]")

# Expected Improvement with custom baseline
ei_values_custom, next_point_custom = model.EI(T=-2.0)  # Custom threshold
print(f"EI with custom baseline: {next_point_custom}")

何时使用:

  • 通用优化

  • 平衡探索-利用

  • 大多数研究应用

5.2.2. 对数期望提升#

对 EI 值应用对数变换以放大细微差异。

# logarithmic Expected Improvement
eilog_values, next_point_eilog = model.EI_log()
print(f"Logarithmic EI selected point: {next_point_eilog}")

# Compare with standard EI
print(f"Standard EI point: {next_point}")
print(f"Logarithmic EI point: {next_point_eilog}")

5.2.3. 带插件的期望提升#

使用模型对训练数据的预测作为基线,而不是实际的最佳观测值。

# Expected Improvement with Plugin
eip_values, next_point_eip = model.EI_plugin()
print(f"EI Plugin selected point: {next_point_eip}")

# Compare with standard EI
print(f"Standard EI point: {next_point}")
print(f"Plugin EI point: {next_point_eip}")

何时使用:

  • 当训练数据有噪声时

  • 模型预测比观测值更可靠时

5.2.4. 上置信界 (UCB)#

乐观方法,选择具有高预测均值加不确定性的点。

数学公式:

UCB(x) = μ(x) + α * σ(x)
# Upper Confidence Bound with different exploration parameters
ucb_conservative, point_conservative = model.UCB(alpha=1.0)  # Conservative
ucb_balanced, point_balanced = model.UCB(alpha=2.0)  # Balanced (default)
ucb_exploratory, point_exploratory = model.UCB(alpha=3.0)  # Exploratory

print("UCB Results:")
print(f"Conservative (α=1.0): {point_conservative}")
print(f"Balanced (α=2.0): {point_balanced}")
print(f"Exploratory (α=3.0): {point_exploratory}")

# Visualize the effect of alpha
import matplotlib.pyplot as plt

fig, axes = plt.subplots(1, 3, figsize=(15, 5))
alphas = [1.0, 2.0, 3.0]
titles = ['Conservative', 'Balanced', 'Exploratory']

for i, (alpha, title) in enumerate(zip(alphas, titles)):
    ucb_vals, _ = model.UCB(alpha=alpha)

    # Reshape for 2D plot (assuming square grid)
    grid_size = int(np.sqrt(len(ucb_vals)))
    ucb_grid = ucb_vals[:grid_size**2].reshape(grid_size, grid_size)

    im = axes[i].imshow(ucb_grid, extent=[-3, 3, -3, 3], origin='lower', cmap='viridis')
    axes[i].set_title(f'{title} (α={alpha})')
    axes[i].set_xlabel('x1')
    axes[i].set_ylabel('x2')
    plt.colorbar(im, ax=axes[i])

plt.tight_layout()
plt.show()

何时使用:

  • 噪声函数

  • 当您想要显式控制探索时

  • 多臂老虎机问题

5.2.5. 改进概率 (PoI)#

选择相对于当前最佳值具有最高改进概率的点。

数学公式:

PoI(x) = Φ((μ(x) - f* - τ) / σ(x))
# Probability of Improvement with different thresholds
poi_strict, point_strict = model.PoI(tao=0.0)  # Strict improvement
poi_relaxed, point_relaxed = model.PoI(tao=0.1)  # Allow small degradation
poi_very_relaxed, point_very_relaxed = model.PoI(tao=0.5)  # Very relaxed

print("PoI Results:")
print(f"Strict (τ=0.0): {point_strict}")
print(f"Relaxed (τ=0.1): {point_relaxed}")
print(f"Very Relaxed (τ=0.5): {point_very_relaxed}")

# Custom baseline
poi_custom, point_custom = model.PoI(tao=0.1, T=-1.5)
print(f"Custom baseline (T=-1.5): {point_custom}")

何时使用:

  • 当任何改进都有价值时

  • 风险规避优化

  • 概念验证研究

5.2.6. 增强期望提升 (AEI)#

EI 的增强版本,考虑噪声并使用更复杂的基线。

# Augmented Expected Improvement
aei_default, point_aei_default = model.Augmented_EI()
aei_custom, point_aei_custom = model.Augmented_EI(alpha=1.5, tao=0.1)

print("AEI Results:")
print(f"Default parameters: {point_aei_default}")
print(f"Custom (α=1.5, τ=0.1): {point_aei_custom}")

参数:

  • alpha:基线选择的权衡系数

  • tao:噪声标准差

何时使用:

  • 有噪声的实验数据

  • 当您想要更复杂的基线选择时

5.2.7. 期望分位数提升 (EQI)#

使用分位数而不是均值进行更稳健的优化。

# Expected Quantile Improvement
eqi_median, point_eqi_median = model.EQI(beta=0.5)  # Median
eqi_conservative, point_eqi_conservative = model.EQI(beta=0.25)  # 25th percentile
eqi_optimistic, point_eqi_optimistic = model.EQI(beta=0.75)  # 75th percentile

print("EQI Results:")
print(f"Median (β=0.5): {point_eqi_median}")
print(f"Conservative (β=0.25): {point_eqi_conservative}")
print(f"Optimistic (β=0.75): {point_eqi_optimistic}")

何时使用:

  • 稳健优化

  • 当您想要优化特定分位数时

  • 风险管理场景

5.2.8. 重插值期望提升 (REI)#

使用重插值值进行基线计算。

# Reinterpolation Expected Improvement
rei_values, point_rei = model.Reinterpolation_EI()
print(f"REI selected point: {point_rei}")

何时使用:

  • 当模型对训练数据的预测不可靠时

  • 迭代细化场景

5.2.9. 预测熵搜索 (PES)#

信息论方法,最大化关于最优值的信息增益。

# Predictive Entropy Search
pes_default, point_pes_default = model.PES()  # Default 100 samples
pes_high_precision, point_pes_high = model.PES(sam_num=500)  # Higher precision

print("PES Results:")
print(f"Default (100 samples): {point_pes_default}")
print(f"High precision (500 samples): {point_pes_high}")

何时使用:

  • 信息论优化

  • 当您想要最大化关于最优值的学习时

  • 学术研究

5.2.10. 知识梯度 (KG)#

估计每个潜在测量的信息价值。

# Knowledge Gradient
kg_fast, point_kg_fast = model.Knowledge_G(MC_num=1)  # Fast approximation
kg_accurate, point_kg_accurate = model.Knowledge_G(MC_num=5)  # More accurate

print("KG Results:")
print(f"Fast (1 MC sample): {point_kg_fast}")
print(f"Accurate (5 MC samples): {point_kg_accurate}")

# Parallel version (if supported)
try:
    kg_parallel, point_kg_parallel = model.Knowledge_G(MC_num=3, Proc_num=2)
    print(f"Parallel (2 processes): {point_kg_parallel}")
except:
    print("Parallel processing not available on this system")

何时使用:

  • 当测量成本变化时

  • 投资组合优化

  • 多保真度优化

何时使用:

  • 探索密集型场景

  • 多臂老虎机问题

  • 当您想要多样化的采样策略时

5.3. 序贯优化策略#

对于多个实验,通过更新模型使用序贯优化:

# Sequential optimization example
def sequential_optimization(model, n_iterations=3):
    """Perform sequential optimization."""
    results = []

    for i in range(n_iterations):
        print(f"\n=== Iteration {i+1} ===")

        # Get recommendation using EI
        ei_values, recommended_points = model.EI()
        next_point = recommended_points[0]

        print(f"Recommended point: {next_point}")

        # Simulate experiment (replace with actual experiment)
        # For demo, we'll use the true function
        simulated_result = -(next_point[0]**2 + next_point[1]**2) + 0.1 * np.random.randn()

        results.append({
            'iteration': i+1,
            'point': next_point,
            'result': simulated_result
        })

        print(f"Experimental result: {simulated_result:.4f}")

        # In practice, you would retrain the model with new data here
        # model = retrain_with_new_data(model, next_point, simulated_result)

    return results

# Run sequential optimization
optimization_results = sequential_optimization(model, n_iterations=3)

5.4. 表 2.1:Bgolearn 中的完整采集函数#

序号

函数名称

方法调用

参数

返回格式

数学基础

主要用例

1

期望提升

model.EI(T=None)

T:基线阈值(float,可选)

(values, points)

EI(x) = (μ(x) - f*) × Φ(Z) + σ(x) × φ(Z)

通用优化

2

对数期望提升

model.EI_log(T=None)

T:基线阈值(float,可选)

(values, points)

EI_log(x) = log[(μ(x) - f*) × Φ(Z) + σ(x) × φ(Z)]

通用优化

3

带插件的 EI

model.EI_plugin()

(values, points)

使用模型预测基线的 EI

有噪声的实验数据

4

增强期望提升

model.Augmented_EI(alpha=1, tao=0)

alpha:权衡系数(float)
tao:噪声标准差(float)

(values, points)

考虑噪声的增强 EI

有噪声的优化问题

5

期望分位数提升

model.EQI(beta=0.5, tao_new=0)

beta:分位数水平(0-1)
tao_new:噪声标准差(float)

(values, points)

基于分位数的改进

稳健优化

6

重插值 EI

model.Reinterpolation_EI()

(values, points)

使用重插值基线的 EI

模型细化场景

7

上置信界

model.UCB(alpha=1)

alpha:探索权重(float)

(values, points)

UCB(x) = μ(x) ± α × σ(x)

高探索需求

8

改进概率

model.PoI(tao=0, T=None)

tao:改进阈值(float)
T:基线(float,可选)

(values, points)

PoI(x) = Φ((μ(x) - f* - τ) / σ(x))

风险规避优化

9

预测熵搜索

model.PES(sam_num=500)

sam_num:蒙特卡洛样本数(int)

(values, points)

信息论方法

最大信息增益

10

知识梯度

model.Knowledge_G(MC_num=1, Proc_num=None)

MC_num:MC 模拟次数(1-10)
Proc_num:处理器数(int,可选)

(values, points)

信息价值估计

多保真度优化

11

Thompson 采样

model.Thompson_sampling()

(point, value, uncertainty)

后验采样

多样化探索策略

5.4.1. 函数类别#

5.4.1.1. 基于改进的函数#

  • EI, EI_log, EI_plugin, Augmented_EI, EQI, Reinterpolation_EI:关注相对于当前最佳值的期望提升

  • 数学基础:基于改进概率和幅度

  • 最适合:通用优化、有噪声数据、稳健优化

5.4.1.2. 基于置信度的函数#

  • UCB, PoI:基于置信界限和改进概率

  • 数学基础:统计置信区间

  • 最适合:探索控制、风险管理

5.4.1.3. 信息论函数#

  • PES, Knowledge_G:最大化关于最优值的信息增益

  • 数学基础:熵和信息论

  • 最适合:学习函数、多保真度问题

5.4.1.4. 基于采样的函数#

  • Thompson_sampling:从后验进行概率采样

  • 数学基础:贝叶斯后验采样

  • 最适合:多样化探索、多臂老虎机

5.4.2. 表 2.2:参数详情和默认值#

函数

参数

类型

默认值

范围/选项

描述

效果

EI

T

float

None

任意 float 或 None

改进的基线阈值

更低的 T → 更多探索

EI_log

T

float

None

任意 float 或 None

改进的基线阈值

更低的 T → 更多探索

Augmented_EI

alpha

float

1

> 0

权衡系数

更高的 α → 更保守的基线

tao

float

0

≥ 0

噪声标准差

更高的 τ → 考虑更多噪声

EQI

beta

float

0.5

[0, 1]

分位数水平(0.5 = 中位数)

更低的 β → 更保守

tao_new

float

0

≥ 0

噪声标准差

更高的 τ → 更稳健

UCB

alpha

float

1

> 0

探索权重

更高的 α → 更多探索

PoI

tao

float

0

≥ 0

改进阈值

更高的 τ → 更容易满足

T

float

None

任意 float 或 None

基线阈值

自定义基线覆盖

PES

sam_num

int

500

> 0

蒙特卡洛样本数

更高 → 更准确,更慢

Knowledge_G

MC_num

int

1

1-10

蒙特卡洛模拟次数

更高 → 更准确,更慢

Proc_num

int

None

> 0 或 None

处理器数量

并行处理控制

5.4.3. 表 2.3:探索与利用特性#

函数

探索水平

利用水平

平衡类型

调节参数

EI

中等

中等

平衡

T(基线)

EI_log

中等

中等

平衡

T(基线)

EI_plugin

中等

中等

平衡

Augmented_EI

中高

中等

平衡+

alpha, tao

EQI

中等

中高

平衡

beta

Reinterpolation_EI

中等

中等

平衡

UCB

中低

探索为主

alpha

PoI

利用为主

tao

PES

探索为主

sam_num

Knowledge_G

中高

中等

平衡

MC_num

Thompson_sampling

探索为主

5.4.4. 快速选择指南#

对于初学者:从期望提升 (EI) 开始 - 它是最广泛使用和最容易理解的。

对于有噪声的数据:使用增强 EI 或带适当参数的 UCB

对于风险规避优化:使用改进概率 (PoI)

对于最大探索:使用高 alpha 的 UCBThompson 采样

对于信息论方法:使用 PES知识梯度

对于稳健优化:使用期望分位数提升 (EQI)

5.5. 表 2.4:完整使用示例#

# Complete demonstration of all acquisition functions
from Bgolearn import BGOsampling
import numpy as np
import pandas as pd

# Create sample optimization problem
def demonstrate_all_acquisition_functions():
    """Demonstrate all 10 acquisition functions in Bgolearn."""

    # Setup data
    np.random.seed(42)
    X_train = pd.DataFrame(np.random.randn(15, 2), columns=['x1', 'x2'])
    y_train = pd.Series(-(X_train['x1']**2 + X_train['x2']**2) + 0.1*np.random.randn(15))
    X_candidates = pd.DataFrame(np.random.randn(50, 2), columns=['x1', 'x2'])

    # Fit model
    optimizer = BGOsampling.Bgolearn()
    model = optimizer.fit(X_train, y_train, X_candidates, opt_num=1)

    print("All Bgolearn Acquisition Functions Demo")
    print("=" * 60)

    # 1. Expected Improvement
    print("\n1. Expected Improvement (EI)")
    ei_values, ei_point = model.EI()
    print(f"   Selected point: {ei_point[0]}")
    print(f"   EI range: [{ei_values.min():.4f}, {ei_values.max():.4f}]")

    # 2. EI with Plugin
    print("\n2. Expected Improvement with Plugin")
    eip_values, eip_point = model.EI_plugin()
    print(f"   Selected point: {eip_point[0]}")
    print(f"   EI Plugin range: [{eip_values.min():.4f}, {eip_values.max():.4f}]")

    # 3. Augmented EI
    print("\n3. Augmented Expected Improvement")
    aei_values, aei_point = model.Augmented_EI(alpha=1.5, tao=0.1)
    print(f"   Selected point: {aei_point[0]}")
    print(f"   AEI range: [{aei_values.min():.4f}, {aei_values.max():.4f}]")

    # 4. Expected Quantile Improvement
    print("\n4. Expected Quantile Improvement")
    eqi_values, eqi_point = model.EQI(beta=0.5, tao_new=0.05)
    print(f"   Selected point: {eqi_point[0]}")
    print(f"   EQI range: [{eqi_values.min():.4f}, {eqi_values.max():.4f}]")

    # 5. Reinterpolation EI
    print("\n5. Reinterpolation Expected Improvement")
    rei_values, rei_point = model.Reinterpolation_EI()
    print(f"   Selected point: {rei_point[0]}")
    print(f"   REI range: [{rei_values.min():.4f}, {rei_values.max():.4f}]")

    # 6. Upper Confidence Bound
    print("\n6. Upper Confidence Bound")
    ucb_values, ucb_point = model.UCB(alpha=2.0)
    print(f"   Selected point: {ucb_point[0]}")
    print(f"   UCB range: [{ucb_values.min():.4f}, {ucb_values.max():.4f}]")

    # 7. Probability of Improvement
    print("\n7. Probability of Improvement")
    poi_values, poi_point = model.PoI(tao=0.01)
    print(f"   Selected point: {poi_point[0]}")
    print(f"   PoI range: [{poi_values.min():.4f}, {poi_values.max():.4f}]")

    # 8. Predictive Entropy Search
    print("\n8. Predictive Entropy Search")
    pes_values, pes_point = model.PES(sam_num=100)
    print(f"   Selected point: {pes_point[0]}")
    print(f"   PES range: [{pes_values.min():.4f}, {pes_values.max():.4f}]")

    # 9. Knowledge Gradient
    print("\n9. Knowledge Gradient")
    kg_values, kg_point = model.Knowledge_G(MC_num=1)
    print(f"   Selected point: {kg_point[0]}")
    print(f"   KG range: [{kg_values.min():.4f}, {kg_values.max():.4f}]")

    # 10. Thompson Sampling (different return format)
    print("\n10. Thompson Sampling")
    ts_point, ts_value, ts_uncertainty = model.Thompson_sampling()
    print(f"   Selected point: {ts_point}")
    print(f"   Sampled value: {ts_value:.4f}")
    print(f"   Uncertainty: {ts_uncertainty:.4f}")

    print("\n" + "=" * 60)
    print("All 10 acquisition functions demonstrated successfully!")

# Run the demonstration
demonstrate_all_acquisition_functions()

5.6. 比较采集函数#

# Compare all acquisition functions
def compare_acquisition_functions(model):
    """Compare different acquisition functions."""
    results = {}

    # Standard acquisition functions (return values, points)
    methods = {
        'EI': lambda: model.EI(),
        'EI_Plugin': lambda: model.EI_plugin(),
        'Augmented_EI': lambda: model.Augmented_EI(),
        'EQI': lambda: model.EQI(beta=0.5),
        'Reinterpolation_EI': lambda: model.Reinterpolation_EI(),
        'UCB': lambda: model.UCB(alpha=2.0),
        'PoI': lambda: model.PoI(tao=0.01),
        'PES': lambda: model.PES(sam_num=100),
        'Knowledge_G': lambda: model.Knowledge_G(MC_num=1)
    }

    # Thompson Sampling (different return format)
    ts_methods = {
        'Thompson_Sampling': lambda: model.Thompson_sampling()
    }

    for name, method in methods.items():
        try:
            values, point = method()
            results[name] = {
                'point': point[0] if len(point.shape) > 1 else point,
                'max_value': values.max(),
                'mean_value': values.mean(),
                'std_value': values.std()
            }
        except Exception as e:
            print(f"Error with {name}: {e}")
            results[name] = None

    # Handle Thompson Sampling separately (different return format)
    for name, method in ts_methods.items():
        try:
            point, value, uncertainty = method()
            results[name] = {
                'point': point,
                'sampled_value': value,
                'uncertainty': uncertainty
            }
        except Exception as e:
            print(f"Error with {name}: {e}")
            results[name] = None

    return results

# Run comparison
comparison = compare_acquisition_functions(model)

# Display results
print("Acquisition Function Comparison:")
print("-" * 70)
for name, result in comparison.items():
    if result:
        print(f"{name:15s}: Point={result['point']}")
        if 'max_value' in result:
            print(f"                Max={result['max_value']:.4f}, "
                  f"Mean={result['mean_value']:.4f}, "
                  f"Std={result['std_value']:.4f}")
        elif 'sampled_value' in result:
            print(f"                Sampled Value={result['sampled_value']:.4f}, "
                  f"Uncertainty={result['uncertainty']:.4f}")
    else:
        print(f"{name:15s}: Failed")
    print()

5.7. 可视化采集函数#

import matplotlib.pyplot as plt
import numpy as np

# Basic visualization using matplotlib

# Example: 1D acquisition function visualization
def visualize_1d_acquisition():
    """Visualize acquisition functions for 1D problems."""
    from Bgolearn import BGOsampling
    import pandas as pd

    # Create 1D test problem
    x_1d = np.linspace(-3, 3, 100).reshape(-1, 1)
    y_1d = -(x_1d.flatten() - 1)**2 + 0.1 * np.random.randn(100)

    # Select training points
    train_indices = np.random.choice(100, 10, replace=False)
    X_train_1d = x_1d[train_indices]
    y_train_1d = y_1d[train_indices]

    # Fit model
    optimizer_1d = BGOsampling.Bgolearn()
    model_1d = optimizer_1d.fit(
        pd.DataFrame(X_train_1d, columns=['x']),
        pd.Series(y_train_1d),
        pd.DataFrame(x_1d, columns=['x']),
        min_search=False
    )

    # Get acquisition values
    ei_vals, ei_point = model_1d.EI()

    # Create custom plot
    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8))

    # Plot 1: Objective function and model
    x_plot = x_1d.flatten()
    ax1.plot(x_plot, y_1d, 'b-', alpha=0.3, label='True function')
    ax1.scatter(X_train_1d.flatten(), y_train_1d, c='red', s=50, label='Training data')
    ax1.plot(x_plot, model_1d.virtual_samples_mean, 'g-', label='GP mean')
    ax1.fill_between(x_plot,
                     model_1d.virtual_samples_mean - model_1d.virtual_samples_std,
                     model_1d.virtual_samples_mean + model_1d.virtual_samples_std,
                     alpha=0.2, color='green', label='GP uncertainty')
    ax1.axvline(x=ei_point[0], color='orange', linestyle='--', label='Next point')
    ax1.set_ylabel('Objective Value')
    ax1.set_title('Gaussian Process Model')
    ax1.legend()
    ax1.grid(True)

    # Plot 2: Acquisition function
    ax2.plot(x_plot, ei_vals, 'purple', linewidth=2, label='Expected Improvement')
    ax2.axvline(x=ei_point[0], color='orange', linestyle='--', label='Next point')
    ax2.set_xlabel('x')
    ax2.set_ylabel('EI Value')
    ax2.set_title('Expected Improvement Acquisition Function')
    ax2.legend()
    ax2.grid(True)

    plt.tight_layout()
    plt.show()

# Run 1D visualization
visualize_1d_acquisition()

5.8. 选择正确的采集函数#

5.8.1. 决策树#

您是否在进行并行实验?
├─ 是 → 使用 batch_EI() 或 batch_UCB()
└─ 否 → 继续下面

您的函数是否有很大噪声?
├─ 是 → 使用 UCB(高 α)或 AEI
└─ 否 → 继续下面

您想要平衡探索/利用吗?
├─ 是 → 使用 EI(大多数情况下推荐)
└─ 否 → 继续下面

您想要更多探索吗?
├─ 是 → 使用 UCB(高 α)或 PES
└─ 否 → 使用 PoI 或 EQI

5.8.2. 性能特征#

函数

探索

利用

噪声鲁棒性

计算成本

EI

中等

中等

中等

UCB

PoI

AEI

中等

中等

中等

EQI

中等

中等

中等

REI

中等

中等

中等

中等

PES

中等

KG

中等

中等

中等

5.9. 高级技巧#

5.9.1. 自定义采集函数#

# You can implement custom acquisition functions
class CustomAcquisition:
    def __init__(self, model, X_train, y_train):
        self.model = model
        self.X_train = X_train
        self.y_train = y_train
        self.current_best = y_train.max()  # For maximization

    def custom_ei_variant(self, X_candidates, beta=1.0):
        """Custom EI variant with additional parameter."""
        mean, std = self.model.fit_pre(self.X_train, self.y_train, X_candidates)

        improvement = mean - self.current_best
        z = improvement / (std + 1e-9)

        # Custom modification: add beta parameter
        ei = improvement * norm.cdf(z) + beta * std * norm.pdf(z)
        return np.maximum(ei, 0)

# Usage would require integration with the main framework

5.9.2. 参数调优#

# Systematic parameter exploration
def tune_acquisition_parameters():
    """Tune acquisition function parameters."""

    # UCB alpha tuning
    alphas = [0.5, 1.0, 1.5, 2.0, 2.5, 3.0]
    ucb_results = {}

    for alpha in alphas:
        ucb_vals, point = model.UCB(alpha=alpha)
        ucb_results[alpha] = {
            'point': point,
            'max_acquisition': ucb_vals.max()
        }

    print("UCB Alpha Tuning:")
    for alpha, result in ucb_results.items():
        print(f"α={alpha}: max_acq={result['max_acquisition']:.4f}")

    # PoI tau tuning
    taus = [0.0, 0.01, 0.05, 0.1, 0.2]
    poi_results = {}

    for tau in taus:
        poi_vals, point = model.PoI(tao=tau)
        poi_results[tau] = {
            'point': point,
            'max_acquisition': poi_vals.max()
        }

    print("\nPoI Tau Tuning:")
    for tau, result in poi_results.items():
        print(f"τ={tau}: max_acq={result['max_acquisition']:.4f}")

tune_acquisition_parameters()