콘텐츠로 바로가기

now0930 일지

이런저런 생각

  • 홈
  • 비공개
  • 강좌
  • 잔여 작업 조회
  • 위치

인구 데이터로 년 수입 예측

데이터 얻기

데이터 셋을 무료로 제공하는 사이트에서 미국 성인 나이, 학력, 가족관계, 년 소득을 받을 수 있다. 입력된 데이터로 이 사람이 연소득 50k dollar을 넘어가는지 아닌지를 예측해보려고 한다. 다행히 이 데이터 셋으로 연습한 사람들이 많은지, 조회수가 상당히 많다.

전체적인 접근 방법

데이터의 구조는 나이, 이름, 가족관계 등과 연 소득이 넘어가는지 아닌지로 구성되어 있다. feature로 쓸 부분을 보면 categorical, continuous 데이터로 구분된다.
1. 파일을 training, test set으로 구분하여 읽는다.
2. categorical 데이터는 숫자로 변경
3. integer 데이터는 그대로 사용
4. training..

feature로 쓸 항목별 데이터가 상당히 많다. python의 dictionary로 일일히 쳐 변환하기는 귀찮다. 관련 소스를 찾아 보았는데 tensorflow tutorial에 이 예제가 설명을 했다.!!빙고!!!이래서 남들이 쓰는 예제를 써야한다!!

tensorflow tutorial 정리

튜토리얼의 구조는 대략 아래와 같다.
1. 데이터 셋을 읽음
2. label을 붙임(0 또는 1)
3. feature를 categorical, continuous 기준으로 분류
4. feature를 tensor로 읽어 들임
5. feature를 아래 4가지 경우로 세부 분류
– SparseColumn : categorical
– RealValuedColumn : continuous
– BucketizedColumn : 일정한 구간으로 분류되는 데이터들
– CrossedColumn : 서로 연관되는 데이터들..
6. feature에 적정한 함수를 사용하여 ID를 부여..
7. training
위 기능들을 모두 tensorflow가 제공하는 함수로 쉽게? 따라서 구현할 수 있다. tensorflow가 없었으면 machine learning의 접근이 상당히 어려웠다고 생각된다.

코드를 써보고 이해하는 과정이 남아있다…

sparse tensor, 4.15 추가분

위 tutorial은 categorical 형식의 데이터를 sparse tensor를 사용하여 표현하였다.

sparse_tensor = tf.SparseTensor(indices=[[0,1], [2,4]],values=[6, 0.5],dense_shape=[3, 5])

sparse tensor는 일정 행렬에 특정 부분(indices)에만 데이터(values)가 있고 나머지 부분은 0인 텐서이다. sparse tensor 선언시 전체 행렬의 크기(dense_shape)도 선언한다. 위와 같이 만들면 [0,1]에 6이 들어가고, [2,4]에 0.5가 들어가게 된다. 전체 shape는 [3,5]로 제한된다. 대략 아래와 같은 형식의 데이터가 된다.
[ [0 6 0 0 0 ]
[0 0 0 0 0 ]
[0 0 0 0 0.5 ] ]
문제는 위의 행렬을 print로 보고 싶은데, 볼 수 있는 방법이 없다.

sparse_tensor = tf.SparseTensor(indices=[[0,1], [2,4]],values=[6, 0.5],dense_shape=[3, 5]) 
with tf.Session() as sess:
    print sparse_tensor

이렇게 실행하면

SparseTensor(indices=Tensor("SparseTensor_2/indices:0", shape=(2, 2), dtype=int64), values=Tensor("SparseTensor_2/values:0", shape=(2,), dtype=float32), dense_shape=Tensor("SparseTensor_2/dense_shape:0", shape=(2,), dtype=int64))

아래와 같이 메세지가 나온다. 인터넷을 찾아 보았지만 sparse tensor를 눈으로 볼 수 있는 방법이 없어 보인다. 필요도 없어 보이고

몇 시간의 삽질 결과..아래와 같이 결론을 내릴 수 있다.

gender = tf.contrib.layers.sparse_column_with_keys(column_name="gender", keys=["Female", "Male"], combiner="sum")
education = tf.contrib.layers.sparse_column_with_hash_bucket("education", hash_bucket_size=1000, combiner="sum")

feature, label = train_input_fn()

train_input_fn은 아래와 같다.

def input_fn(df):
    # Creates a dictionary mapping from each continuous feature column name (k) to
    # the values of that column stored in a constant Tensor.
    # Creates a dictionary mapping from each categorical feature column name (k)
    # to the values of that column stored in a tf.SparseTensor.
    categorical_cols = {k: tf.SparseTensor(
        indices=[[i, 0] for i in range(df[k].size)],
        values=df[k].values,
        dense_shape=[df[k].size, 1])
        for k in CATEGORICAL_COLUMNS}
    # Merges the two dictionaries into one.
    feature_cols = dict(categorical_cols.items())

    # Converts the label column into a constant Tensor.
    label = tf.constant(df[LABEL_COLUMN].values)
    # Returns the feature columns and the label.
    return feature_cols, label

def train_input_fn():
    return input_fn(df_train)

1. training data에서 해당하는 column을 key 형식으로 읽어 들인다.
2. train_input_fn에서는 해당 key별로 sparse tensor를 새로 만든다. -> 칼럼별 어느 데이터가 있는지 다른 데이터를 만든다.
3. categorical_cols을 feature_cols로 dict 타입으로 변경한다.
4. 위 예제에서는 key가 gender, education이 되고 values가 각 키에 해당하는 sparse tensor가 된다.

나중에 dict 형식의 feature를 러닝하면 자동으로 변환되어서 입력이 되나보다.

이 글 공유하기:

  • Tweet
발행일 2017-04-15글쓴이 이대원
카테고리 tensorflow 태그 machinelearning, tensorflow

댓글 남기기응답 취소

이 사이트는 Akismet을 사용하여 스팸을 줄입니다. 댓글 데이터가 어떻게 처리되는지 알아보세요.

글 내비게이션

이전 글

하드디스크에서 나온 옛날 사진

다음 글

BMW 어린이 운전교육

2025 6월
일 월 화 수 목 금 토
1234567
891011121314
15161718192021
22232425262728
2930  
5월    

최신 글

  • common mode, differential mode 2025-05-11
  • signal conditioner, 신호 처리기 2025-05-10
  • strain gage 2025-05-09
  • 칼만 필터 2025-05-01
  • positioner(I/P) 2025-04-26

카테고리

  • 산업계측제어기술사
  • 삶 자국
    • 책과 영화
    • 투자
  • 생활코딩
    • LEGO
    • ROS
    • tensorflow
  • 전기기사
  • 피아노 악보

메타

  • 로그인
  • 엔트리 피드
  • 댓글 피드
  • WordPress.org

페이지

  • 소개
  • 잔여 작업 조회
    • 작업 추가
    • 작업의 사진 조회
    • 작업 수정 페이지
  • 사진
    • GPS 입력된 사진
    • 사진 조회
  • 위치
    • 하기 휴가 방문지
    • 해외 출장

태그

android bash c docker driver FSM gps java kernel LEGO linux mysql network program opcua open62541 plc programmers python raspberry reinforcementLearning ros state space system program tensorflow transfer function 경제 미국 민수 삼국지 세계사 실기 에너지 역사 유전자 일본 임베디드 리눅스 전기기사 조선 중국 채윤 코딩 테스트 통계 한국사 한국어

팔로우하세요

  • Facebook
now0930 일지
WordPress로 제작.