飞道的博客

使用文本数据预测一个人的性格

307人阅读  评论(0)

廖雪峰的“大数据分析全栈工程师”课程第11期开始招生

我们使用的用 迈尔斯布里格斯类型(MBTI人格)标注的数据集。

一共有4个维度,每个维度有两个类型,所以常人的性格从MBTI指标来看,一共有16种性格。

读取数据

mbti数据集中有两个字段

  • type: 性格类型

  • posts: 每个用户的最近的50条推文,推文与推文之间用 ||| 间隔开

先查看前5行数据


   
  1. import pandas as pd
  2. import warnings
  3. warnings.filterwarnings( 'ignore')
  4. df = pd.read_csv( 'data/mbti.csv')
  5. df.info()

   
  1. <class 'pandas.core.frame.DataFrame'>
  2. RangeIndex: 8675 entries, 0 to 8674
  3. Data columns (total 2 columns):
  4. type 8675 non-null object
  5. posts 8675 non-null object
  6. dtypes: object( 2)
  7. memory usage: 135.7+ KB

mbti数据集一共有8675条数据

数据探索

这里我计算出每个推文的长度(没啥大用,复习apply和seaborn可视化)


   
  1. df[ 'words_per_comment'] = df[ 'posts'].apply(lambda x: len(x.split()))/ 50
  2. df[ 'posts'] = df[ 'posts'].apply(lambda x:x.lower())
  3. df.head()

小提琴图show一下各个性格的wordspercomment信息


   
  1. import seaborn as sns
  2. import matplotlib.pyplot as plt
  3. #画布设置及尺寸
  4. sns.set(style= 'white', font_scale= 1.5)
  5. plt.figure(figsize=( 15, 10))
  6. #绘制小提琴图
  7. sns.violinplot(x= 'type',
  8. y= 'words_per_comment',
  9. data=df,
  10. color= 'lightgray')
  11. #绘制分类三点图,叠加到小提琴图图层上方
  12. sns.stripplot(x= 'type',
  13. y= 'words_per_comment',
  14. data=df,
  15. size= 2,
  16. jitter=True)
  17. #标题及y轴名
  18. plt.title( 'The Violin Plot of Words Per Comment', size= 18)
  19. plt.ylabel( 'Words Per Comment')
  20. #显示
  21. plt.show()

分割数据

将数据集分为训练集和测试集


   
  1. from sklearn.model_selection import train_test_split
  2. X_train, X_test, y_train, y_test = train_test_split(df[ 'posts'], df[ 'type'],
  3. test_size= 0.2,
  4. random_state= 123)

文本向量化

机器不理解文本,需要先编码为数字,这里使用tfidf方法进行编码。不熟悉的可以看看这个介绍

如何从文本中提取特征信息?


   
  1. from sklearn.feature_extraction.text import TfidfVectorizer
  2. tfidf = TfidfVectorizer(stop_words= 'english')
  3. X_train = tfidf.fit_transform(X_train)
  4. X_test = tfidf.transform(X_test)

训练模型及模型得分

这里我选来三种模型,使用score得分评价模型表现


   
  1. from sklearn.linear_model import LogisticRegression
  2. model1 = LogisticRegression()
  3. model1.fit(X_train, y_train)
  4. model1.score(X_test, y_test)
0.6357348703170029

   
  1. from sklearn.linear_model import SGDClassifier
  2. model2 = SGDClassifier()
  3. model2.fit(X_train, y_train)
  4. model2.score(X_test, y_test)
0.6824207492795389

   
  1. from sklearn.linear_model import Perceptron
  2. model3 = Perceptron()
  3. model3.fit(X_train, y_train)
  4. model3.score(X_test, y_test)
0.5994236311239193

找到的这个数据集标注的可能有问题,如果是经典的数据集,一般跑出来都能达到80+%的准确率。

近期文章

精选课 | Python网络爬虫与文本数据分析(学术)

用statsmodels库做计量分析

NRC词语情绪词典和词语色彩词典

Loughran&McDonald金融文本情感分析库

股评师分析报告文本情感分析预测股价

使用分析师报告中含有的情感信息预测上市公司股价变动

【公开视频课】Python语法快速入门

【公开视频课】Python爬虫快速入门

一行pandas代码生成哑变量

使用Python读取图片中的文本数据

代码不到40行的超燃动态排序图

情绪及色彩词典获取方式,请在公众号后台回复关键词“20191226” ,

如果想做文本分析

可购买网课 | Python文本数据分析实战(学术) 

或参加Python&Stata数据分析课寒假工作坊


转载:https://blog.csdn.net/weixin_38008864/article/details/103725004
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场