> [!tldr] Spline Fitter > Fits a scatterplot smoother and returns its callable (instance of `scipy.interpolate.UnivariateSpline`). > > Related notes: [[Linear Smoothers]] ```python from scipy.interpolate import UnivariateSpline from statsmodels.nonparametric.smoothers_lowess import lowess def get_spline(feature, response, data: pd.DataFrame = None, s = None): if (data is not None) and isinstance(feature, str): feature = data[feature] if (data is not None) and isinstance(feature, str): response = data[response] smoothed_data = lowess(response, feature) _, unique_indices = np.unique(smoothed_data[:, 0], return_index=True) smoothed_data = smoothed_data[unique_indices, :] return UnivariateSpline(smoothed_data[:, 0], smoothed_data[:, 1], ext = "const", s = s) ``` ### Example ```python from sklearn.datasets import load_diabetes X, y = load_diabetes(return_X_y=True, as_frame=True) bmi_spline = get_spline(X.bmi, y, s = 0) ax = plt.subplot() plot_x = np.linspace(-0.1, 0.15, 100) sns.lineplot(x = plot_x, y = bmi_spline(plot_x), color = '#7d233f', linewidth = 3, ax = ax) sns.scatterplot(x = X['bmi'], y = y, color = '#aaaaaa', ax = ax) ``` ![[coeff.svg#invert|center]]