优化这段代码为8个X:import numpy as npdef gray_relation_analysis(X, Y): # 将X、Y序列进行归一化处理 X0 = np.array([min(X), max(X)]) X1 = (X - X0[0]) / (X0[1] - X0[0]) Y1 = (Y - min(Y)) / (max(Y) - min(Y)) # 求出X1、Y1的均值 x_mean = np.mean(X1) y_mean = np.mean(Y1) # 计算灰色关联度 k = len(X1) delta_x = np.abs(X1 - x_mean) delta_y = np.abs(Y1 - y_mean) # 求出最大值和最小值 delta_x_max = np.max(delta_x) delta_x_min = np.min(delta_x) delta_y_max = np.max(delta_y) delta_y_min = np.min(delta_y) # 计算关联度 r = 0.5 for i in range(k): a = r * (delta_x_max - delta_x[i]) / (delta_x_max - delta_x_min) + (1 - r) * (delta_y_max - delta_y[i]) / (delta_y_max - delta_y_min) print("第%d个元素的关联度为%f" % (i+1, a))# 测试X = np.array([1, 2, 3, 4, 5])Y = np.array([2, 3, 5, 7, 9])gray_relation_analysis(X, Y)
时间: 2024-04-01 13:36:24 浏览: 56
优化后的代码如下:
import numpy as np
def gray_relation_analysis(X, Y):
# 将X、Y序列进行归一化处理
X0 = np.array([min(X), max(X)])
X1 = (X - X0[0]) / (X0[1] - X0[0])
Y1 = (Y - min(Y)) / (max(Y) - min(Y))
# 求出X1、Y1的均值
x_mean, y_mean = np.mean(X1), np.mean(Y1)
# 计算灰色关联度
k = len(X1)
delta_x, delta_y = np.abs(X1 - x_mean), np.abs(Y1 - y_mean)
# 求出最大值和最小值
delta_x_max, delta_x_min = np.max(delta_x), np.min(delta_x)
delta_y_max, delta_y_min = np.max(delta_y), np.min(delta_y)
# 计算关联度
r = 0.5
a = r * (delta_x_max - delta_x) / (delta_x_max - delta_x_min) + (1 - r) * (delta_y_max - delta_y) / (delta_y_max - delta_y_min)
print("元素的关联度为:")
for i in range(k):
print("%.8f" % a[i])
# 测试
X = np.array([1, 2, 3, 4, 5])
Y = np.array([2, 3, 5, 7, 9])
gray_relation_analysis(X, Y)
阅读全文