A Single Neuron
Explore and run machine learning code with Kaggle Notebooks | Using data from DL Course Data
www.kaggle.com
*Kaggle에서 제공하는 Deep Learning Tutorial을 학습하며 번역한 내용입니다.
Deep Learning
인공지능의 발전의 많은 부분이 딥러닝 분야에서 이루어 졌다. 번역, 이미지 인식, 게임 등 다양한 분야에서 딥러닝 모델이 인간과 가까워 졌고 심지어는 인간을 능가하기 시작했다.
딥러닝은 아주 깊은 연산들의 stack이다. 이 딥러닝의 깊은 연산은 복잡한 현실세계 문제들을 풀 수 있다. neural networks는 neuron들로 구성되어 있다. neuron은 단순한 연한 하나를 수행하지만 이 neuron들의 복잡한 연결관계가 neural network의 power가 된다.
Linear Unit
neural network를 구성하는 가장 기본적인 단위는 neuron, unit이라고 한다. 다이어그램으로 표현하면 다음과 같다.
x는 input이고 weight이 곱해져 wx가 neuron에 도달한다. weight에 따라 neural network가 학습하게 된다.
b는 bias라고 하는 특별한 weight이다. input값과 관련이 없으며 input과 별도로 neuron의 output을 수정하도록 한다.
y가 궁극적인 뉴런의 output이고 output을 구하기 위한 식은 y = w * x + b가 된다.
이렇게 3 input connections를 nueron에 추가해 세가지 feature를 받아서 output을 내는 Linear unit model을 keras로 구현해보자.
from tensorflow import keras
from tensorflow.keras import layers
# Create a network with 1 linear unit
model = keras.Sequential([
layers.Dense(units=1, input_shape=[3])
])
units는 output의 수이다. 두번째 인자 input_shape로 keras에게 input의 dimension을 알려줄 수있다. [3]을 넣어주면 세개의 feature를 입력으로 받을 수 있게 된다. 이렇게 모델을 정의하면 데이터를 학습할 준비가 된 것이다.
Exercise
# Setup plotting
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
# Set Matplotlib defaults
plt.rc('figure', autolayout=True)
plt.rc('axes', labelweight='bold', labelsize='large',
titleweight='bold', titlesize=18, titlepad=10)
# Setup feedback system
from learntools.core import binder
binder.bind(globals())
from learntools.deep_learning_intro.ex1 import *
matplotlib는 파이썬 데이터 분석에서 사용하는 시각화 라이브러리다.
style.use("스타일시트")로 데이터를 표현할 스타일을 설정할 수 있다.
import pandas as pd
red_wine = pd.read_csv('../input/dl-course-data/red-wine.csv')
red_wine.head()
pandas는 데이터 조작, 분석을 위한 라이브러리이다. red-wine.csv를 읽어오자. 이 파일은 read-wine quality dataset이다. 각 와인의 physiochemical 성분들과 이 와인을 평가한 점수가 들어가 있다.
이 데이터셋을 학습시켜서 어떤 와인의 physiochemical 성분들을 Input으로 받아 점수를 Output으로 출력하는 keras 모델을 만들어보자.
red_wine.head()로 내용을 살펴보면 다음과 같다. 11개의 features와 와인의 quailty가 들어가 있다.
red_wine.shape # (rows, columns)
pandas로 읽어들인 dataFrame이 몇행 몇열로 되어있는지 확인할 수 있다.
# YOUR CODE HERE
input_shape = [11]
총 11개의 features를 input으로 받아야 하기 때문에 input_shape = [11]이다.
from tensorflow import keras
from tensorflow.keras import layers
# YOUR CODE HERE
model = keras.Sequential([
layers.Dense(units=1, input_shape = input_shape)
])
이제 본격적으로 keras model을 만들어보자. sequential의 의미는 뒤에서 차차 알아보도록 하고 지금은 단일 unit으로 구성된 input_shape=[11]인 모델을 만들었다.
내부적으로 keras는 neural network의 weights를 tensors로 표현한다. tensor는 기본적으로 다차원 배열이다. model의 weights은 tensor의 list로 저장되어있다. 우리가 정의한 model의 attribute인 weights를 꺼내보자.
# YOUR CODE HERE
w, b = model.weights
print("Weights\n{}\n\nBias\n{}".format(w, b))
weight과 bias를 출력해서 내용을 살펴보자. 총 11개의 input에 대해 각각 weight 출력되었다. weights는 tensors로 표현된다.
참고로 input_shape으로 Keras에게 3차원의 array input을 받겠다고 했다. 각 example마다 길이가 3인 vectors, [0.2, 0.4, 0.6]를 network가 받아들일 수 있고 이 examples로 이루어진 training data(3-dimentions)또한 tensor로 표현할 수 있다.
아직 모델이 학습하기 전이기 때문에 random으로 w, b가 정해진다. neural network는 더 나은 Weights를 찾아가며 학습을 진행하게 될 것이다.
Optional
우리의 목표는 data에 가장 잘 맞는 curve를 찾는 것이 될 것이다. curve-fitting과 매우 유사한 regression problems에 대해 공부하게 될텐데 선형모델이 만드는 curve를 잠깐 구경하고 마무리하자.
import tensorflow as tf
import matplotlib.pyplot as plt
model = keras.Sequential([
layers.Dense(1, input_shape=[1]),
])
x = tf.linspace(-1.0, 1.0, 100)
y = model.predict(x)
plt.figure(dpi=100)
plt.plot(x, y, 'k')
plt.xlim(-1, 1)
plt.ylim(-1, 1)
plt.xlabel("Input: x")
plt.ylabel("Target y")
w, b = model.weights # you could also use model.get_weights() here
plt.title("Weight: {:0.2f}\nBias: {:0.2f}".format(w[0][0], b[0]))
plt.show()
Input 1개, output 1개인 single neuron이기 때문에 linear한 그래프가 그려질 것이다.
'ComputerScience > Machine Learning' 카테고리의 다른 글
DeepLearning - 6. Binary Classification (0) | 2021.08.11 |
---|---|
DeepLearning - 5. Dropout and Batch Normalization (0) | 2021.08.10 |
DeepLearning - 4. Overfitting and Underfitting (0) | 2021.08.10 |
DeepLearning - 3. Stochastic Gradient Descent (0) | 2021.08.06 |
DeepLearning - 2. Deep Neural Networks (0) | 2021.08.04 |