### 2021.12.16

AND 연산은 논리 연산 (Logic operation)의 한 종류로 위의 그림과 같이 두 상태가 모두 참 (True, 1)일 때 참이고,

둘 중 하나라도 거짓 (False, 0)이라면 거짓이 되는 연산입니다.

전기 신호가 0과 1로 구성되어 있는 디지털 회로에서는 트랜지스터 게이트의 조합으로 구현할 수 있습니다.

위 그림은 두 개의 입력값을 받고, 하나의 값을 출력하는 간단한 인공신경망 (Artificial Neural Network)을 나타냅니다.

이제 TensorFlow를 이용해서 두 입력값에 대해 AND 논리 연산의 결과를 출력하는 신경망을 구현해보겠습니다.

 

훈련 데이터 준비하기

import tensorflow as tf
from tensorflow import keras
import numpy as np

tf.random.set_seed(0)

# 1. 훈련 데이터 준비하기
x_train = [[0, 0], [0, 1], [1, 0], [1, 1]]
y_train = [[0], [0], [0], [1]]

우선 tf.random 모듈의 set_seed() 함수를 사용해서 랜덤 시드를 설정했습니다.

예제에서 x_train, y_train은 각각 훈련에 사용할 입력값, 출력값입니다.

 

Neural Network 구성하기

# 2. 모델 구성하기
model = keras.Sequential([
    keras.layers.Dense(units=3, input_shape=[2], activation='relu'),
    keras.layers.Dense(units=1)
    ])

tf.keras 모듈의 Sequantial 클래스는 Neural Network의 각 층을 순서대로 쌓을 수 있도록 합니다.

tf.keras.layers 모듈의 Dense 클래스는 완전히 연결된 뉴런층을 구성합니다.

두 개의 Dense를 사용해서 아래 그림과 같은 구조의 신경망을 구성했습니다.

은닉층 (Hidden layer)의 활성화함수로 ReLU (Rectified Linear Unit)를 사용했습니다.

Neural Network 컴파일하기

# 3. 모델 컴파일하기
model.compile(loss='mse', optimizer='Adam')

손실 함수로 ‘mse’를, 옵티마이저로 ‘Adam’을 지정했습니다.

 

Neural Network 훈련하기

# 4. 모델 훈련하기
In[]
pred_before_training = model.predict(x_train)
print('Before Training: \n', pred_before_training)

history = model.fit(x_train, y_train, epochs=1000, verbose=0)

pred_after_training = model.predict(x_train)
print('After Training: \n', pred_after_training)


#Out[]
Before Training: 
 [[0.        ]
 [0.6210649 ]
 [0.06930891]
 [0.6721569 ]]
After Training: 
 [[-0.00612798]
 [ 0.00896964]
 [ 0.00497075]
 [ 0.99055475]]

tf.keras 모듈의 Model 클래스는 predict() 메서드를 포함합니다.

predict() 메서드를 이용해서 Neural Network의 예측값 (predicted value)을 얻을 수 있습니다.

Model 클래스의 fit() 메서드는 모델을 훈련하고, 훈련 진행 상황과 현재의 손실값을 반환합니다.

모델 훈련의 전후로 입력 데이터에 대한 Neural Network의 예측값을 출력하도록 했습니다.

 

손실값 확인하기

# 5. 손실값 확인하기
import matplotlib.pyplot as plt

loss = history.history['loss']
plt.plot(loss)
plt.xlabel('Epoch', labelpad=15)
plt.ylabel('Loss', labelpad=15)

plt.show()

fit() 메서드가 반환하는 손실값을 Matplotlib 라이브러리를 사용해서 시각화했습니다.

 

훈련 결과 확인하기

import matplotlib.pyplot as plt
import numpy as np

plt.style.use('default')
plt.rcParams['figure.figsize'] = (6, 4)
plt.rcParams['font.size'] = 14

plt.plot(pred_before_training, 's-', markersize=10, label='pred_before_training')
plt.plot(pred_after_training, 'd-', markersize=10, label='pred_after_training')
plt.plot(y_train, 'o-', markersize=10, label='y_train')

