728x90
반응형

데이터 전처리(preprocessing) 클링징 : 수정, 결손값 처리 :nullnan 처리(제거, 평균, 추가코드부여).

인코딩(ml은 숫자만 인식해서 2진수(01), 문자를 숫자로 표현),

스케일링(정규화, 표준화 // 키, 몸무게 단위가 다른경우),

이상치 제거,

feature 적절한 선택,

추출가공

데이터 인코딩

  • 레이블 인코딩(Label encoding) : 1개 col으로 해결 상품이름을 상품코드번호로 maping하는 경우(냉장고 => 코드번호 13)
from sklearn.preprocessing import LabelEncoder

items=['TV','냉장고','전자렌지','컴퓨터','선풍기','선풍기','믹서','믹서']

# LabelEncoder를 객체로 생성한 후 , fit( ) 과 transform( ) 으로 label 인코딩 수행. 
encoder = LabelEncoder() # 객체생성
encoder.fit(items) # 형태 맞추기
labels = encoder.transform(items)
print('인코딩 변환값:',labels) # 실제 값 변환

# 인코딩 변환값: [0 1 4 5 3 3 2 2]

 

print('인코딩 클래스:',encoder.classes_)

# 인코딩 클래스: ['TV' '냉장고' '믹서' '선풍기' '전자렌지' '컴퓨터']

 

print('디코딩 원본 값:',encoder.inverse_transform([4, 5, 2, 0, 1, 1, 3, 3])) # 원본값을 보고싶을때

# 디코딩 원본 값: ['전자렌지' '컴퓨터' '믹서' 'TV' '냉장고' '냉장고' '선풍기' '선풍기']

 

  • 원-핫 인코딩(One-Hot encoding) : 차원분류 상품수만큼 col 부여 해당시 1 값 지정 특징 상품이름은 서로 연관이 없음 => 숫자라서 원치않는 방향으로 알고리즘 코딩될 수 있음 => 원핫인코딩 해결 pd get_dummies(인자) 손쉽게 가능
from sklearn.preprocessing import OneHotEncoder 
import numpy as np

items=['TV','냉장고','전자렌지','컴퓨터','선풍기','선풍기','믹서','믹서']

# 먼저 숫자값으로 변환을 위해 LabelEncoder로 변환합니다.  비지도학습인 경우 fit transform 데이터 변환
encoder = LabelEncoder() # 객체생성
encoder.fit(items) # 와꾸 맞추기
labels = encoder.transform(items) # 실제 값 변환

# 1차원 레이블 추가작업
# 2차원 데이터로 변환합니다. 
labels = labels.reshape(-1,1) # col은 하나.행은 동쪽으로

# 원-핫 인코딩을 적용합니다. 
oh_encoder = OneHotEncoder()
oh_encoder.fit(labels)
oh_labels = oh_encoder.transform(labels)

print('원-핫 인코딩 데이터')
print(oh_labels.toarray())
print('원-핫 인코딩 데이터 차원')
print(oh_labels.shape)

# 이 복잡한 과정을 get_dummies로 형식, 고유값문제까지 해결해서 더 깔끔하게 해결

원-핫 인코딩 데이터
[[1. 0. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0. 0.]
 [0. 0. 0. 0. 1. 0.]
 [0. 0. 0. 0. 0. 1.]
 [0. 0. 0. 1. 0. 0.]
 [0. 0. 0. 1. 0. 0.]
 [0. 0. 1. 0. 0. 0.]
 [0. 0. 1. 0. 0. 0.]]
원-핫 인코딩 데이터 차원
(8, 6)

 

import pandas as pd

df = pd.DataFrame({'item':['TV','냉장고','전자렌지','컴퓨터','선풍기','선풍기','믹서','믹서'] })
df

item
0	TV
1	냉장고
2	전자렌지
3	컴퓨터
4	선풍기
5	선풍기
6	믹서
7	믹서

 

pd.get_dummies(df)

	item_TV	item_냉장고	item_믹서	item_선풍기	item_전자렌지	item_컴퓨터
0	1	0	0	0	0	0
1	0	1	0	0	0	0
2	0	0	0	0	1	0
3	0	0	0	0	0	1
4	0	0	0	1	0	0
5	0	0	0	1	0	0
6	0	0	1	0	0	0
7	0	0	1	0	0	0

 

피처 스케일링과 정규화

표준화 : feature 각각을 평균 0이고 분산 1인 가우시안 정규분포를 가진 값으로 변환 정규화 : 서로다른 피처의 크기를 통일 크기변환

 

  • StandardScaler : 평균 0, 분산 1인 정규분포형태 변환
from sklearn.datasets import load_iris
import pandas as pd
# 붓꽃 데이터 셋을 로딩하고 DataFrame으로 변환합니다. 
iris = load_iris()
iris_data = iris.data
iris_df = pd.DataFrame(data=iris_data, columns=iris.feature_nam es)

print('feature 들의 평균 값')
print(iris_df.mean())
print('\nfeature 들의 분산 값')
print(iris_df.var())

feature 들의 평균 값
sepal length (cm)    5.843333
sepal width (cm)     3.054000
petal length (cm)    3.758667
petal width (cm)     1.198667
dtype: float64

feature 들의 분산 값
sepal length (cm)    0.685694
sepal width (cm)     0.188004
petal length (cm)    3.113179
petal width (cm)     0.582414
dtype: float64

 

from sklearn.preprocessing import StandardScaler

# StandardScaler객체 생성
scaler = StandardScaler()
# StandardScaler 로 데이터 셋 변환. fit( ) 과 transform( ) 호출.  
scaler.fit(iris_df)
iris_scaled = scaler.transform(iris_df)

#transform( )시 scale 변환된 데이터 셋이 numpy ndarry로 반환되어 이를 DataFrame으로 변환
iris_df_scaled = pd.DataFrame(data=iris_scaled, columns=iris.feature_names)
print('feature 들의 평균 값')
print(iris_df_scaled.mean())
print('\nfeature 들의 분산 값')
print(iris_df_scaled.var())

feature 들의 평균 값
sepal length (cm)   -1.690315e-15
sepal width (cm)    -1.637024e-15
petal length (cm)   -1.482518e-15
petal width (cm)    -1.623146e-15
dtype: float64

feature 들의 분산 값
sepal length (cm)    1.006711
sepal width (cm)     1.006711
petal length (cm)    1.006711
petal width (cm)     1.006711
dtype: float64

 

  • MinMaxScaler : 데이터값을 0 ~ 1 사이의 범위값으로 변환(음수 값있으면 -1 ~ 1 변환)
from sklearn.preprocessing import MinMaxScaler

# MinMaxScaler객체 생성
scaler = MinMaxScaler()
# MinMaxScaler 로 데이터 셋 변환. fit() 과 transform() 호출.  
scaler.fit(iris_df)
iris_scaled = scaler.transform(iris_df)

# transform()시 scale 변환된 데이터 셋이 numpy ndarry로 반환되어 이를 DataFrame으로 변환
iris_df_scaled = pd.DataFrame(data=iris_scaled, columns=iris.feature_names)
print('feature들의 최소 값')
print(iris_df_scaled.min())
print('\nfeature들의 최대 값')
print(iris_df_scaled.max())

feature들의 최소 값
sepal length (cm)    0.0
sepal width (cm)     0.0
petal length (cm)    0.0
petal width (cm)     0.0
dtype: float64

feature들의 최대 값
sepal length (cm)    1.0
sepal width (cm)     1.0
petal length (cm)    1.0
petal width (cm)     1.0
dtype: float64

 

반응형

'Data_Science > ML_Perfect_Guide' 카테고리의 다른 글

3-1. Accuracy || 평가지표  (0) 2021.12.22
2-5. titanic || sklearn  (0) 2021.12.22
2-3. model selection || sklearn  (0) 2021.12.22
2-2. sklearn 내장 데이터 || iris  (0) 2021.12.22
2-1. iris || sklearn  (0) 2021.12.22
728x90
반응형

Model Selection 소개

학습/테스트 데이터 셋 분리 – train_test_split()

from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score

iris = load_iris()
dt_clf = DecisionTreeClassifier()
train_data = iris.data
train_label = iris.target
# 학습 fit
dt_clf.fit(train_data, train_label)

# 학습 데이터 셋으로 예측 수행
pred = dt_clf.predict(train_data)
print('예측 정확도:',accuracy_score(train_label,pred))

# 예측 정확도 1.0 : 100% => 잘못된 결과 => train_data 학습 후 예측도 동일 데이터
# 좋은 모델, 좋은 실력은 학습, 테스트 내용이 달라도 결과가 거의 동일해야 함

# 예측 정확도: 1.0

 

from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

dt_clf = DecisionTreeClassifier( )
iris_data = load_iris()
# x feature, y label
# 학습, 테스트 분리 함수 train_test_split(featureset, target, 학7:테3, 시드번호)
X_train, X_test,y_train, y_test= train_test_split(iris_data.data, iris_data.target, 
                                                    test_size=0.3, random_state=121)

 

dt_clf.fit(X_train, y_train)
pred = dt_clf.predict(X_test)
print('예측 정확도: {0:.4f}'.format(accuracy_score(y_test,pred)))

# 예측 정확도: 0.9556

 

넘파이 ndarray 뿐만 아니라 판다스 DataFrame/Series도 train_test_split( )으로 분할 가능

import pandas as pd
# 내장 데이터를 데이터프레임 형태로 바꿔서 판다스로 하고 싶다면
iris_df = pd.DataFrame(iris_data.data, columns=iris_data.feature_names)
iris_df['target']=iris_data.target
iris_df.head()

	sepal length (cm)	sepal width (cm)	petal length (cm)	petal width (cm)	target
0	5.1	3.5	1.4	0.2	0
1	4.9	3.0	1.4	0.2	0
2	4.7	3.2	1.3	0.2	0
3	4.6	3.1	1.5	0.2	0
4	5.0	3.6	1.4	0.2	0

 

ftr_df = iris_df.iloc[:, :-1] # [행 - 전부, 열 = 처음부터 -1까지] 그래서 tgt = 0
tgt_df = iris_df.iloc[:, -1] # -1만 - series가 됨
X_train, X_test, y_train, y_test = train_test_split(ftr_df, tgt_df, 
                                                    test_size=0.3, random_state=121)

 

print(type(X_train), type(X_test), type(y_train), type(y_test))

# <class 'pandas.core.frame.DataFrame'> <class 'pandas.core.frame.DataFrame'> <class 'pandas.core.series.Series'> <class 'pandas.core.series.Series'>

 

dt_clf = DecisionTreeClassifier( )
dt_clf.fit(X_train, y_train)
pred = dt_clf.predict(X_test)
print('예측 정확도: {0:.4f}'.format(accuracy_score(y_test,pred)))

# 예측 정확도: 0.9556

 

교차 검증 : ML은 데이터의존

여러번하는 건데 학습데이터를 분할학습

  • K 폴드 => 5개 폴드세트(학4/5, 검1/5)를 5번해서 전부 검증후 평균 // 평균(평가[1, 2, 3, 4, 5])
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import KFold # 불러오기
import numpy as np

iris = load_iris()
features = iris.data
label = iris.target
dt_clf = DecisionTreeClassifier(random_state=156)

# 5개의 폴드 세트로 분리하는 KFold 객체와 폴드 세트별 정확도를 담을 리스트 객체 생성.
kfold = KFold(n_splits=5) # 5등분
cv_accuracy = [] # 예측성능을 담겠다.
print('붓꽃 데이터 세트 크기:',features.shape[0])

# 붓꽃 데이터 세트 크기: 150

 

n_iter = 0

# KFold객체의 split( ) 호출하면 폴드 별 학습용, 검증용 테스트의 로우 인덱스를 array로 반환  
for train_index, test_index  in kfold.split(features): # generator
    # kfold.split( )으로 반환된 인덱스를 이용하여 학습용, 검증용 테스트 데이터 추출
    X_train, X_test = features[train_index], features[test_index]
    y_train, y_test = label[train_index], label[test_index]
    
    #학습 및 예측 
    dt_clf.fit(X_train , y_train)    
    pred = dt_clf.predict(X_test)
    n_iter += 1
    
    # 반복 시 마다 정확도 측정 
    accuracy = np.round(accuracy_score(y_test,pred), 4)
    train_size = X_train.shape[0]
    test_size = X_test.shape[0]
    print('\n#{0} 교차 검증 정확도 :{1}, 학습 데이터 크기: {2}, 검증 데이터 크기: {3}'
          .format(n_iter, accuracy, train_size, test_size))
    print('#{0} 검증 세트 인덱스:{1}'.format(n_iter,test_index))
    
    cv_accuracy.append(accuracy) #  평균
    
# 개별 iteration별 정확도를 합하여 평균 정확도 계산 
print('\n## 평균 검증 정확도:', np.mean(cv_accuracy)) 
#검증세트 인덱스 : 위치인덱스

#1 교차 검증 정확도 :1.0, 학습 데이터 크기: 120, 검증 데이터 크기: 30
#1 검증 세트 인덱스:[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 24 25 26 27 28 29]

#2 교차 검증 정확도 :0.9667, 학습 데이터 크기: 120, 검증 데이터 크기: 30
#2 검증 세트 인덱스:[30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
 54 55 56 57 58 59]

#3 교차 검증 정확도 :0.8667, 학습 데이터 크기: 120, 검증 데이터 크기: 30
#3 검증 세트 인덱스:[60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
 84 85 86 87 88 89]

#4 교차 검증 정확도 :0.9333, 학습 데이터 크기: 120, 검증 데이터 크기: 30
#4 검증 세트 인덱스:[ 90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107
 108 109 110 111 112 113 114 115 116 117 118 119]

#5 교차 검증 정확도 :0.7333, 학습 데이터 크기: 120, 검증 데이터 크기: 30
#5 검증 세트 인덱스:[120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
 138 139 140 141 142 143 144 145 146 147 148 149]

## 평균 검증 정확도: 0.9

 

  • Stratified K 폴드 : 불균형(imbalanced) 분포 레이블(결정클래스)데이터 집합용 => 신용카드 사기건수 10000건 중 100 1%이면 학습하기가 어려움 이런경우 검증 시 비율을 일부러 균일하게 넣어줘야 함 99:1
import pandas as pd

iris = load_iris()

iris_df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
iris_df['label']=iris.target
iris_df['label'].value_counts()

# 2    50
# 1    50
# 0    50
# Name: label, dtype: int64

 

kfold = KFold(n_splits=3)
# kfold.split(X)는 폴드 세트를 3번 반복할 때마다 달라지는 학습/테스트 용 데이터 로우 인덱스 번호 반환. 
n_iter =0
for train_index, test_index  in kfold.split(iris_df):
    n_iter += 1
    label_train= iris_df['label'].iloc[train_index]
    label_test= iris_df['label'].iloc[test_index]
    print('## 교차 검증: {0}'.format(n_iter))
    print('학습 레이블 데이터 분포:\n', label_train.value_counts())
    print('검증 레이블 데이터 분포:\n', label_test.value_counts())
    

## 교차 검증: 1
# 학습 레이블 데이터 분포:
#  2    50
# 1    50
# Name: label, dtype: int64
# 검증 레이블 데이터 분포:
#  0    50
# Name: label, dtype: int64
# ## 교차 검증: 2
# 학습 레이블 데이터 분포:
#  2    50
# 0    50
# Name: label, dtype: int64
# 검증 레이블 데이터 분포:
#  1    50
# Name: label, dtype: int64
## 교차 검증: 3
# 학습 레이블 데이터 분포:
#  1    50
# 0    50
# Name: label, dtype: int64
# 검증 레이블 데이터 분포:
#  2    50
# Name: label, dtype: int64

 

from sklearn.model_selection import StratifiedKFold

skf = StratifiedKFold(n_splits=3) # 쪼게주는 함수
n_iter=0
# 유의점 : split할때 y값이 들어가야함 label값
for train_index, test_index in skf.split(iris_df, iris_df['label']):
    n_iter += 1
    label_train= iris_df['label'].iloc[train_index]
    label_test= iris_df['label'].iloc[test_index]
    print('## 교차 검증: {0}'.format(n_iter))
    print('학습 레이블 데이터 분포:\n', label_train.value_counts())
    print('검증 레이블 데이터 분포:\n', label_test.value_counts())
    
## 교차 검증: 1
학습 레이블 데이터 분포:
 2    34
