TensorFlow tf.metrics accuracy precision recall 二分类和多分类(TensorFlow 自带没有多分类指标)

这篇博客介绍了在TensorFlow中如何计算二分类的accuracy, precision, recall,并指出tf.metrics不支持多分类的precision和recall。提供了计算多分类macro-precision和macro-recall的方法链接,以及一个第三方库tf_metrics来支持多分类效果指标的计算。同时,强调了正确设置类别数量的重要性,以避免影响precision和recall的准确性。" 114586172,10326384,使用Heimdall轻松编排Java接口服务,"['Java接口服务', 'API管理', 'Heimdall框架', '中间件', '安全']
摘要由CSDN通过智能技术生成

平时用的评价指标

tf.metrics.accuracy()

tf.metrics.precision()

tf.metrics.recall()

 

需要注意:

tf.metrics 不支持precision/recall/f1多分类效果指标的计算,其中为二分类指标

 

计算二分类precision/recall效果指标,可通过如下实现方式:

def metric_fn(per_example_loss, label_ids, logits):
    predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)
    accuracy = tf.metrics.accuracy(label_ids, predictions)
    recall = tf.metrics.recall(label_ids, predictions)
    precision = tf.metrics.precision(label_ids, predictions)
    loss = tf.metrics.mean(per_example_loss)
    return {
        "eval_accuracy": accuracy,
        "eval_loss": loss,
        "recall": recall,
        "precision": precision,
    }

 

 

计算多分类macro-precision/macro-recall效果指标,可通过如下实现方式:

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
中文情感分类是一种将中文文本分为积极、消极或中性情感的任务。在本文中,我们将使用TensorFlow实现中文情感分类。 1. 数据集准备 在此,我们将使用THUCNews数据集。该数据集包含14个类别,每个类别有10000个新闻文档。我们将仅使用其中的5个类别:体育、娱乐、家居、房产和教育。 2. 数据预处理 为了训练我们的模型,我们需要将文本数据转换为数字表示。我们将使用Tokenizer类将文本数据转换为数字表示。此外,我们还需要将每个文本序列填充为相同长度,以便它们可以传递到我们的模型中。 3. 构建模型 我们将使用嵌入层、卷积层和全连接层来构建我们的模型。嵌入层将输入序列转换为密集向量,卷积层将提取特征,全连接层将生成分类结果。 4. 训练模型 我们将使用交叉熵损失函数和Adam优化器来训练我们的模型。我们还将使用EarlyStopping回调函数来防止过拟合。 5. 评估模型 我们将使用测试集来评估我们的模型。我们将计算准确性、精确性、召回率和F1分数来评估我们的模型。 下面是代码实现的大致流程: ```python # 导入相关库 import tensorflow as tf from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score # 加载数据集 data = pd.read_csv('data.csv') # 定义标签 labels = ['体育', '娱乐', '家居', '房产', '教育'] # 过滤数据集 data = data[data['label'].isin(labels)] data = data.sample(frac=1).reset_index(drop=True) # 分割训练集和测试集 train_data, test_data = train_test_split(data, test_size=0.2, random_state=42) # 创建Tokenizer对象 tokenizer = Tokenizer(num_words=5000, oov_token='<OOV>') # 将文本转换为数字序列 tokenizer.fit_on_texts(train_data['text']) train_sequences = tokenizer.texts_to_sequences(train_data['text']) test_sequences = tokenizer.texts_to_sequences(test_data['text']) # 填充序列 max_length = 100 train_padded = pad_sequences(train_sequences, maxlen=max_length, padding='post', truncating='post') test_padded = pad_sequences(test_sequences, maxlen=max_length, padding='post', truncating='post') # 构建模型 model = tf.keras.Sequential([ tf.keras.layers.Embedding(input_dim=5000, output_dim=64, input_length=max_length), tf.keras.layers.Conv1D(filters=128, kernel_size=5, activation='relu'), tf.keras.layers.GlobalMaxPooling1D(), tf.keras.layers.Dense(units=64, activation='relu'), tf.keras.layers.Dense(units=len(labels), activation='softmax') ]) # 编译模型 model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # 定义回调函数 early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=2) # 训练模型 model.fit(train_padded, train_data['label'], validation_split=0.2, epochs=10, callbacks=[early_stopping]) # 评估模型 predictions = model.predict(test_padded) predictions = [np.argmax(p) for p in predictions] accuracy = accuracy_score(test_data['label'], predictions) precision = precision_score(test_data['label'], predictions, average='macro') recall = recall_score(test_data['label'], predictions, average='macro') f1 = f1_score(test_data['label'], predictions, average='macro') print('Accuracy:', accuracy) print('Precision:', precision) print('Recall:', recall) print('F1 Score:', f1) ``` 希望这个例子对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值