mirror of
https://github.com/Visualize-ML/Book4_Power-of-Matrix.git
synced 2026-05-05 06:03:45 +08:00
Delete Book4_Ch21_Python_Codes directory
This commit is contained in:
committed by
GitHub
parent
5dfa3e60f6
commit
c74b1e3cd2
@@ -1,26 +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_Ch21_01.py
|
||||
|
||||
import numpy as np
|
||||
|
||||
def is_pos_def(A):
|
||||
if np.array_equal(A, A.T):
|
||||
try:
|
||||
np.linalg.cholesky(A)
|
||||
return True
|
||||
except np.linalg.LinAlgError:
|
||||
return False
|
||||
else:
|
||||
return False
|
||||
|
||||
A = np.array([[1,0],
|
||||
[0,0]])
|
||||
|
||||
print(is_pos_def(A))
|
||||
@@ -1,100 +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_Ch21_02.py
|
||||
|
||||
import sympy
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
def mesh_circ(c1, c2, r, num):
|
||||
|
||||
theta = np.arange(0,2*np.pi+np.pi/num,np.pi/num)
|
||||
r = np.arange(0,r,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([[1.5, 0.5],
|
||||
[0.5, 1.5]])
|
||||
|
||||
x = np.array([[x1,x2]]).T
|
||||
|
||||
f_x = x.T@A@x
|
||||
f_x = f_x[0][0]
|
||||
print(f_x)
|
||||
|
||||
#take the gradient symbolically
|
||||
grad_f = [sympy.diff(f_x,var) for var in (x1,x2)]
|
||||
print(grad_f)
|
||||
|
||||
f_x_fcn = sympy.lambdify([x1,x2],f_x)
|
||||
|
||||
#turn into a bivariate lambda for numpy
|
||||
grad_fcn = sympy.lambdify([x1,x2],grad_f)
|
||||
|
||||
|
||||
xx1, xx2 = mesh_circ(0, 0, 4, 20)
|
||||
|
||||
# coarse mesh
|
||||
xx1_, xx2_ = mesh_circ(0, 0, 4, 10)
|
||||
V = grad_fcn(xx1_,xx2_)
|
||||
V_z = np.ones_like(V[1]);
|
||||
|
||||
if isinstance(V[1], int):
|
||||
V[1] = np.zeros_like(V[0])
|
||||
|
||||
elif isinstance(V[0], int):
|
||||
V[0] = np.zeros_like(V[1])
|
||||
|
||||
ff_x = f_x_fcn(xx1,xx2)
|
||||
|
||||
color_array = np.sqrt(V[0]**2 + V[1]**2)
|
||||
l_3D_vectors = np.sqrt(V[0]**2 + V[1]**2 + V_z**2)
|
||||
|
||||
# 3D visualization
|
||||
ax = plt.figure().add_subplot(projection='3d')
|
||||
ax.plot_wireframe(xx1, xx2, ff_x, rstride=1,
|
||||
cstride=1, color = [0.5,0.5,0.5],
|
||||
linewidth = 0.2)
|
||||
ax.contour3D(xx1, xx2, ff_x, 20, cmap = 'RdYlBu_r')
|
||||
|
||||
ax.xaxis.set_ticks([])
|
||||
ax.yaxis.set_ticks([])
|
||||
ax.zaxis.set_ticks([])
|
||||
plt.xlim(xx1.min(),xx1.max())
|
||||
plt.ylim(xx2.min(),xx2.max())
|
||||
ax.set_proj_type('ortho')
|
||||
ax.view_init(30, -125)
|
||||
ax.set_xlabel('$x_1$')
|
||||
ax.set_ylabel('$x_2$')
|
||||
ax.set_zlabel('$f(x_1,x_2)$')
|
||||
plt.tight_layout()
|
||||
|
||||
color_array = np.sqrt(V[0]**2 + V[1]**2)
|
||||
|
||||
# 2D visualization
|
||||
fig, ax = plt.subplots()
|
||||
plt.quiver (xx1_, xx2_, -V[0], -V[1],color_array,
|
||||
angles='xy', scale_units='xy',
|
||||
edgecolor='none', alpha=0.8,cmap = 'RdYlBu_r')
|
||||
|
||||
plt.contour(xx1, xx2, ff_x,20, 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$')
|
||||
plt.tight_layout()
|
||||
@@ -1,110 +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 streamlit as st
|
||||
import plotly.graph_objects as go
|
||||
import sympy
|
||||
import numpy as np
|
||||
|
||||
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}''')
|
||||
|
||||
st.latex(r'''
|
||||
f(x_1,x_2) = ax_1^2 + 2bx_1x_2 + cx_2^2
|
||||
''')
|
||||
|
||||
|
||||
a = st.slider('a',-2.0, 2.0, step = 0.1)
|
||||
b = st.slider('b',-2.0, 2.0, step = 0.1)
|
||||
c = st.slider('c',-2.0, 2.0, step = 0.1)
|
||||
|
||||
#%%
|
||||
|
||||
x1_ = np.linspace(-2, 2, 101)
|
||||
x2_ = np.linspace(-2, 2, 101)
|
||||
|
||||
xx1,xx2 = np.meshgrid(x1_, x2_)
|
||||
|
||||
#define symbolic vars, function
|
||||
x1,x2 = sympy.symbols('x1 x2')
|
||||
|
||||
A = np.array([[a, b],
|
||||
[b, c]])
|
||||
|
||||
D,V = np.linalg.eig(A)
|
||||
D = np.diag(D)
|
||||
|
||||
st.latex(r'''A = \begin{bmatrix}%s & %s\\%s & %s\end{bmatrix}''' %(a, b, b, c))
|
||||
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
|
||||
|
||||
f_x = a*x1**2 + 2*b*x1*x2 + c*x2**2
|
||||
|
||||
st.latex(r'''f(x_1,x_2) = ''')
|
||||
st.write(f_x)
|
||||
|
||||
f_x_fcn = sympy.lambdify([x1,x2],f_x)
|
||||
|
||||
ff_x = f_x_fcn(xx1,xx2)
|
||||
|
||||
#%% Plot 3D surface
|
||||
|
||||
fig_surface = go.Figure(go.Surface(
|
||||
x = x1_,
|
||||
y = x2_,
|
||||
z = ff_x,
|
||||
colorscale= 'RdYlBu_r'))
|
||||
|
||||
fig_surface.update_layout(
|
||||
autosize=False,
|
||||
width=500,
|
||||
height=500)
|
||||
st.plotly_chart(fig_surface)
|
||||
|
||||
#%% Plot 2D contour
|
||||
|
||||
fig_contour = go.Figure(
|
||||
go.Contour(
|
||||
z=ff_x,
|
||||
x=x1_,
|
||||
y=x2_,
|
||||
colorscale= 'RdYlBu_r'
|
||||
))
|
||||
|
||||
fig_contour.update_layout(
|
||||
autosize=False,
|
||||
width=500,
|
||||
height=500)
|
||||
|
||||
st.plotly_chart(fig_contour)
|
||||
|
||||
@@ -1,117 +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
|
||||
from sympy import lambdify, diff, exp, latex, simplify, symbols
|
||||
import numpy as np
|
||||
import plotly.figure_factory as ff
|
||||
import plotly.graph_objects as go
|
||||
import streamlit as st
|
||||
|
||||
x1,x2 = symbols('x1 x2')
|
||||
num = 301; # number of mesh grids
|
||||
x1_array = np.linspace(-3,3,num)
|
||||
x2_array = np.linspace(-3,3,num)
|
||||
xx1,xx2 = np.meshgrid(x1_array,x2_array)
|
||||
|
||||
# f_xy = x*exp(- x**2 - y**2);
|
||||
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_zz = f_x_fcn(xx1,xx2)
|
||||
|
||||
st.latex('f(x_1, x_2) = ' + latex(f_x))
|
||||
|
||||
#%% gradient
|
||||
|
||||
#take the gradient symbolically
|
||||
grad_f = [diff(f_x,var) for var in (x1,x2)]
|
||||
|
||||
#turn into a bivariate lambda for numpy
|
||||
grad_fcn = lambdify([x1,x2],grad_f)
|
||||
|
||||
x1__ = np.linspace(-3,3,40)
|
||||
x2__ = np.linspace(-3,3,40)
|
||||
# coarse mesh
|
||||
xx1_, xx2_ = np.meshgrid(x1__,x2__)
|
||||
V = grad_fcn(xx1_,xx2_)
|
||||
|
||||
#%%
|
||||
|
||||
#%% visualizations
|
||||
|
||||
fig_surface = go.Figure(go.Surface(
|
||||
x = x1_array,
|
||||
y = x2_array,
|
||||
z = f_zz,
|
||||
showscale=False,
|
||||
colorscale = 'RdYlBu_r'))
|
||||
fig_surface.update_layout(
|
||||
autosize=False,
|
||||
width =800,
|
||||
height=600)
|
||||
|
||||
st.plotly_chart(fig_surface)
|
||||
|
||||
#%% gradient vector plot
|
||||
|
||||
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,
|
||||
y = x2_array,
|
||||
z = f_zz,
|
||||
showscale=False,
|
||||
colorscale = 'RdYlBu_r')
|
||||
|
||||
data=[trace1,trace2]
|
||||
fig = go.FigureWidget(data)
|
||||
fig.update_layout(
|
||||
autosize=False,
|
||||
width =800,
|
||||
height=800)
|
||||
|
||||
|
||||
fig.add_hline(y=0, line_color = 'black')
|
||||
fig.add_vline(x=0, line_color = 'black')
|
||||
|
||||
fig.update_xaxes(range=[-2, 2])
|
||||
fig.update_yaxes(range=[-2, 2])
|
||||
fig.update_coloraxes(showscale=False)
|
||||
|
||||
st.plotly_chart(fig)
|
||||
|
||||
#%% streamlit plot
|
||||
|
||||
data2=[trace3,trace2]
|
||||
fig2 = go.FigureWidget(data2)
|
||||
fig2.update_layout(
|
||||
autosize=False,
|
||||
width =800,
|
||||
height=800)
|
||||
|
||||
|
||||
fig2.add_hline(y=0, line_color = 'black')
|
||||
fig2.add_vline(x=0, line_color = 'black')
|
||||
|
||||
fig2.update_xaxes(range=[-2, 2])
|
||||
fig2.update_yaxes(range=[-2, 2])
|
||||
fig2.update_coloraxes(showscale=False)
|
||||
|
||||
st.plotly_chart(fig2)
|
||||
Reference in New Issue
Block a user