OkBublewrap

Human Activity Recognition 본문

Python/프로젝트

Human Activity Recognition

옥뽁뽁 2022. 10. 6. 21:45

Data Set

https://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones 

 

UCI Machine Learning Repository: Human Activity Recognition Using Smartphones Data Set

Human Activity Recognition Using Smartphones Data Set Download: Data Folder, Data Set Description Abstract: Human Activity Recognition database built from the recordings of 30 subjects performing activities of daily living (ADL) while carrying a waist-moun

archive.ics.uci.edu

features.txt

from google.colab import drive
drive.mount('/content/drive')

# packages
import pandas as pd
import matplotib.pyplot as plt
%matplotlib inline

feature_name_df = pd.read_csv('human_activity/features.txt',  sep='\s+', 
                        header=None, names=['column_index','column_name'])
                        
feature_name_df.head()

feature_name_df.head(5)

중복된 피쳐명 확인

# 중복된 피쳐명 확인
feature_dup_df = feature_name_df.groupby('column_name').count()
print(feature_dup_df[feature_dup_df['column_index'] > 1].count())
feature_dup_df[feature_dup_df['column_index']>1].head()

feature_dup_df[feature_dup_df['column_index']>1].head()

42개 피쳐명이 중복, get_new_feature_name_df()으로 _1,_2,_3으로 변환

def get_new_feature_name_df(old_feature_name_df):
    feature_dup_df = pd.DataFrame(data=old_feature_name_df.groupby('column_name').cumcount(),
                                  columns=['dup_cnt'])
    feature_dup_df = feature_dup_df.reset_index()
    new_feature_name_df = pd.merge(old_feature_name_df.reset_index(), feature_dup_df, how='outer')
    new12 = (lambda x : x[0]+'_'+str(x[1]) if x[1] >0 else x[0]) 
    new_feature_name_df['column_name'] = new_feature_name_df[['column_name', 'dup_cnt']].apply(new12,  axis=1)
    new_feature_name_df = new_feature_name_df.drop(['index'], axis=1)
    return new_feature_name_df
import pandas as pd

def get_human_dataset( ):
    
    # 각 데이터 파일들은 공백으로 분리되어 있으므로 read_csv에서 공백 문자를 sep으로 할당.
    feature_name_df = pd.read_csv('/content/drive/MyDrive/python_ksu/human_activity/features.txt',sep='\s+',
                        header=None,names=['column_index','column_name'])
    
    # 중복된 피처명을 수정하는 get_new_feature_name_df()를 이용, 신규 피처명 DataFrame생성. 
    new_feature_name_df = get_new_feature_name_df(feature_name_df)
    
    # DataFrame에 피처명을 컬럼으로 부여하기 위해 리스트 객체로 다시 변환
    feature_name = new_feature_name_df.iloc[:, 1].values.tolist()
    
    # 학습 피처 데이터 셋과 테스트 피처 데이터을 DataFrame으로 로딩. 컬럼명은 feature_name 적용
    X_train = pd.read_csv('/content/drive/MyDrive/python_ksu/human_activity/train/X_train.txt',sep='\s+', names=feature_name )
    X_test = pd.read_csv('/content/drive/MyDrive/python_ksu/human_activity/test/X_test.txt',sep='\s+', names=feature_name)
    
    # 학습 레이블과 테스트 레이블 데이터을 DataFrame으로 로딩하고 컬럼명은 action으로 부여
    y_train = pd.read_csv('/content/drive/MyDrive/python_ksu/human_activity/train/y_train.txt',sep='\s+',header=None, names=['action'])
    y_test = pd.read_csv('/content/drive/MyDrive/python_ksu/human_activity/test/y_test.txt',sep='\s+',header=None, names=['action'])
    
    # 로드된 학습/테스트용 DataFrame을 모두 반환 
    return X_train, X_test, y_train, y_test

데이터 훝어보기

print('## 학습 피처 데이터셋 info()')
print(X_train.info())

## 학습 피처 데이터셋 info()

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

RangeIndex: 7352 entries, 0 to 7351

Columns: 561 entries, tBodyAcc-mean()-X to angle(Z,gravityMean)

dtypes: float64(561)

memory usage: 31.5 MB

None

 

학습데이터 7352개 레코드, 561개 피처

print(y_train['action'].value_counts())

6 1407

5 1374

4 1286

1 1226

2 1073

3 986

Name: action, dtype: int64

 

레이블은 총 6개

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

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

