데이터과학 삼학년

tensorflow_decision_forests 를 이용해서 손쉽게 RandomForest, GBM 사용하기 본문

Machine Learning

tensorflow_decision_forests 를 이용해서 손쉽게 RandomForest, GBM 사용하기

Dan-k 2022. 6. 28. 20:39
반응형

tensorflow_decision_forests 라는 라이브러리를 통해 손쉽게 tf기반의 randomforest, gradient boosting tree를 사용할 수 있다.

사실 sklearn이나 xgboost와 같은 라이브러리를 이용하면 되지만, 굳이 tensorflow를 이용하는 것은

Google Cloud Platform의 Bigquery에 모델을 등록하고, 예측을 하면, 서비스 적용과 운영측면에서 용이하기 때문에 사용한다.

 

Bigquery ML은 custom model의 경우 tensorflow로 작성한 모델만을 지원하기 때문에...

그마저도 메모리를 많이 차지하는 무거운 모델은 등록할 수 가 없다.

 

그래서...하이퍼파라미터를 조절해서 비교적 shallow한 모델을 구성하여 등록해야한다.

tensorflow로 GBM을 구성할때 구버전 tf 2.2는 estimator를 사용해야했으나,

tf2.9이후부터는 tensorflow_decision_forests 로 아주..손쉽게 모델을 학습하고 예측시킬수 있다.

 

 

 

모델학습코드

import tensorflow_decision_forests as tfdf
import pandas as pd

dataset = pd.read_csv("project/dataset.csv")
tf_dataset = tfdf.keras.pd_dataframe_to_tf_dataset(dataset, label="my_label")

model = tfdf.keras.GradientBoostedTreesModel()
model.fit(tf_dataset)

print(model.summary())
y_pred = model.predict(test_ds)

from sklearn.metrics import classification_report
from tensorflow.keras.utils import to_categorical

y_true = eval_df.label
target_names = ['class 0', 'class 1', 'class 2']
print(classification_report(to_categorical(y_true).argmax(axis=1), y_pred.argmax(axis=1), target_names=target_names))


MODEL_EXPORT_PATH = 'gs://<model_path>'
tf.saved_model.save(model, MODEL_EXPORT_PATH)

 

 

GCP bigquery ML 등록 및 예측

-- BQ ML 모델 등록
#standardSQL
CREATE OR REPLACE MODEL `<project>.<dataset>.<model_name>`
OPTIONS (
    MODEL_TYPE = 'TENSORFLOW',
    MODEL_PATH = 'gs://<model_path>/*'
);

-- 예측 
#standardSQL
WITH
predictions AS (
  SELECT
    *, output_1[OFFSET(2)] as label_2_prob --(label은 총 3개이다)
  FROM
    ML.PREDICT( MODEL `<project>.<dataset>.<model_name>`,
      (
      SELECT
        *
      FROM
        `<project>.<dataset>.<predict_table>`
      WHERE TRUE
      )
    )
),
ranked_predictions AS (
  SELECT
    *,
    ROW_NUMBER() OVER (PARTITION BY user_id) AS rownum,
    DENSE_RANK() OVER (PARTITION BY user_id ORDER BY flattened_prediction DESC) AS array_rank
  FROM
    predictions P, UNNEST(P.output_1) AS flattened_prediction
)
SELECT
  * EXCEPT(flattened_prediction, rownum, array_rank, output_1),
  rownum-1 AS pred_label
FROM
  ranked_predictions
WHERE array_rank = 1

 

feature 중요도 확인

import collections
# number_of_use[F] will be the number of node using feature F in its condition.
number_of_use = collections.defaultdict(lambda: 0)

# Iterate over all the nodes in a Depth First Pre-order traversals.
for node_iter in inspector.iterate_on_nodes():

  if not isinstance(node_iter.node, tfdf.py_tree.node.NonLeafNode):
    # Skip the leaf nodes
    continue

  # Iterate over all the features used in the condition.
  # By default, models are "oblique" i.e. each node tests a single feature.
  for feature in node_iter.node.condition.features():
    number_of_use[feature] += 1

print("Number of condition nodes per features:")
for feature, count in number_of_use.items():
  print("\t", feature.name, ":", count)

참조

https://www.tensorflow.org/decision_forests/api_docs/python/tfdf/keras/GradientBoostedTreesModel

 

tfdf.keras.GradientBoostedTreesModel  |  TensorFlow Decision Forests

Gradient Boosted Trees learning algorithm.

www.tensorflow.org

 

728x90
반응형
LIST
Comments