Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >SELU︱在keras、tensorflow中使用SELU激活函数

SELU︱在keras、tensorflow中使用SELU激活函数

作者头像
悟乙己
发布于 2018-01-02 08:54:56
发布于 2018-01-02 08:54:56
2.5K00
代码可运行
举报
文章被收录于专栏:素质云笔记素质云笔记
运行总次数:0
代码可运行

arXiv 上公开的一篇 NIPS 投稿论文《Self-Normalizing Neural Networks》引起了圈内极大的关注,它提出了缩放指数型线性单元(SELU)而引进了自归一化属性,该单元主要使用一个函数 g 映射前后两层神经网络的均值和方差以达到归一化的效果。 Shao-Hua Sun 在 Github 上放出了 SELU 与 Relu、Leaky Relu 的对比,机器之心对比较结果进行了翻译介绍,具体的实现过程可参看以下项目地址。

项目地址:shaohua0116/Activation-Visualization-Histogram 来源机器之心:引爆机器学习圈:「自归一化神经网络」提出新型激活函数SELU

keras中使用SELU激活函数

在keras 2.0.6版本之后才可以使用selu激活函数,但是在版本2.0.5还是不行,所以得升级到这个版本。 在全连接层后面接上selu最终收敛会快一些

来看一下,一个介绍非常详细的github:bigsnarfdude/SELU_Keras_Tutorial

具体对比效果:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
from __future__ import print_function

import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.layers.noise import AlphaDropout
from keras.utils import np_utils
from keras.optimizers import RMSprop, Adam

batch_size = 128
num_classes = 10
epochs = 20
learning_rate = 0.001

# the data, shuffled and split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

x_train = x_train.reshape(60000, 784)
x_test = x_test.reshape(10000, 784)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

modelSELU = Sequential()
modelSELU.add(Dense(512, activation='selu', input_shape=(784,)))
modelSELU.add(AlphaDropout(0.1))
modelSELU.add(Dense(512, activation='selu'))
modelSELU.add(AlphaDropout(0.1))
modelSELU.add(Dense(10, activation='softmax'))

modelSELU.summary()

modelSELU.compile(loss='categorical_crossentropy',
              optimizer=RMSprop(),
              metrics=['accuracy'])

historySELU = modelSELU.fit(x_train, y_train,
                    batch_size=batch_size,
                    epochs=epochs,
                    verbose=1,
                    validation_data=(x_test, y_test))
scoreSELU = modelSELU.evaluate(x_test, y_test, verbose=0)
print('Test loss:', scoreSELU[0])
print('Test accuracy:', scoreSELU[1])

tensorflow中使用dropout_selu + SELU

该文作者在tensorflow也加入了selu 和 dropout_selu两个新的激活函数。 可见:https://github.com/bigsnarfdude/SELU_Keras_Tutorial/blob/master/Basic_MLP_combined_comparison.ipynb 定义了两个新函数:SELU 和 dropout_selu

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
def selu(x):
    with ops.name_scope('elu') as scope:
        alpha = 1.6732632423543772848170429916717
        scale = 1.0507009873554804934193349852946
        return scale*tf.where(x>=0.0, x, alpha*tf.nn.elu(x))

def dropout_selu(x, keep_prob, alpha= -1.7580993408473766, fixedPointMean=0.0, fixedPointVar=1.0,
                 noise_shape=None, seed=None, name=None, training=False):
    """Dropout to a value with rescaling."""

    def dropout_selu_impl(x, rate, alpha, noise_shape, seed, name):
        keep_prob = 1.0 - rate
        x = ops.convert_to_tensor(x, name="x")
        if isinstance(keep_prob, numbers.Real) and not 0 < keep_prob <= 1:
            raise ValueError("keep_prob must be a scalar tensor or a float in the "
                                             "range (0, 1], got %g" % keep_prob)
        keep_prob = ops.convert_to_tensor(keep_prob, dtype=x.dtype, name="keep_prob")
        keep_prob.get_shape().assert_is_compatible_with(tensor_shape.scalar())

        alpha = ops.convert_to_tensor(alpha, dtype=x.dtype, name="alpha")
        keep_prob.get_shape().assert_is_compatible_with(tensor_shape.scalar())

        if tensor_util.constant_value(keep_prob) == 1:
            return x

        noise_shape = noise_shape if noise_shape is not None else array_ops.shape(x)
        random_tensor = keep_prob
        random_tensor += random_ops.random_uniform(noise_shape, seed=seed, dtype=x.dtype)
        binary_tensor = math_ops.floor(random_tensor)
        ret = x * binary_tensor + alpha * (1-binary_tensor)

        a = tf.sqrt(fixedPointVar / (keep_prob *((1-keep_prob) * tf.pow(alpha-fixedPointMean,2) + fixedPointVar)))

        b = fixedPointMean - a * (keep_prob * fixedPointMean + (1 - keep_prob) * alpha)
        ret = a * ret + b
        ret.set_shape(x.get_shape())
        return ret

    with ops.name_scope(name, "dropout", [x]) as name:
        return utils.smart_cond(training,
                                lambda: dropout_selu_impl(x, keep_prob, alpha, noise_shape, seed, name),
                                lambda: array_ops.identity(x))

