Delete Book4_Ch14_Python_Codes directory

This commit is contained in:
Iris Series: Visualize Math -- From Arithmetic Basics to Machine Learning
2025-02-01 17:02:08 +08:00
committed by GitHub
parent a722f54863
commit d9ca162c8e
5 changed files with 0 additions and 354 deletions

View File

@@ -1,22 +0,0 @@
###############
# Authored by Weisheng Jiang
# Book 4 | From Basic Arithmetic to Machine Learning
# Published and copyrighted by Tsinghua University Press
# Beijing, China, 2022
###############
# Bk4_Ch14_01.py
import numpy as np
A = np.matrix([[1.25, -0.75],
[-0.75, 1.25]])
LAMBDA, V = np.linalg.eig(A)
B = V@np.diag(np.sqrt(LAMBDA))@np.linalg.inv(V)
A_reproduced = B@B
print(A_reproduced)

View File

@@ -1,53 +0,0 @@
###############
# Authored by Weisheng Jiang
# Book 4 | From Basic Arithmetic to Machine Learning
# Published and copyrighted by Tsinghua University Press
# Beijing, China, 2022
###############
# Bk4_Ch14_02.py
import numpy as np
import matplotlib.pyplot as plt
# transition matrix
T = np.matrix([[0.7, 0.2],
[0.3, 0.8]])
# steady state
sstate = np.linalg.eig(T)[1][:,1]
sstate = sstate/sstate.sum()
print(sstate)
# initial states
initial_x_array = np.array([[1, 0, 0.5, 0.4], # Chicken
[0, 1, 0.5, 0.6]]) # Rabbit
num_iterations = 10;
for i in np.arange(0,4):
initial_x = initial_x_array[:,i][:, None]
x_i = np.zeros_like(initial_x)
x_i = initial_x
X = initial_x.T;
# matrix power through iterations
for x in np.arange(0,num_iterations):
x_i = T@x_i;
X = np.concatenate([X, x_i.T],axis = 0)
fig, ax = plt.subplots()
itr = np.arange(0,num_iterations+1);
plt.plot(itr,X[:,0],marker = 'x',color = (1,0,0))
plt.plot(itr,X[:,1],marker = 'x',color = (0,0.6,1))
ax.grid(linestyle='--', linewidth=0.25, color=[0.5,0.5,0.5])
ax.set_xlim(0, num_iterations)
ax.set_ylim(0, 1)
ax.set_xlabel('Iteration, k')
ax.set_ylabel('State')

View File

@@ -1,106 +0,0 @@
###############
# Authored by Weisheng Jiang
# Book 4 | From Basic Arithmetic to Machine Learning
# Published and copyrighted by Tsinghua University Press
# Beijing, China, 2022
###############
# Bk4_Ch14_03.py
import sympy
import numpy as np
import matplotlib.pyplot as plt
from numpy import linalg as L
def mesh_circ(c1, c2, r, num):
theta = np.linspace(0, 2*np.pi, num)
r = np.linspace(0,r, num)
theta,r = np.meshgrid(theta,r)
xx1 = np.cos(theta)*r + c1
xx2 = np.sin(theta)*r + c2
return xx1, xx2
#define symbolic vars, function
x1,x2 = sympy.symbols('x1 x2')
A = np.array([[0.5, -0.5],
[-0.5, 0.5]])
Lambda, V = L.eig(A)
x = np.array([[x1,x2]]).T
f_x = x.T@A@x
f_x = f_x[0][0]
f_x_fcn = sympy.lambdify([x1,x2],f_x)
xx1, xx2 = mesh_circ(0, 0, 1, 50)
ff_x = f_x_fcn(xx1,xx2)
if Lambda[1] > 0:
levels = np.linspace(0,Lambda[0],21)
else:
levels = np.linspace(Lambda[1],Lambda[0],21)
t = np.linspace(0,np.pi*2,100)
# 2D visualization
fig, ax = plt.subplots()
ax.plot(np.cos(t), np.sin(t), color = 'k')
cs = plt.contourf(xx1, xx2, ff_x,
levels=levels, cmap = 'RdYlBu_r')
plt.show()
ax.set_aspect('equal')
ax.xaxis.set_ticks([])
ax.yaxis.set_ticks([])
ax.set_xlabel('$x_1$')
ax.set_ylabel('$x_2$')
ax.set_xlim(-1,1)
ax.set_ylim(-1,1)
clb = fig.colorbar(cs, ax=ax)
clb.set_ticks(levels)
#%% 3D surface of f(x1,x2)
x1_ = np.linspace(-1.2,1.2,31)
x2_ = np.linspace(-1.2,1.2,31)
xx1_fine, xx2_fine = np.meshgrid(x1_,x2_)
ff_x_fine = f_x_fcn(xx1_fine,xx2_fine)
f_circle = f_x_fcn(np.cos(t), np.sin(t))
# 3D visualization
fig, ax = plt.subplots()
ax = plt.axes(projection='3d')
ax.plot(np.cos(t), np.sin(t), f_circle, color = 'k')
# circle projected to f(x1,x2)
ax.plot_wireframe(xx1_fine,xx2_fine,ff_x_fine,
color = [0.8,0.8,0.8],
linewidth = 0.25)
ax.contour3D(xx1_fine,xx2_fine,ff_x_fine,15,
cmap = 'RdYlBu_r')
ax.view_init(elev=30, azim=60)
ax.xaxis.set_ticks([])
ax.yaxis.set_ticks([])
ax.zaxis.set_ticks([])
ax.set_xlim(xx1_fine.min(),xx1_fine.max())
ax.set_ylim(xx2_fine.min(),xx2_fine.max())
plt.tight_layout()
ax.set_proj_type('ortho')
plt.show()

