独热编码与顺序编码分别实现Softmax多分类_为什么独热编码乘以softmax_虽千万人 吾往矣的博客-程序员秘密

技术标签: tensorflow  机器学习  深度学习  迁移学习  

参考文章
对于多分类问题我们使用以下两种损失函数(在model.compile 方法中改写参数 loss)
当标签类别使用独热编码时,使用 loss = 'categorical_crossentropy’计算softmax交叉熵
当标签类别使用顺序编码时,使用 loss = 'sparse_categorical_crossentropy’计算softmax交叉熵
在这里插入图片描述
顺序编码时实现softmax多分类

import gzip

import numpy as np
import tensorflow as tf


def get_data():
    # 文件获取
    train_image = r"../../dataset/fashion-mnist/train-images-idx3-ubyte.gz"
    test_image = r"../../dataset/fashion-mnist/t10k-images-idx3-ubyte.gz"
    train_label = r"../../dataset/fashion-mnist/train-labels-idx1-ubyte.gz"
    test_label = r"../../dataset/fashion-mnist/t10k-labels-idx1-ubyte.gz"  # 文件路径
    paths = [train_label, train_image, test_label, test_image]

    with gzip.open(paths[0], 'rb') as lbpath:
        y_train = np.frombuffer(lbpath.read(), np.uint8, offset=8)

    with gzip.open(paths[1], 'rb') as imgpath:
        x_train = np.frombuffer(
            imgpath.read(), np.uint8, offset=16).reshape(len(y_train), 28, 28)

    with gzip.open(paths[2], 'rb') as lbpath:
        y_test = np.frombuffer(lbpath.read(), np.uint8, offset=8)

    with gzip.open(paths[3], 'rb') as imgpath:
        x_test = np.frombuffer(
            imgpath.read(), np.uint8, offset=16).reshape(len(y_test), 28, 28)

    return (x_train, y_train), (x_test, y_test)


# 加载数据
(train_image, train_lable), (test_image, test_label) = get_data()

# print(train_image.shape)
# print(train_lable.shape)
# plt.imshow(train_image[0])
# plt.show()

train_image = train_image / 255
test_image = test_image / 255

model = tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28, 28)))  # 28*28
model.add(tf.keras.layers.Dense(128, activation='relu'))
model.add(tf.keras.layers.Dense(10, activation='softmax'))
print(model.summary())
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['acc']
              )
model.fit(train_image, train_lable, epochs=5)
model.evaluate(test_image, test_label)

独热编码时实现softmax多分类

import gzip

import numpy as np
import tensorflow as tf


def get_data():
    # 文件获取
    train_image = r"../../dataset/fashion-mnist/train-images-idx3-ubyte.gz"
    test_image = r"../../dataset/fashion-mnist/t10k-images-idx3-ubyte.gz"
    train_label = r"../../dataset/fashion-mnist/train-labels-idx1-ubyte.gz"
    test_label = r"../../dataset/fashion-mnist/t10k-labels-idx1-ubyte.gz"  # 文件路径
    paths = [train_label, train_image, test_label, test_image]

    with gzip.open(paths[0], 'rb') as lbpath:
        y_train = np.frombuffer(lbpath.read(), np.uint8, offset=8)

    with gzip.open(paths[1], 'rb') as imgpath:
        x_train = np.frombuffer(
            imgpath.read(), np.uint8, offset=16).reshape(len(y_train), 28, 28)

    with gzip.open(paths[2], 'rb') as lbpath:
        y_test = np.frombuffer(lbpath.read(), np.uint8, offset=8)

    with gzip.open(paths[3], 'rb') as imgpath:
        x_test = np.frombuffer(
            imgpath.read(), np.uint8, offset=16).reshape(len(y_test), 28, 28)

    return (x_train, y_train), (x_test, y_test)


# 加载数据
(train_image, train_lable), (test_image, test_label) = get_data()

# print(train_image.shape)
# print(train_lable.shape)
# plt.imshow(train_image[0])
# plt.show()

train_image = train_image / 255
test_image = test_image / 255

# 将顺序编码转为独热编码
train_label_onehot = tf.keras.utils.to_categorical(train_lable)
test_label_onehot = tf.keras.utils.to_categorical(test_label)

model = tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28, 28)))  # 28*28
model.add(tf.keras.layers.Dense(128, activation='relu'))
model.add(tf.keras.layers.Dense(10, activation='softmax'))
print(model.summary())
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.01),
              loss='categorical_crossentropy',
              metrics=['acc']
              )
model.fit(train_image, train_label_onehot, epochs=5)
predict = model.predict(test_image)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_44575660/article/details/112862400

智能推荐

result之global-results全局结果集_weixin_30239339的博客-程序员秘密

1:如图:传type值根据传入的值选择返回结果:注意:你会发现,在对应的avtion中根本没有action叫“mainpage”,原因是:当有多个action返回同一个结果时,只需要配置一个全局action即可如图:2:假如另外一个package想用另外一个package全局结果集时,如何配置?此时:extends就起作用了,将默认的改为另外一个包的包名即可。3...

