TechTogetWorld

인공지능의 실전입문에 관한 글입니다.

알고리즘을 만드는것이 아니고, 만들어진 알로리즘을 활용하는 방법에 관한 글입니다.

자동차 운전을 위해 자동차를 만드는방법을 알필요는 없습니다. 물론 알면 좋기는 하겠지만, 서로 별도의 분야라고 할수있습니다.


본글은 학습용 데이터를 학습/테스트/측정하는 방법에 대한 글입니다.

글의 순서는 아래와 같습니다.


=========================================================================================


1. X-OR 구현 => [ # 170814 7 xor-train ]

2. 손글씨 맞추기

  - MNIST DOWN ==> [ # 170814 10 mnist-download ] 

  - DATA 변환 ==> CSV 로 , [# 170814 11 mnist-tocsv]    

t10k.csv

train.csv

  - 학습/테스트/평가 ==> [# 170814 9 mnist-train]

    . DATA숫자가 5000개 정도 수준으로, 정확도는 78% 수준임,  전체DATA로 하게되면 정확도는 95% 수준으로 올라감


3. 참고자료


=========================================================================================


[ # 170814 7 xor-train ]


from sklearn import svm

# XOR의 계산 결과 데이터 --- (※1)

xor_data = [

    #P, Q, result

    [0, 0, 0],

    [0, 1, 1],

    [1, 0, 1],

    [1, 1, 0]

]

# 학습을 위해 데이터와 레이블 분리하기 --- (※2)

data = []

label = []

for row in xor_data:

    p = row[0]

    q = row[1]

    r = row[2]

    data.append([p, q])

    label.append(r)

# 데이터 학습시키기 --- (※3)

clf = svm.SVC()

clf.fit(data, label)

# 데이터 예측하기 --- (※4)

pre = clf.predict(data)

print(" 예측결과:", pre)

# 결과 확인하기 --- (※5)

ok = 0; total = 0

for idx, answer in enumerate(label):

    p = pre[idx]

    if p == answer: ok += 1

    total += 1

print("정답률:", ok, "/", total, "=", ok/total)




[ # 170814 10 mnist-download ]

import urllib.request as req
import gzip, os, os.path
savepath = "./mnist"
baseurl = "http://yann.lecun.com/exdb/mnist"
files = [
    "train-images-idx3-ubyte.gz",
    "train-labels-idx1-ubyte.gz",
    "t10k-images-idx3-ubyte.gz",
    "t10k-labels-idx1-ubyte.gz"]
# 다운로드
if not os.path.exists(savepath): os.mkdir(savepath)
for f in files:
    url = baseurl + "/" + f
    loc = savepath + "/" + f
    print("download:", url)
    if not os.path.exists(loc):
        req.urlretrieve(url, loc)
# GZip 압축 해제
for f in files:
    gz_file = savepath + "/" + f
    raw_file = savepath + "/" + f.replace(".gz", "")
    print("gzip:", f)
    with gzip.open(gz_file, "rb") as fp:
        body = fp.read()
        with open(raw_file, "wb") as w:
            w.write(body)
print("ok")


[# 170814 11 mnist-tocsv]

import struct
def to_csv(name, maxdata):
    # 레이블 파일과 이미지 파일 열기
    lbl_f = open("./mnist/"+name+"-labels-idx1-ubyte", "rb")
    img_f = open("./mnist/"+name+"-images-idx3-ubyte", "rb")
    csv_f = open("./mnist/"+name+".csv", "w", encoding="utf-8")
    # 헤더 정보 읽기 --- (※1)
    mag, lbl_count = struct.unpack(">II", lbl_f.read(8))
    mag, img_count = struct.unpack(">II", img_f.read(8))
    rows, cols = struct.unpack(">II", img_f.read(8))
    pixels = rows * cols
    # 이미지 데이터를 읽고 CSV로 저장하기 --- (※2)
    res = []
    for idx in range(lbl_count):
        if idx > maxdata: break
        label = struct.unpack("B", lbl_f.read(1))[0]
        bdata = img_f.read(pixels)
        sdata = list(map(lambda n: str(n), bdata))
        csv_f.write(str(label)+",")
        csv_f.write(",".join(sdata)+"\r\n")
        # 잘 저장됐는지 이미지 파일로 저장해서 테스트하기 -- (※3)
        if idx < 10:
            s = "P2 28 28 255\n"
            s += " ".join(sdata)
            iname = "./mnist/{0}-{1}-{2}.pgm".format(name,idx,label)
            with open(iname, "w", encoding="utf-8") as f:
                f.write(s)
    csv_f.close()
    lbl_f.close()
    img_f.close()
# 결과를 파일로 출력하기 --- (※4)
to_csv("train", 1000)
to_csv("t10k", 500)



[# 170814 9 mnist-train]

from sklearn import model_selection,svm,metrics
import pandas

train_csv=pandas.read_csv("./mnist/train.csv",header=None)
tk_csv=pandas.read_csv("./mnist/t10k.csv",header=None)

def test(l) :
    output=[]
    for i in l:
        output.append(float(i)/256)
    return output

train_csv_data=list(map(test,train_csv.iloc[:,1:].values))
tk_csv_data=list(map(test,tk_csv.iloc[:,1:].values))

train_csv_label=train_csv[0].values
tk_csv_label=tk_csv[0].values

clf = svm.SVC()
clf.fit(train_csv_data, train_csv_label)
predict = clf.predict(tk_csv_data)
print(predict)
score = metrics.accuracy_score(tk_csv_label,predict)
print("정답률 =", score)





[참고자료]


https://www.docker.com/products/docker-toolbox  ==> docker 설치방법

https://www.data.go.kr/main.do