반응형
반응형

랜덤 포레스트



기계 학습에서의 랜덤 포레스트(영어: random forest)는 분류회귀 분석 등에 사용되는 앙상블 학습 방법의 일종으로, 훈련 과정에서 구성한 다수의 결정 트리로부터 부류(분류) 또는 평균 예측치(회귀 분석)를 출력함으로써 동작한다.



정의

랜덤 포레스트는 여러 개의 결정 트리들을 임의적으로 학습하는 방식의 앙상블 방법이다. 랜덤 포레스트 방법은 크게 다수의 결정 트리를 구성하는 학습 단계와 입력 벡터가 들어왔을 때, 분류하거나 예측하는 테스트 단계로 구성되어있다. 랜덤 포레스트는 검출, 분류, 그리고 회귀 등 다양한 애플리케이션으로 활용되고 있다.

역사

랜덤 포레스트의 초기 발전은 단일 트리를 확장하는 맥락에서 이용 가능한 결정(available decisions)에 대한 임의의 부분집합(random subset)에 대해 검색하는 아이디어를 도입한 얄리 아미트(Yali Amit)와 도널드 게먼(Donald Geman)의 연구[1]에 영향을 받았다. 또한 임의의 부분공간(random subspace)을 선택하는 틴 캄 호(Tin Kam Ho)의 아이디어[2] 역시 랜덤 포레스트의 디자인에 영향을 미쳤다. 포레스트가 성장할 때, 각 트리를 맞추기(fitting) 전에 임의로 선택한 부분공간으로 훈련 데이터를 투영(projection) 시키는 과정에서 트리 사이에 변형이 일어난다.

현재의 랜덤 포레스트의 개념은 레오 브레이먼(Leo Breiman)의 논문[3]에서 만들어졌다. 이 논문에서는 임의 노드 최적화(randomized node optimization, RNO)와 배깅(bootstrap aggregating, bagging)을 결합한 방법과 같은 CART(classification and regression tree)를 사용해 상관관계가 없는 트리들로 포레스트를 구성하는 방법을 제시하였다.

동기

일반적으로 결정 트리를 이용한 방법의 경우, 그 결과 또는 성능의 변동 폭이 크다는 결점을 가지고 있다. 특히 학습 데이터에 따라 생성되는 결정 트리가 매우 달라지기 때문에 일반화하여 사용하기에 매우 어려움이 따른다. 특히, 결정 트리는 계층적 접근방식이기 때문에 만약 중간에 에러가 발생한다면 다음 단계로 에러가 계속 전파되는 특성을 가진다. 배깅(Bagging) 또는 임의 노드 최적화(Randomized node optimization)와 같은 임의화 기술은 결정 트리가 가진 이러한 단점을 극복하고 좋은 일반화 성능을 갖도록 한다.

기여

  • 월등히 높은 정확성
  • 간편하고 빠른 학습 및 테스트 알고리즘
  • 변수소거 없이 수천 개의 입력 변수들을 다루는 것이 가능
  • 임의화를 통한 좋은 일반화 성능
  • 다중 클래스 알고리즘 특성


반응형
반응형

[ChatScript] ChatScript 에서 Harry를 Dorothy로 바꾸고, 한글인사하기 


참고 : http://exagen.tistory.com/45


맥에선 설치가 안되고, 윈도우에서 잘되네. 이런. ComEmu는 원래 써오던거라 최신으로 업데이트 한번.


참고 글에서의 설명과 달리 버전이 변경되었는지 일단 느낌적으로 해봄. 


/RAWDATA/에 도로시를 Harry 카피해서 만든다. 

그리고, RAWDATA에 filesHarry.txt를 카피해서 filesDorothy.txt를 만든다. 

filesDorothy에서 RAWDATA/QUIBBLE/은 삭제. 삭제권고하셔서 삭제. 근데 build하면 왜 연결안하냐고 경고 나옴. 


CMD에서 >chatscript 실행. 

그리고, 빌드 >:build Dorothy

