我想添加一个自定义指标来使用 Keras 建模,我正在调试我的工作代码,但我找不到执行所需操作的方法。
该问题可以描述为通过逻辑多项式回归进行的多分类。我想实现的自定义指标是这样的:
(1/Number_of_Classes)*(TruePositivesClass1/TotalElementsClass1 + TruePositivesClass2/TotalElementsClass2 + ... + TruePositivesClassN/TotalElementsClassN)
其中 Number_of_Classes 必须从批次计算,即类似于np.unique(y_true).count()
and 并且每个求和项都类似于
len(np.where(y_true==class_i,1,0) == np.where(y_pred==class_i,1,0) )/np.where(y_true==class_i,1,0).sum()
就混淆矩阵而言(以 2 个变量的最小形式)
True False
True 15 3
False 12 1
公式是0.5*(15)/(15+12) + 0.5*(1/(1+3))=0.4027
代码可能类似于
def custom_metric(y_true,y_pred):
total_classes = Unique(y_true) #How calculate total unique elements?
summation = 0
for _ in unique_value_on_target:
# calculates Number of y_predict that are _
true_predics_of_class = Count(y_predict,_)
# calculates total number of items of class _ in batch y_true
true_values = Count(y_true,_)
value = true_predicts/true_values
summation + = value
return summation
我的预处理数据是一个像 numpy 的数组x=[v1,v2,v3,v4,...,vn]
,而我的目标列是一个 numpy 数组y=[1, 0, 1, 0, 1, 0, 0, 1 ,..., 0, 1]
然后,它们被转换为张量:
x_train = tf.convert_to_tensor(x)
y_train = tf.convert_to_tensor(tf.keras.utils.to_categorical(y))
然后,它们被转换为 tensorflow 数据集对象:
train_ds = tf.data.Dataset.zip((tf.data.Dataset.from_tensor_slices(x_train),
tf.data.Dataset.from_tensor_slices(y_train)))
后来,我拿了一个迭代器:
train_itr = iter(
train_ds.shuffle(len(y_train) * 5, reshuffle_each_iteration=True).batch(len(y_train)))
最后,我采用迭代器的一个元素并训练
x_train, y_train = train_itr.get_next()
model.fit(x=x_train, y=y_train, batch_size=batch_size, epochs=epochs,
callbacks=[custom_callback], validation_data=test_itr.get_next())
因此,由于对象是数据集迭代器,我无法找到按我的意愿操作它们的函数,以便获得所描述的自定义指标。