• 5주차 과제 : Random Forest

    image image

    • 사용 언어 : python
    • 해결 날짜 : 2021-10-17
    • 코드 설명 :

      • pandas의 read_csv 함수로 wdbc.data 파일을 읽어오고, 2열 이후의 값들은 data로, 2열의 값들은 target으로 설정한다.
      • train_test_split 함수로 data와 target을 3:1로 랜덤하게 분리한다.
      • decision tree, Random Forest(5), Random Forest(100)를 각 classifier로 생성 후 cross_val_score 함수를 통해 5-cross validation을 진행한 다음 평균을 프린트하였다.
      • 그 결과 트리의 개수가 100개인 Random Forest 방식의 성능이 가장 높았기 때문에 트리의 개수가 100개인 랜덤 포레스트에 데이터를 학습시키고, score 함수로 Test data에 대한 성능을 측정하였다.
    • 결과 : image

    • 코드

      #!/usr/bin/env python
      # coding: utf-8
      
      # In[63]:
      import pandas as pd
      from sklearn.tree import DecisionTreeClassifier
      from sklearn.ensemble import RandomForestClassifier
      from sklearn.model_selection import train_test_split
      from sklearn.model_selection import cross_val_score
      
      datas = pd.read_csv('wdbc.data', header = None)
      data = datas.iloc[:, 2:]
      target = datas.iloc[:, 1]
      train_input, test_input, train_target, test_target = train_test_split(data, target, random_state = 0)
      
      # decision tree
      tree = DecisionTreeClassifier(random_state=0)
      score = cross_val_score(tree, train_input, train_target, cv=5)
      print("한 개의 DecisionTree일 때 교차 검증 점수 평균 : " + str(score.mean()))
      
      # Random Forest (트리 개수 5개)
      forest_1 = RandomForestClassifier(n_estimators=1, random_state=0)
      score_1 = cross_val_score(forest_1, train_input, train_target, cv=5)
      print("트리 개수 5개인 RandomForest일 때 교차 검증 점수 평균 : " + str(score_1.mean()))
      
      # Random Forest (트리 개수 100개)
      forest_100 = RandomForestClassifier(n_estimators=100, random_state=0)
      score_100 = cross_val_score(forest_100, train_input, train_target, cv=5)
      print("트리 개수 100개인 RandomForest일 때 교차 검증 점수 평균 : " + str(score_100.mean()))
      
      forest_100.fit(train_input, train_target)
      print("Test Data에 대한 성능 : " + str(forest_100.score(test_input, test_target)))