关于tensorflow里面的tf.contrib.rnn.BasicLSTMCell 中num_units参数问题

这里的num_units参数并不是指这一层油多少个相互独立的时序lstm,而是lstm单元内部的几个门的参数,这几个门其实内部是一个神经网络,答案来自知乎:

class TRNNConfig(object):
    """RNN配置参数"""

    # 模型参数
    embedding_dim = 100      # 词向量维度
    seq_length = 100        # 序列长度
    num_classes = 2        # 类别数
    vocab_size = 10000       # 词汇表达小

    num_layers= 2           # 隐藏层层数
    hidden_dim = 128        # 隐藏层神经元
    rnn = ‘lstm‘             # lstm 或 gru

    dropout_keep_prob = 0.8 # dropout保留比例
    learning_rate = 1e-3    # 学习率

    batch_size = 128         # 每批训练大小
    num_epochs = 5          # 总迭代轮次

    print_per_batch = 20    # 每多少轮输出一次结果
    save_per_batch = 10      # 每多少轮存入tensorboard

class TextRNN(object):
    """文本分类,RNN模型"""
    def __init__(self, config):
        self.config = config

        # 三个待输入的数据
        self.input_x = tf.placeholder(tf.int32, [None, self.config.seq_length], name=‘input_x‘)
        self.input_y = tf.placeholder(tf.float32, [None, self.config.num_classes], name=‘input_y‘)
        self.keep_prob = tf.placeholder(tf.float32, name=‘keep_prob‘)

        self.rnn()

    def rnn(self):
        """rnn模型"""

        def lstm_cell():   # lstm核
            return tf.contrib.rnn.BasicLSTMCell(self.config.hidden_dim, state_is_tuple=True)

        def gru_cell():  # gru核
            return tf.contrib.rnn.GRUCell(self.config.hidden_dim)

        def dropout():  # 为每一个rnn核后面加一个dropout层
            if (self.config.rnn == ‘lstm‘):
                cell = lstm_cell()
            else:
                cell = gru_cell()
            return tf.contrib.rnn.DropoutWrapper(cell, output_keep_prob=self.keep_prob)

        # 词向量映射
        with tf.device(‘/cpu:0‘):
            embedding = tf.get_variable(‘embedding‘, [self.config.vocab_size, self.config.embedding_dim])
            embedding_inputs = tf.nn.embedding_lookup(embedding, self.input_x)

        with tf.name_scope("rnn"):
            # 多层rnn网络
            cells = [dropout() for _ in range(self.config.num_layers)]
            rnn_cell = tf.contrib.rnn.MultiRNNCell(cells, state_is_tuple=True)

            _outputs, _ = tf.nn.dynamic_rnn(cell=rnn_cell, inputs=embedding_inputs, dtype=tf.float32)
            last = _outputs[:, -1, :]  # 取最后一个时序输出作为结果
            # last = _outputs  # 取最后一个时序输出作为结果

        with tf.name_scope("score"):
            # 全连接层,后面接dropout以及relu激活
            fc = tf.layers.dense(last, self.config.hidden_dim, name=‘fc1‘)
            fc = tf.contrib.layers.dropout(fc, self.keep_prob)
            fc = tf.nn.relu(fc)

            # 分类器
            self.logits = tf.layers.dense(fc, self.config.num_classes, name=‘fc2‘)
            self.y_pred_cls = tf.argmax(tf.nn.softmax(self.logits), 1)  # 预测类别

        with tf.name_scope("optimize"):
            # 损失函数,交叉熵
            cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=self.logits, labels=self.input_y)
            self.loss = tf.reduce_mean(cross_entropy)
            # 优化器
            self.optim = tf.train.AdamOptimizer(learning_rate=self.config.learning_rate).minimize(self.loss)

        with tf.name_scope("accuracy"):
            # 准确率
            correct_pred = tf.equal(tf.argmax(self.input_y, 1), self.y_pred_cls)
            self.acc = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

原文地址:https://www.cnblogs.com/cupleo/p/9902413.html

时间: 2024-08-30 12:30:59

关于tensorflow里面的tf.contrib.rnn.BasicLSTMCell 中num_units参数问题的相关文章

tf.contrib.rnn.static_rnn与tf.nn.dynamic_rnn区别

tf.contrib.rnn.static_rnn与tf.nn.dynamic_rnn区别 https://blog.csdn.net/u014365862/article/details/78238807 MachineLP的Github(欢迎follow):https://github.com/MachineLP 我的GitHub:https://github.com/MachineLP/train_cnn-rnn-attention 自己搭建的一个框架,包含模型有:vgg(vgg16,vg

