Error in Python script “Expected 2D array, got 1D array instead:”?

后端 未结 9 709
执念已碎
执念已碎 2020-11-30 01:29

I\'m following this tutorial to make this ML prediction:

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

style.use(\"ggplot\         


        
相关标签:
9条回答
  • 2020-11-30 02:11

    Just insert the argument between a double square bracket:

    regressor.predict([[values]])

    that worked for me

    0 讨论(0)
  • 2020-11-30 02:13

    The problem is occurring when you run prediction on the array [0.58,0.76]. Fix the problem by reshaping it before you call 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
    
    0 讨论(0)
  • 2020-11-30 02:20

    I use the below approach.

    reg = linear_model.LinearRegression()
    reg.fit(df[['year']],df.income)
    
    reg.predict([[2136]])
    
    0 讨论(0)
提交回复
热议问题