# DecisionTreeClassifier의 하이퍼 파라미터 추출
print('DecisionTreeClassifier 기본 하이퍼 파라미터:\n', dt_clf.get_params())

결정 트리 예측 정확도: 0.8548 DecisionTreeClassifier 기본 하이퍼 파라미터: {'ccp_alpha': 0.0, 'class_weight': None, 'criterion': 'gini', 'max_depth': None, 'max_features': None, 'max_leaf_nodes': None, 'min_impurity_decrease': 0.0, 'min_samples_leaf': 1, 'min_samples_split': 2, 'min_weight_fraction_leaf': 0.0, 'random_state': 156, 'splitter': 'best'}

 

결정 트리 예측 정확도는 0.8548으로 나왔다. min_samples_leaf : 1, min_samples_split : 2

 

최적의 모델 찾기 GridSearchCV

from sklearn.model_selection import GridSearchCV

params = {'max_depth' : [ 6, 8 ,10, 12, 16 ,20, 24]}

grid_cv = GridSearchCV(dt_clf, param_grid=params, scoring='accuracy', cv=5, verbose=1)
grid_cv.fit(X_train , y_train)
print('GridSearchCV 최고 평균 정확도 수치:{0:.4f}'.format(grid_cv.best_score_))
print('GridSearchCV 최적 하이퍼 파라미터:', grid_cv.best_params_)

max_depth : 최대 나무 깊이 6, 8, 10, 12, 16, 20, 24

Fitting 5 folds for each of 7 candidates, totalling 35 fits

GridSearchCV 최고 평균 정확도 수치:0.8513

GridSearchCV 최적 하이퍼 파라미터: {'max_depth': 16}

 

최적 하이퍼 파라미터는 max_depth이 16으로 나왔다.16으로 했을 때 정확도 수치가 0.8513으로 나왔다.

cv_results_df = pd.DataFrame(grid_cv.cv_results_)
cv_results_df[['param_max_depth', 'mean_test_score']]

max_depth = 6 정확도: 0.8558

max_depth = 8 정확도: 0.8707

max_depth = 10 정확도: 0.8673

max_depth = 12 정확도: 0.8646

max_depth = 16 정확도: 0.8575

max_depth = 20 정확도: 0.8548

max_depth = 24 정확도: 0.8548

params = {
    'max_depth' : [ 8 , 12, 16 ,20], 
    'min_samples_split' : [16,24],
}

grid_cv = GridSearchCV(dt_clf, param_grid=params, scoring='accuracy', cv=5, verbose=1 )
grid_cv.fit(X_train , y_train)
print('GridSearchCV 최고 평균 정확도 수치: {0:.4f}'.format(grid_cv.best_score_))
print('GridSearchCV 최적 하이퍼 파라미터:', grid_cv.best_params_)

Fitting 5 folds for each of 8 candidates, totalling 40 fits

GridSearchCV 최고 평균 정확도 수치: 0.8549

GridSearchCV 최적 하이퍼 파라미터: {'max_depth': 8, 'min_samples_split': 16}

 

최대나무깊이는 8, 최소 샘플수는 16이였을 때 0.8549가 나왔다.

 

best_df_clf = grid_cv.best_estimator_
pred1 = best_df_clf.predict(X_test)
accuracy = accuracy_score(y_test , pred1)
print('결정 트리 예측 정확도:{0:.4f}'.format(accuracy))

결정 트리 예측 정확도:0.8717

import seaborn as sns

ftr_importances_values = best_df_clf.feature_importances_
# Top 중요도로 정렬을 쉽게 하고, 시본(Seaborn)의 막대그래프로 쉽게 표현하기 위해 Series변환
ftr_importances = pd.Series(ftr_importances_values, index=X_train.columns  )
# 중요도값 순으로 Series를 정렬
ftr_top20 = ftr_importances.sort_values(ascending=False)[:20]
plt.figure(figsize=(8,6))
plt.title('Feature importances Top 20')
sns.barplot(x=ftr_top20 , y = ftr_top20.index)
plt.show()

변수중요도

사람 행동에서는 tGravityAcc-min, fBodyAccjerk-bandsenergy 순으로 나왔다.

'Python > 프로젝트' 카테고리의 다른 글

실전 데이터 분석 프로젝트(3)  (0) 2023.03.24
실전 데이터 분석 프로젝트(2)  (0) 2023.03.22
실전 데이터 분석 프로젝트(1)  (0) 2023.03.21
wine_modeling(1)  (0) 2023.03.05
Wine_EDA  (0) 2023.02.22