当前位置:   article > 正文

深度学习——模块化神经网络搭建八股_深度学习 模块化建立

深度学习 模块化建立

 opt4_8_generateds.py

  1. #coding:utf-8
  2. #0 导入模块,生成模拟数据集
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. seed = 2
  6. def generateds():
  7. #基于seed生成随机数
  8. rdm = np.random.RandomState(seed)
  9. #随机数返回300行2列的矩阵,表示300组坐标点(x0,x1)作为输入数据集
  10. X = rdm.randn(300,2)
  11. Y_= [int(x0*x0+x1*x1 < 2) for (x0,x1) in X]
  12. Y_c = [['red' if y else 'blue'] for y in Y_]
  13. X = np.vstack(X).reshape(-1,2)
  14. Y_= np.vstack(Y_).reshape(-1,1)
  15. return X,Y_,Y_c
'
运行

opt4_8_forward.py

  1. #coding:utf-8
  2. #0 导入模块,生成模拟数据集
  3. import tensorflow as tf
  4. #定义神经网络的输入,参数和输出,定义前向传播过程
  5. def get_weight(shape,regularizer):
  6. w = tf.Variable(tf.random_normal(shape),dtype=tf.float32)
  7. tf.add_to_collection('losses',tf.contrib.layers.l2_regularizer(regularizer)(w))
  8. return w
  9. def get_bias(shape):
  10. b = tf.Variable(tf.constant(0.01,shape=shape))
  11. return b
  12. def forward(x,regularizer):
  13. w1 = get_weight([2,11],regularizer)
  14. b1 = get_bias([11])
  15. y1 = tf.nn.relu(tf.matmul(x,w1)+b1)
  16. w2 = get_weight([11,1],regularizer)
  17. b2 = get_bias([1])
  18. y = tf.matmul(y1,w2)+b2
  19. return y

opt4_8_backward.py

  1. #coding:utf-8
  2. #0 导入模块,生成模拟数据集
  3. import tensorflow as tf
  4. import numpy as np
  5. import matplotlib.pyplot as plt
  6. import os
  7. os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
  8. import opt4_8_generateds
  9. import opt4_8_forward
  10. STEPS = 40000
  11. BATCH_SIZE = 30
  12. LEARNING_RATE_BASE = 0.001
  13. LEARNING_RATE_DECAY = 0.999
  14. REGULARIZER = 0.01
  15. def backward():
  16. x = tf.placeholder(tf.float32,shape = (None, 2))
  17. y_= tf.placeholder(tf.float32, shape = (None,1))
  18. X, Y_, Y_c = opt4_8_generateds.generateds()
  19. y = opt4_8_forward.forward(x, REGULARIZER)
  20. global_step = tf.Variable(0,trainable=False)
  21. learning_rate = tf.train.exponential_decay(
  22. LEARNING_RATE_BASE,
  23. global_step,
  24. 300/BATCH_SIZE,
  25. LEARNING_RATE_DECAY,
  26. staircase=True)
  27. #定义损失函数
  28. loss_mse = tf.reduce_mean(tf.square(y-y_))
  29. loss_total = loss_mse + tf.add_n(tf.get_collection('losses'))
  30. #定义反向传播方法:包含正则化
  31. train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss_total)
  32. with tf.Session() as sess:
  33. init_op = tf.global_variables_initializer()
  34. sess.run(init_op)
  35. for i in range(STEPS):
  36. start = (i*BATCH_SIZE)%300
  37. end = start+BATCH_SIZE
  38. sess.run(train_step,feed_dict={x : X[start:end],y_ : Y_[start:end]})
  39. if i%2000 == 0:
  40. loss_v = sess.run(loss_total,feed_dict = {x:X,y_:Y_})
  41. print("After %d steps, loss is : %f" %(i, loss_v))
  42. xx, yy = np.mgrid[-3:3:.01,-3:3:.01]
  43. grid = np.c_[xx.ravel(), yy.ravel()]
  44. probs = sess.run(y, feed_dict={x:grid})
  45. probs = probs.reshape(xx.shape)
  46. plt.scatter(X[:,0],X[:,1], c = np.squeeze(Y_c))
  47. plt.contour(xx,yy,probs,levels=[.5])
  48. plt.show()
  49. if __name__=='__main__':
  50. backward()

运行:python opt4_8_backward.py

结果:

  1. # 搭建模块化的神经网络八股:
  2. # 前向传播就是搭建网络。设计网络结构(forword.py)
  3. def forward(x, regularizer):
  4. w =
  5. b =
  6. y =
  7. return y
  8. def get_weight(shape, regularizer):
  9. w = tf.Variable()
  10. tf.add_to_collection('losses', tf.contrib.l2_regularizer(regularizer)(w))
  11. return w
  12. # shape表示b的形状,就是某层中b的个数
  13. def get_bias(shape):
  14. b = tf.Variable()
  15. return b
  16. # 反向传播就是训练网络,优化网络参数(backward.py)
  17. def backward():
  18. x = tf.placeholder()
  19. y_ = tf.placeholder()
  20. y = forward.forward(x, REGULARIZER)
  21. # 轮数计数器
  22. global_step = tf.Variable(0, trainable=False)
  23. loss =
  24. '''
  25. 正则化:
  26. loss可以是:
  27. 均方误差:y与y_的差距(loss_mse) = tf.reduce_mean(tf.square(y-y_))
  28. 交叉熵:ce = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y, labels=tf.argmax(y_, 1))
  29. y与y_的差距(cem) = tf.reduce_mean(ce)
  30. 加入正则化后,则还要加上:
  31. loss = y与y_的差距 + tf.add_n(tf.get_collection('losses'))
  32. '''
  33. # 若使用,指数衰减学习率,则加上:
  34. learning_rate = tf.train.exponential_decay(
  35. LEARNING_RATE_BASE,
  36. global_step,
  37. 数据样本数/BATCH_SIZE,
  38. LEARNING_RATE_DECAY,
  39. staircase=True)
  40. train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step}
  41. # 滑动平均:
  42. ema = tf.train.ExponentialMovingAverage(MOVlNG_AVERAGE_DECAY, global_step)
  43. ema_op = ema.apply(tf.trainable_variables()}
  44. with tf.control_dependencies([train_step, ema.op]):
  45. train.op = tf.no_op(name='train')
  46. with tf.Session() as sess:
  47. init.op = tf.global_Variables_initializer()
  48. sess.run(init_op)
  49. for i in range(STEPS):
  50. sess.run(train_step, feed_dict={x:, y_: })
  51. if i % 轮数 == 0:
  52. print()
  53. # 判断python运行的文件是否是主文件,若是主文件,则执行backward()函数
  54. if __name__ == '__main__':
  55. backward()

 

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/运维做开发/article/detail/823703
推荐阅读
相关标签
  

闽ICP备14008679号