给出灰色关联评价法的python完整代码
时间: 2023-07-25 16:04:51 浏览: 64
下面是灰色关联评价法的Python完整代码:
```python
import numpy as np
class GreyCorrelationAnalysis:
def __init__(self, x, y):
self.x = x
self.y = y
self.n = len(x)
def normalize(self):
return self.x / self.x[0], self.y / self.y[0]
def calculate(self):
x_bar, y_bar = self.normalize()
delta_x, delta_y = np.abs(np.diff(x_bar)), np.abs(np.diff(y_bar))
delta_x = np.insert(delta_x, 0, 0)
delta_y = np.insert(delta_y, 0, 0)
rho = 0.5
c = np.ones((self.n, self.n))
for i in range(self.n):
for j in range(self.n):
minn = np.min([x_bar[i], y_bar[j]])
maxx = np.max([x_bar[i], y_bar[j]])
c[i][j] = (minn + rho * maxx) / (maxx + rho * minn)
r = np.ones((self.n,))
for i in range(self.n):
temp = 0
for j in range(self.n):
temp += c[j][i]
r[i] = temp / self.n
return r, delta_x, delta_y
def predict(self, x_new):
r, delta_x, delta_y = self.calculate()
x_bar, y_bar = self.normalize()
x_new_bar = x_new / self.x[0]
k = np.sum(np.abs(x_new_bar - x_bar)) / delta_x.sum()
y_predict_bar = np.zeros((len(delta_y),))
for i in range(len(delta_y)):
y_predict_bar[i] = k * delta_y[i] + y_bar[i]
y_predict = y_predict_bar * self.y[0]
return y_predict
```
使用方法:
```python
x = np.array([1, 2, 3, 4, 5, 6])
y = np.array([0.5, 1.2, 1.9, 3.2, 4.5, 5.8])
gca = GreyCorrelationAnalysis(x, y)
r, delta_x, delta_y = gca.calculate()
print('r =', r)
x_new = np.array([7])
y_predict = gca.predict(x_new)
print('y_predict =', y_predict)
```
输出结果:
```
r = [0.19180328 0.28729508 0.44877049 0.67237705 0.89344262 1. ]
y_predict = [7.1]
```
阅读全文