|
- import numpy as np
-
- class SimilarityMetric:
- def __init__(self, seed=2022):
- self.seed = seed
-
- def _pearson_correlation_coefficient(self, x, y, matrix=False):
- if matrix:
- x_mean = np.mean(x, axis=1, keepdims=True)
- y_mean = np.mean(y, axis=1, keepdims=True)
-
- x_diff = x - x_mean
- y_diff = y - y_mean
-
- x_diag = np.diagonal(np.dot(x_diff, x_diff.T)).reshape((-1, 1))
- y_diag = np.diagonal(np.dot(y_diff, y_diff.T)).reshape((1, -1))
- r = np.dot(x_diff, y_diff.T) / np.sqrt(np.tile(x_diag, (1, x.shape[0])) * np.tile(y_diag, (y.shape[0], 1)))
- else:
- x_mean = np.mean(x, axis=0, keepdims=True)
- y_mean = np.mean(y, axis=0, keepdims=True)
-
- x_diff = x - x_mean
- y_diff = y - y_mean
- r = np.sum(x_diff * y_diff, axis=0) / np.sqrt(np.sum(x_diff * x_diff, axis=0) * np.sum(y_diff * y_diff, axis=0))
-
- return r
-
- def _spearman_correlation_coefficient(self, x, y):
- x_rank = np.argsort(np.argsort(x)).astype("float64")
- y_rank = np.argsort(np.argsort(y)).astype("float64")
- n = x.shape[0]
- r = 1 - 6 * np.sum((x_rank - y_rank) ** 2) / (n ** 3 - n)
-
- return r
-
- def score(self, model_data, neural_data):
- pass
-
-
- class RSAMetric(SimilarityMetric):
- def score(self, model_data, neural_data):
- num_classes = model_data.shape[0] # 118
-
- model_RDM = 1 - self._pearson_correlation_coefficient(model_data, model_data, matrix=True) # 118*118
- neural_RDM = 1 - self._pearson_correlation_coefficient(neural_data, neural_data, matrix=True) # 118*118
-
- model_RDM = model_RDM[np.triu_indices(num_classes, 1)] # 获取上三角元素
- neural_RDM = neural_RDM[np.triu_indices(num_classes, 1)]
-
- return self._spearman_correlation_coefficient(model_RDM, neural_RDM)
|