In Vehicle Infortainment (IVI) 车载信息娱乐系统_diyun5122的博客-程序员秘密

本文将作为工作笔记将不断补充更新有关IVI的行业信息。【行业公司】Cinemo:德国。汽车级嵌入式多媒体播放、流媒体、媒体管理和连接中间件的全球领导者NXP:荷兰。恩智浦半导体,由飞利浦公司创立。2015年2月,与飞思卡尔(Freescale)合并【行业术语】meter:计量仪。指车辆仪表盘center panel:中央面板。指车辆中控head uni...

squashfs 文件系统的制作与使用_mksquashfs__kerneler的博客-程序员秘密

简介quashfs是以linux 内核源码补丁的形式发布,附带mksquashfs工具,用于创建squash文件系统。squashfs可以将整个文件系统或者某个单一的目录压缩在一起, 存放在某个设备, 某个分区或者普通的文件中. 如果你将其压缩到一个设备中, 那么你可以将其直接mount起来使用; 而如果它仅仅是个文件,你可以将其当为一个loopback 设备使用. squashfs文件系统的设计令人欣喜. For archiving purposes, 它可以让你更加灵活的使用, 而且它比.tar.g

混合易失和非易失主存的日志结构文件系统NOVA[FAST‘16](前言部分到实现部分)_Test1688root的博客-程序员秘密

前言写这篇博文的初衷是NOVA采用了Eurosys‘14文章system software for persistent memory相同的实验平台PMEP(Persistent Memory Emulation Platform)。此篇文章主要基于混合易失/非易失内存主内存上的日志结构文件系统,采用DRAM模拟的非易失内存PM(Persistent Memory),具有DAX(Direct Access)功能,可通过mmap直接将PM设备映射到应用程序地址空间中。本篇文章是我今年四月份精读过的一篇好文

Android Studio使用IconFont阿里矢量图标库_android studio 图标库_沧海龙腾LV的博客-程序员秘密

什么是矢量图矢量图 svg 是 W3C(World Wide Web ConSortium 国际互联网标准组织)在2000年8月制定的一种新的二维矢量图形格式,也是规范中的网络矢量图形标准。矢量图像用点和线来描述物体,所以文件会比较小,同时也能提供高清晰的画面。用户可以任意缩放图像显示,而不会破坏图像的清晰度、细节等。总体来讲,SVG文件比那些GIF和JPEG格式的文件要小很多,因而下载也很快。只要跟着本文章的步骤保证你能很快的集成到项目中使用优缺点 文件小,图像中保存的是线条和图块的信息

随便推点

Java类加载链接初始化过程_Jasper兰的博客-程序员秘密

Java类加载链接初始化过程类加载类加载器继承关系(如图1所示)BootStarp 根类加载器,无法直接获得ExtClassLoader 拓展类加载器SystemclassLoader(AppClassLoader) 系统类加载器 为所有自定义类加载器的父类,自己写的Java类一般由该加载器加载图1:类加载器继承关系双亲委派机制双亲委托模型的工作过程是:如果一个类加载器收到了类加载的请求,它首先不会自己去尝试加载这个类,而是把这个请求委托给父类加载器去完成,每

[译] 提高营销效率的工程(第一部分)_weixin_34259159的博客-程序员秘密

原文地址:Engineering to Improve Marketing Effectiveness (Part 1)原文作者:Netflix Technology Blog译文出自:掘金翻译计划本文永久链接:github.com/xitu/gold-m…译者:Starrier校对者:kuangbao9作者— Subir Parulekar、Gopal Krishnan“让...

【Android】用Android Studio将项目打包成apk_ScriptGirl的博客-程序员秘密

1、Build——Generate Signed Bundle or APK这里不是mykey,而是android.keystore2、

Vue设置title属性动态显示标签里的内容_动态title属性_在线小白www的博客-程序员秘密

<div :title="item.name">{{item.name}}</div>将后端传回来的数据格式直接绑定在title上即可,就是这么简单。。。

ubuntu mysql emma中文乱码问题解决_weixin_30591551的博客-程序员秘密

ubuntu mysql emma中文乱码问题解决 emma默认用apt-get 安装的话,emma是不支持中文的,配置文件或直接修改emma程序源文件(python)。apt-get安装emmasudo apt-get install emma ubuntu的apt-get 安装emma是在/usr/share/emma目录下面。cd /usr/share...

iOS获取最顶层ViewController_早起的年轻人的博客-程序员秘密

1.获取当前屏幕显示的 Viewcontroller 案例源码2.UIApplication 的简析3.KeyWindow 的简析4.rootViewController 的简析5.PresentedViewController 的简析1 获取当前屏幕显示的 Viewcontroller//获取当前屏幕显示的viewcontroller- (UIViewController *...

推荐文章

热门文章

相关标签