Home > Back-end >  Splitting data in x_train and x_test gives error: Too many values to unpack expected 2
Splitting data in x_train and x_test gives error: Too many values to unpack expected 2

Time:11-02

Whenever I try to split the data into x_train and x_test I get the following error:

Too many values to unpack expected 2

My code:

import glob
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.image as mpimg

for img in glob.glob("F:/Pics/Training_data/*.jpg"):
  k_images = mpimg.imread(img)
  plt.show()
  plt.imshow(k_images)

  (x_train, _), (x_test, _) = k_images

Here k_images is of np.ndarray type and contains 10 images.

Please tell me what should I change to avoid the error at train, test split of k_images.

CodePudding user response:

assuming the shape of the ndarray is (10,x,y,c) if you don't care about randomness you can just use pythons list notations

x = np.arange(10).reshape((10, 1,1,1))
x_train = x[:8]
x_test = x[8:]
x_train.shape
(8, 1, 1, 1)
x_test.shape
(2, 1, 1, 1)

or just use sklearn train_test_split function which is way better and adds randomness to the selection process...

https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html

CodePudding user response:

I think what you are looking for is

x_train, x_test = np.array_split(k_images, 2, 2)

Documentation found here.

If you're looking into ML I suggest checking out sklearn, for example sklearn.model_selection.train_test_split would help you a lot with this, documentation found here.

  • Related