在处理多维数组时,我总是发现自己处于困惑的状态。 具有以下数组的图像,其中每个数组包含数据集中每个类别(5 个类别)的特征重要性分数(3 个特征)。该数据集总共包含 4 个样本。
arr = np.random.randn(5,4,3).round(1)
arr
array([[[ 0.7, -0.1, 0.6], # class 0 feature importances
[-0.8, -0.7, 1.4],
[ 1.4, -0.1, 1.4],
[-1.8, -1.2, -1.6]],
[[-0.3, 2.1, 0.5], # class 1 feature importances
[-1.2, 1.4, -0.4],
[ 0. , -1. , 0.8],
[-0.8, 2.3, 0.3]],
[[ 0.2, 0.6, -0.1], # class 2 feature importances
[-1.8, -0.2, 1.2],
[-0.5, 0.5, 1. ],
[ 1.3, 0.4, -2.6]],
[[-1. , 0.8, -0.4], # class 3 feature importances
[ 1.2, 1.5, -0.5],
[ 0.1, -0.5, 0.8],
[ 2.5, -1.6, -0.6]],
[[-1.2, 0.3, -0.9], # class 4 feature importances
[ 1. , -1. , -0.5],
[ 0.3, 1.4, 0.5],
[-2.3, 0.6, 0.2]]])
我有兴趣计算各个类别的特征重要性的
mean absolute
值(总体)。理想情况下,所得的排列应为排名 1 (3,)
,因为它具有三个特征:
Feature1 = sum( abs(0.7,-0.8, 1.4, -1.8, -0.3, -1.2, 0.0, -0.8, 0.2, -1.8, -0.5, 1.3,
-1.0, 1.2, 0.1, 2.5, -1.2, 1.0, 0.3,, -2.3) ) / 12 # n = 12
如果你这样做
arr[:,:,0]
,你将获得你想要的整个数组。
就做
np.sum(np.abs(arr[:,:,0])) / 12
np.sum( np.abs([0.7,-0.8, 1.4, -1.8, -0.3, -1.2, 0.0, -0.8, 0.2, -1.8, -0.5, 1.3,
-1.0, 1.2, 0.1, 2.5, -1.2, 1.0, 0.3, -2.3]) ) / 12
>>> 1.7000000000000002
np.sum(np.abs(xx[:,:,0])) / 12
>>> 1.7000000000000002
我认为您需要计算数组中每个元素的绝对值,然后沿代表类的轴取平均值。具体方法如下:
import numpy as np
arr = np.random.randn(5, 4, 3).round(1)
# Compute the mean absolute value along the axis representing the classes
mean_absolute_values = np.mean(np.abs(arr), axis=0)
# Compute the mean absolute value across all classes for each feature
result = np.mean(mean_absolute_values, axis=0)
print(result)
这将输出所需的结果:
[0.75 1.02 0.88]