python实现灰色预测GM(1,1)

python实现灰色预测GM(1,1)

  • 级比检验
  • 预测
  • main

级比检验

对数据进行级比检验,若不符合进行平移变换,并返回变换后的数据,以及变换次数

// 级比检验
def deal_data(data, c):
    times = 0
    while True:
        i = 1
        while i < len(data):
            proportion = data[i - 1] / data[i]
            if math.exp(-2 / (len(data) + 1)) < proportion < math.exp(2 / (len(data) + 1)):
                i = i + 1
            else:
                data = data + [c] * len(data)
                times += 1
                break
        if i == len(data):
            break
    return data, times

预测


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

main

if __name__ == '__main__':
    x = np.array([71.1, 72.4, 72.4, 72.1, 71.4, 72.0, 71.6])
    c = 0.1   # 平移常数,自行设定
    data, times = deal_data(x, c)  # 数据检验,并返回平移后的数据,和平移次数
    predict_data = predict(data)   # 预测x1
    result = np.ediff1d(predict_data)  # 递减
    result = result - c * times   # 减去平移的影响
    print(result)
    print((np.array(result[:len(x)]) - np.array(x[1 :len(x)])) / np.array(x[1 :len(x)]))

你可能感兴趣的:(数学建模,算法,python)