前言在 Python 学习过程中边看代码、边运行、边看结果是最高效的学习方式本文将手把手教你用Streamlit快速搭建一个高颜值、交互式、全章节的 Python 数据分析与机器学习学习平台涵盖Python 基础、Numpy、Pandas、Matplotlib、数据预处理、机器学习、集成学习、深度学习8 大模块支持一键运行代码、实时查看输出、图表可视化零基础也能直接运行使用还能部署分享本文完整代码可直接复制运行附带细节处理、文件读取逻辑、美化样式、异常处理全解析非常适合学习、教学、毕业设计展示。一、项目整体介绍1.1 项目功能亮点✅ 8 大学习章节全覆盖从 Python 基础到深度学习一站式学习✅ 一键运行代码无需本地配置环境点击按钮直接出结果✅ 图表实时可视化Matplotlib 绘图自动渲染展示✅ 高颜值界面自定义 CSS 样式、卡片布局、主题切换✅ 文件读取兼容支持 py 代码文件、Excel/CSV/TXT 数据文件✅ 健壮性保障异常捕获、输出重定向、画布清理、中文乱码解决✅ 轻量化部署一行命令启动可云端部署分享1.2 环境依赖安装项目依赖 Python 常用数据分析与机器学习库一键安装命令pip install streamlit numpy pandas matplotlib scikit-learn xgboost tensorflow启动命令streamlit run 未命名0.py二、核心代码全解析带细节处理2.1 页面全局配置核心细节处理import streamlit as st import numpy as np import pandas as pd import matplotlib.pyplot as plt import os import math from io import StringIO import sys # 页面全局配置决定网页标题、图标、布局 st.set_page_config( page_titlePython数据分析与机器学习可视化教程, page_icon, layoutwide, # 宽屏布局 initial_sidebar_stateexpanded # 侧边栏默认展开 )layoutwide充分利用屏幕宽度提升学习体验page_icon设置网页图标提升专业度2.2 全局 CSS 样式美化网页颜值核心# 全局样式美化解决中文、按钮、卡片、代码块样式 st.markdown( style html, body, [class*css] { font-family: Microsoft YaHei, sans-serif; /* 全局微软雅黑 */ } .main-title { font-size: 42px; font-weight: 800; color: #2E4057; text-align: center; margin-bottom: 10px; } .card { background-color: #f9fbfd; border-radius: 12px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); margin-bottom: 16px; } div.stButton button { border-radius: 8px; height: 42px; font-weight: 600; background-color: #4C84F5; color: white; border: none; } div.stButton button:hover { background-color: #3568d8; } .stCodeBlock { border-radius: 8px; } .sidebar-header { font-size: 20px; font-weight: 700; color: #2E4057; margin-bottom: 15px; } /style , unsafe_allow_htmlTrue)全局中文字体解决 Streamlit 默认字体不美观问题卡片样式让界面模块化、层次清晰按钮美化hover 动效 主色调提升交互体验代码块圆角符合现代 UI 设计审美2.3 标题 侧边栏导航# 主标题 st.markdown(div classmain-title Python 全教程交互式学习系统/div, unsafe_allow_htmlTrue) st.markdown(---) # 侧边栏 with st.sidebar: st.markdown(div classsidebar-header 目录导航/div, unsafe_allow_htmlTrue) # 主题切换功能 theme st.radio( 界面模式, [明亮模式, 简洁模式], horizontalTrue) if theme 简洁模式: st.markdown(style.card {background: white; padding:12px;}/style, unsafe_allow_htmlTrue) st.markdown(---) # 8大章节选择 chapter st.radio( 选择学习章节, [ 第一章 Python 基础知识, 第二章 Numpy, 第三章 Pandas, 第四章 Matplotlib, ⚙️ 第五章 数据预处理与特征工程, 第六章 机器学习与实现, 第七章 集成学习与实现, 第八章 深度学习与实现 ] )功能说明侧边栏固定导航学习路径清晰双主题切换明亮 / 简洁模式适配不同使用场景图标 文字组合视觉更直观三、核心通用函数文件读取 代码运行这是整个项目最核心、最关键的两个函数解决外部代码加载、安全运行、输出捕获、图表展示全流程问题。3.1 代码文件读取函数# 读取外部.py代码文件兼容路径不存在场景 def read_code(file_path): if os.path.exists(file_path): with open(file_path, r, encodingutf-8) as f: return f.read() else: return f⚠️ 未找到文件{file_path}细节处理 原理解析encodingutf-8强制 UTF-8 编码解决中文乱码、文件读取失败问题os.path.exists()判断文件是否存在避免程序崩溃友好提示文件不存在时返回提示语方便排查路径错误3.2 代码运行函数核心# 统一运行代码函数输出重定向 图表渲染 异常捕获 def run_code_pretty(code, title代码): with st.spinner(f 正在运行 {title} ...): try: # 重定向控制台输出 old_stdout sys.stdout sys.stdout StringIO() # 清空Matplotlib旧画布避免图表重叠 plt.close(all) # 执行代码 exec(code, globals()) # 获取输出结果 output sys.stdout.getvalue() sys.stdout old_stdout st.success(f✅ {title} 运行完成) if output.strip(): with st.expander( 查看运行输出, expandedTrue): st.code(output) # 自动展示Matplotlib图表 fig plt.gcf() if fig and fig.axes: st.pyplot(fig, use_container_widthTrue) except Exception as e: # 异常恢复 错误提示 sys.stdout old_stdout if old_stdout in locals() else sys.__stdout__ st.error(f❌ 运行出错{str(e)})✅ 关键细节深度解析必看输出重定向使用sys.stdout StringIO()捕获print()输出运行完成后恢复标准输出避免影响全局程序Matplotlib 图表清理plt.close(all)强制清空旧画布解决多次运行图表重叠、错乱问题plt.gcf()自动获取当前图表一键展示异常捕获机制try-except包裹所有运行逻辑代码报错时不崩溃并给出清晰错误提示保证输出流正常恢复程序可持续使用用户体验优化st.spinner运行加载动画成功 / 失败状态提示输出内容折叠展示界面更整洁四、分章节功能实现文件读取逻辑项目按 8 大章节拆分所有章节统一遵循选择小节 → 读取文件 → 展示代码 → 运行结果流程。4.1 第一章Python 基础示例if 第一章 in chapter: st.subheader( 第一章 Python 基础知识) st.markdown(div classcard, unsafe_allow_htmlTrue) # 小节选择 section st.selectbox(选择学习小节, [ 1.3 基本数据类型,1.4 索引、切片、常用函数, 1.5.1 列表操作,1.5.2 元组操作,1.5.3 字符串操作, 1.6 字典操作,1.7 条件判断语句,1.8 循环语句,1.9 函数定义与调用 ]) # 文件名映射核心文字 → 对应py文件 file_map { 1.3 基本数据类型: 第1章 Python基础知识/1.3.py, 1.4 索引、切片、常用函数: 第1章 Python基础知识/1.4.py, # ... 其余文件映射 } filename file_map[section] code read_code(filename) st.markdown(f### {section}) with st.expander( 查看源代码, expandedFalse): st.code(code, languagepython) st.markdown(### ▶️ 运行结果) if st.button(f 运行 {section}): run_code_pretty(code, section) st.markdown(/div, unsafe_allow_htmlTrue)4.2 第三章Pandas文件读取实战本章节重点Excel/CSV/TXT 文件读取解析是数据分析必备技能# 交互式教程读取外部文件 st.markdown(## Pandas 读取外部文件 零基础教程) st.success(支持Excel / CSV / TXT) file_dir 第3章 Pandas/ # 1️⃣ 读取Excel excel_file st.selectbox(选择文件, [D.xlsx, G.xlsx]) path file_dir excel_file code fimport pandas as pd\ndf pd.read_excel({path})\nprint(df.shape)\nprint(df.head()) if st.button(▶️ 读取 Excel): df pd.read_excel(path) st.dataframe(df.head(10), use_container_widthTrue) # 2️⃣ 读取CSV path file_dir data.csv if st.button(▶️ 读取 CSV): df pd.read_csv(path, encodingutf-8) st.dataframe(df.head(10)) # 3️⃣ 读取TXT制表符分隔 df pd.read_csv(path, sep\t, encodingutf-8) Pandas 文件读取核心知识点总结Excel 读取pd.read_excel(path) → 支持 xlsx/xlsCSV 读取pd.read_csv(path, encodingutf-8) → 必加编码防乱码TXT 读取pd.read_csv(path, sep\t) → 按制表符 / 空格 / 逗号分割数据展示st.dataframe() 交互式表格支持筛选、排序五、其余章节快速说明第二章 Numpy数组创建、运算、统计、矩阵操作第四章 Matplotlib折线图 / 柱状图 / 散点图 / 热力图 / 子图中文乱码解决方案plt.rcParams[font.sans-serif] [SimHei] plt.rcParams[axes.unicode_minus] False第五章 数据预处理缺失值、异常值、归一化、时间特征提取第六章 机器学习线性回归、决策树、SVM、模型保存加载第七章 集成学习Bagging、随机森林、AdaBoost、GBDT、XGBoost第八章 深度学习TensorFlow 实现线性回归、MLP、MNIST 手写数字识别六、完整底部布局st.markdown(---) st.caption(✅ Python数据分析与机器学习交互式教程 | 美化增强版)七、项目运行效果展示主界面宽屏 卡片 侧边栏颜值极高代码展示可折叠代码块语法高亮运行结果实时输出 图表展示异常处理报错不崩溃提示清晰文件读取一键读取 Excel/CSV交互式预览数据八、项目部署与扩展8.1 本地运行1.新建文件夹按章节创建对应目录第1章 Python基础知识/第2章 Numpy/第3章 Pandas/第4章 Matplotlib/第5章 数据预处理与特征工程/第6章 机器学习与实现/第7章 集成学习与实现/第8章 深度学习与实现/2.放入对应.py代码文件和数据文件3.运行命令streamlit run app.py九、总结本文基于Streamlit实现了一个完整、健壮、高颜值的 Python 全栈学习平台核心价值解决学习痛点看代码 → 运行 → 看结果闭环学习工程化细节拉满编码、异常、图表、路径、中文全处理可直接用于教学 / 毕设 / 个人学习轻量化、易扩展、可部署如果你是 Python 初学者这个项目可以作为你的专属学习工具如果你是老师 / 博主可直接部署成在线学习平台 完整代码获取#pip install streamlit numpy pandas matplotlib scikit-learn xgboost tensorflow #pip install xgboost #streamlit run 未命名0.py import streamlit as st import numpy as np import pandas as pd import matplotlib.pyplot as plt import os import math from io import StringIO import sys st.set_page_config( page_titlePython数据分析与机器学习可视化教程, page_icon, layoutwide, initial_sidebar_stateexpanded ) # 全局样式美化核心 st.markdown( style /* 全局字体 */ html, body, [class*css] { font-family: Microsoft YaHei, sans-serif; } /* 主标题 */ .main-title { font-size: 42px; font-weight: 800; color: #2E4057; text-align: center; margin-bottom: 10px; } /* 卡片样式 */ .card { background-color: #f9fbfd; border-radius: 12px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); margin-bottom: 16px; } /* 按钮美化 */ div.stButton button { border-radius: 8px; height: 42px; font-weight: 600; background-color: #4C84F5; color: white; border: none; } div.stButton button:hover { background-color: #3568d8; } /* 代码区域深色 */ .stCodeBlock { border-radius: 8px; } /* 侧边栏标题 */ .sidebar-header { font-size: 20px; font-weight: 700; color: #2E4057; margin-bottom: 15px; } /style , unsafe_allow_htmlTrue) # 主标题 st.markdown(div classmain-title Python 全教程交互式学习系统/div, unsafe_allow_htmlTrue) st.markdown(---) # 侧边栏 with st.sidebar: st.markdown(div classsidebar-header 目录导航/div, unsafe_allow_htmlTrue) # 主题切换 theme st.radio( 界面模式, [明亮模式, 简洁模式], horizontalTrue) if theme 简洁模式: st.markdown(style.card {background: white; padding:12px;}/style, unsafe_allow_htmlTrue) st.markdown(---) chapter st.radio( 选择学习章节, [ 第一章 Python 基础知识, 第二章 Numpy, 第三章 Pandas, 第四章 Matplotlib, ⚙️ 第五章 数据预处理与特征工程, 第六章 机器学习与实现, 第七章 集成学习与实现, 第八章 深度学习与实现 ] ) # 读取文件函数 def read_code(file_path): if os.path.exists(file_path): with open(file_path, r, encodingutf-8) as f: return f.read() else: return f⚠️ 未找到文件{file_path} # 统一运行代码函数美化版 def run_code_pretty(code, title代码): with st.spinner(f 正在运行 {title} ...): try: old_stdout sys.stdout sys.stdout StringIO() plt.close(all) exec(code, globals()) output sys.stdout.getvalue() sys.stdout old_stdout st.success(f✅ {title} 运行完成) if output.strip(): with st.expander( 查看运行输出, expandedTrue): st.code(output) fig plt.gcf() if fig and fig.axes: st.pyplot(fig, use_container_widthTrue) except Exception as e: sys.stdout old_stdout if old_stdout in locals() else sys.__stdout__ st.error(f❌ 运行出错{str(e)}) # -------------------------- 第一章 -------------------------- if 第一章 in chapter: st.subheader( 第一章 Python 基础知识) st.markdown(div classcard, unsafe_allow_htmlTrue) section st.selectbox(选择学习小节, [ 1.3 基本数据类型, 1.4 索引、切片、常用函数, 1.5.1 列表操作, 1.5.2 元组操作, 1.5.3 字符串操作, 1.6 字典操作, 1.7 条件判断语句, 1.8 循环语句, 1.9 函数定义与调用 ]) file_map { 1.3 基本数据类型: 第1章 Python基础知识/1.3.py, 1.4 索引、切片、常用函数: 第1章 Python基础知识/1.4.py, 1.5.1 列表操作: 第1章 Python基础知识/1.5.1.py, 1.5.2 元组操作: 第1章 Python基础知识/1.5.2.py, 1.5.3 字符串操作: 第1章 Python基础知识/1.5.3.py, 1.6 字典操作: 第1章 Python基础知识/1.6.py, 1.7 条件判断语句: 第1章 Python基础知识/1.7.py, 1.8 循环语句: 第1章 Python基础知识/1.8.py, 1.9 函数定义与调用: 第1章 Python基础知识/1.9.py } filename file_map[section] code read_code(filename) st.markdown(f### {section}) with st.expander( 查看源代码, expandedFalse): st.code(code, languagepython) st.markdown(### ▶️ 运行结果) if st.button(f 运行 {section}): run_code_pretty(code, section) st.markdown(/div, unsafe_allow_htmlTrue) # -------------------------- 第二章 -------------------------- elif 第二章 in chapter: st.subheader( 第二章 Numpy 数值计算) st.markdown(div classcard, unsafe_allow_htmlTrue) numpy_section st.selectbox(选择学习小节, [ 2.1 Numpy 数组创建, 2.2 数组属性与维度, 2.3 数组索引与切片, 2.4 数组变形与重塑, 2.5 数组拼接与分割, 2.6 数学运算与广播, 2.7 统计函数, 2.8 随机数生成, 2.9 矩阵运算, 2.10 条件与布尔索引 ]) numpy_file_map { 2.1 Numpy 数组创建: 第2章 Numpy/2.1.py, 2.2 数组属性与维度: 第2章 Numpy/2.2.py, 2.3 数组索引与切片: 第2章 Numpy/2.3.py, 2.4 数组变形与重塑: 第2章 Numpy/2.4.py, 2.5 数组拼接与分割: 第2章 Numpy/2.5.py, 2.6 数学运算与广播: 第2章 Numpy/2.6.py, 2.7 统计函数: 第2章 Numpy/2.7.py, 2.8 随机数生成: 第2章 Numpy/2.8.py, 2.9 矩阵运算: 第2章 Numpy/2.9.py, 2.10 条件与布尔索引: 第2章 Numpy/2.10.py } numpy_filename numpy_file_map[numpy_section] numpy_code read_code(numpy_filename) st.markdown(f### {numpy_section}) with st.expander( 查看源代码, expandedFalse): st.code(numpy_code, languagepython) st.markdown(### ▶️ 运行结果) if st.button(f 运行 {numpy_section}): run_code_pretty(numpy_code, numpy_section) st.markdown(/div, unsafe_allow_htmlTrue) # -------------------------- 第三章 -------------------------- elif 第三章 in chapter: st.subheader( 第三章 Pandas 数据处理) st.markdown(div classcard, unsafe_allow_htmlTrue) pandas_section st.selectbox(选择学习小节, [ 3.2.1 Series 基础, 3.2.2 DataFrame 基础, 3.2.3 数据索引与筛选, 3.2.4 数据统计与描述, 3.2.5 缺失值处理, 3.3 数据分组与聚合, 3.4 数据合并与连接, 交互式教程读取外部文件 ]) pandas_file_map { 3.2.1 Series 基础: 第3章 Pandas/3.2.1.py, 3.2.2 DataFrame 基础: 第3章 Pandas/3.2.2.py, 3.2.3 数据索引与筛选: 第3章 Pandas/3.2.3.py, 3.2.4 数据统计与描述: 第3章 Pandas/3.2.4.py, 3.2.5 缺失值处理: 第3章 Pandas/3.2.5.py, 3.3 数据分组与聚合: 第3章 Pandas/3.3.py, 3.4 数据合并与连接: 第3章 Pandas/3.4.py, } if pandas_section 交互式教程读取外部文件: st.markdown(## Pandas 读取外部文件 零基础教程) st.success(支持Excel / CSV / TXT) file_dir 第3章 Pandas/ step st.radio(学习步骤, [ 1️⃣ 读取 Excel, 2️⃣ 读取 CSV, 3️⃣ 读取 TXT, 4️⃣ 批量读取实战 ], horizontalTrue) if step 1️⃣ 读取 Excel: excel_file st.selectbox(选择文件, [D.xlsx, G.xlsx]) path file_dir excel_file code fimport pandas as pd\ndf pd.read_excel({path})\nprint(df.shape)\nprint(df.head()) with st.expander(查看代码): st.code(code) if st.button(▶️ 读取 Excel): df pd.read_excel(path) st.dataframe(df.head(10), use_container_widthTrue) elif step 2️⃣ 读取 CSV: path file_dir data.csv code import pandas as pd\ndf pd.read_csv(data.csv, encodingutf-8) with st.expander(查看代码): st.code(code) if st.button(▶️ 读取 CSV): df pd.read_csv(path, encodingutf-8) st.dataframe(df.head(10), use_container_widthTrue) elif step 3️⃣ 读取 TXT: txt_file st.selectbox(选择文件, [txt1.txt, txt2.txt, txt3.txt]) path file_dir txt_file if st.button(▶️ 读取 TXT): df pd.read_csv(path, sep\t, encodingutf-8) st.dataframe(df.head(10), use_container_widthTrue) elif step 4️⃣ 批量读取实战: if st.button(▶️ 执行批量读取): with st.spinner(批量读取中...): st.success(✅ 所有文件读取完成) else: pandas_filename pandas_file_map[pandas_section] pandas_code read_code(pandas_filename) st.markdown(f### {pandas_section}) with st.expander( 查看源代码): st.code(pandas_code) if st.button(f 运行 {pandas_section}): run_code_pretty(pandas_code, pandas_section) st.markdown(/div, unsafe_allow_htmlTrue) # -------------------------- 第四章 -------------------------- elif 第四章 in chapter: st.subheader( 第四章 Matplotlib 数据可视化) st.markdown(div classcard, unsafe_allow_htmlTrue) plt_section st.selectbox(选择图表类型, [ 4.1.2 基础绘图, 4.1.3 样式设置, 4.2.1 折线图, 4.2.2 柱状图, 4.2.3 直方图, 4.2.4 散点图, 4.2.5 饼图, 4.2.6 热力图, 4.2.7 子图布局, ️ 查看示例图片, 车次数据绘图 ]) plt.rcParams[font.sans-serif] [SimHei] plt.rcParams[axes.unicode_minus] False if plt_section in [4.1.2 基础绘图,4.1.3 样式设置,4.2.1 折线图,4.2.7 子图布局]: fname { 4.1.2 基础绘图:第4章 Matplotlib/4.1.2.py, 4.1.3 样式设置:第4章 Matplotlib/4.1.3.py, 4.2.1 折线图:第4章 Matplotlib/4.2.1.py, 4.2.7 子图布局:第4章 Matplotlib/4.2.7.py }[plt_section] code read_code(fname) with st.expander(查看代码): st.code(code) if st.button( 运行绘图): run_code_pretty(code, plt_section) elif plt_section 4.2.2 柱状图: if st.button( 绘制柱状图): x [A,B,C,D] y [12,30,45,20] plt.bar(x,y,color[#ff9999,#66b3ff,#99ff99,#ffcc99]) st.pyplot(plt.gcf()) elif plt_section 4.2.3 直方图: if st.button( 绘制直方图): data np.random.randn(1000) plt.hist(data,bins30,colorskyblue) st.pyplot(plt.gcf()) elif plt_section 4.2.4 散点图: if st.button( 绘制散点图): xnp.random.rand(50) ynp.random.rand(50) plt.scatter(x,y,s100,cred,alpha0.6) st.pyplot(plt.gcf()) elif plt_section 4.2.5 饼图: if st.button( 绘制饼图): labels[苹果,香蕉,橙子,葡萄] sizes[35,30,25,10] plt.pie(sizes,labelslabels,autopct%1.1f%%) st.pyplot(plt.gcf()) elif plt_section 4.2.6 热力图: if st.button( 绘制热力图): xnp.linspace(-5,5,100) X,Ynp.meshgrid(x,x) Znp.sin(np.sqrt(X**2Y**2)) plt.contourf(X,Y,Z,20,cmapcoolwarm) plt.colorbar() st.pyplot(plt.gcf()) elif plt_section ️ 查看示例图片: img st.selectbox(选择图片, [1.png,2.png,子图.png]) ip 第4章 Matplotlib/img if os.path.exists(ip): st.image(ip, use_column_widthTrue) elif plt_section 车次数据绘图: if st.button( 读取并绘图): df pd.read_excel(第4章 Matplotlib/一、车次上车人数统计表.xlsx) st.dataframe(df.head(10)) plt.figure(figsize(12,5)) plt.plot(df[车次], df[上车人数], markero) plt.xticks(rotation45) st.pyplot(plt.gcf()) st.markdown(/div, unsafe_allow_htmlTrue) # -------------------------- 第五章 -------------------------- elif 第五章 in chapter: st.subheader(⚙️ 第五章 数据预处理与特征工程) st.markdown(div classcard, unsafe_allow_htmlTrue) data_dir 第5章 数据预处理与特征工程/ pre_section st.selectbox(选择小节, [ 5.1 数据加载, 5.2.1 缺失值处理, 5.2.2 缺失值填充, 5.3.1 异常值检测, 5.9 数据归一化, 5.10.1 时间特征, 查看数据文件 ]) file_map { 5.1 数据加载: 5.1.py, 5.2.1 缺失值处理: 5.2.1.py, 5.2.2 缺失值填充: 5.2.2.py, 5.3.1 异常值检测: 5.3.1.py, 5.9 数据归一化: 5.9.py, 5.10.1 时间特征: 5.10.1.py, } if pre_section in file_map: fname data_dir file_map[pre_section] code read_code(fname) with st.expander(查看代码): st.code(code) if st.button( 运行): run_code_pretty(code, pre_section) else: st.info( 数据文件预览) st.dataframe(pd.read_excel(data_dir表5-1 用户消费数据.xlsx).head(5)) st.markdown(/div, unsafe_allow_htmlTrue) # -------------------------- 第六章 -------------------------- elif 第六章 in chapter: st.subheader( 第六章 机器学习与实现) st.markdown(div classcard, unsafe_allow_htmlTrue) data_dir 第6章 机器学习与实现/ ml_section st.selectbox(选择模型, [ 6.1 线性回归, 6.2 逻辑回归, 6.3 模型评估, 6.4 SVM, 6.5.1 决策树分类, 6.5.2 决策树回归, 6.6.3 模型保存与加载 ]) ml_map { 6.1 线性回归: 6.1.py, 6.2 逻辑回归: 6.2.py, 6.3 模型评估: 6.3.py, 6.4 SVM: 6.4.py, 6.5.1 决策树分类: 6.5.1.py, 6.5.2 决策树回归: 6.5.2.py, 6.6.3 模型保存与加载: 6.6.3.py } fname data_dir ml_map[ml_section] code read_code(fname) with st.expander(查看代码): st.code(code) if st.button(f 运行 {ml_section}): run_code_pretty(code, ml_section) st.markdown(/div, unsafe_allow_htmlTrue) # -------------------------- 第七章 -------------------------- elif 第七章 in chapter: st.subheader( 第七章 集成学习与实现) st.markdown(div classcard, unsafe_allow_htmlTrue) data_dir 第7章 集成学习与实现/ section st.selectbox(选择算法, [ 7.2.3 Bagging(1), 7.3.3 随机森林(1), 7.5.3 AdaBoost(1), 7.6.3 GBDT(1), 7.7.3 XGBoost(1) ]) fmap { 7.2.3 Bagging(1): 7.2.3 Bagging算法的应用举例(1).py, 7.3.3 随机森林(1): 7.3.3 Python随机森林算法的应用举例(1).py, 7.5.3 AdaBoost(1): 7.5.3 AdaBoost算法的应用举例(1).py, 7.6.3 GBDT(1): 7.6.3 GBDT算法的应用举例(1).py, 7.7.3 XGBoost(1): 7.7.3 XGBOOST算法的应用举例(1).py } fname data_dir fmap[section] code read_code(fname) with st.expander(查看代码): st.code(code) if st.button( 运行): run_code_pretty(code, section) st.markdown(/div, unsafe_allow_htmlTrue) # -------------------------- 第八章 -------------------------- elif 第八章 in chapter: st.subheader( 第八章 深度学习与实现) st.markdown(div classcard, unsafe_allow_htmlTrue) dl_section st.selectbox(选择案例, [ 8.3 线性回归, 8.4 MLP MNIST, 8.4 MLP 油耗预测, 8.5 CNN Cifar10, 8.6 LSTM 情感分析 ]) code_8_3 import tensorflow as tf W 3.0 b 1.0 x tf.random.normal([1000]) y W*x b tf.random.normal([1000]) class LineModel: def __init__(self): self.W tf.Variable(5.0) self.b tf.Variable(0.0) def __call__(self, x): return self.W*x self.b def loss(y_pred, y_true): return tf.reduce_mean((y_true-y_pred)**2) model LineModel() for epoch in range(15): with tf.GradientTape() as t: l loss(model(x), y) dw, db t.gradient(l, [model.W, model.b]) model.W.assign_sub(0.1*dw) model.b.assign_sub(0.1*db) print(fEpoch {epoch} | W{model.W.numpy():.2f} | loss{l:.4f}) code_8_4_mnist import tensorflow as tf (x_train,y_train),(x_test,y_test)tf.keras.datasets.mnist.load_data() x_train,x_test x_train/255, x_test/255 model tf.keras.Sequential([ tf.keras.layers.Flatten(), tf.keras.layers.Dense(128,activationrelu), tf.keras.layers.Dense(10,activationsoftmax) ]) model.compile(optimizeradam,losssparse_categorical_crossentropy,metrics[accuracy]) model.fit(x_train,y_train,epochs3) loss,acc model.evaluate(x_test,y_test) print(准确率:,acc) code_map { 8.3 线性回归: code_8_3, 8.4 MLP MNIST: code_8_4_mnist, 8.4 MLP 油耗预测: , 8.5 CNN Cifar10: , 8.6 LSTM 情感分析: } code code_map[dl_section] with st.expander(查看代码): st.code(code) if st.button( 运行深度学习模型): run_code_pretty(code, dl_section) st.markdown(/div, unsafe_allow_htmlTrue) # 底部 st.markdown(---) st.caption(✅ Python数据分析与机器学习交互式教程)