programing

Python 스크립트 "예상 된 2D 배열, 대신 1D 배열이 있습니다."오류가 발생합니까?

itsource 2021. 1. 18. 08:00
반응형

Python 스크립트 "예상 된 2D 배열, 대신 1D 배열이 있습니다."오류가 발생합니까?


이 ML 예측을 위해이 자습서따르고 있습니다 .

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style

style.use("ggplot")
from sklearn import svm

x = [1, 5, 1.5, 8, 1, 9]
y = [2, 8, 1.8, 8, 0.6, 11]

plt.scatter(x,y)
plt.show()

X = np.array([[1,2],
             [5,8],
             [1.5,1.8],
             [8,8],
             [1,0.6],
             [9,11]])

y = [0,1,0,1,0,1]
X.reshape(1, -1)

clf = svm.SVC(kernel='linear', C = 1.0)
clf.fit(X,y)

print(clf.predict([0.58,0.76]))

Python 3.6을 사용하고 있는데 "예상 된 2D 배열, 대신 1D 배열이 있습니다."라는 오류가 발생합니다. 스크립트가 이전 버전 용이라고 생각하지만 3.6 버전으로 변환하는 방법을 모릅니다.

이미 시도해보십시오 :

X.reshape(1, -1)

predict동일한 2D 배열로 메서드 를 제공해야 하지만 처리하려는 값이 하나 이상 있습니다. 간단히 말해

[0.58,0.76]

[[0.58,0.76]]

그리고 그것은 작동합니다


어레이에서 예측을 실행할 때 문제가 발생합니다 [0.58,0.76]. 전화하기 전에 모양을 변경하여 문제를 해결하십시오 predict().

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style

style.use("ggplot")
from sklearn import svm

x = [1, 5, 1.5, 8, 1, 9]
y = [2, 8, 1.8, 8, 0.6, 11]

plt.scatter(x,y)
plt.show()

X = np.array([[1,2],
             [5,8],
             [1.5,1.8],
             [8,8],
             [1,0.6],
             [9,11]])

y = [0,1,0,1,0,1]

clf = svm.SVC(kernel='linear', C = 1.0)
clf.fit(X,y)

test = np.array([0.58, 0.76])
print test       # Produces: [ 0.58  0.76]
print test.shape # Produces: (2,) meaning 2 rows, 1 col

test = test.reshape(1, -1)
print test       # Produces: [[ 0.58  0.76]]
print test.shape # Produces (1, 2) meaning 1 row, 2 cols

print(clf.predict(test)) # Produces [0], as expected

예측하려는 인스턴스의 데이터 유형이 panda.Series객체 라는 점을 제외하고는 동일한 문제에 직면했습니다 .

Well I just needed to predict one input instance. I took it from a slice of my data.

df = pd.DataFrame(list(BiogasPlant.objects.all()))
test = df.iloc[-1:]       # sliced it here

In this case, you'll need to convert it into a 1-D array and then reshape it.

 test2d = test.values.reshape(1,-1)

From the docs, values will convert Series into a numpy array.


I use the below approach.

reg = linear_model.LinearRegression()
reg.fit(df[['year']],df.income)

reg.predict([[2136]])

I faced the same problem. You just have to make it an array and moreover you have to put double squared brackets to make it a single element of the 2D array as first bracket initializes the array and the second makes it an element of that array.

So simply replace the last statement by:

print(clf.predict(np.array[[0.58,0.76]]))

With one feature my Dataframe list converts to a Series. I had to convert it back to a Dataframe list and it worked.

if type(X) is Series:
    X = X.to_frame()

I was facing the same issue earlier but I have somehow found the solution, You can try reg.predict([[3300]]).

The API used to allow scalar value but now you need to give a 2D array.


Just insert the argument between a double square bracket:

regressor.predict([[values]])

that worked for me


The X and Y matrix of Independent Variable and Dependent Variable respectively to DataFrame from int64 Type so that it gets converted from 1D array to 2D array.. i.e X=pd.DataFrame(X) and Y=pd.dataFrame(Y) where pd is of pandas class in python. and thus feature scaling in-turn doesn't lead to any error!

ReferenceURL : https://stackoverflow.com/questions/45554008/error-in-python-script-expected-2d-array-got-1d-array-instead

반응형