Config Router

  • Google Sheets
  • CCNA Online training
    • CCNA
  • CISCO Lab Guides
    • CCNA Security Lab Manual With Solutions
    • CCNP Route Lab Manual with Solutions
    • CCNP Switch Lab Manual with Solutions
  • Juniper
  • Linux
  • DevOps Tutorials
  • Python Array
You are here: Home / Error in Python script “Expected 2D array, got 1D array instead:”?

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

August 1, 2021 by James Palmer

You are just supposed to provide the predict method with the same 2D array, but with one value that you want to process (or more). In short, you can just replace
[0.58,0.76]

With
[[0.58,0.76]]

And it should work.
EDIT: This answer became popular so I thought I’d add a little more explanation about ML. The short version: we can only use predict on data that is of the same dimensionality as the training data (X) was.
In the example in question, we give the computer a bunch of rows in X (with 2 values each) and we show it the correct responses in y. When we want to predict using new values, our program expects the same – a bunch of rows. Even if we want to do it to just one row (with two values), that row has to be part of another array.

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

Related

Filed Under: Uncategorized

Recent Posts

  • How do I give user access to Jenkins?
  • What is docker volume command?
  • What is the date format in Unix?
  • What is the difference between ARG and ENV Docker?
  • What is rsync command Linux?
  • How to Add Music to Snapchat 2021 Android? | How to Search, Add, Share Songs on Snapchat Story?
  • How to Enable Snapchat Notifications for Android & iPhone? | Steps to Turn on Snapchat Bitmoji Notification
  • Easy Methods to Fix Snapchat Camera Not Working Black Screen Issue | Reasons & Troubleshooting Tips to Solve Snapchat Camera Problems
  • Detailed Procedure for How to Update Snapchat on iOS 14 for Free
  • What is Snapchat Spotlight Feature? How to Make a Spotlight on Snapchat?
  • Snapchat Hack Tutorial 2021: Can I hack a Snapchat Account without them knowing?

Copyright © 2025 · News Pro Theme on Genesis Framework · WordPress · Log in