深度学习原理与框架-递归神经网络-RNN网络基本框架(代码?) 1.rnn.LSTMCell(生成单层LSTM) 2.rnn.DropoutWrapper(对rnn进行dropout操作) 3.tf.contrib.rnn.MultiRNNCell(堆叠多层LSTM) 4.mlstm_cell.zero_state(state初始化) 5.mlstm_cell(进行LSTM求解)

问题:LSTM的输出值output和state是否是一样的 1. rnn.LSTMCell(num_hidden, reuse=tf.get_variable_scope().reuse)  # 构建单层的LSTM网络 参数说明:num_hidden表示隐藏层的个数,reuse表示LSTM的参数进行复用 2.rnn.DropoutWrapper(cell, output_keep_prob=keep_prob) # 表示对rnn的输出层进行dropout 参数说明:cell表示单层的lstm,o

ValueError: Attempt to reuse RNNCell <tensorflow.contrib.rnn.python.ops.core_rnn_cell_impl.BasicLSTMCell object at 0x7f1a3c448390> with a different variable scope than its first use.解决方法

最近在做生成电视剧本小项目,遇到以下报错 --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-16-a2d9a7091ca5> in <module>() 10 input_data_shape = tf.shape(input_text) 11 cell, ini

TF之RNN:实现利用scope.reuse_variables()告诉TF想重复利用RNN的参数的案例—Jason niu

import tensorflow as tf # 22 scope (name_scope/variable_scope) from __future__ import print_function class TrainConfig: batch_size = 20 time_steps = 20 input_size = 10 output_size = 2 cell_size = 11 learning_rate = 0.01 class TestConfig(TrainConfig):

TensorFlow(十二):使用RNN实现手写数字识别

上代码: import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data #载入数据集 mnist = input_data.read_data_sets("MNIST_data/",one_hot=True) # 输入图片是28*28 n_inputs = 28 #输入一行,一行有28个数据 max_time = 28 #一共28行 lstm_size = 100 #隐层单元 n_c

深度学习原理与框架-递归神经网络-RNN_exmaple(代码) 1.rnn.BasicLSTMCell(构造基本网络) 2.tf.nn.dynamic_rnn(执行rnn网络) 3.tf.expand_dim(增加输入数据的维度) 4.tf.tile(在某个维度上按照倍数进行平铺迭代) 5.tf.squeeze(去除维度上为1的维度)

1. rnn.BasicLSTMCell(num_hidden) #  构造单层的lstm网络结构 参数说明:num_hidden表示隐藏层的个数 2.tf.nn.dynamic_rnn(cell, self.x, tf.float32) # 执行lstm网络,获得state和outputs 参数说明:cell表示实例化的rnn网络,self.x表示输入层,tf.float32表示类型 3. tf.expand_dim(self.w, axis=0) 对数据增加一个维度 参数说明:self.w表

TensorFlow中的L2正则化函数:tf.nn.l2_loss()与tf.contrib.layers.l2_regularizerd()的用法与异同

tf.nn.l2_loss()与tf.contrib.layers.l2_regularizerd()都是TensorFlow中的L2正则化函数,tf.contrib.layers.l2_regularizerd()函数在tf 2.x版本中被弃用了. 两者都能用来L2正则化处理,但运算有一点不同. import tensorflow as tf sess = InteractiveSession() a = tf.constant([1, 2, 3], dtype=tf.float32) b =

TF之RNN:matplotlib动态演示之基于顺序的RNN回归案例实现高效学习逐步逼近余弦曲线—Jason niu

import tensorflow as tf import numpy as np import matplotlib.pyplot as plt BATCH_START = 0 TIME_STEPS = 20 BATCH_SIZE = 50 INPUT_SIZE = 1 OUTPUT_SIZE = 1 CELL_SIZE = 10 LR = 0.006 BATCH_START_TEST = 0 def get_batch(): global BATCH_START, TIME_STEPS #

学习笔记TF044:TF.Contrib组件、统计分布、Layer、性能分析器tfprof

TF.Contrib,开源社区贡献,新功能,内外部测试,根据反馈意见改进性能,改善API友好度,API稳定后,移到TensorFlow核心模块.生产代码,以最新官方教程和API指南参考. 统计分布.TF.contrib.ditributions模块,Bernoulli.Beta.Binomial.Gamma.Ecponential.Normal.Poisson.Uniform等统计分布,统计研究.应用中常用,各种统计.机器学习模型基石,概率模型.图形模型依赖. 每个不同统计分布不同特征.函数,同