Twitter 情感分析

用 R 分析社交媒体数据

Vivek Vijayaraghavan

Data Science Coach

课程概览

  • 什么是情感分析?
  • 对推文进行情感分析
  • 解读以理解人们的情绪与观点
用 R 分析社交媒体数据

情感分析

  • 获取对产品或品牌的感知信息
  • 提取并量化正面、负面和中性观点
  • 从文本中识别信任、喜悦、愤怒等情绪

情感分析中的情绪

用 R 分析社交媒体数据

情感分析的重要性

  • 客户感知会影响购买决策
  • 有助于把握客户情绪脉搏
  • 主动倾听并直接与客户互动
用 R 分析社交媒体数据

情感分析的工作原理

  • 预定义情感词典用于计算得分
  • 基于词义或意图进行训练与评分
  • 每个词按其与正/负面词的接近度打分
  • 同样适用于表达特定情绪的词
用 R 分析社交媒体数据

情感分析步骤

情感分析的第 1 步

用 R 分析社交媒体数据

情感分析步骤

情感分析的第 2 步

用 R 分析社交媒体数据

情感分析步骤

情感分析的第 3 步

用 R 分析社交媒体数据

情感分析步骤

情感分析的第 4 步

用 R 分析社交媒体数据

提取用于情感分析的推文

# Extract tweets on galaxy fold
twts_galxy  <-  search_tweets("galaxy fold", n = 5000, 
                                lang = "en", include_rts = FALSE)
用 R 分析社交媒体数据

执行情感分析

# Perform sentiment analysis for tweets on galaxy fold
library(syuzhet)
sa.value <- get_nrc_sentiment(twts_galxy$text)
用 R 分析社交媒体数据

查看情感得分

# View the sentiment scores
sa.value[1:5,1:7]
anger    anticipation    disgust    fear    joy    sadness    surprise
<dbl>       <dbl>         <dbl>     <dbl>  <dbl>    <dbl>       <dbl> 
0             0             0         0      0        0           0
1             0             0         0      0        0           0
1             1             0         2      1        1           1
0             0             0         1      0        0           0
0             0             0         0      0        0           0
用 R 分析社交媒体数据

情感得分总计

# Calculate sum of sentiment scores
score <- colSums(sa.value[,])
用 R 分析社交媒体数据

情感得分数据框

# Convert to data frame
score_df <- data.frame(score)
# View the data frame
score_df
               score
               <dbl>
anger           211            
anticipation    825            
disgust         214            
fear            253            
joy             412            
sadness         197            
surprise        315            
trust           641            
negative        487            
positive       1351
用 R 分析社交媒体数据

情感得分数据框

# Convert row names into 'sentiment' column
# Combine with sentiment scores
sa.score <- cbind(sentiment = row.names(score_df), 
                  score_df, row.names=NULL)
用 R 分析社交媒体数据

情感得分数据框

# View data frame with sentiment scores
print(sa.score)
sentiment      score
<fct>         <dbl>
anger           211            
anticipation    825            
disgust         214            
fear            253            
joy             412            
sadness         197            
surprise        315            
trust           641            
negative        487            
positive        1351    
用 R 分析社交媒体数据

绘制与可视化情感

  • 使用 ggplot() 绘制并可视化情感
# Plot the sentiment scores
ggplot(data = sa.score2, aes(x = sentiment, y = score, 
       fill = sentiment)) +
       geom_bar(stat = "identity") +
       theme(axis.text.x = element_text(angle = 45, hjust = 1))
用 R 分析社交媒体数据

可视化情感

可视化情感

用 R 分析社交媒体数据

开始练习!

用 R 分析社交媒体数据

Preparing Video For Download...