반응형
Recent Posts
Recent Comments
관리 메뉴

개발잡부

[tf] 3. Convolution Layer 본문

강좌

[tf] 3. Convolution Layer

닉의네임 2022. 7. 31. 14:29
반응형

 

import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt

(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
#32x32x3
#Norma

train_images, test_images = train_images/255.0, test_images/255.0

이미지 확인

class_names = ['airplane','automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
plt.figure(figsize=(10,10))
for i in range(25) :
  plt.subplot(5,5,i+1)
  plt.xticks([])
  plt.yticks([])
  plt.grid(False)
  plt.imshow(train_images[i], cmap=plt.cm.binary)
  plt.xlabel(class_names[train_labels[i][0]])
plt.show()

Fucntional API 활용

import tensorflow as tf

inputs = tf.keras.Input(shape=(32,32,3))
x = tf.keras.layers.Flatten()(inputs)
x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(x)
outputs = tf.keras.layers.Dense(10, activation=tf.nn.softmax)(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)

Model class 상속

import tensorflow as tf
class MyModel(tf.keras.Model):
  def __init__(self) :
      super(MyModel, self).__init__()
      self.Dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
      self.Dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)

  def call(self, inputs):
    x=self.dense1(inputs)
    return self.dense2(x)
model = MyModel()

Sequential Funtion 활용

model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(8, input_shape=(16,0)))
model.add(tf.keras.layers.Dense(4))

Convolution Layer 생성 실습

tf.keras.layers.Conv2D(
    filters, kernel_size, strides=(1, 1), padding='valid',
    data_format=None, dilation_rate=(1, 1), groups=1, activation=None,
    use_bias=True, kernel_initializer='glorot_uniform',
    bias_initializer='zeros', kernel_regularizer=None,
    bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, 
    bias_constraint=None, **kwargs
)
x = tf.keras.layers.Conv2D(
      filters=32,
      kernel_size=(3,3),
      strides=(1, 1),
      padding='valid',
      activation='relu')(inputs)

x = tf.keras.layers.Conv2D(
      filters=64,
      kernel_size=(3,3),
      strides=(1, 1),
      padding='valid',
      activation='relu')(x)


x = tf.keras.layers.Flatten()(x)
outputs = tf.keras.layers.Dense(10, activation=tf.nn.softmax)(x)
model_by_func = tf.keras.Model(inputs=inputs, outputs=outputs, name='model_by_func')
model_by_func.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])
model_by_func.summary()

학습

hitstory = model_by_func.fit(train_images, train_labels, epochs=10, validation_data=(test_images, test_labels))

 

평가 (Evaluation)

plt.plot(hitstory.history['accuracy'], label='accuracy')
plt.plot(hitstory.history['val_accuracy'], label='val_accuracy')
plt.xlabel('Epoch')
plt.xlabel('Accuracy')
plt.ylim([0,1])
plt.legend(loc='lower right')

test_loss, test_acc = model_by_func.evaluate(test_images, test_labels, verbose=2)

반응형

'강좌' 카테고리의 다른 글

[cnn] Residual block  (0) 2022.08.07
[tf] 11. RNN  (0) 2022.07.31
선형회귀  (0) 2022.05.30
12.Multi-Classification 실습  (0) 2022.05.14
google colab  (0) 2022.03.24
Comments