forked from Visualize-ML/Book1_Python-For-Beginners
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathBk1_Ch36_03.py
85 lines (68 loc) · 2.87 KB
/
Bk1_Ch36_03.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
###############
# Authored by Weisheng Jiang
# Book 1 | From Basic Arithmetic to Machine Learning
# Published and copyrighted by Tsinghua University Press
# Beijing, China, 2023
###############
import plotly.graph_objects as go
import numpy as np
import streamlit as st
from scipy.stats import multivariate_normal
st.latex(r'''{\displaystyle f_{\mathbf {X} }(x_{1},\ldots ,x_{k})=
{\frac {\exp \left(-{\frac {1}{2}}
({\mathbf {x} }-{\boldsymbol {\mu }})
^{\mathrm {T} }{\boldsymbol {\Sigma }}^{-1}
({\mathbf {x} }-{\boldsymbol {\mu }})\right)}
{\sqrt {(2\pi )^{k}|{\boldsymbol {\Sigma }}|}}}}''')
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)
# x1_array = np.linspace(-3,3,301)
# x2_array = np.linspace(-3,3,301)
# x3_array = np.linspace(-3,3,301)
xxx1,xxx2,xxx3 = np.mgrid[-3:3:0.2,-3:3:0.2,-3:3:0.2]
with st.sidebar:
st.title('Trivariate Gaussian Distribution')
sigma_1 = st.slider('sigma_1', min_value=0.5, max_value=3.0, value=1.0, step=0.1)
sigma_2 = st.slider('sigma_2', min_value=0.5, max_value=3.0, value=1.0, step=0.1)
sigma_3 = st.slider('sigma_3', min_value=0.5, max_value=3.0, value=1.0, step=0.1)
rho_1_2 = st.slider('rho_1_2', min_value=-0.95, max_value=0.95, value=0.0, step=0.05)
rho_1_3 = st.slider('rho_1_3', min_value=-0.95, max_value=0.95, value=0.0, step=0.05)
rho_2_3 = st.slider('rho_2_3', min_value=-0.95, max_value=0.95, value=0.0, step=0.05)
SIGMA = np.array([[sigma_1**2, rho_1_2*sigma_1*sigma_2, rho_1_3*sigma_1*sigma_3],
[rho_1_2*sigma_1*sigma_2, sigma_2**2, rho_2_3*sigma_2*sigma_3],
[rho_1_3*sigma_1*sigma_3, rho_2_3*sigma_2*sigma_3, sigma_3**2]])
st.latex(r'\Sigma = ' + bmatrix(SIGMA))
MU = np.array([0, 0, 0])
# st.write(xxx1.shape)
pos = np.dstack((xxx1.ravel(),xxx2.ravel(),xxx3.ravel()))
# st.write(pos.shape)
rv = multivariate_normal(MU, SIGMA)
PDF = rv.pdf(pos)
fig = go.Figure(data=go.Volume(
x=xxx1.flatten(),
y=xxx2.flatten(),
z=xxx3.flatten(),
value=PDF.flatten(),
isomin=0,
isomax=PDF.max(),
colorscale = 'RdYlBu_r',
opacity=0.1,
surface_count=11,
))
fig.update_layout(scene = dict(
xaxis_title=r'x_1',
yaxis_title=r'x_2',
zaxis_title=r'x_3'),
width=1000,
margin=dict(r=20, b=10, l=10, t=10))
st.plotly_chart(fig, theme=None, use_container_width=True)