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


海燕愤怒
海燕愤怒 2022-09-20 11:11:52 49920
分类专栏: 资讯

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

 

目录

输出结果

代码设计


 

 

输出结果

 

代码设计

  1. 23 Batch Normalization
  2. import numpy as np
  3. import tensorflow as tf
  4. import matplotlib.pyplot as plt
  5. ACTIVATION = tf.nn.tanh
  6. N_LAYERS = 7           
  7. N_HIDDEN_UNITS = 30   
  8. def fix_seed(seed=1): 
  9.      reproducible
  10.     np.random.seed(seed)
  11.     tf.set_random_seed(seed)
  12. def plot_his(inputs, inputs_norm):
  13.      plot histogram for the inputs of every layer
  14.      
  15.     for j, all_inputs in enumerate([inputs, inputs_norm]):
  16.         for i, input in enumerate(all_inputs):
  17.             plt.subplot(2len(all_inputs), j*len(all_inputs)+(i+1))
  18.             plt.cla()
  19.             if i == 0:
  20.                 the_range = (-710)
  21.             else:
  22.                 the_range = (-11)
  23.             plt.hist(input.ravel(), bins=15range=the_range, color='0000FF')
  24.             plt.yticks(())
  25.             if j == 1:
  26.                 plt.xticks(the_range)
  27.             else:
  28.                 plt.xticks(())
  29.             ax = plt.gca()
  30.             ax.spines['right'].set_color('none')
  31.             ax.spines['top'].set_color('none')
  32.         plt.title("%s normalizing" % ("Without" if j == 0 else "With"))
  33.     plt.title('Matplotlib,BN,histogram--Jason Niu')
  34.     plt.draw()
  35.     plt.pause(0.001)
  36. def built_net(xs, ys, norm): 
  37.     def add_layer(inputs, in_size, out_size, activation_function=None, norm=False):
  38.          weights and biases (bad initialization for this case)
  39.         Weights = tf.Variable(tf.random_normal([in_size, out_size], mean=0., stddev=1.))
  40.         biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
  41.          fully connected product
  42.         Wx_plus_b = tf.matmul(inputs, Weights) + biases
  43.          normalize fully connected product
  44.         if norm:
  45.              Batch Normalize
  46.             fc_mean, fc_var = tf.nn.moments( 
  47.                 Wx_plus_b,
  48.                 axes=[0],  
  49.                              
  50.             )
  51.             scale = tf.Variable(tf.ones([out_size]))
  52.             shift = tf.Variable(tf.zeros([out_size]))
  53.             epsilon = 0.001
  54.              apply moving average for mean and var when train on batch
  55.             ema = tf.train.ExponentialMovingAverage(decay=0.5)
  56.             def mean_var_with_update():
  57.                 ema_apply_op = ema.apply([fc_mean, fc_var])
  58.                 with tf.control_dependencies([ema_apply_op]):
  59.                     return tf.identity(fc_mean), tf.identity(fc_var)
  60.             mean, var = mean_var_with_update()
  61.             Wx_plus_b = tf.nn.batch_normalization(Wx_plus_b, mean, var, shift, scale, epsilon)
  62.              
  63.              Wx_plus_b = (Wx_plus_b - fc_mean) / tf.sqrt(fc_var + 0.001)  进行BN一下
  64.              Wx_plus_b = Wx_plus_b * scale + shift
  65.   
  66.          activation
  67.         if activation_function is None:
  68.             outputs = Wx_plus_b
  69.         else:
  70.             outputs = activation_function(Wx_plus_b)
  71.         return outputs  输出激活结果
  72.     fix_seed(1)
  73.     if norm:
  74.          BN for the first input
  75.         fc_mean, fc_var = tf.nn.moments(
  76.             xs,
  77.             axes=[0],
  78.         )
  79.         scale = tf.Variable(tf.ones([1]))
  80.         shift = tf.Variable(tf.zeros([1]))
  81.         epsilon = 0.001
  82.          apply moving average for mean and var when train on batch
  83.         ema = tf.train.ExponentialMovingAverage(decay=0.5)
  84.         def mean_var_with_update():
  85.             ema_apply_op = ema.apply([fc_mean, fc_var])
  86.             with tf.control_dependencies([ema_apply_op]):
  87.                 return tf.identity(fc_mean), tf.identity(fc_var)
  88.         mean, var = mean_var_with_update()
  89.         xs = tf.nn.batch_normalization(xs, mean, var, shift, scale, epsilon)
  90.      record inputs for every layer
  91.     layers_inputs = [xs] 
  92.      build hidden layers
  93.     for l_n in range(N_LAYERS):
  94.         layer_input = layers_inputs[l_n]
  95.         in_size = layers_inputs[l_n].get_shape()[1].value
  96.         output = add_layer(
  97.             layer_input,     input
  98.             in_size,         input size
  99.             N_HIDDEN_UNITS,  output size
  100.             ACTIVATION,      activation function
  101.             norm,            normalize before activation
  102.         )
  103.         layers_inputs.append(output)  
  104.      build output layer
  105.     prediction = add_layer(layers_inputs[-1], 301, activation_function=None)
  106.     cost = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices=[1]))
  107.     train_op = tf.train.GradientDescentOptimizer(0.001).minimize(cost)
  108.     return [train_op, cost, layers_inputs] 
  109. fix_seed(1)
  110. x_data = np.linspace(-7102500)[:, np.newaxis]  水平轴-7~10
  111. np.random.shuffle(x_data)
  112. noise = np.random.normal(08, x_data.shape)
  113. y_data = np.square(x_data) - 5 + noise
  114. xs = tf.placeholder(tf.float32, [None1])   [num_samples, num_features]
  115. ys = tf.placeholder(tf.float32, [None1])
  116. 建立两个神经网络作对比
  117. train_op, cost, layers_inputs = built_net(xs, ys, norm=False
  118. train_op_norm, cost_norm, layers_inputs_norm = built_net(xs, ys, norm=True)
  119. sess = tf.Session()
  120. if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:
  121.     init = tf.initialize_all_variables()
  122. else:
  123.     init = tf.global_variables_initializer()
  124. sess.run(init)
  125. record cost
  126. cost_his = []       
  127. cost_his_norm = []  
  128. record_step = 5     
  129. plt.ion()
  130. plt.figure(figsize=(73)) 
  131. for i in range(250):
  132.     if i % 50 == 0
  133.          plot histogram
  134.         all_inputs, all_inputs_norm = sess.run([layers_inputs, layers_inputs_norm], feed_dict={xs: x_data, ys: y_data})
  135.         plot_his(all_inputs, all_inputs_norm)
  136.      train on batch每一步都run一下
  137.     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]})
  138.     if i % record_step == 0:
  139.          record cost
  140.         cost_his.append(sess.run(cost, feed_dict={xs: x_data, ys: y_data}))
  141.         cost_his_norm.append(sess.run(cost_norm, feed_dict={xs: x_data, ys: y_data}))
  142. 以下是绘制误差值Cost误差曲线的方法
  143. plt.ioff()
  144. plt.figure()
  145. plt.title('Matplotlib,BN,Error_curve--Jason Niu')
  146. plt.plot(np.arange(len(cost_his))*record_step, np.array(cost_his), label='no BN')      no norm
  147. plt.plot(np.arange(len(cost_his))*record_step, np.array(cost_his_norm), label='BN')    norm
  148. plt.legend()
  149. plt.show()

 

 

 

 

 

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