1    33
0    33
Name: label, dtype: int64
검증 레이블 데이터 분포:
 1    17
0    17
2    16
Name: label, dtype: int64
## 교차 검증: 2
학습 레이블 데이터 분포:
 1    34
2    33
0    33
Name: label, dtype: int64
검증 레이블 데이터 분포:
 2    17
0    17
1    16
Name: label, dtype: int64
## 교차 검증: 3
학습 레이블 데이터 분포:
 0    34
2    33
1    33
Name: label, dtype: int64
검증 레이블 데이터 분포:
 2    17
1    17
0    16
Name: label, dtype: int64

 

dt_clf = DecisionTreeClassifier(random_state=156)

skfold = StratifiedKFold(n_splits=3)
n_iter=0
cv_accuracy=[]

# StratifiedKFold의 split( ) 호출시 반드시 레이블 데이터 셋도 추가 입력 필요  
for train_index, test_index  in skfold.split(features, label):
    # split( )으로 반환된 인덱스를 이용하여 학습용, 검증용 테스트 데이터 추출
    X_train, X_test = features[train_index], features[test_index]
    y_train, y_test = label[train_index], label[test_index]
    
    #학습 및 예측 
    dt_clf.fit(X_train , y_train)    
    pred = dt_clf.predict(X_test)

    # 반복 시 마다 정확도 측정 
    n_iter += 1
    accuracy = np.round(accuracy_score(y_test,pred), 4)
    train_size = X_train.shape[0]
    test_size = X_test.shape[0]
    
    print('\n#{0} 교차 검증 정확도 :{1}, 학습 데이터 크기: {2}, 검증 데이터 크기: {3}'
          .format(n_iter, accuracy, train_size, test_size))
    print('#{0} 검증 세트 인덱스:{1}'.format(n_iter,test_index))
    cv_accuracy.append(accuracy)
    
# 교차 검증별 정확도 및 평균 정확도 계산 
print('\n## 교차 검증별 정확도:', np.round(cv_accuracy, 4))
print('## 평균 검증 정확도:', np.mean(cv_accuracy)) 

#1 교차 검증 정확도 :0.98, 학습 데이터 크기: 100, 검증 데이터 크기: 50
#1 검증 세트 인덱스:[  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  50
  51  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66 100 101
 102 103 104 105 106 107 108 109 110 111 112 113 114 115]

#2 교차 검증 정확도 :0.94, 학습 데이터 크기: 100, 검증 데이터 크기: 50
#2 검증 세트 인덱스:[ 17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  67
  68  69  70  71  72  73  74  75  76  77  78  79  80  81  82 116 117 118
 119 120 121 122 123 124 125 126 127 128 129 130 131 132]

#3 교차 검증 정확도 :0.98, 학습 데이터 크기: 100, 검증 데이터 크기: 50
#3 검증 세트 인덱스:[ 34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  83  84
  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 133 134 135
 136 137 138 139 140 141 142 143 144 145 146 147 148 149]

## 교차 검증별 정확도: [0.98 0.94 0.98]
## 평균 검증 정확도: 0.9666666666666667

 

  • cross_val_score( ) 함수통해서 (폴드세트추출, 학습/예측, 평균예측성능 평가)과정을 한방에
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import cross_val_score , cross_validate
from sklearn.datasets import load_iris
import numpy as np

iris_data = load_iris()
dt_clf = DecisionTreeClassifier(random_state=156)

data = iris_data.data
label = iris_data.target

# 성능 지표는 정확도(accuracy) , 교차 검증 세트는 3개 // 평가(scoring)
scores = cross_val_score(dt_clf , data , label , scoring='accuracy',cv=3)
print('교차 검증별 정확도:',np.round(scores, 4))
print('평균 검증 정확도:', np.round(np.mean(scores), 4))

# 교차 검증별 정확도: [0.98 0.94 0.98]
# 평균 검증 정확도: 0.9667

 

  • GridSearchCV grid 격자 hyper parameter(튜닝을 위한)와 cross val 수행
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.metrics import accuracy_score

# 데이터를 로딩하고 학습데이타와 테스트 데이터 분리
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris_data.data, iris_data.target, 
                                                    test_size=0.2, random_state=121)
dtree = DecisionTreeClassifier()

# FOR문을 거칠수록 복잡도, 가시성이 떨어짐 => DICT형식으로
### parameter 들을 dictionary 형태로 설정 // DT알고리즘을 튜닝하고 싶은 부분
parameters = {'max_depth':[1, 2, 3], 'min_samples_split':[2,3]}
# KEY => Hyper Parameter 이름, 반드시 리스트[](단일값도)

 

import pandas as pd

# param_grid의 하이퍼 파라미터들을 3개의 train, test set fold 로 나누어서 테스트 수행 설정.  
### refit=True 가 default 임. True이면 가장 좋은 파라미터 설정으로 재 학습 시킴.  
grid_dtree = GridSearchCV(dtree, param_grid=parameters, cv=3, refit=True, return_train_score=True)

# refit : grid cv가 학습검정하면서 최적hp값 찾으면 최종으로 hp값을 fit호출해서 dt를 학습시켜버림

# 붓꽃 Train 데이터로 param_grid의 하이퍼 파라미터들을 순차적으로 학습/평가 .
grid_dtree.fit(X_train, y_train)

# GridSearchCV 결과는 cv_results_ 라는 딕셔너리로 저장됨. 이를 가시성 떨어져서 DataFrame으로 변환
scores_df = pd.DataFrame(grid_dtree.cv_results_)
# 주요속성들은 빼옴
scores_df[['params', 'mean_test_score', 'rank_test_score', 
           'split0_test_score', 'split1_test_score', 'split2_test_score']]

# params 기준으로 정렬됨

params	mean_test_score	rank_test_score	split0_test_score	split1_test_score	split2_test_score
0	{'max_depth': 1, 'min_samples_split': 2}	0.700000	5	0.700	0.7	0.70
1	{'max_depth': 1, 'min_samples_split': 3}	0.700000	5	0.700	0.7	0.70
2	{'max_depth': 2, 'min_samples_split': 2}	0.958333	3	0.925	1.0	0.95
3	{'max_depth': 2, 'min_samples_split': 3}	0.958333	3	0.925	1.0	0.95
4	{'max_depth': 3, 'min_samples_split': 2}	0.975000	1	0.975	1.0	0.95
5	{'max_depth': 3, 'min_samples_split': 3}	0.975000	1	0.975	1.0	0.95

 

grid_dtree.cv_results_

{'mean_fit_time': array([0.00033267, 0.00066535, 0.00033037, 0.00066455, 0.00033951,
        0.00066066]),
 'std_fit_time': array([0.00047047, 0.00047047, 0.00046721, 0.00046991, 0.00048014,
        0.00046718]),
 'mean_score_time': array([0.00066471, 0.00033466, 0.00033212, 0.0003322 , 0.00033251,
        0.00066821]),
 'std_score_time': array([0.00047002, 0.00047328, 0.00046968, 0.0004698 , 0.00047025,
        0.00047251]),
 'param_max_depth': masked_array(data=[1, 1, 2, 2, 3, 3],
              mask=[False, False, False, False, False, False],
        fill_value='?',
             dtype=object),
 'param_min_samples_split': masked_array(data=[2, 3, 2, 3, 2, 3],
              mask=[False, False, False, False, False, False],
        fill_value='?',
             dtype=object),
 'params': [{'max_depth': 1, 'min_samples_split': 2},
  {'max_depth': 1, 'min_samples_split': 3},
  {'max_depth': 2, 'min_samples_split': 2},
  {'max_depth': 2, 'min_samples_split': 3},
  {'max_depth': 3, 'min_samples_split': 2},
  {'max_depth': 3, 'min_samples_split': 3}],
 'split0_test_score': array([0.7  , 0.7  , 0.925, 0.925, 0.975, 0.975]),
 'split1_test_score': array([0.7, 0.7, 1. , 1. , 1. , 1. ]),
 'split2_test_score': array([0.7 , 0.7 , 0.95, 0.95, 0.95, 0.95]),
 'mean_test_score': array([0.7       , 0.7       , 0.95833333, 0.95833333, 0.975     ,
        0.975     ]),
 'std_test_score': array([1.11022302e-16, 1.11022302e-16, 3.11804782e-02, 3.11804782e-02,
        2.04124145e-02, 2.04124145e-02]),
 'rank_test_score': array([5, 5, 3, 3, 1, 1]),
 'split0_train_score': array([0.7   , 0.7   , 0.975 , 0.975 , 0.9875, 0.9875]),
 'split1_train_score': array([0.7   , 0.7   , 0.9375, 0.9375, 0.9625, 0.9625]),
 'split2_train_score': array([0.7   , 0.7   , 0.9625, 0.9625, 0.9875, 0.9875]),
 'mean_train_score': array([0.7       , 0.7       , 0.95833333, 0.95833333, 0.97916667,
        0.97916667]),
 'std_train_score': array([1.11022302e-16, 1.11022302e-16, 1.55902391e-02, 1.55902391e-02,
        1.17851130e-02, 1.17851130e-02])}

 

print('GridSearchCV 최적 파라미터:', grid_dtree.best_params_) 
print('GridSearchCV 최고 정확도: {0:.4f}'.format(grid_dtree.best_score_))

# refit=True로 설정된 GridSearchCV 객체가 fit()을 수행 시 학습이 완료된 Estimator를 내포하고 있으므로 predict()를 통해 예측도 가능. 
pred = grid_dtree.predict(X_test)
print('테스트 데이터 세트 정확도: {0:.4f}'.format(accuracy_score(y_test,pred)))

# GridSearchCV 최적 파라미터: {'max_depth': 3, 'min_samples_split': 2}
# GridSearchCV 최고 정확도: 0.9750
# 테스트 데이터 세트 정확도: 0.9667

 

# GridSearchCV의 refit으로 이미 학습이 된 estimator 반환
estimator = grid_dtree.best_estimator_ # 

# GridSearchCV의 best_estimator_는 이미 최적 하이퍼 파라미터로 학습이 됨
pred = estimator.predict(X_test)
print('테스트 데이터 세트 정확도: {0:.4f}'.format(accuracy_score(y_test,pred)))

# 테스트 데이터 세트 정확도: 0.9667

 

반응형

'Data_Science > ML_Perfect_Guide' 카테고리의 다른 글

2-5. titanic || sklearn  (0) 2021.12.22
2-4. Data Preprocessing  (0) 2021.12.22
2-2. sklearn 내장 데이터 || iris  (0) 2021.12.22
2-1. iris || sklearn  (0) 2021.12.22
1-3. Pandas 2  (0) 2021.12.22
728x90
반응형

사이킷런 내장 예제 데이터

from sklearn.datasets import load_iris

iris_data = load_iris()
print(type(iris_data))

# <class 'sklearn.utils.Bunch'>

 

keys = iris_data.keys()
print('붓꽃 데이터 세트의 키들:', keys)

# 붓꽃 데이터 세트의 키들: dict_keys(['data', 'target', 'frame', 'target_names', 'DESCR', 'feature_names', 'filename'])

 

키는 보통 data, target, target_name, feature_names, DESCR로 구성돼 있습니다. 개별 키가 가리키는 의미는 다음과 같습니다.

  • data는 피처의 데이터 세트를 가리킵니다.
  • target은 분류 시 레이블 값, 회귀일 때는 숫자 결괏값 데이터 세트입니다..
  • target_names는 개별 레이블의 이름을 나타냅니다.
  • feature_names는 피처의 이름을 나타냅니다.
  • DESCR은 데이터 세트에 대한 설명과 각 피처의 설명을 나타냅니다.
print('\n feature_names 의 type:',type(iris_data.feature_names))
print(' feature_names 의 shape:',len(iris_data.feature_names))
print(iris_data.feature_names)

print('\n target_names 의 type:',type(iris_data.target_names))
print(' feature_names 의 shape:',len(iris_data.target_names))
print(iris_data.target_names)

print('\n data 의 type:',type(iris_data.data))
print(' data 의 shape:',iris_data.data.shape)
print(iris_data['data'])

print('\n target 의 type:',type(iris_data.target))
print(' target 의 shape:',iris_data.target.shape)
print(iris_data.target)

 feature_names 의 type: <class 'list'>
 feature_names 의 shape: 4
['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']

 target_names 의 type: <class 'numpy.ndarray'>
 feature_names 의 shape: 3
['setosa' 'versicolor' 'virginica']

 data 의 type: <class 'numpy.ndarray'>
 data 의 shape: (150, 4)
[[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]
 [5.4 3.9 1.7 0.4]
 [4.6 3.4 1.4 0.3]
 [5.  3.4 1.5 0.2]
 [4.4 2.9 1.4 0.2]
 [4.9 3.1 1.5 0.1]
 [5.4 3.7 1.5 0.2]
 [4.8 3.4 1.6 0.2]
 [4.8 3.  1.4 0.1]
 [4.3 3.  1.1 0.1]
 [5.8 4.  1.2 0.2]
 [5.7 4.4 1.5 0.4]
 [5.4 3.9 1.3 0.4]
 [5.1 3.5 1.4 0.3]
 [5.7 3.8 1.7 0.3]
 [5.1 3.8 1.5 0.3]
 [5.4 3.4 1.7 0.2]
 [5.1 3.7 1.5 0.4]
 [4.6 3.6 1.  0.2]
 [5.1 3.3 1.7 0.5]
 [4.8 3.4 1.9 0.2]
 [5.  3.  1.6 0.2]
 [5.  3.4 1.6 0.4]
 [5.2 3.5 1.5 0.2]
 [5.2 3.4 1.4 0.2]
 [4.7 3.2 1.6 0.2]
 [4.8 3.1 1.6 0.2]
 [5.4 3.4 1.5 0.4]
 [5.2 4.1 1.5 0.1]
 [5.5 4.2 1.4 0.2]
 [4.9 3.1 1.5 0.2]
 [5.  3.2 1.2 0.2]
 [5.5 3.5 1.3 0.2]
 [4.9 3.6 1.4 0.1]
 [4.4 3.  1.3 0.2]
 [5.1 3.4 1.5 0.2]
 [5.  3.5 1.3 0.3]
 [4.5 2.3 1.3 0.3]
 [4.4 3.2 1.3 0.2]
 [5.  3.5 1.6 0.6]
 [5.1 3.8 1.9 0.4]
 [4.8 3.  1.4 0.3]
 [5.1 3.8 1.6 0.2]
 [4.6 3.2 1.4 0.2]
 [5.3 3.7 1.5 0.2]
 [5.  3.3 1.4 0.2]
 [7.  3.2 4.7 1.4]
 [6.4 3.2 4.5 1.5]
 [6.9 3.1 4.9 1.5]
 [5.5 2.3 4.  1.3]
 [6.5 2.8 4.6 1.5]
 [5.7 2.8 4.5 1.3]
 [6.3 3.3 4.7 1.6]
 [4.9 2.4 3.3 1. ]
 [6.6 2.9 4.6 1.3]
 [5.2 2.7 3.9 1.4]
 [5.  2.  3.5 1. ]
 [5.9 3.  4.2 1.5]
 [6.  2.2 4.  1. ]
 [6.1 2.9 4.7 1.4]
 [5.6 2.9 3.6 1.3]
 [6.7 3.1 4.4 1.4]
 [5.6 3.  4.5 1.5]
 [5.8 2.7 4.1 1. ]
 [6.2 2.2 4.5 1.5]
 [5.6 2.5 3.9 1.1]
 [5.9 3.2 4.8 1.8]
 [6.1 2.8 4.  1.3]
 [6.3 2.5 4.9 1.5]
 [6.1 2.8 4.7 1.2]
 [6.4 2.9 4.3 1.3]
 [6.6 3.  4.4 1.4]
 [6.8 2.8 4.8 1.4]
 [6.7 3.  5.  1.7]
 [6.  2.9 4.5 1.5]
 [5.7 2.6 3.5 1. ]
 [5.5 2.4 3.8 1.1]
 [5.5 2.4 3.7 1. ]
 [5.8 2.7 3.9 1.2]
 [6.  2.7 5.1 1.6]
 [5.4 3.  4.5 1.5]
 [6.  3.4 4.5 1.6]
 [6.7 3.1 4.7 1.5]
 [6.3 2.3 4.4 1.3]
 [5.6 3.  4.1 1.3]
 [5.5 2.5 4.  1.3]
 [5.5 2.6 4.4 1.2]
 [6.1 3.  4.6 1.4]
 [5.8 2.6 4.  1.2]
 [5.  2.3 3.3 1. ]
 [5.6 2.7 4.2 1.3]
 [5.7 3.  4.2 1.2]
 [5.7 2.9 4.2 1.3]
 [6.2 2.9 4.3 1.3]
 [5.1 2.5 3.  1.1]
 [5.7 2.8 4.1 1.3]
 [6.3 3.3 6.  2.5]
 [5.8 2.7 5.1 1.9]
 [7.1 3.  5.9 2.1]
 [6.3 2.9 5.6 1.8]
 [6.5 3.  5.8 2.2]
 [7.6 3.  6.6 2.1]
 [4.9 2.5 4.5 1.7]
 [7.3 2.9 6.3 1.8]
 [6.7 2.5 5.8 1.8]
 [7.2 3.6 6.1 2.5]
 [6.5 3.2 5.1 2. ]
 [6.4 2.7 5.3 1.9]
 [6.8 3.  5.5 2.1]
 [5.7 2.5 5.  2. ]
 [5.8 2.8 5.1 2.4]
 [6.4 3.2 5.3 2.3]
 [6.5 3.  5.5 1.8]
 [7.7 3.8 6.7 2.2]
 [7.7 2.6 6.9 2.3]
 [6.  2.2 5.  1.5]
 [6.9 3.2 5.7 2.3]
 [5.6 2.8 4.9 2. ]
 [7.7 2.8 6.7 2. ]
 [6.3 2.7 4.9 1.8]
 [6.7 3.3 5.7 2.1]
 [7.2 3.2 6.  1.8]
 [6.2 2.8 4.8 1.8]
 [6.1 3.  4.9 1.8]
 [6.4 2.8 5.6 2.1]
 [7.2 3.  5.8 1.6]
 [7.4 2.8 6.1 1.9]
 [7.9 3.8 6.4 2. ]
 [6.4 2.8 5.6 2.2]
 [6.3 2.8 5.1 1.5]
 [6.1 2.6 5.6 1.4]
 [7.7 3.  6.1 2.3]
 [6.3 3.4 5.6 2.4]
 [6.4 3.1 5.5 1.8]
 [6.  3.  4.8 1.8]
 [6.9 3.1 5.4 2.1]
 [6.7 3.1 5.6 2.4]
 [6.9 3.1 5.1 2.3]
 [5.8 2.7 5.1 1.9]
 [6.8 3.2 5.9 2.3]
 [6.7 3.3 5.7 2.5]
 [6.7 3.  5.2 2.3]
 [6.3 2.5 5.  1.9]
 [6.5 3.  5.2 2. ]
 [6.2 3.4 5.4 2.3]
 [5.9 3.  5.1 1.8]]

 target 의 type: <class 'numpy.ndarray'>
 target 의 shape: (150,)