뭔가 안되서 보니 filesDorothy.txt 에  엉뚱한 내용이 있음. 


#underlying conversation system

RAWDATA/Dorothy/


위의 폴더 경로만 txt 파일에 들어있으면됨. 


다시 빌드하니 도로시가 인사를 한다. "Hi"  


"what is your name?" 이라고 하니까 "내 이름은  도로시에요." 라고 나온다. 

근데, 또 물어보면 딴 얘기함. 

그럴땐 리셋!!!


> :build Dorothy reset


introduction.top에서 영어를 국문으로 바꾸면 한국말 한다. ㅋㅋㅋ





...

반응형
반응형

[ChatScript] ChatScript - https://github.com/bwilcox-1234/ChatScript


Natural Language tool/dialog manager


ChatScript

Natural Language tool/dialog manager

ChatScript is the next generation chatbot engine that has won the Loebner's 4 times and is the basis for natural language company for a variety of tech startups.

ChatScript is a rule-based engine, where rules are created by humans writers in program scripts through a process called dialog flow scripting. These use a scripting metalanguage (simply called a "script") as their source code. Here what a ChatScript script file looks like:

#
# file: food.top
#
topic: ~food []

#! I like spinach
s: ( I like spinach ) Are you a fan of the Popeye cartoons?
	
	a: ( ~yes )  I used to watch him as a child. Did you lust after Olive Oyl?
    	    b: ( ~no ) Me neither. She was too skinny.
    	    b: ( yes ) You probably like skinny models.
	
	a: ( ~no ) What cartoons do you watch?
     		b: ( none ) You lead a deprived life.
     		b: ( Mickey Mouse ) The Disney icon.

#! I often eat chicken
u: ( ![ not never rarely ] I * ~ingest * ~meat ) You eat meat.

#! I really love chicken
u: ( !~negativeWords I * ~like * ~meat ) You like meat.

#! do you eat bacon?
?: ( do you eat _ [ ham eggs bacon] ) I eat '_0

#! do you like eggs or sushi?
?: ( do you like _* or _* ) I don't like '_0 so I guess that means I prefer '_1.

#! I adore kiwi.
s: ( ~like ~fruit ![~animal _bear] )  Vegan, you too...

#! do you eat steak?
?: ( do you eat _~meat ) No, I hate _0.

#! I eat fish.
s: ( I eat _*1 > ) 
  $food = '_0 
  I eat oysters.

Above example mentioned in article How to build your first chatbot using ChatScript.

Basic Features

  • Powerful pattern matching aimed at detecting meaning.
  • Simple rule layout combined with C-style general scripting.
  • Built-in WordNet dictionary for ontology and spell-checking.
  • Extensive extensible ontology of nouns, verbs, adjectives, adverbs.
  • Data as fact triples enables inferencing and supports JSON representation.
  • Rules can examine and alter engine and script behavior.
  • Planner capabilities allow a bot to act in real/virtual worlds.
  • Remembers user interactions across conversations.
  • Document mode allows you to scan documents for content.
  • Ability to control local machines via popen/tcpopen/jsonopen.
  • Ability to read structured JSON data from websites.
  • Postgres and Mongo databases support for big data or large-user-volume chatbots.

OS Features

  • Runs on Windows or Linux or Mac or iOS or Android
  • Fast server performance supports a thousand simultaneous users.
  • Multiple bots can cohabit on the same server.

Support Features

  • Mature technology in use by various parties around the world.
  • Integrated tools to support maintaining and testing large systems.
  • UTF8 support allows scripts written in any language
  • User support forum on chatbots.org
  • Issues or bugs on this repo

Getting started

Installation

Take this project and put it into some directory on your machine (typically we call the directory ChatScript, but you can name it whatever). That takes care of installation.

git clone https://github.com/bwilcox-1234/ChatScript

Standalone mode - run locally on a console (for developement/test)

From your ChatScript home directory, go to the BINARIES directory:

cd BINARIES

And run the ChatScript engine

