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

  • 2019 年 12 月 31 日
  • 筆記

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

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

读取数据

mbti数据集中有两个字段

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

先查看前5行数据

import pandas as pd  import warnings  warnings.filterwarnings('ignore')  df = pd.read_csv('data/mbti.csv')  df.info()
<class 'pandas.core.frame.DataFrame'>  RangeIndex: 8675 entries, 0 to 8674  Data columns (total 2 columns):  type     8675 non-null object  posts    8675 non-null object  dtypes: object(2)  memory usage: 135.7+ KB

mbti数据集一共有8675条数据

数据探索

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

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

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

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

分割数据

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

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

文本向量化

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

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

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

训练模型及模型得分

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

from sklearn.linear_model import LogisticRegression    model1 = LogisticRegression()  model1.fit(X_train, y_train)  model1.score(X_test, y_test)
0.6357348703170029
from sklearn.linear_model import SGDClassifier    model2 = SGDClassifier()  model2.fit(X_train, y_train)  model2.score(X_test, y_test)
0.6824207492795389
from sklearn.linear_model import Perceptron    model3 = Perceptron()  model3.fit(X_train, y_train)  model3.score(X_test, y_test)
0.5994236311239193

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