sklearn对MBTI分类并统计指标

一、读取数据

使用 pandas 读取文件:

data_set = pd.read_csv("data/mbti_1.csv")  # 读取文件

二、显示文件信息

def showTableInfo(data_set):
    print("DATA PROFILING")
    print()
    print("a. Desribing Data Set:")
    data_set.info()                     # 输出表格信息
    print()
    # 统计行、列数目
    print("b. We have {r} Rows and {c} Columns".format(r=data_set.shape[0], c=data_set.shape[1]))
    print()
    # 统计空值数目
    print("c. Null Values are :")
    print(data_set[data_set.isnull()].count())
    print()
    # 统计一共有多少种性格类型
    print("d. There are {t} Unique MBTI types in this study".format(t=data_set['type'].nunique()))
    print(np.unique(np.array(data_set['type'])))
    print()
    # 统计用户数目和发言语句数量
    print("e. No. of Total users & Posts =>")
    posts = []
    data_set.apply(lambda x: extract(x, posts), axis=1)
    print("Number of users", len(data_set))
    print("Number of posts", len(posts))
    print()
    # 输出文件前五行
    print("f. Data Sneak Peek: First 5 rows")
    print(data_set.head(5))

三、统计各类型数目

def countTypeNumber(data_set):
    p_post = data_set['type'].value_counts()  # count of comments per personality type - sns barplot requires 1D data

    # 柱状图统计每个类别数量
    plt.figure(figsize=(15, 4))  # 图像的尺寸
    sns.barplot(p_post.index, p_post.values)  # 柱状图横坐标为类别,纵坐标为数量
    plt.xlabel('MBTI Personality', size=12)  # x 轴标题
    plt.ylabel('Posts available', size=12)  # y 轴标题
    plt.title('Posts with regards to each personality type')  # 图标标题
    plt.show()  # 显示图表
    print()
    print("The number of every type is :")
    # 输出每个类别的人数
    for idx in range(len(p_post.values)):
        print(p_post.index[idx], ": ", p_post.values[idx])

四、数据集处理

# 数据集分割为训练集和测试集,比例为 7:3
X_train, X_test, y_train, y_test = train_test_split(data_set['posts'], data_set['type'],
                                                        test_size=0.3,
                                                        random_state=123)

tfidf = TfidfVectorizer(stop_words='english')   # 统计词频,并使用 tf-idf编码
X_train = tfidf.fit_transform(X_train)          # 对训练集使用 tf-idf 编码
X_test = tfidf.transform(X_test)                # 对测试集使用 tf-idf 编码

五、模型建立与预测

model1 = LogisticRegression()                   # 逻辑回归模型
model1.fit(X_train, y_train)                    # 训练逻辑回归模型
y_pred1 = model1.predict(X_test)                # 使用训练好的模型预测

六、指标评价

def showMetrics(y_true,y_pred,model_name): # 计算各种指标
    conf_matrix = confusion_matrix(y_true, y_pred)        # 混淆矩阵
    acc    = accuracy_score(y_true, y_pred)               # 准确率
    prec   = precision_score(y_true, y_pred,average='macro')   # 精确率
    recall = recall_score(y_true, y_pred,average='macro') # 召回率

    classes = ['ENFJ','ENFP','ENTJ','ENTP','ESFJ','ESFP','ESTJ','ESTP',
               'INFJ','INFP','INTJ','INTP','ISFJ','ISFP','ISTJ','ISTP']  #

    # 可视化混淆矩阵
    disp = ConfusionMatrixDisplay(confusion_matrix=conf_matrix, display_labels=classes)
    disp.plot(
        include_values=True,  # 混淆矩阵每个单元格上显示具体数值
        cmap="viridis",  # 使用的sklearn中的默认值
        ax=None,  # 同上
        xticks_rotation="horizontal",  # 同上
        values_format="d"  # 显示的数值格式
    )
    plt.title('Confusion Matrix of ' + model_name) # 标题名
    plt.show()                # 显示图片

    print("Accuracy :",acc)   # 输出准确率
    print("Precision :",prec) # 输出精确率
    print("Recall :",recall)  # 输出召回率

七、完整代码

import warnings
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score
from sklearn.metrics import recall_score
from sklearn.metrics import precision_score
from sklearn.metrics import confusion_matrix,ConfusionMatrixDisplay

def extract(posts, new_posts): # 统计语句数量
    for post in posts[1].split("|||"):     # 以 ”|||“ 为分隔符
        new_posts.append((posts[0], post)) # 构建语句列表

def showTableInfo(data_set):
    print("DATA PROFILING")
    print()
    print("a. Desribing Data Set:")
    data_set.info()                     # 输出表格信息
    print()
    # 统计行、列数目
    print("b. We have {r} Rows and {c} Columns".format(r=data_set.shape[0], c=data_set.shape[1]))
    print()
    # 统计空值数目
    print("c. Null Values are :")
    print(data_set[data_set.isnull()].count())
    print()
    # 统计一共有多少种性格类型
    print("d. There are {t} Unique MBTI types in this study".format(t=data_set['type'].nunique()))
    print(np.unique(np.array(data_set['type'])))
    print()
    # 统计用户数目和发言语句数量
    print("e. No. of Total users & Posts =>")
    posts = []
    data_set.apply(lambda x: extract(x, posts), axis=1)
    print("Number of users", len(data_set))
    print("Number of posts", len(posts))
    print()
    # 输出文件前五行
    print("f. Data Sneak Peek: First 5 rows")
    print(data_set.head(5))

