<jupyter_start><jupyter_text><jupyter_code>"""
import tensorflow as tf
print(tf.__version__)

mnist = tf.keras.datasets.mnist

(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

model.fit(x_train, y_train, epochs=5)
model.evaluate(x_test, y_test)

model.metrics_names
"""
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

import os
import pickle
import numpy as np

cifar10 = tf.keras.datasets.cifar10

(x_img_train, y_label_train),(x_img_test, y_label_test) = cifar10.load_data()

def get_mul(*nums):
    ret = 1
    for num in nums:
        ret *= num
    return ret

class CifarData:
    def __init__(self, data, label, need_shuffle):
        #index = [True if item[0] in [0, 1] else False for item in label]
        # print(set(index))
        index = [True for item in label]
        self._data = data[index]
        self._data = np.reshape(self._data, [self._data.shape[0], get_mul(*list(self._data.shape)[1:])])
        self._data = self._data / 127.5 - 1
        # self._labels = label[index]
        # self._labels = np.reshape(np.eye(10)[label[index]], (-1, 10))
        self._labels = np.reshape(label, (-1,))
        print(self._data.shape)
        print(self._labels.shape)
        # print(self._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
        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_data = CifarData(x_img_train, y_label_train, True)
test_data = CifarData(x_img_test, y_label_test, False)
print(set([item[0] for item in y_label_train]))
tf.reset_default_graph()

x = tf.placeholder(tf.float32, [None, 3072])
y = tf.placeholder(tf.int64, [None])

#w = tf.get_variable('w', [x.get_shape()[-1], 1], initializer=tf.random_normal_initializer(0, 1))
#b = tf.get_variable('b', [1], initializer=tf.constant_initializer(0))
w = tf.get_variable('w', [x.get_shape()[-1], 10], initializer=tf.random_normal_initializer(0, 1))
b = tf.get_variable('b', [10], initializer=tf.constant_initializer(0))

y_ = tf.matmul(x, w) + b

# p_y_1 = tf.nn.sigmoid(y_)
# y_reshaped = tf.reshape(y, (-1, 1))
p_y = tf.nn.softmax(y_)
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.sparse_softmax_cross_entropy(labels=y, logits=y_)

# indices
predict = tf.argmax(y_, 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 = 100000
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(x_img_test, y_label_test, 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))<jupyter_output>[Train] Step: 500, loss: 12.32553, acc: 0.25000
[Train] Step: 1000, loss: 11.45547, acc: 0.20000
[Train] Step: 1500, loss: 9.28195, acc: 0.20000
[Train] Step: 2000, loss: 16.18590, acc: 0.10000
[Train] Step: 2500, loss: 10.96650, acc: 0.35000
[Train] Step: 3000, loss: 8.29427, acc: 0.40000
[Train] Step: 3500, loss: 10.29505, acc: 0.15000
[Train] Step: 4000, loss: 10.03922, acc: 0.15000
[Train] Step: 4500, loss: 10.27045, acc: 0.15000
[Train] Step: 5000, loss: 9.97001, acc: 0.20000
(10000, 3072)
(10000,)
[Test ] Step: 5000, acc: 0.28000
[Train] Step: 5500, loss: 4.53131, acc: 0.40000
[Train] Step: 6000, loss: 7.77492, acc: 0.35000
[Train] Step: 6500, loss: 8.55934, acc: 0.25000
[Train] Step: 7000, loss: 7.36624, acc: 0.25000
[Train] Step: 7500, loss: 6.63871, acc: 0.25000
[Train] Step: 8000, loss: 6.45370, acc: 0.25000
[Train] Step: 8500, loss: 5.94166, acc: 0.25000
[Train] Step: 9000, loss: 4.21311, acc: 0.35000
[Train] Step: 9500, loss: 5.87860, acc: 0.35000
[Train] Step: 10000, loss:[...]
{'fraction_non_alphanumeric': 0.14133986928104575, 'fraction_numerical': 0.07581699346405228, 'mean_word_length': 2.954134366925065, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '532574', 'license': 'Apache-2.0', 'n_tokens_mistral': 2632, 'n_tokens_neox': 2263, 'n_words': 484, 'path': 'dl-imooc-259/chapter1.ipynb', 'repo_name': 'shqcandy/colab-backup', 'size': '6120'}