plt.xticks(np.arange(4), labels=['[0, 0]', '[0, 1]', '[1, 0]', '[1, 1]'])
plt.xlabel('Input (x_train)', labelpad=15)
plt.ylabel('Output (y_train)', labelpad=15)

plt.legend()
plt.show()

Matplotlib 라이브러리를 사용해서 훈련 전후의 입력값, 출력값을 나타냈습니다.

간단한 신경망에 대해 1000회의 훈련이 이루어지면, 네가지 경우의 0과 1 입력에 대해 1% 미만의 오차로

AND 연산을 수행할 수 있음을 확인할 수 있습니다.

 

전체 예제 코드

전체 코드는 아래와 같습니다.

신경망을 구성하는 과정에서 뉴런의 개수, 활성화함수, 그리고 옵티마이저를 바꿔가면서

훈련의 횟수와 정확도에 미치는 영향을 확인해 볼 수 있습니다.

import tensorflow as tf
from tensorflow import keras
import numpy as np

tf.random.set_seed(0)


# 1. 훈련 데이터 준비하기
x_train = [[0, 0], [0, 1], [1, 0], [1, 1]]
y_train = [[0], [0], [0], [1]]


# 2. 모델 구성하기
model = keras.Sequential([
    keras.layers.Dense(units=3, input_shape=[2], activation='relu'),
    # keras.layers.Dense(units=3, input_shape=[2], activation='sigmoid'),
    keras.layers.Dense(units=1)
    ])


# 3. 모델 컴파일하기
# model.compile(loss='mse', optimizer='SGD')
model.compile(loss='mse', optimizer='Adam')


# 4. 모델 훈련하기
pred_before_training = model.predict(x_train)
print('Before Training: \n', pred_before_training)

history = model.fit(x_train, y_train, epochs=1000, verbose=0)

pred_after_training = model.predict(x_train)
print('After Training: \n', pred_after_training)


# 5. 손실값 확인하기
import matplotlib.pyplot as plt

loss = history.history['loss']
plt.plot(loss)
plt.xlabel('Epoch', labelpad=15)
plt.ylabel('Loss', labelpad=15)

plt.show()

 

### 2021.12.16

 

티마이저 (Optimizer)는 손실 함수을 통해 얻은 손실값으로부터 모델을 업데이트하는 방식을 의미합니다.

TensorFlow는 SGD, Adam, RMSprop과 같은 다양한 종류의 옵티마이저를 제공합니다.

옵티마이저의 기본 사용법을 알아보고, 훈련 과정에서 옵티마이저에 따라 모델의 손실값이 어떻게 감소하는지 확인해 보겠습니다.

 

Neural Network 구성하기

이전 페이지에서와 마찬가지로 1개의 입력, 3개의 출력 노드를 갖는 신경망 모델을 구성합니다.

import tensorflow as tf
from tensorflow import keras
import numpy as np

tf.random.set_seed(0)

model = keras.Sequential([keras.layers.Dense(units=3, input_shape=[1])])

이번에는 tf.random 모듈의 set_seed() 함수를 사용해서 랜덤 시드를 설정했습니다.

tf.keras 모듈의 Sequantial 클래스는 Neural Network의 각 층을 순서대로 쌓을 수 있도록 합니다.

 

Neural Network 컴파일하기

구성한 모델의 손실 함수와 옵티마이저를 지정하기 위해 compile() 메서드를 사용합니다.

model.compile(loss='mse', optimizer='SGD')

손실 함수로 ‘mse’를, 옵티마이저로 ‘SGD’을 지정했습니다.

‘SGD’는 Stochastic Gradient Descent의 줄임말이며, 우리말로는 확률적 경사하강법이라고 부릅니다.

 

Neural Network 훈련하기

fit() 메서드는 컴파일 과정에서 지정한 손실 함수와 옵티마이저를 사용해서 모델을 훈련합니다.

In[]
model.fit([1], [[0, 1, 0]], epochs=1)
model.evaluate([1], [[0, 1, 0]])

