【问题标题】:Preprocess Accuracy metric预处理准确度指标
【发布时间】:2020-09-07 08:01:15
【问题描述】:

我有一个模型可以预测 5 个类别。我想更改准确度指标,如下例所示:

def accuracy(y_pred,y_true):
    #our pred tensor 
    y_pred = [ [0,0,0,0,1], [0,1,0,0,0], [0,0,0,1,0], [1,0,0,0,0], [0,0,1,0,0]]
    # make some manipulations with tensor y_pred
    # actons description : 
    for array in y_pred :
        if array[3] == 1 :
             array[3] = 0
             array[0] = 1
        if array[4] == 1 :
             array[4] = 0
             array[1] = 1
        else :
             continue 

    #this nice work with arrays but howe can i implement it with tensors ? 
    #after manipulations result-> 
    y_pred = [ [0,1,0,0,0], [0,1,0,0,0], [1,0,0,0,0], [1,0,0,0,0],[0,0,1,0,0] ]
    #the same ations i want to do with y_true 
    # and after it i want to run this preprocess tensors the same way as  simple tf.keras.metrics.Accuracy metric 

我认为 tf.where 可以帮助过滤张量,但不幸的是不能正确地做到这一点。

如何使用张量制作这个预处理精度指标?

【问题讨论】:

  • 这类似于this。希望对你有帮助
  • 你想怎么改?
  • @Zabir Al Nazi 这只是一个动作示例,我想用我的张量来做。这个循环不是张量的正确解决方案。

标签: python python-3.x tensorflow machine-learning tensorflow2.x


【解决方案1】:

如果你想将这些向左移动 3 个索引,你可以这样做:

import numpy as np

y_pred = [ [0,0,0,0,1], [0,1,0,0,0], [0,0,0,1,0], [1,0,0,0,0], [0,0,1,0,0]]

y_pred = np.array(y_pred)

print(y_pred)

shift = 3

one_pos = np.where(y_pred==1)[1] # indices where the y_pred is 1
# updating the new positions with 1
y_pred[range(y_pred.shape[1]),one_pos - shift] = np.ones((y_pred.shape[1],))
# making the old positions zero
y_pred[range(y_pred.shape[1]),one_pos] = np.zeros((y_pred.shape[1],))

print(y_pred)
[[0 0 0 0 1]
 [0 1 0 0 0]
 [0 0 0 1 0]
 [1 0 0 0 0]
 [0 0 1 0 0]]
[[0 1 0 0 0]
 [0 0 0 1 0]
 [1 0 0 0 0]
 [0 0 1 0 0]
 [0 0 0 0 1]]

更新:

如果您只想移动索引 3 和 4。

import numpy as np

y_pred = [ [0,0,0,0,1], [0,1,0,0,0], [0,0,0,1,0], [1,0,0,0,0], [0,0,1,0,0]]

y_pred = np.array(y_pred)

print(y_pred)

shift = 3

one_pos = np.where(y_pred==1)[1]# indices where the y_pred is 1

print(one_pos)

y_pred[range(y_pred.shape[1]),one_pos - shift] = [1 if (i == 3 or i == 4) else 0 for i in one_pos]
y_pred[range(y_pred.shape[1]),one_pos] = [0 if (i == 3 or i == 4) else 1 for i in one_pos]

print(y_pred)
[[0 0 0 0 1]
 [0 1 0 0 0]
 [0 0 0 1 0]
 [1 0 0 0 0]
 [0 0 1 0 0]]
[4 1 3 0 2]
[[0 1 0 0 0]
 [0 1 0 0 0]
 [1 0 0 0 0]
 [1 0 0 0 0]
 [0 0 1 0 0]]

【讨论】:

  • 我只想将索引从 3 移到 0 和从 4 移到 1 。另一个必须保存他们的索引。如果我的已经在索引 0 或 1 或 2 -> 什么也不做
  • @ВладиславБушменьов 完成,检查更新的答案。
猜你喜欢
  • 2021-08-02
  • 2020-04-04
  • 2021-12-19
  • 1970-01-01
  • 2019-01-20
  • 1970-01-01
  • 2014-04-30
  • 2013-07-16
  • 1970-01-01
相关资源
最近更新 更多