tf.contrib.learn.DNNClassifer 활용한 모델링하기

2019. 6. 16. 20:51분석 Python/Tensorflow

728x90

일단은 Numeric 버전만 진행을 하려고 한다.

 

추후에 wide-deep 이든 embedding 해서 하는 것을 해보겠다.

 

여기서 tf.data를 적용하려고 했는데, 계속 안되서 포기하고 그냥 해보기! 

 

import numpy as np
from sklearn.model_selection import train_test_split
from sklearn import datasets

cancer = datasets.load_breast_cancer()
cancer.data.shape, cancer.target.shape
## stratifed를 제공했었다!
X_train, X_test, y_train, y_test = train_test_split(
    cancer.data, cancer.target, test_size=0.4, random_state=0 , stratify = cancer.target )
    
X_train.shape, y_train.shape , X_test.shape, y_test.shape
## ((341, 30), (341,), (228, 30), (228,))


import os
import warnings
import tensorflow as tf
warnings.filterwarnings(action='ignore') 
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'  # or any {'0', '1', '2'}



def main():
    # Specify that all features have real-value data
    ## 컬럼 이름해주는 것 같은데, 아직 특별한 전처리는 안하니 그냥 대충 넣어버러기 
    feature_columns = [tf.contrib.layers.real_valued_column("", dimension=30)]
    classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns,
                                                hidden_units=[256 , 128 , 64 , 32 , 16 ],
                                                n_classes=2, # l1_regularization_strength=0.001
                                                optimizer=tf.train.AdamOptimizer(
                                                    learning_rate=0.001,
                                                ))
    ## 이쪽을 tf.data를 하고 싶었는데, 안됨 
    ## batch가 안되는 것 같음 메이비 
    def get_train_inputs():
        x = tf.constant(X_train)
        y = tf.constant(y_train)
        return x , y 
    def get_test_inputs():
        x = tf.constant(X_test)
        y = tf.constant(y_test)

        return x, y

    classifier.fit(
                   input_fn=get_train_inputs , 
                   steps=3000  
    ) 
    # 
    accuracy_score = classifier.evaluate(input_fn=get_test_inputs, steps=1)["accuracy"]
    ## tensorboard 쉽게 제공 
    #graph_location = '/tmp/tensorflow/car-evaluation'
    #print('Saving graph to: %s' % graph_location)
    #train_writer = tf.summary.FileWriter(graph_location)
    #train_writer.add_graph(tf.get_default_graph())
    print("Test Accuracy: {0:f}".format(accuracy_score))
    prob = classifier.predict_proba(input_fn=get_test_inputs )
    pred = classifier.predict(input_fn=get_test_inputs)
    return prob , pred


if __name__ == "__main__":
    prob , pred  = main()

prediction = list(pred)
output = list(prob)

나온 결과값은 Generator 형식이라서 한번 부르면 없어지니 다른 객체로 만들어주면 됨.

다른 것들보다 쉽게 월등한 성능냄. sklearn 했던 것들 보다! 

 

728x90