Tensorflow_基础(下)
激活函数activation function :引入激活函数,避免纯线性组合,提高模型的表达力,使模型有更好的区分度
常用的激活函数:tf.nn.relu() / tf.nn.sigmold() / tf.nn.tanh()
NN复杂度:多用NN层数和NN参数个数表示。
层数=隐藏层的层数+1个输出层;
总参数= 总W+总b
神经网络优化:
损失函数loss:
预测值(y)与已知答案(y_)的差距:
NN优化目标:loss最小 :mse (Mean Squared Error)/ 自定义 / ce(Cross Entropy)
均方误差mse:loss_mse=tf.reduce_mean(tf.square(y_-y)
#coding:utf-8
#预测多或少的影响一样
#0导入模块,生成数据集
import tensorflow as tf
import numpy as np
BATCH_SIZE=8
SEED=23455
rdm=np.random.RandomState(SEED)
X=rdm.rand(32,2)
Y_=[[x1+x2+(rdm.rand()/10.0-0.05)] for (x1,x2) in X]
#1定义神经网络的输入,参数和输出,定义前向传播过程。
x=tf.placeholder(tf.float32, shape=(None, 2))
y_=tf.placeholder(tf.float32,shape=(None,1))
w1=tf.Variable(tf.random_normal([2,1],stddev=1,seed=1))
y=tf.matmul(x,w1)
#2定义损失函数及反向传播过程。
#定义损失函数为MSE,反向传播方法为梯度下降。
loss_mse = tf.reduce_mean(tf.square(y_-y))
train_step = tf.train.GradientDescentOptimizer(0.001).minimize(loss_mse)
#3生成会话,训练STEPS轮:
with tf.Session() as sess:
init_op = tf.global_variables_initializer()
sess.run(init_op)
STEPS=20000
for i in range(STEPS):
start=(i*BATCH_SIZE)%32
end=(i*BATCH_SIZE)%32 + BATCH_SIZE
sess.run(train_step,feed_dict={x:X[start:end],y_:Y_[start:end]})
if i % 500 == 0:
print ("After %d training steps, w1 is :" % (i))
print ((sess.run(w1)),"\n")
print ("Final w1 is: \n", sess.run(w1))
结果:
Final w1 is:
[[0.98019385]
[1.0159807 ]]
自定义损失函数:如预测商品销量,预测多了,损失成本;预测少了,损失利润。若利润与成本不相等,则mse产生的loss无法利益最大化。
loss=tf.reduce_sum(tf.where(tf.where(tf.greater(y,y_),COST(y-y_),PROFIT(y_-y)))
#tf.where(tf.greater(y,y_)询问 y 是否大于y_,若成立,则取COST(y-y_),不成立取PROFIT(y_-y)
#coding:utf-8
#预测多或少的影响不一样,成本第,利润高
#0导入模块,生成数据集
import tensorflow as tf
import numpy as np
BATCH_SIZE=8
SEED=23455
COST=1
PROFIT=9
rdm=np.random.RandomState(SEED)
X=rdm.rand(32,2)
Y_=[[x1+x2+(rdm.rand()/10.0-0.05)] for (x1,x2) in X]
#1定义神经网络的输入,参数和输出,定义前向传播过程。
x=tf.placeholder(tf.float32, shape=(None, 2))
y_=tf.placeholder(tf.float32,shape=(None,1))
w1=tf.Variable(tf.random_normal([2,1],stddev=1,seed=1))
y=tf.matmul(x,w1)
#2定义损失函数及反向传播过程。
#定义损失函数为MSE,反向传播方法为梯度下降。
loss_mse = tf.reduce_mean(tf.where(tf.greater(y,y_),(y-y_)*COST,(y_-y)*PROFIT))
train_step = tf.train.GradientDescentOptimizer(0.001).minimize(loss_mse)
#3生成会话,训练STEPS轮:
with tf.Session() as sess:
init_op = tf.global_variables_initializer()
sess.run(init_op)
STEPS=20000
for i in range(STEPS):
start=(i*BATCH_SIZE)%32
end=(i*BATCH_SIZE)%32 + BATCH_SIZE
sess.run(train_step,feed_dict={x:X[start:end],y_:Y_[start:end]})
if i % 500 == 0:
print ("After %d training steps, w1 is :" % (i))
print ((sess.run(w1)),"\n")
print ("Final w1 is: \n", sess.run(w1))
交叉熵ce(Cross Entropy):表征两个概率分布之间的距离
ce=-tf.reduce_mean(y_*tf.log(tf.clip_by_value(y,1e-12,1.0)))
当n分类的n个输出(y1,y2,…yn)通过softmax()函数,便满足了概率分布要求:
ce = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y,labels=tf.argmax(y_,1))
cem = tf.reduce_mean(ce)
输出即为当前预测值与标准答案间的差距,也就是损失函数。
学习率learning_rate:每次参数更新的幅度:w(n+1) = w(n) - learning_rate*grad
更新后的参数 = 当前参数 - 学习率 * 损失函数的梯度
优化参数w,就是要找到某个参数w使得损失函数的梯度最小,从而使损失函数最小。
#coding:utf-8
#设损失函数为 loss = (w+1)^2,令w的初值是5,反向传播就是求最优w,即求最小loss对应的w的值
import tensorflow as tf
#定义待优化参数w初值为5
w=tf.Variable(tf.constant(5,dtype=tf.float32))
#定义损失函数loss
loss=tf.square(w+1)
#定义反向传播方法
train_step=tf.train.GradientDescentOptimizer(0.2).minimize(loss)
#生成会话,训练40轮
with tf.Session() as sess:
init_op=tf.global_variables_initializer()
sess.run(init_op)
for i in range (40):
sess.run(train_step)
w_val = sess.run(w)
loss_val=sess.run(loss)
print ("After % steps: w is %f, loss is %f." %(i, w_val,loss_val))
学习率设置多少合适 :学习率过大震荡不收敛,过小收敛速度漫。
指数衰减学习率:
learning_rate=LEARNING_RATE_BASE.LAERNING_RATE_DECAY
#学习率基数,学习率初始值 学习率衰减率(0,1) ,
global_step/LEARNING_RATE_STEP 多少轮更新一次学习率=样本总数/BATCH_SIZE
global_step=tf.Variable(0,trainable=False)
learning_rate=tf.train.exponential_decay(
LEARNING_RATE_BASE,
global_step,
LEARNING_RATE_STEP,
LEARNING_RATE_DECAY,
staircase=True)
#coding:utf-8
#设损失函数为 loss = (w+1)^2,令w的初值是10,反向传播就是求最优w,即求最小loss对应的w的值
#使用指数衰减的学习率,在迭代初期得到较高的下降渡,可在较小的训练轮数下取得更有收敛度
import tensorflow as tf
LEARNING_RATE_BASE = 0.1 #最初学习率
LEARNING_RATE_DECAY = 0.99 #学习率衰减率
LEARNING_RATE_STEP = 1 #喂入多少轮的BATCH_SIZE后,更新一次学习率,一般设为:样本总数/BATCH_SIZE
#运行了几轮的BATCH_SIZE的计数器,初值给0,设为不被训练
global_step=tf.Variable(0,trainable=False)
#定义指数下降学习率
learning_rate= tf.train.exponential_decay(LEARNING_RATE_BASE,global_step,LEARNING_RATE_STEP,LEARNING_RATE_DECAY,staircase=True)
#定义待优化参数w初值为10
w=tf.Variable(tf.constant(10,dtype=tf.float32))
#定义损失函数loss
loss=tf.square(w+1)
#定义反向传播方法
train_step=tf.train.GradientDescentOptimizer(0.2).minimize(loss)
#生成会话,训练40轮
with tf.Session() as sess:
init_op=tf.global_variables_initializer()
sess.run(init_op)
for i in range (40):
sess.run(train_step)
learning_rate_val=sess.run(learning_rate)
global_step_val=sess.run(global_step)
w_val = sess.run(w)
loss_val=sess.run(loss)
print ("After % steps:global_step is %f , w is %f,learning_rate is %f, loss is %f." %(i,global_step_val, w_val,learning_rate_val,loss_val))
滑动平均ema(影子值):记录了每个参数一段时间内过往值的平均,增加了模型的泛化性。针对所有参数:w 和 b
(像是个参数加了影子,参数变化,影子慢慢追随)
影子 = 衰减率 + 影子 +(1 - 衰减率)+ 参数 影子缓存相随
衰减率 = min { MOVING_AVGRAGE_DECAY ,(1+轮数)/(10+轮数)}
MOVING_AVERAGE_DECAY为0.99,轮数global_step为0,w1的滑动平均值为0,参数w1更新为1则:
w1滑动平均值=min(0.99,1/10)*0+(1-min(0.99,1/10)*1=0.9
轮数global_step为100时,参数w1更新为10则:
w1滑动平均值=min(0.99,101/110)*0.9+(1-min(0.99,101/110)*10=0.826+0.818=1.644
再次运行
w1滑动平均值=min(0.99,101/110)*1.644+(1-min(0.99,101/110)*10=2,328
再次运行
w1滑动平均值=2.956
ema = tf.train.ExponentialMovingAverage(
衰减率MOVING_AVERAGE_DECAY,
当前轮数global_step)
ema_op = ema.apply([])
ema_op = ema.apply(tf.trainable_variables()) #
with tf.control_dependencies([train_step,ema_op]):
train_op=tf.no.op(name='train')
ema.average(参数名) #查看某参数的滑动平均值
#coding:utf-8
import tensorflow as tf
#0定义变量及滑动平均类
#定义一个3位浮点变量,初始值为0.0 这个代码就是不断更新w1参数,优化w1参数,滑动平均做了个w1的影子
w1 = tf.Variable(0, dtype=tf.float32)
#定义num_update(NN的迭代次数),初始值为0,不可被优化(训练),这个参数不训练。
global_step = tf.Variable(0,trainable=False)
#实例化滑动平局类,给删减率0.99,当前轮数global.step
MOVING_AVERAGE_DECAY = 0.99
ema = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)
#ems.apply后的括号例是更新列表,每次运行sess.run(eam_op)时,对更新列表中的元素求滑动平均值
#在实际应用中会使用tf.trainable_variables()自动将所有带训练的参数汇总为列表
#ema_op = ema.apply([w1])
ema_op = ema.apply(tf.trainable_variables())
#查看不同迭代中变量取值的变化
with tf.Session() as sess:
#初始化
init_op = tf.global_variables_initializer()
sess.run(init_op)
#用ema.average(w1)获取w1滑动平均值 (要运行多个节点,作为列表中的元素列出,写在sess.run中)
#打印出当前参数w1和w1的滑动平均值。
print (sess.run([w1,ema.average(w1)]))
#参数w1的值赋为1.
sess.run(tf.assign(w1,1))
sess.run(ema_op)
print (sess.run([w1,ema.average(w1)]))
#更新step和w1的值,模拟出100轮迭代后,参数w1变为10
sess.run(tf.assign(global_step, 100))
sess.run(tf.assign(w1,10))
sess.run(ema_op)
print (sess.run([w1,ema.average(w1)]))
#每次sess.run 后会更新呢一次w1的滑动平均值
sess.run(ema_op)
print (sess.run([w1,ema.average(w1)]))
sess.run(ema_op)
print (sess.run([w1,ema.average(w1)]))
sess.run(ema_op)
print (sess.run([w1,ema.average(w1)]))
sess.run(ema_op)
print (sess.run([w1,ema.average(w1)]))
sess.run(ema_op)
print (sess.run([w1,ema.average(w1)]))
sess.run(ema_op)
print (sess.run([w1,ema.average(w1)]))
正则化regularization:缓解过拟合
正则化在损失函数中引入模型复杂度指标,利用给w加权,弱化了训练数据的噪声
loss = loss (y与 y_)+REGULARIZER*loss(w)
loss为模型中所有参数的损失函数,如均方误差,交叉熵等
超参数 REGULARIZER给出参数w在总loss中的比例,即正则化的权重
w是需要 正则化的参数
loss(w) = tf.contrib.layers.l1_regularizer(REGULARIZER)(w) #对所有参数的绝对值求和
loss(w) = tf.contrib.layers.l2_regualrizer(REGULARIZER)(w)#对所有参数的平方的绝对值求和
tf.add_to_collection('losser',tf.contreb.layerss.l2_regularizer(regularizer)(w))
loss = cem +tf.add_n(tf.get_collection('losser'))
import matplotlib,pyplot as plt
plt.scatter(x坐标,y坐标,c="颜色")
plt.show()
xx,yy = np.mgrid[起止:步长;起止:步长) grid = np.c_[xx.ravel(),yy.ravel()]
probs = sess.run(y,feed_dict={x:grid})
probs = probs.reshape(xx.shape)
plt.contour(x轴坐标值,y坐标值,该店的高度,levels=[等高线的高度])
plt.show()
#coding:utf-8
#0导入模块生成模拟数据集
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
BATCH_SIZE = 30
seed = 2
#基于seed产生随机数
rdm = np.random.RandomState(seed)
#随机数返回300行2列,表示300组坐标点, (X0,X1) 作为输入数据集
X=rdm.randn(300,2)
#从X这个300行2列的矩阵中取出一行,判断如果2个坐标的平方和小于2,给Y赋值1,其余赋值0
#作为输入数据集的标签(正确答案)
Y_= [int(x0*x0 + x1*x1 < 2) for (x0,x1 ) in X ]
#遍历Y中的每个元素,1赋值red,其余赋值 blue,这样可视化显示时,人可以直观区分
Y_c = [['red' if y else 'blue'] for y in Y_]
#对数据集X和标签Y进行shape整理,第一个元素为-1表示,第二个参数计算得到,第二个元素表示多少列,把X整理为n行2列,把Y整理成n行1列
X = np.vstack(X).reshape(-1,2)
Y_ = np.vstack(Y_).reshape(-1,1)
print (X)
print (Y_)
print (Y_c)
#用plt.scatter画出数据集x各行中第0列元素和第1列元素的点即各行 (x0,x1) , 用各行Y_c对应的值表示颜色
plt.scatter(X[:,0],X[:,1], c=np.squeeze(Y_c))
plt.show()
#定义神经网络的输入,参数和输出,定义前向传播过程
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
x=tf.placeholder(tf.float32, shape=(None, 2))
y_=tf.placeholder(tf.float32, shape=(None, 1))
w1 = get_weight([2,11],0.01)
b1 = get_bias([11])
y1 = tf.nn.relu(tf.matmul(x,w1) + b1)
w2 = get_weight([11,1],0.01)
b2 = get_bias([1])
y = tf.matmul(y1, w2) + b2#输出层不过激活
#定义损失函数
loss_mse = tf.reduce_mean(tf.square(y-y_))
loss_total = loss_mse + tf.add_n(tf.get_collection('losses'))
#定义方向传播方法:不含正则化
train_step=tf.train.AdadeltaOptimizer(0.0001).minimize(loss_mse)
with tf.Session() as sess:
init_op = tf.global_variables_initializer()
sess.run(init_op)
STEPS = 40000
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_mse_v = sess.run(loss_mse, feed_dict={x:X, y_:Y_})
print ("After %d steps , loss is: %f" % (i,loss_mse_v))
#xx在-3到3之间以步长0.01,yy在-3到3之间以步长0.01,生成二维网格坐标点
xx, yy = np.mgrid[-3:3:.01, -3:3:.01]
#将xx,yy拉直,并合并成一个2列的矩阵,得到一个网格坐标点的集合
grid = np.c_[xx.ravel(), yy.ravel()]
#将网格坐标点喂入神经网络,probs为输出
probs=sess.run(y, feed_dict={x:grid})
#prob的shape调整成xx的样子
probs=probs.reshape(xx.shape)
print ("w1:\n",sess.run(w1))
print ("b1:\n",sess.run(b1))
print ("w2:\n",sess.run(w2))
print ("b2:\n",sess.run(b2))
plt.scatter(X[:,0],X[:,1],c=np.squeeze(Y_c))
plt.contour(xx,yy,probs,levels=[.5])
plt.show()
搭建模块化的神经网络八股:
前线传播即搭建网络,设计网络结果(forward.py)
def forwardd(x, regularizer): //定义了前向传播过程
w =
b =
y =
return y
def get_weight(shape,regularizer): //给w赋初值,把每个layers的正则化损失加到总损失中
w = tf.Variable( )
tf.add_to_collection("losses",tf.contrib.layers.l2_regualrizer(regularizer)(w))
return w
def get_bias(shape): //与参数b有关,某层中b的个数
b = tf.Vraiable( )
return b
def backward( ):
x = tf.placeholder( )
y_ =tf.placeholder( )
global_step = tf.Variable(0,trainable=False)
loss //loss可以是y与y_的差距=tf.reduce_mean(tf.square(y-y_)) 也可以是
ce=tf.nn.square_softmax_cross_entropy_with_logits(logits=y,labels=tf.argmax(y_,1))
y与y_的差距 = 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.GradinetDescentOptimizer(learning_rate).minimize(loss,global_step=global_step)
ema=tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY,global_step) //滑动平均
ema_op=ema.apply(tf.trainable_variable())
with tf.control_depandencies([train_step,ema_op]);
train_op = tf.no_op(name="train")
with tf.Sessin() 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:
if __name__== '__main__''
backward()
#generateds
import numpy as np
import matplotlib.pyplot as plt
seed = 2
def generateds():
rdm = np.random.RandomState(seed)
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
#forward
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
#backward
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import forward
import generateds
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 = generateds.generateds()
y = 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()
还没有评论,来说两句吧...