프로그래밍 Programming
01. Rattle 설치 및 실행
2014. 11. 27.rattle 설치 및 실행 > install.packages("rattle")Installing package into ‘C:/Users/fukaeri/Documents/R/win-library/3.1’(as ‘lib’ is unspecified)trying URL 'http://cran.nexr.com/bin/windows/contrib/3.1/rattle_3.3.0.zip'Content type 'application/zip' length 3211032 bytes (3.1 Mb)opened URLdownloaded 3.1 Mb package ‘rattle’ successfully unpacked and MD5 sums checked The downloaded binary packages are inC..
16. 워드 클라우드 Word Clouds - 옵션
2014. 11. 27.Word Clouds 의 기타옵션 Reducing Clutter With Max Words - 표시될 단어의 갯수를 max.words 를 통해 늘리거나 줄일 수 있다.> set.seed(142)> wordcloud(names(freq), freq, max.word= 100) Reducing Clutter With Min Freq - 표시될 갯수를 제한하는 또 다른 방법은 min.freq 를 이용하는 것이다. 아래 예제는 최소 12번 이상 언급되는 단어들만 나타나도록 했다.> set.seed(142)> wordcloud(names(freq), freq, min.freq= 9) Adding Some Colour - Color-Brewer (Neuwirth, 2011)의 brewer.pal() 를 이용하여 색..
15. 워드 클라우드 Word Clouds
2014. 11. 26.아래와 같이 corpus 내의 단어들을 대상으로 빈도 기준으로 워드 클라우드 Word Clouds 를 만들어 본다. > install.packages("wordcloud") // 패키지부터 설치하고Installing package into ‘C:/Users/fukaeri/Documents/R/win-library/3.1’(as ‘lib’ is unspecified)trying URL 'http://cran.nexr.com/bin/windows/contrib/3.1/wordcloud_2.5.zip'Content type 'application/zip' length 466745 bytes (455 Kb)opened URLdownloaded 455 Kb package ‘wordcloud’ successfull..
14. 워드 출현빈도 그래프로 나타내기 Plotting Word Frequencies
2014. 11. 26.sort() 를 이용하여 해당 corpus 내 모든 단어들의 빈도를 카운트할 수 있다. > freq head(freq,14) the and that you have will this but draft 71 56 51 27 15 15 13 11 11 about all strickland: for know 10 10 9 8 8 > wf head(wf) word freqthe the 71and and 56that that 51you you 27have have 15will will 15 > library(ggplot2) Attaching package: ‘ggplot2’ The following object is masked from ‘package:NLP’: annotate > p 10), aes(word,..
13. 상관관계 그래프로 보여주기 Correlations Plots
2014. 11. 26.Rgraphviz 는 corpus 내 선택된 단어들간의 상관관계를 네트워크 그래프로 보여주는 기능을 한다. 아래는 10번 이상 언급된 단어들 중 상관관계가 0.5 이상인 5개의 단어들 간의 관계를 보여주는 그래프이다. 상관도라든지 빈도 등의 옵션이 주어지지 않았을 때 기본값은 20번 이상 언급, 그리고 0.7 의 상관도이다. > plot(dtm, terms=findFreqTerms(dtm, lowfreq=10)[1:5], corThreshold=0.5)Loading required package: RgraphvizLoading required package: graphLoading required package: grid
12. 등장빈도 및 단어간 상관도에 의거한 term 조회 Identifying Frequent Items and Associations
2014. 11. 25.등장빈도에 따른 term 조회는 findFreqTerms()를 이용한다. > findFreqTerms(dtm,lowfreq=1000) // 최소 1,000번 이상 등장한 term, 없다.character(0)> findFreqTerms(dtm,lowfreq=10) // 10번 이상 나온 term [1] "about" "all" "and" "but" "draft" "have" "that" "the" "this" [10] "will" "you" We can also nd associations with a word, specifying a correlation limit.특정 단어와의 상관도를 기준으로한 조회도 가능하다. findAssocs() 를 이용하는 것으로, 두 단어가 항상 같이 등장하면 그 값은 1..
11. Removing Sparse Terms
2014. 11. 25.sparse는 0 또는 등장하지 않는 term 이 얼마나 많은지를 의미하는 것으로, 수많은 0 으로 이루어진 행렬의 경우 알고리즘이 불필요한 수행으로 쓸데없는 시간을 낭비하게 만든다. 이런 경우 sparse term을 제거함으로써 효율적인 데이터 분석을 할 수 있다. removeSparseTerms() 을 이용하여 sparse term 을 제거할 수 있으며, 필요한 것은 얼마만큼의 행을 지워버릴 것인가이다. 현상태에서 보면 sparsity = 90% 이며, 의미있는 actual data values ("non-sparse entities") 는 547개이다. 먼저 sparse 를 70 으로 한 경우는 다음과 같다. > dtm.common.70 inspect(dtm.common.70)해당 corpus 내에..
리눅스 방화벽 설정 iptables
2014. 11. 25.1. 변경내용 적용방법iptables 파일은 아래에서 보시다시피 /etc/sysconfig 에 위치한다. 직접 수정후 업로딩하거나 아래와 같이 콘솔상에서 직접 편집한다. #cd /etc/sysconfig/#vi iptables#service iptables restart#/etc/init.d/iptables save2. 도입부# Firewall configuration written by lokkit# Manual customization of this file is not recommended.# Note: ifup-post will punch the current nameservers through the# firewall; such entries will *not* be listed here.*fi..
ftp 프로그램 파일질라 FileZilla 편집기 설정변경방법
2014. 11. 25.ftp 프로그램 파일질라 FileZilla 편집기 설정변경방법 기본설정과 편집하려는 파일 유형에 따라서는 아래와 같이 보기 불편한 뷰를 선보이는 경우가 있다. 파일 유형에 따라 편집기를 달리 설정하거나 아니면 쓸만한 놈으로 기본편집기를 설정해보자. [편집] - [설정] - [파일편집] 으로 이동하여 아래와 같이 '사용자 편집기 사용'을 체크한 후 찾아보기를 통해 기본 편집기를 선택한다. 여기서는 eclipse 를 사용하기로 한다. 해당 실행파일을 선택한 후 아래 메뉴에서 '항상 기본 편집기 사용'에 체크한 후 [확인]을 누른다. 아래와 같이 이클립스에서 해당 파일이 열리는 것을 볼 수 있다. [파일편집] 서브메뉴인 [파일유형연결]을 통해서는 확장자별로 편집프로그램을 달리 가져갈 수도 있다.텍스트박스에 직..
10. 행렬로 전환하여 CSV 포맷으로 저장하기 Conversion to Matrix and Save to CSV
2014. 11. 22.Document-term matrix 를 다른 툴에서 활용할 수 있도록 CSV 파일로 저장하기 위해 단순 행렬로 변환할 수 있다. 아래와 같은 방법으로 행렬 변환이 가능하다.> m dim(m)[1] 10 531R의 계산한계를 넘어서는 경우에는 아래와 같은 에러 메시지가 출력된다.## Error in vector(typeof(x$v), nr * nc) : vector size cannot be NA## In addition: Warning message:## In nr * nc : NAs produced by integer overflow이런 경우에는 밀도가 희박한 term 을 제거하는 것을 고려해볼 필요가 있다. 일단 표준 행렬로 변환되고 나면, write.csv() 를 이용하여 파일로 저장할 수 있다...
09. term의 출현빈도에 대한 분포 구하기 Distribution of Term Frequencies
2014. 11. 22.앞에서 살펴본 term의 출현 빈도에 대한 분포를 구한다 > head(table(freq),15) // Frequency of frequenciesfreq 1 2 3 4 5 6 7 8 9 10 11 13 15 27 51 // 그러니깐 1번 나오는 용어가 362개, 2번 나오는 용어가 82개와 같은 식362 82 31 16 8 11 6 3 1 2 2 1 2 1 1 > tail(table(freq),15)freq 3 4 5 6 7 8 9 10 11 13 15 27 51 56 71 // 71번 나오는 용어는 1개와 같은 식31 16 8 11 6 3 1 2 2 1 2 1 1 1 1 >
08. Exploring the Document Term Matrix
2014. 11. 22.Document-term matrix 를 행렬로 변환하고, 컬럼끼리 값을 합하여 출현빈도를 구할 수 있다.> freq length(freq)[1] 531위의 freq 를 정렬함으로써, 출현 빈도가 가장 높은 term과 가장 낮은 term을 구할 수 있다. > ord freq[head(ord)] // # Least frequent terms (sample @coordinator @delighted @she @two 10,000. 1 1 1 1 1 1 > freq[tail(ord)] // # most frequent termshave will you that and the 15 15 27 51 56 71 > freq[tail(ord,10)] // 갯수 지정도 가능 all but draft this have ..
07. Document-Term행렬 만들기 Creating a Document-Term Matrix
2014. 11. 22.Document-term matrix 란 문서를 행으로, 그리고 용어를 열로 가지는 행렬로, 해당 문서의 해당 용어의 출현빈도를 카운팅해서 알려준다. DocumentTermMatrix() 를 이용하여 해당 행렬을 만들 수 있다. 예를 들면, 다음과 같다. D1 = "I like databases"D2 = "I hate databases",then the document-term matrix would be:IlikehatedatabasesD11101D21011 [출처] http://en.wikipedia.org/wiki/Document-term_matrix아래와 같이 실행해보면 총 10개의 문서에, 503개의 용어가 사용되고 있음을 알 수 있다. > dtm dtmNon-/sparse entries: 51..
06. Stemming 어간추출
2014. 11. 22.Stemming 어간추출 예를 들면, "es", "ed", "s" 와 같은 common word endings english 을 제거하는 알고리즘을 이용한다. SnowballC 패키지의 wordStem() 의 기능을 이용한다(Bouchet-Valat, 2014) 많은 경우에 데이터 분석을 위해 어간을 추출할 필요가 있다. 예를 들어, "example" 과 "examples" 은 동일한 "exampl" 에서 비롯되었다고 할 수 있기 때문이다. 아래 결과를 통해 추출전과 추출후를 비교해보자. > doc[[3]]STRICKLAND: All right. So it will be prior to August 14th or whatever date it is.> doc[[6]]STRICKLAND: Way prior..
05. Preparing the Corpus - 특정 변환
2014. 11. 22.Specific Transformations 의 예 > toString inspect(doc[6]) [[1]]clewell yes im coordinator reading language arts montgomery county public schools suburban district surrounding washington schools elementary schools > doc inspect(doc[6]) [[1]]clewell yes im coordinator reading language arts montgomery county public schools suburban district surrounding WA schools elementary schools
04. Preparing the Corpus - 기본 변환
2014. 11. 22.1. 소문자 변환 Conversion to Lower Case > inspect(doc[2]) [[1]]STRICKLAND: Good morning. > doc inspect(doc[2]) [[1]]strickland: good morning. // G -> g 로 변환되었음을 알 수 있다. 2. 숫자 지우기 Remove Numbers > inspect(doc[6]) [[1]]clewell: yes. i'm the coordinator for reading language arts with the montgomery county public schools which is the suburban district surrounding washington. we have 173 schools and 25 el..
03. Exploring the corpus - 전처리 및 간단한 변환
2014. 11. 21.1. Exploring the Corpusinspect() 를 이용하여 문서의 데이터가 제대로 로딩되었는지 확인이 가능하다. > inspect(docs[2]) [[1]]NULL2. Preparing the Corpus텍스트 분석을 위해서 경우에 따라서는 전처리 과정이 필요할 수 있다. 아래에서 보듯이 대상 텍스트를 소문자로 변환시키고, 숫자를 제거하는 등의 기능을 갖고 있음을 확인할 수 있다. > getTransformations()## [1] "removeNumbers" "removePunctuation" "removeWords"## [4] "stemDocument" "stripWhitespace"변환을 위해서는 tm_map() 을 사용한다. 아래에서 살펴본다. 3. Simple Transforms 아..
02. Loading a Corpus (txt, pdf, word)
2014. 11. 18.1. Corpus 로딩분석의 대상이 되는 문서의 포맷은 다양하지만, 우리가 앞으로 사용하게 될 tm 패키지는 꽤 많은 포맷을 지원한다. text, PDF, Microsoft Word, XML.의 포맷을 포함한다. 2. Corpus Sources and Readers1) sources> getSources()[1] "DataframeSource" "DirSource" "URISource" "VectorSource" "XMLSource" 2) readers - 텍스트 분석 결과는 다음의 포맷 등으로 표현가능하다> getReaders()[1] "readDOC" "readPDF" "readPlain" "readRCV1" [5] "readRCV1asPlain" "readReut21578XML" "readReut2..
01. 텍스트마이닝(Text Mining)을 위한 패키지 준비
2014. 11. 14.본격적인 텍스트 마이닝에 앞서 아래 패키지들이 설치되어 있는지 먼저 확인한다. 설치되어 있지 않으면 install.packages("tm") 과 같은 식으로 설치한 후 아래와 같이 실행한다. > library("tm") > library("SnowballC") > library("RColorBrewer") > library("ggplot2") > library("Rgraphviz")> install.packages("Rgraphviz")Installing package into ‘C:/Users/fukaeri/Documents/R/win-library/3.1’(as ‘lib’ is unspecified)Warning in install.packages : package ‘Rgraphviz’ is not ..
Plot geoms(geometric objects) (1) - 추세선 그리기 (span, gam, lm, rlm)
2014. 11. 9.Geom(geometric object)은 데이터를 보여주는데 사용되는 객체의 유형으로, gplot 은 산포도에 다양한 형태의 geom 을 표현할 수 있다.이 외에도 "histogram", "freqpoly", "density", "bar" 등 다양한 객체가 존재한다. geom 설명 "point" 산포도에 사용. qplot() 사용시 기본값 "smooth" 데이터의 추세선을 나타내고, 표준오차의 정도를 나타내는 데 사용 "boxplot" 상자그림, 상자수염도, 분포를 요약해서 나타내는 데 사용 "path", "line" 데이터 포인트 사이에 선으로 연결. line 은 왼쪽에서 오른쪽으로 그려지는 반면, path 는 어느 방향으로든지 가능하다. 1. 추세선 그리기 무수한 데이터 포인트로 이루어진 산포도로는..
ggplot2 패키지 설치 및 기본사용법
2014. 11. 9.※ 본 예제에 사용하는 diamonds dataset 는 ggplot2 패키지에 포함되어 있다. ※ ggplot2 패키지의 설치는 다음과 같이 한다. > install.package('ggplot2') 위 데이터는 정제되지 않은 데이터이므로 아래와 같이 랜덤으로 100개의 샘플을 뽑아낸 dsmall 이라는 dataset 를 이용해서 얘기를 전개해나가고자 한다. > library("ggplot2", lib.loc="~/R/win-library/3.1") > set.set(1410) Error: could not find function "set.set" dsmall qplot(carat, price, data = diamonds) 2. qplot() 은 아래와 같이 변수의 함수를 인수로 가질 수 있음 > ..
데이터 읽기, 데이터 프레임, 세분화, 요약 (Data Handling)
2014. 11. 1.1. 텍스트 포맷으로 저장하기1) 엑셀의 데이터를 R 로 가져오기 위해 text 포맷으로 저장한다. 2) 엑셀 프로그램에서 파일 > 다른이름으로저장 > 파일 형식에서 '텍스트 (탭으로 분리)' 선택 2. R 에서 데이터 읽기1) read.table 을 이용해서 R 로 읽어들일 수 있다. > degrees = read.table(file.choose(), sep = "\t", header = TRUE) // sep = "\t" 는 탭으로 구분된다는 의미이고, header = TRUE 는 첫번째 행에 변수 이름을 포함한다는 의미이다. 파일을 선택하는 팝업이 뜨면 읽고자 하는 파일을 선택하면 된다. 3. 데이터 프레임1) 이렇게 읽어들인 값은 data frame 라는 형태로 저장된다. 2) 데이터 프레임은 변..
Information Visualization (15) - R 그래픽 기초 (직선그래프 영역채우기)
2014. 10. 29.> y // y x=1920:1970> plot.new() > plot.window(xlim=c(1920,1970), xaxs="i",ylim=c(46.5,55.5), yaxs="i") > abline(v=seq(1930,1960,by=10), col="gray") //배경 그리드 그리기> abline(h=seq(48,54, by=2), col="gray")> xx=c(1920,x,1970) > yy=c(46.5,y,46.5)> polygon(xx,yy,col="gray") // 다각형 그리기> axis(1)> axis(2, las=1)> box()>
Information Visualization (14) - R 그래픽 기초 (그래프 그리기 Line Graphs, Curves)
2014. 10. 29.1. 직선 그리기 > plot.new()> plot.window(xlim = c(1, 4), ylim = c(0, 3)) > x = c(1, 2, 3, 4)> y = c(0, 2, 1, 3)> lines(x, y)> axis(1)> axis(2)> box()2. 곡선 그리기 특정 구간 사이에 y = f (x) 형태의 그래프를 그리는 경우가 많은데,하나의 방법은 해당 구간을 잘게 잘라 직선의 모음으로 보는 것이다. 예를 들면, 다음과 같이 정규분포곡선을 그릴 수 있다. > x = seq(-3, 3, length = 1000) // 해당 구간을 1,000개로 쪼갠다> y = dnorm(x) > plot.new()> plot.window(xlim = range(x), ylim = range(y))> lines..
Information Visualization (13) - R 그래픽 기초 (축 axis)
2014. 10. 29.1. 축과 주석 axis(1, at=1:4, lab=c("A", "B", "C", "D"))예제의 경우 x축 1, 2, 3, 4 에 tick mark 가 위치하고 각각에 "A", "B", "C", "D" 라고 라벨을 붙인다는 의미- las=. 라벨의 로테이션 결정 (기본값은 0 이며 값에 따라 다음과 같다) las=0 : 항상 축과 평행(parallel) las=1 : 항상 수평(horizontal) las=2 : 항상 축에 대해 수직(perpendicular) las=3 : 항상 수직(vertical) 2. 축의 최대, 최소값 설정 plot.window(xlim=c(0,1), ylim=c(10,20), xaxs="i")- xlim, ylim : x 축, y 축 각각의 최소값과 최대값을 지정하는 것으로 ..
Information Visualization (12) - R 그래픽 기초 (텍스트, 범례)
2014. 10. 25.1. 텍스트 넣기 text(x, y, labels)- x, y : 텍스트가 위치하는 좌표- labels : 삽입되는 문장- col : 텍스트 색깔- srt : 문장의 방향 (수평으로부터 반시계방향으로 각도)- adj : 위치조정 > plot.new()> plot.window(xlim = c(0, 5), ylim = c(0, 10))> axis(1)> axis(2)> box()> text(1,2,"text",srt=0)> text(2,3,"text",srt=90)> text(3,4,"text",srt=180)> text(4,5,"text",srt=270)> text(3,5,"text",srt=180, adj=1) 2. 범례 legend(xloc, yloc,legend = c("Exact", "Approxi..
Information Visualization (11) - R 그래픽 기초 (도형 그리기)
2014. 10. 25.1. 화살표 그리기 arrows(x0, y0, x1, y1, code=int, length=num, angle=num)- x0, y0, x1, y1 는 시작점과 끝점을 의미- code 1 : 화살표가 그려지는 지점이 시작점 2 : 끝점에 그려짐 3 : 선의 양쪽에 화살표 그려짐- length – 화살표의 길이 (단위는 인치)- angle - 화살표의 각도 > plot.new()> plot.window(xlim = c(0, 5), ylim = c(0, 10))> axis(1)> axis(2)> arrows(1, 2, 4, 6, code=2, length=1, angle=45)> 2. 사각형 그리기 rect(x0, y0, x1, y1, col=str, border=str)- x0, y0, x1, y1 은 아..
Information Visualization (10) - R 그래픽 기초 (선 그리기 Adding Disconnected Lines Segments To A Plot)
2014. 10. 24.기본형태 segments(x0, y0, x1, y1) * x0, y0 - 시작점의 좌표 x1, y1 - 끝나는 점의 좌표* 라인모양, 색상, 폭 등 설정 가능 > plot.new()> plot.window(xlim = c(0, 10), ylim = c(0, 10))> axis(1)> axis(2)> segments(1,1,5,7)>
Information Visualization (9) - R 그래픽 기초 (선 그리기Drawing Straight Lines Across A Plot)
2014. 10. 24.기본형태 abline(a=intercept, b=slope) // a = y 절편, b= 기울기abline(h=numbers) // 수직선 긋기abline(v=numbers) // 수평선 긋기* 라인 형태, 색상, 폭 등의 인수는 기존 line() 함수와 마찬가지로 적용가능함 > plot.new()> plot.window(xlim = c(0, 10), ylim = c(0, 10))> axis(1)> axis(2)> abline(2,1)> abline(v=2)> abline(h=6)> box()>
Information Visualization (8) - R 그래픽 기초 (선 그리기Adding Connected Line Segments)
2014. 10. 24.기본형태 lines(x, y, lty=str, lwd=num, col=str) 1. lty=int or name선의 스타일 (기본값 "solid")"blank", "solid", "dashed", "dotted", "dotdash", "longdash", "twodash" 등이 있으며 아래 샘플 참조. > plot.new()> plot.window(xlim = c(0, 10), ylim = c(0, 10))> axis(1)> axis(2)> lines(c(0,10),c(1,1),lty="solid")> lines(c(0,10),c(2,2),lty="dashed")> lines(c(0,10),c(3,3),lty="dotted")> lines(c(0,10),c(4,4),lty="dotdash")> lines..