[英]R: Top N elements of each group without duplicates
對於一個課堂項目,我有一組推文,分為3種類型的演講:仇恨,常規和令人反感。 我的目標是最終訓練分類器,以根據數據預測正確的推文類型。
我以整齊的格式(每行一個單詞)來整理數據,其中包含每個單詞的TF-IDF分數。 我用星號檢查了攻擊性語言:
> tfidf_words
# A tibble: 34,717 x 7
speech tweet_id word n tf idf tf_idf
<fct> <int> <chr> <int> <dbl> <dbl> <dbl>
1 hate 24282747 reason 1 0.25 5.69 1.42
2 hate 24282747 usd 1 0.25 8.73 2.18
3 hate 24282747 bunch 1 0.25 5.60 1.40
4 hate 24282747 ****** 1 0.25 5.21 1.30
5 hate 24284443 sand 1 0.5 4.76 2.38
6 hate 24284443 ****** 1 0.5 2.49 1.24
7 hate 24324552 madden 1 0.111 8.73 0.970
8 hate 24324552 call 1 0.111 4.11 0.456
9 hate 24324552 ****** 1 0.111 2.05 0.228
10 hate 24324552 set 1 0.111 5.90 0.655
# ... with 34,707 more rows
為了限制我的訓練特征空間的大小,我想根據它們的TF-IDF分數獲得每種語音類型的前“ n”個唯一詞。
我的vocabulary
是為我的特征空間選擇的所有唯一單詞的向量,定義為vocabulary <- unique(feature_space$word)
在我的程序中,我使用SENTIMENT_SIZE
定義我的模型中每種語音類型需要多少個單詞。
我已經嘗試過這兩個:
feature_space <- tfidf_words %>%
arrange(desc(tf_idf)) %>%
group_by(speech) %>%
slice(1:SENTIMENT_SIZE) %>%
ungroup() %>%
arrange(tweet_id)
和這個:
feature_space <- tfidf_words %>%
group_by(speech) %>%
top_n(n = SENTIMENT_SIZE, wt = tf_idf) %>%
ungroup()
這些都是“分類”工作,但是它們都不以我希望的方式處理重復項。 例如,如果我將SENTIMENT_SIZE
設置為100,則希望從所選的每種語音類型中看到100個唯一的單詞,總共300個單詞。
相反,方法1的結果如下:
> length(vocabulary)
[1] 248
方法2的結果
> length(vocabulary)
[1] 293
我怎樣才能:
在這里,我假設您正在尋找每組speech
的唯一word
tfidf_words %>% arrange(desc(tf_idf)) %>%
group_by(speech) %>% distinct(word, .keep_all = TRUE)
感謝@A。 蘇里曼,我想我現在有一些可行的方法。
feature_space <- tfidf_words %>%
arrange(desc(tf_idf)) %>%
distinct(word, .keep_all = TRUE) %>% #remove all duplicate words
group_by(speech) %>%
slice(1:SENTIMENT_SIZE) %>% #grab first n of each speech category
ungroup()
這應該總是能在我的詞匯表中產生預期的單詞數,因為它可以搶先消除平局的機會。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.