from preamble import *
%matplotlib inline
import numpy as np
x = np.array([[1, 2, 3], [4, 5, 6]])
print("x:\n{}".format(x))
x: [[1 2 3] [4 5 6]]
from scipy import sparse
# 대각선 원소는 1이고 나머지는 0인 2차원 NumPy 배열을 만듭니다.
eye = np.eye(4)
print("NumPy 배열:\n{}".format(eye))
NumPy 배열: [[1. 0. 0. 0.] [0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.]]
# NumPy 배열을 CSR 포맷의 SciPy 희박 행렬로 변환합니다.
# 0이 아닌 원소만 저장됩니다.
sparse_matrix = sparse.csr_matrix(eye)
print("\nSciPy의 CSR 행렬:\n{}".format(sparse_matrix))
SciPy의 CSR 행렬: (0, 0) 1.0 (1, 1) 1.0 (2, 2) 1.0 (3, 3) 1.0
data = np.ones(4)
row_indices = np.arange(4)
col_indices = np.arange(4)
eye_coo = sparse.coo_matrix((data, (row_indices, col_indices)))
print("COO 표현:\n{}".format(eye_coo))
COO 표현: (0, 0) 1.0 (1, 1) 1.0 (2, 2) 1.0 (3, 3) 1.0
%matplotlib inline
import matplotlib.pyplot as plt
# -10에서 10까지 100개의 간격으로 나뉘어진 배열을 생성합니다.
x = np.linspace(-10, 10, 100)
# 사인 함수를 사용하여 y 배열을 생성합니다.
y = np.sin(x)
# plot 함수는 한 배열의 값을 다른 배열에 대응해서 선 그래프를 그립니다.
plt.plot(x, y, marker="x")
[<matplotlib.lines.Line2D at 0x7f433da2d470>]
from IPython.display import display
import pandas as pd
# 회원 정보가 들어간 간단한 데이터셋을 생성합니다.
data = {'Name': ["John", "Anna", "Peter", "Linda"],
'Location' : ["New York", "Paris", "Berlin", "London"],
'Age' : [24, 13, 53, 33]
}
data_pandas = pd.DataFrame(data)
# IPython.display는 주피터 노트북에서 Dataframe을 미려하게 출력해줍니다.
display(data_pandas)
Age | Location | Name | |
---|---|---|---|
0 | 24 | New York | John |
1 | 13 | Paris | Anna |
2 | 53 | Berlin | Peter |
3 | 33 | London | Linda |
# Age 열의 값이 30 이상인 모든 행을 선택합니다.
display(data_pandas[data_pandas.Age > 30])
Age | Location | Name | |
---|---|---|---|
2 | 53 | Berlin | Peter |
3 | 33 | London | Linda |
import sys
print("Python 버전: {}".format(sys.version))
import pandas as pd
print("pandas 버전: {}".format(pd.__version__))
import matplotlib
print("matplotlib 버전: {}".format(matplotlib.__version__))
import numpy as np
print("NumPy 버전: {}".format(np.__version__))
import scipy as sp
print("SciPy 버전: {}".format(sp.__version__))
import IPython
print("IPython 버전: {}".format(IPython.__version__))
import sklearn
print("scikit-learn 버전: {}".format(sklearn.__version__))
Python 버전: 3.5.6 |Anaconda, Inc.| (default, Aug 26 2018, 21:41:56) [GCC 7.3.0] pandas 버전: 0.23.4 matplotlib 버전: 3.0.0 NumPy 버전: 1.15.2 SciPy 버전: 1.1.0 IPython 버전: 6.5.0 scikit-learn 버전: 0.20.1
from sklearn.datasets import load_iris
iris_dataset = load_iris()
print("iris_dataset의 키: {}".format(iris_dataset.keys()))
iris_dataset의 키: dict_keys(['DESCR', 'data', 'target_names', 'target', 'filename', 'feature_names'])
print(iris_dataset['DESCR'][:193] + "\n...")
.. _iris_dataset: Iris plants dataset -------------------- **Data Set Characteristics:** :Number of Instances: 150 (50 in each of three classes) :Number of Attributes: 4 numeric, pre ...
print("타깃의 이름: {}".format(iris_dataset['target_names']))
타깃의 이름: ['setosa' 'versicolor' 'virginica']
print("특성의 이름: {}".format(iris_dataset['feature_names']))
특성의 이름: ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']
print("data의 타입: {}".format(type(iris_dataset['data'])))
data의 타입: <class 'numpy.ndarray'>
print("data의 크기: {}".format(iris_dataset['data'].shape))
data의 크기: (150, 4)
print("data의 처음 다섯 행:\n{}".format(iris_dataset['data'][:5]))
data의 처음 다섯 행: [[5.1 3.5 1.4 0.2] [4.9 3. 1.4 0.2] [4.7 3.2 1.3 0.2] [4.6 3.1 1.5 0.2] [5. 3.6 1.4 0.2]]
print("target의 타입: {}".format(type(iris_dataset['target'])))
target의 타입: <class 'numpy.ndarray'>
print("target의 크기: {}".format(iris_dataset['target'].shape))
target의 크기: (150,)
print("타깃:\n{}".format(iris_dataset['target']))
타깃: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2]
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
iris_dataset['data'], iris_dataset['target'], random_state=0)
print("X_train 크기: {}".format(X_train.shape))
print("y_train 크기: {}".format(y_train.shape))
X_train 크기: (112, 4) y_train 크기: (112,)
print("X_test 크기: {}".format(X_test.shape))
print("y_test 크기: {}".format(y_test.shape))
X_test 크기: (38, 4) y_test 크기: (38,)
# X_train 데이터를 사용해서 데이터프레임을 만듭니다.
# 열의 이름은 iris_dataset.feature_names에 있는 문자열을 사용합니다.
iris_dataframe = pd.DataFrame(X_train, columns=iris_dataset.feature_names)
# 데이터프레임을 사용해 y_train에 따라 색으로 구분된 산점도 행렬을 만듭니다.
pd.plotting.scatter_matrix(iris_dataframe, c=y_train, figsize=(15, 15), marker='o',
hist_kwds={'bins': 20}, s=60, alpha=.8, cmap=mglearn.cm3)
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x7f433d9c8320>, <matplotlib.axes._subplots.AxesSubplot object at 0x7f433d9654a8>, <matplotlib.axes._subplots.AxesSubplot object at 0x7f433d97c9b0>, <matplotlib.axes._subplots.AxesSubplot object at 0x7f433d996eb8>], [<matplotlib.axes._subplots.AxesSubplot object at 0x7f433d932400>, <matplotlib.axes._subplots.AxesSubplot object at 0x7f433d949908>, <matplotlib.axes._subplots.AxesSubplot object at 0x7f433d960e10>, <matplotlib.axes._subplots.AxesSubplot object at 0x7f433d8ff358>], [<matplotlib.axes._subplots.AxesSubplot object at 0x7f433d916860>, <matplotlib.axes._subplots.AxesSubplot object at 0x7f433d8aed68>, <matplotlib.axes._subplots.AxesSubplot object at 0x7f433d8cc2b0>, <matplotlib.axes._subplots.AxesSubplot object at 0x7f433d8657b8>], [<matplotlib.axes._subplots.AxesSubplot object at 0x7f433d87fcc0>, <matplotlib.axes._subplots.AxesSubplot object at 0x7f433d89e208>, <matplotlib.axes._subplots.AxesSubplot object at 0x7f433d835710>, <matplotlib.axes._subplots.AxesSubplot object at 0x7f433d84dbe0>]], dtype=object)
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=1)
knn.fit(X_train, y_train)
KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski', metric_params=None, n_jobs=None, n_neighbors=1, p=2, weights='uniform')
X_new = np.array([[5, 2.9, 1, 0.2]])
print("X_new.shape: {}".format(X_new.shape))
X_new.shape: (1, 4)
prediction = knn.predict(X_new)
print("예측: {}".format(prediction))
print("예측한 타깃의 이름: {}".format(
iris_dataset['target_names'][prediction]))
예측: [0] 예측한 타깃의 이름: ['setosa']
y_pred = knn.predict(X_test)
print("테스트 세트에 대한 예측값:\n {}".format(y_pred))
테스트 세트에 대한 예측값: [2 1 0 2 0 2 0 1 1 1 2 1 1 1 1 0 1 1 0 0 2 1 0 0 2 0 0 1 1 0 2 1 0 2 2 1 0 2]
print("테스트 세트의 정확도: {:.2f}".format(np.mean(y_pred == y_test)))
테스트 세트의 정확도: 0.97
print("테스트 세트의 정확도: {:.2f}".format(knn.score(X_test, y_test)))
테스트 세트의 정확도: 0.97
X_train, X_test, y_train, y_test = train_test_split(
iris_dataset['data'], iris_dataset['target'], random_state=0)
knn = KNeighborsClassifier(n_neighbors=1)
knn.fit(X_train, y_train)
print("테스트 세트의 정확도: {:.2f}".format(knn.score(X_test, y_test)))
테스트 세트의 정확도: 0.97