1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RでTweetをクラスタリング(DBSCAN)

Last updated at Posted at 2018-05-26

RでTweetをリプライの内容によってクラスタリング(DBSCAN)する。
特徴量は形容詞のTF-IDFを利用。

必要なライブラリをインポート

#DBSCAN
library("fpc")
#形態素解析
library(RMeCab)
#データベース
library(RSQLite)

データベース接続

dbd <- dbDriver("SQLite")
dbname <- "/path/to/database.db"
dbcon <- dbConnect(dbd, dbname)

データベースから特定のツイートに対するリプライが10以上のものを取ってくる

tweet_list <- dbGetQuery(dbcon, "select to_tweet_id 
  from reply_table group by to_tweet_id having count(to_tweet_id)>=10")
for(i in 1:length(tweet_list[[1]])){
 print(tweet_list[[1]][i])
 #tweet_idを指定してリプライを取得
 sql <- paste("select text from reply where to_tweet_id = ", tweet_list[[1]][i], sqp = "") 
 #リプライをベクトルとして格納
 vec <- dbGetQuery(dbcon, sql) 
 #ノイズを取り除く
 vec <- gsub("\\n","",vec) 
 vec <- gsub("\\\"","",vec)
 vec <- gsub("\\\\n","",vec)
 vec <- gsub(",","",vec)
 print(vec)
 #データをテキストファイルに出力して保存
 file <- paste("/path/to/a/folder/to/store/data", tweet_list[[1]][i], ".txt", sqp = "")
 write(vec, file)
}

TFIDFNORMで規格化しつつ文書行列を作成

doc_mat <- docMatrix("/path/to/a/folder/to/store/data", pos=c("形容詞"), weight="tf*idf*norm")

DF取り除いて積集合

df <- docMatrix("/path/to/a/folder/to/store/data", pos=c("形容詞"), weight="df")
df <- df[row.names(df) !="[[LESS-THAN-1]]",]
df <- df[row.names(df) !="[[TOTAL-TOKENS]]",]

#DFが3以上のものを取り出す
df_min3 <- df[rowSums(df) >= 3, ]
doc_t <- t(doc_mat)
doc_s <- subset(doc_t, 1==1, rownames(df_min3))

DBSCANを行う

dist_mat <- dist(doc_mat, method="euclidean", diag=FALSE, p=2)
db <- dbscan(dist_mat,eps = 1.8, MinPts=4)
db
db$cluster

グラフ結果出力

plotcluster(dist_mat, c)
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?