网站声明:如果转载,请联系本站管理员。否则一切后果自行承担。

本文链接:https://www.xckfsq.com/news/show.html?id=4229
赞同 0
评论 0 条
海燕愤怒L0
粉丝 0 发表 5 + 关注 私信
上周热门
如何使用 StarRocks 管理和优化数据湖中的数据?  2951
【软件正版化】软件正版化工作要点  2872
统信UOS试玩黑神话:悟空  2833
信刻光盘安全隔离与信息交换系统  2728
镜舟科技与中启乘数科技达成战略合作,共筑数据服务新生态  1261
grub引导程序无法找到指定设备和分区  1226
华为全联接大会2024丨软通动力分论坛精彩议程抢先看!  165
2024海洋能源产业融合发展论坛暨博览会同期活动-海洋能源与数字化智能化论坛成功举办  163
点击报名 | 京东2025校招进校行程预告  163
华为纯血鸿蒙正式版9月底见!但Mate 70的内情还得接着挖...  159
本周热议
我的信创开放社区兼职赚钱历程 40
今天你签到了吗? 27
如何玩转信创开放社区—从小白进阶到专家 15
信创开放社区邀请他人注册的具体步骤如下 15
方德桌面操作系统 14
用抖音玩法闯信创开放社区——用平台宣传企业产品服务 13
我有15积分有什么用? 13
如何让你先人一步获得悬赏问题信息?(创作者必看) 12
2024中国信创产业发展大会暨中国信息科技创新与应用博览会 9
中央国家机关政府采购中心:应当将CPU、操作系统符合安全可靠测评要求纳入采购需求 8

加入交流群

请使用微信扫一扫!