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
Exemplo n.º 2
0
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
Exemplo n.º 3
0
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
Exemplo n.º 4
0
    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()
Exemplo n.º 5
0
    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()
Exemplo n.º 6
0
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)