[英]Tensorflow: How to use tf.keras.metrics in multiclass classification?
[英]Use different metrics in tf.keras.metrics for mutli-classification model
我正在使用 TensorFlow 聯合框架來解決多分類問題。 我正在關注教程,其中大多數使用指標( tf.keras.metrics.SparseCategoricalAccuracy
)來衡量模型的准確性。 我想探索其他指標,例如(AUC、召回、F1 和精度),但我得到了錯誤。 下面提供了代碼和錯誤消息。
def create_keras_model():
initializer = tf.keras.initializers.Zeros()
return tf.keras.models.Sequential([
tf.keras.layers.Input(shape=(8,)),
tf.keras.layers.Dense(64),
tf.keras.layers.Dense(4, kernel_initializer=initializer),
tf.keras.layers.Softmax(),
])
def model_fn():
keras_model = create_keras_model()
return tff.learning.from_keras_model(
keras_model,
input_spec=train_data[0].element_spec,
loss=tf.keras.losses.SparseCategoricalCrossentropy(),
metrics=[tf.keras.metrics.SparseCategoricalAccuracy(),
tf.keras.metrics.Recall()]
)
錯誤
ValueError: Shapes (None, 4) and (None,) are incompatible
是因為多分類問題,我們不能使用這些措施嗎? 如果是這樣,我是否可以使用任何其他指標來衡量我的多分類模型。
tf.keras.metrics.SparseCategoricalAccuracy() --> 用於 SparseCategorical (int) 類。 tf.keras.metrics.Recall() --> 用於分類(one-hot)類。
如果要使用沒有“稀疏”的任何度量命名,則必須使用 one-hot 類。
更新:
num_class=4
def get_img_and_onehot_class(img_path, class):
img = tf.io.read_file(img_path)
img = tf.io.decode_jpeg(img, channels=3)
""" Other preprocessing of image."""
return img, tf.one_hot(class, num_class)
當你上了一堂熱課時:
loss=tf.losses.CategoricalCrossentropy
METRICS=[tf.keras.metrics.CategoricalAccuracy(name='accuracy'),
tf.keras.metrics.Precision(name='precision'),
tf.keras.metrics.Recall(name='recall'),]
model.compile(
optimizer = tf.keras.optimizers.Adam(learning_rate=0.0001),
loss=loss,
metrics= METRICS)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.