【问题标题】:From a one-hot representation to the labels从 one-hot 表示到标签
【发布时间】:2019-06-20 21:34:39
【问题描述】:

我的预测在张量 pred 下,pred.shape 是 (4254, 10, 3)。所以我们有4254 维矩阵(10, 3)。让我们来看看其中一个矩阵。

W = array([[0.04592975, 0.09632163, 0.85774857],
          [0.03408821, 0.27141285, 0.6944989 ],
          [0.02538731, 0.4691383 , 0.50547445],
          [0.01959289, 0.6456455 , 0.33476162],
          [0.01333424, 0.7494791 , 0.23718661],
          [0.0109237 , 0.77042925, 0.218647  ],
          [0.01438793, 0.7796771 , 0.20593494],
          [0.01474626, 0.6817438 , 0.30350992],
          [0.02189695, 0.57687664, 0.40122634],
          [0.03810155, 0.5130332 , 0.44886518]], dtype=float32)

从上面的例子可以看出,有 10 个向量代表一个标签的 one-hot 表示。例如,np.argmax([0.04592975, 0.09632163, 0.85774857]) = 2。

为什么我要批量处理 10 个向量?我正在研究一个时间序列预测问题,在时间t_0,我预测时间t_1 到时间t_10 的下10 个标签。

对于这些矩阵中的每一个,我都有兴趣取回原始标签。所以对于矩阵W,我应该得到数组array([2, 2, 2, 1, 1, 1, 1, 1, 1, 1])。

让我们定义阈值数组threshold_array = np.array([0.6, 0.65, 0.70, 0.75, 0.80, 0.80, 0.80, 0.80, 0.80, 0.80]) 并取回labels = array([2, 2, 2, 1, 1, 1, 1, 1, 1, 1])。假设中立位置为1,动作为0 或2。这里的目标是根据threshold_array 和我们的矩阵W 修改labels。

如果我选择W[0],我们知道np.argmax(W[0]) = 2 和W[0][2] = 0.85774857。作为W[0][2] >= threshold_array[0],那么labels[0] 将保持2。

另一个例子有点不同。如果我选择W[2],我们知道np.argmax(W[2]) = 2 和W[2][2] = 0.50547445。如W[2][2] < threshold_array[2],则labels[2] 将从2 更改为0。

如果我将该策略应用于W 中的每个向量,labels 现在设置为array([2, 2, 0, 1, 1, 1, 1, 1, 1, 1])。请注意,只有一个动作可以成为中立位置,而不是相反。

如何在 python 中将该策略编码到pred 内的每个矩阵W 以获得维度为(4254, 10) 的标签矩阵?

【问题讨论】:

    标签: python numpy tensor threshold


    【解决方案1】:

    我不确定这是解决这个问题的最佳方法,但这里有一个答案。

    import numpy as np
    
    threshold_array = np.array([0.6, 0.65, 0.70, 0.75, 0.80, 0.80, 0.80, 0.80, 0.80, 0.80])   
    
    def get_labels(W, threshold_array):
    
        labels = []
        for i, vect in enumerate(W):
            neutral_position = 1
            label = np.argmax(vect)
            if label in [0, 2]:
                if vect[label] < threshold_array[i]:
                    labels.append(neutral_position)
                else:
                    labels.append(label)
            else:
                labels.append(label)
        return np.array(labels)
    
    if __name__ == "__main__":
        labels = []
        for matrix in pred:
            labels.append(get_labels(matrix, theshold_array))
        labels = np.array(labels)
    

    【讨论】:

      猜你喜欢
      • 2017-07-27
      • 1970-01-01
      • 2021-12-05
      • 2021-08-05
      • 2020-07-18
      • 2021-12-13
      • 2020-11-04
      • 1970-01-01
      • 2019-10-09
      相关资源
      最近更新 更多