def setUp(self): ndim = 3 nt = 100 ne = 100 ncomp = 1 problems = OrderedDict() problems['exp'] = TensorProduct(ndim=ndim, func='exp') problems['tanh'] = TensorProduct(ndim=ndim, func='tanh') problems['cos'] = TensorProduct(ndim=ndim, func='cos') sms = OrderedDict() sms['LS'] = LS() sms['QP'] = QP() sms['KRG'] = KRG(theta0=[1e-2] * ndim) sms['KPLS'] = KPLS(theta0=[1e-2] * ncomp, n_comp=ncomp) sms['KPLSK'] = KPLSK(theta0=[1] * ncomp, n_comp=ncomp) sms['GEKPLS'] = GEKPLS(theta0=[1e-2] * ncomp, n_comp=ncomp, delta_x=1e-1) if compiled_available: sms['IDW'] = IDW() sms['RBF'] = RBF() sms['RMTC'] = RMTC() sms['RMTB'] = RMTB() t_errors = {} t_errors['LS'] = 1.0 t_errors['QP'] = 1.0 t_errors['KRG'] = 1e-5 t_errors['KPLS'] = 1e-5 t_errors['KPLSK'] = 1e-5 t_errors['GEKPLS'] = 1e-5 if compiled_available: t_errors['IDW'] = 1e-15 t_errors['RBF'] = 1e-2 t_errors['RMTC'] = 1e-1 t_errors['RMTB'] = 1e-1 e_errors = {} e_errors['LS'] = 1.5 e_errors['QP'] = 1.5 e_errors['KRG'] = 1e-2 e_errors['KPLS'] = 1e-2 e_errors['KPLSK'] = 1e-2 e_errors['GEKPLS'] = 1e-2 if compiled_available: e_errors['IDW'] = 1e0 e_errors['RBF'] = 1e0 e_errors['RMTC'] = 2e-1 e_errors['RMTB'] = 2e-1 self.nt = nt self.ne = ne self.ndim = ndim self.problems = problems self.sms = sms self.t_errors = t_errors self.e_errors = e_errors
class RBF_smt(surrogate_model): def __init__(self, d0=1): super().__init__() self.rbf_sm = RBF(d0=d0) def train(self, X_train, y_train): self.rbf_sm.set_training_values(X_train, y_train) self.rbf_sm.train() def calculate(self, X): """ :param X: numpy array, with shape(number,dimension) """ X = self.normalize_X(X) y = self.rbf_sm.predict_values(X) y = self.inverse_normalize_y(y) return y
def rBF(xt, yt, xtest, ytest): t = RBF(print_prediction=False, poly_degree=0) t.set_training_values(xt, yt) t.train() # Prediction of the validation points y = t.predict_values(xtest) print('RBF, err: ' + str(compute_rms_error(t, xtest, ytest))) # Plot prediction/true values title = 'RBF model' return t, title, xtest, ytest
def setUp(self): ndim = 2 self.nt = 50 self.ne = 10 self.problem = Sphere(ndim=ndim) self.sms = sms = OrderedDict() if compiled_available: sms['IDW'] = IDW() sms['RBF'] = RBF() sms['RMTB'] = RMTB(regularization_weight=1e-8, nonlinear_maxiter=100, solver_tolerance=1e-16) sms['RMTC'] = RMTC(regularization_weight=1e-8, nonlinear_maxiter=100, solver_tolerance=1e-16)
def setUp(self): ndim = 2 nt = 5000 ne = 100 problems = OrderedDict() problems['sphere'] = Sphere(ndim=ndim) sms = OrderedDict() if compiled_available: sms['RBF'] = RBF() sms['RMTC'] = RMTC() sms['RMTB'] = RMTB() self.nt = nt self.ne = ne self.problems = problems self.sms = sms
def setUp(self): ndim = 2 nt = 5000 ne = 100 problems = OrderedDict() problems["sphere"] = Sphere(ndim=ndim) sms = OrderedDict() if compiled_available: sms["RBF"] = RBF() sms["RMTC"] = RMTC() sms["RMTB"] = RMTB() sms["MFK"] = MFK(theta0=[1e-2] * ndim) self.nt = nt self.ne = ne self.problems = problems self.sms = sms
def setUp(self): ndim = 2 nt = 5000 ne = 100 problems = OrderedDict() problems['sphere'] = Sphere(ndim=ndim) sms = OrderedDict() if compiled_available: sms['RBF'] = RBF() sms['RMTC'] = RMTC() sms['RMTB'] = RMTB() sms['MFK'] = MFK(theta0=[1e-2] * ndim, eval_noise=True) self.nt = nt self.ne = ne self.problems = problems self.sms = sms
def setUp(self): ndim = 10 nt = 500 ne = 100 problems = OrderedDict() problems["sphere"] = Sphere(ndim=ndim) problems["exp"] = TensorProduct(ndim=ndim, func="exp") problems["tanh"] = TensorProduct(ndim=ndim, func="tanh") problems["cos"] = TensorProduct(ndim=ndim, func="cos") sms = OrderedDict() sms["LS"] = LS() sms["QP"] = QP() sms["KRG"] = KRG(theta0=[4e-1] * ndim) sms["KPLS"] = KPLS() if compiled_available: sms["IDW"] = IDW() sms["RBF"] = RBF() t_errors = {} t_errors["LS"] = 1.0 t_errors["QP"] = 1.0 t_errors["KRG"] = 1e-4 t_errors["IDW"] = 1e-15 t_errors["RBF"] = 1e-2 t_errors["KPLS"] = 1e-3 e_errors = {} e_errors["LS"] = 2.5 e_errors["QP"] = 2.0 e_errors["KRG"] = 2.0 e_errors["IDW"] = 4 e_errors["RBF"] = 2 e_errors["KPLS"] = 2.5 self.nt = nt self.ne = ne self.problems = problems self.sms = sms self.t_errors = t_errors self.e_errors = e_errors
def setUp(self): ndim = 10 nt = 500 ne = 100 problems = OrderedDict() problems['sphere'] = Sphere(ndim=ndim) problems['exp'] = TensorProduct(ndim=ndim, func='exp') problems['tanh'] = TensorProduct(ndim=ndim, func='tanh') problems['cos'] = TensorProduct(ndim=ndim, func='cos') sms = OrderedDict() sms['LS'] = LS() sms['QP'] = QP() sms['KRG'] = KRG(theta0=[4e-1]*ndim) if compiled_available: sms['IDW'] = IDW() sms['RBF'] = RBF() t_errors = {} t_errors['LS'] = 1.0 t_errors['QP'] = 1.0 t_errors['KRG'] = 1e-6 t_errors['IDW'] = 1e-15 t_errors['RBF'] = 1e-2 e_errors = {} e_errors['LS'] = 2.5 e_errors['QP'] = 2.0 e_errors['KRG'] = 2.0 e_errors['IDW'] = 1.5 e_errors['RBF'] = 1.5 self.nt = nt self.ne = ne self.problems = problems self.sms = sms self.t_errors = t_errors self.e_errors = e_errors
class SurrogateModelSMT(SurrogateModelPredict): def __init__(self, problem): super().__init__(problem) self.train_step = -1 self.sigma_threshold = 10 self.score_threshold = 0.5 def init_default_regressor(self): # default regressor self.regressor = RBF(d0=5, print_prediction=False) self.has_epsilon = False def predict(self, x, *args): if self.trained: return self.regressor.predict_values(np.array([x])) else: assert 0 def predict_variances(self, x, *args): if self.trained: return self.regressor.predict_variances(np.array([x]), *args) else: assert 0 def train(self): self.trained = False assert(len(self.x_data) == len(self.y_data)) # print(self.x_data) # print("Trained set: {}".format(len(self.x_data))) self.regressor.options["print_global"] = False self.regressor.set_training_values(np.array(self.x_data), np.array(self.y_data)) self.regressor.train() if self.eval_stats: # score pass # self.score = self.regressor.score(self.x_data, self.y_data) # print("self.score = {} : {}".format(len(self.x_data), self.score)) # lml (Gaussian regressor) # if "log_marginal_likelihood" in dir(self.regressor): # self.lml, self.lml_gradient = self.regressor.log_marginal_likelihood(self.regressor.kernel_.theta, eval_gradient=True) self.trained = True
def train(self, train_method, **kwargs): """Trains the surrogate model with given training data. Parameters ---------- train_method : str Training method among ``IDW``, ``KPLS``, ``KPLSK``, ``KRG``, ``LS``, ``QP``, ``RBF``, ``RMTB``, ``RMTC`` kwargs : dict Additional keyword arguments supported by SMT objects """ if train_method == 'IDW': self.trained = IDW(**kwargs) elif train_method == 'KPLS': self.trained = KPLS(**kwargs) elif train_method == 'KPLSK': self.trained = KPLSK(**kwargs) elif train_method == 'KRG': self.trained = KRG(**kwargs) elif train_method == 'LS': self.trained = LS(**kwargs) elif train_method == 'QP': self.trained = QP(**kwargs) elif train_method == 'RBF': self.trained = RBF(**kwargs) elif train_method == 'RMTB': self.trained = RMTB(xlimits=self.limits, **kwargs) elif train_method == 'RMTC': self.trained = RMTC(xlimits=self.limits, **kwargs) else: raise ValueError( 'train_method must be one between IDW, KPLS, KPLSK, KRG, LS, QP, RBF, RMTB, RMTC' ) self.trained.set_training_values(self.x_samp, self.m_prop) self.trained.train()
def test_rbf(self): import numpy as np import matplotlib.pyplot as plt from smt.surrogate_models import RBF xt = np.array([0., 1., 2., 3., 4.]) yt = np.array([0., 1., 1.5, 0.5, 1.0]) sm = RBF(d0=5) sm.set_training_values(xt, yt) sm.train() num = 100 x = np.linspace(0., 4., num) y = sm.predict_values(x) plt.plot(xt, yt, 'o') plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.legend(['Training data', 'Prediction']) plt.show()
def test_rbf(self): import numpy as np import matplotlib.pyplot as plt from smt.surrogate_models import RBF xt = np.array([0.0, 1.0, 2.0, 3.0, 4.0]) yt = np.array([0.0, 1.0, 1.5, 0.5, 1.0]) sm = RBF(d0=5) sm.set_training_values(xt, yt) sm.train() num = 100 x = np.linspace(0.0, 4.0, num) y = sm.predict_values(x) plt.plot(xt, yt, "o") plt.plot(x, y) plt.xlabel("x") plt.ylabel("y") plt.legend(["Training data", "Prediction"]) plt.show()
def __init__(self, d0=1): super().__init__() self.rbf_sm = RBF(d0=d0)
def realXYZ(): # 预测值 start = time.perf_counter() # 更换样本点时,这里要改 # d = np.array([-30, -22, -13, -5, 0, 5, 13, 22, 30]) forceArr = [10, 20, 30] degreeArr = [30, 45, 60] combine = [] for iForce in range(len(forceArr)): for iDegree in range(len(degreeArr)): combine.append((forceArr[iForce], degreeArr[iDegree])) d = np.array(combine, dtype=np.float) d_pred_1 = np.array([[15, 37.5]]) d_pred_2 = np.array([[15, 52.5]]) d_pred_3 = np.array([[25, 37.5]]) d_pred_4 = np.array([[25, 52.5]]) # list_w_y = [] # list_w_z = [] list_w_stress = [] # list_w_dSum = [] # list_w_y = '' # list_w_z = '' # list_w_stress = '' # list_w_dSum = '' # stds = '' list_pred = [] list_pred_1 = [] list_pred_2 = [] list_pred_3 = [] list_pred_4 = [] length = len(list_stress) for i in range(length): # for i in range(1): # 取得list_x, list_y, list_z中每个元素不包含原始坐标值的数值 # y_real = list_y # z_real = list_z stress_real = np.array(list_stress[i], dtype=np.float) rbfnet_stress = RBF(print_global=False) w_stress = rbfnet_stress.set_training_values(d, stress_real) rbfnet_stress.train() # w_dSum = rbfnet_dSum.fit(d, dSum_real) # stds = str(rbfnet_y.std) # x_pred = rbfnet_x.predict(d_pred) # y_pred = rbfnet_y.predict(d_pred) # z_pred = rbfnet_z.predict(d_pred) stress_pred_1 = rbfnet_stress.predict_values(d_pred_1) stress_pred_2 = rbfnet_stress.predict_values(d_pred_2) stress_pred_3 = rbfnet_stress.predict_values(d_pred_3) stress_pred_4 = rbfnet_stress.predict_values(d_pred_4) list_pred.append([ stress_pred_1[0], stress_pred_2[0], stress_pred_3[0], stress_pred_4[0] ]) list_pred_1.append(stress_pred_1) list_pred_2.append(stress_pred_2) list_pred_3.append(stress_pred_3) list_pred_4.append(stress_pred_4) list_w_stress.append(w_stress) print("\r程序当前已完成:" + str(round(i / len(list_stress) * 10000) / 100) + '%', end="") arr_train_1 = np.array(list_train_1) arr_train_2 = np.array(list_train_2) arr_train_3 = np.array(list_train_3) arr_train_4 = np.array(list_train_4) arr_train = np.array(list_train) arr_pred_1 = np.array(list_pred_1).flatten() arr_pred_2 = np.array(list_pred_2).flatten() arr_pred_3 = np.array(list_pred_3).flatten() arr_pred_4 = np.array(list_pred_4).flatten() arr_pred = np.array(list_pred) dd = np.arange(1, 401) list_RR = [] for i in range(arr_train.shape[0]): RR = 1 - (np.sum(np.square(arr_pred[i] - arr_train[i])) / np.sum(np.square(arr_pred[i] - np.mean(arr_pred[i])))) list_RR.append(RR) plt.figure() fig, axs = plt.subplots(nrows=4, ncols=2, figsize=(20, 20)) zz = arr_train_1 zz1 = arr_train_2 zz2 = arr_train_3 zz3 = arr_train_4 zz4 = arr_pred_1 zz5 = arr_pred_2 zz6 = arr_pred_3 zz7 = arr_pred_4 cha_1 = np.abs((arr_train_1 - arr_pred_1) / arr_train_1) cha_2 = np.abs((arr_train_2 - arr_pred_2) / arr_train_2) cha_3 = np.abs((arr_train_3 - arr_pred_3) / arr_train_3) cha_4 = np.abs((arr_train_4 - arr_pred_4) / arr_train_4) zz_list = [[zz, zz4], cha_1, [zz1, zz5], cha_2, [zz2, zz6], cha_3, [zz3, zz7], cha_4] # print(min(arr_x), max(arr_x)) # print(min(arr_y), max(arr_y)) X = np.linspace(min(arr_x) - 1, max(arr_x) + 1, 100) X_bianyi = np.array(list(map(lambda x: x + 11, X))) Y = np.linspace(min(arr_y) - 1, max(arr_y) + 1, 100) # # print(arr_xy.shape) # 广播为100*100的一个面信息 grid_X, grid_Y = np.meshgrid(X, Y) grid_X_bianyi, grid_Y_bianyi = np.meshgrid(X_bianyi, Y) title = [ '15 37.5', '15 37.5', '15 52.5', '15 52.5', '25 37.5', '25 37.5', '25 52.5', '25 52.5' ] for ax, z, i, t in zip(axs.flat, zz_list, range(len(zz_list)), title): if (i + 1) % 2 == 0: zz = griddata(arr_xy, z, xi=(grid_X, grid_Y), method='cubic') ax_subplt = ax.contourf(grid_X, grid_Y, zz, levels=100, cmap='jet') fig.colorbar(ax_subplt, ax=ax) ax.set_title('|(real-predict)/real| ' + t) else: # method=nearest/linear/cubic 将数据变为插值 zz1 = griddata(arr_xy, z[0], xi=(grid_X, grid_Y), method='cubic') zz2 = griddata(arr_xy_bianyi, z[1], xi=(grid_X_bianyi, grid_Y_bianyi), method='cubic') ax_subplt1 = ax.contourf(grid_X, grid_Y, zz1, levels=100, cmap='jet') ax_subplt2 = ax.contourf(grid_X_bianyi, grid_Y_bianyi, zz2, levels=100, cmap='jet') ax.set_title('left(real) right(predict) ' + t) fig.colorbar(ax_subplt2, ax=ax) nn1 = np.array(list_RR) plt.figure() print(nn1) fig, axs2 = plt.subplots(nrows=1, ncols=1, figsize=(20, 20)) zzr = griddata(arr_xy, nn1, xi=(grid_X, grid_Y), method='cubic') ax_subplt = axs2.contourf(grid_X, grid_Y, zzr, levels=100, cmap='jet') fig.colorbar(ax_subplt, ax=axs2) axs2.set_title('r2') # zz = np.mat(zz) # zz, zz1 = np.meshgrid(arr_train_1, arr_train_1) # xx, xx1 = np.meshgrid(arr_x, arr_x) # yy, yy = np.meshgrid(arr_y, arr_y) # print(xx.shape) # plt.figure() # plt.plot(dd, np.array(list_RR), color='#ff0000', linestyle='-', linewidth=0.5, # label='z-real') # plt.title('R2') # plt.figure() # plt.plot(dd, arr_pred_1, color='#ff0000', linestyle='--', linewidth=0.5, # label='stress_predict') # plt.plot(dd, arr_train_1, color='#0000ff', linestyle='-', linewidth=0.5, # label='stress_real') # plt.title('force=' + str(d_pred_1[0][0]) + ' degree=' + str(d_pred_1[0][1])) # plt.figure() # plt.plot(dd, arr_pred_2, color='#ff0000', linestyle='--', linewidth=0.5, # label='stress_predict') # plt.plot(dd, arr_train_2, color='#0000ff', linestyle='-', linewidth=0.5, # label='stress_real') # plt.title('force=' + str(d_pred_2[0][0]) + ' degree=' + str(d_pred_2[0][1])) # plt.figure() # plt.plot(dd, arr_pred_3, color='#ff0000', linestyle='--', linewidth=0.5, # label='stress_predict') # plt.plot(dd, arr_train_3, color='#0000ff', linestyle='-', linewidth=0.5, # label='stress_real') # plt.title('force=' + str(d_pred_3[0][0]) + ' degree=' + str(d_pred_3[0][1])) # plt.figure() # plt.plot(dd, arr_pred_4, color='#ff0000', linestyle='--', linewidth=0.5, # label='stress_predict') # plt.plot(dd, arr_train_4, color='#0000ff', linestyle='-', linewidth=0.5, # label='stress_real') # plt.title('force=' + str(d_pred_4[0][0]) + ' degree=' + str(d_pred_4[0][1])) # plt.legend() # plt.show() # Text_Create('y_pre', ','.join(map(str, list_w_y)) + ',' + stds, 'hex') # Text_Create('z_pre', ','.join(map(str, list_w_z)), 'hex') # Text_Create('stress_pre', ','.join(map(str, list_w_stress)), 'hex') # Text_Create('dSum_pre', ','.join(map(str, list_w_dSum)), 'hex') # print('\n'.join(list_w_y) + '\n' + stds + '\n' + ','.join(map(str, list(d))) + '\n' + rbf_type['y']) # 一般用这个 # Text_Create('y_pred_list', '\n'.join(list_w_y), 'four') # Text_Create('y_pred_list', # '\n'.join(list_w_y) + '\n' + stds + '\n' + ','.join(map(str, list(d))) + '\n' + rbf_type['y'], # 'four') # Text_Create('z_pred_list', '\n'.join(list_w_z) + '\n' + rbf_type['z'], 'four') # Text_Create('stress_pred_list', '\n'.join(list_w_stress) + '\n' + rbf_type['stress'], 'four') # Text_Create('dSum_pred_list', '\n'.join(list_w_dSum) + '\n' + rbf_type['dSum'], 'four') # Text_Create('y_pred_list', '\n'.join(list_w_y) + '\n' + stds, 'hex') # Text_Create('z_pred_list', '\n'.join(list_w_z), 'hex') # Text_Create('stress_pred_list', '\n'.join(list_w_stress), 'hex') # Text_Create('dSum_pred_list', '\n'.join(list_w_dSum), 'hex') # Text_Create('y_pre_str', list_w_y + stds, 'hex') # Text_Create('z_pre_str', list_w_z.rstrip('\n'), 'hex') # Text_Create('stress_pre_str', list_w_stress.rstrip('\n'), 'hex') # Text_Create('dSum_pre_str', list_w_dSum.rstrip('\n'), 'hex') # plt.plot(d_pred, Duplicated_list(list_zAll, 'coords'), color='#000000', marker='+', linestyle='-.') # plt.plot(d_pred, Duplicated_list(list_stressAll, 'stress'), color='#000000', marker='+', linestyle='-.') # plt.legend() plt.tight_layout() plt.show() elapsed = (time.perf_counter() - start) print("Time used:", elapsed)
def setUp(self): ndim = 3 nt = 100 ne = 100 ncomp = 1 problems = OrderedDict() problems["exp"] = TensorProduct(ndim=ndim, func="exp") problems["tanh"] = TensorProduct(ndim=ndim, func="tanh") problems["cos"] = TensorProduct(ndim=ndim, func="cos") sms = OrderedDict() sms["LS"] = LS() sms["QP"] = QP() sms["KRG"] = KRG(theta0=[1e-2] * ndim) sms["MFK"] = MFK(theta0=[1e-2] * ndim) sms["KPLS"] = KPLS(theta0=[1e-2] * ncomp, n_comp=ncomp) sms["KPLSK"] = KPLSK(theta0=[1] * ncomp, n_comp=ncomp) sms["GEKPLS"] = GEKPLS(theta0=[1e-2] * ncomp, n_comp=ncomp, delta_x=1e-1) sms["GENN"] = genn() if compiled_available: sms["IDW"] = IDW() sms["RBF"] = RBF() sms["RMTC"] = RMTC() sms["RMTB"] = RMTB() t_errors = {} t_errors["LS"] = 1.0 t_errors["QP"] = 1.0 t_errors["KRG"] = 1e0 t_errors["MFK"] = 1e0 t_errors["KPLS"] = 1e0 t_errors["KPLSK"] = 1e0 t_errors["GEKPLS"] = 1e0 t_errors["GENN"] = 1e0 if compiled_available: t_errors["IDW"] = 1e0 t_errors["RBF"] = 1e-2 t_errors["RMTC"] = 1e-1 t_errors["RMTB"] = 1e-1 e_errors = {} e_errors["LS"] = 1.5 e_errors["QP"] = 1.5 e_errors["KRG"] = 1e-2 e_errors["MFK"] = 1e-2 e_errors["KPLS"] = 1e-2 e_errors["KPLSK"] = 1e-2 e_errors["GEKPLS"] = 1e-2 e_errors["GENN"] = 1e-2 if compiled_available: e_errors["IDW"] = 1e0 e_errors["RBF"] = 1e0 e_errors["RMTC"] = 2e-1 e_errors["RMTB"] = 2e-1 self.nt = nt self.ne = ne self.ndim = ndim self.problems = problems self.sms = sms self.t_errors = t_errors self.e_errors = e_errors
def init_default_regressor(self): # default regressor self.regressor = RBF(d0=5, print_prediction=False) self.has_epsilon = False
def train(self, X_train, y_train): self.smt_model = RBF(d0=self.d0, poly_degree=self.poly_degree, reg=self.reg) super(RBFModel, self).train(X_train, y_train)
# Prediction of the validation points y = t.predict_values(xtest) print("IDW, err: " + str(compute_rms_error(t, xtest, ytest))) if plot_status: plt.figure() plt.plot(ytest, ytest, "-.") plt.plot(ytest, y, ".") plt.xlabel(r"$y_{true}$") plt.ylabel(r"$\hat{y}$") plt.title("Validation of the IDW model") plt.show() ########### The RBF model t = RBF(print_prediction=False, poly_degree=0) t.set_training_values(xt, yt[:, 0]) t.train() # Prediction of the validation points y = t.predict_values(xtest) print("RBF, err: " + str(compute_rms_error(t, xtest, ytest))) if plot_status: k, l = 0, 0 f, axarr = plt.subplots(4, 3) axarr[k, l].plot(ytest, ytest, "-.") axarr[k, l].plot(ytest, y, ".") l += 1 axarr[3, 2].arrow(0.3, 0.3, 0.2, 0) axarr[3, 2].arrow(0.3, 0.3, 0.0, 0.4)
def test_smt_rbf(self): self._check_smt(RBF(d0=5, print_prediction=False))