题目链接:Deep-ML
不使用numpy数组来完成计算:
def calculate_covariance_matrix(vectors: list[list[float]]) -> list[list[float]]:
# 转置矩阵
# vectors = [[vectors[j][i] for j in range(len(vectors))] for i in range(len(vectors[0]))]
n = len(vectors[0])
p = len(vectors)
# 计算每个特征的平均值
M = [sum(feature) / n for feature in vectors]
# 计算中心化后的矩阵 B
B = [[vectors[i][j] - M[i] for j in range(n)] for i in range(p)]
# 计算 B 的转置
B_T = [[B[j][i] for j in range(p)] for i in range(n)]
# 计算协方差矩阵
covariance_matrix = [[sum(B[i][k] * B_T[k][j] for k in range(n)) / (n - 1) for j in range(p)] for i in range(p)]
return covariance_matrix
if __name__ == '__main__':
print(calculate_covariance_matrix([[1, 2, 3], [4, 5, 6]]))