深度学习入门——mini_batch小批量数据的交叉熵误差

# coding:utf-8

import sys, os
sys.path.append(os.pardir)
import numpy as np
from dataset.mnist import load_mnist


(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, one_hot_label=True)

print(x_train.shape) # (6000. 784) 6000个数据,784维
print(t_train.shape) # (6000, 10) 6000个数据,10维

# --------------------------------抽取小批量的数据---------------------------------------------------
# 抽取小批量的数据
train_size = x_train.shape[0]
batch_size = 10 # 抽10个
batch_mask = np.random.choice(train_size, batch_size) # 从6000个数据中随机抽取10个 获得其索引

x_batch = x_train[batch_mask] # 通过索引取出该值
t_batch = t_train[batch_mask] # 通过索引取出该监督值

# -------------------------mini_batch版交叉熵误差的实现,t为one_hot形式----------------------------------------------


def cross_entropy_error(y, t):
    if y.ndim == 1: # 若神经网络输出y为一维数据(单个数据)
        t = t.reshape(1, t.size) # 改变形状成行,后面的矩阵乘法
        y = y.reshape(1, y.size)

    batch_size = y.shape[0]
    return -np.sum(t * np.log(y + 1e-07)) / batch_size

# --------------------------mini_batch版交叉熵误差,t为非one_hot形式------------------------------------------------


def cross_entropy_error_2(y, t):
    if y.ndim == 1:
        t = t.reshape(1, t.size)  # 改变形状成行,后面的矩阵乘法
        y = y.reshape(1, y.size)

    batch_size = y.shape[0]
    return -np.sum(np.log(y[np.arange(batch_size), t] + 1e-07)) / batch_size
# np.arange(batch_size)生成 0~batch_size-1 的数组,又因为t为非one-hot形式,故可以抽取其输出值,例如:y[0, 1]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值