-
Notifications
You must be signed in to change notification settings - Fork 0
/
.Rhistory
512 lines (512 loc) · 19.9 KB
/
.Rhistory
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
# help(package = "quanteda")
# Tokenize
tokens <- tokens(raw, what = "word",
remove_numbers = TRUE, remove_punct = TRUE,
remove_symbols = TRUE, remove_hyphens = TRUE)
# for bigrams.
# test.tokens <- tokens_ngrams(test.tokens, n = 1:2)
# minimize capital letters
tokens <- tokens_tolower(tokens)
# stopwords
stop<-stopwords()
new_stopwords<-append(stop,c("fig.","eq.","abstracttext"))
tokens <- tokens_select(tokens, new_stopwords, selection = "remove")
# stem
# tokens <- tokens_wordstem(tokens, language = "english")
# print(tokens)
# Create our first bag-of-words model.
tokens.dfm <- dfm(tokens, tolower = FALSE)
# Transform to a matrix and inspect.
tokens.matrix <- as.matrix(tokens.dfm)
View(tokens.matrix[1:NbrDoc, 1:100])
dim(tokens.matrix)
# Tokenfrequence
# In corpus
freq <- sort(colSums(tokens.matrix), decreasing=TRUE)
wf <- data.frame(word=names(freq), freq=freq)
# In specific document
Doc<-5
freqInDoc <- sort(tokens.matrix[Doc,], decreasing=TRUE)
wfindoc <- data.frame(word=names(freqInDoc), freq=freqInDoc)
# plot word frequence
pl <- ggplot(subset(wf, freq > 1) ,aes(word, freq))
# pl <- ggplot(subset(wfindoc, freq > 1) ,aes(word, freq))
pl <- pl + geom_bar(stat="identity", fill="darkred", colour="white")
pl + theme(axis.text.x=element_text(angle=90, hjust=1)) + ggtitle("Uni-Gram Frequency")
# Word Cloud
library(wordcloud)
set.seed(100)
wordcloud(names(freq), freq, min.freq=2, colors=brewer.pal(6, "Dark2"))
# Our function for calculating relative term frequency (TF)
term.frequency <- function(row) {
row / sum(row)
}
# Our function for calculating inverse document frequency (IDF)
inverse.doc.freq <- function(col) {
corpus.size <- length(col)
doc.count <- length(which(col > 0))
log10(corpus.size / doc.count)
}
# Our function for calculating TF-IDF.
tf.idf <- function(x, idf) {
x * idf
}
# First step, normalize all documents via TF.
tokens.df <- apply(tokens.matrix, 1, term.frequency)
dim(tokens.df)
View(tokens.df[1:100, 1:NbrDoc])
# Second step, calculate the IDF vector that we will use - both
tokens.idf <- apply(tokens.matrix, 2, inverse.doc.freq)
str(tokens.idf)
# Lastly, calculate TF-IDF for our training corpus.
tokens.tfidf <- apply(tokens.df, 2, tf.idf, idf = tokens.idf)
dim(tokens.tfidf)
View(tokens.tfidf[1:25, 1:NbrDoc])
# Transpose the matrix
tokens.tfidf <- t(tokens.tfidf)
dim(tokens.tfidf)
View(tokens.tfidf[1:NbrDoc, 1:25])
#
# # Check for incopmlete cases.
# incomplete.cases <- which(!complete.cases(tokens.tfidf))
# raw[incomplete.cases]
#
# # Fix incomplete cases
# tokens.tfidf[incomplete.cases,] <- rep(0.0, ncol(tokens.tfidf))
# dim(tokens.tfidf)
# sum(which(!complete.cases(tokens.tfidf)))
# Make a clean data frame.
tokens.tfidf.df <- data.frame(tokens.tfidf)
names(tokens.tfidf.df) <- make.names(names(tokens.tfidf.df))
library(irlba)
# Perform SVD. Specifically, reduce dimensionality down to 300 columns
# for our latent semantic analysis (LSA).
irlba <- irlba(t(tokens.tfidf), nv = 4, maxit = 60)
# Take a look at the new feature data up close.
View(irlba$v)
# Make 3D plot
#-------------
#atribution de nom de lignes
rownames(irlba$v)<-row.names(tokens.tfidf)
eig1<-irlba$v[,1]
eig2<-irlba$v[,2]
eig3<-irlba$v[,3]
# 2D Plot:
#---------
plot(eig1,eig2,col="blue")
text(eig1,eig2,row.names(irlba$v), cex=0.6, pos=4, col="red")
# 3D Plot:
#---------
# install.packages("scatterplot3d") # Install
library("scatterplot3d")
s3d<-scatterplot3d(eig1,eig2,eig3, pch = 16, color="steelblue")
text(s3d$xyz.convert(eig1,eig2,eig3), labels = rownames(irlba$v),
cex= 0.7, col = "red")
library(plotly)
plot_ly(mtcars, x = ~eig1, y = ~eig2, z = ~eig3, colors = c('#BF382A'),size = 0.5)
if (!require("easyPubMed")) install.packages("easyPubMed")
library(XML)
library(easyPubMed)
library(ggplot2)
############### PART 1: extraction des textes
##### Option 1: 698 documents via une requete
Querry_String <- "mouse"
Ids <- get_pubmed_ids(Querry_String)
# get_pubmed_ids() decompose les characteristiques de Querry_String en nombre de char et mot clef (ex: AND) et compose une querry comprehensible pour fetch_pubmed_data().
papers <- fetch_pubmed_data(Ids)
# papers est une structure type html qui contien tt les info pour tt les documents (ici +-700 doc) qui ont etes recueillis par fetch_pubmed_data()
print(papers)
##### Option 2: 52349 documents via importation du fichier xml.
# papers <- xmlParse(file = "/home/francois/Desktop/pubmed18n0924.xml")
# papers est une structure type html qui contien tt les info pour tt les documents (ici +-52300 doc) qui ont etes recueillis par fetch_pubmed_data()
# print(papers)
#------------------------------------------------ A FAIRE
# A partir de papers, on va chercher l'Abstract.
# /!\ Probleme: les abstracts sont composes de plusieurs parties:
# <AbstractText Label=\"BACKGROUND AND OBJECTIVE\" NlmCategory=\"OBJECTIVE\">
# <AbstractText Label=\"MATERIALS AND METHODS\" NlmCategory=\"METHODS\">
# <AbstractText Label=\"RESULTS\" NlmCategory=\"RESULTS\">
# <AbstractText Label=\"CONCLUSION\" NlmCategory=\"CONCLUSIONS\">
# le code suivant ne fait pas une bonne partition du coup.
#---------------------------------------------------------
Abstract <- unlist(xpathApply(papers, "//AbstractText", saveXML))
head(Abstract)
# position des "<AbstractText>"
Abstract_pos <- regexpr('<AbstractText>.*<\\/AbstractText>', Abstract)
# on enleve le <AbstractText> au debut de l' Abstract.
Abstract <- substr(Abstract, Abstract_pos + 14, Abstract_pos + attributes(Abstract_pos)$match.length - 16)
head(Abstract)
if (!require("easyPubMed")) install.packages("easyPubMed")
library(XML)
library(easyPubMed)
library(ggplot2)
############### PART 1: extraction des textes
##### Option 1: 698 documents via une requete
Querry_String <- "mouse"
Ids <- get_pubmed_ids(Querry_String)
# get_pubmed_ids() decompose les characteristiques de Querry_String en nombre de char et mot clef (ex: AND) et compose une querry comprehensible pour fetch_pubmed_data().
papers <- fetch_pubmed_data(Ids)
# papers est une structure type html qui contien tt les info pour tt les documents (ici +-700 doc) qui ont etes recueillis par fetch_pubmed_data()
print(papers)
##### Option 2: 52349 documents via importation du fichier xml.
# papers <- xmlParse(file = "/home/francois/Desktop/pubmed18n0924.xml")
# papers est une structure type html qui contien tt les info pour tt les documents (ici +-52300 doc) qui ont etes recueillis par fetch_pubmed_data()
# print(papers)
#------------------------------------------------ A FAIRE
# A partir de papers, on va chercher l'Abstract.
# /!\ Probleme: les abstracts sont composes de plusieurs parties:
# <AbstractText Label=\"BACKGROUND AND OBJECTIVE\" NlmCategory=\"OBJECTIVE\">
# <AbstractText Label=\"MATERIALS AND METHODS\" NlmCategory=\"METHODS\">
# <AbstractText Label=\"RESULTS\" NlmCategory=\"RESULTS\">
# <AbstractText Label=\"CONCLUSION\" NlmCategory=\"CONCLUSIONS\">
# le code suivant ne fait pas une bonne partition du coup.
#---------------------------------------------------------
Abstract <- unlist(xpathApply(papers, "//AbstractText", saveXML))
head(Abstract)
head(Abstract)
# position des "<AbstractText>"
Abstract_pos <- regexpr('<AbstractText>.*<\\/AbstractText>', Abstract)
# on enleve le <AbstractText> au debut de l' Abstract.
Abstract <- substr(Abstract, Abstract_pos + 14, Abstract_pos + attributes(Abstract_pos)$match.length - 16)
head(Abstract)
if (!require("easyPubMed")) install.packages("easyPubMed")
library(XML)
library(easyPubMed)
library(ggplot2)
############### PART 1: extraction des textes
##### Option 1: 698 documents via une requete
Querry_String <- "mouse"
Ids <- get_pubmed_ids(Querry_String)
# get_pubmed_ids() decompose les characteristiques de Querry_String en nombre de char et mot clef (ex: AND) et compose une querry comprehensible pour fetch_pubmed_data().
papers <- fetch_pubmed_data(Ids)
# papers est une structure type html qui contien tt les info pour tt les documents (ici +-700 doc) qui ont etes recueillis par fetch_pubmed_data()
print(papers)
##### Option 2: 52349 documents via importation du fichier xml.
# papers <- xmlParse(file = "/home/francois/Desktop/pubmed18n0924.xml")
# papers est une structure type html qui contien tt les info pour tt les documents (ici +-52300 doc) qui ont etes recueillis par fetch_pubmed_data()
# print(papers)
#------------------------------------------------ A FAIRE
# A partir de papers, on va chercher l'Abstract.
# /!\ Probleme: les abstracts sont composes de plusieurs parties:
# <AbstractText Label=\"BACKGROUND AND OBJECTIVE\" NlmCategory=\"OBJECTIVE\">
# <AbstractText Label=\"MATERIALS AND METHODS\" NlmCategory=\"METHODS\">
# <AbstractText Label=\"RESULTS\" NlmCategory=\"RESULTS\">
# <AbstractText Label=\"CONCLUSION\" NlmCategory=\"CONCLUSIONS\">
# le code suivant ne fait pas une bonne partition du coup.
#---------------------------------------------------------
Abstract <- unlist(xpathApply(papers, "//AbstractText", saveXML))
head(Abstract)
# position des "<AbstractText>"
Abstract_pos <- regexpr('<AbstractText>.*<\\/AbstractText>', Abstract)
# on enleve le <AbstractText> au debut de l' Abstract.
Abstract <- substr(Abstract, Abstract_pos + 14, Abstract_pos + attributes(Abstract_pos)$match.length - 16)
head(Abstract)
############### PART 2: text mining
# Approche Bag of words:
NbrDoc<-10
raw <- Abstract[1:NbrDoc]
print(raw)
library(quanteda)
# help(package = "quanteda")
# Tokenize
tokens <- tokens(raw, what = "word",
remove_numbers = TRUE, remove_punct = TRUE,
remove_symbols = TRUE, remove_hyphens = TRUE)
# for bigrams.
# test.tokens <- tokens_ngrams(test.tokens, n = 1:2)
# minimize capital letters
tokens <- tokens_tolower(tokens)
# stopwords
stop<-stopwords()
new_stopwords<-append(stop,c("fig.","eq.","abstracttext"))
tokens <- tokens_select(tokens, new_stopwords, selection = "remove")
# stem
# tokens <- tokens_wordstem(tokens, language = "english")
# print(tokens)
# Create our first bag-of-words model.
tokens.dfm <- dfm(tokens, tolower = FALSE)
# Transform to a matrix and inspect.
tokens.matrix <- as.matrix(tokens.dfm)
View(tokens.matrix[1:NbrDoc, 1:100])
dim(tokens.matrix)
# Tokenfrequence
# In corpus
freq <- sort(colSums(tokens.matrix), decreasing=TRUE)
wf <- data.frame(word=names(freq), freq=freq)
# In specific document
Doc<-5
freqInDoc <- sort(tokens.matrix[Doc,], decreasing=TRUE)
wfindoc <- data.frame(word=names(freqInDoc), freq=freqInDoc)
# plot word frequence
pl <- ggplot(subset(wf, freq > 1) ,aes(word, freq))
# pl <- ggplot(subset(wfindoc, freq > 1) ,aes(word, freq))
pl <- pl + geom_bar(stat="identity", fill="darkred", colour="white")
pl + theme(axis.text.x=element_text(angle=90, hjust=1)) + ggtitle("Uni-Gram Frequency")
# Word Cloud
library(wordcloud)
set.seed(100)
wordcloud(names(freq), freq, min.freq=2, colors=brewer.pal(6, "Dark2"))
# Our function for calculating relative term frequency (TF)
term.frequency <- function(row) {
row / sum(row)
}
# Our function for calculating inverse document frequency (IDF)
inverse.doc.freq <- function(col) {
corpus.size <- length(col)
doc.count <- length(which(col > 0))
log10(corpus.size / doc.count)
}
# Our function for calculating TF-IDF.
tf.idf <- function(x, idf) {
x * idf
}
# First step, normalize all documents via TF.
tokens.df <- apply(tokens.matrix, 1, term.frequency)
dim(tokens.df)
View(tokens.df[1:100, 1:NbrDoc])
# Second step, calculate the IDF vector that we will use - both
tokens.idf <- apply(tokens.matrix, 2, inverse.doc.freq)
str(tokens.idf)
# Lastly, calculate TF-IDF for our training corpus.
tokens.tfidf <- apply(tokens.df, 2, tf.idf, idf = tokens.idf)
dim(tokens.tfidf)
View(tokens.tfidf[1:25, 1:NbrDoc])
# Transpose the matrix
tokens.tfidf <- t(tokens.tfidf)
dim(tokens.tfidf)
View(tokens.tfidf[1:NbrDoc, 1:25])
#
# # Check for incopmlete cases.
# incomplete.cases <- which(!complete.cases(tokens.tfidf))
# raw[incomplete.cases]
#
# # Fix incomplete cases
# tokens.tfidf[incomplete.cases,] <- rep(0.0, ncol(tokens.tfidf))
# dim(tokens.tfidf)
# sum(which(!complete.cases(tokens.tfidf)))
# Make a clean data frame.
tokens.tfidf.df <- data.frame(tokens.tfidf)
names(tokens.tfidf.df) <- make.names(names(tokens.tfidf.df))
library(irlba)
# Perform SVD. Specifically, reduce dimensionality down to 300 columns
# for our latent semantic analysis (LSA).
irlba <- irlba(t(tokens.tfidf), nv = 4, maxit = 60)
# Take a look at the new feature data up close.
View(irlba$v)
# Make 3D plot
#-------------
#atribution de nom de lignes
rownames(irlba$v)<-row.names(tokens.tfidf)
eig1<-irlba$v[,1]
eig2<-irlba$v[,2]
eig3<-irlba$v[,3]
# 2D Plot:
#---------
plot(eig1,eig2,col="blue")
text(eig1,eig2,row.names(irlba$v), cex=0.6, pos=4, col="red")
# 3D Plot:
#---------
# install.packages("scatterplot3d") # Install
# library("scatterplot3d")
#
# s3d<-scatterplot3d(eig1,eig2,eig3, pch = 16, color="steelblue")
# text(s3d$xyz.convert(eig1,eig2,eig3), labels = rownames(irlba$v),
# cex= 0.7, col = "red")
library(plotly)
plot_ly(mtcars, x = ~eig1, y = ~eig2, z = ~eig3, colors = c('#BF382A'),size = 0.5)
scatter3d(mtcars, x = ~eig1, y = ~eig2, z = ~eig3, colors = c('#BF382A'),size = 0.5)
plot_ly(mtcars, x = ~eig1, y = ~eig2, z = ~eig3, colors = c('#BF382A'),size = 0.5)
install.packages(c("rgl", "car"))
library("car")
library("car")
scatter3d(x = eig1, y = eig2, z = eig3)
library("rgl")
scatter3d(x = eig1, y = eig2, z = eig3)
install.packages("rgl")
library("rgl")
scatter3d(x = eig1, y = eig2, z = eig3)
library("rgl")
install.packages("rgl")
library("rgl")
scatter3d(x = eig1, y = eig2, z = eig3)
install.packages("rgl")
library("rgl")
# 2D Plot:
#---------
plot(eig1,eig2,col="blue")
res<-kmeans(irlba$v,centers=2)
res
plot(res$centers,col =1:5,pch=8)
plot(res$centers,col =1:4,pch=8)
plot(res$centers,col =1:3,pch=8)
res<-kmeans(irlba$v,centers=2)
points(irlba&v, col=res$cluster,pch=res$cluster)
plot(irlba&v, col=res$cluster,pch=res$cluster)
irlba
res<-kmeans(irlba$v,centers=2)
plot(irlba$v, col=res$cluster,pch=res$cluster)
points(res$centers,col =1:5,pch=8)
res<-kmeans(irlba$v,centers=2)
plot(irlba$v, col=res$cluster,pch=res$cluster)
points(res$centers,col =1:5,pch=8)
plot(irlba$v, col=res$cluster,pch=res$cluster)
plot(irlba$v, col=res$cluster,pch=res$cluster)
res<-kmeans(irlba$v,centers=2)
plot(irlba$v, col=res$cluster,pch=res$cluster)
points(res$centers,col =1:5,pch=8)
plot(irlba$v, col=res$cluster,pch=res$cluster)
points(res$centers,col =1:5,pch=8)
res<-kmeans(irlba$v,centers=2)
plot(irlba$v, col=res$cluster,pch=res$cluster)
res<-kmeans(irlba$v,centers=2)
plot(irlba$v, col=res$cluster,pch=res$cluster)
points(res$centers,col =1:5,pch=8)
res<-kmeans(irlba$v,centers=3)
plot(irlba$v, col=res$cluster,pch=res$cluster)
irlba
# Perform SVD. Specifically, reduce dimensionality down to 300 columns
# for our latent semantic analysis (LSA).
irlba <- irlba(t(tokens.tfidf), nv = 4, maxit = 60)
# Perform SVD. Specifically, reduce dimensionality down to 300 columns
# for our latent semantic analysis (LSA).
irlba <- irlba(t(tokens.tfidf), nv = 3, maxit = 60)
if (!require("easyPubMed")) install.packages("easyPubMed")
library(XML)
library(easyPubMed)
library(ggplot2)
############### PART 1: extraction des textes
##### Option 1: 698 documents via une requete
Querry_String <- "mouse"
Ids <- get_pubmed_ids(Querry_String)
# get_pubmed_ids() decompose les characteristiques de Querry_String en nombre de char et mot clef (ex: AND) et compose une querry comprehensible pour fetch_pubmed_data().
papers <- fetch_pubmed_data(Ids)
# papers est une structure type html qui contien tt les info pour tt les documents (ici +-700 doc) qui ont etes recueillis par fetch_pubmed_data()
print(papers)
##### Option 2: 52349 documents via importation du fichier xml.
papers <- xmlParse(file = "/home/francois/Desktop/pubmed18n0924.xml")
# papers est une structure type html qui contien tt les info pour tt les documents (ici +-52300 doc) qui ont etes recueillis par fetch_pubmed_data()
print(papers)
# A partir de papers, on va chercher l'Abstract.
# /!\ Probleme: les abstracts sont composes de plusieurs parties:
# <AbstractText Label=\"BACKGROUND AND OBJECTIVE\" NlmCategory=\"OBJECTIVE\">
# <AbstractText Label=\"MATERIALS AND METHODS\" NlmCategory=\"METHODS\">
# <AbstractText Label=\"RESULTS\" NlmCategory=\"RESULTS\">
# <AbstractText Label=\"CONCLUSION\" NlmCategory=\"CONCLUSIONS\">
# le code suivant ne fait pas une bonne partition du coup.
Abstract <- unlist(xpathApply(papers, "//AbstractText", saveXML))
head(Abstract)
# position des "<AbstractText>"
Abstract_pos <- regexpr('<AbstractText>.*<\\/AbstractText>', Abstract)
# on enleve le <AbstractText> au debut de l' Abstract.
Abstract <- substr(Abstract, Abstract_pos + 14, Abstract_pos + attributes(Abstract_pos)$match.length - 16)
head(Abstract)
############### PART 2: text mining
# Approche Bag of words:
NbrDoc<-10
raw <- Abstract[1:NbrDoc]
print(raw)
library(quanteda)
# help(package = "quanteda")
# Tokenize
tokens <- tokens(raw, what = "word",
remove_numbers = TRUE, remove_punct = TRUE,
remove_symbols = TRUE, remove_hyphens = TRUE)
# for bigrams.
# test.tokens <- tokens_ngrams(test.tokens, n = 1:2)
# minimize capital letters
tokens <- tokens_tolower(tokens)
# stopwords
stop<-stopwords()
new_stopwords<-append(stop,c("fig.","eq.","abstracttext"))
tokens <- tokens_select(tokens, new_stopwords, selection = "remove")
# stem
# tokens <- tokens_wordstem(tokens, language = "english")
# print(tokens)
# Create our first bag-of-words model.
tokens.dfm <- dfm(tokens, tolower = FALSE)
# Transform to a matrix and inspect.
tokens.matrix <- as.matrix(tokens.dfm)
View(tokens.matrix[1:NbrDoc, 1:100])
dim(tokens.matrix)
# Tokenfrequence
# In corpus
freq <- sort(colSums(tokens.matrix), decreasing=TRUE)
wf <- data.frame(word=names(freq), freq=freq)
# In specific document
Doc<-5
freqInDoc <- sort(tokens.matrix[Doc,], decreasing=TRUE)
wfindoc <- data.frame(word=names(freqInDoc), freq=freqInDoc)
# plot word frequence
pl <- ggplot(subset(wf, freq > 1) ,aes(word, freq))
# pl <- ggplot(subset(wfindoc, freq > 1) ,aes(word, freq))
pl <- pl + geom_bar(stat="identity", fill="darkred", colour="white")
pl + theme(axis.text.x=element_text(angle=90, hjust=1)) + ggtitle("Uni-Gram Frequency")
# Word Cloud
library(wordcloud)
set.seed(100)
wordcloud(names(freq), freq, min.freq=2, colors=brewer.pal(6, "Dark2"))
# Our function for calculating relative term frequency (TF)
term.frequency <- function(row) {
row / sum(row)
}
# Our function for calculating inverse document frequency (IDF)
inverse.doc.freq <- function(col) {
corpus.size <- length(col)
doc.count <- length(which(col > 0))
log10(corpus.size / doc.count)
}
# Our function for calculating TF-IDF.
tf.idf <- function(x, idf) {
x * idf
}
# First step, normalize all documents via TF.
tokens.df <- apply(tokens.matrix, 1, term.frequency)
dim(tokens.df)
View(tokens.df[1:100, 1:NbrDoc])
# Second step, calculate the IDF vector that we will use - both
tokens.idf <- apply(tokens.matrix, 2, inverse.doc.freq)
str(tokens.idf)
# Lastly, calculate TF-IDF for our training corpus.
tokens.tfidf <- apply(tokens.df, 2, tf.idf, idf = tokens.idf)
dim(tokens.tfidf)
View(tokens.tfidf[1:25, 1:NbrDoc])
# Transpose the matrix
tokens.tfidf <- t(tokens.tfidf)
dim(tokens.tfidf)
View(tokens.tfidf[1:NbrDoc, 1:25])
#
# # Check for incopmlete cases.
# incomplete.cases <- which(!complete.cases(tokens.tfidf))
# raw[incomplete.cases]
#
# # Fix incomplete cases
# tokens.tfidf[incomplete.cases,] <- rep(0.0, ncol(tokens.tfidf))
# dim(tokens.tfidf)
# sum(which(!complete.cases(tokens.tfidf)))
# Make a clean data frame.
tokens.tfidf.df <- data.frame(tokens.tfidf)
names(tokens.tfidf.df) <- make.names(names(tokens.tfidf.df))
library(irlba)
# Perform SVD. Specifically, reduce dimensionality down to 300 columns
# for our latent semantic analysis (LSA).
irlba <- irlba(t(tokens.tfidf), nv = 4, maxit = 60)
# Take a look at the new feature data up close.
View(irlba$v)
# Make 3D plot
#-------------
#atribution de nom de lignes
rownames(irlba$v)<-row.names(tokens.tfidf)
eig1<-irlba$v[,1]
eig2<-irlba$v[,2]
eig3<-irlba$v[,3]
# 2D Plot:
#---------
plot(eig1,eig2,col="blue")
text(eig1,eig2,row.names(irlba$v), cex=0.6, pos=4, col="red")
# 3D Plot:
#---------
# install.packages("scatterplot3d") # Install
library("scatterplot3d")
s3d<-scatterplot3d(eig1,eig2,eig3, pch = 16, color="steelblue")
text(s3d$xyz.convert(eig1,eig2,eig3), labels = rownames(irlba$v),
cex= 0.7, col = "red")