本文小编为大家详细介绍“RNN中的Dropout怎么实现”,内容详细,步骤清晰,细节处理妥当,希望这篇“RNN中的Dropout怎么实现”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。
我们可以简单的在RNN之前或之后加一个DropOut层,但是如果我们想在RNN层中间加上DropOut的话,就得用DropoutWrapper了。下面代码在每个RNN层的输入都应用Dropout,对每个输入有50%的概率丢弃。
keep_prob = 0.5cell = tf.contrib.rnn.BasicRNNCell(num_units=n_neurons)cell_drop = tf.contrib.rnn.DropoutWrapper(cell, input_keep_prob=keep_prob)multi_layer_cell = tf.contrib.rnn.MultiRNNCell([cell_drop] * n_layers)rnn_outputs, states = tf.nn.dynamic_rnn(multi_layer_cell, X, dtype=tf.float32)
当然,我们也可以通过设置output_keep_prob来对输出进行dropout。
其实,细心的童鞋可能已经发现,上面的代码是有问题的,因为我们在前面CNN中应用Dropout的时候是有一个is_training的placeholder来区分是在training还是testing应用的。但是上面代码并没有。确实,上面代码的最大问题就是在testing的时候,也会应用Dropout,当然,这并不是我们想要的。不幸的是,DropoutWrapper并不支持is_training的placeholder,因此,我们要么自己重写一个DropoutWapper类,要么我们有两个计算图,一个是用来training,另一个用来testing。这里我们看下两个计算图是怎么实现的,如下:
import sysis_training = (sys.argv[-1] == "train")X = tf.placeholder(tf.float32, [None, n_steps, n_inputs])y = tf.placeholder(tf.float32, [None, n_steps, n_outputs])cell = tf.contrib.rnn.BasicRNNCell(num_units=n_neurons)if is_training: cell = tf.contrib.rnn.DropoutWrapper(cell, input_keep_prob=keep_prob)multi_layer_cell = tf.contrib.rnn.MultiRNNCell([cell] * n_layers)rnn_outputs, states = tf.nn.dynamic_rnn(multi_layer_cell, X, dtype=tf.float32)[...] # build the rest of the graphinit = tf.global_variables_initializer()saver = tf.train.Saver()with tf.Session() as sess: if is_training: init.run() for iteration in range(n_iterations): [...] # train the model save_path = saver.save(sess, "/tmp/my_model.ckpt") else: saver.restore(sess, "/tmp/my_model.ckpt") [...] # use the model
读到这里,这篇“RNN中的Dropout怎么实现”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/4584682/blog/4390491