作者将其使用在以下案例之中:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# Check out https://www.tensorflow.org/get_started/mnist/beginners for
# more information about the mnist dataset

# parameters
learning_rate = 0.001
training_epochs = 50
batch_size = 100

# input place holders
X = tf.placeholder(tf.float32, [None, 784])
Y = tf.placeholder(tf.float32, [None, 10])

# dropout (keep_prob) rate  0.7 on training, but should be 1 for testing
keep_prob = tf.placeholder(tf.float32)

# weights & bias for nn layers
# http://stackoverflow.com/questions/33640581/how-to-do-xavier-initialization-on-tensorflow
W1 = tf.get_variable("W1", shape=[784, 512],
                     initializer=tf.contrib.layers.xavier_initializer())
b1 = tf.Variable(tf.random_normal([512]))
L1 = selu(tf.matmul(X, W1) + b1)
L1 = dropout_selu(L1, keep_prob=keep_prob)

W2 = tf.get_variable("W2", shape=[512, 512],
                     initializer=tf.contrib.layers.xavier_initializer())
b2 = tf.Variable(tf.random_normal([512]))
L2 = selu(tf.matmul(L1, W2) + b2)
L2 = dropout_selu(L2, keep_prob=keep_prob)

W3 = tf.get_variable("W3", shape=[512, 512],
                     initializer=tf.contrib.layers.xavier_initializer())
b3 = tf.Variable(tf.random_normal([512]))
L3 = selu(tf.matmul(L2, W3) + b3)
L3 = dropout_selu(L3, keep_prob=keep_prob)

W4 = tf.get_variable("W4", shape=[512, 512],
                     initializer=tf.contrib.layers.xavier_initializer())
b4 = tf.Variable(tf.random_normal([512]))
L4 = selu(tf.matmul(L3, W4) + b4)
L4 = dropout_selu(L4, keep_prob=keep_prob)

W5 = tf.get_variable("W5", shape=[512, 10],
                     initializer=tf.contrib.layers.xavier_initializer())
b5 = tf.Variable(tf.random_normal([10]))
hypothesis = tf.matmul(L4, W5) + b5

# define cost/loss & optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
    logits=hypothesis, labels=Y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

# initialize
sess = tf.Session()
sess.run(tf.global_variables_initializer())

# train my model
for epoch in range(training_epochs):
    avg_cost = 0
    total_batch = int(mnist.train.num_examples / batch_size)

    for i in range(total_batch):
        batch_xs, batch_ys = mnist.train.next_batch(batch_size)
        feed_dict = {X: batch_xs, Y: batch_ys, keep_prob: 0.7}
        c, _ = sess.run([cost, optimizer], feed_dict=feed_dict)
        avg_cost += c / total_batch

    print('Epoch:', '%04d' % (epoch + 1), 'cost =', '{:.9f}'.format(avg_cost))

print('Learning Finished!')

