파이선 코딩을 배우는 초보자도 머신 러닝에 독학으로 한번 도전해 보자.
왜냐구요? 그다지 어렵지 않으니까요!
머신 러닝을 배우려는 파이선 코딩 초보자들이 가지게 될 확률이 높은 의문점들을
하나하나 찾아내어 실제 풀어보고 결과를 확인해볼 수 있는 머신 러닝!
인터넷 교보문고에서 450페이지19900원에 판매중입니다.
________________________________________________________________________________________________________________________
머신 러닝 코드에서 일반적으로 전체 데이터를 읽어 들인 후 cost 함수를 구성하여 컴퓨팅을 하지만 만약에 처리해야 할 데이터가 컴퓨터 연산 속도와 메모리 용량을 위협할 정도로 엄청나게 클 경우 치명적인 문제가 발생할 수밖에 없다. 일단 해결책은 그때그때 온라인으로 입력된 데이터 양 만큼 Stochastic Gradient Descent 기법에 의해 미리 미리 처리하도록 하자. 일반 적인 Gradient Descent 와 달리 initialization 단계에서 w_initialized 와 shuffle 변수들이 추가된다.
Shuffling 이 필요한 이유는 학습 단계에서 업데이트되는 양상이 랜덤해져 동일한 문제를 매번 풀더라도 같은 패턴으로 반복되는 업데이트 과정을 피할 수 있기 때문이다. 현재 코드 상에는 shuffle=True로 되어 있는데 False 로 바꾸어도 결과는 동일하게 얻어진다.
Attributes(속성) 중 1차원 어레이로 취급되는 웨이트와 리스트 데이터 구조를 가지는 cost 는 AdalineGD 와 비교해 변동이 없다.
한 번 셔플된 상태에서 입력된 전체 데이터 중에서 하나씩을 대상으로 _update_weights(xi, target) 루틴을 실행하게 되면 데이터 하나에 대응하는 cost 값이 계산되어 sum(cost) 에 의해 합산이 되며 len(y) 값으로 나누면 샘플 한 개당의 평균 cost 값 즉 avg_cost 가 계산된다.
한편 _update_weights(xi, target) 루틴 내부에서는 데이터 하나별로 웨이트들의 업데이트가 일어난다. 이 점이 전체 데이터에 대해서 누적된 cost를 계산함과 아울러 한번에 웨이트를 업데이트 해버리는 AdalineGD와 근본적으로 다른 점이다.
하지만 Iris flowers 데이터에 대한 두가지 방법의 적용 후 cost 함수의 변동 결과를 관찰해 보면 큰 차이점이 있다는 것을 알 수 있다. 즉 Stochastic Gradient Descent가 잦은 웨이트 업데이트에 기인하여 학습초기에 수렴률이 무척 빠르다는 점이며 어느 정도 학습이 진행되면 AdalineGD와 비슷한 양상을 보이게 된다.
# ch02_Adaline_1_3_SGD
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
df = pd.read_csv('https://archive.ics.uci.edu/ml/'
'machine-learning-databases/iris/iris.data', header=None)
df.tail()
df = pd.read_csv('iris.data', header=None)
df.tail()
#select setosa and versicolor
y = df.iloc[0:100, 4].values
y = np.where(y == 'Iris-setosa', -1, 1)
#extract sepal length and petal length
X = df.iloc[0:100, [0, 2]].values
#standardize features
X_std = np.copy(X)
X_std[:, 0] = (X[:, 0] - X[:, 0].mean()) / X[:, 0].std()
X_std[:, 1] = (X[:, 1] - X[:, 1].mean()) / X[:, 1].std()
#Large scale machine learning and stochastic gradient descent
class AdalineSGD(object):
"""ADAptive LInear NEuron classifier.
Parameters
------------
eta : float
Learning rate (between 0.0 and 1.0)
n_iter : int
Passes over the training dataset.
shuffle : bool (default: True)
Shuffles training data every epoch if True to prevent cycles.
random_state : int
Random number generator seed for random weight
initialization.
Attributes
-----------
w_ : 1d-array
Weights after fitting.
cost_ : list
Sum-of-squares cost function value averaged over all
training samples in each epoch.
"""
def __init__(self, eta=0.01, n_iter=10, shuffle=False, random_state=None):
self.eta = eta
self.n_iter = n_iter
self.w_initialized = False
self.shuffle = shuffle
self.random_state = random_state
def fit(self, X, y):
""" Fit training data.
Parameters
----------
X : {array-like}, shape = [n_samples, n_features]
Training vectors, where n_samples is the number of samples and
n_features is the number of features.
y : array-like, shape = [n_samples]
Target values.
Returns
-------
self : object
"""
self._initialize_weights(X.shape[1])
self.cost_ = []
for i in range(self.n_iter):
if self.shuffle:
X, y = self._shuffle(X, y)
cost = []
for xi, target in zip(X, y):
cost.append(self._update_weights(xi, target))
avg_cost = sum(cost) / len(y)
self.cost_.append(avg_cost)
return self
def partial_fit(self, X, y):
"""Fit training data without reinitializing the weights"""
if not self.w_initialized:
self._initialize_weights(X.shape[1])
if y.ravel().shape[0] > 1:
for xi, target in zip(X, y):
self._update_weights(xi, target)
else:
self._update_weights(X, y)
return self
def _shuffle(self, X, y):
"""Shuffle training data"""
r = self.rgen.permutation(len(y))
return X[r], y[r]
def _initialize_weights(self, m):
"""Initialize weights to small random numbers"""
self.rgen = np.random.RandomState(self.random_state)
self.w_ = self.rgen.normal(loc=0.0, scale=0.01, size=1 + m)
self.w_initialized = True
def _update_weights(self, xi, target):
"""Apply Adaline learning rule to update the weights"""
#output means hypothesis
output = self.activation(self.net_input(xi))
error = (target - output)
self.w_[1:] += self.eta * xi.dot(error)
self.w_[0] += self.eta * error
cost = 0.5 * error**2
return cost
def net_input(self, X):
"""Calculate net input"""
return np.dot(X, self.w_[1:]) + self.w_[0]
def activation(self, X):
"""Compute linear activation"""
return X
def predict(self, X):
"""Return class label after unit step"""
return np.where(self.activation(self.net_input(X)) >= 0.0, 1, -1)
def plot_decision_regions(X, y, classifier, resolution=0.01):
#setup marker generator and color map
markers = ('s', 'x', 'o', '^', 'v')
colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
cmap = ListedColormap(colors[:len(np.unique(y))])
#plot the decision surface
x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
np.arange(x2_min, x2_max, resolution))
Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
Z = Z.reshape(xx1.shape )
plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap)
plt.xlim(xx1.min(), xx1.max())
plt.ylim(xx2.min(), xx2.max())
#plot class samples
for idx, cl in enumerate(np.unique(y)):
plt.scatter(x=X[y == cl, 0],
y=X[y == cl, 1],
alpha=0.8,
c=colors[idx],
marker=markers[idx],
label=cl,
edgecolor='black')
ada = AdalineSGD(n_iter=15, eta=0.01, random_state=1)
ada.fit(X_std, y)
plot_decision_regions(X_std, y, classifier=ada)
plt.title('Adaline - Stochastic Gradient Descent')
plt.xlabel('sepal length [standardized]')
plt.ylabel('petal length [standardized]')
plt.legend(loc='upper left')
plt.tight_layout()
plt.show()
plt.plot(range(1, len(ada.cost_) + 1), ada.cost_, marker='o')
plt.xlabel('Epochs')
plt.ylabel('Average Cost')
plt.tight_layout()
plt.show()
ada.partial_fit(X_std[0, :], y[0])
'머신러닝' 카테고리의 다른 글
Computational Graph 생성을 위한 GraphViz 사용법 (0) | 2019.04.24 |
---|---|
GraphViz, PyDotPlus 설치에 따른 Decision Tree Classifier 실행 (0) | 2019.04.23 |
Iris flowers data 사용 K 근접이웃 머신 러닝: K-nearest neighbors:KNN (0) | 2019.04.21 |
Boltzmann machine으로 표현한 Hopfield 네트워크 (0) | 2019.04.18 |
5 Units Hopfield 네트워크 계산 예제 (0) | 2019.04.18 |