Python Keras度量实现
我正试图用Keras建立一个模型,它使用一个指标:一个特殊的f1分数。我正在为它的实施而挣扎 到目前为止,我已经:Python Keras度量实现,python,tensorflow,keras,metrics,Python,Tensorflow,Keras,Metrics,我正试图用Keras建立一个模型,它使用一个指标:一个特殊的f1分数。我正在为它的实施而挣扎 到目前为止,我已经: def f1_metric(y_true,y_pred): y_pred = K.one_hot(indices=K.argmax(y_pred,1), num_classes=4) arr = np.zeros((4,4)) for pred,true in zip(y_pred,y_true): c_pred = K.constant(K.arg
def f1_metric(y_true,y_pred):
y_pred = K.one_hot(indices=K.argmax(y_pred,1), num_classes=4)
arr = np.zeros((4,4))
for pred,true in zip(y_pred,y_true):
c_pred = K.constant(K.argmax(pred))
c_true = K.constant(K.argmax(true))
arr[c_true][c_pred] += 1
fn = 2*arr[0][0]/(np.sum(arr[0]) + np.sum(arr.T[0])) if (np.sum(arr[0]) + np.sum(arr.T[0])) != 0 else 0
fa = 2*arr[1][1]/(np.sum(arr[1]) + np.sum(arr.T[1])) if (np.sum(arr[1]) + np.sum(arr.T[1])) != 0 else 0
fo = 2*arr[2][2]/(np.sum(arr[2]) + np.sum(arr.T[2])) if (np.sum(arr[2]) + np.sum(arr.T[2])) != 0 else 0
fp = 2*arr[3][3]/(np.sum(arr[3]) + np.sum(arr.T[3])) if (np.sum(arr[3]) + np.sum(arr.T[3])) != 0 else 0
return K.constant((fn + fa + fo + fp)/4)
当我使用我的f1\u metric
功能时,出现以下错误:
operator不允许在“tf.Tensor”上迭代
我知道循环不能被使用。我已经读了一段时间了,但还是找不到其他选择
如何正确实现for循环?错误非常具体。y_true和y_pred是张量类型的,不能对它们进行迭代。您可以尝试使用to_numpy_array(y_pred)将它们转换为numpy数组,执行需要执行的操作,并返回一个张量值,就像您已经在做的那样
因此,在将y_true和y_pred转换为数组后,for循环中不需要K.constant,但函数必须返回一个张量值,因此保留K.constant((fn+fa+fo+fp)/4)