![](/img/trans.png)
[英]ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 1 is different from 3)
[英]ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 1 is different from 2)
第一次尝试适应 Python。 我有一组测量值,需要对提供的数据进行非线性拟合。 拟合应该是二次多项式。 这是代码和错误:
from numpy import *
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
x = array([[0.121644, 0.243288, 0.486576, 0.60822, 0.729864, 0.851508]]).reshape(-1,1)
y = array([[0.95, 1.02, 1.21, 1.35, 1.47, 1.61]]).reshape(-1,1)
poly = PolynomialFeatures(degree= 2, include_bias=False)
x_poly = poly.fit_transform(x)
reg = LinearRegression()
reg.fit(x,y)
x_val= linspace(0.121644, 0.851508, 100).reshape(-1,1)
x_vp= poly.transform(x_val)
y_val = reg.predict(x_vp)
plt.scatter(x,y)
plt.plot(x_val, y_val)
ValueError Traceback (most recent call last)
<ipython-input-49-38d844be643a> in <module>
9
10
---> 11 y_val = reg.predict(x_vp)
12
13 plt.scatter(x,y)
~\anaconda3\lib\site-packages\sklearn\linear_model\_base.py in predict(self, X)
223 Returns predicted values.
224 """
--> 225 return self._decision_function(X)
226
227 _preprocess_data = staticmethod(_preprocess_data)
~\anaconda3\lib\site-packages\sklearn\linear_model\_base.py in _decision_function(self, X)
207 X = check_array(X, accept_sparse=['csr', 'csc', 'coo'])
208 return safe_sparse_dot(X, self.coef_.T,
--> 209 dense_output=True) + self.intercept_
210
211 def predict(self, X):
~\anaconda3\lib\site-packages\sklearn\utils\extmath.py in safe_sparse_dot(a, b, dense_output)
149 ret = np.dot(a, b)
150 else:
--> 151 ret = a @ b
152
153 if (sparse.issparse(a) and sparse.issparse(b)
ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 1 is different from 2)
我知道问题出在 x 和 x_val 的尺寸上,但我不知道如何解决。
我会发表评论,但还可以。
poly = PolynomialFeatures(degree= 2, include_bias=False)
x_poly = poly.fit_transform(x)
reg = LinearRegression()
reg.fit(x,y)
您制作了设计矩阵 x_poly,但在 x 上拟合了模态。 然后您尝试预测新数据的转换设计矩阵,因此形状会有所不同。
如果我没记错的话,应该是
...
reg.fit(x_poly,y)
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.