【发布时间】:2018-09-08 19:13:48
【问题描述】:
以下代码模拟机器学习、线性回归过程。
它旨在允许用户在 Jupyter 笔记本中手动和直观地进行回归,以更好地了解线性回归过程。
函数的第一部分 (x,y) 生成一个图来执行回归。
下一部分 (a,b) 生成要玩的线,用于模拟回归。
我希望能够在不重新生成散点图的情况下更改斜率滑块。
任何指导都会非常有帮助和欢迎。 :-)
import numpy as np
import ipywidgets as widgets
from ipywidgets import interactive
import matplotlib.pyplot as plt
def scatterplt(rand=3, num_points=20, slope=1):
x = np.linspace(3, 9, num_points)
y = np.linspace(3, 9, num_points)
#add randomness to scatter
pcent_rand = rand
pcent_decimal = pcent_rand/100
x = [n*np.random.uniform(low=1-pcent_decimal, high=1+ pcent_decimal) for n in x]
y = [n*np.random.uniform(low=1-pcent_decimal, high=1+ pcent_decimal) for n in y]
#plot regression line
a = np.linspace(0, 9, num_points)
b = [(slope * n) for n in a]
#format & plot the figure
plt.figure(figsize=(9, 9), dpi=80)
plt.ylim(ymax=max(x)+1)
plt.xlim(xmax=max(x)+1)
plt.scatter(x, y)
plt.plot(a, b)
plt.show()
#WIDGETS
interactive_plot = interactive(scatterplt,
rand = widgets.FloatSlider(
value=3,
min=0,
max=50,
step=3,
description='Randomness:', num_points=(10, 50, 5)
),
num_points = widgets.IntSlider(
value=20,
min=10,
max=50,
step=5,
description='Number of points:'
),
slope=widgets.FloatSlider(
value=1,
min=-1,
max=5,
step=0.1,
description='Slope'
)
)
interactive_plot
【问题讨论】:
-
线和散点图都在同一个图中。因此,如果该图中的任何内容发生变化,则需要重新绘制。从这个意义上说,您想要实现的目标并不太清楚。
-
我希望能够在不改变散点图的情况下改变斜线。但是如果不在函数中使用 plt.plot() ,我无法让它重绘。如果我使用坐标轴,它不会画任何东西
标签: python numpy matplotlib jupyter ipywidgets