我有 3 个数据集,分别包含预测、用户名和标签。使用下面的代码,我对各个用户的预测进行平均(基于 Jaime 和 ali_m 来自 Average using grouping value in another vector (numpy / Python) 的帮助)。标签与每个观察结果相关联,因此存在冗余信息。我想使用 idx 找到每个用户的唯一标签。我如何在 NumPy 中做到这一点?
>>> pred
[ 0.99 0.23 0.11 0.64 0.45 0.55 0.76 0.72 0.97 ]
>>> users
['User2' 'User3' 'User2' 'User3' 'User0' 'User1' 'User4' 'User4' 'User4']
>>> label
[ 1 0 1 0 0 1 0 0 0 ]
unq, idx, cnt = np.unique(user_data, return_inverse=True, return_counts=True) # assign integer indices to each unique user name, and get the total number of occurrences for each name
predictions_user = np.bincount(idx, weights=pred) / cnt # now sum the values of pred corresponding to each index value and divide to get the mean
当前输出:
>>> unq
array(['User0', 'User1', 'User2', 'User3', 'User4'], dtype='|S5')
>>> predictions_user
array([ 0.45, 0.55, 0.55, 0.435, 0.81666667])
我想添加最后一个变量,名为label_user
。每个值都是与 unq
中同一索引处的用户关联的标签。
示例输出:
>>> label_user
array([0, 1, 1, 0, 0])
最佳答案
您可以通过将 return_index=True
传递给 np.unique
来完成此操作。来自 the docs :
return_index : bool, optional
If True, also return the indices of ar that result in the unique array.
这为您提供了 user_data
中的一组索引,这些索引在 unq
中给出了唯一值。要获取与 unq
中每个值对应的标签,只需使用这些索引来索引到 labels
:
unq, idx, inv_idx, cnt = np.unique(user_data, return_index=True,
return_inverse=True, return_counts=True)
print(unq)
# ['User0' 'User1' 'User2' 'User3' 'User4']
print(label_user[idx])
# [0, 1, 1, 0, 0]
我已将“逆”索引数组重命名为 inv_idx
,以将其与 idx
区分开来。
与计算每个唯一用户名的平均值一样,还有一种使用 pandas 获取相应标签的简单方法:
import pandas as pd
df = pd.DataFrame({'user_data':user_data, 'label_user':label_user})
print(df.groupby('user_data').label_user.unique())
# user_data
# User0 [0]
# User1 [1]
# User2 [1]
# User3 [0]
# User4 [0]
# Name: label_user, dtype: object
关于python - 在对用户进行平均预测时附加标签信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29257995/