from sklearn.tree import DecisionTreeRegressorfrom sklearn.tree import plot_treeregr = DecisionTreeRegressor(max_leaf_nodes=4, # 最大叶结点数量 min_samples_leaf=3) # 每个结点最小样本数regr.fit(precip, demand)mu, index, counts = np.unique(regr.predict(precip), axis=0, return_inverse=True, return_counts=True) # conditional meanw = counts/precip.shape[0] # 场景权重 phi = np.array([demand.values[index==i].var(axis=0) for i in range(len(counts))]) # conditional varianced_ub = np.array([demand.values[index==i].max(axis=0) for i in range(len(counts))]) # upper bound of each scenariod_lb = np.array([demand.values[index==i].min(axis=0) for i in range(len(counts))]) # lower bound of each scenarioplt.figure(figsize=(20, 10)) # 回归树可视化plot_tree(regr, rounded=True, feature_names=demand.columns, fontsize=13)plt.show()
# 可视化不同场景下不同地区的需求分布情况fig = plt.figure(figsize=(10, 4))gs = fig.add_gridspec(1, 4, hspace=0, wspace=0)axes = gs.subplots(sharey='row')for i in range(4): each_demand = demand.values[index==i] axes[i].boxplot(each_demand, vert=False, flierprops={'markersize': 4}) axes[i].set_yticks(list(range(1, 11)), ['Region{0}'.format(i) for i in range(1, 11)], fontsize=11) axes[i].set_xlabel('Demand', fontsize=12) axes[i].set_title('Sample size: {0}'.format(each_demand.shape[0]), fontsize=13)axes[3].set_ylim(10.5, 0.5)plt.show()
基于由场景均值和方差定义的模糊集𝐹,分布鲁棒模型的实现如下
from rsome import dro # import the dro modulefrom rsome import square # import the element-wise square functionfrom rsome import E # import the notion of expectationfrom rsome import eco_solver as eco # import the ECOS interfaceS = len(w) # number of scenariosmodel = dro.Model(S) # create a DRO model with S scenariosd = model.rvar(J) # random demand as the variable du = model.rvar(J) # auxiliary random variable ufset = model.ambiguity() # create an ambiguity setfor s in range(S): # for each scenario: fset[s].exptset(E(d) == mu[s], # specify the expectation set of d and u E(u) <= phi[s]) fset[s].suppset(d >= d_lb[s], # specify the support of d and u d <= d_ub[s], square(d - mu[s]) <= u)pr = model.p # an array of scenario probabilitiesfset.probset(pr == w) # w as scenario weightsx = model.dvar((I, J)) # here-and-now decision xy = model.dvar(J) # wait-and-see decision yy.adapt(d) # y affinely adapts to dy.adapt(u) # y affinely adapts to ufor s in range(S): # for each scenario: y.adapt(s) # affine adaptation of y is differentmodel.minsup(((c-r)*x).sum() + E(r@y), fset) # minimize the worst-case objectivemodel.st(y >= x.sum(axis=0) - d, y >= 0) # robust constraintsmodel.st(x >= 0, x.sum(axis=0) <= q) # deterministic constraintsmodel.solve(eco) # solve the model by ECOSstatus = model.solution.status # return the solution statustime = model.solution.time # return the solution timeobjval = model.get() # get the optimal objective valuex_sol = x.get() # get the optimal solution