Windows

ChatScript

Linux

./LinuxChatScript64 local

Note: to set the file executable: chmod a+x ./LinuxChatScript64

MacOS

./MacChatScript local

This will cause ChatScript to load and ask you for a username. Enter whatever you want. You are then talking to the default demo bot Harry.

Server Mode (for production)

From your ChatScript home directory, go to the BINARIES directory and run the ChatScript engine as server

Run the server on Windows

ChatScript port=1024

Run the server on Linux

./LinuxChatScript64

Run the server on MacOS

./MacChatScript

This will cause ChatScript to load as a server.
But you also need a client (to test client-server communication). You can run a separate command window and go to the BINARIES directory and type

Run a client (test) on Windows

ChatScript client=localhost:1024 

Run a client (test) on Linux

./LinuxChatScript64 client=localhost:1024

Run a client (test) on MacOS

./MacChatScript client=localhost:1024

This will cause ChatScript to load as a client and you can talk to the server.

How to build a bot

Run ChatScript locally. From the ChatScript command prompt, type

:build Harry

or whatever other preinstalled bot exists. If you have revised basic data, you can first:

:build 0

How to compile the engine.

On windows if you have Visual Studio installed, launch VS2010/chatscript.sln or VS2015/chatscript.sln and do a build. The result will go in the BINARIES directory.

On Linux, go stand in the SRC directory and type make server (assuming you have make and g++ installed). This creates BINARIES/ChatScript, which can run as a server or locally. There are other make choices for installing PostGres or Mongo.

Full Documentation

ChatScript Wiki (user guides, tutorials, papers)

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Last releases

changes.md

Author


반응형
반응형

[ChatScript] ChatScript start & stop


설치 디렉토리 에서  ./BINARIES/의 CHARSCRIPT 명령어 실행. 


>chatscript 


Enter user name : 이름


한참 대화 후 종료할때 명령어. 


:quit


>:quit  

Exiting ChatScript via Quit


D:\>  



반응형
반응형


Scikit-Learn 을 이용한 전처리


문서 전처리 - Scikit-Learn 의 문서 전처리 기능 https://datascienceschool.net/view-notebook/3e7aadbf88ed4f0d87a76f9ddc925d69/

 

 


도서 카테고리 예측하기 프로젝트 #1 데이터 수집 및 전처리하기

 - http://www.sturdylad.co.kr/%EB%8F%84%EC%84%9C-%EC%B9%B4%ED%85%8C%EA%B3%A0%EB%A6%AC-%EC%98%88%EC%B8%A1%ED%95%98%EA%B8%B0-%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8-%EB%8D%B0%EC%9D%B4%ED%84%B0%EC%A0%84%EC%B2%98%EB%A6%AC/


 도서 카테고리 예측하기 프로젝트 #2 데이터 학습 시키기

  - http://www.sturdylad.co.kr/%EB%8F%84%EC%84%9C-%EC%B9%B4%ED%85%8C%EA%B3%A0%EB%A6%AC-%EC%98%88%EC%B8%A1%ED%95%98%EA%B8%B0-%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8-%EB%AA%A8%EB%8D%B8%ED%95%99%EC%8A%B5/


 도서 카테고리 예측하기 프로젝트 #3 생성된 모델로 텍스트 데이터 카테고리 예측해보기

 - http://www.sturdylad.co.kr/%EB%8F%84%EC%84%9C-%EC%B9%B4%ED%85%8C%EA%B3%A0%EB%A6%AC-%EC%98%88%EC%B8%A1%ED%95%98%EA%B8%B0-%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8-%EC%98%88%EC%B8%A1%ED%95%98%EA%B8%B0/



...



반응형
반응형



6.2. 파일을 입맛대로(pickle, glob, os.path)

파일을 입맛대로 요리할 수 있도록 여러 가지 비법을 전수해드리지요. 먼저 조금 복잡한 자료를 파일에 쓰고 읽는 방법부터 알아봅시다. 이럴 때는 pickle(피클)이란 모듈을 사용합니다. 왜 피자 먹을 때 나오는 반찬을 이름으로 붙였는지…

