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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 | # -*- coding: utf-8 -*- """ML_Day03_vision05_Multiclass.ipynb Automatically generated by Colaboratory. Original file is located at """ from google.colab import drive drive.mount('/gdrive') PATH = "/gdrive/My Drive/Colab Notebooks/resources/" import matplotlib.pyplot as plt from tensorflow import keras import tensorflow as tf import numpy as np print(tf.__version__) ## download dataset as a zipfile !wget --no-check-certificate \ https://storage.googleapis.com/laurencemoroney-blog.appspot.com/rps.zip \ -O /tmp/rps.zip !wget --no-check-certificate \ https://storage.googleapis.com/laurencemoroney-blog.appspot.com/rps-test-set.zip \ -O /tmp/rps-test-set.zip ## extract zip file to temp folder import os import zipfile local_zip = '/tmp/rps.zip' zip_ref = zipfile.ZipFile(local_zip, 'r') zip_ref.extractall('/tmp/') zip_ref.close() local_zip = '/tmp/rps-test-set.zip' zip_ref = zipfile.ZipFile(local_zip, 'r') zip_ref.extractall('/tmp/') zip_ref.close() ## create fileName lists rock_dir = os.path.join('/tmp/rps/rock') paper_dir = os.path.join('/tmp/rps/paper') scissors_dir = os.path.join('/tmp/rps/scissors') print('total training rock images:', len(os.listdir(rock_dir))) print('total training paper images:', len(os.listdir(paper_dir))) print('total training scissors images:', len(os.listdir(scissors_dir))) rock_files = os.listdir(rock_dir) print(rock_files[:10]) paper_files = os.listdir(paper_dir) print(paper_files[:10]) scissors_files = os.listdir(scissors_dir) print(scissors_files[:10]) # %matplotlib inline import matplotlib.pyplot as plt import matplotlib.image as mpimg ## show pictures of images in filenames pic_index = 2 next_rock = [os.path.join(rock_dir, fname) for fname in rock_files[pic_index-2:pic_index]] next_paper = [os.path.join(paper_dir, fname) for fname in paper_files[pic_index-2:pic_index]] next_scissors = [os.path.join(scissors_dir, fname) for fname in scissors_files[pic_index-2:pic_index]] for i, img_path in enumerate(next_rock+next_paper+next_scissors): #print(img_path) img = mpimg.imread(img_path) plt.imshow(img) plt.axis('Off') plt.show() import tensorflow as tf import keras_preprocessing from keras_preprocessing import image from keras_preprocessing.image import ImageDataGenerator ## create image generator with options TRAINING_DIR = "/tmp/rps/" training_datagen = ImageDataGenerator( rescale = 1./255, rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest') VALIDATION_DIR = "/tmp/rps-test-set/" validation_datagen = ImageDataGenerator(rescale = 1./255) train_generator = training_datagen.flow_from_directory( TRAINING_DIR, target_size=(150,150), class_mode='categorical' ) validation_generator = validation_datagen.flow_from_directory( VALIDATION_DIR, target_size=(150,150), class_mode='categorical' ) ## 4 convolution and maxpooling layer with Dropout ## using softmax since we are doing multiclass classification model = tf.keras.models.Sequential([ # Note the input shape is the desired size of the image 150x150 with 3 bytes color # This is the first convolution tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(150, 150, 3)), tf.keras.layers.MaxPooling2D(2, 2), # The second convolution tf.keras.layers.Conv2D(64, (3,3), activation='relu'), tf.keras.layers.MaxPooling2D(2,2), # The third convolution tf.keras.layers.Conv2D(128, (3,3), activation='relu'), tf.keras.layers.MaxPooling2D(2,2), # The fourth convolution tf.keras.layers.Conv2D(128, (3,3), activation='relu'), tf.keras.layers.MaxPooling2D(2,2), # Flatten the results to feed into a DNN tf.keras.layers.Flatten(), tf.keras.layers.Dropout(0.5), # 512 neuron hidden layer tf.keras.layers.Dense(512, activation='relu'), tf.keras.layers.Dense(3, activation='softmax') ]) model.summary() model.compile(loss = 'categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) history = model.fit_generator(train_generator, epochs=25, validation_data = validation_generator, verbose = 1) model.save("rps.h5") ## we can see that validation accuracy's fluctuation.. import matplotlib.pyplot as plt acc = history.history['acc'] val_acc = history.history['val_acc'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(len(acc)) plt.plot(epochs, acc, 'r', label='Training accuracy') plt.plot(epochs, val_acc, 'b', label='Validation accuracy') plt.title('Training and validation accuracy') plt.legend(loc=0) plt.figure() plt.show() | cs |
참고자료 및 출처 : Convolutional Neural Networks in TensorFlow - Weak 4 Exercise
'Python Library > Machine Learning' 카테고리의 다른 글
[DNN] Day 04_shallow_neural-net_With_Vectorization (0) | 2019.07.28 |
---|---|
[DNN] Day 03_Logistic_Classification_With_Vectorized_Algorithm (0) | 2019.07.28 |
[CNN] Day 03_vision02_Model_Transfer_With_Augmentation (0) | 2019.07.27 |
[CNN] Day 02_vision01_basicOfCNN (0) | 2019.07.27 |
[NN] Day 01_introduction With MNIST (0) | 2019.07.23 |