1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | import tensorflow as tf from tensorflow.keras.optimizers import Adam from tensorflow.keras.layers import Dense class Model(tf.keras.Model): def __init__(self): super(Model, self).__init__() self.input_layer = Dense(256, activation='relu', input_shape=(784,)) self.hidden_layer = Dense(128, activation='relu') self.output_layer = Dense(10, activation='softmax') def call(self, x): x = self.input_layer(x) x = self.hidden_layer(x) output = self.output_layer(x) return output if __name__ == "__main__": # ¸ðµ¨, ¿À·ùÇÔ¼ö, ¿ÉƼ¸¶ÀÌÀú »ý¼º model = Model() cross_entropy = tf.keras.losses.CategoricalCrossentropy(from_logits=False) optimizer = Adam(1e-4) # µ¥ÀÌÅÍ ºÒ·¯¿À±â mnist = tf.keras.datasets.fashion_mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() # 0~255 ¹üÀ§ÀÇ Çȼ¿°ªÀ» 0~1·Î ³ë¸Ö¶óÀÌÁî x_train, x_test = x_train / 255.0, x_test / 255.0 # ¹Ì´Ï¹èÄ¡ »çÀÌÁî ¼³Á¤ batch_size = 32 num_train_data = x_train.shape[0] num_test_data = x_test.shape[0] num_epoch = 10 for e in range(num_epoch): # 1 ¿¡Æ÷Å© µ¿¾È ÈÆ·Ã ÁøÇà for i in range(num_train_data // batch_size): # ¹Ì´Ï ¹èÄ¡ Çϳª¸¸Å µ¥ÀÌÅÍ °¡Á®¿À±â x_batch = x_train[i * batch_size:(i + 1) * batch_size] y_batch = y_train[i * batch_size:(i + 1) * batch_size] # (batch_size, 28, 28) -> (batch_size, 28, 28, 1)·Î shape º¯°æ x_batch = x_batch.reshape(-1, 28*28) # Á¤´äÀ» one-hot encodingÀ¸·Î º¯°æ y_batch = tf.one_hot(y_batch, 10) # °è»ê °úÁ¤À» ±â·ÏÇϱâ À§ÇÑ tape scope ¼±¾ð model_params = model.trainable_variables with tf.GradientTape() as tape: # ¸ðµ¨À» ÅëÇÑ ¿¹Ãø predicts = model(x_batch) # ¿À·ùÇÔ¼ö °è»ê losses = cross_entropy(predicts, y_batch) # tape¸¦ ÅëÇÑ ±×·¹À̵ð¾ðÆ® °è»ê grads = tape.gradient(losses, model_params) # °è»êÇÑ ±×·¹À̵ð¾ðÆ®¸¦ ÅëÇØ ¸ðµ¨À» ¾÷µ¥ÀÌÆ® optimizer.apply_gradients(zip(grads, model_params)) x_test = x_test.reshape(-1, 28*28) predicts = model(x_test) corrects = tf.equal(tf.argmax(predicts, 1), y_test) accuracy = tf.reduce_mean(tf.cast(corrects, tf.float32), axis=-1) print("accuracy=%f"%accuracy) | cs |