mirror of
https://github.com/Visualize-ML/Book4_Power-of-Matrix.git
synced 2026-02-03 02:24:03 +08:00
Add files via upload
This commit is contained in:
@@ -9,8 +9,8 @@
|
||||
# Bk4_Ch4_15.py
|
||||
|
||||
import numpy as np
|
||||
A = np.array([[3, 1],
|
||||
[2, 4]])
|
||||
A = np.array([[4, 2],
|
||||
[1, 3]])
|
||||
|
||||
# calculate determinant of A
|
||||
det_A = np.linalg.det(A)
|
||||
|
||||
129
Book4_Ch04_Python_Codes/Streamlit_Bk4_Ch4_16.py
Normal file
129
Book4_Ch04_Python_Codes/Streamlit_Bk4_Ch4_16.py
Normal file
@@ -0,0 +1,129 @@
|
||||
|
||||
###############
|
||||
# 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 numpy as np
|
||||
from plotly.subplots import make_subplots
|
||||
import streamlit as st
|
||||
|
||||
|
||||
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)
|
||||
|
||||
n = m = 20
|
||||
|
||||
fig = make_subplots(rows=1, cols=2, horizontal_spacing=0.035)
|
||||
|
||||
xv = []
|
||||
yv = []
|
||||
|
||||
for k in range(-n, n+1):
|
||||
xv.extend([k, k, np.nan])
|
||||
yv.extend([-m, m, np.nan])
|
||||
lw= 1 #line_width
|
||||
fig.add_trace(go.Scatter(x=xv, y=yv, mode="lines", line_width=lw,
|
||||
line_color = 'red'), 1, 1)
|
||||
#set up the lists of horizontal line x and y-end coordinates
|
||||
|
||||
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:
|
||||
|
||||
st.latex(r'''
|
||||
A = \begin{bmatrix}
|
||||
a & b\\
|
||||
c & d
|
||||
\end{bmatrix}''')
|
||||
|
||||
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('c',-2.0, 2.0, step = 0.1, value = 1.0)
|
||||
|
||||
theta = np.pi/6
|
||||
A = np.array([[a, b],
|
||||
[c, d]], dtype=float)
|
||||
|
||||
#get only the coordinates from -3 to 3
|
||||
# X = np.array(xv[6:-6])
|
||||
# Y = np.array(yv[6:-6])
|
||||
|
||||
X = np.array(xv)
|
||||
Y = np.array(yv)
|
||||
|
||||
# transform by T the vector of coordinates [x, y]^T where the vector runs over the columns of np.stack((X, Y))
|
||||
Txvyv = A@np.stack((X, Y)) #transform by T the vertical lines
|
||||
|
||||
# X = np.array(xh[6:-6])
|
||||
# Y = np.array(yh[6:-6])
|
||||
|
||||
X = np.array(xh)
|
||||
Y = np.array(yh)
|
||||
|
||||
Txhyh = A@np.stack((X, Y))# #transform by T the horizontal lines
|
||||
|
||||
st.latex(r'A = ' + bmatrix(A))
|
||||
|
||||
a1 = A[:,0].reshape((-1, 1))
|
||||
a2 = A[:,1].reshape((-1, 1))
|
||||
|
||||
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)
|
||||
)
|
||||
|
||||
st.latex(r'\begin{vmatrix} A \end{vmatrix} = ' + str(np.linalg.det(A)))
|
||||
square_x = np.array([0, 1, 1, 0])
|
||||
square_y = np.array([0, 0, 1, 1])
|
||||
square_array = np.stack((square_x, square_y))
|
||||
|
||||
fig.add_trace(go.Scatter(x=square_x, y=square_y,
|
||||
fill="toself", line_color='orange'), 1, 1)
|
||||
|
||||
A_times_square_array = A@square_array
|
||||
|
||||
fig.add_trace(go.Scatter(x=A_times_square_array[0,:],
|
||||
y=A_times_square_array[1,:],
|
||||
fill="toself", line_color='orange'), 1, 2)
|
||||
|
||||
fig.add_trace(go.Scatter(x=Txvyv[0], y=Txvyv[1],
|
||||
mode="lines", line_width=lw,
|
||||
line_color = 'blue'), 1, 2)
|
||||
|
||||
fig.add_trace(go.Scatter(x=Txhyh[0], y=Txhyh[1],
|
||||
mode="lines", line_width=lw,
|
||||
line_color = 'red'), 1, 2)
|
||||
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)
|
||||
|
||||
st.plotly_chart(fig)
|
||||
Binary file not shown.
@@ -1,61 +1,116 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Created on Mon Sep 12 21:19:47 2022
|
||||
|
||||
@author: Work
|
||||
"""
|
||||
###############
|
||||
# Authored by Weisheng Jiang
|
||||
# Book 4 | From Basic Arithmetic to Machine Learning
|
||||
# Published and copyrighted by Tsinghua University Press
|
||||
# Beijing, China, 2022
|
||||
###############
|
||||
|
||||
import pandas as pd
|
||||
import plotly.graph_objs as go
|
||||
import streamlit as st
|
||||
import plotly.graph_objects as go
|
||||
import numpy as np
|
||||
from plotly.subplots import make_subplots
|
||||
import streamlit as st
|
||||
|
||||
|
||||
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)
|
||||
|
||||
n = m = 20
|
||||
|
||||
fig = make_subplots(rows=1, cols=2, horizontal_spacing=0.035)
|
||||
|
||||
xv = []
|
||||
yv = []
|
||||
|
||||
for k in range(-n, n+1):
|
||||
xv.extend([k, k, np.nan])
|
||||
yv.extend([-m, m, np.nan])
|
||||
lw= 1 #line_width
|
||||
fig.add_trace(go.Scatter(x=xv, y=yv, mode="lines", line_width=lw,
|
||||
line_color = 'red'), 1, 1)
|
||||
#set up the lists of horizontal line x and y-end coordinates
|
||||
|
||||
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:
|
||||
num = st.slider('Number of points for each dimension',
|
||||
max_value = 20,
|
||||
min_value = 10,
|
||||
step = 1)
|
||||
|
||||
x1 = np.linspace(0,1,num)
|
||||
x2 = x1
|
||||
x3 = x1
|
||||
st.latex(r'''
|
||||
A = \begin{bmatrix}
|
||||
a & b\\
|
||||
c & d
|
||||
\end{bmatrix}''')
|
||||
|
||||
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('c',-2.0, 2.0, step = 0.1, value = 1.0)
|
||||
|
||||
xx1,xx2,xx3 = np.meshgrid(x1,x2,x3)
|
||||
theta = np.pi/6
|
||||
A = np.array([[a, b],
|
||||
[c, d]], dtype=float)
|
||||
|
||||
x1_ = xx1.ravel()
|
||||
x2_ = xx2.ravel()
|
||||
x3_ = xx3.ravel()
|
||||
#get only the coordinates from -3 to 3
|
||||
# X = np.array(xv[6:-6])
|
||||
# Y = np.array(yv[6:-6])
|
||||
|
||||
#%%
|
||||
df = pd.DataFrame({'X': x1_,
|
||||
'Y': x2_,
|
||||
'Z': x3_,
|
||||
'R': (x1_*256).round(),
|
||||
'G': (x2_*256).round(),
|
||||
'B': (x3_*256).round()})
|
||||
X = np.array(xv)
|
||||
Y = np.array(yv)
|
||||
|
||||
trace = go.Scatter3d(x=df.X,
|
||||
y=df.Y,
|
||||
z=df.Z,
|
||||
mode='markers',
|
||||
marker=dict(size=3,
|
||||
color=['rgb({},{},{})'.format(r,g,b)
|
||||
for r,g,b in
|
||||
zip(df.R.values, df.G.values, df.B.values)],
|
||||
opacity=0.9,))
|
||||
# transform by T the vector of coordinates [x, y]^T where the vector runs over the columns of np.stack((X, Y))
|
||||
Txvyv = A@np.stack((X, Y)) #transform by T the vertical lines
|
||||
|
||||
data = [trace]
|
||||
# X = np.array(xh[6:-6])
|
||||
# Y = np.array(yh[6:-6])
|
||||
|
||||
layout = go.Layout(margin=dict(l=0,
|
||||
r=0,
|
||||
b=0,
|
||||
t=0),
|
||||
scene = dict(
|
||||
xaxis = dict(title='e_1'),
|
||||
yaxis = dict(title='e_2'),
|
||||
zaxis = dict(title='e_3'),),
|
||||
)
|
||||
X = np.array(xh)
|
||||
Y = np.array(yh)
|
||||
|
||||
fig = go.Figure(data=data, layout=layout)
|
||||
Txhyh = A@np.stack((X, Y))# #transform by T the horizontal lines
|
||||
|
||||
st.plotly_chart(fig)
|
||||
st.latex(bmatrix(A))
|
||||
|
||||
a1 = A[:,0].reshape((-1, 1))
|
||||
a2 = A[:,1].reshape((-1, 1))
|
||||
|
||||
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 = 'blue'), 1, 2)
|
||||
|
||||
fig.add_trace(go.Scatter(x=Txhyh[0], y=Txhyh[1],
|
||||
mode="lines", line_width=lw,
|
||||
line_color = 'red'), 1, 2)
|
||||
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)
|
||||
|
||||
st.plotly_chart(fig)
|
||||
61
Book4_Ch07_Python_Codes/Streamlit_Bk4_Ch7_02.py
Normal file
61
Book4_Ch07_Python_Codes/Streamlit_Bk4_Ch7_02.py
Normal file
@@ -0,0 +1,61 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Created on Mon Sep 12 21:19:47 2022
|
||||
|
||||
@author: Work
|
||||
"""
|
||||
|
||||
import pandas as pd
|
||||
import plotly.graph_objs as go
|
||||
import streamlit as st
|
||||
import numpy as np
|
||||
|
||||
with st.sidebar:
|
||||
num = st.slider('Number of points for each dimension',
|
||||
max_value = 20,
|
||||
min_value = 10,
|
||||
step = 1)
|
||||
|
||||
x1 = np.linspace(0,1,num)
|
||||
x2 = x1
|
||||
x3 = x1
|
||||
|
||||
xx1,xx2,xx3 = np.meshgrid(x1,x2,x3)
|
||||
|
||||
x1_ = xx1.ravel()
|
||||
x2_ = xx2.ravel()
|
||||
x3_ = xx3.ravel()
|
||||
|
||||
#%%
|
||||
df = pd.DataFrame({'X': x1_,
|
||||
'Y': x2_,
|
||||
'Z': x3_,
|
||||
'R': (x1_*256).round(),
|
||||
'G': (x2_*256).round(),
|
||||
'B': (x3_*256).round()})
|
||||
|
||||
trace = go.Scatter3d(x=df.X,
|
||||
y=df.Y,
|
||||
z=df.Z,
|
||||
mode='markers',
|
||||
marker=dict(size=3,
|
||||
color=['rgb({},{},{})'.format(r,g,b)
|
||||
for r,g,b in
|
||||
zip(df.R.values, df.G.values, df.B.values)],
|
||||
opacity=0.9,))
|
||||
|
||||
data = [trace]
|
||||
|
||||
layout = go.Layout(margin=dict(l=0,
|
||||
r=0,
|
||||
b=0,
|
||||
t=0),
|
||||
scene = dict(
|
||||
xaxis = dict(title='e_1'),
|
||||
yaxis = dict(title='e_2'),
|
||||
zaxis = dict(title='e_3'),),
|
||||
)
|
||||
|
||||
fig = go.Figure(data=data, layout=layout)
|
||||
|
||||
st.plotly_chart(fig)
|
||||
Binary file not shown.
131
Book4_Ch08_Python_Codes/Streamlit_Bk4_Ch8_03.py
Normal file
131
Book4_Ch08_Python_Codes/Streamlit_Bk4_Ch8_03.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, 2022
|
||||
###############
|
||||
|
||||
import plotly.graph_objects as go
|
||||
import numpy as np
|
||||
from plotly.subplots import make_subplots
|
||||
import streamlit as st
|
||||
|
||||
|
||||
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)
|
||||
|
||||
n = m = 20
|
||||
|
||||
fig = make_subplots(rows=1, cols=2, horizontal_spacing=0.035)
|
||||
|
||||
xv = []
|
||||
yv = []
|
||||
|
||||
for k in range(-n, n+1):
|
||||
xv.extend([k, k, np.nan])
|
||||
yv.extend([-m, m, np.nan])
|
||||
lw= 1 #line_width
|
||||
fig.add_trace(go.Scatter(x=xv, y=yv, mode="lines", line_width=lw,
|
||||
line_color = 'red'), 1, 1)
|
||||
#set up the lists of horizontal line x and y-end coordinates
|
||||
|
||||
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:
|
||||
|
||||
st.latex(r'''
|
||||
A = \begin{bmatrix}
|
||||
a & b\\
|
||||
c & d
|
||||
\end{bmatrix}''')
|
||||
|
||||
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('c',-2.0, 2.0, step = 0.1, value = 1.0)
|
||||
|
||||
theta = np.pi/6
|
||||
A = np.array([[a, b],
|
||||
[c, d]], dtype=float)
|
||||
|
||||
#get only the coordinates from -3 to 3
|
||||
# X = np.array(xv[6:-6])
|
||||
# Y = np.array(yv[6:-6])
|
||||
|
||||
X = np.array(xv)
|
||||
Y = np.array(yv)
|
||||
|
||||
# transform by T the vector of coordinates [x, y]^T where the vector runs over the columns of np.stack((X, Y))
|
||||
Txvyv = A@np.stack((X, Y)) #transform by T the vertical lines
|
||||
|
||||
# X = np.array(xh[6:-6])
|
||||
# Y = np.array(yh[6:-6])
|
||||
|
||||
X = np.array(xh)
|
||||
Y = np.array(yh)
|
||||
|
||||
Txhyh = A@np.stack((X, Y))# #transform by T the horizontal lines
|
||||
|
||||
st.latex(r'A = ' + bmatrix(A))
|
||||
|
||||
a1 = A[:,0].reshape((-1, 1))
|
||||
a2 = A[:,1].reshape((-1, 1))
|
||||
|
||||
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)
|
||||
)
|
||||
|
||||
st.latex(r'\begin{vmatrix} A \end{vmatrix} = ' + str(np.linalg.det(A)))
|
||||
|
||||
theta_array = np.linspace(0, 2*np.pi, 101)
|
||||
circle_x = np.cos(theta_array)
|
||||
circle_y = np.sin(theta_array)
|
||||
circle_array = np.stack((circle_x, circle_y))
|
||||
|
||||
fig.add_trace(go.Scatter(x=circle_x, y=circle_y,
|
||||
fill="toself", line_color='orange'), 1, 1)
|
||||
|
||||
A_times_circle_array = A@circle_array
|
||||
|
||||
fig.add_trace(go.Scatter(x=A_times_circle_array[0,:],
|
||||
y=A_times_circle_array[1,:],
|
||||
fill="toself", line_color='orange'), 1, 2)
|
||||
|
||||
fig.add_trace(go.Scatter(x=Txvyv[0], y=Txvyv[1],
|
||||
mode="lines", line_width=lw,
|
||||
line_color = 'blue'), 1, 2)
|
||||
|
||||
fig.add_trace(go.Scatter(x=Txhyh[0], y=Txhyh[1],
|
||||
mode="lines", line_width=lw,
|
||||
line_color = 'red'), 1, 2)
|
||||
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)
|
||||
|
||||
st.plotly_chart(fig)
|
||||
Binary file not shown.
122
Book4_Ch10_Python_Codes/Streamlit_Bk4_Ch10_01.py
Normal file
122
Book4_Ch10_Python_Codes/Streamlit_Bk4_Ch10_01.py
Normal file
@@ -0,0 +1,122 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Created on Tue Sep 27 19:46:17 2022
|
||||
|
||||
@author: Work
|
||||
"""
|
||||
|
||||
|
||||
###############
|
||||
# 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.express as px
|
||||
|
||||
import seaborn as sns
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
import pandas as pd
|
||||
from sklearn.datasets import load_iris
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
# A copy from Seaborn
|
||||
iris = load_iris()
|
||||
X = iris.data
|
||||
y = iris.target
|
||||
|
||||
feature_names = ['Sepal length, x1','Sepal width, x2',
|
||||
'Petal length, x3','Petal width, x4']
|
||||
|
||||
# Convert X array to dataframe
|
||||
X_df = pd.DataFrame(X, columns=feature_names)
|
||||
|
||||
#%% Original data, X
|
||||
|
||||
X = X_df.to_numpy();
|
||||
|
||||
# Gram matrix, G and orthogonal basis V
|
||||
|
||||
G = X.T@X
|
||||
D, V = np.linalg.eig(G)
|
||||
np.set_printoptions(suppress=True)
|
||||
D = np.diag(D)
|
||||
st.latex(r'G = X^T X = ' + bmatrix(G))
|
||||
st.latex(r'G = V \Lambda V^T')
|
||||
|
||||
st.latex(r'G = ' +
|
||||
bmatrix(np.round(V,2)) + '@' +
|
||||
bmatrix(np.round(D,2)) + '@' +
|
||||
bmatrix(np.round(V.T,2)))
|
||||
|
||||
#%%
|
||||
|
||||
Z = X@V
|
||||
|
||||
df = pd.DataFrame(Z, columns = ['PC1','PC2','PC3','PC4'])
|
||||
|
||||
mapping_rule = {0: 'setosa', 1: 'versicolor', 2: 'virginica'}
|
||||
df.insert(4, "species", y)
|
||||
df['species'] = df['species'].map(mapping_rule)
|
||||
|
||||
#%%
|
||||
features = df.columns.to_list()[:-1]
|
||||
with st.sidebar:
|
||||
st.write('2D scatter plot')
|
||||
x_feature = st.radio('Horizontal axis',
|
||||
features)
|
||||
y_feature = st.radio('Vertical axis',
|
||||
features)
|
||||
|
||||
# Heatmap
|
||||
with st.expander('Heatmap'):
|
||||
fig_1 = px.imshow(df.iloc[:,0:4],
|
||||
color_continuous_scale='RdYlBu_r')
|
||||
st.plotly_chart(fig_1)
|
||||
|
||||
# 2D scatter plot
|
||||
with st.expander('2D scatter plot'):
|
||||
fig_2 = px.scatter(df, x=x_feature, y=y_feature, color="species")
|
||||
st.plotly_chart(fig_2)
|
||||
|
||||
# 3D scatter plot
|
||||
with st.expander('3D scatter plot'):
|
||||
fig_3 = px.scatter_3d(df,
|
||||
x='PC1',
|
||||
y='PC2',
|
||||
z='PC3',
|
||||
color='species')
|
||||
st.plotly_chart(fig_3)
|
||||
|
||||
# Pairwise scatter plot
|
||||
with st.expander('Pairwise scatter plot'):
|
||||
fig_4 = px.scatter_matrix(df,
|
||||
dimensions=["PC1",
|
||||
"PC2",
|
||||
"PC3",
|
||||
"PC4"],
|
||||
color="species")
|
||||
st.plotly_chart(fig_4)
|
||||
|
||||
|
||||
|
||||
|
||||
Binary file not shown.
90
Book4_Ch13_Python_Codes/Streamlit_Bk4_Ch13_04.py
Normal file
90
Book4_Ch13_Python_Codes/Streamlit_Bk4_Ch13_04.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, 2022
|
||||
###############
|
||||
|
||||
|
||||
import streamlit as st
|
||||
import numpy as np
|
||||
import plotly.express as px
|
||||
import pandas as pd
|
||||
|
||||
|
||||
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\\
|
||||
c & d
|
||||
\end{bmatrix}''')
|
||||
|
||||
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)
|
||||
|
||||
#%%
|
||||
|
||||
x1_ = np.linspace(-1, 1, 11)
|
||||
x2_ = np.linspace(-1, 1, 11)
|
||||
|
||||
xx1,xx2 = np.meshgrid(x1_, x2_)
|
||||
|
||||
X = np.column_stack((xx1.flatten(), xx2.flatten()))
|
||||
|
||||
# st.write(X)
|
||||
A = np.array([[a, b],
|
||||
[c, d]])
|
||||
|
||||
X = X@A
|
||||
|
||||
# st.write(len(X))
|
||||
#%%
|
||||
color_array = np.linspace(0,1,len(X))
|
||||
# st.write(color_array)
|
||||
X = np.column_stack((X, color_array))
|
||||
df = pd.DataFrame(X, columns=['z1','z2', 'color'])
|
||||
|
||||
#%% Scatter
|
||||
|
||||
st.latex(bmatrix(A))
|
||||
|
||||
fig = px.scatter(df,
|
||||
x="z1",
|
||||
y="z2",
|
||||
color='color',
|
||||
color_continuous_scale = '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_xaxes(range=[-3, 3])
|
||||
fig.update_yaxes(range=[-3, 3])
|
||||
fig.update_coloraxes(showscale=False)
|
||||
|
||||
st.plotly_chart(fig)
|
||||
|
||||
|
||||
|
||||
Binary file not shown.
119
Book4_Ch14_Python_Codes/Streamlit_Bk4_Ch14_04.py
Normal file
119
Book4_Ch14_Python_Codes/Streamlit_Bk4_Ch14_04.py
Normal file
@@ -0,0 +1,119 @@
|
||||
|
||||
###############
|
||||
# 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)
|
||||
|
||||
|
||||
|
||||
Binary file not shown.
Reference in New Issue
Block a user