VMLS: Least squares
The data for this plot comes from Introduction to Applied Linear Algebra – Vectors, Matrices, and Least Squares (Boyd and Vandenberghe, 2018).
#| '!! shinylive warning !!': |
#| shinylive does not work in self-contained HTML documents.
#| Please set `embed-resources: false` in your metadata.
#| standalone: true
#| viewerHeight: 600
from shiny import App, render, ui, reactive
import numpy as np
import matplotlib.pyplot as plt
import plotly.graph_objects as go
from shinywidgets import render_widget, output_widget
def Z_func(x, y):
return (2*x - 1)**2 + (-x + y)**2 + (2*y + 1)**2
app_ui = ui.page_fluid(
ui.layout_columns(
output_widget('curve'),
output_widget('contourplot')
),
)
def server(input, output, session):
@render_widget
def curve():
X_lin = np.arange(-1, 1.5, 0.05)
Y_lin = np.arange(-1.5, 1, 0.05)
X, Y = np.meshgrid(X_lin, Y_lin)
Z = Z_func(X, Y)
fig = go.Figure(data=[go.Surface(x=X, y=Y, z=Z, name='Curve', colorscale='Turbo')])
fig = fig.update_layout(
autosize=True,
height=600,
margin=dict(l=65, r=50, b=65, t=90),
scene = dict(xaxis = dict(range=[-1, 1.5], title=dict(text='x_1')),
yaxis = dict(range=[-1.5, 1], title=dict(text='x_2')),
zaxis = dict(range=[np.min(Z) - (np.max(Z) - np.min(Z)) * 0.05, np.max(Z) + (np.max(Z) - np.min(Z)) * 0.05], title=dict(text=''))
)
)
return fig
# ========================================================================
@render_widget
def contourplot():
X_lin = np.arange(-1, 1.5, 0.05)
Y_lin = np.arange(-1.5, 1, 0.05)
X, Y = np.meshgrid(X_lin, Y_lin)
Z = Z_func(X, Y)
fig = go.Figure(data =
[go.Contour(
z=Z,
x=X_lin,
y=Y_lin,
colorscale='Turbo',
contours=dict(
start=0.666666,
end=22.666666,
size=1,
),
)])
fig = fig.update_layout(
autosize=True,
height=600,
margin=dict(l=65, r=50, b=65, t=90),
scene = dict(xaxis = dict(range=[-1, 1.5], title=dict(text='x_1')),
yaxis = dict(range=[-1.5, 1], title=dict(text='x_2')),
zaxis = dict(range=[np.min(Z) - (np.max(Z) - np.min(Z)) * 0.05, np.max(Z) + (np.max(Z) - np.min(Z)) * 0.05], title=dict(text=''))
)
)
return fig
# ========================================================================
app = App(app_ui, server)
References
Boyd, S. P., & Vandenberghe, L. (2018). Introduction to Applied Linear Algebra : Vectors, Matrices, and Least Squares (First edition.). Cambridge University Press.