深度学习之cifar-10⑦——LSTM(长短期记忆)

此代码是在以前代码的基础上结合LSTM

import tensorflow as tf
import os
import pickle
import numpy as np

CIFAR_DIR = "../../datas/cifar-10-batches-py"
print(os.listdir(CIFAR_DIR))
#cifar_10 的LSTM实现
#其实就是把CNN的四维卷积换成三维
def load_data(filename):
    """read data from data file."""
    with open(filename, 'rb') as f:
        data = pickle.load(f, encoding='bytes')
        return data[b'data'], data[b'labels']

# tensorflow.Dataset.
class CifarData:
    def __init__(self, filenames, need_shuffle):
        all_data = []
        all_labels = []
        for filename in filenames:
            data, labels = load_data(filename)
            all_data.append(data)
            all_labels.append(labels)
        self._data = np.vstack(all_data)
        self._data = self._data / 127.5 - 1
        self._labels = np.hstack(all_labels)
        print(self._data.shape)
        print(self._labels.shape)

        self._num_examples = self._data.shape[0]
        self._need_shuffle = need_shuffle
        self._indicator = 0
        if self._need_shuffle:
            self._shuffle_data()

    #洗牌
    def _shuffle_data(self):
        # [0,1,2,3,4,5] -> [5,3,2,4,0,1]
        p = np.random.permutation(self._num_examples)
        self._data = self._data[p]
        self._labels = self._labels[p]

    #批次
    def next_batch(self, batch_size):
        """return batch_size examples as a batch."""
        end_indicator = self._indicator + batch_size
        if end_indicator > self._num_examples:
            if self._need_shuffle:
                self._shuffle_data()
                self._indicator = 0
                end_indicator = batch_size
            else:
                raise Exception("have no more examples")
        if end_indicator > self._num_examples:
            raise Exception("batch size is larger than all examples")
        batch_data = self._data[self._indicator: end_indicator]
        batch_labels = self._labels[self._indicator: end_indicator]
        self._indicator = end_indicator
        return batch_data, batch_labels

train_filenames = [os.path.join(CIFAR_DIR, 'data_batch_%d' % i) for i in range(1, 6)]
test_filenames = [os.path.join(CIFAR_DIR, 'test_batch')]

train_data = CifarData(train_filenames, True)
test_data = CifarData(test_filenames, False)

# Models
x = tf.placeholder(tf.float32, [None, 3072])
# [None], eg: [0,5,6,3]
y = tf.placeholder(tf.int64, [None])

# x_image = tf.reshape(x, [-1, 3, 32, 32])
x_image = tf.reshape(x, [-1, 3, 32*32])#这一步就是cnn和rnn的不同

hidden_size = 100#隐藏单元数
time_steps = 3#序列长度
classes_num = 10#分类数

cell = tf.contrib.rnn.MultiRNNCell([tf.contrib.rnn.BasicLSTMCell(hidden_size) for i in range(3)])
outputs,states = tf.nn.dynamic_rnn(cell,x_image,dtype = tf.float32)
outputs = tf.reshape(outputs,[-1,time_steps*hidden_size])
# logits = tf.contrib.layers.fully_connected(states[-1][1],classes_num,activation_fn=None)
logits = tf.contrib.layers.fully_connected(outputs,classes_num,activation_fn=None)


loss = tf.losses.sparse_softmax_cross_entropy(labels=y, logits=logits)

predict = tf.argmax(logits, 1)

correct_prediction = tf.equal(predict, y)
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float64))

with tf.name_scope('train_op'):
    train_op = tf.train.AdamOptimizer(1e-3).minimize(loss)
init = tf.global_variables_initializer()
batch_size = 20
train_steps = 10000
test_steps = 100


with tf.Session() as sess:
    sess.run(init)
    for i in range(train_steps):
        batch_data, batch_labels = train_data.next_batch(batch_size)
        loss_val, acc_val, _ = sess.run(
            [loss, accuracy, train_op],
            feed_dict={
                x: batch_data,
                y: batch_labels})
        if (i+1) % 500 == 0:
            print('[Train] Step: %d, loss: %4.5f, acc: %4.5f'
                  % (i+1, loss_val, acc_val))

        if (i+1) % 5000 == 0:
            test_data = CifarData(test_filenames, False)
            all_test_acc_val = []
            for j in range(test_steps):
                test_batch_data, test_batch_labels \
                    = test_data.next_batch(batch_size)
                test_acc_val = sess.run(
                    [accuracy],
                    feed_dict = {
                        x: test_batch_data,
                        y: test_batch_labels
                    })
                all_test_acc_val.append(test_acc_val)
            test_acc = np.mean(all_test_acc_val)
            print('[Test ] Step: %d, acc: %4.5f' % (i+1, test_acc))

[Train] Step: 500, loss: 2.03645, acc: 0.30000
[Train] Step: 1000, loss: 1.81862, acc: 0.30000
[Train] Step: 1500, loss: 1.18864, acc: 0.55000
[Train] Step: 2000, loss: 1.57325, acc: 0.45000
[Train] Step: 2500, loss: 1.50124, acc: 0.55000
[Train] Step: 3000, loss: 1.31993, acc: 0.50000
[Train] Step: 3500, loss: 1.47380, acc: 0.45000
[Train] Step: 4000, loss: 1.42851, acc: 0.45000
[Train] Step: 4500, loss: 1.37336, acc: 0.60000
[Train] Step: 5000, loss: 1.68647, acc: 0.35000
(10000, 3072)
(10000,)
[Test ] Step: 5000, acc: 0.48000
[Train] Step: 5500, loss: 1.14762, acc: 0.65000
[Train] Step: 6000, loss: 1.19144, acc: 0.65000
[Train] Step: 6500, loss: 1.46445, acc: 0.50000
[Train] Step: 7000, loss: 1.31382, acc: 0.60000
[Train] Step: 7500, loss: 1.78067, acc: 0.25000
[Train] Step: 8000, loss: 1.36945, acc: 0.70000
[Train] Step: 8500, loss: 1.53757, acc: 0.35000
[Train] Step: 9000, loss: 1.52190, acc: 0.35000
[Train] Step: 9500, loss: 1.05639, acc: 0.60000
[Train] Step: 10000, loss: 1.01759, acc: 0.60000
(10000, 3072)
(10000,)
[Test ] Step: 10000, acc: 0.49050
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值