# Test model and check accuracy
correct_prediction = tf.equal(tf.argmax(hypothesis, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
tensorflow编程: Layers (contrib)
min(max(features, 0), 6)。即对 tf.nn.relu 的优化,防止 relu过后 某些 极端值 依然 大于6
JNingWei
2018/09/28
8060
tensorflow dropout实现
指定keep_prob即可,下面的例子使用了占位符。为了简便起见,直接给keep_prob赋一个定值可能更好,但占位符在每次运行时都可以指定keep_prob的值。
Steve Wang
2019/05/26
9290
利用tensorflow训练简单的生成对抗网络GAN
对抗网络是14年Goodfellow Ian在论文Generative Adversarial Nets中提出来的。 原理方面,对抗网络可以简单归纳为一个生成器(generator)和一个判断器(discriminator)之间博弈的过程。整个网络训练的过程中,
狼啸风云
2020/09/27
1.2K0
【DL笔记5】一文上手TensorFlow,并搭建神经网络实现手写数字识别
从【DL笔记1】到【DL笔记N】,是我学习深度学习一路上的点点滴滴的记录,是从Coursera网课、各大博客、论文的学习以及自己的实践中总结而来。从基本的概念、原理、公式,到用生动形象的例子去理解,到动手做实验去感知,到著名案例的学习,到用所学来实现自己的小而有趣的想法......我相信,一路看下来,我们可以感受到深度学习的无穷的乐趣,并有兴趣和激情继续钻研学习。 正所谓 Learning by teaching,写下一篇篇笔记的同时,我也收获了更多深刻的体会,希望大家可以和我一同进步,共同享受AI无穷的乐趣。
beyondGuo
2018/10/25
7880
【DL笔记5】一文上手TensorFlow,并搭建神经网络实现手写数字识别
深度学习之 TensorFlow(五):mnist 的 Alexnet 实现
尝试用 Alexnet 来构建一个网络模型,并使用 mnist 数据查看训练结果。 我们将代码实现分为三个过程,加载数据、定义网络模型、训练数据和评估模型。 实现代码如下: #-*- coding:utf-8 -*_ #加载数据 import tensorflow as tf # 输入数据 from tensorflow.examples.tutorials.mnist import input_data #TensorFlow 自带,用来下载并返回 mnist 数据。可以自己下载 mnist数据
希希里之海
2018/05/16
7100
tensorflow学习笔记(八):dropout
我们都知道dropout对于防止过拟合效果不错 dropout一般用在全连接的部分,卷积部分一般不会用到dropout,输出曾也不会使用dropout,适用范围[输入,输出)
ke1th
2019/05/26
5670
tf21: 身份证识别——识别身份证号
上一篇: 身份证识别——生成身份证号和汉字 代码直接参考,验证码识别 #!/usr/bin/env python2 # -*- coding: utf-8 -*- """ tf 训练识别身份证数字(18个字符)图片 @author: 刘鹏 """ from genIDCard import * import numpy as np import tensorflow as tf #obj = gen_id_card() #image,text,vec = obj.gen_image() #图像大小
MachineLP
2018/01/09
5.8K0
优达学城深度学习之六——TensorFlow实现卷积神经网络
TensorFlow提供了tf.nn.conv2d() 和tf.nn.bias_add() 函数来创建你自己的卷积层。
墨明棋妙27
2022/08/24
2530
优达学城深度学习之六——TensorFlow实现卷积神经网络
初步了解TensorFlow
在本章中,我们一起来学习下TensorFlow。我们将会学习到TensorFlow的一些基本库。通过计算一个线性函数来熟悉这些库。最后还学习使用TensorFlow搭建一个神经网络来识别手势。本章用到的一些库在这里下载。
夜雨飘零
2020/05/06
5520
02.改善深层神经网络:超参数调试、正则化以及优化 W3. 超参数调试、Batch Norm和程序框架(作业:TensorFlow教程+数字手势预测)
笔记:02.改善深层神经网络:超参数调试、正则化以及优化 W3. 超参数调试、Batch Norm和程序框架
Michael阿明
2021/02/19
9270
TensorFlow基础入门
到目前为止,您一直使用numpy来构建神经网络。现在我们将引导您使用一个深度学习框架,让您可以更轻松地构建神经网络。TensorFlow、PaddlePaddle、Torch、Caffe、Keras等机器学习框架可显著加速机器学习开发。在此作业中,您将学习在TensorFlow中执行以下操作:
云水木石
2019/07/01
1.7K0
TensorFlow基础入门
Tensorflow ActiveFunction激活函数解析
输入参数:● features: 一个Tensor。数据类型必须是:float32,float64,int32,int64,uint8,int16,int8。● name: (可选)为这个操作取一个名字。
演化计算与人工智能
2020/08/14
1.3K0
Tensorflow ActiveFunction激活函数解析
tensorflow0.10.0 ptb_word_lm.py 源码解析
Created with Raphaël 2.1.0inputlstm1_1lstm2_1softmaxoutput
ke1th
2019/05/28
4670
TensorFlow_Tutorial_v3b——improving NN performance测验
Welcome to this week's programming assignment. Until now, you've always used numpy to build neural networks. Now we will step you through a deep learning framework that will allow you to build neural networks more easily. Machine learning frameworks like TensorFlow, PaddlePaddle, Torch, Caffe, Keras, and many others can speed up your machine learning development significantly. All of these frameworks also have a lot of documentation, which you should feel free to read. In this assignment, you will learn to do the following in TensorFlow:
列夫托尔斯昊
2020/08/25
1.4K0
TensorFlow_Tutorial_v3b——improving NN performance测验
tensorflow 实现wgan-gp mnist图片生成
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_25737169/article/details/76695935
DoubleV
2018/09/12
1.5K0
tensorflow 实现wgan-gp  mnist图片生成
开发 | 如何利用微信监管你的TF训练
AI科技评论按:本文作者Coldwings,AI科技评论获其授权发布。 之前回答问题【在机器学习模型的训练期间,大概几十分钟到几小时不等,大家都会在等实验的时候做什么?】的时候,说到可以用微信来管着训练,完全不用守着。没想到这么受欢迎…… 原问题下的回答如下 不知道有哪些朋友是在TF/keras/chainer/mxnet等框架下用python撸的….… 这可是python啊……上itchat,弄个微信号加自己为好友(或者自己发自己),训练进展跟着一路发消息给自己就好了,做了可视化的话顺便把图也一并发过来。
AI科技评论
2018/03/14
6990
开发 | 如何利用微信监管你的TF训练
(二)Tensorflow搭建卷积神经网络实现MNIST手写字体识别及预测
1 搭建卷积神经网络 1.0 网络结构 [图1.0 卷积网络结构 ] 1.2 网络分析 序号 网络层 描述 1 卷积层 一张原始图像(28, 28, 1),batch=1,经过卷积处理,得到图像特征(28, 28, 32) 2 下采样 即池化层,最大池化后图像特征(14, 14, 32) 3 卷积层 将池化特征(14, 14, 32)卷积处理后,得到图像特征(14, 14, 64) 4 下采样 最大池化,得到图像特征(7, 7, 64) 5 全连接层 将上一层即池化层的图像特征经过矩阵内积计算,拉成一个向量
xdq101
2019/06/02
7680
(二)Tensorflow搭建卷积神经网络实现MNIST手写字体识别及预测
[TensorFlow深度学习入门]实战六·用CNN做Kaggle比赛手写数字识别准确率99%+
参考博客地址 本博客采用Lenet5实现,也包含TensorFlow模型参数保存与加载参考我的博文,实用性比较好。在训练集准确率99.85%,测试训练集准确率99%+。
小宋是呢
2019/06/27
9580
【深度学习系列】用PaddlePaddle和Tensorflow实现经典CNN网络Vgg
  上周我们讲了经典CNN网络AlexNet对图像分类的效果,2014年,在AlexNet出来的两年后,牛津大学提出了Vgg网络,并在ILSVRC 2014中的classification项目的比赛中取得了第2名的成绩(第一名是GoogLeNet,也是同年提出的)。在论文《Very Deep Convolutional Networks for Large-Scale Image Recognition》中,作者提出通过缩小卷积核大小来构建更深的网络。 Vgg网络结构 VGGnet是Oxford的Visu
Charlotte77
2018/01/09
1.9K0
【深度学习系列】用PaddlePaddle和Tensorflow实现经典CNN网络Vgg
【深度学习】实例第三部分:TensorFlow
注意:此代码全部为TensorFlow1版本。 查看Tensorflow版本 from __future__ import absolute_import, division, print_function, unicode_literals # 导入TensorFlow和tf.keras import tensorflow as tf from tensorflow import keras # 导入辅助库 import numpy as np import matplotlib.pyplot as
杨丝儿
2022/02/28
9920
推荐阅读
相关推荐
tensorflow编程: Layers (contrib)
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验