#Out[]
1/1 [==============================] - 0s 209ms/step - loss: 1.0738
1/1 [==============================] - 0s 165ms/step - loss: 1.0453
1.0453256368637085

fit() 메서드는 훈련 진행 상황과 현재의 손실값을 반환합니다.

1회의 에포크 (epoch) 이후, evaluate() 메서드를 사용해서 손실값을 확인해보면

손실값이 1.0738에서 1.0453으로 감소했음을 알 수 있습니다.

history = model.fit([1], [[0, 1, 0]], epochs=100)

이번에는 훈련의 에포크를 100회로 지정했습니다.

100회 훈련 과정의 훈련 시간과 손실값이 출력됩니다.

 

손실값 시각화하기

import matplotlib.pyplot as plt

plt.style.use('default')
plt.rcParams['figure.figsize'] = (4, 3)
plt.rcParams['font.size'] = 12

loss = history.history['loss']
plt.plot(loss)
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.show()

fit() 메서드는 History 객체를 반환합니다.

History 객체의 history 속성은 훈련 과정의 손실값 (loss values)과 지표 (metrics)를 포함합니다.

컴파일 과정에서 지표를 지정하지 않았기 때문에 이 예제의 history 속성은 지표 (metrics)를 포함하지 않습니다.

훈련 과정의 손실값을 Matplotlib을 이용해서 그래프로 나타내면 아래와 같이 감소하는 경향을 확인할 수 있습니다.

 

출력값 시각화하기

import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
import numpy as np

plt.style.use('default')
plt.rcParams['figure.figsize'] = (4, 3)
plt.rcParams['font.size'] = 12

tf.random.set_seed(0)

model = keras.Sequential([keras.layers.Dense(units=3, input_shape=[1], use_bias=False)])
model.compile(loss='mse', optimizer='SGD')

pred = model.predict([1])
print(pred)
print(model.get_weights())

plt.bar(np.arange(3), pred[0])
plt.ylim(-1.1, 1.1)
plt.xlabel('Output Node')
plt.ylabel('Output')
plt.text(-0.4, 0.8, 'Epoch 0')
plt.tight_layout()
plt.savefig('./pred000.png')
plt.clf()

epochs = 500
for i in range(1, epochs+1):
  model.fit([1], [[0, 1, 0]], epochs=1, verbose=0)
  pred = model.predict([1])

  if i % 25 == 0:
      plt.bar(np.arange(3), pred[0])
      plt.ylim(-1.1, 1.1)
      plt.xlabel('Output Node')
      plt.ylabel('Output')
      plt.text(-0.4, 0.8, 'Epoch ' + str(i))
      plt.tight_layout()
      plt.savefig('./pred' + str(i).zfill(3) + '.png')
      plt.clf()

print(pred)
print(model.get_weights())
#Out[]
[[-0.5095548  -0.7187625   0.08668923]]
[array([[-0.5095548 , -0.7187625 ,  0.08668923]], dtype=float32)]
[[-0.0179761   0.9393657   0.00305823]]
[array([[-0.0179761 ,  0.9393657 ,  0.00305823]], dtype=float32)]
<Figure size 400x300 with 0 Axes>

이 코드는 Matplotlib을 이용해서 500회의 에포크 동안 훈련에 의해 출력값이 변화하는 과정을 시각화합니다.

Matplotlib의 다양한 함수에 대해서는 Matplotlib - 파이썬으로 그래프 그리기를 참고하세요.

아래 그림과 같이 훈련 과정 동안 출력값이 Target 값 [0, 1, 0]에 가까워지는 것을 알 수 있습니다.

 

옵테마이저 비교하기

아래의 예제는 세가지 옵티마이저 ‘SGD’, ‘Adam’, ‘RMSprop 이 모델을 업데이트하는 성능을 비교합니다.

import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt

plt.style.use('default')
plt.rcParams['figure.figsize'] = (4, 3)
plt.rcParams['font.size'] = 12

tf.random.set_seed(0)
model = keras.Sequential([keras.layers.Dense(units=3, input_shape=[1])])

tf.random.set_seed(0)
model2 = tf.keras.models.clone_model(model)