[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]

 

반응형

'Data_Science > ML_Perfect_Guide' 카테고리의 다른 글

2-4. Data Preprocessing  (0) 2021.12.22
2-3. model selection || sklearn  (0) 2021.12.22
2-1. iris || sklearn  (0) 2021.12.22
1-3. Pandas 2  (0) 2021.12.22
1-2. Pandas  (0) 2021.12.22
728x90
반응형

사이킷런을 이용하여 붓꽃(Iris) 데이터 품종 예측하기

피처feature는 데이터 세트의 일반 속성(attribute) 머신러닝은 2차원이상의 다차원 데이터에서도 많이 사용되므로 넓은, 범용의 타겟값을 제외한 나머지 속성을 모두 피처로 지칭

target(value), decision(value) - 지도학습시 학습위한 정답데이터 label, class은 지도학습 중 분류의 경우 결정 값을 레이블 또는 클래스로 지칭

분류(classfication)는 다양한 피처와 결정값, 레이블을 모델로 학습한뒤, 별도의 테스트 데이터 세트에서 미지의 레이블 예측 // 학습데이터 세트 & 테스트 데이터세트(성능평가용)

1) 데이터 세트분리 - 학습, 테스트 데이터 분리

2) 모델학습 - 학습 데이터 기반 학습

3) 예측수행 - 학습된 모델을 이용해 테스트 데이터의 분류(붓꽃 종류) 예측 4) 평가 - 예측된 결과값, 테스트 데이터의 실제 결과값 비교해 평가

# 사이킷런 버전 확인
import sklearn
print(sklearn.__version__)

# 0.23.2

 

** 붓꽃 예측을 위한 사이킷런 필요 모듈 로딩 **

from sklearn.datasets import load_iris # 내장 데이터 셋 불러오기
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split # 테스트데이터 분리 함수

 

데이터 세트를 로딩

import pandas as pd

# 붓꽃 데이터 세트를 로딩합니다. 
iris = load_iris()

# iris.data는 Iris 데이터 세트에서 피처(feature)만으로 된 데이터를 numpy로 가지고 있습니다. 
iris_data = iris.data

# iris.target은 붓꽃 데이터 세트에서 레이블(결정 값) 데이터를 numpy로 가지고 있습니다. 
iris_label = iris.target
print('iris target값:', iris_label)
print('iris target명:', iris.target_names)

# 붓꽃 데이터 세트를 자세히 보기 위해 DataFrame으로 변환합니다. 
iris_df = pd.DataFrame(data=iris_data, columns=iris.feature_names)
iris_df['label'] = iris.target
iris_df.head(3)

iris 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]
iris target명: ['setosa' 'versicolor' 'virginica']
sepal length (cm)	sepal width (cm)	petal length (cm)	petal width (cm)	label
0	5.1	3.5	1.4	0.2	0
1	4.9	3.0	1.4	0.2	0
2	4.7	3.2	1.3	0.2	0

 

** 학습 데이터와 테스트 데이터 세트로 분리 **

X_train, X_test, y_train, y_test = train_test_split(iris_data, iris_label,  # X 피처, Y 타겟 test, train분리
                                                    test_size=0.2, random_state=11)

 

** 학습 데이터 세트로 학습(Train) 수행 **

# DecisionTreeClassifier 객체 생성 
dt_clf = DecisionTreeClassifier(random_state=11)

# 학습 수행 
dt_clf.fit(X_train, y_train)
# DecisionTreeClassifier(random_state=11)

 

** 테스트 데이터 세트로 예측(Predict) 수행 ** 별도의 데이터로 수행

# 학습이 완료된 DecisionTreeClassifier 객체에서 테스트 데이터 세트로 예측 수행. 
pred = dt_clf.predict(X_test)

 

pred

# array([2, 2, 1, 1, 2, 0, 1, 0, 0, 1, 1, 1, 1, 2, 2, 0, 2, 1, 2, 2, 1, 0,
       0, 1, 0, 0, 2, 1, 0, 1])

 

** 예측 정확도 평가 **

from sklearn.metrics import accuracy_score
print('예측 정확도: {0:.4f}'.format(accuracy_score(y_test,pred)))

# 예측 정확도: 0.9333

 

반응형

'Data_Science > ML_Perfect_Guide' 카테고리의 다른 글

2-3. model selection || sklearn  (0) 2021.12.22
2-2. sklearn 내장 데이터 || iris  (0) 2021.12.22
1-3. Pandas 2  (0) 2021.12.22
1-2. Pandas  (0) 2021.12.22
1-1. Numpy  (0) 2021.12.22
728x90
반응형

Aggregation 함수 및 GroupBy 적용

** Aggregation 함수 sum, max, min, count 집합연산**

import pandas as pd
titanic_df = pd.read_csv('titanic_train.csv')

 

## NaN 값은 count에서 제외
titanic_df.count()

PassengerId    891
Survived       891
Pclass         891
Name           891
Sex            891
Age            714
SibSp          891
Parch          891
Ticket         891
Fare           891
Cabin          204
Embarked       889
dtype: int64

 

특정 컬럼들로 Aggregation 함수 수행.

titanic_df[['Age', 'Fare']].mean(axis=1) # 열들 평균

0      14.62500
1      54.64165
2      16.96250
3      44.05000
4      21.52500
         ...   
886    20.00000
887    24.50000
888    23.45000
889    28.00000
890    19.87500
Length: 891, dtype: float64

 

titanic_df[['Age', 'Fare']].sum(axis=0) # 불러온 것은 '행'을 불러왔지만 '행들'을 연산한 것이라 실상 col 합

Age     21205.1700
Fare    28693.9493
dtype: float64

 

titanic_df[['Age', 'Fare']].count() # col당 row 개수 // null은 제외

Age     714
Fare    891
dtype: int64

 

groupby( ) 

by 인자에 Group By 하고자 하는 컬럼을 입력, 여러개의 컬럼으로 Group by 하고자 하면 [ ] 내에 해당 컬럼명을 입력.

DataFrame에 groupby( )를 호출하면 DataFrameGroupBy 객체를 반환. SQL과의 차이점 주목

titanic_groupby = titanic_df.groupby(by='Pclass')
print(type(titanic_groupby)) 
print(titanic_groupby)

# <class 'pandas.core.groupby.generic.DataFrameGroupBy'>
# <pandas.core.groupby.generic.DataFrameGroupBy object at 0x0000014E7CF8BC70>

 

DataFrameGroupBy객체에 Aggregation함수를 호출하여 Group by 수행.

titanic_groupby = titanic_df.groupby('Pclass').count() # 인덱스명은 gb 된 pclass로 됨
titanic_groupby

	PassengerId	Survived	Name	Sex	Age	SibSp	Parch	Ticket	Fare	Cabin	Embarked
Pclass											
1	216	216	216	216	186	216	216	216	216	176	214
2	184	184	184	184	173	184	184	184	184	16	184
3	491	491	491	491	355	491	491	491	491	12	491

 

print(type(titanic_groupby))
print(titanic_groupby.shape) # 원래는 col이 12개인데 pclass가 index가 되면서 col이 11개가 됨
print(titanic_groupby.index) # index는 name 이 pclass

# <class 'pandas.core.frame.DataFrame'>
# (3, 11)
# Int64Index([1, 2, 3], dtype='int64', name='Pclass')

 

titanic_groupby = titanic_df.groupby(by='Pclass')[['PassengerId', 'Survived']].count() # 또 특정 col 만 모으기 가능  브레이킷
titanic_groupby

	PassengerId	Survived
Pclass		
1	216	216
2	184	184
3	491	491

 

titanic_df[['Pclass','PassengerId', 'Survived']].groupby('Pclass').count() 
# 순서 상관없음 // col 먼저 따지면 메모리 최소화하기도 // 기존이 된 pclass는 무조건 넣어줘야함

	PassengerId	Survived
Pclass		
1	216	216
2	184	184
3	491	491

 

titanic_df.groupby('Pclass')['Pclass'].count() # plass 만하고싶다면 gb[]보다는 value_count가 좋음
titanic_df['Pclass'].value_counts()

3    491
1    216
2    184
Name: Pclass, dtype: int64

 

RDBMS의 group by는 select 절에 여러개의 aggregation 함수를 적용할 수 있음.

Select max(Age), min(Age) from titanic_table group by Pclass

판다스는 여러개의 aggregation 함수를 적용할 수 있도록 agg( )함수를 별도로 제공

titanic_df.groupby('Pclass')['Age'].agg([max, min]) # 여러개를 .max().min()이 안되서  agg([ , ])로 수행

	max	min
Pclass		
1	80.0	0.92
2	70.0	0.67
3	74.0	0.42

 

딕셔너리를 이용하여 다양한 aggregation 함수를 적용

agg_format={'Age':'max', 'SibSp':'sum', 'Fare':'mean'} # 각컬럼에 각기 다른 함수를 부여하고 싶다면 dict으로 key 부여
titanic_df.groupby('Pclass').agg(agg_format)

	Age	SibSp	Fare
Pclass			
1	80.0	90	84.154687
2	70.0	74	20.662183
3	74.0	302	13.675550

 

Missing 데이터 처리하기

DataFrame의 isna( ) 메소드는 모든 컬럼값들이 NaN인지 True/False값을 반환함(NaN이면 True)

titanic_df.isna().head(3) # 모든 COL에 T/F 출력

	PassengerId	Survived	Pclass	Name	Sex	Age	SibSp	Parch	Ticket	Fare	Cabin	Embarked
0	False	False	False	False	False	False	False	False	False	False	True	False
1	False	False	False	False	False	False	False	False	False	False	False	False
2	False	False	False	False	False	False	False	False	False	False	True	False

 

아래와 같이 isna( ) 반환 결과에 sum( )을 호출하여 컬럼별로 NaN 건수를 구할 수 있습니다.

titanic_df.isna( ).sum( ) # NULL의 개수를 계산 VS COUNT와 반대

PassengerId      0
Survived         0
Pclass           0
Name             0
Sex              0
Age            177
SibSp            0
Parch            0
Ticket           0
Fare             0
Cabin          687
Embarked         2
dtype: int64

 

** fillna( ) 로 Missing 데이터를 인자로 대체하기 **

titanic_df['Cabin'] = titanic_df['Cabin'].fillna('C000') #NULL 이면 COOO으로 채워주줘
titanic_df.head(3)

	PassengerId	Survived	Pclass	Name	Sex	Age	SibSp	Parch	Ticket	Fare	Cabin	Embarked
0	1	0	3	Braund, Mr....	male	22.0	1	0	A/5 21171	7.2500	C000	S
1	2	1	1	Cumings, Mr...	female	38.0	1	0	PC 17599	71.2833	C85	C
2	3	1	3	Heikkinen, ...	female	26.0	0	0	STON/O2. 31...	7.9250	C000	S

 

titanic_df['Age'] = titanic_df['Age'].fillna(titanic_df['Age'].mean())
titanic_df['Embarked'] = titanic_df['Embarked'].fillna('S')
titanic_df.isna().sum()

PassengerId    0
Survived       0
Pclass         0
Name           0
Sex            0
Age            0
SibSp          0
Parch          0
Ticket         0
Fare           0
Cabin          0
Embarked       0
dtype: int64

 

apply lambda // 함수 식으로 데이터 가공

파이썬 lambda 식 기본 // apply 함수에 lambda 결합, df, series에 레코드별 데이터 가공 기능,

보통은 일괄 데이터 가공이 속도면에서 빠르지만, 복잡한데이터 가공시 행별 apply lambda 이용

lambda x(입력 인자) : x**2(입력인자를 기반으로한 계산식이며 호출 시 계산 결과가 반환됨)

def get_square(a):
    return a**2

print('3의 제곱은:',get_square(3))

# 3의 제곱은: 9

 

lambda_square = lambda x : x ** 2
print('3의 제곱은:',lambda_square(3))

# 3의 제곱은: 9

 

a=[1,2,3]
squares = map(lambda x : x**2, a) # 입력값이 여러개면 map
list(squares)

# [1, 4, 9]

 

** 판다스에 apply lambda 식 적용 **

titanic_df['Name_len']= titanic_df['Name'].apply(lambda x : len(x)) # 이경우는 매우심플, 그냥 내장함수를 서도 되는 정도
titanic_df[['Name','Name_len']].head(3)


Name	Name_len
0	Braund, Mr....	23
1	Cumings, Mr...	51
2	Heikkinen, ...	22

 

titanic_df['Child_Adult'] = titanic_df['Age'].apply(lambda x : 'Child' if x <=15 else 'Adult' ) #함수처럼 자체 가공
titanic_df[['Age','Child_Adult']].head(10)

	Age	Child_Adult
0	22.000000	Adult
1	38.000000	Adult
2	26.000000	Adult
3	35.000000	Adult
4	35.000000	Adult
5	29.699118	Adult
6	54.000000	Adult
7	2.000000	Child
8	27.000000	Adult
9	14.000000	Child

 

titanic_df['Age_cat'] = titanic_df['Age'].apply(lambda x : 'Child' if x<=15 else ('Adult' if x <= 60 else 
                                                                                  'Elderly'))
titanic_df['Age_cat'].value_counts()

Adult      786
Child       83
Elderly     22
Name: Age_cat, dtype: int64

 

def get_category(age):
    cat = ''
    if age <= 5: cat = 'Baby'
    elif age <= 12: cat = 'Child'
    elif age <= 18: cat = 'Teenager'
    elif age <= 25: cat = 'Student'
    elif age <= 35: cat = 'Young Adult'
    elif age <= 60: cat = 'Adult'
    else : cat = 'Elderly'
    
    return cat # 꼭 return을 해줘야함

