自定义模型中自定义评价指标的添加问题

自 定 义 模 型 中 自 定 义 评 价 指 标 的 添 加 问 题 自定义模型中自定义评价指标的添加问题

from __future__ import absolute_import, division, print_function, unicode_literals

import tensorflow as tf

from tensorflow.keras.layers import Dense, Flatten, Conv2D
from tensorflow.keras import Model
import numpy as np

print(tf.__version__)
print(np.__version__)


在这里插入图片描述

数据集简介

mnist = np.load("mnist.npz")
x_train, y_train, x_test, y_test = mnist['x_train'],mnist['y_train'],mnist['x_test'],mnist['y_test']

x_train, x_test = x_train / 255.0, x_test / 255.0

import matplotlib.pyplot as plt
 
fig, ax = plt.subplots(
    nrows=2,
    ncols=5,
    sharex=True,
    sharey=True, )
 
ax = ax.flatten()
for i in range(10):
    img = x_train[y_train == i][0].reshape(28, 28)
    ax[i].imshow(img, cmap='Greys', interpolation='nearest')
    
ax[0].set_xticks([])
ax[0].set_yticks([])
plt.tight_layout()
plt.show()

在这里插入图片描述


# Add a channels dimension
x_train = x_train[..., tf.newaxis]
x_test = x_test[..., tf.newaxis]

train_ds = tf.data.Dataset.from_tensor_slices(
    (x_train, y_train)).shuffle(10000).batch(32)
test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32)


class MyModel(Model):
    def __init__(self):
        super(MyModel, self).__init__()
        self.conv1 = Conv2D(32, 3, activation='relu')
        self.flatten = Flatten()
        self.d1 = Dense(128, activation='relu')
        self.d2 = Dense(10, activation='softmax')

    def call(self, x):
        x = self.conv1(x)
        x = self.flatten(x)
        x = self.d1(x)
        return self.d2(x)

#返回的是一个正确的个数
class CatgoricalTruePositives(tf.keras.metrics.Metric):
    def __init__(self, name='categorical_true_positives', **kwargs):
        super(CatgoricalTruePositives, self).__init__(name=name, **kwargs)
        self.true_positives = self.add_weight(name='tp', initializer='zeros')

    def update_state(self, y_true, y_pred, sample_weight=None):
        y_pred = tf.argmax(y_pred,axis=-1)
        values = tf.equal(tf.cast(y_true, 'int32'), tf.cast(y_pred, 'int32'))
        values = tf.cast(values, 'float32')
        if sample_weight is not None:
            sample_weight = tf.cast(sample_weight, 'float32')
            values = tf.multiply(values, sample_weight)
        self.true_positives.assign_add(tf.reduce_sum(values))

    def result(self):
        return self.true_positives

    def reset_states(self):
        self.true_positives.assign(0.)

for x,y in train_ds:
    a = x
    b =y
    break
tf.shape(a)

在这里插入图片描述

tf.shape(b)

在这里插入图片描述

b

在这里插入图片描述


model = MyModel()

loss_object = tf.keras.losses.SparseCategoricalCrossentropy() #损失函数


optimizer = tf.keras.optimizers.Adam() #优化器

#评估函数
train_loss = tf.keras.metrics.Mean(name='train_loss') #loss

train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy') #准确率

train_tp = CatgoricalTruePositives(name="train_tp") #返回正确的个数

test_loss = tf.keras.metrics.Mean(name='test_loss')
test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy')
test_tp = CatgoricalTruePositives(name='test_tp')

@tf.function
def train_step(images, labels):
    with tf.GradientTape() as tape:
        predictions = model(images)
        loss = loss_object(labels, predictions)
    gradients = tape.gradient(loss, model.trainable_variables)
    optimizer.apply_gradients(zip(gradients, model.trainable_variables))

    #评估函数的结果
    train_loss(loss)
    train_accuracy(labels, predictions)
    train_tp(labels, predictions)

@tf.function
def test_step(images, labels):
    predictions = model(images)
    t_loss = loss_object(labels, predictions)

    test_loss(t_loss)
    test_accuracy(labels, predictions)
    test_tp(labels, predictions)

EPOCHS = 5
for epoch in range(EPOCHS):
    # 在下一个epoch开始时,重置评估指标
    train_loss.reset_states()
    train_accuracy.reset_states()
    train_tp.reset_states()
    test_loss.reset_states()
    test_accuracy.reset_states()
    test_tp.reset_states()


    for images, labels in train_ds:
        train_step(images, labels)

    for test_images, test_labels in test_ds:
        test_step(test_images, test_labels)

    template = 'Epoch {}, Loss: {}, Accuracy: {}, TP: {},Test Loss: {}, Test Accuracy: {}, Test TP:{}'
    print(template.format(epoch + 1,
                          train_loss.result(),
                          train_accuracy.result() * 100,
                          train_tp.result(),
                          test_loss.result(),
                          test_accuracy.result() * 100,
                          test_tp.result()))

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WDCNN(Wide and Deep Convolutional Neural Network)是一种经典的深度学习模型,它结合了卷积神经网络(CNN)的广度和深度学习的思想,在多个领域都取得了良好的表现。下面是使用PyTorch复现WDCNN模型的步骤: 1. 数据准备:从数据集获取需要训练和测试的数据,并进行预处理。预处理包括数据的归一化、划分训练集和测试集等。 2. 模型搭建:使用PyTorch搭建WDCNN模型。首先定义卷积层和池化层,然后定义全连接层。可以根据具体需求选择不同的卷积神经网络结构,也可以自定义网络结构。 3. 模型训练:使用定义好的模型对训练集进行训练。可以使用随机梯度下降(SGD)等优化算法,选择合适的损失函数计算损失,并通过反向传播算法更新模型的参数。 4. 模型评估:使用训练好的模型对测试集进行预测,计算预测准确率等评价指标。可以使用混淆矩阵、准确率、召回率等指标评估模型性能。 5. 超参数调优:根据模型的评估结果,调整超参数,如学习率、batch size等,以提高模型的性能。 6. 模型保存和加载:将训练好的模型保存到本地文件,以便后续的使用和部署。可以使用PyTorch提供的模型保存和加载功能。 通过以上步骤,可以使用PyTorch复现WDCNN模型。在实际应用,根据具体任务的需求,可以对模型结构进行修改和优化,例如添加正则化、dropout层等,以提高模型的泛化能力和鲁棒性。同时,可以通过增加训练数据集的规模、使用数据增强等方法来进一步改善模型性能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值