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

import numpy as np
import matplotlib.pyplot as plt

# 导入时间序列
x = [31.87,32.87,31.77,31.5,30.44,30.77,29.69,29.69,29.13,27.68,29.79,25.19]
lan = []
for i in range(len(x)):
    if i == len(x) - 1:
        continue
    # 求级比
    lan.append(x[i] / x[i + 1])
x_1 = np.cumsum(x)

# 构造数据矩阵B及数据向量
B = np.array([-1 / 2 * (x_1[i] + x_1[i + 1]) for i in range(len(x) - 1)])
B = np.mat(np.vstack((B, np.ones((len(x) - 1,)))).T)
Y = np.mat([x[i + 1] for i in range(len(x) - 1)]).T
u = np.dot(np.dot(B.T.dot(B).I, B.T), Y)
[a, b] = [u[0, 0], u[1, 0]]
a_new, b = x[0] - b / a, b / a

# 输入需要预测的年数
year = 20
year += len(x)
x_predict = [x[0]]
x_predict = x_predict + [a_new * (np.exp(-a * i) - np.exp(-a * (i - 1))) for i in range(1, year)]

#计算相对误差,如果较小,则可以使用
print((np.array(x_predict[:len(x)])-np.array(x[:len(x)]))/np.array(x[:len(x)]))
print(x_predict[len(x):])

#注意这里数字要根据时间序列的具体年份更改
plt.plot(range(2005,2017),x[:len(x)],range(2005,2037),x_predict)
plt.xlabel('Years')
plt.ylabel('Concentration [mt]')
plt.legend(['Actual','Forecast'])
plt.savefig('1.png',dpi=600)

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