반응형
TensorFlow란?
- Tensor를 활용할 수 있도록 Google Brain에서 제공하는 라이브러리
Tensor란?
- 단일 형태로 구성되어 있는 다차원 배열
- numpy와 비슷함
- "scalar"는 rank-0 tensor로, axis가 없다.
- "vector"는 rank-1 tensor (1-axis)
- "matrix"는 rank-2 tensor (2-axis)
import tensorflow as tf
# Constant Tensor
rank_3_tensor = tf.constant([
[[0, 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]]
])
print(rank_3_tensor)
# Reshape
print(tf.reshape(rank_3_tensor, [3*2 ,5], "\n"))
print(tf.reshape(rank_3_tensor, [3, -1]))
# Variable : 상태의 저장, 공유 등을 할 수 있는 것
my_tensor = tf.constant([[1.0, 2.0], [3.0, 4.0]])
my_variable = tf.Variable(my_tensor)
# Variables는 어떤 변수 형태도 사용 가능
bool_variable = tf.Variable([False, False, False, True])
complex_variable = tf.Variable([5 + 4j, 6 + 1j])
print("Shape: ", my_variable.shape)
print("DType: ", my_variable.dtype)
print("As NumPy: ", my_variable.numpy)
print("A variable: ", my_variable)
print("\nViewed as a tensor: ", tf.convert_to_tensor(my_variable))
print("\nIndex of highest value: ", tf.argmax(my_variable))
# Variable을 reshape하는 것이 아니라 새로 만든다.
print("\nCopying and reshaping: ", tf.reshape(my_variable, ([1,4])))
# Tensor는 CPU/GPU에 할당할 수 있다!
with tf.device("CPU:0"):
# Create some tensors
a = tf.Variable([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
c = tf.matmul(a, b)
print(c)
분류 문제 실습 (Fashion Mnist - 옷 레이블 분류 문제)
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
print(tf.__version__)
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
# About train data...
print("Train data shape: ", train_images.shape)
print("Number of labels: ", len(train_labels))
print("Train labels: ", train_labels)
print("Test data shape: ", test_images.shape)
print("Test labels: ", test_labels)
plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show()
# Normalization
train_images = train_images / 255.0
test_images = test_images / 255.0
# Train images의 시각화
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.show()
# Setup layer
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28,28)), # Input 28x28(784) -> Output 128
keras.layers.Dense(128, activation='relu'), # Input 128 -> Output 10
keras.layers.Dense(10) # Input 10 -> Output 1
])
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=10)
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print("\nTest accuracy: ", test_acc)반응형
'AI > Deep Learning' 카테고리의 다른 글
| [딥러닝] 인공신경망(Artifical Neural Network) (0) | 2025.12.07 |
|---|---|
| [딥러닝] 선형회귀와 경사하강법 (0) | 2025.12.07 |
| [딥러닝] 생성형 AI의 발전 과정 (0) | 2025.08.06 |
| [딥러닝] CNN (Convolutional Neural Network) (0) | 2024.12.11 |
| [딥러닝] 과대적합 (Overfitting) (0) | 2024.12.10 |