tf.random.set_seed(0)
model3 = tf.keras.models.clone_model(model)

model.compile(loss='mse', optimizer='SGD')
model2.compile(loss='mse', optimizer='Adam')
model3.compile(loss='mse', optimizer='RMSprop')

history = model.fit([1], [[0, 1, 0]], epochs=100, verbose=0)
history2 = model2.fit([1], [[0, 1, 0]], epochs=100, verbose=0)
history3 = model3.fit([1], [[0, 1, 0]], epochs=100, verbose=0)

loss = history.history['loss']
loss2 = history2.history['loss']
loss3 = history3.history['loss']
plt.plot(loss, label='SGD')
plt.plot(loss2, label='Adam')
plt.plot(loss3, label='RMSprop')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend(loc='lower left')
plt.show()


# 우선 세 개의 모델이 동일한 가중치 값을 갖도록 하기 위해 **set_seed()** 함수를 세번 호출했습니다.

# **compile()** 메서드에 각각 다른 옵티마이저를 지정합니다.

100회 훈련 과정의 손실값을 시각화하면 위와 같습니다.

옵티마이저에 따라 모델을 업데이트하는 방식과 손실값이 감소하는 경향에 차이가 있음을 알 수 있습니다.

 

### 2021.12.16

손실 함수 (Loss function)는 Neural Network의 예측이 얼마나 잘 맞는지 측정하는 역할을 합니다.

손실 함수로부터 얻어진 손실값 (Loss value)은 훈련 과정에서 Neural Network가 얼마나 잘 훈련되었는지 확인하는 지표가 됩니다.

Mean Squared Error 손실 함수를 사용해서 모델의 손실값을 확인하는 과정에 대해 소개합니다.

 

Neural Network 구성하기

아래의 코드는 하나의 입력을 받고 세 개의 출력 노드를 갖는 Neural Network를 구성합니다.

import tensorflow as tf
from tensorflow import keras
import numpy as np

model = keras.Sequential([keras.layers.Dense(units=3, input_shape=[1])])

tf.keras 모듈의 Sequential 클래스는 Neural Network의 각 층을 순서대로 쌓을 수 있도록 합니다.

tf.keras.layers 모듈의 Dense 클래스는 (완전 연결된) 하나의 뉴런층을 구현합니다.

units는 뉴런 또는 출력 노드의 개수를 의미하며, 양의 정수로 설정합니다.

input_shape는 입력 데이터의 형태를 결정합니다.

 

Neural Network 컴파일하기

모델을 구성했다면, 이 모델을 훈련하기 전에 손실 함수와 옵티마이저를 지정해주는 컴파일 과정이 필요합니다.

model.compile(loss='mse')

compile() 메서드의 loss 파라미터를 이용해서 손실 함수를 'mse'로 지정했습니다.

mse Mean Squared Error의 줄임말이며 아래의 수식을 이용해서 평균 제곱 오차를 계산하는 방식입니다.

  • n은 출력값의 개수.
  • yi는 관측값 (목표값).
  • y^i는 예측값.

예측치와 관측값의 차이인 오차의 제곱에 비례해서 손실 함수로부터 계산되는 손실값이 커집니다.

 

Neural Network 예측하기

predict() 메서드를 이용해서 Neural Network의 예측값 (predicted value)을 얻을 수 있습니다.

 

in[]
pred = model.predict([0])
print(pred)

#out[]
[[0. 0. 0.]]

임의로 생성된 모델의 가중치 값 (weights)이 있지만, 입력이 0이므로 예측값도 모두 0을 출력합니다.

 

Neural Network 손실 계산하기

evaluate() 메서드는 예측값과 관측값 사이의 손실값을 반환합니다.

in[]
model.evaluate([0], [[0, 1, 0]])

#out[]
1/1 [==============================] - 0s 111ms/step - loss: 0.3333
0.3333333432674408

 

 

### 2021.12.16

Neural Network 구성하기

import tensorflow as tf
from tensorflow import keras
import numpy as np

model = keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])

