TF之BN:BN算法对多层中的每层神经网络加快学习QuadraticFunction_InputData+Histogram+BN的Error_curve

简介: TF之BN:BN算法对多层中的每层神经网络加快学习QuadraticFunction_InputData+Histogram+BN的Error_curve

输出结果

image.png


代码设计


# 23 Batch Normalization

import numpy as np

import tensorflow as tf

import matplotlib.pyplot as plt

ACTIVATION = tf.nn.tanh

N_LAYERS = 7          

N_HIDDEN_UNITS = 30  

def fix_seed(seed=1):

   # reproducible

   np.random.seed(seed)

   tf.set_random_seed(seed)

def plot_his(inputs, inputs_norm):

   # plot histogram for the inputs of every layer

 

   for j, all_inputs in enumerate([inputs, inputs_norm]):

       for i, input in enumerate(all_inputs):

           plt.subplot(2, len(all_inputs), j*len(all_inputs)+(i+1))

           plt.cla()

           if i == 0:

               the_range = (-7, 10)

           else:

               the_range = (-1, 1)

           plt.hist(input.ravel(), bins=15, range=the_range, color='#0000FF')

           plt.yticks(())

           if j == 1:

               plt.xticks(the_range)

           else:

               plt.xticks(())

           ax = plt.gca()

           ax.spines['right'].set_color('none')

           ax.spines['top'].set_color('none')

       plt.title("%s normalizing" % ("Without" if j == 0 else "With"))

   plt.title('Matplotlib,BN,histogram--Jason Niu')

   plt.draw()

   plt.pause(0.001)

def built_net(xs, ys, norm):

   def add_layer(inputs, in_size, out_size, activation_function=None, norm=False):

       # weights and biases (bad initialization for this case)

       Weights = tf.Variable(tf.random_normal([in_size, out_size], mean=0., stddev=1.))

       biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)

       # fully connected product

       Wx_plus_b = tf.matmul(inputs, Weights) + biases

       # normalize fully connected product

       if norm:

           # Batch Normalize

           fc_mean, fc_var = tf.nn.moments(

               Wx_plus_b,

               axes=[0],  

                         

           )

           scale = tf.Variable(tf.ones([out_size]))

           shift = tf.Variable(tf.zeros([out_size]))

           epsilon = 0.001

           # apply moving average for mean and var when train on batch

           ema = tf.train.ExponentialMovingAverage(decay=0.5)

           def mean_var_with_update():

               ema_apply_op = ema.apply([fc_mean, fc_var])

               with tf.control_dependencies([ema_apply_op]):

                   return tf.identity(fc_mean), tf.identity(fc_var)

           mean, var = mean_var_with_update()

           Wx_plus_b = tf.nn.batch_normalization(Wx_plus_b, mean, var, shift, scale, epsilon)

         

           # Wx_plus_b = (Wx_plus_b - fc_mean) / tf.sqrt(fc_var + 0.001)  #进行BN一下

           # Wx_plus_b = Wx_plus_b * scale + shift

 

       # activation

       if activation_function is None:

           outputs = Wx_plus_b

       else:

           outputs = activation_function(Wx_plus_b)

       return outputs  #输出激活结果

   fix_seed(1)

   if norm:

       # BN for the first input

       fc_mean, fc_var = tf.nn.moments(

           xs,

           axes=[0],

       )

       scale = tf.Variable(tf.ones([1]))

       shift = tf.Variable(tf.zeros([1]))

       epsilon = 0.001

       # apply moving average for mean and var when train on batch

       ema = tf.train.ExponentialMovingAverage(decay=0.5)

       def mean_var_with_update():

           ema_apply_op = ema.apply([fc_mean, fc_var])

           with tf.control_dependencies([ema_apply_op]):

               return tf.identity(fc_mean), tf.identity(fc_var)

       mean, var = mean_var_with_update()

       xs = tf.nn.batch_normalization(xs, mean, var, shift, scale, epsilon)

   # record inputs for every layer

   layers_inputs = [xs]

   # build hidden layers

   for l_n in range(N_LAYERS):

       layer_input = layers_inputs[l_n]

       in_size = layers_inputs[l_n].get_shape()[1].value

       output = add_layer(

           layer_input,    # input

           in_size,        # input size

           N_HIDDEN_UNITS, # output size

           ACTIVATION,     # activation function

           norm,           # normalize before activation

       )

       layers_inputs.append(output)  

   # build output layer

   prediction = add_layer(layers_inputs[-1], 30, 1, activation_function=None)

   cost = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices=[1]))

   train_op = tf.train.GradientDescentOptimizer(0.001).minimize(cost)

   return [train_op, cost, layers_inputs]

fix_seed(1)

x_data = np.linspace(-7, 10, 2500)[:, np.newaxis]  #水平轴-7~10

np.random.shuffle(x_data)

noise = np.random.normal(0, 8, x_data.shape)

y_data = np.square(x_data) - 5 + noise

xs = tf.placeholder(tf.float32, [None, 1])  # [num_samples, num_features]

ys = tf.placeholder(tf.float32, [None, 1])

#建立两个神经网络作对比

train_op, cost, layers_inputs = built_net(xs, ys, norm=False)

train_op_norm, cost_norm, layers_inputs_norm = built_net(xs, ys, norm=True)

sess = tf.Session()

if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:

   init = tf.initialize_all_variables()

