损失函数对模型训练结果的影响
程序员文章站
2024-03-15 11:31:23
...
import tensorflow as tf
from numpy.random import RandomState
batch_size = 8
#定义两个占位符,表示输入的x 与 正确的y
x = tf.placeholder(tf.float32,shape=(None ,2),name="x-input")
y_ = tf.placeholder(tf.float32,shape=(None , 1),name='y-input')
#正态分布产生一组2*1 的随机数矩阵
w1 = tf.Variable(tf.random_normal([2,1],stddev=1,seed = 1))
#定义前向传播函数
y= tf.matmul(x,w1)
#自定义损失函数
loss_less = 10
loss_more = 1
loss = tf.reduce_sum(tf.where(tf.greater(y,y_),
(y-y_)*loss_more,
(y_-y)*loss_less))
#定义反向传播算法
train_step = tf.train.AdadeltaOptimizer(0.001).minimize(loss)
#通过随机数产生一个模拟数据集
rdm = RandomState(1)
dataset_size = 128
X = rdm.rand(dataset_size,2)
#之所以加上一个随机量是为了加入不可预测的噪声,噪声为一个均值为0的小量,在这里噪声是一个 -0.05~0.05的随机数
Y = [[x1+x2+rdm.rand()/10.0-0.05]for (x1,x2) in X]
with tf.Session() as sess :
#初始化全局的变量,书上用到的是tf.initialize_all_variables(),编译器提示可以用这个
init_op = tf.global_variables_initializer()
sess.run(init_op)
Steps = 5000
for i in range(Steps):
start = (i*batch_size)%dataset_size
end = min(start+batch_size,dataset_size)
sess.run(train_step,feed_dict={x:X[start:end],y_:Y[start:end]})
print
tf.initialize_all_variables(): THIS FUNCTION IS DEPRECATED. It will be removed after 2017-03-02. Instructions for updating: Use tf.global_variables_initializer instead.
tf.initialize_all_variables() 该函数将不再使用,在 2017年3月2号以后;
图片来自:Tensorflow:实战Google深度学习框架