
3장. 앙상블 학습을 이용한 예측 분석
앙상블 학습
+앙상블 학습을 이용한 학습 모델 구축하기
의사 결정 트리
의사 결정 트리 기반 분류기 구축하기
랜덤 포레스트와 극단 랜덤포레스트
__랜덤 포레스트와 극단 랜덤 포레스트 분류기 만들기
예측 신뢰도 측정하기
클래스 별 데이터 불균형 처리
그리드 검색을 사용해 최적의 학습 매개변수 찾기
특징별 상대적 중요도 계산
극단 랜덤 포레스트 회귀분석을 이용한 교통량 예측
요약
4장. 비지도 학습을 이용한 패턴 추출
비지도 학습
K-평균 알고리즘을 이용한 데이터 군집화
평균 이동 알고리즘으로 군집 개수 예측하기
실루엣 지수로 군집화 품질 측정하기
가우시안 혼합 모델
가우시안 혼합 모델 기반 분류기 만들기
AP 모델로 주식 시장에서 소그룹 찾기
쇼핑 패턴에 따른 시장 세분화
__요약
#3장. 앙상블 학습을 이용한 예측 분석
분류기 사용 시 최적의 매개변수 찾기 어려움 <- 그리드 검색 유용
하이퍼파라미터 최적화 (Hyperparameter Optimization): 머신 러닝 모델의 성능은 하이퍼파라미터에 크게 의존함 / 코드에서는 ExtraTreesClassifier 모델의 두 가지 주요 하이퍼파라미터인 n_estimators와 max_depth를 조정하여 모델의 성능을 최적화하고자 함
그리드 검색 (Grid Search): 가능한 모든 하이퍼파라미터 조합을 시도하여 최적의 조합을 찾는 탐색 기법 / 매개변수 값의 범위를 지정하면 자동으로 다양한 매개변수를 조합해 최적의 값을 찾아줌 / 코드에서는 GridSearchCV를 사용하여 parameter_grid에 정의된 다양한 하이퍼파라미터 조합을 탐색하고, 각 조합에 대한 성능을 평가함
교차 검증 (Cross-Validation): 교차 검증은 모델의 일반화 성능을 더 정확하게 평가하기 위한 기법으로, 훈련 데이터를 여러 개의 서브셋으로 나누고 각각을 사용하여 모델을 평가하는 것 / 코드에서는 GridSearchCV의 cv 매개변수를 통해 5-fold 교차 검증을 사용함
성능 평가 (Performance Evaluation): 모델의 성능을 평가하기 위해 여러 지표를 사용할 수 있음 / 코드에서는 precision과 recall을 가중치를 고려하여 평가하는 precision_weighted와 recall_weighted 지표를 사용함 / 이러한 성능 지표를 통해 모델이 각 클래스에 대해 얼마나 잘 분류되는지 평가할 수 있음
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import classification_report
from sklearn import cross_validation, grid_search
from sklearn.ensemble import ExtraTreesClassifier
from sklearn import cross_validation
from sklearn.metrics import classification_report
from utilities import visualize_classifier
# Load input data
input_file = 'data_random_forests.txt'
data = np.loadtxt(input_file, delimiter=',')
X, y = data[:, :-1], data[:, -1]
# Separate input data into three classes based on labels
class_0 = np.array(X[y==0])
class_1 = np.array(X[y==1])
class_2 = np.array(X[y==2])
# Split the data into training and testing datasets
X_train, X_test, y_train, y_test = cross_validation.train_test_split(
X, y, test_size=0.25, random_state=5)
# Define the parameter grid
parameter_grid = [ {'n_estimators': [100], 'max_depth': [2, 4, 7, 12, 16]},
{'max_depth': [4], 'n_estimators': [25, 50, 100, 250]}
]
metrics = ['precision_weighted', 'recall_weighted']
for metric in metrics:
print("\n##### Searching optimal parameters for", metric)
classifier = grid_search.GridSearchCV(
ExtraTreesClassifier(random_state=0),
parameter_grid, cv=5, scoring=metric)
classifier.fit(X_train, y_train)
print("\nGrid scores for the parameter grid:")
for params, avg_score, _ in classifier.grid_scores_:
print(params, '-->', round(avg_score, 3))
print("\nBest parameters:", classifier.best_params_)
y_pred = classifier.predict(X_test)
print("\nPerformance report:\n")
print(classification_report(y_test, y_pred))
import numpy as np
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import AdaBoostRegressor
from sklearn import datasets
from sklearn.metrics import mean_squared_error, explained_variance_score
from sklearn import cross_validation
from sklearn.utils import shuffle
# 주택 데이터 로드
housing_data = datasets.load_boston()
# 데이터 셔플
X, y = shuffle(housing_data.data, housing_data.target, random_state=7)
# 데이터를 훈련 및 테스트 데이터로 분할
X_train, X_test, y_train, y_test = cross_validation.train_test_split(
X, y, test_size=0.2, random_state=7)
# 아다부스트 회귀 분류기 모델 생성
regressor = AdaBoostRegressor(DecisionTreeRegressor(max_depth=4),
n_estimators=400, random_state=7)
regressor.fit(X_train, y_train)
# 아다부스트 회귀 분류기 성능 평가
y_pred = regressor.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
evs = explained_variance_score(y_test, y_pred)
print("\nADABOOST REGRESSOR")
print("Mean squared error =", round(mse, 2))
print("Explained variance score =", round(evs, 2))
# 특성 중요도 추출
feature_importances = regressor.feature_importances_
feature_names = housing_data.feature_names
# 중요도 값 정규화
feature_importances = 100.0 * (feature_importances / max(feature_importances))
# 값 정렬 및 뒤집기
index_sorted = np.flipud(np.argsort(feature_importances))
# X축 틱 정렬
pos = np.arange(index_sorted.shape[0]) + 0.5
# 막대 그래프 플롯
plt.figure()
plt.bar(pos, feature_importances[index_sorted], align='center')
plt.xticks(pos, feature_names[index_sorted])
plt.ylabel('Relative Importance')
plt.title('Feature importance using AdaBoost regressor')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import classification_report, mean_absolute_error
from sklearn import cross_validation, preprocessing
from sklearn.ensemble import ExtraTreesRegressor
from sklearn.metrics import classification_report
# Load input data
input_file = 'traffic_data.txt'
data = []
with open(input_file, 'r') as f:
for line in f.readlines():
items = line[:-1].split(',')
data.append(items)
data = np.array(data)
# Convert string data to numerical data
label_encoder = []
X_encoded = np.empty(data.shape)
for i, item in enumerate(data[0]):
if item.isdigit():
X_encoded[:, i] = data[:, i]
else:
label_encoder.append(preprocessing.LabelEncoder())
X_encoded[:, i] = label_encoder[-1].fit_transform(data[:, i])
X = X_encoded[:, :-1].astype(int)
y = X_encoded[:, -1].astype(int)
# Split data into training and testing datasets
X_train, X_test, y_train, y_test = cross_validation.train_test_split(
X, y, test_size=0.25, random_state=5)
# Extremely Random Forests regressor
params = {'n_estimators': 100, 'max_depth': 4, 'random_state': 0}
regressor = ExtraTreesRegressor(**params)
regressor.fit(X_train, y_train)
# Compute the regressor performance on test data
y_pred = regressor.predict(X_test)
print("Mean absolute error:", round(mean_absolute_error(y_test, y_pred), 2))
# Testing encoding on single data instance
test_datapoint = ['Saturday', '10:20', 'Atlanta', 'no']
test_datapoint_encoded = [-1] * len(test_datapoint)
count = 0
for i, item in enumerate(test_datapoint):
if item.isdigit():
test_datapoint_encoded[i] = int(test_datapoint[i])
else:
test_datapoint_encoded[i] = int(label_encoder[count].transform(test_datapoint[i]))
count = count + 1
test_datapoint_encoded = np.array(test_datapoint_encoded)
# Predict the output for the test datapoint
print("Predicted traffic:", int(regressor.predict([test_datapoint_encoded])[0]))
#4장. 비지도 학습을 이용한 패턴 추출
e.g.,
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn import metrics
# Load input data
X = np.loadtxt('data_clustering.txt', delimiter=',')
num_clusters = 5
# Plot input data
plt.figure()
plt.scatter(X[:,0], X[:,1], marker='o', facecolors='none',
edgecolors='black', s=80)
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
plt.title('Input data')
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.xticks(())
plt.yticks(())
# Create KMeans object
kmeans = KMeans(init='k-means++', n_clusters=num_clusters, n_init=10)
# Train the KMeans clustering model
kmeans.fit(X)
# Step size of the mesh
step_size = 0.01
# Define the grid of points to plot the boundaries
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
x_vals, y_vals = np.meshgrid(np.arange(x_min, x_max, step_size),
np.arange(y_min, y_max, step_size))
# Predict output labels for all the points on the grid
output = kmeans.predict(np.c_[x_vals.ravel(), y_vals.ravel()])
# Plot different regions and color them
output = output.reshape(x_vals.shape)
plt.figure()
plt.clf()
plt.imshow(output, interpolation='nearest',
extent=(x_vals.min(), x_vals.max(),
y_vals.min(), y_vals.max()),
cmap=plt.cm.Paired,
aspect='auto',
origin='lower')
# Overlay input points
plt.scatter(X[:,0], X[:,1], marker='o', facecolors='none',
edgecolors='black', s=80)
# Plot the centers of clusters
cluster_centers = kmeans.cluster_centers_
plt.scatter(cluster_centers[:,0], cluster_centers[:,1],
marker='o', s=210, linewidths=4, color='black',
zorder=12, facecolors='black')
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
plt.title('Boundaries of clusters')
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.xticks(())
plt.yticks(())
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import MeanShift, estimate_bandwidth
from itertools import cycle
# Load data from input file
X = np.loadtxt('data_clustering.txt', delimiter=',')
# Estimate the bandwidth of X
bandwidth_X = estimate_bandwidth(X, quantile=0.1, n_samples=len(X))
# Cluster data with MeanShift
meanshift_model = MeanShift(bandwidth=bandwidth_X, bin_seeding=True)
meanshift_model.fit(X)
# Extract the centers of clusters
cluster_centers = meanshift_model.cluster_centers_
print('\nCenters of clusters:\n', cluster_centers)
# Estimate the number of clusters
labels = meanshift_model.labels_
num_clusters = len(np.unique(labels))
print("\nNumber of clusters in input data =", num_clusters)
# Plot the points and cluster centers
plt.figure()
markers = 'o*xvs'
for i, marker in zip(range(num_clusters), markers):
# Plot points that belong to the current cluster
plt.scatter(X[labels==i, 0], X[labels==i, 1], marker=marker, color='black')
# Plot the cluster center
cluster_center = cluster_centers[i]
plt.plot(cluster_center[0], cluster_center[1], marker='o',
markerfacecolor='black', markeredgecolor='black',
markersize=15)
plt.title('Clusters')
plt.show()