手写Cross Entropy Loss Function

手写交叉熵Cross Entropy Loss Function,针对分割任务,2D-Tensor

最近准备在cross entropy的基础上自定义loss function, 但是看pytorch的源码Python部分没有写loss function的实现,看实现过程还得去翻它的c代码,比较复杂。写这个帖子的另一个原因是,网络上大多数Cross Entropy Loss 的实现是针对于一维信号,或者是分类任务的,没找到关于分割任务的。因此,准备手写一个Cross Entropy Loss Function,也供大家参考。

先介绍两种Pytorch的Cross Entropy loss function的写法

一. Pytorch 比较常用的CrossEntropyLoss

import torch
ce_loss = torch.nn.CrossEntropyLoss(ignore_index=255, reduction='mean', size_average = True)
cross_entropy1 = ce_loss(yHat, y)

yHat 就是模型的输出,y就是了label。

二. 使用Pytorch里面的

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
抱歉,作为AI语言模型,我无法手写代码或进行图像识别任务。但是,我可以为您提供一个基本的MLP代码框架,您可以使用它来构建一个MINIST手写字体识别MLP模型: ``` import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) # Define hyperparameters learning_rate = 0.1 num_epochs = 100 batch_size = 100 # Define the number of neurons in each layer input_layer = 784 hidden_layer1 = 256 hidden_layer2 = 256 output_layer = 10 # Define the input and output placeholders X = tf.placeholder(tf.float32, [None, input_layer]) Y = tf.placeholder(tf.float32, [None, output_layer]) # Define the weights and biases for each layer weights = { 'w1': tf.Variable(tf.random_normal([input_layer, hidden_layer1])), 'w2': tf.Variable(tf.random_normal([hidden_layer1, hidden_layer2])), 'out': tf.Variable(tf.random_normal([hidden_layer2, output_layer])) } biases = { 'b1': tf.Variable(tf.random_normal([hidden_layer1])), 'b2': tf.Variable(tf.random_normal([hidden_layer2])), 'out': tf.Variable(tf.random_normal([output_layer])) } # Define the forward propagation hidden_layer1_output = tf.nn.relu(tf.add(tf.matmul(X, weights['w1']), biases['b1'])) hidden_layer2_output = tf.nn.relu(tf.add(tf.matmul(hidden_layer1_output, weights['w2']), biases['b2'])) output = tf.add(tf.matmul(hidden_layer2_output, weights['out']), biases['out']) # Define the loss function and optimizer loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=output, labels=Y)) optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(loss) # Define the accuracy metric correct_pred = tf.equal(tf.argmax(output, 1), tf.argmax(Y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) # Initialize the variables init = tf.global_variables_initializer() # Start the session with tf.Session() as sess: sess.run(init) num_batches = int(mnist.train.num_examples/batch_size) # Train the model for epoch in range(num_epochs): avg_loss = 0 for batch in range(num_batches): batch_x, batch_y = mnist.train.next_batch(batch_size) _, l = sess.run([optimizer, loss], feed_dict={X: batch_x, Y: batch_y}) avg_loss += l/num_batches if epoch % 10 == 0: print("Epoch:", epoch+1, " Loss:", avg_loss) # Test the model test_accuracy = sess.run(accuracy, feed_dict={X: mnist.test.images, Y: mnist.test.labels}) print("Test Accuracy:", test_accuracy) ``` 这个代码框架包含了一个基本的MLP模型,使用MNIST数据集进行训练和测试。您可以根据需要进行调整和修改,以获得更好的性能和准确性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值