mirror of
https://github.com/Visualize-ML/Book4_Power-of-Matrix.git
synced 2026-05-05 11:32:52 +08:00
Add files via upload
This commit is contained in:
committed by
GitHub
parent
f985536e82
commit
79be5dda7d
131
Book4_Ch07_Python_Codes/Streamlit_Bk4_Ch07_01.py
Normal file
131
Book4_Ch07_Python_Codes/Streamlit_Bk4_Ch07_01.py
Normal file
@@ -0,0 +1,131 @@
|
||||
|
||||
###############
|
||||
# Authored by Weisheng Jiang
|
||||
# Book 4 | From Basic Arithmetic to Machine Learning
|
||||
# Published and copyrighted by Tsinghua University Press
|
||||
# Beijing, China, 2025
|
||||
###############
|
||||
|
||||
import plotly.graph_objects as go
|
||||
import numpy as np
|
||||
from plotly.subplots import make_subplots
|
||||
import streamlit as st
|
||||
|
||||
# 定义一个函数,用于返回LaTeX格式的bmatrix
|
||||
def bmatrix(a):
|
||||
"""返回LaTeX bmatrix
|
||||
:a: numpy数组
|
||||
:returns: 作为字符串的LaTeX bmatrix
|
||||
"""
|
||||
if len(a.shape) > 2:
|
||||
raise ValueError('bmatrix最多只能显示二维数组')
|
||||
lines = str(a).replace('[', '').replace(']', '').splitlines()
|
||||
rv = [r'\begin{bmatrix}']
|
||||
rv += [' ' + ' & '.join(l.split()) + r'\\' for l in lines]
|
||||
rv += [r'\end{bmatrix}']
|
||||
return '\n'.join(rv)
|
||||
|
||||
# 设置网格的范围
|
||||
n = m = 20
|
||||
|
||||
# 创建一个具有两个子图的图表
|
||||
fig = make_subplots(rows=1, cols=2, horizontal_spacing=0.035)
|
||||
|
||||
# 初始化垂直线的x和y坐标列表
|
||||
xv = []
|
||||
yv = []
|
||||
|
||||
# 添加垂直线的坐标
|
||||
for k in range(-n, n + 1):
|
||||
xv.extend([k, k, np.nan])
|
||||
yv.extend([-m, m, np.nan])
|
||||
|
||||
# 设置线宽
|
||||
lw = 1
|
||||
# 添加垂直线到图表
|
||||
fig.add_trace(go.Scatter(x=xv, y=yv, mode="lines", line_width=lw,
|
||||
line_color='red'), 1, 1)
|
||||
|
||||
# 初始化水平线的x和y坐标列表
|
||||
xh = []
|
||||
yh = []
|
||||
# 添加水平线的坐标
|
||||
for k in range(-m, m + 1):
|
||||
xh.extend([-m, m, np.nan])
|
||||
yh.extend([k, k, np.nan])
|
||||
fig.add_trace(go.Scatter(x=xh, y=yh, mode="lines", line_width=lw,
|
||||
line_color='blue'), 1, 1)
|
||||
|
||||
# 在侧边栏中添加滑块控件
|
||||
with st.sidebar:
|
||||
# 显示LaTeX矩阵
|
||||
st.latex(r'''
|
||||
A = \begin{bmatrix}
|
||||
a & b\\
|
||||
c & d
|
||||
\end{bmatrix}''')
|
||||
|
||||
# 添加矩阵A的参数滑块
|
||||
a = st.slider('a', -2.0, 2.0, step=0.1, value=1.0)
|
||||
b = st.slider('b', -2.0, 2.0, step=0.1, value=0.0)
|
||||
c = st.slider('c', -2.0, 2.0, step=0.1, value=0.0)
|
||||
d = st.slider('d', -2.0, 2.0, step=0.1, value=1.0)
|
||||
|
||||
# 定义旋转角度
|
||||
theta = np.pi / 6
|
||||
# 定义矩阵A
|
||||
A = np.array([[a, b],
|
||||
[c, d]], dtype=float)
|
||||
|
||||
# 将垂直线的坐标转换为NumPy数组
|
||||
X = np.array(xv)
|
||||
Y = np.array(yv)
|
||||
|
||||
# 通过矩阵A变换垂直线的坐标
|
||||
Txvyv = A @ np.stack((X, Y))
|
||||
|
||||
# 将水平线的坐标转换为NumPy数组
|
||||
X = np.array(xh)
|
||||
Y = np.array(yh)
|
||||
|
||||
# 通过矩阵A变换水平线的坐标
|
||||
Txhyh = A @ np.stack((X, Y))
|
||||
|
||||
# 显示矩阵A的LaTeX格式
|
||||
st.latex(bmatrix(A))
|
||||
|
||||
# 提取矩阵A的列向量
|
||||
a1 = A[:, 0].reshape((-1, 1))
|
||||
a2 = A[:, 1].reshape((-1, 1))
|
||||
|
||||
# 显示列向量的LaTeX表达式
|
||||
st.latex(r'''
|
||||
a_1 = Ae_1 = ''' + bmatrix(A) +
|
||||
'e_1 = ' + bmatrix(a1)
|
||||
)
|
||||
|
||||
st.latex(r'''
|
||||
a_2 = Ae_2 = ''' + bmatrix(A) +
|
||||
'e_2 = ' + bmatrix(a2)
|
||||
)
|
||||
|
||||
# 添加变换后的垂直线到图表
|
||||
fig.add_trace(go.Scatter(x=Txvyv[0], y=Txvyv[1],
|
||||
mode="lines", line_width=lw,
|
||||
line_color='red'), 1, 2)
|
||||
|
||||
# 添加变换后的水平线到图表
|
||||
fig.add_trace(go.Scatter(x=Txhyh[0], y=Txhyh[1],
|
||||
mode="lines", line_width=lw,
|
||||
line_color='blue'), 1, 2)
|
||||
|
||||
# 设置x轴和y轴的范围
|
||||
fig.update_xaxes(range=[-4, 4])
|
||||
fig.update_yaxes(range=[-4, 4])
|
||||
|
||||
# 设置图表的布局和样式
|
||||
fig.update_layout(width=800, height=500, showlegend=False, template="none",
|
||||
plot_bgcolor="white", yaxis2_showgrid=False, xaxis2_showgrid=False)
|
||||
|
||||
# 在Streamlit应用中显示图表
|
||||
st.plotly_chart(fig)
|
||||
74
Book4_Ch07_Python_Codes/Streamlit_Bk4_Ch07_02.py
Normal file
74
Book4_Ch07_Python_Codes/Streamlit_Bk4_Ch07_02.py
Normal file
@@ -0,0 +1,74 @@
|
||||
|
||||
###############
|
||||
# Authored by Weisheng Jiang
|
||||
# Book 4 | From Basic Arithmetic to Machine Learning
|
||||
# Published and copyrighted by Tsinghua University Press
|
||||
# Beijing, China, 2025
|
||||
###############
|
||||
|
||||
import pandas as pd
|
||||
import plotly.graph_objs as go
|
||||
import streamlit as st
|
||||
import numpy as np
|
||||
|
||||
# 使用 Streamlit 的侧边栏设置滑块,用于选择每个维度的数据点数量
|
||||
with st.sidebar:
|
||||
num = st.slider('Number of points for each dimension', # 滑块标题
|
||||
max_value=20, # 最大值为20
|
||||
min_value=10, # 最小值为10
|
||||
step=1) # 步长为1
|
||||
|
||||
# 生成从0到1均匀分布的线性空间数据点
|
||||
x1 = np.linspace(0, 1, num)
|
||||
x2 = x1 # x2 和 x1 相同
|
||||
x3 = x1 # x3 和 x1 相同
|
||||
|
||||
# 生成三维网格,用于三维坐标的组合
|
||||
xx1, xx2, xx3 = np.meshgrid(x1, x2, x3)
|
||||
|
||||
# 将网格展开为一维数组
|
||||
x1_ = xx1.ravel()
|
||||
x2_ = xx2.ravel()
|
||||
x3_ = xx3.ravel()
|
||||
|
||||
# 创建一个 Pandas DataFrame,存储三维坐标和对应的RGB颜色分量
|
||||
df = pd.DataFrame({'X': x1_, # x 坐标
|
||||
'Y': x2_, # y 坐标
|
||||
'Z': x3_, # z 坐标
|
||||
'R': (x1_ * 256).round(), # R 通道值
|
||||
'G': (x2_ * 256).round(), # G 通道值
|
||||
'B': (x3_ * 256).round()}) # B 通道值
|
||||
|
||||
# 创建 3D 散点图的跟踪对象
|
||||
trace = go.Scatter3d(
|
||||
x=df.X, # x 轴数据
|
||||
y=df.Y, # y 轴数据
|
||||
z=df.Z, # z 轴数据
|
||||
mode='markers', # 数据点的显示模式为散点
|
||||
marker=dict(
|
||||
size=3, # 数据点的大小
|
||||
color=['rgb({},{},{})'.format(r, g, b) # 将 RGB 分量转换为颜色字符串
|
||||
for r, g, b in zip(df.R.values, df.G.values, df.B.values)],
|
||||
opacity=0.9, # 数据点的不透明度
|
||||
)
|
||||
)
|
||||
|
||||
# 将散点图添加到数据列表中
|
||||
data = [trace]
|
||||
|
||||
# 定义 3D 图的布局,包括坐标轴和边距
|
||||
layout = go.Layout(
|
||||
margin=dict(l=0, r=0, b=0, t=0), # 图形边距设置为0
|
||||
scene=dict(
|
||||
xaxis=dict(title='e_1'), # x 轴标题
|
||||
yaxis=dict(title='e_2'), # y 轴标题
|
||||
zaxis=dict(title='e_3'), # z 轴标题
|
||||
),
|
||||
)
|
||||
|
||||
# 创建包含数据和布局的图表对象
|
||||
fig = go.Figure(data=data, layout=layout)
|
||||
|
||||
# 使用 Streamlit 显示图表
|
||||
st.plotly_chart(fig)
|
||||
|
||||
Reference in New Issue
Block a user