행복지수=돈*가중치+상수
Newziland - 7.3
Norway - 7.4
Sweden - 7.2
Swiss - 7.5
-> Rwanda를 예측해보자.
- 해결 기법
- 파라미터 수를 줄인 모델을 선택 : 고차원 다항 모델보다는 선형 모델을 선택
- 훈련 데이터의 특성 수를 줄이거나 모델에 제약(규제)를 가함
- 훈련 데이터를 많이 수집함
- 정제를 통해서 잡음을 줄임
Parameter
- 모델 내부에서 결정되는 변수
선형 회귀를 하게 된다면, 기울기와 절편이 나오게 됩니다.
기울기와 절편은 입력된 데이터에 의해서 결정됩니다.
이런 값들을 매개변수라고 합니다.
Hyper Parameter : 개발자가 결정하는 변수
- 모델을 만들 때, 입력하는 데이터
- 모델의 성능이 좋지 못하다면, 하피어 파라미터를 수정해서 모델의 성능을 좋은 쪽으로 수정
홀드 아웃 검증
- 샘플링 된 데이터에서 일부분을 선택해서 여러 모델을 평가하고, 가장 좋은 하나를 선택하는 방식
- 검증을 위한 데이터의 크기가 너무 작다면, 모델이 정확하게 평가되지를 않아서, 최적이 아닌 모델을 선택할 수 있으며, 검증을 위한 데이터가 너무 크다면 훈련 데이터의 양이 작아지게 되는 효과를 발생함
- 작은 검증 세트를 여러 개 만들어서 반복적인 교차 검증을 수행하는 것을 권장함
#머신러닝에 사용할 데이터 가져오기 import seaborn as sns iris = sns.load_dataset('iris') iris.info() # feature matrix 와 target을 분리 X_iris = iris.drop('species', axis=1) y_iris = iris['species'] print(X_iris.shape) print(y_iris.shape)
- 하나의 행을 Sample이라고 부르고, 전체를 표본(Sample)이라고 하며, 행의 개수를 n_samples라고 합니다.
- 하나의 열은 feature나 target이라고 부르며, 열의 개수를 n_features라고 합니다.
- 전체 데이터를 feature matrix(특징 행렬)이라고도 부르며, 대부분의 경우에는 numpy의 ndarray나 pandas의 DataFrame이지만 특별한 경우에는 sparse matrix로 만들기도 합니다.
target이 없는 featrue matrix는 관례상 X로 사용- target은 관례상 y로 사용하고 numpy의 일차원 배열이나 pandas의 Series로 제공
# 선형 회귀 수행 #1.데이터 수집 rng = np.random.RandomState(42) X = 10 * rng.rand(50) y = 2 * X - 1 + rng.randn(50) plt.scatter(X, y) #2.모델을 선택하고 인스턴스를 생성 from sklearn.linear_model import LinearRegression model = LinearRegression(fit_intercept = True) print(model) #3.모델 훈련 #특징 벡터는 2차원 배열이어야 합니다. #1차원 배열을 2차원 배열로 변경하고자 하면 reshape를 이용해도 되고 #열을 하나 추가해서 2차원으로 만들어도 됩니다. #여기서는 2차원으로 변경 print(X.shape) print(X[:, np.newaxis].shape) model.fit(X[:, np.newaxis], y) print(model.coef_) #기울기 - slope print(model.intercept_) #절편 - intercept #4.예측 #예측에 사용할 데이터 생성 X_fit = np.linspace(-1, 11) Xfit = X_fit[:, np.newaxis] yfit = model.predict(Xfit) #print(yfit) plt.scatter(X, y) plt.plot(Xfit, yfit)
#1.데이터 수집 from sklearn.datasets import load_digits digits = load_digits() print(digits.images.shape)
#2.데이터 확인 - 이미지 출력 #print(digits.images[0]) fig, axes = plt.subplots(10, 10, figsize=(8, 8), subplot_kw={'xticks':[], 'yticks':[]}, gridspec_kw=dict(hspace=0.1, wspace=0.1)) for i, ax in enumerate(axes.flat): ax.imshow(digits.images[i], cmap='binary', interpolation='nearest') ax.text(0.05, 0.05, str(digits.target[i]), transform=ax.transAxes, color='green')
#3.특징 배열 과 타겟을 생성 X = digits.data print(X.shape) y = digits.target print(y.shape) #훈련 데이터 와 테스트 데이터 분리 from sklearn.model_selection import train_test_split #별다른 옵션이 없으면 75:25 로 분할 Xtrain, Xtest, ytrain, ytest = train_test_split(X, y, random_state=42) print(Xtrain.shape) print(Xtest.shape) help(train_test_split)
#4.분류 모델을 선택해서 훈련 from sklearn.naive_bayes import GaussianNB model = GaussianNB() model.fit(Xtrain, ytrain) #예측 y_model = model.predict(Xtest)
#5.정확도 확인 from sklearn.metrics import accuracy_score #실제 값 과 예측한 값을 대입해서 정확도 확인 accuracy_score(ytest, y_model) #6. 오차 행렬 from sklearn.metrics import confusion_matrix mat = confusion_matrix(ytest, y_model) #print(mat) sns.heatmap(mat, square=True, annot=True, cbar=False) plt.xlabel('예측 값') plt.ylabel('실제 값')
#7. 실제 이미지에서 잘못 분류된 데이터 확인
fig, axes = plt.subplots(10, 10, figsize=(8, 8),
subplot_kw={'xticks':[], 'yticks':[]},
gridspec_kw=dict(hspace=0.1, wspace=0.1))
test_images = Xtest.reshape(-1, 8, 8)
#제대로 분류된 경우는 녹색 그렇지 않은 경우는 빨강색으로 화면에 텍스트 출력
for i, ax in enumerate(axes.flat):
ax.imshow(test_images[i], cmap='binary', interpolation='nearest')
ax.text(0.05, 0.05, str(digits.target[i]), transform=ax.transAxes,
color='green' if (ytest[i] == y_model[i]) else 'red')
from sklearn.decomposition import PCA model = PCA(n_components=2) # 2개의 주성분 model.fit(X_iris) #이 경우는 훈련 데이터 와 테스트 데이터를 분할하지 않음 X_2D = model.transform(X_iris) #주성분 결과를 원본 데이터에 반영 iris['PCA1'] = X_2D[:, 0] iris['PCA2'] = X_2D[:, 1] sns.lmplot(x="PCA1", y="PCA2", hue='species', data=iris, fit_reg=False)
from sklearn.mixture import GaussianMixture model = GaussianMixture(n_components=3, covariance_type='full') model.fit(X_iris) y_gmm = model.predict(X_iris) iris['cluster'] = y_gmm print(iris)
- 문제 정의
- 작업 환경 설정
- 데이터 수집
- 데이터 탐색
- 전처리
- 모델을 선택해서 훈련
- 모델을 상세하게 조정
- 솔루션을 제시
- 시스템을 론칭하고 모니터링하면서 유지 보수
데이터 수집
import pandas as pd #1.데이터 가져오기 housing = pd.read_csv('./data/housing.csv') print(housing.head())
데이터 탐색
housing.info() #총 데이터 개수는 20640개 #속성은 10개 #ocean_proximity 을 제외하고는 전부 실수 #total_bedrooms 은 결측치 존재 #범주형 가능성이 있는 데이터를 확인 print(housing['ocean_proximity'].value_counts()) #값이 5가지만 존재하므로 범주형일 가능성이 높음 #기술 통계량 확인 housing.describe() #데이터의 분포 확인 housing.hist(bins=50, figsize=(20, 15)) #이미지 저장 plt.savefig('histogram', format='png', dpi=300) plt.show()
- 데이터의 분포를 확인해서, 꼬리가 길고 한쪽으로 많이 쏠려있는 데이터의 경우는 패턴을 찾기 어렵기 때문에, 좀 더 종의 분포가 되도록 조정할 필요가 있음
- 각 속성의 단위가 다르다면, 좋은 모델이 만들어지기 어렵기 때문에 스케일링을 고려해야 한다.
#시드를 고정 np.random.seed(42) #데이터 와 테스트 데이터의 비율을 매개변수로 받아서 테스트 데이터를 리턴해주는 함수 def split_train_test(data, test_ratio): #랜덤한 숫자 인덱스를 생성 shuffled_indices = np.random.permutation(len(data)) #테스트 데이터의 크기 결정 test_set_size = int(len(data) * test_ratio) test_indices = shuffled_indices[:test_set_size] train_indices = shuffled_indices[test_set_size:] return data.iloc[train_indices], data.iloc[test_indices] train_set, test_set = split_train_test(housing, 0.2) print(len(train_set), len(test_set))