View File

@@ -1,54 +0,0 @@
###############
# Authored by Weisheng Jiang
# Book 4 | From Basic Arithmetic to Machine Learning
# Published and copyrighted by Tsinghua University Press
# Beijing, China, 2022
###############
import numpy as np
import streamlit as st
import time
# transition matrix
A = np.matrix([[0.7, 0.2],
[0.3, 0.8]])
with st.sidebar:
pi_0_chicken = st.slider('Ratio of chicken:',
0.0, 1.0, step = 0.1)
pi_0_rabbit = 1 - pi_0_chicken
st.write('Ratio of rabbit: ' + str(round(pi_0_rabbit,1)))
num_iterations = st.slider('Number of nights:',
20,100,step = 5)
progress_bar = st.sidebar.progress(0)
status_text = st.sidebar.empty()
last_rows = np.array([[pi_0_chicken, pi_0_rabbit]])
# st.write(last_rows) # row vector
chart = st.line_chart(last_rows)
for i in range(1, num_iterations):
last_status = last_rows[-1,:]
# st.write(last_status)
new_rows = last_status@A.T
percent = (i + 1)*100/num_iterations
status_text.text("%i%% Complete" % percent)
chart.add_rows(new_rows)
progress_bar.progress(i)
last_rows = new_rows
time.sleep(0.1)
progress_bar.empty()

View File

@@ -1,119 +0,0 @@
###############
# Authored by Weisheng Jiang
# Book 4 | From Basic Arithmetic to Machine Learning
# Published and copyrighted by Tsinghua University Press
# Beijing, China, 2022
###############
import plotly.graph_objects as go
import streamlit as st
import numpy as np
import plotly.express as px
import pandas as pd
import sympy
def bmatrix(a):
"""Returns a LaTeX bmatrix
:a: numpy array
:returns: LaTeX bmatrix as a string
"""
if len(a.shape) > 2:
raise ValueError('bmatrix can at most display two dimensions')
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)
with st.sidebar:
st.latex(r'''
A = \begin{bmatrix}
a & b\\
b & c
\end{bmatrix}''')
a = st.slider('a',-2.0, 2.0, step = 0.05, value = 1.0)
b = st.slider('b',-2.0, 2.0, step = 0.05, value = 0.0)
c = st.slider('c',-2.0, 2.0, step = 0.05, value = 1.0)
#%%
theta_array = np.linspace(0, 2*np.pi, 36)
X = np.column_stack((np.cos(theta_array),
np.sin(theta_array)))
# st.write(X)
A = np.array([[a, b],
[b, c]])
st.latex(r'''z^Tz = 1''')
st.latex(r'''x = Az''')
st.latex('A =' + bmatrix(A))
X_ = X@A
#define symbolic vars, function
x1,x2 = sympy.symbols('x1 x2')
y1,y2 = sympy.symbols('y1 y2')
x = np.array([[x1,x2]]).T
y = np.array([[y1,y2]]).T
Q = np.linalg.inv(A@A.T)
D,V = np.linalg.eig(Q)
D = np.diag(D)
st.latex(r'Q = \left( AA^T\right)^{-1} = ' + bmatrix(np.round(Q, 3)))
st.latex(r'''Q = V \Lambda V^{T}''')
st.latex(bmatrix(np.around(Q, decimals=3)) + '=' +
bmatrix(np.around(V, decimals=3)) + '@' +
bmatrix(np.around(D, decimals=3)) + '@' +
bmatrix(np.around(V.T, decimals=3)))
f_x = x.T@np.round(Q, 3)@x
f_y = y.T@np.round(D, 3)@y
from sympy import *
st.write('The formula of the ellipse:')
st.latex(latex(simplify(f_x[0][0])) + ' = 1')
st.write('The formula of the transformed ellipse:')
st.latex(latex(simplify(f_y[0][0])) + ' = 1')
#%%
color_array = np.linspace(0,1,len(X))
# st.write(color_array)
X_c = np.column_stack((X_, color_array))
df = pd.DataFrame(X_c, columns=['x1','x2', 'color'])
#%% Scatter
fig = px.scatter(df,
x="x1",
y="x2",
color='color',
color_continuous_scale=px.colors.sequential.Rainbow)
fig.update_layout(
autosize=False,
width=500,
height=500)
fig.add_hline(y=0, line_color = 'black')
fig.add_vline(x=0, line_color = 'black')
fig.update_layout(coloraxis_showscale=False)
fig.update_xaxes(range=[-3, 3])
fig.update_yaxes(range=[-3, 3])
st.plotly_chart(fig)