def countTypeNumber(data_set):
    p_post = data_set['type'].value_counts()  # count of comments per personality type - sns barplot requires 1D data

    # 柱状图统计每个类别数量
    plt.figure(figsize=(15, 4))  # 图像的尺寸
    sns.barplot(p_post.index, p_post.values)  # 柱状图横坐标为类别,纵坐标为数量
    plt.xlabel('MBTI Personality', size=12)  # x 轴标题
    plt.ylabel('Posts available', size=12)  # y 轴标题
    plt.title('Posts with regards to each personality type')  # 图标标题
    plt.show()  # 显示图表
    print()
    print("The number of every type is :")
    # 输出每个类别的人数
    for idx in range(len(p_post.values)):
        print(p_post.index[idx], ": ", p_post.values[idx])

def showMetrics(y_true,y_pred,model_name): # 计算各种指标
    conf_matrix = confusion_matrix(y_true, y_pred)        # 混淆矩阵
    acc    = accuracy_score(y_true, y_pred)               # 准确率
    prec   = precision_score(y_true, y_pred,average='macro')   # 精确率
    recall = recall_score(y_true, y_pred,average='macro') # 召回率

    classes = ['ENFJ','ENFP','ENTJ','ENTP','ESFJ','ESFP','ESTJ','ESTP',
               'INFJ','INFP','INTJ','INTP','ISFJ','ISFP','ISTJ','ISTP']  #

    # 可视化混淆矩阵
    disp = ConfusionMatrixDisplay(confusion_matrix=conf_matrix, display_labels=classes)
    disp.plot(
        include_values=True,  # 混淆矩阵每个单元格上显示具体数值
        cmap="viridis",  # 使用的sklearn中的默认值
        ax=None,  # 同上
        xticks_rotation="horizontal",  # 同上
        values_format="d"  # 显示的数值格式
    )
    plt.title('Confusion Matrix of ' + model_name) # 标题名
    plt.show()                # 显示图片

    print("Accuracy :",acc)   # 输出准确率
    print("Precision :",prec) # 输出精确率
    print("Recall :",recall)  # 输出召回率

if __name__ == '__main__':

    warnings.filterwarnings("ignore")          # 过滤警告
    data_set = pd.read_csv("data/mbti_1.csv")  # 读取文件
    showTableInfo(data_set)                         # 显示数据信息
    countTypeNumber(data_set)                  # 统计每类性格的人数
    # 数据集分割为训练集和测试集,比例为 7:3
    X_train, X_test, y_train, y_test = train_test_split(data_set['posts'], data_set['type'],
                                                        test_size=0.3,
                                                        random_state=123)

    tfidf = TfidfVectorizer(stop_words='english')   # 统计词频,并使用 tf-idf编码
    X_train = tfidf.fit_transform(X_train)          # 对训练集使用 tf-idf 编码
    X_test = tfidf.transform(X_test)                # 对测试集使用 tf-idf 编码

    model1 = LogisticRegression()                   # 逻辑回归模型
    model1.fit(X_train, y_train)                    # 训练逻辑回归模型
    y_pred1 = model1.predict(X_test)                # 使用训练好的模型预测
    print()
    print("The metrics of LogisticRegression:")
    showMetrics(y_test,y_pred1,model_name="LogisticRegression") # 计算并输出各种评价指标

    model2 = SGDClassifier()                        # SGD 线性分类器模型
    model2.fit(X_train, y_train)                    # 训练 SGD 线性分类器模型
    y_pred2 = model2.predict(X_test)                # 使用训练好的模型预测
    print()
    print("The metrics of SGDClassifier:")
    showMetrics(y_test, y_pred2, model_name="SGDClassifier")  # 计算并输出各种评价指标

八、参考链接

### 使用机器学习进行MBTI人格分类 #### 数据收集与预处理 为了实现MBTI人格类型的自动分类,首先需要构建一个包含大量标注了MBTI类型的数据集。这些数据通常来源于社交平台上的公开帖子或专门设计的心理测评问卷。对于来自社交媒体的内容,可以采用网络爬虫工具抓取用户发布的文字内容作为输入样本[^1]。 #### 特征提取 针对获取到的原始文本资料,应用自然语言处理技术来进行特征工程操作。具体来说: - **词袋模型(Bag of Words)** 或 TF-IDF 向量化表示法能够捕捉词汇频率信息; - **主题建模(LDA)** 可用于发现文档集合内的潜在话题分布情况; - **情感分析** 能够识别出积极/消极情绪倾向; - **句法依存关系解析** 则有助于理解句子结构特点; 此外,还可以考虑加入一些额外的人工定义属性,比如平均单词长度、标点符号使用习惯等个性化指标。 #### 模型训练与验证 选用合适的监督式学习算法完成最终的任务目标——即给定一段新的未见过的文字材料后能准确预测其对应的四个维度(外向vs内向,感觉vs直觉,思考vs情感,判断vs知觉)。常见的候选方案有随机森林(Random Forest),逻辑回归(Logistic Regression), 支持向量机(Support Vector Machine) 和神经网络(Neural Network)。 ```python from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.pipeline import Pipeline from sklearn.naive_bayes import MultinomialNB import pandas as pd # 加载准备数据集 data = pd.read_csv('mbti_data.csv') X_train, X_test, y_train, y_test = train_test_split(data['posts'], data['type'], test_size=0.2) # 构造管道流程 pipeline = Pipeline([ ('tfidf', TfidfVectorizer()), ('clf', MultinomialNB()) ]) # 训练朴素贝叶斯分类器 pipeline.fit(X_train, y_train) # 测试性能 accuracy = pipeline.score(X_test, y_test) print(f'Accuracy on the testing set is {accuracy:.3f}') ``` 通过上述过程建立起来的性格推断系统不仅限于MBTI体系,在其他领域同样具有广泛的应用前景,例如人力资源管理中的员工选拔面试环节或是在线教育平台上对学生学习风格偏好的定制化服务等方面均展现出巨大潜力。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SanXiMeng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值