tensorflow, keras) 정형 데이터를 이용하여 모델 만들기

2022. 1. 8. 15:35분석 Python/Tensorflow

728x90
 

목차

    umap에서 ParametricUMAP 을 사용하기 위해서는 keras 모델을 만들어야 하는데, 정형데이터를 임베딩해서 적용해보고 싶어서, 테스트를 하는 도중에 나온 결과물을 정리한다.

    결론적으로 현재(22/01/08)는 umap에서 dict 데이터 타입을 지원하지 않고, 오로지 array 형태로만 가능하기 때문에, 사용할수가 없었다. 

    데이터를 one-hot으로 해서 하는 방법이 있겠지만, 차원 축소를 할 때 임베딩도 차원 축소할 때 학습시키고자 했기 때문에 좀 더 라이브러리가 개선되면 그때 다시 시도해봐야겠다. 아니면 일부 코드를 뜯어내서 수정하거나...

     

    이러한 예시는 tensorflow에서 더 잘되어 있긴 하지만, 간단하게 구현해놔서 정리만 해둔다.

     

    라이브러리 호출

    import pandas as pd
    import numpy as np
    import tensorflow as tf
    from sklearn.preprocessing import LabelEncoder

    Column 별로 전처리 나눠서 진행하기

    df = pd.read_csv("./data/adult.csv")
    categorical_columns = list(df.select_dtypes("object"))
    continuous_columns = [i  for i in list(df) if i not in categorical_columns]
    feature_columns = []
    inputs = {}
    
    for col in  continuous_columns :
        feature_columns.append( tf.feature_column.numeric_column(col))
        inputs[col] = tf.keras.Input(shape=(1,), name=col, dtype=tf.dtypes.float32) 
    for col in categorical_columns :
        le = LabelEncoder()
        le.fit(df[col])
        df[col] = le.transform(df[col])
        #df[col] = df[col].astype(np.float32)
        unique_v = df[col].unique().tolist()
        _col = tf.feature_column.categorical_column_with_vocabulary_list(col,unique_v)
        _emb = tf.feature_column.embedding_column(_col,4)
        feature_columns.append(_emb)
        inputs[col] = tf.keras.Input(shape=(1,), name=col, dtype=tf.dtypes.int32) 
    feature_layer = tf.keras.layers.DenseFeatures(feature_columns)

     

    일반적인 Keras 모델로 모델 만들기

    n_components = 2
    x = feature_layer(inputs)
    x = tf.keras.layers.Dense(128, activation='relu')(x)
    x = tf.keras.layers.Dense(128, activation='relu')(x)
    x = tf.keras.layers.Dropout(.1)(x)
    out = tf.keras.layers.Dense(n_components)(x)
    encoder = tf.keras.Model(inputs=dict(inputs), outputs=out)
    encoder.summary()

    Keras Custom Model 만들기

    class TabularModel(tf.keras.Model):
        
        def __init__(self):
            super(TabularModel, self).__init__()
            self.feature_layer = feature_layer
            self.n_components = 2
    
        def call(self, tensor_array):
            x = self.feature_layer(tensor_array)
            x = tf.keras.layers.Dense(128, activation='relu')(x)
            x = tf.keras.layers.Dense(128, activation='relu')(x)
            x = tf.keras.layers.Dropout(.1)(x)
            out = tf.keras.layers.Dense(self.n_components)(x)
            return out

     

     

    https://umap-learn.readthedocs.io/en/latest/parametric_umap.html

     

    Parametric (neural network) Embedding — umap 0.5 documentation

    UMAP is comprised of two steps: First, compute a graph representing your data, second, learn an embedding for that graph: Parametric UMAP replaces the second step, minimizing the same objective function as UMAP (we’ll call it non-parametric UMAP here), b

    umap-learn.readthedocs.io

     

    https://www.tensorflow.org/tutorials/structured_data/feature_columns?hl=ko 

     

    정형 데이터 다루기  |  TensorFlow Core

    도움말 Kaggle에 TensorFlow과 그레이트 배리어 리프 (Great Barrier Reef)를 보호하기 도전에 참여 정형 데이터 다루기 Note: 이 문서는 텐서플로 커뮤니티에서 번역했습니다. 커뮤니티 번역 활동의 특성상

    www.tensorflow.org

     

    728x90