这是我的猫狗图像识别代码:
import numpy as np
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
filename= 'catdog_datasets.txt'
filename1= 'catdog_datasets.txt'
raw_data = open(filename, 'rt')
raw_data1 = open(filename1, 'rt')
#data = numpy.loadtxt(raw_data,dtype='object',delimiter=":")
features_data = np.loadtxt(raw_data,dtype='object',delimiter=":",usecols=(0))
labels_data = np.loadtxt(raw_data1,dtype='object',delimiter=":",usecols=(1))
print(features_data.shape)
print(labels_data.shape)
#print(labels_data)
#print(features_data)
X_train, X_test, y_train, y_test = train_test_split(features_data,labels_data,test_size=0.2)
print (y_train.shape)
print (y_test.shape)
print (X_train.shape)
print (X_test.shape)
clf = SVC(kernel='linear',C=1.0)
clf.fit(X_train,y_train)
predictions = clf.predict(X_test)
catdog_datsets.txt包含每个猫和狗500张图像的HOG特征向量,标签分配为0,用于cat& 1为dog.文件格式为: 0.270150 0.070257 0.040265 0.037243 0.013678:0
注意:特征向量的大小约为1765 * 1只是为了问我给出的大小为5 * 1的问题。问题是特征向量是一个字符串,我想将它转换为数组浮点数提供给SVM。这是我得到的错误:
clf.fit(X_train,y_train)
File "C:\Users\TIKA-OPT790-04\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sklearn\svm\base.py", line 149, in fit
X, y = check_X_y(X, y, dtype=np.float64, order='C', accept_sparse='csr')
File "C:\Users\TIKA-OPT790-04\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sklearn\utils\validation.py", line 573, in check_X_y
ensure_min_features, warn_on_dtype, estimator)
File "C:\Users\TIKA-OPT790-04\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sklearn\utils\validation.py", line 433, in check_array
array = np.array(array, dtype=dtype, order=order, copy=copy)
ValueError: could not convert string to float:0.270150 0.070257 0.040265 0.037243 0.013678
答案 0 :(得分:0)
错误是因为您的文件包含以下行:
f1 f2 f3 f4 ............................................f1565 :0
如您所见,要素由空格分隔,整个要素向量通过冒号(:)与标签分隔。
现在,在您的代码中,您使用的是delimiter=":"
,因此您的features_data
每行只包含一个值,如下所示:
f1 f2 f3 f4 ............................................f1565
您需要将其拆分为多个功能才能正确使用它。
现在numpy.loadtxt
不支持多个分隔符,因此您必须使用其他选项或解决方法。
完成当前程序后,将features_data
拆分:
features_data = np.array([l.strip().split(' ') for l in features_data])
推荐:使用pandas.read_csv()
:
all_data = pd.read_csv(raw_data, sep=':|\s+', engine='python', header=None)
# All but last column
features_data = all_data.iloc[:,0:-1]
#last column
labels_data = all_data.iloc[:,-1]