titanic_df['Age_cat'] = titanic_df['Age'].apply(lambda x : get_category(x)) # 함수처럼 호출리턴
titanic_df[['Age','Age_cat']].head()

	Age	Age_cat
0	22.0	Student
1	38.0	Adult
2	26.0	Young Adult
3	35.0	Young Adult
4	35.0	Young Adult

 

 

 

반응형

'Data_Science > ML_Perfect_Guide' 카테고리의 다른 글

2-3. model selection || sklearn  (0) 2021.12.22
2-2. sklearn 내장 데이터 || iris  (0) 2021.12.22
2-1. iris || sklearn  (0) 2021.12.22
1-2. Pandas  (0) 2021.12.22
1-1. Numpy  (0) 2021.12.22
728x90
반응형
import pandas as pd

read_csv()
read_csv()를 이용하여 csv 파일을 편리하게 DataFrame으로 로드
read_csv() 의 sep 인자를 콤마(,)가 아닌 다른 분리자로 변경하여 다른 유형의 파일도 로드가 가능

titanic_train.csv
0.06MB

titanic_df = pd.read_csv('titanic_train.csv')
print('titanic 변수 type:',type(titanic_df))

# titanic 변수 type: <class 'pandas.core.frame.DataFrame'>

 

head()
DataFrame의 맨 앞 일부 데이터만 추출

 

titanic_df.head(5)
# col, row 모든 값이 ndarray 2차원이니깐 // index는 차원에 포함 안됨
	PassengerId	Survived	Pclass	Name	Sex	Age	SibSp	Parch	Ticket	Fare	Cabin	Embarked
