我正在使用svm为uni进行机器学习项目。我正在尝试标记训练有素的数据,但在最后一行出现错误。消息是:
ValueError: Expected 2D array, got 1D array instead:
array = [].
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."
代码:
#to the newly created training type folder
trainingType_files = './training_type'
#create empty data holders for the training data
data = []
train_label = []
#training
for i in letter_string:
cur_letter = i
cur_folder = trainingType_files + cur_letter + '/'
for j in glob.glob(cur_folder + '*.png'):
cur_folder = j
image = imreead(cur_folder, 1)
image = imresize(image, (200,200))
#hog applied here so that they have the same dimensions
hog_features = hog(image, orientations=12, pixels_per_cell=(16, 16), cells_per_block=(1, 1))
hog_feature = hog_feature.reshape(-1,1)
data.append(hog_features)
train_label.append(cur_letter)
print ('labelled ' + cur_letter)
#Perform training
clf = LinearSVC(dual = False, verbose = 1)
clf.fit(data, train_label)
我了解问题是我正在传递一维数组,但使用array.reshape无法正常工作。有解决方案吗?
您的数组为空,错误中指出:
array = [ ].
似乎您的for循环是以不执行内部for
主体的方式设计的。
这是与您的设置配合使用的代码示例:
from skimage.feature import hog
from sklearn.svm import LinearSVC
import numpy as np
X = np.ones((10, 50, 50, 3))
Y = np.random.randint(0,2,10)
data = []
for example in X:
hog_features = hog(example, orientations=12, pixels_per_cell=(16, 16), cells_per_block=(1, 1))
data.append(hog_features)
clf = LinearSVC(dual = False, verbose = 1)
clf.fit(data, Y)
尝试用X
替换[]
以重现您的错误。