import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
나이와 연봉으로 분석해서, 물건을 구매할지 안할지를 분류하자
나이와 연봉으로 데이터를 학습시키기위해 데이터를 분리하였다.
X = df.iloc[:, 2:3+1]
y = df.Purchased
데이터의 크기를 맞춰주기 위해 정규화 하였다.
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X=sc.fit_transform(X)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.2, random_state =0)
from sklearn.linear_model import LogisticRegression
classifier = LogisticRegression(random_state=0)
classifier.fit(X_train, y_train)
y_pred=classifier.predict(X_test)
분류가 두가지밖에 없으므로 confusion_matrix 를 이용하여 눈으로 오답률이 얼마나 되는지 확인할 수 있다.
from sklearn.metrics import confusion_matrix, accuracy_score
cm = confusion_matrix(y_test, y_pred)
# 정확도 (적중)/(total)
(57+17)/cm.sum()
>>> 0.925
# accuracy_score을 이용하여도 구할 수 있다.
as =accuracy_score(y_test, y_pred)
as
>>> 0.925
# Visualising the Training set results
from matplotlib.colors import ListedColormap
X_set, y_set = X_train, y_train
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
plt.figure(figsize=[10,7])
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
alpha = 0.6, cmap = ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
c = ListedColormap(('red', 'green'))(i), label = j)
plt.title('Logistic Regression (Training set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()
[머신러닝]KNN 구매여부 확인 (0) | 2021.05.19 |
---|---|
[머신러닝]KNN(K-Nearest Neighbor) (0) | 2021.05.19 |
[머신러닝]Logistic Regression (0) | 2021.05.17 |
[머신러닝] Label Encoding / One-Hot Encoding (0) | 2021.05.17 |
[머신러닝]Multiple Linear Regression (0) | 2021.05.17 |