灰色预测模型是一种常用的时间序列预测模型,其思路十分简单,只要给定一个原始的时间序列串就可以预测出未来几期的结果,但这个比较适用于短期预测,不适用于中长期预测。原理我不想多讲了,大家自己去百度吧,直接代码,python3可以用,输入你的序列直接出结果,包括算法和检验所有内容。各位要是觉得有用,点个赞再走,哈哈。
import numpy as np
def cal_canshu(input_line):
cumsum_input = np.cumsum(input_line)
# print(cumsum_input)
Y = input_line[1:]
B = np.ones((len(input_line)-1,2))
for i in range(np.shape(B)[0]):
B[i,0] = -0.5 * (cumsum_input[i] + cumsum_input[i+1])
# print(B)
B = np.mat(B)
Y = np.mat(Y)
out_canshu = ((B.T*B).I)*B.T*Y.T
return out_canshu
def forcast_hanshu(canshu,input_line,k):
out_1 = (input_line[0] - canshu[1]/canshu[0]) * np.exp(-canshu[0] * (k-1)) + canshu[1]/canshu[0]
return out_1
def forcast_out(canshu,input_line):
n = len(input_line)
out_1 = np.zeros(n)#默认按行排列
for i in range(n):
out_1[i] = forcast_hanshu(canshu,input_line,i+1)
out_0 = np.zeros(n)
out_0[0] = out_1[0]
for i in range(1,n):
out_0[i] = out_1[i] - out_1[i-1]
return out_1.T,out_0.T
def model_test(input_line, forcast_line):
sigma = np.abs(forcast_line - input_line)
rela_sigma = np.average(sigma / input_line)
print('相对误差为:',rela_sigma)
yita = np.average((min(sigma) + 0.5 * max(sigma)) / (sigma + 0.5 * max(sigma)))
print('关联度为:',yita)
sq_input = np.square(input_line)
sq_error = np.square(sigma)
sq_ratio = np.average(sq_error)/np.average(sq_input)
print('均方差比为:',sq_ratio)
little_error = len(sigma[(sigma - np.average(sigma)) < 0.6745*np.average(sq_input)])/len(sigma)
print('小误差概率为:',little_error)
return rela_sigma, yita, sq_ratio, little_error
test = np.array([1,2,3,4,5,6])
a,b = forcast_out(cal_canshu(test), test)
model_test(test, b)