LSTMCLASS

4 篇文章 0 订阅
import tensorflow as tf


class LSTM(object):
    """docstring for LSTM"""

    def __init__(self, n_batch, n_step, n_input, n_output, n_cell, lr):
        super(LSTM, self).__init__()
        self.batch = n_batch
        self.step = n_step
        self.n_input = n_input
        self.n_output = n_output
        self.cellnum = n_cell
        self.lr = lr
        self.x = tf.placeholder(tf.float32, [None, n_step, n_input])
        self.y = tf.placeholder(tf.float32, [None, n_output])
        self.add_in_layer()
        self.add_lstm_layer()
        self.add_out_layer()
        self.get_loss()
        self.train()
        self.evaluate()

    def add_in_layer(self):
        x_input = tf.reshape(self.x, [-1, self.n_input])
        layer_input = tf.layers.dense(x_input, self.cellnum)
        self.layer_input = tf.reshape(
            layer_input, [-1, self.step, self.cellnum])

    def add_lstm_layer(self):
        self.cell = tf.contrib.rnn.BasicLSTMCell(self.cellnum)
        self.init_state = self.cell.zero_state(self.batch, dtype=tf.float32)
        self.output, self.state = tf.nn.dynamic_rnn(
            self.cell, self.layer_input, initial_state=self.init_state, time_major=False)

    def add_out_layer(self):
        self.layer_output = tf.layers.dense(self.state[1], self.n_output)

    def get_loss(self):
        self.loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
            labels=self.y, logits=self.layer_output))

    def train(self):
    	self.train_op = tf.train.AdamOptimizer(self.lr).minimize(self.loss)

    def evaluate(self):
    	self.acc = tf.cast(tf.equal(tf.argmax(self.y, 1), tf.argmax(self.layer_output, 1)), tf.float32)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值