예제로는 회원의 ID와 비밀번호를 파일에 저장하는 것을 생각해보았습니다.

>>> users = {'kim':'3kid9', 'sun80':'393948', 'ljm':'py90390'}
>>> f = open('d:/python21/exam/users.txt', 'w')
>>> import pickle
>>> pickle.dump(users, f)
>>> f.close()

처음에 ID와 비밀번호를 users라는 사전에 담았습니다. 그리고 users.txt라는 파일을 새로 열어서 f라고 했구요. 그 다음에는 오이지(pickle^^;) 모듈의 덤프(dump)를 사용했습니다.

여러분 덤프 트럭 다 아시죠? 왜 공사장에서 흙 싣고 다니는 무지 큰 트럭 있잖아요. 그런 차는 뒤쪽 짐칸을 들어올려서 흙을 와르르 쏟아내지 않습니까? 여기서 보시는 dump도 마찬가지입니다. users라는 리스트의 내용을 파일 f에 와르르 쏟아붓는 거지요. 음, 이렇게까지 설명할 필요는 없을 텐데… 오늘 쓸 것이 없다보니…

이제 메모장으로 users.txt 파일을 열어보시면 모양이 좀 지저분하긴 해도 데이터가 다 들어있는 걸 보실 수 있을 거예요.

그렇다면 이 파일에 들어있는 것을 원래대로 돌려볼까요? 원래대로 돌리는 것도 역시 오이지 모듈이 할 일이겠죠.

>>> f = open('d:/python21/exam/users.txt')
>>> a = pickle.load(f)
>>> print a
{'sun80': '393948', 'kim': '3kid9', 'ljm': 'py90390'}

사실 방금 보여드린 것은 그리 복잡할 것도 없지만 pickle 모듈은 파이썬에서 만들어지는 것은 뭐든지 다 파일에 적을 수 있다고 합니다. '그게 뭐 어때서'라고 생각하실지 모르겠지만 이건 놀라운 기능이라고 튜토리얼에 쓰여있습니다.

오이지는 이쯤 해두고, 전에 잠깐 구경했던 glob 모듈에 대해 알아보도록 하죠. glob는 파일들의 목록을 뽑을 때 사용하는데, 파일의 경로명을 이용해서 입맛대로 요리할 수 있답니다.

>>> import glob
>>> glob.glob('*.*')
['INSTALL.LOG', 'LICENSE.txt', 'NEWS.txt', 'py.ico', 'pyc.ico',
'pycon.ico', 'python.exe', 'pythonw.exe', 'readme.txt',
'UNWISE.EXE', 'w9xpopen.exe']
>>> glob.glob('*.txt')
['LICENSE.txt', 'NEWS.txt', 'readme.txt']

위의 별표(*)는 무슨 글자든, 몇 글자든 상관 없다는 뜻으로, 디렉토리(폴더)에 들어있는 파일들을 그냥 다 보려면 *.*라고 해주면 됩니다. 파일명에 상관 없이 확장자가 txt인 파일을 모두 보고 싶으면 *.txt라고 하면 되지요.

다음은 glob과 함께 os.path 모듈을 사용한 예제입니다.

>>> import os.path
>>> files = glob.glob('*')
>>> for x in files:
...     print x,
...     if os.path.isdir(x):                  # 디렉토리인가?
...             print '<DIR>'
...     else:
...             print ''

스크립트만 보고 어떤 일을 하는건지 짐작이 가시는지요?

둘째줄에서 glob.glob('*')를 해서 얻어진 파일 목록들을 files라는 리스트로 넣어줬습니다. 그 다음부터는 for 문을 통해서 파일명을 하나씩 출력한 다음 그것이 디렉토리이면 <DIR>이라고 출력해주고, 그렇지 않으면 그냥 줄만 넘겨주도록 했지요.



...


반응형

+ Recent posts