python生成GM(2,1)灰色预测模型代码
时间: 2024-02-07 08:02:10 浏览: 178
以下是一个简单的Python程序,用于生成GM(2,1)灰色预测模型:
```python
import numpy as np
def GM21(x0):
x1 = np.cumsum(x0)
z1 = (x1[:-1] + x1[1:]) / 2.0
z1 = z1.reshape((len(z1), 1))
B = np.append(-z1, np.ones_like(z1), axis=1)
Y = x0[1:].reshape((len(x0) - 1, 1))
[[a], [b]] = np.dot(np.dot(np.linalg.inv(np.dot(B.T, B)), B.T), Y)
predict = (x0[0] - b / a) * np.exp(-a * np.arange(1, len(x0) + 1))
return predict
# 测试
x0 = np.array([10, 12, 13, 15, 18, 20])
print(GM21(x0))
```
上面的代码中,我们使用了NumPy库。该程序接受一组输入数据x0,并返回预测结果。我们首先计算一阶累加数列x1,然后计算平均值z1。接下来,我们使用B矩阵和Y矩阵来计算a和b,最后使用预测公式来生成预测值。
相关问题
灰色预测gm(1、1)的模型python代码_python 实现 灰色预测 GM(1,1)模型 灰色系统 预测 灰色预测公式推导...
以下是灰色预测GM(1,1)模型的Python代码实现:
```python
import numpy as np
def GM11(x0):
# 累加生成序列
x1 = np.cumsum(x0)
# 得到累加生成序列的一阶差分序列
z1 = (x1[:-1] + x1[1:]) / 2.0
z1 = z1.reshape((-1, 1))
# 构建矩阵B和Y
B = np.zeros((len(z1) - 1, 2))
Y = np.zeros((len(z1) - 1, 1))
for i in range(len(z1) - 1):
B[i][0] = -z1[i]
B[i][1] = 1
Y[i][0] = x0[i + 1]
# 计算GM(1,1)微分方程的参数a和u
a, u = np.dot(np.dot(np.linalg.inv(np.dot(B.T, B)), B.T), Y)
# 对原始序列进行预测
result = np.zeros(len(x0))
result[0] = x0[0]
for i in range(1, len(x0)):
result[i] = (x0[0] - u / a) * (1 - np.exp(a)) * np.exp(-a * (i))
return result
# 测试代码
x0 = np.array([13.0, 15.0, 16.0, 20.0, 22.0, 25.0, 28.0, 30.0])
result = GM11(x0)
print(result)
```
该代码实现了GM(1,1)模型,输入原始序列x0,通过累加生成序列、得到一阶差分序列、构建矩阵B和Y、计算微分方程的参数a和u,最后预测出序列的结果。
需要注意的是,GM(1,1)模型对原始序列的要求比较苛刻,需要满足一定的规律性,否则预测效果会比较差。
gm11灰色预测模型python
嗨!对于使用Python实现GM(1,1)灰色预测模型,你可以按照以下步骤进行操作:
1. 导入所需的库:
```
import numpy as np
import matplotlib.pyplot as plt
```
2. 定义GM(1,1)灰色预测函数:
```
def gm11(x):
n = len(x)
# 累加生成
cum_x = np.cumsum(x)
# 紧邻均值生成
z = (cum_x[:-1] + cum_x[1:]) / 2.0
# 紧邻均值级比生成
B = np.append(-z.reshape((n-2, 1)), np.ones_like(z.reshape((n-2, 1))), axis=1)
Y = x[1:].reshape((n-1, 1))
# 矩阵运算求参数
[[a], [b]] = np.dot(np.dot(np.linalg.inv(np.dot(B.T, B)), B.T), Y)
# 模型精度的后验差检验
delta = np.abs(Y - (a * z + b))
C = delta.std() / y.std()
P = 1.0 * (np.abs(delta - delta.mean()) < 0.6745 * y.std()).sum() / len(delta)
# 修正后的灰色预测模型
result = (x[0] - b / a) * np.exp(-a * (list(range(n)) - 1)) - (x[0] - b / a) * np.exp(-a * (list(range(n)) - 2))
# 预测数据
predict = np.abs(result - np.append(x[0], x[:-1])).tolist()
return result, predict, C, P
```
3. 输入数据并调用灰色预测函数进行预测:
```
x = np.array([1, 2, 3, 4, 5, 6]) # 输入数据
result, predict, C, P = gm11(x) # 调用GM(1,)灰色预测函数
```
4. 可视化结果:
```
plt.plot(list(range(len(x))), x, marker='o', label='原始数据')
plt.plot(list(range(len(x))), result, marker='o', label='预测数据')
plt.plot(list(range(len(x))), predict, marker='o', label='残差')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()
```
这样,你就可以使用Python编写GM(1,1)灰色预测模型了。希望对你有所帮助!如有其他问题,请随时提问。
阅读全文
相关推荐















