cifar10 进行多分类

import pickle
import numpy as np
import os
CIFAR_DIR = r'./data/cifar-10-batches-py'
print(os.listdir(CIFAR_DIR))

with open(os.path.join(CIFAR_DIR, 'data_batch_1'), 'rb') as f:
    data = pickle.load(f,encoding='latin1')
    print(type(data))
    print(type(data['data']))
    print(data['data'].shape)

image_arr = data['data'][100]
image_arr = image_arr.reshape((3,32,32)) # 32,32,33
image_arr = image_arr.transpose((1,2,0)) # numpy转换维度

import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow
imshow(image_arr)
plt.show()

# tensorlow model
import tensorflow as tf
import os
import numpy as np

def load_data(filename):
    """ read data from data file."""
    with open(filename, 'rb') as f:
        data = pickle.load(f,encoding='latin1')
        return data['data'],data['labels']

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)
            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  # 其实位置加上 batch
        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)
batch_data, batch_labels = train_data.next_batch(10)

# #####################
# 二分类
# 占位符,数据来时把数据出入进去  32*32*3 = 3072
x = tf.placeholder(tf.float32, [None, 3072])
y = tf.placeholder(tf.int64, [None])
# (3072 * 10)
w = tf.get_variable('w', [x.get_shape()[-1], 10],
                    initializer = tf.random_normal_initializer(0,1))
# (1,)
b = tf.get_variable('b',[10],
                    initializer=tf.constant_initializer(0.0))
# (None, 3072) * (3072,10) = [None, 10]
# mean square loss
y_ = tf.matmul(x,w) +b
p_y = tf.nn.softmax(y_) # [0.1,0.2,0.01,0.3,.....]
# 5 --> [0,0,0,0,1,0,0,0,0,0]
y_one_hot = tf.one_hot(y,10,dtype=tf.float32)
loss = tf.reduce_mean(tf.square(y_one_hot - p_y))
"""
loss = tf.losses.aparse_softmax_cross_entropy(labels=y, logits=y_)

# y_ --> sofmax
# y --> one_hot
# loss = y log (y)

"""
"""
# [None, 1]
p_y_1 = tf.nn.sigmoid(y_)  # 得到概率值
y_reshaped = tf.reshape(y, (-1,1))
y_reshaped_float = tf.cast(y_reshaped, tf.float32)
#平方差
loss = tf.reduce_mean(tf.square(y_reshaped_float - p_y_1))
"""

# predict = p_y_1 > 0.5
# 判断预测中的正确个数
predict = tf.argmax(y_, 1)
correct_prediction = tf.equal(tf.cast(predict,tf.float32),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

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, loss_val, acc_val))

        if (i+1) % 5000 ==0:
            test_data = CifarData(test_filenames, False)
            all_test_acc_val = []
            for j in ragne(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.5' %(i, test_acc))



 

你可能感兴趣的:(深度学习,cifar10数据,多分类,tensorflow,神经网络)