tf.keras (tensorflow.keras)는 TensorFlow의 하이레벨 구현을 위한 Keras API 모듈입니다.

tf.keras 모듈의 Sequential 클래스는 Neural Network의 각 층을 순서대로 쌓을 수 있도록 합니다.

tf.keras.layers 모듈의 Dense 클래스는 (완전 연결된) 하나의 뉴런층을 구현합니다.

units는 뉴런 또는 출력 노드의 개수를 의미하며, 양의 정수로 설정합니다.

input_shape는 입력 데이터의 형태를 결정합니다.

 

Neural Network 컴파일하기

model.compile(loss='mean_squared_error', optimizer='sgd')

다음으로 Neural Network 모델을 컴파일하는 과정에서는,

모델의 학습에 필요한 손실함수 (loss function)와 옵티마이저 (optimizer)를 결정합니다.

손실함수는 Neural Network의 예측이 얼마나 잘 맞는지 측정하는 역할을 하고, 옵티마이저는 더 개선된 예측값을 출력하도록 최적화하는 알고리즘입니다.

예제에서는 각각 mean_squared_error와 SGD (Stochastic Gradient Descent)로 설정했습니다.

경우에 따라 다른 손실함수와 옵티마이저가 더 효과적일 수 있습니다.

더 자세한 내용은 TensorFlow 공식 문서를 참고하세요.

 

Neural Network 훈련하기

xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float)

model.fit(xs, ys, epochs=500)

xs, ys는 Neural Network의 훈련에 사용할 입력과 출력 데이터이며, ‘y = 2x - 1’의 관계를 갖는 것처럼 보입니다.

에포크 (epoch)는 주어진 데이터를 한 번 훈련하는 단위입니다.

 

Neural Network 예측하기

Sequantial 클래스의 predict() 메서드를 사용하면 특정 입력에 대해 Neural Network가 출력 (예측)하는 값을 얻을 수 있습니다.

in[]
pred = model.predict([5.0])
print(pred)

#out[]
[[8.995342]]

훈련이 끝난 Neural Network에 숫자 5.0을 입력하면, 약 8.99를 출력합니다.

비록 작은 오차가 있지만, 이제 이 간단한 Neural Network는 어떤 입력 x에 대해서 대략 2x - 1를 출력하도록 훈련되었습니다.

작은 오차가 발생하는 이유는 ‘여섯 개’라는 적은 양의 입출력 데이터를 훈련에 사용했기 때문이고,

또한 모든 x에 대해, 입출력의 관계가 ‘y = 2x - 1’이 아닐 가능성이 있기 때문입니다.

전체 코드

import tensorflow as tf
from tensorflow import keras
import numpy as np

model = keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])
model.compile(optimizer='sgd', loss='mean_squared_error')

xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float)

model.fit(xs, ys, epochs=500)

pred = model.predict([5.0])
print(pred)

 

 

### 2021.12.16

 

텐서란?

텐서 (Tensor)는 다차원 배열 (Multi-dimensional Array)입니다.

텐서 (Tensor)는 벡터 (Vector)와 행렬 (Matrix)을 일반화한 것이며, 3차원 이상으로 확장할 수 있습니다.

텐서 (Tensor)는 TensorFlow의 가장 주요한 객체이며, TensorFlow의 작업은 주로 텐서의 연산으로 이루어집니다.

즉, TensorFlow는 텐서 (Tensor)를 정의하고 연산을 수행하도록 하는 프레임워크 (Framework)입니다.

 

텐서의 차원 - 랭크(Rank)

텐서의 랭크 확인하기

import tensorflow as tf

scalar = tf.constant(1)
vector = tf.constant([1, 2, 3])
matrix = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
tensor = tf.constant([[[1, 2, 3], [4, 5, 6], [7, 8, 9],[10, 11, 12]],
                      [[1, 2, 3], [4, 5, 6], [7, 8, 9],[10, 11, 12]]])
in[]
print(tf.rank(scalar))
print(scalar)

#out[]
tf.Tensor(0, shape=(), dtype=int32)
tf.Tensor(1, shape=(), dtype=int32)
in[]
print(tf.rank(vector))
print(vector)

