我正在用Jupyter Notebook写一本书的简单代码。它是Gaussian
基本函数的代码,但我收到了 TypeError消息 TypeError: _gauss_basis() got multiple values for argument 'axis'
。
下面是我的代码和结果:
from sklearn.base import BaseEstimator, TransformerMixin
import numpy as np
import matplotlib.pyplot as plt
class GaussianFeatures(BaseEstimator, TransformerMixin):
def __init__(self, N, width_factor= 2):
self.N= N
self.width_factor= width_factor
def _gauss_basis(x, y, width, axis= None):
arg= (x- y)/ width
return np.exp(-.5 * np.sum(arg ** 2, axis))
def fit(self, X, y= None):
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])
plt.scatter(x, y)
plt.plot(xfit, yfit)
plt.xlim(0, 10)
TypeError Traceback (most recent call last)
<ipython-input-105-ce19f63fb83d> in <module>
20
21 gauss_model= make_pipeline(GaussianFeatures(20),LinearRegression())
---> 22 gauss_model.fit(x[:, np.newaxis], y)
23 yfit= gauss_model.predict(xfit[:, np.newaxis])
24
~/.local/lib/python3.5/site-packages/sklearn/pipeline.py in fit(self, X, y, **fit_params)
263 This estimator
264
--> 265 Xt, fit_params = self._fit(X, y, **fit_params)
266 if self._final_estimator is not None:
267 self._final_estimator.fit(Xt, y, **fit_params)
~/.local/lib/python3.5/site-packages/sklearn/pipeline.py in _fit(self, X, y, **fit_params)
228 Xt, fitted_transformer = fit_transform_one_cached(
229 cloned_transformer, Xt, y, None,
--> 230 **fit_params_steps[name])
231 # Replace the transformer of the step with the fitted
232 # transformer. This is necessary when loading the transformer
~/.local/lib/python3.5/site-packages/sklearn/externals/joblib/memory.py in __call__(self, *args, **kwargs)
340
341 def __call__(self, *args, **kwargs):
--> 342 return self.func(*args, **kwargs)
343
344 def call_and_shelve(self, *args, **kwargs):
~/.local/lib/python3.5/site-packages/sklearn/pipeline.py in _fit_transform_one(transformer, X, y, weight, **fit_params)
612 def _fit_transform_one(transformer, X, y, weight, **fit_params):
613 if hasattr(transformer, 'fit_transform'):
--> 614 res = transformer.fit_transform(X, y, **fit_params)
615 else:
616 res = transformer.fit(X, y, **fit_params).transform(X)
~/.local/lib/python3.5/site-packages/sklearn/base.py in fit_transform(self, X, y, **fit_params)
465 else:
466 # fit method of arity 2 (supervised transformation)
--> 467 return self.fit(X, y, **fit_params).transform(X)
468
469
<ipython-input-105-ce19f63fb83d> in transform(self, X)
17
18 def transform(self, X):
---> 19 return self._gauss_basis(X[:,:, np.newaxis], self.centers_, self.width_, axis= 1)
20
21 gauss_model= make_pipeline(GaussianFeatures(20),LinearRegression())
TypeError: _gauss_basis() got multiple values for argument 'axis'