0	1	0	3	Braund, Mr. Owen Harris	male	22.0	1	0	A/5 21171	7.2500	NaN	S
1	2	1	1	Cumings, Mrs. John Bradley (Florence Briggs Th...	female	38.0	1	0	PC 17599	71.2833	C85	C
2	3	1	3	Heikkinen, Miss. Laina	female	26.0	0	0	STON/O2. 3101282	7.9250	NaN	S
3	4	1	1	Futrelle, Mrs. Jacques Heath (Lily May Peel)	female	35.0	1	0	113803	53.1000	C123	S
4	5	0	3	Allen, Mr. William Henry	male	35.0	0	0	373450	8.0500	NaN	S

 

** DataFrame의 생성 **

dic1 = {'Name': ['Chulmin', 'Eunkyung','Jinwoong','Soobeom'],
        'Year': [2011, 2016, 2015, 2015],
        'Gender': ['Male', 'Female', 'Male', 'Male']
       }
# 딕셔너리를 DataFrame으로 변환 // key 값이 col 나머지가 value로들어감
data_df = pd.DataFrame(dic1)
print(data_df)
print("#"*30)

# 새로운 컬럼명을 추가
data_df = pd.DataFrame(dic1, columns=["Name", "Year", "Gender", "Age"])
print(data_df)
print("#"*30)

# 인덱스를 새로운 값으로 할당. 
data_df = pd.DataFrame(dic1, index=['one','two','three','four']) 
# index 마음 대로 가능 //보통은 arange형인데
print(data_df)
print("#"*30)


       Name  Year  Gender
0   Chulmin  2011    Male
1  Eunkyung  2016  Female
2  Jinwoong  2015    Male
3   Soobeom  2015    Male
##############################
       Name  Year  Gender  Age
0   Chulmin  2011    Male  NaN
1  Eunkyung  2016  Female  NaN
2  Jinwoong  2015    Male  NaN
3   Soobeom  2015    Male  NaN
##############################
           Name  Year  Gender
one     Chulmin  2011    Male
two    Eunkyung  2016  Female
three  Jinwoong  2015    Male
four    Soobeom  2015    Male
##############################

 

DataFrame의 컬럼명과 인덱스

 

print("columns:",titanic_df.columns)
print("index:",titanic_df.index)
print("index value:", titanic_df.index.values) # 값을 보려면 values

columns: Index(['PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp',
       'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked'],
      dtype='object')
index: RangeIndex(start=0, stop=891, step=1)
index value: [  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17
  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35
  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53
  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71
  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89
  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107
 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
 882 883 884 885 886 887 888 889 890]

 

DataFrame에서 Series 추출 및 DataFrame 필터링 추출

# DataFrame객체에서 []연산자내에 한개의 컬럼만 입력하면 Series 객체를 반환  
series = titanic_df['Name']
print(series.head(3))
print("## type:",type(series))

# DataFrame객체에서 []연산자내에 여러개의 컬럼을 리스트로 입력하면 그 컬럼들로 구성된 DataFrame 반환  
filtered_df = titanic_df[['Name', 'Age']] # 두개 이상이면 대괄호 두개
print(filtered_df.head(3))
print("## type:", type(filtered_df))

# DataFrame객체에서 []연산자내에 한개의 컬럼을 리스트로 입력하면 한개의 컬럼으로 구성된 DataFrame 반환 
one_col_df = titanic_df[['Name']] #리스트면 시리즈는 아닌데 이차원 데이터 프레임
print(one_col_df.head(3))
print("## type:", type(one_col_df))

# 0                              Braund, Mr. Owen Harris
# 1    Cumings, Mrs. John Bradley (Florence Briggs Th...
# 2                               Heikkinen, Miss. Laina
# Name: Name, dtype: object
# ## type: <class 'pandas.core.series.Series'>
#                                                 Name   Age
# 0                            Braund, Mr. Owen Harris  22.0
# 1  Cumings, Mrs. John Bradley (Florence Briggs Th...  38.0
# 2                             Heikkinen, Miss. Laina  26.0
# ## type: <class 'pandas.core.frame.DataFrame'>
#                                                 Name
# 0                            Braund, Mr. Owen Harris
# 1  Cumings, Mrs. John Bradley (Florence Briggs Th...
# 2                             Heikkinen, Miss. Laina
# ## type: <class 'pandas.core.frame.DataFrame'>

 

** shape ** DataFrame의 행(Row)와 열(Column) 크기를 가지고 있는 속성

print('DataFrame 크기: ', titanic_df.shape)

# DataFrame 크기:  (891, 12)

 

info()
DataFrame내의 컬럼명, 데이터 타입, Null건수, 데이터 건수 정보를 제공합니다.

titanic_df.info()
# angeIndex: 891 entries, 0 to 890
# Data columns (total 12 columns):
# nonnull은 데이터가 존재한다. 차수만큼 없다. // object 는 string, 데이터 형 // 메모리 사용량 을 보여줌

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to 890
Data columns (total 12 columns):
 #   Column       Non-Null Count  Dtype  
---  ------       --------------  -----  
 0   PassengerId  891 non-null    int64  
 1   Survived     891 non-null    int64  
 2   Pclass       891 non-null    int64  
 3   Name         891 non-null    object 
 4   Sex          891 non-null    object 
 5   Age          714 non-null    float64
 6   SibSp        891 non-null    int64  
 7   Parch        891 non-null    int64  
 8   Ticket       891 non-null    object 
 9   Fare         891 non-null    float64
 10  Cabin        204 non-null    object 
 11  Embarked     889 non-null    object 
dtypes: float64(2), int64(5), object(5)
memory usage: 83.7+ KB

 

describe()
데이터값들의 평균,표준편차,4분위 분포도를 제공합니다. 숫자형 컬럼들에 대해서 해당 정보를 제공합니다.

titanic_df.describe()
# PassengerId	Survived	Pclass	정도는 소수점이 의미가 없음, 고유값이라서, null값은 빠진 평균값이다.

	PassengerId	Survived	Pclass	Age	SibSp	Parch	Fare
count	891.000000	891.000000	891.000000	714.000000	891.000000	891.000000	891.000000
mean	446.000000	0.383838	2.308642	29.699118	0.523008	0.381594	32.204208
std	257.353842	0.486592	0.836071	14.526497	1.102743	0.806057	49.693429
min	1.000000	0.000000	1.000000	0.420000	0.000000	0.000000	0.000000
25%	223.500000	0.000000	2.000000	20.125000	0.000000	0.000000	7.910400
50%	446.000000	0.000000	3.000000	28.000000	0.000000	0.000000	14.454200
75%	668.500000	1.000000	3.000000	38.000000	1.000000	0.000000	31.000000
max	891.000000	1.000000	3.000000	80.000000	8.000000	6.000000	512.329200

 

value_counts()
동일한 개별 데이터 값이 몇건이 있는지 정보를 제공합니다. 즉 개별 데이터값의 분포도를 제공함

주의할 점은 value_counts()는 Series객체에서만 호출 될 수 있으므로 반드시 DataFrame을 단일 컬럼으로 입력하여 Series로 변환한 뒤 호출해야 함.

value_counts = titanic_df['Pclass'].value_counts()
print(value_counts)

# 3    491
# 1    216
# 2    184
# Name: Pclass, dtype: int64

 

titanic_pclass = titanic_df['Pclass']
print(type(titanic_pclass))

# <class 'pandas.core.series.Series'>

 

titanic_pclass.head()

# 0    3
# 1    1
# 2    3
# 3    1
# 4    3
# Name: Pclass, dtype: int64

 

value_counts = titanic_df['Pclass'].value_counts()
print(type(value_counts))
print(value_counts)

# <class 'pandas.core.series.Series'>
# 3    491
# 1    216
# 2    184
# Name: Pclass, dtype: int64

 

sort_values() by=정렬컬럼, ascending=True 또는 False로 오름차순/내림차순으로 정렬

titanic_df.sort_values(by='Pclass', ascending=True)

titanic_df[['Name','Age']].sort_values(by='Age') # 특정값, age로 정렬
titanic_df[['Name','Age','Pclass']].sort_values(by=['Pclass','Age']) # 여러개의 칼럼 정렬 list로

Name	Age	Pclass
305	Allison, Master. Hudson Trevor	0.92	1
297	Allison, Miss. Helen Loraine	2.00	1
445	Dodge, Master. Washington	4.00	1
802	Carter, Master. William Thornton II	11.00	1
435	Carter, Miss. Lucile Polk	14.00	1
...	...	...	...
859	Razi, Mr. Raihed	NaN	3
863	Sage, Miss. Dorothy Edith "Dolly"	NaN	3
868	van Melkebeke, Mr. Philemon	NaN	3
878	Laleff, Mr. Kristo	NaN	3
888	Johnston, Miss. Catherine Helen "Carrie"	NaN	3
891 rows × 3 columns

 

DataFrame과 리스트, 딕셔너리, 넘파이 ndarray 상호 변환

리스트, ndarray에서 DataFrame변환

import numpy as np

col_name1=['col1']
list1 = [1, 2, 3]
array1 = np.array(list1)

print('array1 shape:', array1.shape )
df_list1 = pd.DataFrame(list1, columns=col_name1)
print('1차원 리스트로 만든 DataFrame:\n', df_list1)
df_array1 = pd.DataFrame(array1, columns=col_name1)
print('1차원 ndarray로 만든 DataFrame:\n', df_array1)

# array1 shape: (3,)
# 1차원 리스트로 만든 DataFrame:
#     col1
# 0     1
# 1     2
# 2     3
# 1차원 ndarray로 만든 DataFrame:
#     col1
# 0     1
# 1     2
# 2     3

 

# 3개의 컬럼명이 필요함. 
col_name2=['col1', 'col2', 'col3']

# 2행x3열 형태의 리스트와 ndarray 생성 한 뒤 이를 DataFrame으로 변환. 
list2 = [[1, 2, 3],
         [11, 12, 13]]
array2 = np.array(list2)
print('array2 shape:', array2.shape )
df_list2 = pd.DataFrame(list2, columns=col_name2)
print('2차원 리스트로 만든 DataFrame:\n', df_list2)
df_array1 = pd.DataFrame(array2, columns=col_name2)
print('2차원 ndarray로 만든 DataFrame:\n', df_array1)

# array2 shape: (2, 3)
# 2차원 리스트로 만든 DataFrame:
#     col1  col2  col3
# 0     1     2     3
# 1    11    12    13
# 2차원 ndarray로 만든 DataFrame:
#     col1  col2  col3
# 0     1     2     3
# 1    11    12    13

 

** 딕셔너리(dict)에서 DataFrame변환**

# Key는 컬럼명으로 매핑, Value는 리스트 형(또는 ndarray)
dict = {'col1':[1, 11], 'col2':[2, 22], 'col3':[3, 33]}
df_dict = pd.DataFrame(dict)
print('딕셔너리로 만든 DataFrame:\n', df_dict)

# 딕셔너리로 만든 DataFrame:
#     col1  col2  col3
# 0     1     2     3
# 1    11    22    33

 

** DataFrame을 ndarray로 변환**

# DataFrame을 ndarray로 변환
array3 = df_dict.values
print('df_dict.values 타입:', type(array3), 'df_dict.values shape:', array3.shape)
print(array3)

# df_dict.values 타입: <class 'numpy.ndarray'> df_dict.values shape: (2, 3)
# [[ 1  2  3]
#  [11 22 33]]

 

DataFrame을 리스트와 딕셔너리로 변환

# DataFrame을 리스트로 변환
list3 = df_dict.values.tolist()
print('df_dict.values.tolist() 타입:', type(list3))
print(list3)

# DataFrame을 딕셔너리로 변환
dict3 = df_dict.to_dict('list')
print('\n df_dict.to_dict() 타입:', type(dict3))
print(dict3)

# df_dict.values.tolist() 타입: <class 'list'>
# [[1, 2, 3], [11, 22, 33]]

#  df_dict.to_dict() 타입: <class 'dict'>
# {'col1': [1, 11], 'col2': [2, 22], 'col3': [3, 33]}

 

DataFrame의 컬럼 데이터 셋 Access

DataFrame의 컬럼 데이터 세트 생성과 수정은 [ ] 연산자를 이용해 쉽게 가능

새로운 컬럼에 값을 할당하려면 DataFrame [ ] 내에 새로운 컬럼명을 입력하고 값을 할당해주기만 하면 됨

titanic_df['Age_0']=0 # 추가
titanic_df.head(3)


PassengerId	Survived	Pclass	Name	Sex	Age	SibSp	Parch	Ticket	Fare	Cabin	Embarked	Age_0
0	1	0	3	Braund, Mr. Owen Harris	male	22.0	1	0	A/5 21171	7.2500	NaN	S	0
1	2	1	1	Cumings, Mrs. John Bradley (Florence Briggs Th...	female	38.0	1	0	PC 17599	71.2833	C85	C	0
2	3	1	3	Heikkinen, Miss. Laina	female	26.0	0	0	STON/O2. 3101282	7.9250	NaN	S	0

 

titanic_df['Age_by_10'] = titanic_df['Age']*10
titanic_df['Family_No'] = titanic_df['SibSp'] + titanic_df['Parch']+1 # 기존 컬럼을 통해 새로 생성
titanic_df.head(3)

	PassengerId	Survived	Pclass	Name	Sex	Age	SibSp	Parch	Ticket	Fare	Cabin	Embarked	Age_0	Age_by_10	Family_No
0	1	0	3	Braund, Mr. Owen Harris	male	22.0	1	0	A/5 21171	7.2500	NaN	S	0	220.0	2
1	2	1	1	Cumings, Mrs. John Bradley (Florence Briggs Th...	female	38.0	1	0	PC 17599	71.2833	C85	C	0	380.0	2
2	3	1	3	Heikkinen, Miss. Laina	female	26.0	0	0	STON/O2. 3101282	7.9250	NaN	S	0	260.0	1

 

기존 컬럼에 값을 업데이트 하려면 해당 컬럼에 업데이트값을 그대로 지정하면 됨

titanic_df['Age_by_10'] = titanic_df['Age_by_10'] + 100
titanic_df.head(3)

	PassengerId	Survived	Pclass	Name	Sex	Age	SibSp	Parch	Ticket	Fare	Cabin	Embarked	Age_0	Age_by_10	Family_No
0	1	0	3	Braund, Mr. Owen Harris	male	22.0	1	0	A/5 21171	7.2500	NaN	S	0	320.0	2
1	2	1	1	Cumings, Mrs. John Bradley (Florence Briggs Th...	female	38.0	1	0	PC 17599	71.2833	C85	C	0	480.0	2
2	3	1	3	Heikkinen, Miss. Laina	female	26.0	0	0	STON/O2. 3101282	7.9250	NaN	S	0	360.0	1

 

DataFrame 데이터 삭제

** axis에 따른 삭제**

titanic_drop_df = titanic_df.drop('Age_0', axis=1 )
titanic_drop_df.head(3)

	PassengerId	Survived	Pclass	Name	Sex	Age	SibSp	Parch	Ticket	Fare	Cabin	Embarked	Age_by_10	Family_No
0	1	0	3	Braund, Mr. Owen Harris	male	22.0	1	0	A/5 21171	7.2500	NaN	S	320.0	2
1	2	1	1	Cumings, Mrs. John Bradley (Florence Briggs Th...	female	38.0	1	0	PC 17599	71.2833	C85	C	480.0	2
2	3	1	3	Heikkinen, Miss. Laina	female	26.0	0	0	STON/O2. 3101282	7.9250	NaN	S	360.0	1

 

drop( )메소드의 inplace인자의 기본값은 False 임

이 경우 drop( )호출을 한 DataFrame은 아무런 영향이 없으며

drop( )호출의 결과가 해당 컬럼이 drop 된 DataFrame을 반환함

titanic_df.head(3)


PassengerId	Survived	Pclass	Name	Sex	Age	SibSp	Parch	Ticket	Fare	Cabin	Embarked	Age_0	Age_by_10	Family_No
0	1	0	3	Braund, Mr. Owen Harris	male	22.0	1	0	A/5 21171	7.2500	NaN	S	0	320.0	2
1	2	1	1	Cumings, Mrs. John Bradley (Florence Briggs Th...	female	38.0	1	0	PC 17599	71.2833	C85	C	0	480.0	2
2	3	1	3	Heikkinen, Miss. Laina	female	26.0	0	0	STON/O2. 3101282	7.9250	NaN	S	0	360.0	1

 

여러개의 컬럼들의 삭제는 drop의 인자로 삭제 컬럼들을 리스트로 입력함

inplace=True 일 경우 호출을 한 DataFrame에 drop이 반영됨

이 때 반환값은 None임

drop_result = titanic_df.drop(['Age_0', 'Age_by_10', 'Family_No'], axis=1, inplace=True)
print(' inplace=True 로 drop 후 반환된 값:',drop_result)
titanic_df.head(3)

#  inplace=True 로 drop 후 반환된 값: None
	PassengerId	Survived	Pclass	Name	Sex	Age	SibSp	Parch	Ticket	Fare	Cabin	Embarked
0	1	0	3	Braund, Mr. Owen Harris	male	22.0	1	0	A/5 21171	7.2500	NaN	S
1	2	1	1	Cumings, Mrs. John Bradley (Florence Briggs Th...	female	38.0	1	0	PC 17599	71.2833	C85	C
2	3	1	3	Heikkinen, Miss. Laina	female	26.0	0	0	STON/O2. 3101282	7.9250	NaN	S

 

axis=0 일 경우 drop()은 row 방향으로 데이터를 삭제함

titanic_df = pd.read_csv('titanic_train.csv')
pd.set_option('display.width', 1000)
pd.set_option('display.max_colwidth', 15)
print('#### before axis 0 drop ####') 
print(titanic_df.head(6))

titanic_df.drop([0,1,2], axis=0, inplace=True)

print('#### after axis 0 drop ####')
print(titanic_df.head(3))

#### before axis 0 drop ####
   PassengerId  Survived  Pclass            Name     Sex   Age  SibSp  Parch          Ticket     Fare Cabin Embarked
0            1         0       3  Braund, Mr....    male  22.0      1      0       A/5 21171   7.2500   NaN        S
1            2         1       1  Cumings, Mr...  female  38.0      1      0        PC 17599  71.2833   C85        C
2            3         1       3  Heikkinen, ...  female  26.0      0      0  STON/O2. 31...   7.9250   NaN        S
3            4         1       1  Futrelle, M...  female  35.0      1      0          113803  53.1000  C123        S
4            5         0       3  Allen, Mr. ...    male  35.0      0      0          373450   8.0500   NaN        S
5            6         0       3  Moran, Mr. ...    male   NaN      0      0          330877   8.4583   NaN        Q
#### after axis 0 drop ####
   PassengerId  Survived  Pclass            Name     Sex   Age  SibSp  Parch  Ticket     Fare Cabin Embarked
3            4         1       1  Futrelle, M...  female  35.0      1      0  113803  53.1000  C123        S
4            5         0       3  Allen, Mr. ...    male  35.0      0      0  373450   8.0500   NaN        S
5            6         0       3  Moran, Mr. ...    male   NaN      0      0  330877   8.4583   NaN        Q

 

Index 객체

# 원본 파일 재 로딩 
titanic_df = pd.read_csv('titanic_train.csv')
# Index 객체 추출
indexes = titanic_df.index
print(indexes)
# Index 객체를 실제 값 arrray로 변환 
print('Index 객체 array값:\n',indexes.values)

RangeIndex(start=0, stop=891, step=1)
Index 객체 array값:
 [  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17
  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35
  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53
  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71
  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89
  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107
 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
 882 883 884 885 886 887 888 889 890]

 

Index는 1차원 데이터 입니다.

print(type(indexes.values))
print(indexes.values.shape)
print(indexes[:5].values)
print(indexes.values[:5])
print(indexes[6])

# <class 'numpy.ndarray'>
# (891,)
# [0 1 2 3 4]
# [0 1 2 3 4]
# 6

 

[ ]를 이용하여 임의로 Index의 값을 변경할 수는 없습니다.

 

indexes[0] = 5

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-29-2fe1c3d18d1a> in <module>
----> 1 indexes[0] = 5

~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in __setitem__(self, key, value)
   4079 
   4080     def __setitem__(self, key, value):
-> 4081         raise TypeError("Index does not support mutable operations")
   4082 
   4083     def __getitem__(self, key):

TypeError: Index does not support mutable operations

 

Series 객체는 Index 객체를 포함하지만 Series 객체에 연산 함수를 적용할 때 Index는 연산에서 제외됨

Index는 오직 식별용으로만 사용됨

series_fair = titanic_df['Fare']
series_fair.head(5)

# 0     7.2500
# 1    71.2833
# 2     7.9250
# 3    53.1000
# 4     8.0500
# Name: Fare, dtype: float64

 

print('Fair Series max 값:', series_fair.max())
print('Fair Series sum 값:', series_fair.sum())
print('sum() Fair Series:', sum(series_fair))
print('Fair Series + 3:\n',(series_fair + 3).head(3) )
# index 로 의미있는값이 나오는 경우가 있음, 그럼 인덱스를 컬럼으로 만들수 없을까? reset index

# Fair Series max 값: 512.3292
# Fair Series sum 값: 28693.9493
# sum() Fair Series: 28693.949299999967
# Fair Series + 3:
#  0    10.2500
# 1    74.2833
# 2    10.9250
# Name: Fare, dtype: float64

 

DataFrame 및 Series에 reset_index( ) 메서드를 수행하면 새롭게 인덱스를 연속 숫자 형으로 할당하며 기존 인덱스는 ‘index’라는 새로운 컬럼 명으로 추가함

titanic_reset_df = titanic_df.reset_index(inplace=False)
titanic_reset_df.head(3)

	index	PassengerId	Survived	Pclass	Name	Sex	Age	SibSp	Parch	Ticket	Fare	Cabin	Embarked
0	0	1	0	3	Braund, Mr....	male	22.0	1	0	A/5 21171	7.2500	NaN	S
1	1	2	1	1	Cumings, Mr...	female	38.0	1	0	PC 17599	71.2833	C85	C
2	2	3	1	3	Heikkinen, ...	female	26.0	0	0	STON/O2. 31...	7.9250	NaN	S

 

titanic_reset_df.shape
# (891, 13)

 

print('### before reset_index ###')
value_counts = titanic_df['Pclass'].value_counts() #  vc는 series => 고유 칼럼값이 필요한데 
print(value_counts)
print('value_counts 객체 변수 타입:',type(value_counts))


new_value_counts = value_counts.reset_index(inplace=False)
print('### After reset_index ###')
print(new_value_counts)
print('new_value_counts 객체 변수 타입:',type(new_value_counts))

### before reset_index ###
# 3    491
# 1    216
# 2    184
# Name: Pclass, dtype: int64
# value_counts 객체 변수 타입: <class 'pandas.core.series.Series'>
### After reset_index ###
#    index  Pclass
# 0      3     491
# 1      1     216
# 2      2     184
# new_value_counts 객체 변수 타입: <class 'pandas.core.frame.DataFrame'>

 

데이터 Selection 및 Filtering

DataFrame의 [ ] 연산자

넘파이에서 [ ] 연산자는 행의 위치, 열의 위치, 슬라이싱 범위 등을 지정해 데이터를 가져올 수 있음

하지만 DataFrame 바로 뒤에 있는 ‘[ ]’ 안에 들어갈 수 있는 것은 컬럼 명 문자(또는 컬럼 명의 리스트 객체), 또는 인덱스로 변환 가능한 표현식임

titanic_df = pd.read_csv('titanic_train.csv')
print('단일 컬럼 데이터 추출:\n', titanic_df[ 'Pclass' ].head(3))
print('\n여러 컬럼들의 데이터 추출:\n', titanic_df[ ['Survived', 'Pclass'] ].head(3))
print('[ ] 안에 숫자 index는 KeyError 오류 발생:\n', titanic_df[0]) # 숫자형 x 직접 칼럼명 넣어주는게 좋다

단일 컬럼 데이터 추출:
 0    3
1    1
2    3
Name: Pclass, dtype: int64

여러 컬럼들의 데이터 추출:
    Survived  Pclass
0         0       3
1         1       1
2         1       3
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2894             try:
-> 2895                 return self._engine.get_loc(casted_key)
   2896             except KeyError as err:

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 0

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
<ipython-input-35-16b79a4adf85> in <module>
      2 print('단일 컬럼 데이터 추출:\n', titanic_df[ 'Pclass' ].head(3))
      3 print('\n여러 컬럼들의 데이터 추출:\n', titanic_df[ ['Survived', 'Pclass'] ].head(3))
----> 4 print('[ ] 안에 숫자 index는 KeyError 오류 발생:\n', titanic_df[0]) # 숫자형 x 직접 칼럼명 넣어주는게 좋다

~\anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   2900             if self.columns.nlevels > 1:
   2901                 return self._getitem_multilevel(key)
-> 2902             indexer = self.columns.get_loc(key)
   2903             if is_integer(indexer):
   2904                 indexer = [indexer]

~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2895                 return self._engine.get_loc(casted_key)
   2896             except KeyError as err:
-> 2897                 raise KeyError(key) from err
   2898 
   2899         if tolerance is not None:

KeyError: 0

 

앞에서 DataFrame의 [ ] 내에 숫자 값을 입력할 경우 오류가 발생한다고 했는데, Pandas의 Index 형태로 변환가능한
표현식은 [ ] 내에 입력할 수 있음
가령 titanic_df의 처음 2개 데이터를 추출하고자 titanic_df [ 0:2 ] 와 같은 슬라이싱을 이용하였다면 정확히 원하는 결과를 반환해 줌

titanic_df[0:2] #허용은 해주지만 비추

	PassengerId	Survived	Pclass	Name	Sex	Age	SibSp	Parch	Ticket	Fare	Cabin	Embarked
0	1	0	3	Braund, Mr....	male	22.0	1	0	A/5 21171	7.2500	NaN	S
1	2	1	1	Cumings, Mr...	female	38.0	1	0	PC 17599	71.2833	C85	C

 

[ ] 내에 조건식을 입력하여 불린 인덱싱을 수행할 수 있음

(DataFrame 바로 뒤에 있는 []안에 들어갈 수 있는 것은 컬럼명과 불린인덱싱으로 범위를 좁혀서 코딩을 하는게 도움이 됨)

titanic_df[ titanic_df['Pclass'] == 3].head(3)

	PassengerId	Survived	Pclass	Name	Sex	Age	SibSp	Parch	Ticket	Fare	Cabin	Embarked
0	1	0	3	Braund, Mr....	male	22.0	1	0	A/5 21171	7.250	NaN	S
2	3	1	3	Heikkinen, ...	female	26.0	0	0	STON/O2. 31...	7.925	NaN	S
4	5	0	3	Allen, Mr. ...	male	35.0	0	0	373450	8.050	NaN	S

 

* DataFrame iloc[ ] 연산자** 위치기반 인덱싱을 제공함

data_df.head()

	Name	Year	Gender
one	Chulmin	2011	Male
two	Eunkyung	2016	Female
three	Jinwoong	2015	Male
four	Soobeom	2015	Male

 

data_df.iloc[0, 0]
# 'Chulmin'

 

# 아래 코드는 오류를 발생함
data_df.iloc[0, 'Name']

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
~\anaconda3\lib\site-packages\pandas\core\indexing.py in _has_valid_tuple(self, key)
    701             try:
--> 702                 self._validate_key(k, i)
    703             except ValueError as err:

~\anaconda3\lib\site-packages\pandas\core\indexing.py in _validate_key(self, key, axis)
   1368         else:
-> 1369             raise ValueError(f"Can only index by location with a [{self._valid_types}]")
   1370 

ValueError: Can only index by location with a [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array]

The above exception was the direct cause of the following exception:

ValueError                                Traceback (most recent call last)
<ipython-input-60-ab5240d8ed9d> in <module>
      1 # 아래 코드는 오류를 발생합니다.
----> 2 data_df.iloc[0, 'Name']

~\anaconda3\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key)
    871                     # AttributeError for IntervalTree get_value
    872                     pass
--> 873             return self._getitem_tuple(key)
    874         else:
    875             # we by definition only have the 0th axis

~\anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_tuple(self, tup)
   1441     def _getitem_tuple(self, tup: Tuple):
   1442 
-> 1443         self._has_valid_tuple(tup)
   1444         try:
   1445             return self._getitem_lowerdim(tup)

~\anaconda3\lib\site-packages\pandas\core\indexing.py in _has_valid_tuple(self, key)
    702                 self._validate_key(k, i)
    703             except ValueError as err:
--> 704                 raise ValueError(
    705                     "Location based indexing can only have "
    706                     f"[{self._valid_types}] types"

ValueError: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types

 

# 아래 코드는 오류를 발생합니다. 
data_df.iloc['one', 0]

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
~\anaconda3\lib\site-packages\pandas\core\indexing.py in _has_valid_tuple(self, key)
    701             try:
--> 702                 self._validate_key(k, i)
    703             except ValueError as err:

~\anaconda3\lib\site-packages\pandas\core\indexing.py in _validate_key(self, key, axis)
   1368         else:
-> 1369             raise ValueError(f"Can only index by location with a [{self._valid_types}]")
   1370 

ValueError: Can only index by location with a [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array]

The above exception was the direct cause of the following exception:

ValueError                                Traceback (most recent call last)
<ipython-input-61-0fe0a94ee06c> in <module>
      1 # 아래 코드는 오류를 발생합니다.
----> 2 data_df.iloc['one', 0]

~\anaconda3\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key)
    871                     # AttributeError for IntervalTree get_value
    872                     pass
--> 873             return self._getitem_tuple(key)
    874         else:
    875             # we by definition only have the 0th axis

~\anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_tuple(self, tup)
   1441     def _getitem_tuple(self, tup: Tuple):
   1442 
-> 1443         self._has_valid_tuple(tup)
   1444         try:
   1445             return self._getitem_lowerdim(tup)

~\anaconda3\lib\site-packages\pandas\core\indexing.py in _has_valid_tuple(self, key)
    702                 self._validate_key(k, i)
    703             except ValueError as err:
--> 704                 raise ValueError(
    705                     "Location based indexing can only have "
    706                     f"[{self._valid_types}] types"

ValueError: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types

 

data_df_reset.head()


old_index	Name	Year	Gender
1	one	Chulmin	2011	Male
2	two	Eunkyung	2016	Female
3	three	Jinwoong	2015	Male
4	four	Soobeom	2015	Male

 

data_df_reset.iloc[0, 1]

# 'Chulmin'

 

DataFrame loc[ ] 연산자
명칭기반 인덱싱을 제공함

data_df

Name	Year	Gender
one	Chulmin	2011	Male
two	Eunkyung	2016	Female
three	Jinwoong	2015	Male
four	Soobeom	2015	Male

 

data_df.loc['one', 'Name']

# 'Chulmin'

 

data_df_reset.loc[1, 'Name'] # 명칭기반이어도, 인덱스 넘버로 하면 숫자여도 명칭기반임 1234 (단, 0없음)// 위치기반은 0123

# 'Chulmin'

 

# 아래 코드는 오류를 발생합니다. (단, 0없음)
data_df_reset.loc[0, 'Name']

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
~\anaconda3\lib\site-packages\pandas\core\indexes\range.py in get_loc(self, key, method, tolerance)
    354                 try:
--> 355                     return self._range.index(new_key)
    356                 except ValueError as err:

ValueError: 0 is not in range

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
<ipython-input-67-d3c58a57c329> in <module>
      1 # 아래 코드는 오류를 발생합니다. (단, 0없음)
----> 2 data_df_reset.loc[0, 'Name']

~\anaconda3\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key)
    871                     # AttributeError for IntervalTree get_value
    872                     pass
--> 873             return self._getitem_tuple(key)
    874         else:
    875             # we by definition only have the 0th axis

~\anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_tuple(self, tup)
   1042     def _getitem_tuple(self, tup: Tuple):
   1043         try:
-> 1044             return self._getitem_lowerdim(tup)
   1045         except IndexingError:
   1046             pass

~\anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_lowerdim(self, tup)
    784                 # We don't need to check for tuples here because those are
    785                 #  caught by the _is_nested_tuple_indexer check above.
--> 786                 section = self._getitem_axis(key, axis=i)
    787 
    788                 # We should never have a scalar section here, because

~\anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_axis(self, key, axis)
   1108         # fall thru to straight lookup
   1109         self._validate_key(key, axis)
-> 1110         return self._get_label(key, axis=axis)
   1111 
   1112     def _get_slice_axis(self, slice_obj: slice, axis: int):

~\anaconda3\lib\site-packages\pandas\core\indexing.py in _get_label(self, label, axis)
   1057     def _get_label(self, label, axis: int):
   1058         # GH#5667 this will fail if the label is not present in the axis.
-> 1059         return self.obj.xs(label, axis=axis)
   1060 
   1061     def _handle_lowerdim_multi_index_axis0(self, tup: Tuple):

~\anaconda3\lib\site-packages\pandas\core\generic.py in xs(self, key, axis, level, drop_level)
   3489             loc, new_index = self.index.get_loc_level(key, drop_level=drop_level)
   3490         else:
-> 3491             loc = self.index.get_loc(key)
   3492 
   3493             if isinstance(loc, np.ndarray):

~\anaconda3\lib\site-packages\pandas\core\indexes\range.py in get_loc(self, key, method, tolerance)
    355                     return self._range.index(new_key)
    356                 except ValueError as err:
--> 357                     raise KeyError(key) from err
    358             raise KeyError(key)
    359         return super().get_loc(key, method=method, tolerance=tolerance)

KeyError: 0

 

print('위치기반 iloc slicing\n', data_df.iloc[0:1, 0],'\n')
print('명칭기반 loc slicing\n', data_df.loc['one':'two', 'Name'])

# 위치기반 iloc slicing
#  one    Chulmin
# Name: Name, dtype: object 

# 명칭기반 loc slicing
#  one     Chulmin
# two    Eunkyung
# Name: Name, dtype: object

 

print(data_df_reset.loc[1:2 , 'Name'])

# 1     Chulmin
# 2    Eunkyung
# Name: Name, dtype: object

 

** 불린 인덱싱(Boolean indexing) **

헷갈리는 위치기반, 명칭기반 인덱싱을 사용할 필요없이 조건식을 [ ] 안에 기입하여 간편하게 필터링을 수행.

titanic_df = pd.read_csv('titanic_train.csv')
titanic_boolean = titanic_df[titanic_df['Age'] > 60] # 불리언[ 불리언[] 연산자]
print(type(titanic_boolean))
titanic_boolean

# <class 'pandas.core.frame.DataFrame'>

	PassengerId	Survived	Pclass	Name	Sex	Age	SibSp	Parch	Ticket	Fare	Cabin	Embarked
33	34	0	2	Wheadon, Mr...	male	66.0	0	0	C.A. 24579	10.5000	NaN	S
54	55	0	1	Ostby, Mr. ...	male	65.0	0	1	113509	61.9792	B30	C
96	97	0	1	Goldschmidt...	male	71.0	0	0	PC 17754	34.6542	A5	C
116	117	0	3	Connors, Mr...	male	70.5	0	0	370369	7.7500	NaN	Q
170	171	0	1	Van der hoe...	male	61.0	0	0	111240	33.5000	B19	S
252	253	0	1	Stead, Mr. ...	male	62.0	0	0	113514	26.5500	C87	S
275	276	1	1	Andrews, Mi...	female	63.0	1	0	13502	77.9583	D7	S
280	281	0	3	Duane, Mr. ...	male	65.0	0	0	336439	7.7500	NaN	Q
326	327	0	3	Nysveen, Mr...	male	61.0	0	0	345364	6.2375	NaN	S
438	439	0	1	Fortune, Mr...	male	64.0	1	4	19950	263.0000	C23 C25 C27	S
456	457	0	1	Millet, Mr....	male	65.0	0	0	13509	26.5500	E38	S
483	484	1	3	Turkula, Mr...	female	63.0	0	0	4134	9.5875	NaN	S
493	494	0	1	Artagaveyti...	male	71.0	0	0	PC 17609	49.5042	NaN	C
545	546	0	1	Nicholson, ...	male	64.0	0	0	693	26.0000	NaN	S
555	556	0	1	Wright, Mr....	male	62.0	0	0	113807	26.5500	NaN	S
570	571	1	2	Harris, Mr....	male	62.0	0	0	S.W./PP 752	10.5000	NaN	S
625	626	0	1	Sutton, Mr....	male	61.0	0	0	36963	32.3208	D50	S
630	631	1	1	Barkworth, ...	male	80.0	0	0	27042	30.0000	A23	S
672	673	0	2	Mitchell, M...	male	70.0	0	0	C.A. 24580	10.5000	NaN	S
745	746	0	1	Crosby, Cap...	male	70.0	1	1	WE/P 5735	71.0000	B22	S
829	830	1	1	Stone, Mrs....	female	62.0	0	0	113572	80.0000	B28	NaN
851	852	0	3	Svensson, M...	male	74.0	0	0	347060	7.7750	NaN	S

 

titanic_df['Age'] > 60

var1 = titanic_df['Age'] > 60 # []없이 하면 series  형태로 나옴 vs dataframe
print(type(var1))

# <class 'pandas.core.series.Series'>

 

titanic_df[titanic_df['Age'] > 60][['Name','Age']].head(3) #age > 60 인 data중에 name, age col로 3개 // SQL 느낌

	Name	Age
33	Wheadon, Mr...	66.0
54	Ostby, Mr. ...	65.0
96	Goldschmidt...	71.0

 

titanic_df[['Name','Age']][titanic_df['Age'] > 60].head(3) # 거꾸로해도 가능 : 유연성

	Name	Age
33	Wheadon, Mr...	66.0
54	Ostby, Mr. ...	65.0
96	Goldschmidt...	71.0

 

titanic_df.loc[titanic_df['Age'] > 60, ['Name','Age']].head(3) # loc 만으로 불린연산

	Name	Age
33	Wheadon, Mr...	66.0
54	Ostby, Mr. ...	65.0
96	Goldschmidt...	71.0

 

논리 연산자로 결합된 조건식도 불린 인덱싱으로 적용 가능함

titanic_df[ (titanic_df['Age'] > 60) & (titanic_df['Pclass']==1) & (titanic_df['Sex']=='female')] #논리연산자사용

	PassengerId	Survived	Pclass	Name	Sex	Age	SibSp	Parch	Ticket	Fare	Cabin	Embarked
275	276	1	1	Andrews, Mi...	female	63.0	1	0	13502	77.9583	D7	S
829	830	1	1	Stone, Mrs....	female	62.0	0	0	113572	80.0000	B28	NaN

 

조건식은 변수로도 할당 가능함

복잡한 조건식은 변수로 할당하여 가득성을 향상 할 수 있음

cond1 = titanic_df['Age'] > 60
cond2 = titanic_df['Pclass']==1
cond3 = titanic_df['Sex']=='female'
titanic_df[ cond1 & cond2 & cond3] # 가독성을 위해 각각 - 효과적으로 사용

	PassengerId	Survived	Pclass	Name	Sex	Age	SibSp	Parch	Ticket	Fare	Cabin	Embarked
275	276	1	1	Andrews, Mi...	female	63.0	1	0	13502	77.9583	D7	S
829	830	1	1	Stone, Mrs....	female	62.0	0	0	113572	80.0000	B28	NaN

 

 

반응형

'Data_Science > ML_Perfect_Guide' 카테고리의 다른 글

2-3. model selection || sklearn  (0) 2021.12.22
2-2. sklearn 내장 데이터 || iris  (0) 2021.12.22
2-1. iris || sklearn  (0) 2021.12.22
1-3. Pandas 2  (0) 2021.12.22
1-1. Numpy  (0) 2021.12.22
728x90
반응형

Numpy ndarray 개요

  • ndarray 생성 np.array()
import numpy as np
list1 = [1, 2, 3]
print("list1:",list1)
print("list1 type:",type(list1))

array1 = np.array(list1)
print("array1:",array1)
print("array1 type:", type(array1))


# list1: [1, 2, 3]
# list1 type: <class 'list'>
# array1: [1 2 3]
# array1 type: <class 'numpy.ndarray'>

리스트 형이지만 np.array()에 넣으니 numpy.ndarray로 변환됨

 

  • ndarray 의 형태(shape)와 차원
array1 = np.array([1,2,3])
print('array1 type:',type(array1))
print('array1 array 형태:',array1.shape)

array2 = np.array([[1,2,3],
                  [2,3,4]])
print('array2 type:',type(array2))
print('array2 array 형태:',array2.shape)

array3 = np.array([[1,2,3]])
print('array3 type:',type(array3))
print('array3 array 형태:',array3.shape)

# array1 type: <class 'numpy.ndarray'>
# array1 array 형태: (3,)
# array2 type: <class 'numpy.ndarray'>
# array2 array 형태: (2, 3)
# array3 type: <class 'numpy.ndarray'>
# array3 array 형태: (1, 3)

 

print('array1: {:0}차원, array2: {:1}차원, array3: {:2}차원'.format(array1.ndim,array2.ndim,array3.ndim))

# array1: 1차원, array2: 2차원, array3:  2차원

 

  • ndarray 데이터 값 타입
list1 = [1,2,3]
print(type(list1))
array1 = np.array(list1)

print(type(array1))
print(array1, array1.dtype)

# <class 'list'>
# <class 'numpy.ndarray'>
# [1 2 3] int32

 

list2 = [1, 2, 'test']
array2 = np.array(list2)
print(array2, array2.dtype)

list3 = [1, 2, 3.0]
array3 = np.array(list3)
print(array3, array3.dtype)
print('문자열이 있으면 전부 문자화 됨')
print('- 1 int정수, 1.0 float실수 같이 넣으면 전부 정수로 반환')


# ['1' '2' 'test'] <U11
# [1. 2. 3.] float64
# 1 int정수, 1.0 float실수 같이 넣으면 전부 정수로 반환

 

  • astype()을 통한 타입 변환 // 대규모데이터 운용할때, 수행속도, 메모리부족오류 제거위해위해
array_int = np.array([1, 2, 3])
array_float = array_int.astype('float64')
print(array_float, array_float.dtype)

array_int1= array_float.astype('int32')
print(array_int1, array_int1.dtype)

array_float1 = np.array([1.1, 2.1, 3.1])
array_int2= array_float1.astype('int32')
print(array_int2, array_int2.dtype)

# [1. 2. 3.] float64
# [1 2 3] int32
# [1 2 3] int32

 

  • ndarray에서 axis 기반의 연산함수 수행 // 중요한 느낌
array2 = np.array([[1,2,3],
                  [2,3,4]])

print(array2.sum())
print(array2.sum(axis=0), '행합')
print(array2.sum(axis=1), '열합')

# 15
# [3 5 7] 행합
# [6 9] 열합

 

  • ndarray를 편리하게 생성하기 - arange, zeros, ones
sequence_array = np.arange(10)
print(sequence_array)
print(sequence_array.dtype, sequence_array.shape)

# [0 1 2 3 4 5 6 7 8 9]
# int32 (10,)

 

zero_array = np.zeros((3,2),dtype='int32')
print(zero_array)
print(zero_array.dtype, zero_array.shape)

one_array = np.ones((3,2))
print(one_array)
print(one_array.dtype, one_array.shape)

# [[0 0]
#  [0 0]
#  [0 0]]
# int32 (3, 2)
# [[1. 1.]
#  [1. 1.]
#  [1. 1.]]
# float64 (3, 2)

 

  • ndarray의 shape를 변경하는 reshape()
array1 = np.arange(10)
print('array1:\n', array1)

array2 = array1.reshape(2,5)
print('array2:\n',array2)

array3 = array1.reshape(5,2)
print('array3:\n',array3)

# array1:
#  [0 1 2 3 4 5 6 7 8 9]
# array2:
#  [[0 1 2 3 4]
#  [5 6 7 8 9]]
# array3:
#  [[0 1]
#  [2 3]
#  [4 5]
#  [6 7]
#  [8 9]]

 

# 변환할 수 없는 shape구조를 입력하면 오류 발생.

array1.reshape(4,3)

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-2ff703983fd4> in <module>
      1 # 변환할 수 없는 shape구조를 입력하면 오류 발생.
----> 2 array1.reshape(4,3)

NameError: name 'array1' is not defined

 

# reshape()에 -1 인자값을 부여하여 특정 차원으로 고정된 가변적인 ndarray형태 변환

array1 = np.arange(10)
print(array1)
# -1은 나머지 ROW || COLUMN 을 기준으로 설정하겠다는 마인드
#컬럼 axis 크기는 5에 고정하고 로우 axis크기를 이에 맞춰 자동으로 변환. 즉 2x5 형태로 변환 
array2 = array1.reshape(-1,5)
print('array2 shape:',array2.shape)
print('array2:\n', array2)

#로우 axis 크기는 5로 고정하고 컬럼 axis크기는 이에 맞춰 자동으로 변환. 즉 5x2 형태로 변환 
array3 = array1.reshape(5,-1)
print('array3 shape:',array3.shape)
print('array3:\n', array3)

# [0 1 2 3 4 5 6 7 8 9]
# array2 shape: (2, 5)
# array2:
#  [[0 1 2 3 4]
#  [5 6 7 8 9]]
# array3 shape: (5, 2)
# array3:
#  [[0 1]
#  [2 3]
#  [4 5]
#  [6 7]
#  [8 9]]

 

# reshape()는 (-1, 1), (-1,)와 같은 형태로 주로 사용됨. // 이러면 1차원으로 만들어버림
# 1차원 ndarray를 2차원으로 또는 2차원 ndarray를 1차원으로 변환 시 사용. 

array1 = np.arange(5)

# 1차원 ndarray를 2차원으로 변환하되, 컬럼axis크기는 반드시 1이여야 함. 
array2d_1 = array1.reshape(-1, 1)
print("array2d_1 shape:", array2d_1.shape)
print("array2d_1:\n",array2d_1)

# 2차원 ndarray를 1차원으로 변환 
array1d = array2d_1.reshape(-1,)
print("array1d shape:", array1d.shape)
print("array1d:\n",array1d)

# array2d_1 shape: (5, 1)
# array2d_1:
#  [[0]
#  [1]
#  [2]
#  [3]
#  [4]]
# array1d shape: (5,)
# array1d:
#  [0 1 2 3 4]

 

# -1 을 적용하여도 변환이 불가능한 형태로의 변환을 요구할 경우 오류 발생.

array1 = np.arange(10)
array4 = array1.reshape(-1,4)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-23-a27748faa610> in <module>
      1 # -1 을 적용하여도 변환이 불가능한 형태로의 변환을 요구할 경우 오류 발생.
      2 array1 = np.arange(10)
----> 3 array4 = array1.reshape(-1,4)

ValueError: cannot reshape array of size 10 into shape (4)

 

# 반드시 -1 값은 1개의 인자만 입력해야 함. 모두가 불확정이 되어버림

array1.reshape(-1, -1)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-24-da23572df4ae> in <module>
      1 # 반드시 -1 값은 1개의 인자만 입력해야 함.
----> 2 array1.reshape(-1, -1)

ValueError: can only specify one unknown dimension

 

ndarray의 데이터 세트 선택하기 – 인덱싱(Indexing)

특정 위치의 단일값 추출

# 1에서 부터 9 까지의 1차원 ndarray 생성 
array1 = np.arange(start=1, stop=10)
print('array1:',array1)

# index는 0 부터 시작하므로 array1[2]는 3번째 index 위치의 데이터 값을 의미
value = array1[2]
print('value:',value)
print(type(value))

# array1: [1 2 3 4 5 6 7 8 9]
# value: 3
# <class 'numpy.int32'>

 

print('맨 뒤의 값:',array1[-1], ', 맨 뒤에서 두번째 값:',array1[-2])

# 맨 뒤의 값: 9 , 맨 뒤에서 두번째 값: 8

 

array1[0] = 9
array1[8] = 0
print('array1:',array1)

# array1: [9 2 3 4 5 6 7 8 0]

 

array1d = np.arange(start=1, stop=10)
array2d = array1d.reshape(3,3)
print(array2d)

print('(row=0,col=0) index 가리키는 값:', array2d[0,0] )
print('(row=0,col=1) index 가리키는 값:', array2d[0,1] )
print('(row=1,col=0) index 가리키는 값:', array2d[1,0] )
print('(row=2,col=2) index 가리키는 값:', array2d[2,2] )

# [[1 2 3]
#  [4 5 6]
#  [7 8 9]]
# (row=0,col=0) index 가리키는 값: 1
# (row=0,col=1) index 가리키는 값: 2
# (row=1,col=0) index 가리키는 값: 4
# (row=2,col=2) index 가리키는 값: 9

 

슬라이싱(Slicing) // PYTHON 과 동일

array1 = np.arange(start=1, stop=10)
print(array1)
array3 = array1[0:3]
print(array3)
print(type(array3))

# [1 2 3 4 5 6 7 8 9]
# [1 2 3]
# <class 'numpy.ndarray'>

 

array1 = np.arange(start=1, stop=10)
array4 = array1[:3]
print(array4)

array5 = array1[3:]
print(array5)

array6 = array1[:]
print(array6)

# [1 2 3]
# [4 5 6 7 8 9]
# [1 2 3 4 5 6 7 8 9]

 

array1d = np.arange(start=1, stop=10)
array2d = array1d.reshape(3,3)
print('array2d:\n',array2d)

print('array2d[0:2, 0:2] \n', array2d[0:2, 0:2])
print('array2d[1:3, 0:3] \n', array2d[1:3, 0:3])
print('array2d[1:3, :] \n', array2d[1:3, :])
print('array2d[:, :] \n', array2d[:, :])
print('array2d[:2, 1:] \n', array2d[:2, 1:])
print('array2d[:2, 0] \n', array2d[:2, 0])

# array2d:
#  [[1 2 3]
#  [4 5 6]
#  [7 8 9]]
# array2d[0:2, 0:2] 
#  [[1 2]
#  [4 5]]
# array2d[1:3, 0:3] 
#  [[4 5 6]
#  [7 8 9]]
# array2d[1:3, :] 
#  [[4 5 6]
#  [7 8 9]]
# array2d[:, :] 
#  [[1 2 3]
#  [4 5 6]
#  [7 8 9]]
# array2d[:2, 1:] 
#  [[2 3]
#  [5 6]]
# array2d[:2, 0] 
#  [1 4]

 

** 팬시 인덱싱(fancy indexing) // 불연속 값 가능 **

array1d = np.arange(start=1, stop=10)
array2d = array1d.reshape(3,3)
print(array2d)

array3 = array2d[[0,1], 2]
print('array2d[[0,1], 2] => ',array3.tolist())

array4 = array2d[[0,2], 0:2]
print('array2d[[0,2], 0:2] => ',array4.tolist())

array5 = array2d[[0,1]]
print('array2d[[0,1]] => ',array5.tolist())

array5 = array2d[[0,2], [0,2]]
print('array2d[[0,2], [0,2]] => ',array5.tolist())

# [[1 2 3]
#  [4 5 6]
#  [7 8 9]]
# array2d[[0,1], 2] =>  [3, 6]
# array2d[[0,2], 0:2] =>  [[1, 2], [7, 8]]
# array2d[[0,1]] =>  [[1, 2, 3], [4, 5, 6]]
# array2d[[0,1]] =>  [1, 9]

 

** 불린 인덱싱(Boolean indexing) // FOR IF 조합에 쓰이고, [ 비교연산자 ] 쓰임은 유의**

array1d = np.arange(start=1, stop=10)
print(array1d)

# [1 2 3 4 5 6 7 8 9]

 

print(array1d > 5)

var1 = array1d > 5
print("var1:",var1)
print(type(var1))

# [False False False False False  True  True  True  True]
# var1: [False False False False False  True  True  True  True]
# <class 'numpy.ndarray'>

 

# [ ] 안에 array1d > 5 Boolean indexing을 적용 
print(array1d)
array3 = array1d[array1d > 5]
print('array1d > 5 불린 인덱싱 결과 값 :', array3)

# [1 2 3 4 5 6 7 8 9]
# array1d > 5 불린 인덱싱 결과 값 : [6 7 8 9]

 

boolean_indexes = np.array([False, False, False, False, False,  True,  True,  True,  True])
array3 = array1d[boolean_indexes] # TRUE 값을 출력
print('불린 인덱스로 필터링 결과 :', array3)

# 불린 인덱스로 필터링 결과 : [6 7 8 9]

 

indexes = np.array([5,6,7,8])
array4 = array1d[ indexes ] # TRUE 값을 출력
print('일반 인덱스로 필터링 결과 :',array4)

# 일반 인덱스로 필터링 결과 : [6 7 8 9]

 

array1d = np.arange(start=1, stop=10)
target = []

for i in range(0, 9):
    if array1d[i] > 5:
        target.append(array1d[i])

array_selected = np.array(target)
print(array_selected)

# [6 7 8 9]

 

print(array1d[array1 > 5])

# [6 7 8 9]

 

행렬의 정렬 – sort( )와 argsort( )

  • 행렬 정렬
org_array = np.array([ 3, 1, 9, 5]) 
print('원본 행렬:', org_array)

# np.sort( )로 정렬 
sort_array1 = np.sort(org_array)         
print ('np.sort( ) 호출 후 반환된 정렬 행렬:', sort_array1) 
print('np.sort( ) 호출 후 원본 행렬:', org_array)

# ndarray.sort( )로 정렬
sort_array2 = org_array.sort()
org_array.sort()
print('org_array.sort( ) 호출 후 반환된 행렬:', sort_array2)
print('org_array.sort( ) 호출 후 원본 행렬:', org_array)

# 원본 행렬: [3 1 9 5]
# np.sort( ) 호출 후 반환된 정렬 행렬: [1 3 5 9]
# np.sort( ) 호출 후 원본 행렬: [3 1 9 5]
# org_array.sort( ) 호출 후 반환된 행렬: None
# org_array.sort( ) 호출 후 원본 행렬: [1 3 5 9]

 

sort_array1_desc = np.sort(org_array)[::-1]
print ('내림차순으로 정렬:', sort_array1_desc) 

# 내림차순으로 정렬: [9 5 3 1]

 

array2d = np.array([[8, 12], 
                   [7, 1 ]])

sort_array2d_axis0 = np.sort(array2d, axis=0)
print('로우 방향으로 정렬:\n', sort_array2d_axis0)

sort_array2d_axis1 = np.sort(array2d, axis=1)
print('컬럼 방향으로 정렬:\n', sort_array2d_axis1)

# 로우 방향으로 정렬:
#  [[ 7  1]
#  [ 8 12]]
# 컬럼 방향으로 정렬:
#  [[ 8 12]
#  [ 1  7]]

 

  • argsort
org_array = np.array([ 3, 1, 9, 5]) 
print(np.sort(org_array))
 
sort_indices = np.argsort(org_array)
print(type(sort_indices))
print('행렬 정렬 시 원본 행렬의 인덱스:', sort_indices)

# [1 3 5 9]
# <class 'numpy.ndarray'>
# 행렬 정렬 시 원본 행렬의 인덱스: [1 0 3 2]

 

org_array = np.array([ 3, 1, 9, 5]) 
print(np.sort(org_array)[::-1])

sort_indices_desc = np.argsort(org_array)[::-1]
print('행렬 내림차순 정렬 시 원본 행렬의 인덱스:', sort_indices_desc)

# [9 5 3 1]
# 행렬 내림차순 정렬 시 원본 행렬의 인덱스: [2 3 0 1]

 

key-value 형태의 데이터를 John=78, Mike=95, Sarah=84, Kate=98, Samuel=88을 ndarray로 만들고 argsort()를 이용하여 key값을 정렬

name_array=np.array(['John', 'Mike', 'Sarah', 'Kate', 'Samuel'])
score_array=np.array([78, 95, 84, 98, 88])
# MAPING의 편법으로 운용
# score_array의 정렬된 값에 해당하는 원본 행렬 위치 인덱스 반환하고 이를 이용하여 name_array에서 name값 추출.  
sort_indices = np.argsort(score_array)
print("sort indices:", sort_indices)

name_array_sort = name_array[sort_indices]

score_array_sort = score_array[sort_indices]
print(name_array_sort)
print(score_array_sort)

# sort indices: [0 2 4 1 3]
# ['John' 'Sarah' 'Samuel' 'Mike' 'Kate']
# [78 84 88 95 98]

 

선형대수 연산 – 행렬 내적과 전치 행렬 구하기

  • 행렬 내적
A = np.array([[1, 2, 3],
              [4, 5, 6]])
B = np.array([[7, 8],
              [9, 10],
              [11, 12]])

dot_product = np.dot(A, B)
print('행렬 내적 결과:\n', dot_product)

# 행렬 내적 결과:
#  [[ 58  64]
#  [139 154]]

 

  • 전치 행렬
A = np.array([[1, 2, 4],
              [4, 5, 6]])
transpose_mat = np.transpose(A)
print('A의 전치 행렬:\n', transpose_mat)

# A의 전치 행렬:
#  [[1 4]
#  [2 5]
#  [4 6]]

 

반응형

'Data_Science > ML_Perfect_Guide' 카테고리의 다른 글

2-3. model selection || sklearn  (0) 2021.12.22
2-2. sklearn 내장 데이터 || iris  (0) 2021.12.22
2-1. iris || sklearn  (0) 2021.12.22
1-3. Pandas 2  (0) 2021.12.22
1-2. Pandas  (0) 2021.12.22
728x90
반응형
import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, LSTM, Embedding, Bidirectional

 

 

vocab_size = 15000

def create_model() :
    model = Sequential([
        Embedding(vocab_size, 32),
        Bidirectional(LSTM(32, return_sequences=True)),
        Dense(32, activation='relu'),
        Dense(1, activation='sigmoid')
    ])
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    return model

 

 

import pandas as pd
test_file = tf.keras.utils.get_file('ratings_test.txt',\
            origin='https://raw.githubusercontent.com/e9t/nsmc/master/ratings_test.txt', extract=True)
test = pd.read_csv(test_file, sep='\t')
test.head()


id	document	label
0	6270596	굳 ㅋ	1
1	9274899	GDNTOPCLASSINTHECLUB	0
2	8544678	뭐야 이 평점들은.... 나쁘진 않지만 10점 짜리는 더더욱 아니잖아	0
3	6825595	지루하지는 않은데 완전 막장임... 돈주고 보기에는....	0
4	6723715	3D만 아니었어도 별 다섯 개 줬을텐데.. 왜 3D로 나와서 제 심기를 불편하게 하죠??	0

 

 

test.shape 
# (50000, 3)

 

 

import konlpy
from konlpy.tag import Okt
okt = Okt()

train_file = tf.keras.utils.get_file('ratings_train.txt',\
            origin='https://raw.githubusercontent.com/e9t/nsmc/master/ratings_train.txt', extract=True)
train = pd.read_csv(train_file, sep='\t')
train.head()

id	document	label
0	9976970	아 더빙.. 진짜 짜증나네요 목소리	0
1	3819312	흠...포스터보고 초딩영화줄....오버연기조차 가볍지 않구나	1
2	10265843	너무재밓었다그래서보는것을추천한다	0
3	9045019	교도소 이야기구먼 ..솔직히 재미는 없다..평점 조정	0
4	6483659	사이몬페그의 익살스런 연기가 돋보였던 영화!스파이더맨에서 늙어보이기만 했던 커스틴 ...	1

 

 

train['document'] = train['document'].str.replace("[^A-Za-z가-힣ㄱ-ㅎㅏ-ㅣ]","")
train = train.dropna()

 

 

def word_tokenization(text) :
    stop_words = ['는','을','를','이','가','의','던','고','하','다','은','에','들','지','게','도']
    return [word for word in okt.morphs(text) if word not in stop_words]

 

 

data = train['document'].apply((lambda x : word_tokenization(x)))
data.head()

0                              [아더, 빙, 진짜, 짜증나네요, 목소리]
1        [흠, 포스터, 보고, 초딩, 영화, 줄, 오버, 연기, 조차, 가볍지, 않구나]
2                     [너, 무재, 밓었, 다그, 래서, 보는것을, 추천, 한]
3                  [교도소, 이야기, 구먼, 솔직히, 재미, 없다, 평점, 조정]
4    [사이, 몬페, 그, 익살스런, 연기, 돋보였던, 영화, 스파이더맨, 에서, 늙어,...
Name: document, dtype: object

 

 

from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences

 

 

oov_tok = "<OOV>"
vovab_size = 15000
tokenizer = Tokenizer(oov_token = oov_tok, num_words=vocab_size)
tokenizer.fit_on_texts(data)

 


테스트 데이터 전처리
1. 한글, 영문, 공백 제외한 모든 문자 제거
2. 결측값 제거
3. 테스트할 데이터, 레이블 데이터 분리
4. 테스트할 데이터 불용어 부분제거
5. tokenizer를 이용하여 분석할 수 있는 데이터로 변경
6. 패딩하기

import numpy as np
def preprocessing(df) :
    df['document'] = df['document'].str.replace("[^A-Za-z가-힣ㄱ-ㅎㅏ-ㅣ]","")
    df = df.dropna()
    test_label = np.asarray(df['label'])
    test_data = df['document'].apply((lambda x : word_tokenization(x)))
    test_data = tokenizer.texts_to_sequences(test_data)
    test_data = pad_sequences(test_data, padding='post', maxlen=69)
    return test_data, test_label

 

 

test_data, test_label = preprocessing(test)
test_data[2:3]
test_label[2:3]


# array([0], dtype=int64)

 

 

# 평가
model2 = create_model()
model2.evaluate(test_data, test_label)



1563/1563 [==============================] - 6s 3ms/step - loss: 0.6931 - accuracy: 0.5039
[0.6931077837944031, 0.5039322972297668]

 

 

# 저장된 모델을 로드 후 평가하기
checkpoint_path = 'best_performed_model.ckpt'
model2.load_weights(checkpoint_path)
model2.evaluate(test_data, test_label)



1563/1563 [==============================] - 4s 3ms/step - loss: 1.1676 - accuracy: 0.4926
[1.1676305532455444, 0.49262505769729614]

 

print("감동 ==>>", tokenizer.word_index['감동'])
print("영화 ==>>", tokenizer.word_index['영화'])
print("나나 ==>>", tokenizer.word_index['나나'])



감동 ==>> 28
영화 ==>> 2
나나 ==>> 3533

 

반응형

'Data_Science > Data_Analysis_Py' 카테고리의 다른 글

61. 네이버 영화리뷰 || LSTM  (0) 2021.12.07
60. LSTM 기본  (0) 2021.12.07
58. IMDB || SimpleRNN  (0) 2021.12.07
57. seed || simpleRNN  (0) 2021.12.07
56. 영화리뷰 분석  (0) 2021.12.07
728x90
반응형

네이버 영화 리뷰 데이터

import pandas as pd 
import numpy as np 
import seaborn as sns 
import matplotlib.pyplot as plt 
import tensorflow as tf

 

train_file = tf.keras.utils.get_file('ratings_train.txt', \ 
origin='https://raw.githubusercontent.com/e9t/nsmc/master/ratings_train.txt',\ 
extract=True) 








Downloading data from https://raw.githubusercontent.com/e9t/nsmc/master/ratings_train.txt 
14630912/14628807 [==============================] - 0s 0us/step

 

train = pd.read_csv(train_file, sep='\t') 
train.head() 
print("train shape:", train.shape) 


# train shape: (150000, 3)

레이블별 갯수 출력하기


train['label'].value_counts() 
sns.countplot(x='label', data=train)

결측값


train.isnull().sum() 
train[train['document'].isnull()] 
# 결측값 제거 
train = train.dropna() 
print("train shape:",train.shape) 




# train shape: (149995, 3)


레이블 별 글자수의 분포를 히스토그램으로 출력

# 레이블 별 글자수의 분포를 히스토그램으로 출력 
# 긍정의 글자수 
postive_len = train[train['label']==1]['document'].str.len() 
# 부정의 글자수 
negative_len = train[train['label']==0]['document'].str.len() 
postive_len.iloc[:10] 




1 33 4 61 8 22 9 45 10 16 11 43 13 51 15 16 16 64 18 45 Name: document, dtype: int64

 

fig, (ax1, ax2) = plt.subplots(1,2,figsize=(10,5)) 
ax1.hist(postive_len) 
ax1.set_title("positive") 
ax2.hist(negative_len) 
ax2.set_title("negative") 
fig.suptitle("Number of characters") 
plt.show()

형태소 분석하기

text = '한글 자연어 처리는 재밌다. 이제부터 열심히 해야지ㅎㅎㅎㅎ' 
okt.morphs(text)
# 형태소 분리 
okt.morphs(text, stem=True)
# 행태소로 분리, 어간 추출 
okt.nouns(text)
# 명사만 추출 
okt.phrases(text)
# 어절까지추출 
okt.pos(text) 
# 품살르 붙여서 형태소 분석



[('한글', 'Noun'), ('자연어', 'Noun'), ('처리', 'Noun'), ('는', 'Josa'), ('재밌다', 'Adjective'), ('.', 'Punctuation'), ('이제', 'Noun'), ('부터', 'Josa'), ('열심히', 'Adverb'), ('해야지', 'Verb'), ('ㅎㅎㅎㅎ', 'KoreanParticle')]

 

# 데이터 전처리

# 텍스트의 내용 중 한글, 영문, 공백을 제외한 다른 문자들은 제거

train['document'] = \ train['document'].str.replace("[^A-Za-z가-힣ㄱ-ㅎㅏ-ㅣ]","") 
train['document'].head() 


0 아더빙진짜짜증나네요목소리 
1 흠포스터보고초딩영화줄오버연기조차가볍지않구나 
2 너무재밓었다그래서보는것을추천한다 
3 교도소이야기구먼솔직히재미는없다평점조정 
4 사이몬페그의익살스런연기가돋보였던영화스파이더맨에서늙어보이기만했던커스틴던스트가너무나도이... 
Name: document, dtype: object


형태소 분석. stopword 제거 후 형태소 분석하기

def word_tokenization(text) : 
    # 한글 불용어 
    stop_words = ['는','을','를','이','가','의','던','고','하','다','은','에','들','지','게','도'] 
    return [word for word in okt.morphs(text) if word not in stop_words]

 

start = time.time() 
data = train['document'].apply((lambda x : word_tokenization(x))) 
print("실행시간 :", time.time()-start) 
data.head() 



실행시간 : 1631.960827589035 
0 [아더, 빙, 진짜, 짜증나네요, 목소리] 
1 [흠, 포스터, 보고, 초딩, 영화, 줄, 오버, 연기, 조차, 가볍지, 않구나] 
2 [너, 무재, 밓었, 다그, 래서, 보는것을, 추천, 한] 
3 [교도소, 이야기, 구먼, 솔직히, 재미, 없다, 평점, 조정] 
4 [사이, 몬페, 그, 익살스런, 연기, 돋보였던, 영화, 스파이더맨, 에서, 늙어,... 
Name: document, dtype: object

 

from tensorflow.keras.preprocessing.text import Tokenizer 
from tensorflow.keras.preprocessing.sequence 
import pad_sequences 
tokenizer = Tokenizer() tokenizer.fit_on_texts(data) 
print("총 단어 갯수:", len(tokenizer.word_index)) 
# 총 단어 갯수: 122402


5회 이상만 vocab_size 에 포함

def get_vocab_size(threshold) : 
	cnt = 0 
    for x in tokenizer.word_counts.values() : 
    	if x >=threshold : 
        	cnt += 1 
    return cnt

 

vocab_size = get_vocab_size(5) 

# 5회 이상 출현단어 

print("vocab_size:",vocab_size) 
# vocab_size: 23384

 

훈련 데이터 검증데이터 분리

training_size = 120000 
#train 분할 
train_sentences = data[:training_size] 
valid_sentences = data[training_size:] 
# label 분할 
train_labels = train['label'][:training_size] 
valid_labels = train['label'][training_size:]

 

print(train_sentences.shape) 
print(valid_sentences.shape) 


(120000,) 

(29995,)


토큰화하기

oov_tok = "<OOV>" 
vovab_size = 15000 
tokenizer = Tokenizer(oov_token = oov_tok, num_words=vocab_size) 
tokenizer.fit_on_texts(data) print("단어사전개수:",len(tokenizer.word_counts)) 
# 단어사전개수: 122402


문자를 숫자로 표현

print(train_sentences[:2]) 
train_sequences = tokenizer.texts_to_sequences(train_sentences) 
valid_sequences = tokenizer.texts_to_sequences(valid_sentences) 
print(train_sequences[:2]) print(valid_sequences[:2]) 

0 [아더, 빙, 진짜, 짜증나네요, 목소리] 
1 [흠, 포스터, 보고, 초딩, 영화, 줄, 오버, 연기, 조차, 가볍지, 않구나] 
Name: document, dtype: object 
[[13657, 16287, 8, 6835, 615], [1005, 423, 33, 554, 2, 354, 1539, 20, 1044, 6416, 1]] [[277, 9, 299, 208, 3401, 23332, 860, 9, 908, 178, 11017, 877, 3, 156, 48], [381, 158, 2, 487, 193, 2437, 38, 57, 259, 10630, 1, 33, 13153, 2, 72]]


문자의 최대길이

max_length = max(len(x) for x in train_sequences) 
print("문자 최대 길이:", max_length) 

# 문자 최대 길이: 69

 

train_padded = pad_sequences(train_sequences, padding = 'post', maxlen=max_length) 
valid_padded = pad_sequences(valid_sequences, padding = 'post', maxlen=max_length) 
train_padded[:1] 


array([[13657, 16287, 8, 6835, 615, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])

 

모델 구성하기

import tensorflow as tf 
from tensorflow.keras import Sequential 
from tensorflow.keras.layers import Dense, LSTM, Embedding, Bidirectional

 

def create_model() :
	# bi 양방향 rnn 
	# return_sequences=True 상대값 전달 
	model = Sequential([ Embedding(vocab_size, 32), 
                     Bidirectional(LSTM(32, return_sequences=True)), 
                     Dense(32, activation='relu'), 
                     Dense(1, activation='sigmoid') ]) 

	model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) 
    return model

 

model = create_model()
model.summary()


Model: "sequential_1"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
embedding (Embedding)        (None, None, 32)          748288    
_________________________________________________________________
bidirectional_1 (Bidirection (None, None, 64)          16640     
_________________________________________________________________
dense_2 (Dense)              (None, None, 32)          2080      
_________________________________________________________________
dense_3 (Dense)              (None, None, 1)           33        
=================================================================
Total params: 767,041
Trainable params: 767,041
Non-trainable params: 0
_________________________________________________________________


딥러닝 모델의 구조가 복잡하고, 데이터 크기가 클수록 학습시간이 오래걸림.
=> 오랜시간 학습한 모델을 저장할 필요가 있음. modelcheckpoint 함수 이용
save_weights_only=True : weight 만저장
save_weights_only=False : 모델 레이터와 weight 모두 저장
save_best_only = True : 좋은 가중치만 저장
save_best_only = False : 모든 가중치 저장

checkpoint_path = 'best_performed_model.ckpt'
checkpoint = tf.keras.callbacks.ModelCheckpoint(checkpoint_path,
save_weights_only=True,
save_best_only = True,
monitor = 'val_loss', verbose=1)


earlystopping 함수 : 모델의 성능이 개선되지 않을 경우 학습을 중단
monitor = 'val_loss' : 성능평가 기준
patience=2 : 2 epochs 까지 개선되지 않으면 중지
call back : 함수에서 호출되는 함수

early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss',patience=2)

 

학습하기

history = model.fit(train_padded, train_labels, validation_data=(valid_padded, valid_labels),
                   callbacks=[early_stop, checkpoint],
                   batch_size=64, epochs=10, verbose=2)
                   
                   
Epoch 1/10
1875/1875 - 31s - loss: 0.4138 - accuracy: 0.8022 - val_loss: 0.3530 - val_accuracy: 0.8437

Epoch 00001: val_loss improved from inf to 0.35297, saving model to best_performed_model.ckpt
Epoch 2/10
1875/1875 - 24s - loss: 0.3111 - accuracy: 0.8652 - val_loss: 0.3561 - val_accuracy: 0.8424

Epoch 00002: val_loss did not improve from 0.35297
Epoch 3/10
1875/1875 - 24s - loss: 0.2710 - accuracy: 0.8824 - val_loss: 0.3645 - val_accuracy: 0.8445

Epoch 00003: val_loss did not improve from 0.35297

 

def plot_graphs(history, metric) :
    plt.plot(history.history[metric])
    plt.plot(history.history['val_'+metric], '')
    plt.xlabel('Epochs')
    plt.ylabel(metric)
    plt.legend([metric, 'val_'+metric])
    plt.show()

 

plot_graphs(history, 'accuracy') 
plot_graphs(history, 'loss')

반응형

'Data_Science > Data_Analysis_Py' 카테고리의 다른 글

62. Tokenizer  (0) 2021.12.07
60. LSTM 기본  (0) 2021.12.07
58. IMDB || SimpleRNN  (0) 2021.12.07
57. seed || simpleRNN  (0) 2021.12.07
56. 영화리뷰 분석  (0) 2021.12.07
728x90
반응형

Long Short Term Memory
한글 분석하기
한글 형태소 분석기
kkma
komoran
okt
hannanum

 

 

import konlpy
from konlpy.tag import Kkma, Komoran, Okt, Hannanum
import time
kkma = Kkma()
komoran = Komoran()
okt = Okt()
hannanum = Hannanum()

 

def sample_ko_pos(text) :
    print(f"==={text}===")
    start = time.time()
    print("kkma:",kkma.pos(text),",실행시간:",time.time()-start)
    start = time.time()
    print("komoran:",komoran.pos(text),",실행시간:",time.time()-start)
    start = time.time()
    print("okt:",okt.pos(text),",실행시간:",time.time()-start)
    start = time.time()
    print("hannanum:",hannanum.pos(text),",실행시간:",time.time()-start)
    print('\n')

 

# 띄어쓰기 가 올바르지 않은 문장
text1 = '영실아안녕오늘날씨어때?'
sample_ko_pos(text1)

===영실아안녕오늘날씨어때?===
kkma: [('영', 'MAG'), ('싣', 'VV'), ('아', 'ECD'), ('안녕', 'NNG'), ('오늘날', 'NNG'), ('씨', 'VV'), ('어', 'ECD'), ('때', 'NNG'), ('?', 'SF')] ,실행시간: 3.219935178756714
komoran: [('영', 'NNP'), ('실', 'NNP'), ('아', 'NNP'), ('안녕', 'NNP'), ('오늘날', 'NNP'), ('씨', 'NNB'), ('어떻', 'VA'), ('어', 'EF'), ('?', 'SF')] ,실행시간: 0.004001617431640625
okt: [('영', 'Modifier'), ('실아', 'Noun'), ('안녕', 'Noun'), ('오늘날', 'Noun'), ('씨', 'Suffix'), ('어때', 'Adjective'), ('?', 'Punctuation')] ,실행시간: 2.025106191635132
hannanum: [('영실아안녕오늘날씨어때', 'N'), ('?', 'S')] ,실행시간: 0.5730204582214355

 

# 오타가 있는 문장
text2 = '안녕ㅎㅏㅅㅔ여 ㅈㅓ는ㄷㅐ학생 입니다.'
sample_ko_pos(text2)


===안녕ㅎㅏㅅㅔ여 ㅈㅓ는ㄷㅐ학생 입니다.===
kkma: [('안녕ㅎㅏㅅㅔ', 'UN'), ('여', 'JKI'), ('ㅈ', 'NNG'), ('ㅓ', 'UN'), ('는', 'JX'), ('ㄷ', 'NNG'), ('ㅐ', 'UN'), ('학생', 'NNG'), ('이', 'VCP'), ('ㅂ니다', 'EFN'), ('.', 'SF')] ,실행시간: 0.0388941764831543
komoran: [('안녕', 'NNP'), ('하', 'NNP'), ('세', 'NNB'), ('이', 'VCP'), ('어', 'EC'), ('저', 'NP'), ('는', 'JX'), ('대학생', 'NNG'), ('이', 'VCP'), ('ㅂ니다', 'EF'), ('.', 'SF')] ,실행시간: 0.0010001659393310547
okt: [('안녕', 'Noun'), ('ㅎㅏㅅㅔ', 'KoreanParticle'), ('여', 'Noun'), ('ㅈㅓ', 'KoreanParticle'), ('는', 'Verb'), ('ㄷㅐ', 'KoreanParticle'), ('학생', 'Noun'), ('입니다', 'Adjective'), ('.', 'Punctuation')] ,실행시간: 0.00400090217590332
hannanum: [('안녕ㅎㅏㅅㅔ', 'N'), ('이', 'J'), ('어', 'E'), ('ㅈㅓ는ㄷㅐ학생', 'N'), ('일', 'P'), ('ㅂ니다', 'E'), ('.', 'S')] ,실행시간: 0.0020003318786621094

 

text3 = "정말 재미있고 매력적인 영화에요 추천합니다."
sample_ko_pos(text3)

===정말 재미있고 매력적인 영화에요 추천합니다.===
kkma: [('정말', 'MAG'), ('재미있', 'VA'), ('고', 'ECE'), ('매력적', 'NNG'), ('이', 'VCP'), ('ㄴ', 'ETD'), ('영화', 'NNG'), ('에', 'JKM'), ('요', 'JX'), ('추천', 'NNG'), ('하', 'XSV'), ('ㅂ니다', 'EFN'), ('.', 'SF')] ,실행시간: 0.01355123519897461
komoran: [('정말', 'MAG'), ('재미있', 'VA'), ('고', 'EC'), ('매력', 'NNG'), ('적', 'XSN'), ('이', 'VCP'), ('ㄴ', 'ETM'), ('영화', 'NNG'), ('에', 'JKB'), ('요', 'JX'), ('추천', 'NNG'), ('하', 'XSV'), ('ㅂ니다', 'EF'), ('.', 'SF')] ,실행시간: 0.002000093460083008
okt: [('정말', 'Noun'), ('재미있고', 'Adjective'), ('매력', 'Noun'), ('적', 'Suffix'), ('인', 'Josa'), ('영화', 'Noun'), ('에요', 'Josa'), ('추천', 'Noun'), ('합니다', 'Verb'), ('.', 'Punctuation')] ,실행시간: 0.009005308151245117
hannanum: [('정말', 'M'), ('재미있', 'P'), ('고', 'E'), ('매력적', 'N'), ('이', 'J'), ('ㄴ', 'E'), ('영화', 'N'), ('이', 'J'), ('에요', 'E'), ('추천', 'N'), ('하', 'X'), ('ㅂ니다', 'E'), ('.', 'S')] ,실행시간: 0.003000497817993164

 

반응형

'Data_Science > Data_Analysis_Py' 카테고리의 다른 글

62. Tokenizer  (0) 2021.12.07
61. 네이버 영화리뷰 || LSTM  (0) 2021.12.07
58. IMDB || SimpleRNN  (0) 2021.12.07
57. seed || simpleRNN  (0) 2021.12.07
56. 영화리뷰 분석  (0) 2021.12.07

+ Recent posts