本文还是以MNIST的CNN分析为例

loss函数一般有MSE均方差函数、交叉熵损失函数,说明见



另外一部分为正则化部分,这里实际上了解图像的会理解较深,就是防止过拟合的一些方式,符合图像先验的正则化项会给图像恢复带来很大的效果,简单讲神经网络常见的正则化则是

1.对权重加入L2-norm或L1-norm

2.dropout

3.训练数据扩增

可以看



见修改的代码:

#tf可以认为是全局变量,从该变量为类,从中取input_data变量
import tensorflow.examples.tutorials.mnist.input_data as input_data
import tensorflow as tf
#读取数据集
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)

#这里用CNN方法进行训练
#函数定义部分
def weight_variable(shape):
    initial=tf.truncated_normal(shape,stddev=0.1)#随机权重赋值,不过truncated_normal代表如果是2倍标准差之外的结果重新选取该值
    return tf.Variable(initial)

def bias_variable(shape):
    initial=tf.constant(0.1,shape=shape)#偏置项
    return tf.Variable(initial)

def conv2d(x,W):
    return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')#SAME表示输出补边,这里输出与输入尺寸一致

def max_pool_2x2(x):
    return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')#ksize代表池化范围的大小,stride为扫描步长






# 这里是变量的占位符,一般是输入输出使用该部分
x=tf.placeholder(tf.float32,[None,784])
y_=tf.placeholder("float",[None,10])
x_image=tf.reshape(x,[-1,28,28,1])#-1表示自动计算该维度
#建立第一层
W_conv1=weight_variable([5,5,1,32])
b_conv1=bias_variable([32])
h_conv1=tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1)
h_pool1=max_pool_2x2(h_conv1)
#第二层
W_conv2=weight_variable([5,5,32,64])
b_conv2=bias_variable([64])
h_conv2=tf.nn.relu(conv2d(h_pool1,W_conv2)+b_conv2)
h_pool2=max_pool_2x2(h_conv2)


#第三层,而且这里是全连接层
W_fc1=weight_variable([7*7*64,1024])
b_fc1=bias_variable([1024])

h_pool2_flat=tf.reshape(h_pool2,[-1,7*7*64])
h_fc1=tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1)+b_fc1)
#dropout,注意这里也是有一个输入参数的,和x以及y一样
keep_prob=tf.placeholder(tf.float32)
h_fc1_drop=tf.nn.dropout(h_fc1,keep_prob)

W_fc2=weight_variable([1024,10])
b_fc2=bias_variable([10])
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2)+b_fc2)


# 评价函数,该部分是今天想要着重说明的部分
# 常用的函数有方差代价函数,交叉熵代价函数
#cross_entropy = tf.nn.softmax_cross_entropy_with_logits(y_conv, y_)为交叉熵的用法,其中y_conv应该是没有经过softmax的,这里的y_conv=tf.matmul(h_fc1_drop,W_fc2)+b_fc2
#具体差异见
#cross_entropy =tf.nn.sparse_softmax_cross_entropy_with_logits(y_conv, y)也是交叉熵,差异在于这里的标签可以认为是排它的
#方差函数:mse = tf.reduce_mean(tf.square(y_- y_conv))
#分类型的优化函数loss = tf.reduce_sum(tf.select(tf.greater(v1,v2),loss1,loss2)),代表v1>=v2时,使用loss1函数,否则使用loss2函数
#应用场景:危险品的鉴别

#第二种,抑制过拟合
#常用方法,加入权重L1正则项、L2正则项、dropout、训练数据扩展
#可以参考网址
#我们这里使用L2正则化


#L2的正则化项,一些具体的细节使用见https://www.jianshu.com/p/6ffd815e2d11
tf.add_to_collection(tf.GraphKeys.WEIGHTS,W_fc1)
tf.add_to_collection(tf.GraphKeys.WEIGHTS,W_fc2)
regularizer = tf.contrib.layers.l2_regularizer(scale=100/50000)#这里需要和你输入的样品数成正比
reg_term = tf.contrib.layers.apply_regularization(regularizer)




cross_entropy=-tf.reduce_sum(y_*tf.log(y_conv))+reg_term
train_step=tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction=tf.equal(tf.argmax(y_conv,1),tf.argmax(y_,1))
accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))


# 启动模型,Session建立这样一个对象,然后指定某种操作,并实际进行该步
init=tf.initialize_all_variables()
sess=tf.Session()
sess.run(init)



#数据读取部分
for i in range(1000):

    batch_xs, batch_ys = mnist.train.next_batch(50)#这里貌似是代表读取50张图像数据
    #run第一个参数是fetch,可以是tensor也可以是Operation,第二个feed_dict是替换tensor的值
    '''
    if i % 10 == 0:
        train_accuracy = accuracy.eval(feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.5})
        print("step:%d,accuracy:%g" % (i, train_accuracy))
    '''
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.5})#sess.run第一个参数是想要运行的位置,一般有train,accuracy,initdeng
    #第二个参数feed_dict,一般是输入参数,该代码里有x,y以及drop的参数
    if i%20==0 :
        print(i)
        print("train accuracy:%g"%sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.5}))
print("test accuracy:%g"%sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1}))

运行结果:

tensorflow如何自定义loss函数 tensorflow loss_正则化

和之前的结果对比一下:提高了0.3%,不知道这算不算提高。。。其实在正则项的超参数选择不好时,一般结果会比较差,一些超参数的选择可以见