else:

   init = tf.global_variables_initializer()

sess.run(init)

# record cost

cost_his = []      

cost_his_norm = []  

record_step = 5    

plt.ion()

plt.figure(figsize=(7, 3))

for i in range(250):

   if i % 50 == 0:

       # plot histogram

       all_inputs, all_inputs_norm = sess.run([layers_inputs, layers_inputs_norm], feed_dict={xs: x_data, ys: y_data})

       plot_his(all_inputs, all_inputs_norm)

   # train on batch每一步都run一下

   sess.run([train_op, train_op_norm], feed_dict={xs: x_data[i*10:i*10+10], ys: y_data[i*10:i*10+10]})

   if i % record_step == 0:

       # record cost

       cost_his.append(sess.run(cost, feed_dict={xs: x_data, ys: y_data}))

       cost_his_norm.append(sess.run(cost_norm, feed_dict={xs: x_data, ys: y_data}))

#以下是绘制误差值Cost误差曲线的方法

plt.ioff()

plt.figure()

plt.title('Matplotlib,BN,Error_curve--Jason Niu')

plt.plot(np.arange(len(cost_his))*record_step, np.array(cost_his), label='no BN')     # no norm

plt.plot(np.arange(len(cost_his))*record_step, np.array(cost_his_norm), label='BN')   # norm

plt.legend()

plt.show()


相关实践学习
【玩转ComfyUI】基于函数计算一键部署AI生图平台ComfyUI
本次实验将带大家通过使用阿里云产品函数计算FC,快速使用ComfyUI实现更高质量的图像生成。
从 0 入门函数计算
在函数计算的架构中,开发者只需要编写业务代码,并监控业务运行情况就可以了。这将开发者从繁重的运维工作中解放出来,将精力投入到更有意义的开发任务上。
相关文章
|
12月前
|
机器学习/深度学习 算法 调度
14种智能算法优化BP神经网络(14种方法)实现数据预测分类研究(Matlab代码实现)
14种智能算法优化BP神经网络(14种方法)实现数据预测分类研究(Matlab代码实现)
727 0
|
机器学习/深度学习 并行计算 算法
粒子群算法优化RBF神经网络的MATLAB实现
粒子群算法优化RBF神经网络的MATLAB实现
671 123
|
11月前
|
机器学习/深度学习 算法
采用蚁群算法对BP神经网络进行优化
使用蚁群算法来优化BP神经网络的权重和偏置,克服传统BP算法容易陷入局部极小值、收敛速度慢、对初始权重敏感等问题。
610 5
|
12月前
|
存储 算法 安全
即时通讯安全篇(三):一文读懂常用加解密算法与网络通讯安全
作为开发者,也会经常遇到用户对数据安全的需求,当我们碰到了这些需求后如何解决,如何何种方式保证数据安全,哪种方式最有效,这些问题经常困惑着我们。52im社区本次着重整理了常见的通讯安全问题和加解密算法知识与即时通讯/IM开发同行们一起分享和学习。
640 9
|
12月前
|
机器学习/深度学习 传感器 算法
【无人车路径跟踪】基于神经网络的数据驱动迭代学习控制(ILC)算法,用于具有未知模型和重复任务的非线性单输入单输出(SISO)离散时间系统的无人车的路径跟踪(Matlab代码实现)
【无人车路径跟踪】基于神经网络的数据驱动迭代学习控制(ILC)算法,用于具有未知模型和重复任务的非线性单输入单输出(SISO)离散时间系统的无人车的路径跟踪(Matlab代码实现)
689 2
|
12月前
|
JavaScript Java 大数据
基于python的网络课程在线学习交流系统
本研究聚焦网络课程在线学习交流系统,从社会、技术、教育三方面探讨其发展背景与意义。系统借助Java、Spring Boot、MySQL、Vue等技术实现,融合云计算、大数据与人工智能,推动教育公平与教学模式创新,具有重要理论价值与实践意义。
|
12月前
|
机器学习/深度学习 并行计算 算法
【CPOBP-NSWOA】基于豪冠猪优化BP神经网络模型的多目标鲸鱼寻优算法研究(Matlab代码实现)
【CPOBP-NSWOA】基于豪冠猪优化BP神经网络模型的多目标鲸鱼寻优算法研究(Matlab代码实现)
295 8
|
12月前
|
算法 数据挖掘 区块链
基于遗传算法的多式联运车辆路径网络优优化研究(Matlab代码实现)
基于遗传算法的多式联运车辆路径网络优优化研究(Matlab代码实现)
339 2
|
机器学习/深度学习 传感器 算法
【表面粗糙度】基于粒子群PSO算法优化-BP神经网络的表面粗糙度研究(Matlab代码实现)
【表面粗糙度】基于粒子群PSO算法优化-BP神经网络的表面粗糙度研究(Matlab代码实现)
450 7
|
11月前
|
机器学习/深度学习 人工智能 算法
【基于TTNRBO优化DBN回归预测】基于瞬态三角牛顿-拉夫逊优化算法(TTNRBO)优化深度信念网络(DBN)数据回归预测研究(Matlab代码实现)
【基于TTNRBO优化DBN回归预测】基于瞬态三角牛顿-拉夫逊优化算法(TTNRBO)优化深度信念网络(DBN)数据回归预测研究(Matlab代码实现)
400 0

热门文章

最新文章