TechTogetWorld


버전관리 시스템 관한 글입니다.


GIT / Github 활용법 입니다. 

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


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

1. git / github/tools 활용법

2. git /github 활용 하여 "언어판별 프로그램" 등록 ==>https://github.com/david20120720/lang-training-prog

  . 언어판별 프로그램

    . 웨사이트 데이터 수집 (crawler )==>data전처리==> 학습시키기==> 평가하기

    . 웹 사이트 (독일어, 영어, 프랑스어)의 data를 수집해서, 그 글의 언어판별해줌(독일어 인지, 영어인지..)

    . 언어별 알파벳 사용빈도가 틀리다는것에 기인하여, 평가 가능함

3. 참고자료

  . https://opentutorials.org/course/1492 ( 생활코딩  이고잉님 동영상강의)


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


[git / github/tools 활용법]

1. GIT은 버전을 관리할수있는 프로그램 입니다. 이때 소스코드는 본인의 PC에 저장이 되게 됩니다.

   즉 다른곳에 빽업이 않된 상태입니다. 따라서 빽업의 필요성이 생깁니다.

2. GITHUB은 GIT에서 관리하고있는 소스프로그램을 저장하는 저장소 입니다.  

   1) 즉 외부 서버에 빽업을 할수있고,

   2) 다른사람들과 협업을 할수있습니다.

3. 회사의 노하우를 외부 서버에 저장을 한다는것은 부담스러울수 있습니다. 따라서

   1) 서버는 회사내부에서 서버를 두고 운영하고, GIT저장소의 시스템만 다운받아서 , 서버에 설치운영할수도 있습니다.

   이때 사용하는것이 GITLAB 입니다.

4. 협업을 도와주는 YOBI 라는 솔루션도 있습니다.

5.tools 

  - commit, 협업시 push시에 충동해결하는 tool

    . beyond compare(유료), 무료 프로그램도 많이 있음.

  - 아직 끝나지 않은(commit 하지 않은) 코드 안전저장 : stash 

  - 의미있는 버전 표시 : tag

  - 코딩시 부수적으로 생기는 화일 (ex  bak(백업)file, 임시화일등)을 처리 ; ignore

   . ignore할 파일이 많이 생기는 환경의 경우  .gitignore.io 에서 환경별로 검색해서 , 생길수 있는 ignoe화일을 확인하고, 복사해서 환경변수 ignore에 저장/commit 하면 일괄 처리가 됨.

  - 아이디,비밀번호등 환경화일 관리하는법


[ git /github 활용 하여 "언어판별 프로그램" 등록]





 [참고자료]

  https://opentutorials.org/course/1492 ( 생활코딩  이고잉님 동영상강의)

'공통' 카테고리의 다른 글

충전기 만들기  (0) 2018.12.04

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

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

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


본글은 언어구분 방법에 대한 글입니다.

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


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


