twitter_training.csv 和 twitter_validation.csv
收藏情感分析与实体相关性
概述
本项目旨在分析和可视化社交媒体数据中的情感模式,以了解公众对特定话题或品牌的意见和态度。分析内容包括:
- 情感分布分析
- 情感随时间趋势
- 标签情感分布
- 实体与情感的相关性分析
数据集
项目使用两个数据集:
twitter_training.csvtwitter_validation.csv
两个数据集均包含以下列:
Tweet ID:推文的标识符。Entity:推文涉及的特定话题或品牌。Sentiment:情感标签(例如,正面、负面、中性、无关)。Tweet content:推文的文本内容。
文件
DS_04.ipynb:包含情感分析和可视化代码的Jupyter笔记本。twitter_training.csv:用于情感分析的训练数据集。twitter_validation.csv:用于情感分析的验证数据集。
安装
运行代码需要安装以下Python库:
- pandas
- numpy
- matplotlib
- seaborn
可以使用pip安装所需库: bash pip install pandas numpy matplotlib seaborn
使用
- 加载数据: 将提供的数据集加载到pandas DataFrame中。 python import pandas as pd
training_data = pd.read_csv(twitter_training.csv) validation_data = pd.read_csv(twitter_validation.csv)
- 情感分布分析: 使用条形图可视化不同实体的情感分布。 python import matplotlib.pyplot as plt import seaborn as sns
绘制情感分布图
plt.figure(figsize=(12, 6)) sns.countplot(data=training_data, x=Entity, hue=Sentiment, palette=viridis) plt.title(不同实体的情感分布) plt.xticks(rotation=90) plt.show()
- 情感随时间趋势: 分析情感随时间的变化趋势(需要时间戳数据,此处使用模拟数据演示)。 python import numpy as np
生成模拟时间戳数据
np.random.seed(0) training_data[timestamp] = pd.date_range(start=2021-01-01, periods=len(training_data), freq=H)
按日期和情感分组计数
sentiment_trends = training_data.groupby([training_data[timestamp].dt.date, Sentiment]).size().unstack().fillna(0)
绘制情感随时间趋势图
plt.figure(figsize=(12, 6)) sentiment_trends.plot(kind=line, marker=o) plt.title(情感随时间趋势) plt.xlabel(日期) plt.ylabel(推文数量) plt.legend(title=情感) plt.xticks(rotation=45) plt.show()
- 标签情感分布: 提取标签并可视化其情感分布。 python import re
从推文内容中提取标签的函数
def extract_hashtags(text): if isinstance(text, str): hashtags = re.findall(r#w+, text) return [hashtag.lower() for hashtag in hashtags] return []
应用函数提取标签
training_data[hashtags] = training_data[Tweet content].apply(extract_hashtags)
展平标签和情感列表
hashtag_sentiment_list = [(hashtag, sentiment) for hashtags, sentiment in zip(training_data[hashtags], training_data[Sentiment]) for hashtag in hashtags]
从列表创建DataFrame
hashtag_sentiment_df = pd.DataFrame(hashtag_sentiment_list, columns=[Hashtag, Sentiment])
按标签和情感分组计数
hashtag_sentiment_counts = hashtag_sentiment_df.groupby([Hashtag, Sentiment]).size().unstack(fill_value=0)
获取总数量前20的标签
top_hashtags = hashtag_sentiment_counts.sum(axis=1).sort_values(ascending=False).head(20).index top_hashtag_sentiment_counts = hashtag_sentiment_counts.loc[top_hashtags]
绘制前20标签的情感分布图
plt.figure(figsize=(14, 8)) top_hashtag_sentiment_counts.plot(kind=bar, stacked=True, colormap=viridis) plt.title(前20标签的情感分布) plt.xlabel(标签) plt.ylabel(推文数量) plt.xticks(rotation=45) plt.legend(title=情感) plt.show()
- 相关性分析: 检查不同实体与情感之间的关系。 python
创建实体列表
entities = training_data[Entity].unique()
创建实体的二进制矩阵
entity_matrix = pd.DataFrame(0, index=training_data.index, columns=entities)
标记每个推文中实体的存在
for entity in entities: entity_matrix[entity] = training_data[Entity] == entity
将情感标签映射为数值
sentiment_score_mapping = { Positive: 1, Negative: -1, Neutral: 0, Irrelevant: 0 } training_data[sentiment_score] = training_data[Sentiment].map(sentiment_score_mapping)
计算实体存在与情感分数之间的相关性
correlation_matrix = entity_matrix.corrwith(training_data[sentiment_score])
将相关性矩阵转换为DataFrame以便阅读
correlation_df = correlation_matrix.reset_index() correlation_df.columns = [Entity, Correlation]
绘制相关性热图
plt.figure(figsize=(16, 8)) sns.heatmap(correlation_df.set_index(Entity).T, annot=True, cmap=coolwarm, center=0, fmt=".2f", annot_kws={"size": 12}, cbar_kws={label: Correlation}, linewidths=0.5, linecolor=lightgrey) plt.title(实体与情感分数的相关性, fontsize=18) plt.xticks(rotation=45, ha=right, fontsize=14) plt.yticks(fontsize=14) plt.show()