#out[]
tf.Tensor(1, shape=(), dtype=int32)
tf.Tensor([1 2 3], shape=(3,), dtype=int32)
in[]
print(tf.rank(matrix))
print(matrix)

#out[]
tf.Tensor(2, shape=(), dtype=int32)
tf.Tensor(
[[1 2 3]
 [4 5 6]
 [7 8 9]], shape=(3, 3), dtype=int32)
in[]
print(tf.rank(tensor))
print(tensor)

#out[]
tf.Tensor(3, shape=(), dtype=int32)
tf.Tensor(
[[[ 1  2  3]
  [ 4  5  6]
  [ 7  8  9]
  [10 11 12]]

 [[ 1  2  3]
  [ 4  5  6]
  [ 7  8  9]
  [10 11 12]]], shape=(2, 4, 3), dtype=int32)

텐서 (Tensor) 객체의 랭크 (Rank)는 차원의 수 (n-dimension)입니다.

tf.rank()는 텐서의 랭크를 반환합니다.

텐서 scalar, vector, matrix, tensor는 각각 랭크 0, 1, 2, 3를 가집니다.

 

텐서 만들기

모듈 임포트하기

import tensorflow as tf

#TensorFlow 프로그램을 만드는 가장 첫번째 단계는 tensorflow 라이브러리를 임포트하는 것입니다.

tf.constant() 사용하기

  • tf.constant()는 상수 텐서를 만듭니다.
a = tf.constant(1)
b = tf.constant([2])
c = tf.constant([[1, 2], [3, 4]])
in[1]
print(tf.rank(a))
print(a)
#out[1]
tf.Tensor(0, shape=(), dtype=int32)
tf.Tensor(1, shape=(), dtype=int32)

in[2]
print(tf.rank(b))
print(b)
#out[2]
tf.Tensor(1, shape=(), dtype=int32)
tf.Tensor([2], shape=(1,), dtype=int32)

in[3]
print(tf.rank(c))
print(c)
#out[3]
tf.Tensor(2, shape=(), dtype=int32)
tf.Tensor(
[[1 2]
 [3 4]], shape=(2, 2), dtype=int32)

 

tf.zeros() 사용하기

  • tf.zeros()는 모든 요소가 0인 텐서를 만듭니다.
  • tf.zeros()에 만들어질 텐서의 형태 (shape)를 입력합니다.
  • 텐서의 형태에 대해서는 4) 텐서의 데이터 타입과 형태를 참고하세요.
in[]
a = tf.zeros(1)
b = tf.zeros([2])
c = tf.zeros([2, 3])
print(a)
print(b)
print(c)

#out[]
tf.Tensor([0.], shape=(1,), dtype=float32)
tf.Tensor([0. 0.], shape=(2,), dtype=float32)
tf.Tensor(
[[0. 0. 0.]
 [0. 0. 0.]], shape=(2, 3), dtype=float32)

 

tf.ones() 사용하기

  • tf.ones()는 모든 요소가 1인 텐서를 만듭니다.
  • tf.ones()에 만들어질 텐서의 형태 (shape)를 입력합니다.
  • 텐서의 형태에 대해서는 4) 텐서의 데이터 타입과 형태를 참고하세요.
in[]
a = tf.ones(3)
b = tf.ones([4])
c = tf.ones([2, 2, 2])
print(a)
print(b)
print(c)

#out[]
tf.Tensor([1. 1. 1.], shape=(3,), dtype=float32)
tf.Tensor([1. 1. 1. 1.], shape=(4,), dtype=float32)
tf.Tensor(
[[[1. 1.]
  [1. 1.]]

 [[1. 1.]
  [1. 1.]]], shape=(2, 2, 2), dtype=float32)

 

tf.range() 사용하기

  • tf.range()는 파이썬 range()와 비슷하게, 주어진 범위와 간격을 갖는 숫자들의 시퀀스를 만듭니다.
in[]
a = tf.range(0, 3)
b = tf.range(1, 5, 2)
print(a)
print(b)

