PathSpec-ICLR / scripts /opt_tree.py
Rayleihaodong's picture
Add files using upload-large-folder tool
aaebaab verified
Raw
History Blame Contribute Delete
1.97 kB
import numpy as np
from scipy.optimize import minimize
# 参数
p = np.array([0.8, 0.5, 0.3, 0.2, 0.12, 0.07])
q = 1 - p # 失效概率
N_total = 80
def objective(n):
"""目标函数:Σ n_i * [1 - q_i^{n_i}]"""
return np.sum(n * (1 - q**n))
# 约束条件
constraints = [
{'type': 'eq', 'fun': lambda n: np.sum(n) - N_total},
{'type': 'ineq', 'fun': lambda n: n-1} # n_i >= 0
]
# 初始猜测(均匀分配)
n0 = np.ones(6) * N_total / 6
n0 = np.maximum(n0, 1) # 确保初始值 >=1
# 优化(使用连续实数)
res = minimize(lambda n: -objective(n), n0,
constraints=constraints,
bounds=[(0, N_total)]*6,
method='SLSQP',
options={'maxiter': 50, # 修改最大迭代次数为 20(原默认 100)
'ftol': 1e-6, # 函数容差(可调小到 1e-8 以增加迭代)
'disp': True}) # 打印迭代日志)
n_opt = res.x
max_value = objective(n_opt)
print("最优节点分配(连续解):")
for i in range(6):
print(f"层 {i+1}: {n_opt[i]:.2f} 个节点")
print(f"\n最大值: {max_value:.4f}")
# 检查整数解
from itertools import product
import math
# 搜索附近整数解(简单网格)
def integer_search(center, radius=2):
best_val = -1
best_n = None
# 生成附近整数组合
ranges = [range(max(0, int(center[i])-radius),
int(center[i])+radius+1) for i in range(6)]
# 限制组合数量,实际可更精细
for combo in product(*ranges):
if sum(combo) == N_total and all(x >= 0 for x in combo):
val = objective(np.array(combo))
if val > best_val:
best_val = val
best_n = combo
return best_n, best_val
int_n, int_val = integer_search(n_opt, radius=3)
print("\n近似最优整数解:")
for i in range(6):
print(f"层 {i+1}: {int_n[i]} 个节点")
print(f"整数值: {int_val:.4f}")