python实现灰色预测DGM(2,1)

// DGM(2,1)
import numpy as np
import math


def predict(data):
    a_x0 = np.ediff1d(data).T
    B = np.array([-data[1:], np.ones([len(data) - 1])]).T
    Y = a_x0
    u = np.dot(np.dot(np.linalg.inv(np.dot(B.T, B)), B.T), Y)
    a, b = u[0], u[1]
    return [(b / (a * a) - data[0] / a) * math.exp(-a * i) + b / a * i + (1 + a) / a * data[0] - b / (a * a)
            for i in range(len(data))]


if __name__ == '__main__':
    data = np.array([2.874, 3.278, 3.39, 3.679, 3.77, 3.8])
    predict_data = predict(data)  # 预测x1
    result = np.ediff1d(predict_data)  # 递减
    print('原数据:', data[1:])
    print('预测结果:', result)
    print('相对误差:', (np.array(result[:len(data)]) - np.array(data[1:len(data)])) / np.array(data[1:len(data)]))

你可能感兴趣的:(数学建模)