mirror of
https://github.com/Visualize-ML/Book4_Power-of-Matrix.git
synced 2026-05-05 09:23:48 +08:00
Add files via upload
This commit is contained in:
committed by
GitHub
parent
79be5dda7d
commit
5adb9e44a7
155
Book4_Ch21_Python_Codes/Bk4_Ch21_01.ipynb
Normal file
155
Book4_Ch21_Python_Codes/Bk4_Ch21_01.ipynb
Normal file
@@ -0,0 +1,155 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "73bd968b-d970-4a05-94ef-4e7abf990827",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Chapter 21\n",
|
||||
"\n",
|
||||
"# 判断正定矩阵\n",
|
||||
"Book_4《矩阵力量》 | 鸢尾花书:从加减乘除到机器学习 (第二版)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "54195758-c635-45fc-be6a-ebae54b12d78",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"这段代码的功能是判断一个矩阵是否为正定矩阵。首先,正定矩阵 \\( A \\) 的定义要求其必须是对称矩阵,即满足 \\( A = A^T \\)。若矩阵 \\( A \\) 是对称矩阵,代码进一步检查是否可以对其进行 Cholesky 分解。Cholesky 分解是一种将正定矩阵 \\( A \\) 表示为下三角矩阵 \\( L \\) 和其转置 \\( L^T \\) 的操作,即\n",
|
||||
"\n",
|
||||
"$$\n",
|
||||
"A = L L^T\n",
|
||||
"$$\n",
|
||||
"\n",
|
||||
"若分解成功,则说明 \\( A \\) 是正定矩阵,函数返回 `True`;若分解失败(引发 `LinAlgError` 异常),则矩阵不是正定矩阵,函数返回 `False`。在这段代码中,示例矩阵\n",
|
||||
"\n",
|
||||
"$$\n",
|
||||
"A = \\begin{bmatrix} 1 & 0 \\\\ 0 & 0 \\end{bmatrix}\n",
|
||||
"$$\n",
|
||||
"\n",
|
||||
"不是正定矩阵,因此代码会输出 `False`。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"id": "53cb4618-5e9f-4388-b8e2-893534f3cfbe",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import numpy as np # 导入 numpy 进行数值计算"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "74d9b36f-c406-4573-a99e-db75e9380e36",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 定义判断正定矩阵的函数"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"id": "7abef436-2925-4561-90ae-dc85e1fd34f4",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def is_pos_def(A): # 函数 is_pos_def 用于判断矩阵是否为正定矩阵\n",
|
||||
" if np.array_equal(A, A.T): # 检查矩阵是否为对称矩阵\n",
|
||||
" try:\n",
|
||||
" np.linalg.cholesky(A) # 尝试进行 Cholesky 分解\n",
|
||||
" return True # 若成功,则矩阵为正定矩阵\n",
|
||||
" except np.linalg.LinAlgError: # 若分解失败,捕获异常\n",
|
||||
" return False # 分解失败则矩阵不是正定矩阵\n",
|
||||
" else:\n",
|
||||
" return False # 若矩阵不对称,则直接返回 False"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "7632f259-4cc2-40b5-8886-5c2c670b876c",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 定义待检测的矩阵"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"id": "11933a91-89ae-4529-b5f6-302fa7eebf2b",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"A = np.array([[1, 0], \n",
|
||||
" [0, 0]]) # 定义矩阵 A"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 4,
|
||||
"id": "7bb2c23d-c6ef-4f9a-8c48-01f55905fa97",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"## 打印结果"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"id": "6f4d7b05-2a48-40b5-879a-12e58b6ff62a",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"False\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(is_pos_def(A)) # 调用函数 is_pos_def,打印矩阵 A 是否为正定矩阵"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "85a80909-2aac-49ed-bb7a-f8cc6b80ee7d",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": []
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "ecd322f4-f919-4be2-adc3-69d28ef25e69",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": []
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.12.7"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
392
Book4_Ch21_Python_Codes/Bk4_Ch21_02.ipynb
Normal file
392
Book4_Ch21_Python_Codes/Bk4_Ch21_02.ipynb
Normal file
File diff suppressed because one or more lines are too long
76
Book4_Ch21_Python_Codes/Streamlit_Bk4_Ch21_02.py
Normal file
76
Book4_Ch21_Python_Codes/Streamlit_Bk4_Ch21_02.py
Normal file
@@ -0,0 +1,76 @@
|
||||
|
||||
###############
|
||||
# Authored by Weisheng Jiang
|
||||
# Book 4 | From Basic Arithmetic to Machine Learning
|
||||
# Published and copyrighted by Tsinghua University Press
|
||||
# Beijing, China, 2025
|
||||
###############
|
||||
|
||||
import streamlit as st # 导入 Streamlit,用于构建交互式 Web 应用
|
||||
import plotly.graph_objects as go # 导入 Plotly 的图形对象模块,用于绘图
|
||||
import sympy # 导入 SymPy,用于符号运算
|
||||
import numpy as np # 导入 NumPy,用于数值计算
|
||||
|
||||
def bmatrix(a): # 定义一个函数,将 NumPy 数组转换为 LaTeX bmatrix 格式的字符串
|
||||
"""返回一个 LaTeX 矩阵表示"""
|
||||
if len(a.shape) > 2: # 如果输入数组维度大于 2,抛出异常
|
||||
raise ValueError('bmatrix 函数只支持二维矩阵')
|
||||
lines = str(a).replace('[', '').replace(']', '').splitlines() # 将数组转换为字符串并移除方括号
|
||||
rv = [r'\begin{bmatrix}'] # LaTeX 矩阵开始符号
|
||||
rv += [' ' + ' & '.join(l.split()) + r'\\' for l in lines] # 按行格式化
|
||||
rv += [r'\end{bmatrix}'] # LaTeX 矩阵结束符号
|
||||
return '\n'.join(rv) # 返回拼接后的 LaTeX 字符串
|
||||
|
||||
with st.sidebar: # 在侧边栏中创建交互内容
|
||||
st.latex(r'''A = \begin{bmatrix} a & b\\ b & c \end{bmatrix}''') # 显示矩阵 A 的 LaTeX 表示
|
||||
st.latex(r'''f(x_1,x_2) = ax_1^2 + 2bx_1x_2 + cx_2^2''') # 显示二次形式的 LaTeX 表示
|
||||
a = st.slider('a', -2.0, 2.0, step=0.1) # 创建滑块,用于设置矩阵 A 的元素 a
|
||||
b = st.slider('b', -2.0, 2.0, step=0.1) # 创建滑块,用于设置矩阵 A 的元素 b
|
||||
c = st.slider('c', -2.0, 2.0, step=0.1) # 创建滑块,用于设置矩阵 A 的元素 c
|
||||
|
||||
x1_ = np.linspace(-2, 2, 101) # 在 [-2, 2] 范围内生成 101 个均匀点,用于 x1
|
||||
x2_ = np.linspace(-2, 2, 101) # 同样生成 x2 的点
|
||||
xx1, xx2 = np.meshgrid(x1_, x2_) # 生成网格点,方便绘制 3D 和等高线图
|
||||
|
||||
x1, x2 = sympy.symbols('x1 x2') # 定义符号变量 x1 和 x2
|
||||
A = np.array([[a, b], # 定义矩阵 A 的第一行
|
||||
[b, c]]) # 定义矩阵 A 的第二行
|
||||
D, V = np.linalg.eig(A) # 计算矩阵 A 的特征值 D 和特征向量 V
|
||||
D = np.diag(D) # 将特征值转化为对角矩阵
|
||||
|
||||
st.latex(r'''A = \begin{bmatrix}%s & %s\\%s & %s\end{bmatrix}''' % (a, b, b, c)) # 显示矩阵 A 的 LaTeX 表示
|
||||
st.latex(r'''A = V \Lambda V^{T}''') # 显示特征分解公式
|
||||
st.latex(bmatrix(A) + '=' + bmatrix(np.around(V, decimals=3)) + '@' + bmatrix(np.around(D, decimals=3)) + '@' + bmatrix(np.around(V.T, decimals=3))) # 显示特征分解的详细过程
|
||||
|
||||
x = np.array([[x1, x2]]).T # 定义符号向量 x
|
||||
f_x = a * x1**2 + 2 * b * x1 * x2 + c * x2**2 # 定义二次形式 f(x1, x2)
|
||||
st.latex(r'''f(x_1,x_2) = ''') # 显示二次形式的 LaTeX 表示
|
||||
st.write(f_x) # 显示二次形式的符号表达式
|
||||
|
||||
f_x_fcn = sympy.lambdify([x1, x2], f_x) # 将符号函数 f(x1, x2) 转换为数值计算函数
|
||||
ff_x = f_x_fcn(xx1, xx2) # 在网格点上计算二次形式的值
|
||||
|
||||
fig_surface = go.Figure(go.Surface( # 创建 3D 表面图
|
||||
x=x1_, # 表面图的 x 轴为 x1 的值
|
||||
y=x2_, # 表面图的 y 轴为 x2 的值
|
||||
z=ff_x, # 表面图的 z 轴为二次形式的值
|
||||
colorscale='RdYlBu_r')) # 使用红黄蓝颜色映射
|
||||
fig_surface.update_layout(
|
||||
autosize=False, # 禁用自动调整尺寸
|
||||
width=500, # 设置图表宽度为 500 像素
|
||||
height=500) # 设置图表高度为 500 像素
|
||||
st.plotly_chart(fig_surface) # 在 Streamlit 页面上显示 3D 表面图
|
||||
|
||||
fig_contour = go.Figure( # 创建 2D 等高线图
|
||||
go.Contour(
|
||||
z=ff_x, # 等高线的高度值
|
||||
x=x1_, # 等高线图的 x 轴为 x1 的值
|
||||
y=x2_, # 等高线图的 y 轴为 x2 的值
|
||||
colorscale='RdYlBu_r' # 使用红黄蓝颜色映射
|
||||
))
|
||||
fig_contour.update_layout(
|
||||
autosize=False, # 禁用自动调整尺寸
|
||||
width=500, # 设置图表宽度为 500 像素
|
||||
height=500) # 设置图表高度为 500 像素
|
||||
st.plotly_chart(fig_contour) # 在 Streamlit 页面上显示 2D 等高线图
|
||||
|
||||
90
Book4_Ch21_Python_Codes/Streamlit_Bk4_Ch21_03.py
Normal file
90
Book4_Ch21_Python_Codes/Streamlit_Bk4_Ch21_03.py
Normal file
@@ -0,0 +1,90 @@
|
||||
|
||||
###############
|
||||
# Authored by Weisheng Jiang
|
||||
# Book 4 | From Basic Arithmetic to Machine Learning
|
||||
# Published and copyrighted by Tsinghua University Press
|
||||
# Beijing, China, 2025
|
||||
###############
|
||||
|
||||
import numpy as np # 导入 NumPy,用于数值计算
|
||||
from sympy import lambdify, diff, exp, latex, simplify, symbols # 从 SymPy 导入符号计算相关模块
|
||||
import plotly.figure_factory as ff # 从 Plotly 导入工厂方法,用于绘制梯度向量和流线
|
||||
import plotly.graph_objects as go # 从 Plotly 导入图形对象模块,用于绘图
|
||||
import streamlit as st # 导入 Streamlit,用于构建交互式 Web 应用
|
||||
|
||||
x1, x2 = symbols('x1 x2') # 定义符号变量 x1 和 x2
|
||||
num = 301 # 设置网格点数量
|
||||
x1_array = np.linspace(-3, 3, num) # 在 [-3, 3] 范围内生成 301 个均匀点用于 x1
|
||||
x2_array = np.linspace(-3, 3, num) # 在 [-3, 3] 范围内生成 301 个均匀点用于 x2
|
||||
xx1, xx2 = np.meshgrid(x1_array, x2_array) # 创建网格点,用于绘制函数和梯度图
|
||||
|
||||
# 定义函数 f(x1, x2)
|
||||
f_x = 3 * (1 - x1)**2 * exp(-(x1**2) - (x2 + 1)**2) \
|
||||
- 10 * (x1 / 5 - x1**3 - x2**5) * exp(-x1**2 - x2**2) \
|
||||
- 1 / 3 * exp(-(x1 + 1)**2 - x2**2) # 定义复杂的二元函数
|
||||
|
||||
f_x_fcn = lambdify([x1, x2], f_x) # 将符号函数 f_x 转换为数值计算函数
|
||||
f_zz = f_x_fcn(xx1, xx2) # 在网格点上计算函数值,用于绘制表面图和等高线图
|
||||
|
||||
st.latex('f(x_1, x_2) = ' + latex(f_x)) # 在 Streamlit 页面中显示函数的 LaTeX 表示
|
||||
|
||||
# 计算梯度
|
||||
grad_f = [diff(f_x, var) for var in (x1, x2)] # 对 f_x 分别对 x1 和 x2 求偏导,得到梯度向量
|
||||
grad_fcn = lambdify([x1, x2], grad_f) # 将梯度向量转换为数值计算函数
|
||||
|
||||
x1__ = np.linspace(-3, 3, 40) # 在 [-3, 3] 范围内生成 40 个点用于 x1(粗网格)
|
||||
x2__ = np.linspace(-3, 3, 40) # 在 [-3, 3] 范围内生成 40 个点用于 x2(粗网格)
|
||||
xx1_, xx2_ = np.meshgrid(x1__, x2__) # 创建粗网格点
|
||||
V = grad_fcn(xx1_, xx2_) # 在粗网格点上计算梯度向量,用于绘制梯度图
|
||||
|
||||
# 绘制 3D 表面图
|
||||
fig_surface = go.Figure(go.Surface(
|
||||
x=x1_array, # 表面图的 x 轴为 x1 网格点
|
||||
y=x2_array, # 表面图的 y 轴为 x2 网格点
|
||||
z=f_zz, # 表面图的 z 轴为函数值
|
||||
showscale=False, # 禁用颜色条
|
||||
colorscale='RdYlBu_r')) # 使用红黄蓝色带
|
||||
fig_surface.update_layout(
|
||||
autosize=False, # 禁用自动调整尺寸
|
||||
width=800, # 设置图表宽度为 800 像素
|
||||
height=600) # 设置图表高度为 600 像素
|
||||
st.plotly_chart(fig_surface) # 在 Streamlit 页面中显示 3D 表面图
|
||||
|
||||
# 绘制梯度向量图和等高线图
|
||||
f = ff.create_quiver(xx1_, xx2_, V[0], V[1], arrow_scale=.1, scale=0.03) # 创建梯度向量图
|
||||
f_stream = ff.create_streamline(x1__, x2__, V[0], V[1], arrow_scale=.1) # 创建流线图
|
||||
trace1 = f.data[0] # 提取梯度向量的图层数据
|
||||
trace3 = f_stream.data[0] # 提取流线的图层数据
|
||||
trace2 = go.Contour(
|
||||
x=x1_array, # 等高线图的 x 轴为 x1 网格点
|
||||
y=x2_array, # 等高线图的 y 轴为 x2 网格点
|
||||
z=f_zz, # 等高线图的高度值为函数值
|
||||
showscale=False, # 禁用颜色条
|
||||
colorscale='RdYlBu_r') # 使用红黄蓝色带
|
||||
|
||||
data = [trace1, trace2] # 将梯度向量图和等高线图组合
|
||||
fig = go.FigureWidget(data) # 创建图形对象
|
||||
fig.update_layout(
|
||||
autosize=False, # 禁用自动调整尺寸
|
||||
width=800, # 设置图表宽度为 800 像素
|
||||
height=800) # 设置图表高度为 800 像素
|
||||
fig.add_hline(y=0, line_color='black') # 添加水平辅助线
|
||||
fig.add_vline(x=0, line_color='black') # 添加垂直辅助线
|
||||
fig.update_xaxes(range=[-2, 2]) # 设置 x 轴范围为 [-2, 2]
|
||||
fig.update_yaxes(range=[-2, 2]) # 设置 y 轴范围为 [-2, 2]
|
||||
fig.update_coloraxes(showscale=False) # 禁用颜色条
|
||||
st.plotly_chart(fig) # 在 Streamlit 页面中显示组合图形
|
||||
|
||||
# 绘制流线图和等高线图
|
||||
data2 = [trace3, trace2] # 将流线图和等高线图组合
|
||||
fig2 = go.FigureWidget(data2) # 创建图形对象
|
||||
fig2.update_layout(
|
||||
autosize=False, # 禁用自动调整尺寸
|
||||
width=800, # 设置图表宽度为 800 像素
|
||||
height=800) # 设置图表高度为 800 像素
|
||||
fig2.add_hline(y=0, line_color='black') # 添加水平辅助线
|
||||
fig2.add_vline(x=0, line_color='black') # 添加垂直辅助线
|
||||
fig2.update_xaxes(range=[-2, 2]) # 设置 x 轴范围为 [-2, 2]
|
||||
fig2.update_yaxes(range=[-2, 2]) # 设置 y 轴范围为 [-2, 2]
|
||||
fig2.update_coloraxes(showscale=False) # 禁用颜色条
|
||||
st.plotly_chart(fig2) # 在 Streamlit 页面中显示流线图和等高线图
|
||||
Reference in New Issue
Block a user