#out[]
tf.Tensor([0 1 2], shape=(3,), dtype=int32)
tf.Tensor([1 3], shape=(2,), dtype=int32)

 

tf.linspace() 사용하기

  • tf.linspace()는 numpy.linspace()와 비슷하게, 주어진 범위를 균일한 간격으로 나누는 숫자의 시퀀스를 반환합니다.
in[]
a = tf.linspace(0, 1, 3)
b = tf.linspace(0, 3, 10)
print(a)
print(b)

#out[]
tf.Tensor([0.  0.5 1. ], shape=(3,), dtype=float64)
tf.Tensor(
[0.         0.33333333 0.66666667 1.         1.33333333 1.66666667
 2.         2.33333333 2.66666667 3.        ], shape=(10,), dtype=float64)

 

텐서의 자료형과 형태

예제 #1

in[]
a = tf.constant(1)
b = tf.constant([2])
c = tf.constant([3, 4, 5])
print(a.dtype, a.shape)
print(b.dtype, b.shape)
print(c.dtype, c.shape)

#out[]
<dtype: 'int32'> ()
<dtype: 'int32'> (1,)
<dtype: 'int32'> (3,)

dtype, shape 속성은 각각 텐서 (Tensor)의 자료형과 형태를 반환합니다.

텐서 a, b, c는 모두 정수형 (int32)의 데이터를 갖고, 각각 ( ), (1,), (3,)의 형태를 가짐을 알 수 있습니다.

 

예제 #2

in[]
d = tf.constant([1., 2.])
e = tf.constant([[1, 2., 3]])
f = tf.constant([[1, 2], [3, 4]])
print(d.dtype, d.shape)
print(e.dtype, e.shape)
print(f.dtype, f.shape)

#out[]
<dtype: 'float32'> (2,)
<dtype: 'float32'> (1, 3)
<dtype: 'int32'> (2, 2)

텐서 d는 실수형 (float32)의 데이터를 갖고, (2,)의 형태를 가집니다.

텐서 e는 실수형 (float32)의 데이터를 갖고, (1, 3)의 형태를 가집니다.

(정수와 실수를 모두 포함하는 텐서의 자료형은 실수형이 됩니다.)

텐서 f는 정수형 (int32)의 데이터를 갖고, (2, 2)의 형태를 가집니다.

 

간단한 수학 연산

TensorFlow는 텐서 (Tensor)를 생성하고 연산하는 다양한 수학적 함수를 제공합니다.

in[]
a = tf.add(1, 2)
b = tf.subtract(10, 5)
c = tf.square(3)
d = tf.reduce_sum([1, 2, 3])
e = tf.reduce_mean([1, 2, 3])

print(a)
print(b)
print(c)
print(d)
print(e)

#out[]
tf.Tensor(3, shape=(), dtype=int32)
tf.Tensor(5, shape=(), dtype=int32)
tf.Tensor(9, shape=(), dtype=int32)
tf.Tensor(6, shape=(), dtype=int32)
tf.Tensor(2, shape=(), dtype=int32)

 

NumPy 호환성

텐서 (Tensor)는 NumPy 어레이와 비슷하지만,

  • 텐서는 GPU, TPU와 같은 가속기에서 사용할 수 있고,
  • 텐서는 값을 변경할 수 없습니다.

텐서를 NumPy array로 변경

  • 텐서의 numpy() 메서드를 사용해서 텐서를 NumPy 어레이로 변환할 수 있습니다.

 

in[]
a = tf.constant([1, 2, 3])

print(a)
print(a.numpy())

#out[]
tf.Tensor([1 2 3], shape=(3,), dtype=int32)
[1 2 3]

 

NumPy 어레이를 텐서로 변경

  • 반대로, 다양한 TensorFlow 연산은 자동으로 NumPy 어레이를 텐서로 변환합니다
in[]
import numpy as np

b = np.ones(3)

print(b)
print(tf.multiply(b, 3))


#out[]
[1. 1. 1.]
tf.Tensor([3. 3. 3.], shape=(3,), dtype=float64)

 

+ Recent posts