栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

keras学习笔记--交叉熵

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

keras学习笔记--交叉熵

交叉熵是一种损失函数,常用于分类问题中。

原文章讲的 很清楚:损失函数|交叉熵损失函数 - 知乎

如何用看下面这个例子:

#修改交叉熵;在做分类问题时,使用交叉熵迭代效果会更好,效率也更高
model.compile(
    optimizer = sgd,
    loss ='categorical_crossentropy',
    metrics=['accuracy'],
)

此处配置模型时将损失函数直接修改为交叉熵。

本文的例子是基于上一篇的MNIST手写数字识别来的,将损失函数修改为交叉熵,发现效果是更好的,接下来上代码。

import numpy as np
import tensorflow as tf
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense
from tensorflow.keras.optimizers import SGD
#载入数据
(x_train,y_train),(x_test,y_test)=mnist.load_data()
#
print('x_shape:',x_train.shape)
print('y_shape:',y_train.shape)
#格式化并归一化
x_train = x_train.reshape(x_train.shape[0],-1)/255.0
x_test = x_test.reshape(x_test.shape[0],-1)/255.0
#转玮one hot 格式;num_class为输出的类别
y_train = np_utils.to_categorical(y_train,num_classes=10)
y_test = np_utils.to_categorical(y_test,num_classes=10)

#创建模型,输入784个神经元,输出10个神经元
model = Sequential([
     Dense(units =10,input_dim =784,bias_initializer='one',activation='softmax')
])
#定义优化器
sgd = SGD(lr=0.2)
#修改交叉熵;在做分类问题时,使用交叉熵迭代效果会更好,效率也更高
model.compile(
    optimizer = sgd,
    loss ='categorical_crossentropy',
    metrics=['accuracy'],
)

#训练模型
model.fit(x_train,y_train,batch_size=32,epochs=10)

#评估模型
loss,accuracy = model.evaluate(x_test,y_test)
print('ntest loss',loss)
print('accuracy',accuracy)

结果如下:

 上文使用mse作为损失函数时的准确度为0.917,本文使用交叉熵时准确度为0.922.

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/344330.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号