R- Как я могу решить потерю данных и ошибки с TermDocumentMatrix () и DocumentTermMatrix (), соответственно? - PullRequest
1 голос
/ 15 января 2020

У меня в твиттере данные 1000 образцов. И пытаясь сделать некоторый анализ tf и tf-idf на них, чтобы измерить важность каждого смайлика в твитах. Всего 437 уникальных смайликов и 810 твитов.

Моя текущая проблема заключается в том, что с TermDocumentMatrix не отображаются все термины. Принимая во внимание, что с DocumentTermMatrix есть ошибка, которую я не могу обойти. Вот рабочий фрагмент кода:

library(dplyr)
library(tidytext)
library(tm)
library(tidyr) 

#These are NOT from the my data, these are random fake bios I found online just to make this code snippet
tweets_data <- c("Sharp, adversarial⚔️~pro choice?~ban Pit Bulls☠️~BSL?️~aberant psychology?~common sense?~the Piper will lead us to reason?~sealskin woman?",
                 "Blocked by Owen, Adonis. Abbott & many #FBPE? Love seaside, historic houses & gardens, family & pets. RTs & likes/ Follows may=interest not agreement ??",
                 "???????? #healthy #vegetarian #beatchronicillness fix infrastructure",
                 "LIBERTY-IDENTITARIAN. My bio, photo at Site Info. And kindly add my site to your Daily Favorites bar. Thank you, Eric",
                 "??I #BackTheBlue for my son!?? Facts Over Feelings. Border Security saves lives! #ThankYouICE",
                 "???? I play Pedal Steel @CooderGraw & #CharlieShafter???? #GoStars #LiberalismIsAMentalDisorder",
                 "#Englishman  #Londoner  @Chelseafc  ?️‍♂️ ?? ? ???????????",
                 "F*** the Anti-White Agenda #Christian #Traditional #TradThot #TradGirl #European #MAGA #AltRight #Folk #Family #WhitePride",
                 "??❄️Do not dwell in the past, do not dream of the future, concentrate the mind on the present moment.??️❄️",
                 "Ordinary girl in a messed up World | Christian | Anti-War | Anti-Zionist | Pro-Life | Pro ?? | ??Hello intro on the Minds Link |")

emoticons_data <- c("?","?","?","?","?")

TagSet <- data.frame(emoticons_data)
colnames(TagSet) <- "emoticon"

TextSet <- data.frame(tweets_data)
colnames(TextSet) <- "tweet"

myCorpus <- tm::Corpus(tm::VectorSource(TextSet$tweet))

tdm <- tm::TermDocumentMatrix(myCorpus, control= list(stopwords=T))

tdm_onlytags <- tdm[rownames(tdm)%in%TagSet$emoticon, ]

tm::inspect(tdm_onlytags) #Only shows 1 terms, and not 5
#View(as.matrix(tdm_onlytags[1:tdm_onlytags$nrow, 1:tdm_onlytags$ncol])) #just to see in new window

enter image description here

Кроме того, если я пытаюсь выполнить команду tf-idf, я просто получаю сообщение об ошибке. Я огляделся, но не знаю, где исправить ошибку.

tdm <- tm::as.DocumentTermMatrix(myCorpus, control= list(weighting= weightTfIdf))
tdm #Original= Error in dim(data) <- dim : dims [product 810] do not match the length of object [3]

enter image description here

Если кто-нибудь может мне помочь, я был бы очень признателен. Я впервые использую пакет tm. Заранее спасибо, я могу дать больше информации, если вы хотите, чтобы я.

1 Ответ

3 голосов
/ 15 января 2020

Я немного изменил ваши исходные данные, так как ваши смайлики появляются в тексте только один раз, что превращает все значения в tfidf в 1 (см. Ниже, я просто случайно добавил несколько ?). Я использую quanteda вместо tm, так как он быстрее и имеет гораздо меньше проблем с кодировкой.

library(dplyr)
library(quanteda)

tweets_dfm <- dfm(TextSet$tweet)  # convert to document-feature matrix

tweets_dfm %>% 
  dfm_select(TagSet$emoticon) %>% # only leave emoticons in the dfm
  dfm_tfidf() %>%                 # weight with tfidf
  convert("data.frame")           # turn into data.frame to display more easily
#>    document <U+0001F914> <U+0001F4AA> <U+0001F603> <U+0001F953> <U+0001F37A>
#> 1     text1      1.39794            1            0            0            0
#> 2     text2      0.00000            0            1            0            0
#> 3     text3      0.00000            0            0            0            0
#> 4     text4      0.00000            0            0            0            0
#> 5     text5      0.00000            0            0            0            0
#> 6     text6      0.69897            0            0            0            0
#> 7     text7      0.00000            0            0            1            1
#> 8     text8      0.00000            0            0            0            0
#> 9     text9      0.00000            0            0            0            0
#> 10   text10      0.00000            0            0            0            0

Имена столбцов (т.е. emojis) отображаются правильно в моем средстве просмотра, и это должно можно экспортировать полученный data.frame.

data

TagSet <- data.frame(emoticon = c("?","?","?","?","?"),
                     stringsAsFactors = FALSE)

TextSet <- data.frame(tweet = c("?Sharp, adversarial⚔️~pro choice?~ban Pit Bulls☠️~BSL?️~aberant psychology?~common sense?~the Piper will lead us to reason?~sealskin woman?",
                                "Blocked by Owen, Adonis. Abbott & many #FBPE? Love seaside, historic houses & gardens, family & pets. RTs & likes/ Follows may=interest not agreement ??",
                                "???????? #healthy #vegetarian #beatchronicillness fix infrastructure",
                                "LIBERTY-IDENTITARIAN. My bio, photo at Site Info. And kindly add my site to your Daily Favorites bar. Thank you, Eric",
                                "??I #BackTheBlue for my son!?? Facts Over Feelings. Border Security saves lives! #ThankYouICE",
                                "????? I play Pedal Steel @CooderGraw & #CharlieShafter???? #GoStars #LiberalismIsAMentalDisorder",
                                "#Englishman  #Londoner  @Chelseafc  ?️‍♂️ ?? ? ???????????",
                                "F*** the Anti-White Agenda #Christian #Traditional #TradThot #TradGirl #European #MAGA #AltRight #Folk #Family #WhitePride",
                                "??❄️Do not dwell in the past, do not dream of the future, concentrate the mind on the present moment.??️❄️",
                                "Ordinary girl in a messed up World | Christian | Anti-War | Anti-Zionist | Pro-Life | Pro ?? | ??Hello intro on the Minds Link |"),
                      stringsAsFactors = FALSE)
...