# 写前端用的库streamlit
import streamlit as st
# 导入pandas 和 numpy 用这两个库进行数据处理
import pandas as pd
import numpy as np
# 将用来画动态图
import time
# mpl将plt画的图设置中文
import matplotlib as mpl
# 用sns画图,看看最开始的数据长什么样
import seaborn as sns
# PCA将数据降维
from sklearn.decomposition import PCA
# 混淆矩阵
from sklearn.metrics import confusion_matrix
# 决策树
from sklearn.tree import DecisionTreeClassifier
# 用于画出整个决策树
from sklearn.tree import export_graphviz
import graphviz
# k-nn(k-近邻)
from sklearn.neighbors import KNeighborsClassifier
# 支持向量机
from sklearn.svm import SVC
# 集成学习
from sklearn.ensemble import BaggingClassifier
# 保存模型
import joblib
# 各种评价标准
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score
# 用来画图
import matplotlib.pyplot as plt
# 将plt画出来的图设置为中文简体
mpl.rcParams['font.family'] = 'SimHei'
# 读取数据集,数据集可以直接再
test_x = pd.read_csv(r"D:\social-media-usage-and-emotional-well-being\pythonProject\Data preprocessing\test_x.csv")
test_y = pd.read_csv(r"D:\social-media-usage-and-emotional-well-being\pythonProject\Data preprocessing\test_y.csv")
train_y = pd.read_csv(r"D:\social-media-usage-and-emotional-well-being\pythonProject\Data preprocessing\train_y.csv")
train_x = pd.read_csv(r"D:\social-media-usage-and-emotional-well-being\pythonProject\Data preprocessing\train_x.csv")
st.header("根据社交媒体使用情况判断用户情绪")
choice = st.sidebar.selectbox(
label='请选择您想进行的操作',
options=('预测情绪', '调试模型'),
index=0,
format_func=str,
)
if choice == '调试模型':
st.sidebar.subheader('模型选择与调参')
model = st.sidebar.selectbox(
label='请选择您想使用的模型',
options=('决策树 (Decision_Tree)', 'k-近邻 (knn)', '支持向量机 (SVM)', '集成学习 (Ensemble Learning)'),
index=0,
format_func=str,
help='目前只提供这四种模型'
)
if model == '决策树 (Decision_Tree)':
st.subheader('决策树')
iterations = st.sidebar.slider("max_depth(最大深度)", 1, 30, 20, 1, help='决策树的最大深度,限制树的生长,防止过拟合.')
min_samples_split1 = st.sidebar.slider("min_samples_split(最小分裂样本数)", 2, 50, 2, 1, help='内部节点再划分所需的最小样本数。')
min_samples_leaf1 = st.sidebar.slider("min_samples_leaf(最小叶子节点样本数)", 1, 50, 1, 1, help='叶节点所需的最小样本数。')
progress_bar = st.empty()
with st.spinner('加载中...'):
time.sleep(0.5)
# 实例决策树
Decision_Tree = DecisionTreeClassifier(criterion='entropy', max_depth=iterations, min_samples_split=min_samples_split1, min_samples_leaf=min_samples_leaf1, random_state=2024)
# 训练决策树
Decision_Tree.fit(train_x, train_y)
joblib.dump(Decision_Tree,
'D:\social-media-usage-and-emotional-well-being\pythonProject\models\Decision_Tree_model.pickle')
# 预测
Decision_Tree_pred = Decision_Tree.predict(test_x)
# precision成绩
Decision_Tree_precision = precision_score(test_y, Decision_Tree_pred, average='macro')
# recall成绩
Decision_Tree_recall = recall_score(test_y, Decision_Tree_pred, average='micro')
# f1成绩
Decision_Tree_f1 = f1_score(test_y, Decision_Tree_pred, average='weighted')
# 准确率
Decision_Tree_accuracy = accuracy_score(test_y, Decision_Tree_pred)
# 混淆矩阵
conf_matrix = confusion_matrix(test_y, Decision_Tree_pred)
# 指标名称列表
metrics = ['Accuracy', 'Precision', 'Recall', 'F1']
# 对应的指标值列表
values = [Decision_Tree_accuracy, Decision_Tree_precision, Decision_Tree_recall, Decision_Tree_f1]
# 绘制条形图
fig, ax = plt.subplots()
colors = ['lightcoral', 'lightgreen', 'lightskyblue', 'lightsalmon']
ax.bar(metrics, values, color=colors)
# 添加标题
ax.set_title("Decision Tree Metrics")
# 添加x轴标签
ax.set_xlabel("Metrics")
# 添加y轴标签
ax.set_ylabel("Values")
ax.set_ylim(0, 1)
# 显示图形
# st.pyplot(fig)
fig1, ax = plt.subplots()
sns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues')
ax.set_xlabel('Predicted')
ax.set_ylabel('Actual')
# 将两个图放在一行
col1, col2 = st.columns(2)
with col1:
st.pyplot(fig)
with col2:
st.pyplot(fig1)
if st.button('显示整个决策树'):
with st.spinner('加载中...'):
time.sleep(0.5)
target_names = list('Age, Daily_Usage_Time(minutes), Posts_Per_Day, Likes_Received_Per_Day, Comments_Received_Per_Day, Messages_Sent_Per_Day, Gender_Male, Gender_Non - binary, Platform_Instagram, Platform_LinkedIn, Platform_Snapchat, Platform_Telegram, Platform_Twitter, Platform_Whatsapp'.split(","))
# 将决策树模型导出为graphviz格式的dot文件
dot_data = export_graphviz(Decision_Tree, out_file=None,
feature_names=target_names,
class_names=list(set(test_y['Dominant_Emotion'])),
filled=True, rounded=True,
special_characters=True)
# 使用graphviz库的Source函数将dot文件转换为可视化图形
graph = graphviz.Source(dot_data)
st.graphviz_chart(dot_data)
st.code('''
if model == '决策树 (Decision_Tree)':
st.subheader('决策树')
iterations = st.sidebar.slider("max_depth(最大深度)", 1, 30, 20, 1, help='决策树的最大深度,限制树的生长,防止过拟合.')
min_samples_split1 = st.sidebar.slider("min_samples_split(最小分裂样本数)", 2, 50, 2, 1, help='内部节点再划分所需的最小样本数。')
min_samples_leaf1 = st.sidebar.slider("min_samples_leaf(最小叶子节点样本数)", 1, 50, 1, 1, help='叶节点所需的最小样本数。')
progress_bar = st.empty()
with st.spinner('加载中...'):
time.sleep(0.5)
# 实例决策树
Decision_Tree = DecisionTreeClassifier(criterion='entropy', max_depth=iterations, min_samples_split=min_samples_split1, min_samples_leaf=min_samples_leaf1, random_state=2024)
# 训练决策树
Decision_Tree.fit(train_x, train_y)
joblib.dump(Decision_Tree,
'D:\social-media-usage-and-emotional-well-being\pythonProject\models\Decision_Tree_model.pickle')
# 预测
Decision_Tree_pred = Decision_Tree.predict(test_x)
# precision成绩
Decision_Tree_precision = precision_score(test_y, Decision_Tree_pred, average='macro')
# recall成绩
Decision_Tree_recall = recall_score(test_y, Decision_Tree_pred, average='micro')
# f1成绩
Decision_Tree_f1 = f1_score(test_y, Decision_Tree_pred, average='weighted')
# 准确率
Decision_Tree_accurac
学学学学学学学学学学学!!!
- 粉丝: 14
- 资源: 1
最新资源
- 西电微机原理实验四:微机原理实验中8255可编程并行接口的应用实践
- 西电微机原理课程实验指南-理论与实践相结合提升技术素养
- 基于go+gin+vue+element admin 后台管理系统,支持用户管理,认证,内容管理等详细文档+优秀项目+全部资料.zip
- 基于go-kratos +Ant Design Pro的前后端分离微服务管理系统后端模块详细文档+优秀项目+全部资料.zip
- 基于Golang 的后台管理系统(基础版)详细文档+优秀项目+全部资料.zip
- CR750CR751 控制器操作说明书(故障排除).pdf
- 基于goframe搭建的电商前后台API系统详细文档+优秀项目+全部资料.zip
- linux常用命令大全.txt
- 基于golang的分布式即时通讯系统详细文档+优秀项目+全部资料.zip
- linux常用命令大全.txt
- 基于Golang的个人简易博客系统详细文档+优秀项目+全部资料.zip
- 基于Golang实现的单点登录系统(go-sso),实现手机号注册、手机号+验证码登录、手机号+密码登录、账号登出等功能,用户认证采用cookie和jwt两种方式详细文档+优秀项目+全部资料.zip
- 基于Golang+Markdown的博客系统详细文档+优秀项目+全部资料.zip
- 基于golang实现的分布式聊天系统,支持i一对一聊天,聊天室等详细文档+优秀项目+全部资料.zip
- 基于Golang的开源社区系统。简洁对话,高效互动,详细文档+优秀项目+全部资料.zip
- 基于Golang重构考试系统详细文档+优秀项目+全部资料.zip
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