dropout一个生成形象的小应用

本文通过对比实验展示了Dropout技术在神经网络中防止过拟合的效果。在相同的训练数据下,采用Dropout的网络在测试集上的表现更佳,loss更低,证明了Dropout的有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import tensorflow as tf
import numpy as np
import  matplotlib.pyplot as plt
 
tf.set_random_seed(1)
np.random.seed(1)
 
N_SAMPLE = 20
N_HIDDEN = 300
LR = 0.01
 
x = np.linspace(-1,1,N_SAMPLE)[:,np.newaxis]
y = x+0.3*np.random.randn(N_SAMPLE)[:,np.newaxis]
 
test_x = x.copy()
test_y = test_x + 0.3*np.random.randn(N_SAMPLE)[:,np.newaxis]
 
#plt.scatter(x,y,c='magenta',s=50,alpha=0.5,label='train')
plt.scatter(test_x,test_y,c='cyan',s=50,alpha=0.5,label='test')
plt.legend(loc='upper left')
plt.ylim((-2.5,2.5))
plt.show()
 
tf_x = tf.placeholder(tf.float32,[None,1])
tf_y = tf.placeholder(tf.float32,[None,1])
tf_is_training = tf.placeholder(tf.bool,None)
 
 
#overfitting net
o1 = tf.layers.dense(tf_x,N_HIDDEN,tf.nn.relu)
o2 = tf.layers.dense(o1,N_HIDDEN,tf.nn.relu)
o_out = tf.layers.dense(o2,1)
o_loss = tf.losses.mean_squared_error(tf_y,o_out)
o_train = tf.train.AdamOptimizer(LR).minimize(o_loss)
 
#dropout net
d1 = tf.layers.dense(tf_x,N_HIDDEN,tf.nn.relu)
d1 = tf.layers.dropout(d1,rate=0.5,training = tf_is_training)
d2 = tf.layers.dense(d1,N_HIDDEN,tf.nn.relu)
d2 = tf.layers.dropout(d2,rate=0.5,training = tf_is_training)
d_out = tf.layers.dense(d2,1)
d_loss = tf.losses.mean_squared_error(tf_y,d_out)
d_train = tf.train.AdamOptimizer(LR).minimize(d_loss)
 
sess = tf.Session()
sess.run(tf.global_variables_initializer())
 
plt.ion()
 
for t in range(500):
    sess.run([o_train,d_train],feed_dict={tf_x:x,tf_y:y,tf_is_training:True})
    if t%10==0:
        plt.cla()
        [o_loss_,d_loss_,o_out_,d_out_] = sess.run([o_loss,d_loss,o_out,d_out],
        feed_dict = {tf_x:test_x,tf_y:test_y,tf_is_training:False})
        plt.scatter(x,y,c='magenta',s=50,alpha=0.3,label='train')
        plt.scatter(test_x,test_y,c='cyan',s=50,alpha=0.3,label='test')
        plt.plot(test_x,o_out_,'r-',lw=3,label='overfitting')
        plt.plot(test_x,d_out_,'b--',lw=3,label='dropout(50%)')
        plt.text(0,-1.2,'overfitting loss = %.4f'%o_loss_,fontdict={'size':10,'color':'red'})
        plt.text(0,-1.5,'dropout loss=%.4f'%d_loss_,fontdict={'size':10,'color':'blue'})
        plt.legend(loc='upper left')
        plt.ylim((-2.5,2.5))
        plt.pause(0.1)
        
plt.ioff()
plt.show()

 

红色的先为未使用dropout的线,可以看见它对于训练的散点有着较好的拟合效果,但其对于测试数据点效果不佳,并且loss=0.15左右,即其不具有推广性!

蓝色的线为采用了dropout的线,可以看见它在测试数据集上也取得了不错的效果,最后loss稳定在了0.05左右,具有推广性

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值