学习笔记||Tensorflow-softmax分类

        对数几率回归解决的是二分类的问题,对于多个选项问题,softmax函数是对数几率回在N个可能不同的值上的推广。

        softmax层的作用是将神经网络的原始输出变为概率分布

\sigma (z)_{j}=\frac{e^{z_{j}}}{\sum_{k=1}^{K}e^{z_{k}}}          for j=1,2,...,k

        softmax样本分量之和为1,只有两个类别时,与对数几率回归相同。计算交叉熵有两种方法:catrgorical_crossentropy和sparse_categorical_crossentropy.

        使用的数据集是Fashion MNIST数据集。其中包含70000张灰度图像,涵盖10个类别。用60000张图像训练网络,用10000张图像评估准确率。

代码实现:

import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

#加载数据集
(train_image, train_label),(test_image,test_label) = tf.keras.datasets.fashion_mnist.load_data()

#查看数据集
train_image.shape
train_label.shape
test_image.shape, test_label.shape

#将第一张图片画出来
plt.imshow(train_image[0])

#看一下第一张图片的取值
train_image[0]

#查看第一张图的最大值
np.max(train_image[0])

#查看训练集的分类
train_label #运行结果中,9就代表属于第9个分类,5代表属于第5个分类

#将数据归一化
train_image = train_image/255
test_image = test_image/255

#查看训练集形状
train_image.shape

使用数字编码时,损失函数使用sparse_categorical_crossentropy

#模型初始化并添加层
model = tf.keras.Sequential()
#原始数据是二维数据,使用Flatten将二维数据扁平成向量
model.add(tf.keras.layers.Flatten(input_shape = (28,28)))
model.add(tf.keras.layers.Dense(128,activation='relu')) #Dense数值太小会失去很多有用的信息
model.add(tf.keras.layers.Dense(10,activation='softmax')) #输出10个值,softmax将其变为概率分布

#模型编译
model.conpile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['acc'])

#模型训练
model.fit(train_image,train_label,epochs = 5)

#模型评价
model.evaluate(test_image,test_label)

#根据acc值就可以知道模型的拟合正确率

独热编码使用catrgorical_crossentropy,

        独热编码编码方法:

                beijing[1,0,0]

                shanghai[0,1,0]

                shenzhen[0,0,1]

tf.keras内置了一种方法将数据进行独热编码:

#将训练数据进行独热编码
train_label_onehot = tf.keras.utils.to_categorical(train_label)

#查看编码结果
train_label_onehot

#查看第一个数据的编码
train_label_onehot[0]

#将测试数据进行独热编码
test_label_onehot = tf.keras.utils.to_categorical(test_label)

#查看编码结果
test_label_onehot

#初始化模型并添加层
model = tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28,28)))
model.add(tf.keras.layers.Dense(128, activation='relu'))
model.add(tf.keras.layers.Dense(10,activation = 'softmax'))

#模型初始化
model.compile(optimizer='adam',loss='categerical_crossentropy',metrics=['acc'])

#模型训练
model.fit(train_image,train_label_onehot,epochs=5)

#模型预测
predict = model.predict(test_image)

#查看评价集
test.image.shape

#查看预测分类结果
predict.shape #给这10000张图片,每一张都给了维度为10的向量

#查看第一条分类结果
predict[0] #softmax输出分量之和相加为一

#要找到向量的最大概率值,取出最大值所在的索引
np.argmax(predict[0])

#查看原始的分类结果
test_label[0] #会发现np.argmax(predict[0])==test_label[0],说明预测结果正确

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值