赞
踩
- #coding:utf-8
- #0 导入模块,生成模拟数据集
- import numpy as np
- import matplotlib.pyplot as plt
- seed = 2
- def generateds():
- #基于seed生成随机数
- rdm = np.random.RandomState(seed)
- #随机数返回300行2列的矩阵,表示300组坐标点(x0,x1)作为输入数据集
- X = rdm.randn(300,2)
- Y_= [int(x0*x0+x1*x1 < 2) for (x0,x1) in X]
- Y_c = [['red' if y else 'blue'] for y in Y_]
-
- X = np.vstack(X).reshape(-1,2)
- Y_= np.vstack(Y_).reshape(-1,1)
-
- return X,Y_,Y_c
'运行
- #coding:utf-8
- #0 导入模块,生成模拟数据集
- import tensorflow as tf
-
- #定义神经网络的输入,参数和输出,定义前向传播过程
- def get_weight(shape,regularizer):
- w = tf.Variable(tf.random_normal(shape),dtype=tf.float32)
- tf.add_to_collection('losses',tf.contrib.layers.l2_regularizer(regularizer)(w))
- return w
-
- def get_bias(shape):
- b = tf.Variable(tf.constant(0.01,shape=shape))
- return b
-
- def forward(x,regularizer):
- w1 = get_weight([2,11],regularizer)
- b1 = get_bias([11])
- y1 = tf.nn.relu(tf.matmul(x,w1)+b1)
-
- w2 = get_weight([11,1],regularizer)
- b2 = get_bias([1])
- y = tf.matmul(y1,w2)+b2
-
- return y
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- #coding:utf-8
- #0 导入模块,生成模拟数据集
- import tensorflow as tf
- import numpy as np
- import matplotlib.pyplot as plt
- import os
- os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
- import opt4_8_generateds
- import opt4_8_forward
-
- STEPS = 40000
- BATCH_SIZE = 30
- LEARNING_RATE_BASE = 0.001
- LEARNING_RATE_DECAY = 0.999
- REGULARIZER = 0.01
-
- def backward():
- x = tf.placeholder(tf.float32,shape = (None, 2))
- y_= tf.placeholder(tf.float32, shape = (None,1))
- X, Y_, Y_c = opt4_8_generateds.generateds()
- y = opt4_8_forward.forward(x, REGULARIZER)
- global_step = tf.Variable(0,trainable=False)
- learning_rate = tf.train.exponential_decay(
- LEARNING_RATE_BASE,
- global_step,
- 300/BATCH_SIZE,
- LEARNING_RATE_DECAY,
- staircase=True)
- #定义损失函数
- loss_mse = tf.reduce_mean(tf.square(y-y_))
- loss_total = loss_mse + tf.add_n(tf.get_collection('losses'))
-
- #定义反向传播方法:包含正则化
- train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss_total)
-
- with tf.Session() as sess:
- init_op = tf.global_variables_initializer()
- sess.run(init_op)
- for i in range(STEPS):
- start = (i*BATCH_SIZE)%300
- end = start+BATCH_SIZE
- sess.run(train_step,feed_dict={x : X[start:end],y_ : Y_[start:end]})
- if i%2000 == 0:
- loss_v = sess.run(loss_total,feed_dict = {x:X,y_:Y_})
- print("After %d steps, loss is : %f" %(i, loss_v))
-
- xx, yy = np.mgrid[-3:3:.01,-3:3:.01]
- grid = np.c_[xx.ravel(), yy.ravel()]
- probs = sess.run(y, feed_dict={x:grid})
- probs = probs.reshape(xx.shape)
-
- plt.scatter(X[:,0],X[:,1], c = np.squeeze(Y_c))
- plt.contour(xx,yy,probs,levels=[.5])
- plt.show()
-
- if __name__=='__main__':
- backward()
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
运行:python opt4_8_backward.py
结果:
- # 搭建模块化的神经网络八股:
- # 前向传播就是搭建网络。设计网络结构(forword.py)
-
-
- def forward(x, regularizer):
- w =
- b =
- y =
- return y
-
-
- def get_weight(shape, regularizer):
- w = tf.Variable()
- tf.add_to_collection('losses', tf.contrib.l2_regularizer(regularizer)(w))
- return w
-
- # shape表示b的形状,就是某层中b的个数
-
-
- def get_bias(shape):
- b = tf.Variable()
- return b
-
- # 反向传播就是训练网络,优化网络参数(backward.py)
-
-
- def backward():
- x = tf.placeholder()
- y_ = tf.placeholder()
- y = forward.forward(x, REGULARIZER)
- # 轮数计数器
- global_step = tf.Variable(0, trainable=False)
- loss =
-
-
- '''
- 正则化:
- loss可以是:
- 均方误差:y与y_的差距(loss_mse) = tf.reduce_mean(tf.square(y-y_))
- 交叉熵:ce = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y, labels=tf.argmax(y_, 1))
- y与y_的差距(cem) = tf.reduce_mean(ce)
- 加入正则化后,则还要加上:
- loss = y与y_的差距 + tf.add_n(tf.get_collection('losses'))
- '''
- # 若使用,指数衰减学习率,则加上:
- learning_rate = tf.train.exponential_decay(
- LEARNING_RATE_BASE,
- global_step,
- 数据样本数/BATCH_SIZE,
- LEARNING_RATE_DECAY,
- staircase=True)
-
- train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step}
-
- # 滑动平均:
- ema = tf.train.ExponentialMovingAverage(MOVlNG_AVERAGE_DECAY, global_step)
- ema_op = ema.apply(tf.trainable_variables()}
- with tf.control_dependencies([train_step, ema.op]):
- train.op = tf.no_op(name='train')
-
-
- with tf.Session() as sess:
- init.op = tf.global_Variables_initializer()
- sess.run(init_op)
-
- for i in range(STEPS):
- sess.run(train_step, feed_dict={x:, y_: })
- if i % 轮数 == 0:
- print()
-
- # 判断python运行的文件是否是主文件,若是主文件,则执行backward()函数
- if __name__ == '__main__':
- backward()
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。