Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python sklearn不';即使在重塑后也无法识别我的阵列为2d?_Python_Python 3.x_Numpy_Scikit Learn - Fatal编程技术网

Python sklearn不';即使在重塑后也无法识别我的阵列为2d?

Python sklearn不';即使在重塑后也无法识别我的阵列为2d?,python,python-3.x,numpy,scikit-learn,Python,Python 3.x,Numpy,Scikit Learn,我正在尝试运行以下代码。我知道我需要改变数组的形状,使其适合线性回归模型。然而,在我重塑它们之后,它仍然会给出一个错误,即我的数组是标量数组。我也试过至少两次,但都没有成功 from sklearn.linear_model import LinearRegression from sklearn.datasets import load_boston boston = load_boston() x = np.array(boston.data[:,5]) y = boston.target

我正在尝试运行以下代码。我知道我需要改变数组的形状,使其适合线性回归模型。然而,在我重塑它们之后,它仍然会给出一个错误,即我的数组是标量数组。我也试过至少两次,但都没有成功

from sklearn.linear_model import LinearRegression
from sklearn.datasets import load_boston
boston = load_boston()

x = np.array(boston.data[:,5])
y = boston.target

x=np.array(x).reshape(-1,1)
y=np.array(y).reshape(-1,1)

lr = LinearRegression(fit_intercept=True)
lr.fit(x,y)

fig,ax= plt.subplots()

ax.set_xlabel("Average number of rooms(RM)")
ax.set_ylabel("House Price")

xmin = x.min()
xmax = x.max()

ax.plot([xmin,xmax],
       [lr.predict(xmin),lr.predict(xmax)],
        "-",
       lw=2,color="#f9a602")
ax.scatter(x,y,s=2)


> ValueError                                Traceback (most recent call last)
<ipython-input-6-8c6977f43703> in <module>
      7 xmax = xmax
      8 ax.plot([xmin,xmax],
----> 9        [lr.predict(xmin), lr.predict(xmax)],
     10         "-",
     11        lw=2,color="#f9a602")

~\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\linear_model\base.py in predict(self, X)
    211             Returns predicted values.
    212         """
--> 213         return self._decision_function(X)
    214 
    215     _preprocess_data = staticmethod(_preprocess_data)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\linear_model\base.py in _decision_function(self, X)
    194         check_is_fitted(self, "coef_")
    195 
--> 196         X = check_array(X, accept_sparse=['csr', 'csc', 'coo'])
    197         return safe_sparse_dot(X, self.coef_.T,
    198                                dense_output=True) + self.intercept_

~\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\utils\validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator)
    543                     "Reshape your data either using array.reshape(-1, 1) if "
    544                     "your data has a single feature or array.reshape(1, -1) "
--> 545                     "if it contains a single sample.".format(array))
    546             # If input is 1D raise error
    547             if array.ndim == 1:

ValueError: Expected 2D array, got scalar array instead:
array=<built-in method min of numpy.ndarray object at 0x0000019960BF9CB0>.
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

从sklearn.linear\u模型导入线性回归
从sklearn.dataset导入加载
波士顿=加载波士顿()
x=np.array(boston.data[:,5])
y=boston.target
x=np.数组(x).重塑(-1,1)
y=np.数组(y).重塑(-1,1)
lr=线性回归(拟合截距=真)
lr.配合(x,y)
图,ax=plt.子批次()
ax.set_xlabel(“平均房间数(RM)”)
ax.set_ylabel(“房价”)
xmin=x.min()
xmax=x.max()
ax.绘图([xmin,xmax],
[lr.predict(xmin),lr.predict(xmax)],
"-",
lw=2,颜色=“#f9a602”)
最大散射(x,y,s=2)
>ValueError回溯(最近一次调用上次)
在里面
7 xmax=xmax
8最大曲线图([xmin,xmax],
---->9[lr.predict(xmin),lr.predict(xmax)],
10         "-",
11 lw=2,颜色=“#f9a602”)
预测中的~\AppData\Local\Continuum\anaconda3\lib\site packages\sklearn\linear\u model\base.py(self,X)
211返回预测值。
212         """
-->213返回自判定函数(X)
214
215预处理数据=静态方法(预处理数据)
~\AppData\Local\Continuum\anaconda3\lib\site packages\sklearn\linear\u model\base.py in\u decision\u函数(self,X)
194已安装止回阀(自,“coef”)
195
-->196 X=检查数组(X,接受稀疏=['csr','csc','coo'])
197返回安全稀疏点(X,self.coef.T,
198密集_输出=真)+自截距_
检查数组中的~\AppData\Local\Continuum\anaconda3\lib\site packages\sklearn\utils\validation.py(数组、接受稀疏、接受大稀疏、数据类型、顺序、复制、强制所有有限、确保二维、允许nd、确保最小样本、确保最小特征、警告数据类型、估计器)
543“使用数组重塑数据。如果需要重塑(-1,1)
544“您的数据只有一个特征或数组。重塑(1,-1)”
-->545“如果它包含单个样本。”。格式(数组))
546#如果输入为1D上升错误
547如果array.ndim==1:
ValueError:应为2D数组,但改为标量数组:
数组=。
使用数组重塑数据。如果数据具有单个特征或数组,则重塑(-1,1)。如果数据包含单个样本,则重塑(1,-1)。

使用挤压找到此解决方案

from sklearn.linear_model import LinearRegression
lr = LinearRegression(fit_intercept=True)


xmin
xmax = x.max()
xmax = xmax.reshape(-1,1)
xmin = x.min()



lr.fit(x,y)
xmin =xmin.reshape(-1,1)
print(xmin.shape)
print(xmin)
s = lr.predict(xmin)

s= np.squeeze(s)



r = lr.predict(xmax)

r = np.squeeze(r)

xmax = np.squeeze(xmax)

xmin = np.squeeze(xmin)


lr.fit(x,y)

fig,ax= plt.subplots()
ax.set_xlabel("Average number of rooms(RM)")
ax.set_ylabel("House Price")
xmin = xmin
xmax = xmax
ax.plot([xmin,xmax],
       [s, r],
        "-",
       lw=2,color="#f9a602")
ax.scatter(x,y,s=2)

抱歉,我可能用词太差了。回归有效,但绘图无效。即使
x
是2D,
xmin
xmax
都是0D。我需要重塑lr.predict(xmin)和xmax。谢谢你的帮助。我一定会告诉Jay我们遇到了麻烦。