一个简单的卷积神经网络的——functions.py

# coding: utf-8
import numpy as np


# ----------------------------------------------------------------------
def identity_function(x):
    return x


# -----------------------------------------------------------------------
def step_funcetion(x):
    return np.array(x > 0, dtype=np.int) # 数据类型转换,x>0则为True


# ------------------------sigmoid函数------------------------------------------
def sigmoid(x):
    return 1 / (1 + np.exp(-x))


def sigmoid_grad(x):
    return (1.0 - sigmoid(x)) * sigmoid(x)


# ---------------------------relu函数-----------------------------------------
def relu(x):
    return np.maximum(0, x)


def relu_grad(x):
    grad = np.zeros(x) # 生成与x结构一样的数据
    grad[x > 0] = 1 # grad中x>0的值设为1
    return grad


# --------------------------softmax分类器-------------------------------------
"""python中 axis对应于轴且有方向
axis=0,代表纵轴,且从上到下
axis=1,代表横轴,且从左到右
"""
def softmax(x):
    if x.ndim == 2: # x是2维数组
        x = x.T # 转置
        x = x - np.max(x, axis=0) # 溢出对策,因为指数可能发生爆炸
        y = np.exp(x) / np.sum(np.exp(x), axis=0)
        return y.T

    x = x - np.max(x) # 溢出对策
    return np.exp(x) / np.sum(np.exp(x))


# -------------------------------------------------------------------------------
def mean_squared_error(y, t):
    return 0.5 * np.sum((y - t)**2) # 平方差误差,输出减去标签


# --------------------------交叉误差熵函数----------------------------------------
def cross_entropy_error(y, t):
    if y.ndim == 1:
        t = t.reshape(1, t.size)
        y = y.reshape(1, y.size)

    # 监督数据是one-hot-vector的情况下,转换为正确解标签的索引
    if t.size == y.size:
        t = t.argmax(axis=1)

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


# ---------------------softmax_loss函数层-----------------------------------------
def softmax_loss(X, t):
    y = softmax(X)
    return cross_entropy_error(y, t)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值