У меня есть код из книги Python для сложных задачь Commented out IPython magic to ensure…
- User
У меня есть код из книги Python для сложных задачь
Commented out IPython magic to ensure Python compatibility.
%matplotlib inline
import matplotlib.pyplot as plt import seaborn as sns import numpy as np
sns.set_theme()
rng = np.random.RandomState(1) x = 10 * rng.rand(50) y = 2 * x - 1 + rng.randn(50) plt.scatter(x, y); plt.show()
from sklearn.linear_model import LinearRegression model = LinearRegression(fit_intercept=True)
model.fit(x[:, np.newaxis], y)
xfit = np.linspace(0, 10, 1000) yfit = model.predict(xfit[:, np.newaxis])
plt.scatter(x, y) plt.plot(xfit, yfit); plt.show()
print("Model slope: ", model.coef_[0]) print("Model intercept:", model.intercept_)
rng = np.random.RandomState(1) X = 10 * rng.rand(100, 3) y = 0.5 + np.dot(X, [1.5, -2., 1.])
model.fit(X, y) print(model.intercept_) print(model.coef_)
from sklearn.preprocessing import PolynomialFeatures x = np.array([2, 3, 4]) poly = PolynomialFeatures(3, include_bias=False) poly.fit_transform(x[:, None])
from sklearn.pipeline import make_pipeline poly_model = make_pipeline(PolynomialFeatures(7), LinearRegression())
rng = np.random.RandomState(1) x = 10 * rng.rand(50) y = np.sin(x) + 0.1 * rng.randn(50)
poly_model.fit(x[:, np.newaxis], y) yfit = poly_model.predict(xfit[:, np.newaxis])
plt.scatter(x, y) plt.plot(xfit, yfit); plt.show()
from sklearn.base import BaseEstimator, TransformerMixin
class GaussianFeatures(BaseEstimator, TransformerMixin): def init(self, N, width_factor=2.0): self.N = N self.width_factor = width_factor
code@staticmethod def _gauss_basis(x, y, width, axis=None): arg = (x - y) / width return np.exp(-0.5 * np.sum(arg ** 2, axis)) def fit(self, X, y=None): # create N centers spread along the data range self.centers_ = np.linspace(X.min(), X.max(), self.N) self.width_ = self.width_factor * (self.centers_[1] - self.centers_[0]) return self def transform(self, X): return self._gauss_basis(X[:, :, np.newaxis], self.centers_, self.width_, axis=1)gauss_model = make_pipeline(GaussianFeatures(20), LinearRegression())
gauss_model.fit(x[:, np.newaxis], y) yfit = gauss_model.predict(xfit[:, np.newaxis])
- Assistant
Для выполнения заданий, которые вы упомянули, нужно внести изменения в код, чтобы исследовать зависимость от гиперпараметров и провести поиск по сетке.
- User
Для первого задания
ValueError Traceback (most recent call last) in <cell line: 33>() 31 # Ridge 32 plt.subplot(1, 2, 1) ---> 33 plot_alpha_dependence(Ridge, 30, "Ridge Regression: alpha dependence") 34 35 # Lasso
4 frames /usr/local/lib/python3.10/dist-packages/matplotlib/axes/_base.py in _plot_args(self, tup, kwargs, return_kwargs, ambiguous_fmt_datakey) 528 if n_datasets > 1 and not cbook.is_scalar_or_string(label): 529 if len(label) != n_datasets: --> 530 raise ValueError(f"label must be scalar or have the same " 531 f"length as the input data, but found " 532 f"{len(label)} for {n_datasets} datasets.")
ValueError: label must be scalar or have the same length as the input data, but found 1 for 30 datasets.
- Assistant
Ошибка, которую вы получили, связана с передачей параметра
labelв функциюplt.plot(). В текущей реализации функция ожидает, что количество элементов вlabelбудет совпадать с количеством кривых, которые строятся. Давайте изменим код, чтобы корректно отобразить графики.Заменим использование
label=[f'N={N}']на корректное:python