1. 동작구현 ==> [# 170820 4 lang-train-project_v03 ]

  - 프로그램을 실행하면, 프로그램에서 자동으로 독일어 사이트에서 9개의 독일어

    원문을 크롤링 해옵니다.

  - 별도로 저장한 프랑스어 txt 화일과 함께 학습을 합니다(학습용 5개 : fr-1 ~ fr-5 )

  - 프랑스어 4개( fr6~fr9)로 테스트를 실행합니다.

  - 평가합니다.

  - 특기사항

     . 크롤링 프로그램의 경우는 초반에 잘 되다가도, 중간에 인터넷 사이트의 뉴스기사가

        바뀌면  간혹 크롤링이 잘 않되는경우가 발생하는것 같습니다 (단순 텍스트만 바뀌면

        상관이 없지만, 글의 구조가 바뀌는경우입니다), 감안해서 코딩이 필요합니다.

2. Source code


170820 4 lang-train-project_v03.py

fr---6.txt

fr---7.txt

fr---8.txt

fr---9.txt

fr--1.txt

fr--2.txt

fr--3.txt

fr--4.txt

fr--5.txt


3. 참고자료    


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


 [# 170820 4 lang-train-project_v03 ]


import urllib.request

from bs4 import BeautifulSoup

import time

from sklearn import svm, metrics

import glob, os.path ,re, json


# train data

# HTML 가져오기

url = "http://www.zeit.de/index"

response = urllib.request.urlopen(url)

# HTML 분석하기

soup = BeautifulSoup(response, "html.parser")

# 원하는 데이터 추출하기 --- (※1)

results = soup.select("#main > div > div.cp-area.cp-area--major  div > h2 > a")

i=0

for result in results:

  i=i+1

  print(i,"st article")

  print("title:" , result.attrs["title"])

  url_article=result.attrs["href"]

  response = urllib.request.urlopen(url_article)

  soup_article=BeautifulSoup(response, "html.parser")

  content=soup_article.select_one("p")


  output=""

  for item in content.contents:

    stripped=str(item).strip()

    if stripped == "":

      continue

    if stripped[0] not in ["<","/"]:

      output+=str(item).strip()

      print(output)


# 추출한 data를 txt 화일로 저장하기

  fn= "de" +"--"+ str(i)+ ".txt"

  fw = open(fn, 'w', encoding='UTF-8', newline='')

 # f = open("C:/Python/새파일.txt", 'w')

  result_text = output

  fw.write(result_text)

  fw.close()

  # 1초휴식 : 초당 서버호츨 횟수가 늘어나면, 아이디 차단당할수 있음. 휴식시간이 필요함

  time.sleep(1.5)


# 학습시키기

files=glob.glob("*--*.txt")

train_data=[]

train_label=[]

i=0

for file_name in files :

    i=i+1

    print(i)

    basename=os.path.basename(file_name)

    lang=basename.split("-")[0]

    file=open(file_name,"r",encoding="utf-8")

    text=file.read()

    text=text.lower()

    file.close()

    code_a = ord("a")

    code_z = ord("z")

    count = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

    for character in text:

        code_current=ord(character)

        if code_a<=code_current <=code_z :

            count[code_current-code_a] +=1

    total=sum(count)+0.00001

    count=list(map(lambda n : n/total,count))

#리스트에 넣기

    train_label.append(lang)

    train_data.append(count)



# 테스트 하기: 프랑스어 4개 화일(6~9번)을 테스용 데이터로 사용함

i=0

files=glob.glob("*---*.txt")

test_data=[]

test_label=[]

for file_name in files :

    i=i+1

    print(i)

    basename=os.path.basename(file_name)

    lang=basename.split("-")[0]

    file=open(file_name,"r",encoding="utf-8")

    text=file.read()

    text=text.lower()

    file.close()

    code_a = ord("a")

    code_z = ord("z")

    count = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

    for character in text:

        code_current=ord(character)

        if code_a<=code_current <=code_z :

            count[code_current-code_a] +=1

    total=sum(count)+0.00001

    count=list(map(lambda n : round(n/total,3),count))

#리스트에 넣기

    test_label.append(lang)

    test_data.append(count)


# 평가하기

clf = svm.SVC()

clf.fit(train_data, train_label)

predict=clf.predict(test_data)

score=metrics.accuracy_score(test_label, predict)

print("score=",score)

print("=========================================================================")

print("test_data=",test_data)

print("predict=",predict)




[참고자료]


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

http://konlpy-ko.readthedocs.io/ko/v0.4.3/

https://ithub.korean.go.kr/user/total/database/corpusView.do

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

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

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


본글은 한글 형태소 분석 방법에 대한 글입니다.

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


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


1.프로그램 설치

 - 아나콘다 기준임

 - conda install openjdk

 - conda install python

 - pip install konlpy

 - 상기 프로그램 설치후 jvm 관련 에러가 발생할경우 아래 프로그램 추가로 설치한다

    .jdk-8u144-windows-x64.exe  ==> http://docs.oracle.com/cd/E19182-01/820-7851/inst_cli_jdk_javahome_t/index.html

 - jupyter notebook 설치실행하기

    . pip install jupyter

    . 실행 :아나콘도 프롬프트에서 명령어 입력: jupyter notebook ==> 노트북이 열림 ( http://localhost:8888/tree# )

    . 에러 처리 :  셀에 코드 입력후 cell run을 해도 반응이 없을경우, 인터넷 브로우져를 " 크롬"으로 변경한다.

    . 기타 옵션 활성화는 "ipythoen.config 화일을 에서 필요한 항목을 주석해제 한다(활성화 한다)

      -C:\Users\dhp\.ipython\profile_default


2.한글 형태소 분석[ # 170819 10 toji_count ]

 - 단어별 등장빈도를 분석함

 - 소설의 장르구분, 글의 종류등을 구분하는데  많은 응용이 가능함

    


3. 소설 "togi" 내용을 형태소 적용 출력하고, 단어별 가까운 단어 사용빈도를 출력해줌 =>[ # 170820 1 word2vec-toji ]

 - 아래 2 라인은 jupyter 에서는 실행이 잘 되는데, 본 에디터(pycharm)여기서는 실행이 않되는 문제가 있음,확인필요함

    model1 = word2vec.Word2Vec.load("toji.model")

    model1.most_similar(positive=["땅"])


4. 베이지안필터로 텍스트 분류하기 ==? [ #bayes170820 ] [#170820 3bayes_test]

  - 광고성 스팸분류등.



5. MLP(다중 퍼셉트론 ,Multi layers perceptron)을 이용한 텍스트 분류 ==> [#170826 1 mlp2-seq] [# 170826 2 mlp3-classify]

  - 화일(- data.json  data-mini,josn  word-dic.json) 은  "http://wikibook.co.kr/python-machine-learning/ " 참조

 


6. Next Step

 - 문장의 유사도를 n-gram으로 분석하기 ==>[#170826 3 lev-distance]

 - 마르코프 체인과 LSTM으로 문장생성하기 ==>170826 5 markov , 170826 4 lstm-text-gen

 - 챗봇 만들기 =>170826 6 chatbot

 - 이미지와 딥러닝

  . 유사이미지 검출하기

  . cnn으로 caltech101 의 이미지 분류하기

  . opencv로 얼굴 인식하기

  . 이미지  ocr- 연속된 문자 인식하기


7. 참고자료


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


[ # 170819 10 toji_count ]


import codecs

from bs4 import BeautifulSoup

from konlpy.tag import Twitter

# utf-16 인코딩으로 파일을 열고 글자를 출력하기 --- (※1)

fp = codecs.open("170819 8.txt", "r", encoding="utf-16")

soup = BeautifulSoup(fp, "html.parser")

body = soup.select_one("text > body")

text = body.getText()

# 텍스트를 한 줄씩 처리하기 --- (※2)

twitter = Twitter()

word_dic = {}

lines = text.split("\r\n")

for line in lines:

    malist = twitter.pos(line)

    for word in malist:

        if word[1] == "Noun": #  명사 확인하기 --- (※3)

            if not (word[0] in word_dic):

                word_dic[word[0]] = 0

            word_dic[word[0]] += 1 # 카운트하기

# 많이 사용된 명사 출력하기 --- (※4)

keys = sorted(word_dic.items(), key=lambda x:x[1], reverse=True)

for word, count in keys[:50]:

    print("{0}({1}) ".format(word, count), end="")

print()



[ # 170820 1 word2vec-toji ]


"""

아래 2 라인은 jupyter 에서는 실행이 잘 되는데, 본 에디터(pycharm)여기서는 실행이 않되는 문제가 있음

확인필요함

model1 = word2vec.Word2Vec.load("toji.model")

model1.most_similar(positive=["땅"])

"""



import codecs

from bs4 import BeautifulSoup

from konlpy.tag import Twitter

from gensim.models import word2vec


# utf-16 인코딩으로 파일을 열고 글자를 출력하기 --- (※1)

fp = codecs.open("170819 8.txt", "r", encoding="utf-16")

soup = BeautifulSoup(fp, "html.parser")

body = soup.select_one("text > body")

text = body.getText()

# 텍스트를 한 줄씩 처리하기 --- (※2)

twitter = Twitter()

results = []

lines = text.split("\r\n")

for line in lines:

    # 형태소 분석하기 --- (※3)

    # 단어의 기본형 사용

    malist = twitter.pos(line, norm=True, stem=True)

    r = []

    for word in malist:

        # 어미/조사/구두점 등은 대상에서 제외 

        if not word[1] in ["Josa", "Eomi", "Punctuation"]:

            r.append(word[0])

    rl = (" ".join(r)).strip()

    results.append(rl)

    print(rl)

# 파일로 출력하기  --- (※4)

wakati_file = 'toji.wakati'


with open(wakati_file, 'w', encoding='utf-8') as fp:

    fp.write("\n".join(results))


# Word2Vec 모델 만들기 --- (※5)

data = word2vec.LineSentence(wakati_file)


model = word2vec.Word2Vec(data, 

    size=200, window=10, hs=1, min_count=2, sg=1)

model.save("toji.model")

print("ok")



model1 = word2vec.Word2Vec.load("toji.model")

model1.most_similar(positive=["땅"])



[ #bayes170820 ]

"베이지안 필터로 텍스트 분류하기"

import math, sys

from konlpy.tag import Twitter

class BayesianFilter:

    """ 베이지안 필터 """

    def __init__(self):

        self.words = set() # 출현한 단어 기록

        self.word_dict = {} # 카테고리마다의 출현 횟수 기록

        self.category_dict = {} # 카테고리 출현 횟수 기록

    # 형태소 분석하기 --- (※1)

    def split(self, text):

        results = []

        twitter = Twitter()

        # 단어의 기본형 사용

        malist = twitter.pos(text, norm=True, stem=True)

        for word in malist:

            # 어미/조사/구두점 등은 대상에서 제외 

            if not word[1] in ["Josa", "Eomi", "Punctuation"]:

                results.append(word[0])

        return results

    # 단어와 카테고리의 출현 횟수 세기 --- (※2)

    def inc_word(self, word, category):

        # 단어를 카테고리에 추가하기

        if not category in self.word_dict:

            self.word_dict[category] = {}

        if not word in self.word_dict[category]:

            self.word_dict[category][word] = 0

        self.word_dict[category][word] += 1

        self.words.add(word)

    def inc_category(self, category):

        # 카테고리 계산하기

        if not category in self.category_dict:

            self.category_dict[category] = 0

        self.category_dict[category] += 1

    

    # 텍스트 학습하기 --- (※3)

    def fit(self, text, category):

        """ 텍스트 학습 """

        word_list = self.split(text)

        for word in word_list:

            self.inc_word(word, category)

        self.inc_category(category)

    

    # 단어 리스트에 점수 매기기--- (※4)

    def score(self, words, category):

        score = math.log(self.category_prob(category))

        for word in words:

            score += math.log(self.word_prob(word, category))

        return score

    

    # 예측하기 --- (※5)

    def predict(self, text):

        best_category = None

        max_score = -sys.maxsize 

        words = self.split(text)

        score_list = []

        for category in self.category_dict.keys():

            score = self.score(words, category)

            score_list.append((category, score))

            if score > max_score:

                max_score = score

                best_category = category

        return best_category, score_list

    # 카테고리 내부의 단어 출현 횟수 구하기

    def get_word_count(self, word, category):

        if word in self.word_dict[category]:

            return self.word_dict[category][word]

        else:

            return 0

    # 카테고리 계산

    def category_prob(self, category):

        sum_categories = sum(self.category_dict.values())

        category_v = self.category_dict[category]

        return category_v / sum_categories

        

    # 카테고리 내부의 단어 출현 비율 계산 --- (※6)

    def word_prob(self, word, category):

        n = self.get_word_count(word, category) + 1 # ---(※6a)

        d = sum(self.word_dict[category].values()) + len(self.words)

        return n / d



[#170820 3bayes_test]


from bayes170820 import BayesianFilter

bf = BayesianFilter()

# 텍스트 학습

bf.fit("파격 세일 - 오늘까지만 30% 할인", "광고")

bf.fit("쿠폰 선물 & 무료 배송", "광고")

bf.fit("현데계 백화점 세일", "광고")

bf.fit("봄과 함께 찾아온 따뜻한 신제품 소식", "광고")

bf.fit("인기 제품 기간 한정 세일", "광고")

bf.fit("오늘 일정 확인", "중요")

bf.fit("프로젝트 진행 상황 보고","중요")

bf.fit("회의 일정이 등록되었습니다.","중요")

bf.fit("오늘 일정이 없습니다.","중요")

# 예측

pre, scorelist = bf.predict("재고 정리 할인, 무료 배송")

print("결과 =", pre)

print(scorelist)




[#170826 1 mlp2-seq]


import os, glob, json

root_dir = "./newstext"

dic_file = root_dir + "/word-dic.json"

data_file = root_dir + "/data.json"

data_file_min = root_dir + "/data-mini.json"

# 어구를 자르고 ID로 변환하기 ---(※1)

word_dic = { "_MAX": 0 }

def text_to_ids(text):

    text = text.strip()

    words = text.split(" ")

    result = []

    for n in words:

        n = n.strip()

        if n == "": continue

        if not n in word_dic:

            wid = word_dic[n] = word_dic["_MAX"]

            word_dic["_MAX"] += 1

            print(wid, n)

        else:

            wid = word_dic[n]

        result.append(wid)

    print(result)

    return result

# 파일을 읽고 고정 길이의 배열 리턴하기 ---(※2)

def file_to_ids(fname):

    with open(fname, "r") as f:

        text = f.read()

        return text_to_ids(text)

# 딕셔너리에 단어 모두 등록하기 --- (※3)

def register_dic():

    files = glob.glob(root_dir+"/*/*.wakati", recursive=True)

    for i in files:

        file_to_ids(i)

# 파일 내부의 단어 세기 --- (※4)

def count_file_freq(fname):

    cnt = [0 for n in range(word_dic["_MAX"])]

    with open(fname,"r") as f:

        text = f.read().strip()

        ids = text_to_ids(text)

        for wid in ids:

            cnt[wid] += 1

    return cnt

# 카테고리마다 파일 읽어 들이기 --- (※5)

def count_freq(limit = 0):

    X = []

    Y = []

    max_words = word_dic["_MAX"]

    cat_names = []

    for cat in os.listdir(root_dir):

        cat_dir = root_dir + "/" + cat

        if not os.path.isdir(cat_dir): continue

        cat_idx = len(cat_names)

        cat_names.append(cat)

        files = glob.glob(cat_dir+"/*.wakati")

        i = 0

        for path in files:

            print(path)

            cnt = count_file_freq(path)

            X.append(cnt)

            Y.append(cat_idx)

            if limit > 0:

                if i > limit: break

                i += 1

    return X,Y

# 단어 딕셔너리 만들기 --- (※5)

if os.path.exists(dic_file):

     word_dic = json.load(open(dic_file))

else:

    register_dic()

    json.dump(word_dic, open(dic_file,"w"))

# 벡터를 파일로 출력하기 --- (※6)

# 테스트 목적의 소규모 데이터 만들기

X, Y = count_freq(20)

json.dump({"X": X, "Y": Y}, open(data_file_min,"w"))

# 전체 데이터를 기반으로 데이터 만들기

X, Y = count_freq()

json.dump({"X": X, "Y": Y}, open(data_file,"w"))

print("ok")


[# 170826 2 mlp3-classify]


from keras.models import Sequential

from keras.layers import Dense, Dropout, Activation

from keras.wrappers.scikit_learn import KerasClassifier

from keras.utils import np_utils

from sklearn.model_selection import train_test_split

from sklearn import model_selection, metrics

import json

max_words = 56681 # 입력 단어 수: word-dic.json 파일 참고

nb_classes = 9    # 9개의 카테고리

batch_size = 64 

nb_epoch = 20

# MLP 모델 생성하기 --- (※1)

def build_model():

    model = Sequential()

    model.add(Dense(512, input_shape=(max_words,)))

    model.add(Activation('relu'))

    model.add(Dropout(0.5))

    model.add(Dense(nb_classes))

    model.add(Activation('softmax'))

    model.compile(loss='categorical_crossentropy',

        optimizer='adam',

        metrics=['accuracy'])

    return model

# 데이터 읽어 들이기--- (※2)

data = json.load(open("./newstext/data-mini.json"))

#data = json.load(open("./newstext/data.json"))

X = data["X"] # 텍스트를 나타내는 데이터

Y = data["Y"] # 카테고리 데이터

# 학습하기 --- (※3)

X_train, X_test, Y_train, Y_test = train_test_split(X, Y)

Y_train = np_utils.to_categorical(Y_train, nb_classes)

model = KerasClassifier(

    build_fn=build_model, 

    nb_epoch=nb_epoch, 

    batch_size=batch_size)

model.fit(X_train, Y_train)

print(len(X_train),len(Y_train))

# 예측하기 --- (※4)

y = model.predict(X_test)

ac_score = metrics.accuracy_score(Y_test, y)

cl_report = metrics.classification_report(Y_test, y)

print("정답률 =", ac_score)

print("리포트 =\n", cl_report)




[#170826 3 lev-distance]


# 레벤슈타인 거리 구하기

def calc_distance(a, b):

    ''' 레벤슈타인 거리 계산하기 '''

    if a == b: return 0

    a_len = len(a)

    b_len = len(b)

    if a == "": return b_len

    if b == "": return a_len

    # 2차원 표 (a_len+1, b_len+1) 준비하기 --- (※1)

    matrix = [[] for i in range(a_len+1)]

    for i in range(a_len+1): # 0으로 초기화

        matrix[i] = [0 for j in range(b_len+1)]

    # 0일 때 초깃값을 설정

    for i in range(a_len+1):

        matrix[i][0] = i

    for j in range(b_len+1):

        matrix[0][j] = j

    # 표 채우기 --- (※2)

    for i in range(1, a_len+1):

        ac = a[i-1]

        for j in range(1, b_len+1):

            bc = b[j-1]

            cost = 0 if (ac == bc) else 1

            matrix[i][j] = min([

                matrix[i-1][j] + 1,     # 문자 삽입

                matrix[i][j-1] + 1,     # 문자 제거

                matrix[i-1][j-1] + cost # 문자 변경

            ])

    return matrix[a_len][b_len]

# "가나다라"와 "가마바라"의 거리 --- (※3)

print(calc_distance("가나다라","가마바라"))

# 실행 예

samples = ["신촌역","신천군","신천역","신발","마곡역"]

base = samples[0]

r = sorted(samples, key = lambda n: calc_distance(base, n))

for n in r:

    print(calc_distance(base, n), n)




[참고자료]


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

http://konlpy-ko.readthedocs.io/ko/v0.4.3/

https://ithub.korean.go.kr/user/total/database/corpusView.do

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

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

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


본글은 지금까지 한 머신러닝에  딥러닝을 적용하는 방법에 대한 글입니다.

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


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


1. 머신러닝에 딥러닝 적용 ==>[ # 170819 5 keras-bmi ]

  - 모델구조를 정의하고 , 모델을 컴파일 하고 , 모델을 이용해서 학습을 시킴,  이외 과정은 딥 러닝과 동일함.

  - 즉 딥러닝은 머신러닝의 한 부분임을 알수있음.

170819 6 bmi.csv


4. 참고자료


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


[ # 170819 5 keras-bmi ]


from keras.models import Sequential

from keras.layers.core import Dense, Dropout, Activation

from keras.callbacks import EarlyStopping

import pandas as pd, numpy as np

# BMI 데이터를 읽어 들이고 정규화하기 --- (※1)

csv = pd.read_csv("bmi.csv")

# 몸무게와 키 데이터

csv["weight"] /= 100

csv["height"] /= 200

X = csv[["weight", "height"]].as_matrix() # --- (※1a)

# 레이블

bclass = {"thin":[1,0,0], "normal":[0,1,0], "fat":[0,0,1]}

y = np.empty((20000,3))

for i, v in enumerate(csv["label"]):

    y[i] = bclass[v]

# 훈련 전용 데이터와 테스트 전용 데이터로 나누기 --- (※2)

X_train, y_train = X[1:15001], y[1:15001]

X_test,  y_test  = X[15001:20001], y[15001:20001] 

# 모델 구조 정의하기 --- (※3)

model = Sequential()

model.add(Dense(512, input_shape=(2,)))

model.add(Activation('relu'))

model.add(Dropout(0.1))

model.add(Dense(512))

model.add(Activation('relu'))

model.add(Dropout(0.1))

model.add(Dense(3))

model.add(Activation('softmax'))

# 모델 구축하기 --- (※4)

model.compile(

    loss='categorical_crossentropy',

    optimizer="rmsprop",

    metrics=['accuracy'])

# 데이터 훈련하기 --- (※5)

hist = model.fit(

    X_train, y_train,

    batch_size=100,

    nb_epoch=20,

    validation_split=0.1,

    callbacks=[EarlyStopping(monitor='val_loss', patience=2)],

    verbose=1)

# 테스트 데이터로 평가하기 --- (※6)

score = model.evaluate(X_test, y_test)

print('loss=', score[0])

print('accuracy=', score[1])




[참고자료]


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

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

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

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

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


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

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


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


1. 외국어 문장 판별  => [ # 170814 7 xor-train ]

   . count=list(map(lambda n : n/total,count)) ==> 주의 " list " 를 넣치 않으면 error 발생

   . 언어별 알파벳 사용횟수가 틀리다는 점을 이용해서, 문장을 주고 영어인지 프랑스어인지 등 구분하는 알고리즘임. 유첨(학습,테스트 데이터)

lang.zip


2. 외국어별 알파벳 사용빈도을 그래프로 표식하여 비교 ==> [ 170816 3 lang-train graph ]

3. 독버섯과 식용버섯 구분==> [ #170819 3 mushroom-train ]

170819 1 mushroom.csv


4. 참고자료


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


[ # 170816 2 lang-train ]



from sklearn import svm, metrics

import glob, os.path ,re, json


files=glob.glob("./lang/train/*.txt")

train_data=[]

train_label=[]

for file_name in files :

    basename=os.path.basename(file_name)

    lang=basename.split("-")[0]

    file=open(file_name,"r",encoding="utf-8")

    text=file.read()

    text=text.lower()

    file.close()

    code_a = ord("a")

    code_z = ord("z")

    count = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

    for character in text:

        code_current=ord(character)

        if code_a<=code_current <=code_z :

            count[code_current-code_a] +=1

    total=sum(count)

    count=list(map(lambda n : n/total,count))

#리스트에 넣기

    train_label.append(lang)

    train_data.append(count)

#print(train_data)

#print("=========================================================================")

#print(train_label)


files=glob.glob("./lang/test/*.txt")

test_data=[]

test_label=[]

for file_name in files :

    basename=os.path.basename(file_name)

    lang=basename.split("-")[0]

    file=open(file_name,"r",encoding="utf-8")

    text=file.read()

    text=text.lower()

    file.close()

    code_a = ord("a")

    code_z = ord("z")

    count = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

    for character in text:

        code_current=ord(character)

        if code_a<=code_current <=code_z :

            count[code_current-code_a] +=1

    total=sum(count)

    count=list(map(lambda n : n/total,count))

#리스트에 넣기

    test_label.append(lang)

    test_data.append(count)

#print(train_data)

#print("=========================================================================")

#print(train_label)


clf = svm.SVC()

clf.fit(train_data, train_label)

predict=clf.predict(test_data)

score=metrics.accuracy_score(test_label, predict)

print("score=",score)

report=metrics.classification_report(test_label, predict)

print("--------report-----------")

print(report)



[ 170816 3 lang-train graph ]


from sklearn import svm, metrics

import glob, os.path ,re, json

import matplotlib.pyplot as plt

import pandas as pd



files=glob.glob("./lang/train/*.txt")

train_data=[]

train_label=[]

for file_name in files :

    basename=os.path.basename(file_name)

    lang=basename.split("-")[0]

    file=open(file_name,"r",encoding="utf-8")

    text=file.read()

    text=text.lower()

    file.close()

    code_a = ord("a")

    code_z = ord("z")

    count = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

    for character in text:

        code_current=ord(character)

        if code_a<=code_current <=code_z :

            count[code_current-code_a] +=1

    total=sum(count)

    count=list(map(lambda n : n/total,count))

#리스트에 넣기

    train_label.append(lang)

    train_data.append(count)


# 그래픽 준비하기

graph_dict={}

for i in range(0,len(train_label)):

    label = train_label[i]

    data = train_data[i]

    if not (label in graph_dict) :

        graph_dict[label]=data

asclist=[[chr(n) for n in range(97,97+26)]]

print(asclist)

df=pd.DataFrame(graph_dict, index=asclist)


# 그래프 그리기

plt.style.use('ggplot')

df.plot(kind="bar",subplots=True,ylim=(0,0.15))

plt.savefig('lang-plot.png')





[ #170819 3 mushroom-train ]

import pandas as pd

from sklearn.ensemble import RandomForestClassifier

from sklearn import metrics

from sklearn.model_selection import train_test_split

# 데이터 읽어 들이기--- (※1)

mr = pd.read_csv("170819 1 mushroom.csv", header=None)

# 데이터 내부의 기호를 숫자로 변환하기--- (※2)

label = []

data = []

attr_list = []

for row_index, row in mr.iterrows():

    label.append(row.ix[0])

    row_data = []

    for v in row.ix[1:]:

        row_data.append(ord(v))

    data.append(row_data)

# 학습 전용과 테스트 전용 데이터로 나누기 --- (※3)

data_train, data_test, label_train, label_test = \

    train_test_split(data, label)

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

clf = RandomForestClassifier()

clf.fit(data_train, label_train)

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

predict = clf.predict(data_test)

# 결과 테스트하기 --- (※6)

ac_score = metrics.accuracy_score(label_test, predict)

cl_report = metrics.classification_report(label_test, predict)

print("정답률 =", ac_score)

print("리포트 =\n", cl_report)



[참고자료]


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

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

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

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

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


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

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


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


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


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

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

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


본글은 인공지능에 입력할 학습data를 구하는 방법에 관한 글입니다 ( 인터넷에 흩어져 있는 자료수집 )

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


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

[ 웹상의 데이타 가져오기 ]

1.개발환경 구성

  - 아나콘다 기준으로 설명합니다.  

  - Docker를 설치하고, 우분투를 설치하고, 우분투에서 각종 패키지(apt-get install)를 설치해도 무방합니다.
  - 아나콘다는 파이선 패키지를 쉽게 설치할수있도록 도와줍니다.
    . conda install ~
    . pip ~ 등으로 설치한다

2.웹사이트에 자료요청하는 방식 ==> get 요청

3.웹사이트에서 사진한장 가져오기 ==> download-png1

4.쇼핑몰에서 가격정보 가져오기 ==>bs-usd

5.포털에서 뉴스자료 가져오기 ==> download-bs-news2

6.웹 사이트에 파이선으로 프로그램 안에서 로그인 하기 ==> 170813 6 selenium-login

7.자바스크립트를 이용해서 자료 가져오기 selenium-js

8.날씨정보 가져오기 ==>170813 8 api-weather

9.네이버에서 이메일 가져오기 ==> 170813 10 selenium-login

   - 네이버 메일을 가져오는 코드입니다.

   - 네이버에 처음 로그인시에는

      . 1)로그인 ,2)새로운 기기 등록 , 3)로그인상태 유지 3단계의 단계를 통과해야 합니다. 각각 단계에 버튼입력코드가 필요합니다

      . 두번째 부터는 새로운 기기등록 , 로그인상태 유지  2단계의 코드는 필요없습니다, 주석처리를 해야합니다. 주석 처리 않하면 error 발생

10  날씨 가져오기 ==>170814 1 xml-forecast] 
11. 깃 허브에서 자료가져오기 ==>170814 2 json-github

12  csv 화일 읽기 ==> [# EUC_KR로 저장된 CSV 파일 읽기]

13. 엑셀화일 읽기==>[# 170814 4 excel-read]

  - 다운받은 엑셀은  다름이름으로 저장 " 엑셀통합문서" 로 저장해야 파이선에서 불러올수 있음

14. 엑셀에 자료 입력하기[ # 170814 5 write excel ]



[ Next Step ]

  ==> 가져온 데이터를 머신러닝으로 학습 시키기


[ 참고자료 ]

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



[ 개발환경 구성 ] 

1. 아나콘다 기준으로 설명합니다.  
  - Docker를 설치하고, 우분투를 설치하고, 우분투에서 각종 패키지(apt-get install)를 설치해도 무방합니다.
  - 아나콘다는 파이선 패키지를 쉽게 설치할수있도록 도와줍니다.


아나콘다에서 설치

phantomjs

conda install -c trent phantomjs 

conda install -c javascript phantomjs 

conda install -c javascript/label/dev phantomjs

conda install -c mutirri phantomjs 

conda install -c mutirri/label/bokeh-deps phantomjs 

conda install -c mutirri/label/all phantomjs 

conda install -c mutirri/label/selenium phantomjs

selenium

conda install -c metaperl selenium  ==> python 2.xx

conda install -c conda-forge selenium  ==> python 3.xx

beautifulsoup4

conda install -c anaconda beautifulsoup4 ==>python 4.xx

fontconfig

conda install -c anaconda fontconfig python 2.xx




[ Get 요청 ] 

# https://search.naver.com/search.naver?where=nexearch&sm=top_hty&fbm=1&ie=utf8&query=%EC%B4%88%EC%BD%9C%EB%A6%BF

import urllib.request
import urllib.parse
API = "https://search.naver.com/search.naver"
# 매개변수를 URL 인코딩합니다. --- (※1)
values = {
"where" : "nexearch" ,
"sm" : "top_hty" ,
"where" : "nexearch" ,
"fbm" : "1" ,
"ie" : "utf8" ,
"query" : "초콜릿"
}
params = urllib.parse.urlencode(values)
# 요청 전용 URL을 생성합니다. --- (※2)
url = API + "?" + params
print("url=", url)
# 다운로드합니다. --- (※3)
data = urllib.request.urlopen(url).read()
text = data.decode("utf-8")  #euc-kr"
print(text)


[ download-png1 ] 

# 170813 2 download-png1

import urllib.request

# data를 불러올 사이트/화일
url="http://uta.pw/shodou/img/28/214.png"

# 불러운 화일을 저장할 이름
savename="test.png"

# 다운로드 (1)
mem=urllib.request.urlopen(url).read()

#파일로 저장하기 (2)
#"wb" 는 binary file(인간이 읽을수 없음)을 의미함
with open(savename,mode="wb") as f:
    f.write(mem)

print("저장되었습니다")


[ bs-usd ] 

#170813 3 bs-usd

from bs4 import BeautifulSoup
import urllib.request as req
# HTML 가져오기
url = "http://info.finance.naver.com/marketindex/"
res = req.urlopen(url)
# HTML 분석하기
soup = BeautifulSoup(res, "html.parser")
# 원하는 데이터 추출하기 --- (※1)
price = soup.select_one("div.head_info > span.value").string
print("usd/krw =", price)


[ download-bs-news2 ]

# bs-news2

from bs4 import BeautifulSoup
# 분석 대상 HTML --- (※1)
html = """
<html><body>
<div id="meigen">
  <h1>위키북스 도서</h1>
  <ul class="items">
    <li>유니티 게임 이펙트 입문</li>
    <li>스위프트로 시작하는 아이폰 앱 개발 교과서</li>
    <li>모던 웹사이트 디자인의 정석</li>
  </ul>
</div>
</body></html>
"""
# HTML 분석하기 --- (※2)
soup = BeautifulSoup(html, 'html.parser')
# 필요한 부분을 CSS 쿼리로 추출하기
# 타이틀 부분 추출하기 --- (※3)
h1 = soup.select_one("div#meigen > h1").string
print("h1 =", h1)
# 목록 부분 추출하기 --- (※4)
li_list = soup.select("div#meigen > ul.items > li")
for li in li_list:
  print("li =", li.string)



170813 6 selenium-login ]

#"로그인 버튼을 클릭합니다.") 이후 부터 정상실행 않됨

# 170813 6 selenium-login
from selenium import webdriver
USER = "**********"
PASS = "*************^"
# PhantomJS 드라이버 추출하기 --- (※1)
browser = webdriver.PhantomJS()
browser.implicitly_wait(3)
# 로그인 페이지에 접근하기 --- (※2)
url_login = "https://nid.naver.com/nidlogin.login"
browser.get(url_login)
print("로그인 페이지에 접근합니다.")
# 텍스트 박스에 아이디와 비밀번호 입력하기 --- (※3)
e = browser.find_element_by_id("id")
e.clear()
e.send_keys(USER)
e = browser.find_element_by_id("pw")
e.clear()
e.send_keys(PASS)
# 입력 양식 전송해서 로그인하기 --- (※4)
form = browser.find_element_by_css_selector("input.btn_global[type=submit]")
form.submit()
print("로그인 버튼을 클릭합니다.")
# 여기까지만 정상실행됨
# 쇼핑 페이지의 데이터 가져오기 --- (※5)
browser.get("https://order.pay.naver.com/home?tabMenu=SHOPPING")
# 쇼핑 목록 출력하기 --- (※6)
products = browser.find_elements_by_css_selector(".sub_sc h4")
print(products)
for product in products:
    print("-", product.text)


[  170813 67selenium-js ]

# 170813 67selenium-js

from selenium import webdriver
# PhantomJS 드라이버 추출하기
browser = webdriver.PhantomJS()
browser.implicitly_wait(3)
# 적당한 웹 페이지 열기
browser.get("https://google.com")
# 자바스크립트 실행하기
r = browser.execute_script("return 100 + 50")
print(r)

[# 170813 8 api-weather]
mport requests
import json
# API 키를 지정합니다. 자신의 키로 변경해서 사용해주세요. --- (※1)
apikey = "474d59dd890c4108f62f192e0c6fce01"
# 날씨를 확인할 도시 지정하기 --- (※2)
cities = ["Seoul,KR", "Tokyo,JP", "New York,US"]
# API 지정 --- (※3)
api = "http://api.openweathermap.org/data/2.5/weather?q={city}&APPID={key}"
# 켈빈 온도를 섭씨 온도로 변환하는 함수 --- (※4)
k2c = lambda k: k - 273.15
# 각 도시의 정보 추출하기 --- (※5)
for name in cities:
    # API의 URL 구성하기 --- (※6)
    url = api.format(city=name, key=apikey)
    # API에 요청을 보내 데이터 추출하기
    r = requests.get(url)
    # 결과를 JSON 형식으로 변환하기 --- (※7)
    data = json.loads(r.text)    
    # 결과 출력하기 --- (※8)
    print("+ 도시 =", data["name"])
    print("| 날씨 =", data["weather"][0]["description"])
    print("| 최저 기온 =", k2c(data["main"]["temp_min"]))
    print("| 최고 기온 =", k2c(data["main"]["temp_max"]))
    print("| 습도 =", data["main"]["humidity"])
    print("| 기압 =", data["main"]["pressure"])
    print("| 풍향 =", data["wind"]["deg"])
    print("| 풍속 =", data["wind"]["speed"])
    print("")




[# 170813 10 selenium-login]

이메일 제목읽어오기

# 170813 10 selenium-login

from selenium import webdriver
# PhantomJS 드라이버 추출하기 --- (※1)
browser = webdriver.PhantomJS()
# 3초 대기하기 --- (※2) phantumjs의 버그로 무조건 3초를 대기하고 , 이후 진행해야함
browser.implicitly_wait(3)
# 로그인 --- (※3)
browser.get("https://nid.naver.com/nidlogin.login")
# 화면을 캡처해서 저장하기 --- (※4)
element_id=browser.find_element_by_id("id") # 아이디 텍스트 입력
element_id.clear()
element_id.send_keys("****")

element_pw=browser.find_element_by_id("pw") # 비번 텍스트 입력
element_pw.clear()
element_pw.send_keys("****^")
browser.save_screenshot("website_c.png")
# 브라우저 종료하기 --- (※5)

button=browser.find_element_by_css_selector("input.btn_global[type=submit]")
button.submit()

# 메일 페이지 열기
browser.get("https://mail.naver.com/")
browser.save_screenshot("website_D.png")

#브라우져 종료
browser.quit()




[ #170814 1 xml-forecast] 
 -. 날씨 가져오기

from bs4 import BeautifulSoup 
import urllib.request #as req
import os.path
url = "http://www.kma.go.kr/weather/forecast/mid-term-rss3.jsp?stnId=108"
request = urllib.request.urlopen(url)
xml = request.read()
soup=BeautifulSoup(xml,"html.parser")
seoul=soup.find_all("location")[0]
datas=seoul.find_all("data")
for item in datas :
   print(item.find("wf").text)


[ # 170814 2 json-github ]


# 170814 2 json-github

import urllib.request as request
import os.path, random
import json

# JSON 데이터 내려받기 --- (※1)
url = "https://api.github.com/repositories"
savename = "repo.json"
if not os.path.exists(url):
    request.urlretrieve(url, savename)
# JSON 파일 분석하기 --- (※2)
items = json.load(open(savename, "r", encoding="utf-8"))
# 또는
# s = open(savename, "r", encoding="utf-8").read()
# items = json.loads(s)
# 출력하기 --- (※3)
for item in items:
    print(item["name"] + " - " + item["owner"]["login"])

print("--------------------------------------")

json_str=request.urlopen("https://api.github.com/repositories").read()
output=json.loads(json_str)

for item in output :
    print(item["name"])
    print(item["full_name"])
    print(item["owner"]["login"])
print()


[# EUC_KR로 저장된 CSV 파일 읽기]

import codecs
# EUC_KR로 저장된 CSV 파일 읽기
filename = "list-euckr.csv"
csv = codecs.open(filename, "r", "euc_kr").read()
# CSV을 파이썬 리스트로 변환하기
data = []
rows = csv.split("\r\n")
for row in rows:
    if row == "": continue
    cells = row.split(",")
    data.append(cells)
# 결과 출력하기
for c in data:
    print(c[1], c[2])


[# 170814 4 excel-read]

import openpyxl
book=openpyxl.load_workbook("stats_104102.xlsx")
#print(book.get_sheet_names())
#print(book.get_sheet_by_name("stats_104102")

sheet = book.worksheets[0]
for row in sheet.rows:
    for data in row:
     print(data.value,end=" ")
    print("",end="\n")

http://www.index.go.kr/potal/main/EachDtlPageDetail.do?idx_cd=1041


[ # 170814 5 write excel ]

import openpyxl

workbook=openpyxl.Workbook()
sheet=workbook.active

sheet["A1"] = "테스트 화일"
sheet["A2"] = "안녕"

sheet.merge_cells("A1:C1")
sheet["A1"].font=openpyxl.styles.Font(size=20,color="FF0000")

workbook.save("newFile.xlsx")


[ 참고자료 ]

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

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

인공지능 구현 에 대한 글입니다.(Deep Reinforcement Learning)


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


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

요약

 - 신경망 (Neural Network)즉  Q-NETWORK 를 이용하여  Q-Learing 구현( q-talble 형식의경우 메모리가 기하 급수적으로 필요해짐 )

  ==> 실생활에 적용하게에는 무리가 있음(q-table 방식) , 따라서 신경망 방식이 필요해짐


1.q_net_frozenlake

 - Network 으로 변환 


2. 07_3_dqn_2015_cartpole

  - Q-NETWORk 이슈

   1) 데이터가 너무 적어 정확도가 좋치 못하다. 2개의 데이터로 학습을 하게되면 전혀 다른 직선이 나오게 되는것이다

      . 깊게(deep)

      . experience replay : action후 버퍼에 상태,action등 을 저장한다 , 이후 random(골고루) 하게 샘플링해서 학습한다

   2) 타겟이 흔들림 ( 같은 네트웍을 사용해서, 예측변경이 타겟치도 변경이 일어남) => 화살을 쏘자마자 과녁을 움직이는것 같음

      . network을 하나더 만든다 ( 각자 업데이트 하다가, 학습전에 복사해서 합친다)


3. Next Step

  ==> 신경망 (Neural Network)를 이용하여  Q-Learing 구현


4. 참고자료

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




[ 06_q_net_frozenlake ]



06_q_net_frozenlake


This code is based on

https://github.com/hunkim/DeepRL-Agents

'''

import gym

import numpy as np

import matplotlib.pyplot as plt

import time

import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'    # default value = 0  From http://stackoverflow.com/questions/35911252/disable-tensorflow-debugging-information


import tensorflow as tf

env = gym.make('FrozenLake-v0')


# Input and output size based on the Env

input_size = env.observation_space.n;

output_size = env.action_space.n;

learning_rate = 0.1


# These lines establish the feed-forward part of the network used to choose actions

X = tf.placeholder(shape=[1, input_size], dtype=tf.float32)              # state input

W = tf.Variable(tf.random_uniform([input_size, output_size], 0, 0.01))   # weight


Qpred = tf.matmul(X, W)     # Out Q prediction

Y = tf.placeholder(shape=[1, output_size], dtype=tf.float32)    # Y label


loss = tf.reduce_sum(tf.square(Y-Qpred))

train = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(loss)


# Set Q-learning parameters

dis = .99

num_episodes = 2000


# create lists to contain total rewards and steps per episode

rList = []


def one_hot(x):

    return np.identity(16)[x:x+1]


start_time = time.time()


init = tf.global_variables_initializer()

with tf.Session() as sess:

    sess.run(init)

    for i in range(num_episodes):

        # Reset environment and get first new observation

        s = env.reset()

        e = 1. / ((i / 50) + 10)

        rAll = 0

        done = False

        local_loss = []


        # The Q-Table learning algorithm

        while not done:

            # Choose an action by greedly (with a chance of random action)

            # from the Q-network

            Qs = sess.run(Qpred, feed_dict={X: one_hot(s)})

            if np.random.rand(1) < e:

                a = env.action_space.sample()

            else:

                a = np.argmax(Qs)


            # Get new state and reward from environment

            s1, reward, done, _ = env.step(a)

            if done:

                # Update Q, and no Qs+1, since it's a termial state

                Qs[0, a] = reward

            else:

                # Obtain the Q_s` values by feeding the new state through our network

                Qs1 = sess.run(Qpred, feed_dict={X: one_hot(s1)})

                # Update Q

                Qs[0, a] = reward + dis*np.max(Qs1)


            # Train our network using target (Y) and predicted Q (Qpred) values

            sess.run(train, feed_dict={X: one_hot(s), Y: Qs})


            rAll += reward

            s = s1


        rList.append(rAll)


print("--- %s seconds ---" % (time.time() - start_time))


print("Success rate: " + str(sum(rList) / num_episodes))

#plt.bar(range(len(rList)), rList, color="blue")

plt.bar(range(len(rList)), rList, color='b', alpha=0.4)

plt.show()



[07_3_dqn_2015_cartpole]


07_3_dqn_2015_cartpole


This code is based on

https://github.com/hunkim/DeepRL-Agents


CF https://github.com/golbin/TensorFlow-Tutorials

https://github.com/dennybritz/reinforcement-learning/blob/master/DQN/dqn.py


Q-NETWOR 이슈

 1. 데이터가 너무 적어 정확도가 좋치 못하다. 2개의 데이터로 학습을 하게되면 전혀 다른 직선이 나오게 되는것이다

   - 깊게(deep)

   - experience replay : action후 버퍼에 상태,action등 을 저장한다 , 이후 random(골고루) 하게 샘플링해서 학습한다

 2. 타겟이 흔들림 ( 같은 네트웍을 사용해서, 예측변경이 타겟치도 변경이 일어남) => 화살을 쏘자마자 과녁을 움직이는것 같음

    - network을 하나더 만든다

"""


import numpy as np

import tensorflow as tf

import random

from collections import deque

from dqn import dqn


import gym

from gym import wrappers


env = gym.make('CartPole-v0')


# Constants defining our neural network

input_size = env.observation_space.shape[0]

output_size = env.action_space.n


dis = 0.9

REPLAY_MEMORY = 50000


def replay_train(mainDQN, targetDQN, train_batch):

    x_stack = np.empty(0).reshape(0, input_size)

    y_stack = np.empty(0).reshape(0, output_size)


    # Get stored information from the buffer

    for state, action, reward, next_state, done in train_batch:

        Q = mainDQN.predic(state)


        # terminal?

        if done:

            Q[0, action] = reward

        else:

            # get target from target DQN (Q')

            Q[0, action] = reward + dis * np.max(targetDQN.predict(next_state))


        y_stack = np.vstack([y_stack, Q])

        x_stack = np.vstack( [x_stack, state])


    # Train our network using target and predicted Q values on each episode

    return mainDQN.update(x_stack, y_stack)


def ddqn_replay_train(mainDQN, targetDQN, train_batch):


#Double DQN implementation

#param mainDQN main DQN

#param targetDQN target DQN

#param train_batch minibatch for train

#return loss



    x_stack = np.empty(0).reshape(0, mainDQN.input_size)

    y_stack = np.empty(0).reshape(0, mainDQN.output_size)


    # Get stored information from the buffer

    for state, action, reward, next_state, done in train_batch:

        Q = mainDQN.predict(state)


        # terminal?

        if done:

            Q[0, action] = reward

        else:

            # Double DQN: y = r + gamma * targetDQN(s')[a] where

            # a = argmax(mainDQN(s'))

            Q[0, action] = reward + dis * targetDQN.predict(next_state)[0, np.argmax(mainDQN.predict(next_state))]


        y_stack = np.vstack([y_stack, Q])

        x_stack = np.vstack([x_stack, state])


    # Train our network using target and predicted Q values on each episode

    return mainDQN.update(x_stack, y_stack)


def get_copy_var_ops(*, dest_scope_name="target", src_scope_name="main"):


    # Copy variables src_scope to dest_scope

    op_holder = []


    src_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=src_scope_name)

    dest_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=dest_scope_name)


    for src_var, dest_var in zip(src_vars, dest_vars):

        op_holder.append(dest_var.assign(src_var.value()))


    return op_holder


def bot_play(mainDQN, env=env):

    # See our trained network in action

    state = env.reset()

    reward_sum = 0

    while True:

        env.render()

        action = np.argmax(mainDQN.predict(state))

        state, reward, done, _ = env.step(action)

        reward_sum += reward

        if done:

            print("Total score: {}".format(reward_sum))

            break


def main():

    max_episodes = 5000

    # store the previous observations in replay memory

    replay_buffer = deque()


    with tf.Session() as sess:

        mainDQN = dqn.DQN(sess, input_size, output_size, name="main")

        targetDQN = dqn.DQN(sess, input_size, output_size, name="target")

        tf.global_variables_initializer().run()


        #initial copy q_net -> target_net

        copy_ops = get_copy_var_ops(dest_scope_name="target", src_scope_name="main")

        sess.run(copy_ops)


        for episode in range(max_episodes):

            e = 1. / ((episode / 10) + 1)

            done = False

            step_count = 0

            state = env.reset()


            while not done:

                if np.random.rand(1) < e:

                    action = env.action_space.sample()

                else:

                    # Choose an action by greedily from the Q-network

                    action = np.argmax(mainDQN.predict(state))


                # Get new state and reward from environment

                next_state, reward, done, _ = env.step(action)

                if done: # Penalty

                    reward = -100


                # Save the experience to our buffer

                replay_buffer.append((state, action, reward, next_state, done))

                if len(replay_buffer) > REPLAY_MEMORY:

                      replay_buffer.popleft()


                state = next_state

                step_count += 1

                if step_count > 10000:   # Good enough. Let's move on

                    break


            print("Episode: {} steps: {}".format(episode, step_count))

            if step_count > 10000:

                pass

                ##10,000이면 정지(무한루프방지)

                # break


            if episode % 10 == 1: # train every 10 episode

                # Get a random batch of experiences

                for _ in range(50):

                    minibatch = random.sample(replay_buffer, 10)

                    loss, _ = ddqn_replay_train(mainDQN, targetDQN, minibatch)


                print("Loss: ", loss)

                # copy q_net -> target_net

                sess.run(copy_ops)


        # See our trained bot in action

        env2 = wrappers.Monitor(env, 'gym-results', force=True)


        for i in range(200):

            bot_play(mainDQN, env=env2)


        env2.close()

        # gym.upload("gym-results", api_key="sk_VT2wPcSSOylnlPORltmQ")


if __name__ == "__main__":

    main()



[ 참고자료 ]


  https://www.inflearn.com/course/기본적인-머신러닝-딥러닝-강좌

  https://github.com/hunkim/deeplearningzerotoall

  https://www.tensorflow.org/api_docs/python/tf/layers

  https://www.inflearn.com/course/reinforcement-learning/



인공지능 구현 에 대한 글입니다.(Deep Reinforcement Learning)


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


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

요약

 - 얼음얼린 호수에서 구멍에 빠지지 않고 길을 찾아나오는 게임임

 - 얼음은 미끄럽습니다. 길을 안내해주는 사람의 말을 전적으로 의지할경우, 오히려 바람등에 의해(불확실한 환경)

   미끄러질수가 있습니다. 따라서 약간만 의지하고, 나의 의지를 좀더 반영하는 방식으로 정확도를 높일수 있음 ( 1.5% ==> 66% 수준)

 - 현실도 주변 환경에의해 예측이 불가능한 경우가 많습니다. 이럴경우에 적용이 가능한 방식임.


1.OpenAI gym 게임을 위한 프로그램 설치


2. # 01_play_frozenlake_det_windows

 => 화살키를 입력하는 방향으로 이동

 => 화일 실행은 터미널에서 한다(키 인을 받기위함).

 => frozenlake_det_windows.py 가 있는 폴더로 가서, python 명령어 실행

 => 홀에 빠지거나,끝으로 가면 게임이 종료된다.


3.# 03_0_q_table_frozenlake_det

  => 초기에는 임의의 장소로, 두번째 부터는 큰곳으로 이동, 홀을 피해 길을 찾는 알고리즘임

  => 참고(random argmax) : 같은면 아무곳이나, 큰곳이 있으면 큰곳으로 간다

 

4. # 03_2_q_table_frozenlake_det

   ==>e보다 작으면 임의의 장소로 가고,그렇치 않으면, 큰 리워드방향으로 이동한다(explot &exporation)

  ==> 이사간 동네에서 초기에는 랜덤하게 식당을 다니고, 파악이 다되면 맞집위주로 찾아간다게 

  ==> 노이즈 값을 주어서, 기존의 data를 일부 반영하는 방법도 있음 ( 상기 e의 경우는 기존 data를 무시하됨)

      . 차선책을 선택하는 방법임

  ==> discount(0.9) 나중에 받을 리워드는 0.9를 곱해서 비중을 낮춘다.

       최단거리를 찾는 방법임


5. play_frozenlake_windows

 ==> keyboard 인식이 잘 않됨, 추후 보완필요

 ==> 빙판길로, 키보드 조작대로 움직이지 않고, Q 선생의 말에 전적으로 의존하지 않는 상황을 의미함

 ==> 현실세계와 비슷한 환경을 구현하는것임.


6. #05_0_q_table_frozenlake

  ==>미끄러운 환경 ('FrozenLake-v0' ) 에서는 Q 형님의 조언을 그대로 따르면 않된다, 주변환경에 의해  미끄질수 있기때문임

  ==> 빙판에서, 기존과 같이 Q 형님의 말에 전적으로 의존할 경우  1.55%  , 일부 의존할경우 66%


7. # 05_q_table_frozenlake

  ==>미끄러운 환경 ('FrozenLake-v0' ) 에서는 Q 형님의 조언을 그대로 따르면 않된다, 주변환경에 의해  미끄질수 있기때문임

     따라서 Q 형님의 말을 조금만 반영할 필요가 있음

 ==> Q[state, action] = (1-learning_rate) * Q[state, action] \

   + learning_rate*(reward + dis * np.max(Q[new_state, :]))

 ==> 정확도가 어느정도 상승함 (1.55% ==>  66% )

   . 빙판에서, Q 형님의 말에 전적으로 의존할 경우  1.55%  , 일부 의존할경우 66%


8. Next Step

  ==> 신경망 (Neural Network)를 이용하여  Q-Learing 구현


9. 참고자료

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




[ 1.OpenAI gym 게임을 위한 프로그램 설치 ]


- 설치가이드 :https://gym.openai.com/docs

- step 1

  . anaconda3 prompt 실행

- step 2

  . git clone https\\github.com/openai/gym  ==> gym 다운받기

  . cd gym ==> gym 폴더로 이동

  . pip3 install -e . ==> minimal install , pip3로 해야함 , gym으로 다운받은 gym을 pc에 설치해 주는 과정임

- step3 ==> 해당 python 선택( 패키지 별로 python 설치경로가 틀려서, 해당 python을 찾아서 연결시켜 주어야함

  . python 편집기(pycharm 프로그램 설정) 의 interpreter 변경

  . 변경전 : tensorflow 폴더의 python

  . 변경후 : c:\\user\dhp\appdata3\python.exe



- step4 ==> 패키지 추가 ==> tensorflow 패키지 설치가 필요할경우 pycharm 에서 설치가능함

  . 우측상단의 " + " 버튼을 누르면, 설치가능한 패키지 목록이 나옵니다. 여기서 tesorflow를 선택해서 설치한다.

  . 이로서   c:\\user\dhp\appdata3\python.exe의 python에는  gym 과 tesorflow가 동시에 설치됨

  . 진행중 필요한 패키지는 상황에 맞게 추가 설치하면 됨.

- tensorflow 내의 python에 패키지 추가방법 추가확인 필요함. gym설치되어 있는데, 잘 동작하지 않고있음.



- 설치성공 여부 확인 : pycharm 화면에서 아래 코딩후 실행확인

  # cartpolo test


"""cartpolo test

"""

import gym

env = gym.make('CartPole-v0')

env.reset()

for _ in range(100):

    env.render()

    env.step(env.action_space.sample()) # take a random action


for i_episode in range(20):

    observation = env.reset()

    for t in range(100):

        env.render()

        print(observation)

        action = env.action_space.sample()

        observation, reward, done, info = env.step(action)

        if done:

            print("Episode finished after {} timesteps".format(t+1))

            break




[ # 01_play_frozenlake_det_windows ]


# 01_play_frozenlake_det_windows

"""

화일 실행은 터미널에서 한다(키 인을 받기위함).

frozenlake_det_windows.py 가 있는 폴더로 가서, python 명령어 실행

홀에 빠지거나,끝으로 가면 게임이 종료된다.

"""

import gym

from gym.envs.registration import register

from colorama import init

from kbhit import KBHit


init(autoreset=True)    # Reset the terminal mode to display ansi color


register(

    id='FrozenLake-v3',

    entry_point='gym.envs.toy_text:FrozenLakeEnv',

    kwargs={'map_name' : '4x4', 'is_slippery': False}

)


env = gym.make('FrozenLake-v3')        # is_slippery False

env.render()                             # Show the initial board


key = KBHit()


while True:


    action = key.getarrow();

    if action not in [0, 1, 2, 3]:

        print("Game aborted!")

        break


    state, reward, done, info = env.step(action)

    env.render()

    print("State: ", state, "Action: ", action, "Reward: ", reward, "Info: ", info)


    if done:

        print("Finished with reward", reward)

        break



[## 03_0_q_table_frozenlake_det ]


# 03_0_q_table_frozenlake_det

"""

 # random argmax : 같은면 아무곳이나, 큰곳이 있으면 큰곳으로 간다


"""


import gym

import numpy as np

import matplotlib.pyplot as plt

from gym.envs.registration import register

import random as pr


def rargmax(vector):    # https://gist.github.com/stober/1943451

    """ Argmax that chooses randomly among eligible maximum idices. """

    m = np.amax(vector)

    indices = np.nonzero(vector == m)[0]

    return pr.choice(indices)


register(

    id='FrozenLake-v3',

    entry_point='gym.envs.toy_text:FrozenLakeEnv',

    kwargs={'map_name' : '4x4', 'is_slippery': False}

)

env = gym.make('FrozenLake-v3')


# Initialize table with all zeros

Q = np.zeros([env.observation_space.n, env.action_space.n]) #16*4 사이즈임

# Set learning parameters

num_episodes = 2000


# create lists to contain total rewards and steps per episode

rList = []

for i in range(num_episodes):

    # Reset environment and get first new observation

    state = env.reset()

    rAll = 0

    done = False


    # The Q-Table learning algorithm

    while not done:

        action = rargmax(Q[state, :])  # random argmax : 같은면 아무곳이자, 큰곳이 있으면 큰곳으로 간다


        # Get new state and reward from environment

        new_state, reward, done, _ = env.step(action)


        # Update Q-Table with new knowledge using learning rate

        Q[state, action] = reward + np.max(Q[new_state, :])


        rAll += reward

        state = new_state

    rList.append(rAll)


print("Success rate: " + str(sum(rList) / num_episodes))

print("Final Q-Table Values")

print("LEFT DOWN RIGHT UP")

print(Q)


plt.bar(range(len(rList)), rList, color="blue")

#plt.bar(range(len(rList)), rList, color='b', alpha=0.4)

plt.show()



[# 03_2_q_table_frozenlake_det]


# 03_2_q_table_frozenlake_det

"""

   ==> e보다 작으면 임의의 장소로 가고,그렇치 않으면, 큰 리워드방향으로 이동한다(explot &exporation)

  ==> 이사간 동네에서 초기에는 랜덤하게 식당을 다니고, 파악이 다되면 맞집위주로 찾아간다게

  ==> 노이즈 값을 주어서, 기존의 data를 일부 반영하는 방법도 있음 ( 상기 e의 경우는 기존 data를 무시하됨)

      . 차선책을 선택하는 방법임

  ==> discount(0.9) 나중에 받을 리워드는 0.9를 곱해서 비중을 낮춘다.

       최단거리를 찾는 방법임



"""


import gym

import numpy as np

import matplotlib.pyplot as plt

from gym.envs.registration import register


register(

    id='FrozenLake-v3',

    entry_point='gym.envs.toy_text:FrozenLakeEnv',

    kwargs={'map_name' : '4x4', 'is_slippery': False}

)

env = gym.make('FrozenLake-v3')


# Initialize table with all zeros

Q = np.zeros([env.observation_space.n, env.action_space.n])

# Set learning parameters

dis = .99

num_episodes = 2000


# create lists to contain total rewards and steps per episode

rList = []

for i in range(num_episodes):

    # Reset environment and get first new observation

    state = env.reset()

    rAll = 0

    done = False


    e = 1. / ((i // 100) + 1)  # Python2 & 3

    # 후반부로 갈수록 e 값은 작아짐


    # The Q-Table learning algorithm

    while not done:

        # Choose an action by e-greedy

        if np.random.rand(1) < e:

            # e보다 작으면 임의의 장소로 가고

            # 랜더만 방향으로 많이 가게되면 정확도가 떨어질수 있음

            action = env.action_space.sample()

        else:

            # 그렇치 않으면, 큰 리워드방향으로 이동한다

            action = np.argmax(Q[state, :])


        # Get new state and reward from environment

        new_state, reward, done, _ = env.step(action)


        # Update Q-Table with new knowledge using decay rate

        Q[state, action] = reward + dis * np.max(Q[new_state, :])


        # 나중에 받을 리워드는 0.9를 곱해서 비중을 낮춘다. 최단거리를 찾는 방법임


        rAll += reward

        state = new_state

    rList.append(rAll)


print("Success rate: " + str(sum(rList) / num_episodes))

print("Final Q-Table Values")

print("LEFT DOWN RIGHT UP")

print(Q)

#plt.bar(range(len(rList)), rList, color="blue")

plt.bar(range(len(rList)), rList, color='b', alpha=0.4)

plt.show()



[# play_frozenlake_windows]


# play_frozenlake_windows


"""keyboard 인식이 잘 않됨, 추후 보완필요

빙판길로, 키보드 조작대로 움직이지 않고, Q 선생의 말에 전적으로 의존하지 않는 상황을 의미함"""


import gym

from gym.envs.registration import register

from colorama import init

from kbhit import KBHit


init(autoreset=True)    # Reset the terminal mode to display ansi color


env = gym.make('FrozenLake-v0')       # is_slippery True

env.render()                            # Show the initial board


key = KBHit()

while True:


    action = key.getarrow();

    if action not in [0, 1, 2, 3]:

        print("Game aborted!")

        break


    state, reward, done, info = env.step(action)

    env.render()

    print("State: ", state, "Action: ", action, "Reward: ", reward, "Info: ", info)


    if done:

        print("Finished with reward", reward)

        break


[#05_0_q_table_frozenlake]


#05_0_q_table_frozenlake

"""

미끄러운 환경 ('FrozenLake-v0' ) 에서는 Q 형님의 조언을 그대로 따르면 않된다, 주변환경에 의해  미끄질수 있기때문임

. 빙판에서, 기존과 같이 Q 형님의 말에 전적으로 의존할 경우  1.55%  , 일부 의존할경우 66%

"""


import gym

import numpy as np

import matplotlib.pyplot as plt

from gym.envs.registration import register

import random as pr


env = gym.make('FrozenLake-v0')


# Initialize table with all zeros

Q = np.zeros([env.observation_space.n, env.action_space.n])


# Set learning parameters

learning_rate = .85

dis = .99

num_episodes = 2000


# create lists to contain total rewards and steps per episode

rList = []

for i in range(num_episodes):

    # Reset environment and get first new observation

    state = env.reset()

    rAll = 0

    done = False


    # The Q-Table learning algorithm

    while not done:

        action = np.argmax(Q[state, :] + np.random.randn(1, env.action_space.n) / (i + 1))

        # Get new state and reward from environment

        new_state, reward, done, _ = env.step(action)


        # Update Q-Table with new knowledge using learning rate

        Q[state, action] = reward + dis * np.max(Q[new_state, :])

        state = new_state


        rAll += reward


    rList.append(rAll)


print("Success rate: " + str(sum(rList) / num_episodes))

print("Final Q-Table Values")

print("LEFT DOWN RIGHT UP")

print(Q)

plt.bar(range(len(rList)), rList, color="blue")

#plt.bar(range(len(rList)), rList, color='b', alpha=0.4)

plt.show()



[# 05_q_table_frozenlake]

# 05_q_table_frozenlake

"""

미끄러운 환경 ('FrozenLake-v0' ) 에서는 Q 형님의 조언을 그대로 따르면 않된다, 주변환경에 의해  미끄질수 있기때문임

따라서 Q 형님의 말을 조금만 반영할 필요가 있음

 ==> Q[state, action] = (1-learning_rate) * Q[state, action] \

   + learning_rate*(reward + dis * np.max(Q[new_state, :]))

 ==> 정확도가 어느정도 상승함 (1.55% ==>  66% )

   . 빙판에서, Q 형님의 말에 전적으로 의존할 경우  1.55%  , 일부 의존할경우 66%

"""


import gym

import numpy as np

import matplotlib.pyplot as plt

from gym.envs.registration import register

import random as pr


register(

    id='FrozenLake-v3',

    entry_point='gym.envs.toy_text:FrozenLakeEnv',

    kwargs={'map_name' : '4x4', 'is_slippery': False}

)


#env = gym.make('FrozenLake-v3')

env = gym.make('FrozenLake-v0')


# Initialize table with all zeros

Q = np.zeros([env.observation_space.n, env.action_space.n])


# Set learning parameters

learning_rate = .85

dis = .99

num_episodes = 2000


# create lists to contain total rewards and steps per episode

rList = []

for i in range(num_episodes):

    # Reset environment and get first new observation

    state = env.reset()

    rAll = 0

    done = False


    # The Q-Table learning algorithm

    while not done:

        action = np.argmax(Q[state, :] + np.random.randn(1, env.action_space.n) / (i + 1))


        # 노이즈 추가 ==>e 값 이용은, 처음부터 계산 , 노이지 값 이용은 기존값 반영  , 즉 차선책을 선택하는 방법임


        # Get new state and reward from environment

        new_state, reward, done, _ = env.step(action)

        # Q 형님의 말을 조금만 반영

        # Update Q-Table with new knowledge using learning rate

        Q[state, action] = (1-learning_rate) * Q[state, action] \

           + learning_rate*(reward + dis * np.max(Q[new_state, :]))


        rAll += reward

        state = new_state


    rList.append(rAll)


print("Success rate: " + str(sum(rList) / num_episodes))

print("Final Q-Table Values")

print("LEFT DOWN RIGHT UP")

print(Q)

#plt.bar(range(len(rList)), rList, color="blue")

plt.bar(range(len(rList)), rList, color='b', alpha=0.4)

plt.show()



[참고자료]


  https://www.inflearn.com/course/기본적인-머신러닝-딥러닝-강좌

  https://github.com/hunkim/deeplearningzerotoall

  https://www.tensorflow.org/api_docs/python/tf/layers

  https://www.inflearn.com/course/reinforcement-learning/



인공지능 구현에 대한 글입니다.


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


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

1.#lab-12-1-hello-rnn

 전 단계의 출력이 다음단계의 출력에 영향을 주는 경우 적용함

  - 단어, 연관검색등..


2. # lab-12-2-char-seq-rnn

  -rnn 적용  ==> 정확도 높음

    . 49 loss: 0.000650434 Prediction: if you want you

    . y값 if you want you


3.  #lab-12-3-char-seq-softmax-only

  rnn 미적용 ==> 정확도 미흡함

  2999 loss: 0.277323 Prediction: yf you yant you

  y값 if you want you


4. # lab-12-4-rnn_long_char

  error : from __future__ import print_function ==> 실행불가로 주석처리함

  MultiRNNCell 로 여러단을 만들면 , 정확도가 높아짐 

  softmax =>reshape 수행


5. # lab-12-5-rnn_stock_prediction"""
  내일 주가 예측 : 기존의 7일의 data를 학습
  그래프 인쇄않되고 있음.


6. 코드탐구(추가)

  ==>lab-12-5-rnn_stock_prediction

      lab-13-1-mnist_using_scope

      lab-13-2-mnist_tensorboard

      lab-13-3-mnist_save_restore


7. 참고자료

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




#lab-12-1-hello-rnn ]


#lab-12-1-hello-rnn

"""

전 단계의 출력이 다음단계의 출력에 영향을 주는 경우 적용함

- 단어, 연관검색등..


"""

import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

# Lab 12 RNN

import tensorflow as tf

import numpy as np

tf.set_random_seed(777)  # reproducibility


idx2char = ['h', 'i', 'e', 'l', 'o']

# Teach hello: hihell -> ihello

x_data = [[0, 1, 0, 2, 3, 3]]   # hihell

x_one_hot = [[[1, 0, 0, 0, 0],   # h 0

              [0, 1, 0, 0, 0],   # i 1

              [1, 0, 0, 0, 0],   # h 0

              [0, 0, 1, 0, 0],   # e 2

              [0, 0, 0, 1, 0],   # l 3

              [0, 0, 0, 1, 0]]]  # l 3


y_data = [[1, 0, 2, 3, 3, 4]]    # ihello


num_classes = 5

input_dim = 5  # one-hot size

hidden_size = 5  # output from the LSTM. 5 to directly predict one-hot

batch_size = 1   # one sentence

sequence_length = 6  # |ihello| == 6

learning_rate = 0.1


X = tf.placeholder(

    tf.float32, [None, sequence_length, input_dim])  # X one-hot

Y = tf.placeholder(tf.int32, [None, sequence_length])  # Y label


cell = tf.contrib.rnn.BasicLSTMCell(num_units=hidden_size, state_is_tuple=True)

initial_state = cell.zero_state(batch_size, tf.float32)

outputs, _states = tf.nn.dynamic_rnn(

    cell, X, initial_state=initial_state, dtype=tf.float32)


# FC layer

X_for_fc = tf.reshape(outputs, [-1, hidden_size])

# fc_w = tf.get_variable("fc_w", [hidden_size, num_classes])

# fc_b = tf.get_variable("fc_b", [num_classes])

# outputs = tf.matmul(X_for_fc, fc_w) + fc_b

outputs = tf.contrib.layers.fully_connected(

    inputs=X_for_fc, num_outputs=num_classes, activation_fn=None)


# reshape out for sequence_loss

outputs = tf.reshape(outputs, [batch_size, sequence_length, num_classes])


weights = tf.ones([batch_size, sequence_length])

sequence_loss = tf.contrib.seq2seq.sequence_loss(

    logits=outputs, targets=Y, weights=weights)

loss = tf.reduce_mean(sequence_loss)

train = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)


prediction = tf.argmax(outputs, axis=2)


with tf.Session() as sess:

    sess.run(tf.global_variables_initializer())

    for i in range(50):

        l, _ = sess.run([loss, train], feed_dict={X: x_one_hot, Y: y_data})

        result = sess.run(prediction, feed_dict={X: x_one_hot})

        print(i, "loss:", l, "prediction: ", result, "true Y: ", y_data)


        # print char using dic

        result_str = [idx2char[c] for c in np.squeeze(result)]

        print("\tPrediction str: ", ''.join(result_str))


'''

0 loss: 1.71584 prediction:  [[2 2 2 3 3 2]] true Y:  [[1, 0, 2, 3, 3, 4]]

Prediction str:  eeelle

1 loss: 1.56447 prediction:  [[3 3 3 3 3 3]] true Y:  [[1, 0, 2, 3, 3, 4]]

Prediction str:  llllll

2 loss: 1.46284 prediction:  [[3 3 3 3 3 3]] true Y:  [[1, 0, 2, 3, 3, 4]]

Prediction str:  llllll

3 loss: 1.38073 prediction:  [[3 3 3 3 3 3]] true Y:  [[1, 0, 2, 3, 3, 4]]

Prediction str:  llllll

4 loss: 1.30603 prediction:  [[3 3 3 3 3 3]] true Y:  [[1, 0, 2, 3, 3, 4]]

Prediction str:  llllll

5 loss: 1.21498 prediction:  [[3 3 3 3 3 3]] true Y:  [[1, 0, 2, 3, 3, 4]]

Prediction str:  llllll

6 loss: 1.1029 prediction:  [[3 0 3 3 3 4]] true Y:  [[1, 0, 2, 3, 3, 4]]

Prediction str:  lhlllo

7 loss: 0.982386 prediction:  [[1 0 3 3 3 4]] true Y:  [[1, 0, 2, 3, 3, 4]]

Prediction str:  ihlllo

8 loss: 0.871259 prediction:  [[1 0 3 3 3 4]] true Y:  [[1, 0, 2, 3, 3, 4]]

Prediction str:  ihlllo

9 loss: 0.774338 prediction:  [[1 0 2 3 3 4]] true Y:  [[1, 0, 2, 3, 3, 4]]

Prediction str:  ihello

10 loss: 0.676005 prediction:  [[1 0 2 3 3 4]] true Y:  [[1, 0, 2, 3, 3, 4]]

Prediction str:  ihello


...


'''


[# lab-12-2-char-seq-rnn ]


# lab-12-2-char-seq-rnn

"""

rnn 적용  ==> 정확도 높음

 - 49 loss: 0.000650434 Prediction: if you want you

 - y값 if you want you

"""

import os


os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

# Lab 12 Character Sequence RNN

import tensorflow as tf

import numpy as np

tf.set_random_seed(777)  # reproducibility


sample = " if you want you"

idx2char = list(set(sample))  # index -> char

char2idx = {c: i for i, c in enumerate(idx2char)}  # char -> idex


# hyper parameters

dic_size = len(char2idx)  # RNN input size (one hot size)

hidden_size = len(char2idx)  # RNN output size

num_classes = len(char2idx)  # final output size (RNN or softmax, etc.)

batch_size = 1  # one sample data, one batch

sequence_length = len(sample) - 1  # number of lstm rollings (unit #)

learning_rate = 0.1


sample_idx = [char2idx[c] for c in sample]  # char to index

x_data = [sample_idx[:-1]]  # X data sample (0 ~ n-1) hello: hell

y_data = [sample_idx[1:]]   # Y label sample (1 ~ n) hello: ello


X = tf.placeholder(tf.int32, [None, sequence_length])  # X data

Y = tf.placeholder(tf.int32, [None, sequence_length])  # Y label


x_one_hot = tf.one_hot(X, num_classes)  # one hot: 1 -> 0 1 0 0 0 0 0 0 0 0

cell = tf.contrib.rnn.BasicLSTMCell(

    num_units=hidden_size, state_is_tuple=True)

initial_state = cell.zero_state(batch_size, tf.float32)

outputs, _states = tf.nn.dynamic_rnn(

    cell, x_one_hot, initial_state=initial_state, dtype=tf.float32)


# FC layer

X_for_fc = tf.reshape(outputs, [-1, hidden_size])

outputs = tf.contrib.layers.fully_connected(X_for_fc, num_classes, activation_fn=None)


# reshape out for sequence_loss

outputs = tf.reshape(outputs, [batch_size, sequence_length, num_classes])


weights = tf.ones([batch_size, sequence_length])

sequence_loss = tf.contrib.seq2seq.sequence_loss(

    logits=outputs, targets=Y, weights=weights)

loss = tf.reduce_mean(sequence_loss)

train = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)


prediction = tf.argmax(outputs, axis=2)


with tf.Session() as sess:

    sess.run(tf.global_variables_initializer())

    for i in range(50):

        l, _ = sess.run([loss, train], feed_dict={X: x_data, Y: y_data})

        result = sess.run(prediction, feed_dict={X: x_data})


        # print char using dic

        result_str = [idx2char[c] for c in np.squeeze(result)]


        print(i, "loss:", l, "Prediction:", ''.join(result_str))



'''

0 loss: 2.35377 Prediction: uuuuuuuuuuuuuuu

1 loss: 2.21383 Prediction: yy you y    you

2 loss: 2.04317 Prediction: yy yoo       ou

3 loss: 1.85869 Prediction: yy  ou      uou

4 loss: 1.65096 Prediction: yy you  a   you

5 loss: 1.40243 Prediction: yy you yan  you

6 loss: 1.12986 Prediction: yy you wann you

7 loss: 0.907699 Prediction: yy you want you

8 loss: 0.687401 Prediction: yf you want you

9 loss: 0.508868 Prediction: yf you want you

10 loss: 0.379423 Prediction: yf you want you

11 loss: 0.282956 Prediction: if you want you

12 loss: 0.208561 Prediction: if you want you


...


'''


[#lab-12-3-char-seq-softmax-only]

#lab-12-3-char-seq-softmax-only

"""

rnn 미적용 ==> 정확도 미흡함

 - 2999 loss: 0.277323 Prediction: yf you yant you

 - y값 if you want you

"""


import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

# Lab 12 Character Sequence Softmax only

import tensorflow as tf

import numpy as np

tf.set_random_seed(777)  # reproducibility


sample = " if you want you"

idx2char = list(set(sample))  # index -> char

char2idx = {c: i for i, c in enumerate(idx2char)}  # char -> idex


# hyper parameters

dic_size = len(char2idx)  # RNN input size (one hot size)

rnn_hidden_size = len(char2idx)  # RNN output size

num_classes = len(char2idx)  # final output size (RNN or softmax, etc.)

batch_size = 1  # one sample data, one batch

sequence_length = len(sample) - 1  # number of lstm rollings (unit #)

learning_rate = 0.1


sample_idx = [char2idx[c] for c in sample]  # char to index

x_data = [sample_idx[:-1]]  # X data sample (0 ~ n-1) hello: hell

y_data = [sample_idx[1:]]   # Y label sample (1 ~ n) hello: ello


X = tf.placeholder(tf.int32, [None, sequence_length])  # X data

Y = tf.placeholder(tf.int32, [None, sequence_length])  # Y label


# flatten the data (ignore batches for now). No effect if the batch size is 1

X_one_hot = tf.one_hot(X, num_classes)  # one hot: 1 -> 0 1 0 0 0 0 0 0 0 0

X_for_softmax = tf.reshape(X_one_hot, [-1, rnn_hidden_size])


# softmax layer (rnn_hidden_size -> num_classes)

softmax_w = tf.get_variable("softmax_w", [rnn_hidden_size, num_classes])

softmax_b = tf.get_variable("softmax_b", [num_classes])

outputs = tf.matmul(X_for_softmax, softmax_w) + softmax_b


# expend the data (revive the batches)

outputs = tf.reshape(outputs, [batch_size, sequence_length, num_classes])

weights = tf.ones([batch_size, sequence_length])


# Compute sequence cost/loss

sequence_loss = tf.contrib.seq2seq.sequence_loss(

    logits=outputs, targets=Y, weights=weights)

loss = tf.reduce_mean(sequence_loss)  # mean all sequence loss

train = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)


prediction = tf.argmax(outputs, axis=2)


with tf.Session() as sess:

    sess.run(tf.global_variables_initializer())

    for i in range(3000):

        l, _ = sess.run([loss, train], feed_dict={X: x_data, Y: y_data})

        result = sess.run(prediction, feed_dict={X: x_data})


        # print char using dic

        result_str = [idx2char[c] for c in np.squeeze(result)]

        print(i, "loss:", l, "Prediction:", ''.join(result_str))


'''

0 loss: 2.29513 Prediction: yu yny y y oyny

1 loss: 2.10156 Prediction: yu ynu y y oynu

2 loss: 1.92344 Prediction: yu you y u  you


..


2997 loss: 0.277323 Prediction: yf you yant you

2998 loss: 0.277323 Prediction: yf you yant you

2999 loss: 0.277323 Prediction: yf you yant you

'''


[# lab-12-4-rnn_long_char]


# lab-12-4-rnn_long_char

"""

error : from __future__ import print_function ==> 실행불가로 주석처리함

# MultiRNNCell 로 여러단을 만들면 , 정확도가 높아짐

# softmax =>reshape 수행

"""


import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

# from __future__ import print_function


import tensorflow as tf

import numpy as np

from tensorflow.contrib import rnn


tf.set_random_seed(777)  # reproducibility


sentence = ("if you want to build a ship, don't drum up people together to "

            "collect wood and don't assign them tasks and work, but rather "

            "teach them to long for the endless immensity of the sea.")


char_set = list(set(sentence))

char_dic = {w: i for i, w in enumerate(char_set)}


data_dim = len(char_set)

hidden_size = len(char_set)

num_classes = len(char_set)

sequence_length = 10  # Any arbitrary number

learning_rate = 0.1


dataX = []

dataY = []

for i in range(0, len(sentence) - sequence_length):

    x_str = sentence[i:i + sequence_length]

    y_str = sentence[i + 1: i + sequence_length + 1]

    print(i, x_str, '->', y_str)


    x = [char_dic[c] for c in x_str]  # x str to index

    y = [char_dic[c] for c in y_str]  # y str to index


    dataX.append(x)

    dataY.append(y)


batch_size = len(dataX)


X = tf.placeholder(tf.int32, [None, sequence_length])

Y = tf.placeholder(tf.int32, [None, sequence_length])


# One-hot encoding

X_one_hot = tf.one_hot(X, num_classes)

print(X_one_hot)  # check out the shape



# Make a lstm cell with hidden_size (each unit output vector size)

def lstm_cell():

    cell = rnn.BasicLSTMCell(hidden_size, state_is_tuple=True)

    return cell


multi_cells = rnn.MultiRNNCell([lstm_cell() for _ in range(2)], state_is_tuple=True)

# 위와 같이.MultiRNNCell 로 여러단을 만들면 , 정확도가 높아짐


# outputs: unfolding size x hidden size, state = hidden size

outputs, _states = tf.nn.dynamic_rnn(multi_cells, X_one_hot, dtype=tf.float32)


# softmax =>reshape 수행


# FC layer

X_for_fc = tf.reshape(outputs, [-1, hidden_size])

outputs = tf.contrib.layers.fully_connected(X_for_fc, num_classes, activation_fn=None)


# reshape out for sequence_loss

outputs = tf.reshape(outputs, [batch_size, sequence_length, num_classes])


# All weights are 1 (equal weights)

weights = tf.ones([batch_size, sequence_length])


sequence_loss = tf.contrib.seq2seq.sequence_loss(

    logits=outputs, targets=Y, weights=weights)

mean_loss = tf.reduce_mean(sequence_loss)

train_op = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(mean_loss)


sess = tf.Session()

sess.run(tf.global_variables_initializer())


for i in range(500):

    _, l, results = sess.run(

        [train_op, mean_loss, outputs], feed_dict={X: dataX, Y: dataY})

    for j, result in enumerate(results):

        index = np.argmax(result, axis=1)

        print(i, j, ''.join([char_set[t] for t in index]), l)


# Let's print the last char of each result to check it works

results = sess.run(outputs, feed_dict={X: dataX})

for j, result in enumerate(results):

    index = np.argmax(result, axis=1)

    if j is 0:  # print all for the first result to make a sentence

        print(''.join([char_set[t] for t in index]), end='')

    else:

        print(char_set[index[-1]], end='')


'''

0 167 tttttttttt 3.23111

0 168 tttttttttt 3.23111

0 169 tttttttttt 3.23111

499 167  of the se 0.229616

499 168 tf the sea 0.229616

499 169   the sea. 0.229616


g you want to build a ship, don't drum up people together to collect wood and don't assign them tasks and work, but rather teach them to long for the endless immensity of the sea.


'''


[# lab-12-5-rnn_stock_prediction]


# lab-12-5-rnn_stock_prediction
"""
내일 주가 예측 : 기존의 7일의 data를 학습
그래프 인쇄않되고 있음.
"""

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
'''
This script shows how to predict stock prices using a basic RNN
'''
import tensorflow as tf
import numpy as np
import matplotlib
import os

tf.set_random_seed(777)  # reproducibility

if "DISPLAY" not in os.environ:
    # remove Travis CI Error
    matplotlib.use('Agg')

import matplotlib.pyplot as plt

def MinMaxScaler(data):
    ''' Min Max Normalization

    Parameters
    ----------
    data : numpy.ndarray
        input data to be normalized
        shape: [Batch size, dimension]

    Returns
    ----------
    data : numpy.ndarry
        normalized data
        shape: [Batch size, dimension]

    References
    ----------
    .. [1] http://sebastianraschka.com/Articles/2014_about_feature_scaling.html

    '''
    numerator = data - np.min(data, 0)
    denominator = np.max(data, 0) - np.min(data, 0)
    # noise term prevents the zero division
    return numerator / (denominator + 1e-7)


# train Parameters
seq_length = 7
data_dim = 5
hidden_dim = 10
output_dim = 1
learning_rate = 0.01
iterations = 500

# Open, High, Low, Volume, Close
xy = np.loadtxt('data-02-stock_daily.csv', delimiter=',')
xy = xy[::-1]  # reverse order (chronically ordered)
xy = MinMaxScaler(xy)
x = xy
y = xy[:, [-1]]  # Close as label

# build a dataset
dataX = []
dataY = []
for i in range(0, len(y) - seq_length):
    _x = x[i:i + seq_length]
    _y = y[i + seq_length]  # Next close price
    print(_x, "->", _y)
    dataX.append(_x)
    dataY.append(_y)

# train/test split
train_size = int(len(dataY) * 0.7)
test_size = len(dataY) - train_size
trainX, testX = np.array(dataX[0:train_size]), np.array(
    dataX[train_size:len(dataX)])
trainY, testY = np.array(dataY[0:train_size]), np.array(
    dataY[train_size:len(dataY)])

# input place holders
X = tf.placeholder(tf.float32, [None, seq_length, data_dim])
Y = tf.placeholder(tf.float32, [None, 1])

# build a LSTM network
cell = tf.contrib.rnn.BasicLSTMCell(
    num_units=hidden_dim, state_is_tuple=True, activation=tf.tanh)
outputs, _states = tf.nn.dynamic_rnn(cell, X, dtype=tf.float32)
Y_pred = tf.contrib.layers.fully_connected(
    outputs[:, -1], output_dim, activation_fn=None)  # We use the last cell's output

# cost/loss
loss = tf.reduce_sum(tf.square(Y_pred - Y))  # sum of the squares
# optimizer
optimizer = tf.train.AdamOptimizer(learning_rate)
train = optimizer.minimize(loss)

# RMSE
targets = tf.placeholder(tf.float32, [None, 1])
predictions = tf.placeholder(tf.float32, [None, 1])
rmse = tf.sqrt(tf.reduce_mean(tf.square(targets - predictions)))

with tf.Session() as sess:
    init = tf.global_variables_initializer()
    sess.run(init)

    # Training step
    for i in range(iterations):
        _, step_loss = sess.run([train, loss], feed_dict={
                                X: trainX, Y: trainY})
        print("[step: {}] loss: {}".format(i, step_loss))

    # Test step
    test_predict = sess.run(Y_pred, feed_dict={X: testX})
    rmse_val = sess.run(rmse, feed_dict={
                    targets: testY, predictions: test_predict})
    print("RMSE: {}".format(rmse_val))

    # Plot predictions
    plt.plot(testY)
    plt.plot(test_predict)
    plt.xlabel("Time Period")
    plt.ylabel("Stock Price")
    plt.show()


[참고자료]


  https://www.inflearn.com/course/기본적인-머신러닝-딥러닝-강좌

  https://github.com/hunkim/deeplearningzerotoall

  https://www.tensorflow.org/api_docs/python/tf/layers