[카테고리:] tensorflow

tensorflow 테스트

  • 인구 데이터로 년 수입 예측

    인구 데이터로 년 수입 예측

    데이터 얻기

    데이터 셋을 무료로 제공하는 사이트에서 미국 성인 나이, 학력, 가족관계, 년 소득을 받을 수 있다. 입력된 데이터로 이 사람이 연소득 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를 러닝하면 자동으로 변환되어서 입력이 되나보다.

  • 스토리지의 모든 경우를 python permutation으로 구현

    스토리지의 모든 경우를 python으로 출력하기

    스토리지의 모든 경우를 python으로 구현하여, 모든 경우에 대한 행동할 값을 테이블로 작성이 가능하다. 이후 중복된 데이터를 엑셀로 정리가 가능하다. 각 경우에 대한 값을 입력으로 보고, 어떻게 행동할 지를 출력으로 임의로 작성하면 X->Y의 관계를 가르칠 수 있다.

    스토리지의 상황

    어느셀에서대차를뺄것인가

    라인 프로그램을 작성하다 보면, 모든 경우에서 어는 부분을 처리해주는 부분이 없어 중단되는 상황이 있다. 셔틀과 스토리지로 구성된 라인이 있다고 할 때, 마지막 공정이 대차를 아래와 같이 세가지 경우 중 하나로 처리할 수 있다.

    1. 생산 데이터와 마지막 공정 대차가 일치하여 시작 공정으로 다시 돌림
    2. 생산 데이터와 마지막 공정 대차가 같지 않아, 스토리지에서 새로운 대차를 빼고, 마지막 대차는 빈 셀로 넣기
      • 간단하게 만들기 위해서, 스토리지에 생산 데이터의 대차가 있어도 라인에 있는 대차를 먼저 사용

    3. 생산 데이터와 마지막 공정 대차가 같지 않아, 다음 턴에서 맞을 것으로 보고 마지막 대차를 시작 공정으로 다시 돌림

    Python Permutation으로 구현하기

    모든 경우에 대한 데이터를 파악하고, 사용자가 엑셀에서 함수를 데이터를 입력하다면 쉽게 입력/출력 테이블을 만들 수 있다. 모든 경우를 엑셀로 출력하는 vba가 있으나, 사용하기 복잡해 보인다. stack overflow 인터넷의 누군가 python으로 간단하게 구현할 수 있는 코드를 작성하여 참조할 수 있도록 정리했다. 왜 pyhon을 많은 사람들을 쓰는지 이해가 된다.

    import itertools
    
    #all cell are full
    mylist8 = ["UM","UM","UM","UM","UM","UM","UM"]
    mylist1 = ["QF","UM","UM","UM","UM","UM","UM"]
    mylist2 = ["QF","QF","UM","UM","UM","UM","UM"]
    mylist3 = ["QF","QF","QF","UM","UM","UM","UM"]
    mylist4 = ["QF","QF","QF","QF","UM","UM","UM"]
    mylist5 = ["QF","QF","QF","QF","QF","UM","UM"]
    mylist6 = ["QF","QF","QF","QF","QF","QF","UM"]
    mylist7 = ["QF","QF","QF","QF","QF","QF","QF"]
    
    #1 cell is empty
    mylist9 = ["UM","UM","UM","UM","UM","UM","Vacant"]
    mylist10 = ["QF","UM","UM","UM","UM","UM","Vacant"]
    mylist11 = ["QF","QF","UM","UM","UM","UM","Vacant"]
    mylist12 = ["QF","QF","QF","UM","UM","UM","Vacant"]
    mylist13 = ["QF","QF","QF","QF","UM","UM","Vacant"]
    mylist14 = ["QF","QF","QF","QF","QF","UM","Vacant"]
    mylist15 = ["QF","QF","QF","QF","QF","QF","Vacant"]
    
    #2 cell are empty
    mylist16 = ["UM","UM","UM","UM","UM","Vacant","Vacant"]
    mylist17 = ["QF","UM","UM","UM","UM","Vacant","Vacant"]
    mylist18 = ["QF","QF","UM","UM","UM","Vacant","Vacant"]
    mylist19 = ["QF","QF","QF","UM","UM","Vacant","Vacant"]
    mylist20 = ["QF","QF","QF","QF","UM","Vacant","Vacant"]
    mylist21 = ["QF","QF","QF","QF","QF","Vacant","Vacant"]
    
    #3 cell are empty
    mylist22 = ["UM","UM","UM","UM","Vacant","Vacant","Vacant"]
    mylist23 = ["QF","UM","UM","UM","Vacant","Vacant","Vacant"]
    mylist24 = ["QF","QF","UM","UM","Vacant","Vacant","Vacant"]
    mylist25 = ["QF","QF","QF","UM","Vacant","Vacant","Vacant"]
    mylist26 = ["QF","QF","QF","QF","Vacant","Vacant","Vacant"]
    
    #4 cell are empty
    mylist27 = ["UM","UM","UM","Vacant","Vacant","Vacant","Vacant"]
    mylist28 = ["QF","UM","UM","Vacant","Vacant","Vacant","Vacant"]
    mylist29 = ["QF","QF","UM","Vacant","Vacant","Vacant","Vacant"]
    mylist30 = ["QF","QF","QF","Vacant","Vacant","Vacant","Vacant"]
    
    #5 cell are empty
    mylist31 = ["UM","UM","Vacant","Vacant","Vacant","Vacant","Vacant"]
    mylist32 = ["QF","UM","Vacant","Vacant","Vacant","Vacant","Vacant"]
    mylist33 = ["QF","QF","Vacant","Vacant","Vacant","Vacant","Vacant"]
    
    #6 cell are empty
    mylist34 = ["UM","Vacant","Vacant","Vacant","Vacant","Vacant","Vacant"]
    mylist35 = ["QF","Vacant","Vacant","Vacant","Vacant","Vacant","Vacant"]
    
    
    myPermutation1 = itertools.permutations(mylist1)
    myPermutation2 = itertools.permutations(mylist2)
    myPermutation3 = itertools.permutations(mylist3)
    myPermutation4 = itertools.permutations(mylist4)
    myPermutation5 = itertools.permutations(mylist5)
    myPermutation6 = itertools.permutations(mylist6)
    myPermutation7 = itertools.permutations(mylist7)
    myPermutation8 = itertools.permutations(mylist8)
    myPermutation9 = itertools.permutations(mylist9)
    myPermutation10 = itertools.permutations(mylist10)
    myPermutation11 = itertools.permutations(mylist11)
    myPermutation12 = itertools.permutations(mylist12)
    myPermutation13 = itertools.permutations(mylist13)
    myPermutation14 = itertools.permutations(mylist14)
    myPermutation15 = itertools.permutations(mylist15)
    myPermutation16 = itertools.permutations(mylist16)
    myPermutation17 = itertools.permutations(mylist17)
    myPermutation18 = itertools.permutations(mylist18)
    myPermutation19 = itertools.permutations(mylist19)
    myPermutation20 = itertools.permutations(mylist20)
    myPermutation21 = itertools.permutations(mylist21)
    myPermutation22 = itertools.permutations(mylist22)
    myPermutation23 = itertools.permutations(mylist23)
    myPermutation24 = itertools.permutations(mylist24)
    myPermutation25 = itertools.permutations(mylist25)
    myPermutation26 = itertools.permutations(mylist26)
    myPermutation27 = itertools.permutations(mylist27)
    myPermutation28 = itertools.permutations(mylist28)
    myPermutation29 = itertools.permutations(mylist29)
    myPermutation30 = itertools.permutations(mylist30)
    myPermutation31 = itertools.permutations(mylist31)
    myPermutation32 = itertools.permutations(mylist32)
    myPermutation33 = itertools.permutations(mylist33)
    myPermutation34 = itertools.permutations(mylist34)
    myPermutation35 = itertools.permutations(mylist35)
    
    #myCombination = itertools.combinations(mylist, 2)
    
    for i in myPermutation1:
        print i
    for i in myPermutation2:
        print i
    for i in myPermutation3:
        print i
    for i in myPermutation4:
        print i
    for i in myPermutation5:
        print i
    for i in myPermutation6:
        print i
    for i in myPermutation7:
        print i
    for i in myPermutation8:
        print i
    for i in myPermutation9:
        print i
    for i in myPermutation10:
        print i
    for i in myPermutation11:
        print i
    for i in myPermutation12:
        print i
    for i in myPermutation13:
        print i
    for i in myPermutation14:
        print i
    for i in myPermutation15:
        print i
    for i in myPermutation16:
        print i
    for i in myPermutation17:
        print i
    for i in myPermutation18:
        print i
    for i in myPermutation19:
        print i
    for i in myPermutation20:
        print i
    for i in myPermutation21:
        print i
    for i in myPermutation22:
        print i
    for i in myPermutation23:
        print i
    for i in myPermutation24:
        print i
    for i in myPermutation25:
        print i
    for i in myPermutation26:
        print i
    for i in myPermutation27:
        print i
    for i in myPermutation28:
        print i
    for i in myPermutation29:
        print i
    for i in myPermutation30:
        print i
    for i in myPermutation31:
        print i
    for i in myPermutation32:
        print i
    for i in myPermutation33:
        print i
    for i in myPermutation34:
        print i
    for i in myPermutation35:
        print i

    python에 익숙하면 더 세련된 형태로 할 수 있겠으나, 일회성으로 하기 때문에 그냥 노가다로 해결했다.

    엑셀로 중복 데이터 제거

    출력 결과는 중복되는 데이터들이 많은데, 간단한 함수로 중복을 제거할 수 있다. 이를 그냥 입력으로도 사용 가능하나, 중복되는 데이터는 정확도가 떨어지므로, 정리해 주는게 맞아 보인다.
    아래는 정리한 테이블의 데이터 셋이다.
    170217datasetv4

  • tensorflow로 gps 좌표를 Kmean 방법으로 분류하기

    tensorflow kmean으로 gps 분류 연습 예제, 2일차

    내가 참조한 예제에서 원래 제작자는 임의의 샘플을 만들고, 그 중에서 한 개를 중심으로 선택하였다. 나는 데이터를 가지고 있어, 임의의 샘플을 만들 필요가 없다. 이에 따라 내가 가진 여러 개의 데이터 중, 임의 한 점을 중심으로 선택해야 했다. 내가 가진 예제는 이 부분이 없어, 예제를 이해하고, 새로 작성하는데 시간이 오래 걸렸다. 여러 삽질끝에 대략 아래와 같이 했다.
    1일차에는 그룹을 설정하지 않았는데, 이렇게 되면 의미가 없다. 이를 수정하기 위해서 gps 좌표를 요일별로 모은 다음 출력으로 내보냈다. 요일별 모은 데이터에서 두 개의 요일을 선택했고, 여기에서 아무점이나  중심으로 선택했다. 일단 sql에서 요일별로 gps 값을 다시 출력하여 아래와 같은 값을 얻었다.

         latitude  longitude  updated
    0     37.3700    126.935        6
    1     37.3698    126.935        6
    2     37.3698    126.935        6
    3     37.3697    126.935        6
    4     37.3697    126.935        6
    79    37.0344    126.773        5
    80    37.0344    126.773        5
    81    37.0344    126.773        5
    82    37.0343    126.773        5
    83    37.0343    126.773        5
    235   37.0325    126.773        4
    236   37.0325    126.773        4
    237   37.0325    126.773        4
    238   37.0325    126.773        4
    239   37.0325    126.773        4
    401   37.0344    126.773        3
    402   37.0344    126.773        3
    403   37.0344    126.773        3
    404   37.0343    126.773        3
    405   37.0343    126.773        3
    544   37.0344    126.773        2
    545   37.0344    126.773        2
    546   37.0344    126.773        2
    547   37.0344    126.773        2
    548   37.3687    126.935        2
    695   37.0343    126.773        1
    696   37.0344    126.773        1
    697   37.0343    126.773        1
    698   37.0343    126.773        1
    699   37.0343    126.773        1
    900   37.3696    126.935        7
    901   37.3695    126.935        7
    902   37.3695    126.935        7
    903   37.3716    126.935        7
    904   37.3716    126.935        7
    

    pandas에서 dataFrame을 groupby로 정렬하면 python이 데이터 형식을 변경해 버린다. 요일로 선택한 데이터를 dataFrame으로 사용하기 위해서 아래와 같이 했다. append 할 경우, 새로운 dataFrame을 만들어야지, 기존 dataFrame에 넣으면 붙지 않는다.

    ipdGroupbyUpdated = ipd.groupby('updated')
    print ipdGroupbyUpdated.head()
    
    #updated에서 1일차 날짜, 3일차 날짜를 구해서 별도의 dataframe을 설정..
    #pd.show_versions()
    print ipdGroupbyUpdated.get_group(1)
    #print type(ipdGroupbyUpdated.get_group(1))
    ipdSliced=ipdGroupbyUpdated.get_group(1)
    print "1일차 데이터"
    print ipdSliced.head()
    print type(ipdSliced)
    
    ipdSliced1=ipdGroupbyUpdated.get_group(7)
    print "3일차 데이터"
    print ipdSliced1.head()
    print type(ipdSliced1)
    

    찾아보면 더 쉬운 방법이 있겠지만, 여기까지 하는데도 충분히 힘들었다.

    두 개 요일로 선택한 좌표를 그림을 그리기 위해서, 아래과 같이 함수를 정의하고, dataFrame을 인자로 넘겨 주었다. 굳이 함수로 정의한 이유는 원래의 예제가 함수로 되어 있었기 때문이다.

        def plot_clusters(df_ipd, centroids):
        print("plot_clusters was called")
        import matplotlib
        matplotlib.use('Agg')
        import matplotlib.pyplot as plt 
    
        for key, val in df_ipd.groupby('updated'):
            tmp_centoid=df_ipd[df_ipd.updated==key].sample()
            #print "tmp_centoid 출력\n"
            #print tmp_centoid[['longitude','latitude']]
            #print tmp_centoid[['longitude']]
    
            plt.scatter(val['longitude'], val['latitude'], label=key)
            plt.plot(tmp_centoid[['longitude']],tmp_centoid[['latitude']], markersize=35, marker="x", color='k', mew=10) 
            plt.plot(tmp_centoid[['longitude']],tmp_centoid[['latitude']], markersize=30, marker="x", color='m', mew=5)
    

    for문이 groupby의 기준인 날짜기준으로 key값을 변경하면서 루프를 만든다. dataFrame에서 임의의 점을 찾기 위해 tmp_centoid[‘longitude’]와 같은 방식을 선택했다. 마지막에 있는 marker관련 2개의 줄은 X의 색을 칠하는 부분이다. 필요 없다고 판단하여 한 줄만 사용하니 색이 안칠해 졌다.
    대략 아래와 같은 그림을 얻을 수 있다..

    전에 데이터와 달리 위도/경도의 축을 바꿨다.

  • tensorflow로 gps 좌표를 Kmean 방법으로 분류하기

    tensorflow kmean으로 gps 분류 연습 예제, 1일차

    tensorflow를 연습하려고 할만한 아이템을 찾다, gps 위치를 kmean으로 분류하는 방법이 할만해 보인다.
    휴대폰이 시간맞춰 자동으로 서버로 gps 포인트를 올렸는데, 최근 일년, 사진에서 뽑아낸 gps 정보를 뽑아보니 한 50,000개 정도가 된다. 데이터베이스에서 csv로 쉽게 뽑아냈고, 전에 쓰던 코드를 활용하여 pandas로 data frame으로 저장도 되었다. 이 정보를 뿌려짐 형식의 그래프로 그려야 되는데, 잘 안되었다.

    gps 데이터 처음 몇개는 대략 아래와 같다.
    latitude longitude updated
    0 37.8968 127.528 2015-11-06
    1 37.8968 127.528 2015-11-06
    2 37.8968 127.528 2015-11-06
    3 37.8924 127.548 2015-11-06
    4 37.8968 127.528 2015-11-06

    plot에 대한 문서들도 찾아 봤는데, 너무 추상적이라 무슨 말인지 모르겠다. 프로그램을 배우는 방법은 실재 해보는 거라, 인터넷의 예제를 찾아보았다. 여기에주인이 내가 필요한 답을 써놓아 그대로 참조했다.
    아래와 같이 실행하면 gps의 위도, 경도별 그래프를 그릴 수 있다.

    ipd = pd.read_csv("./TRK.csv")
    print(ipd.head())
    
    plt.scatter(ipd.latitude, ipd.longitude)
    plt.show()
    plt.savefig('gps-plot.jpg')
    
    gps
    gps 좌표
  • 텐서플로우 링크 모음

    iris 분류 방법
    http://tneal.org/post/tensorflow-iris/TensorFlowIris/