![](/img/trans.png)
[英]TypeError: only size-1 arrays can be converted to Python scalars (matplotlib)
[英]TypeError: only size-1 arrays can be converted to Python scalars when trying to save numpy arrays to text file
我有以下形状的两个数组:
x_train = np.ndarray(shape = (1383, 15104), dtype = 'int')
y_train = np.ndarray(shape = (1383, 11), dtype = 'int')
然后我有此功能将它们保存到.txt
文件:
# Save the data files into a format compatible with CNTK text reader
def savetxt(filename, data, hasLabels=True, labels=0):
dir = os.path.dirname(filename)
if not os.path.exists(dir):
os.makedirs(dir)
print("Saving", filename )
with open(filename, 'w') as f:
print("opened....")
labels_ohe = list(map(' '.join, np.eye(11, dtype=np.uint).astype(str))) #for one hot encoding
index = 0
for row in data:
row_str = row.astype(str)
if hasLabels:
label_str = labels_ohe[int(labels[index])]
feature_str = ' '.join(row_str)
if hasLabels:
f.write('|labels {} |features {}\n'.format(label_str, feature_str))
else:
f.write('|features {}\n'.format(feature_str))
index = index + 1
然后,当我尝试使用此功能将数组保存到文本文件中时:
train_labels_GT = y_train[:,1] #Get Ground truth
print ('Writing train text file...')
data_dir = os.path.join(os.getcwd(), "Data/Out")
savetxt(os.path.join(data_dir, "train.txt"), x_train, True, y_train)
savetxt(os.path.join(data_dir, "test.txt"), x_test, True, y_test)
print("Done")
我收到错误:
TypeError Traceback (most recent call last)
<ipython-input-12-1da41b3fea4d> in <module>
7
8
----> 9 savetxt(os.path.join(data_dir, "train.txt"), x_train, True, y_train)
10 savetxt(os.path.join(data_dir, "test.txt"), x_test, True, y_test)
11
<ipython-input-6-b3a39923d0b8> in savetxt(filename, data, hasLabels, labels)
14 row_str = row.astype(str)
15 if hasLabels:
---> 16 label_str = labels_ohe[int(labels[index])]
17
18 feature_str = ' '.join(row_str)
TypeError: only size-1 arrays can be converted to Python scalars
为什么会发生此错误,我该如何解决?
提前致谢
解决了:
我只需要在保存文本文件部分中更改以下几行:
代替:
train_labels_GT = y_train[:,1] #Get Ground truth
print ('Writing train text file...')
data_dir = os.path.join(os.getcwd(), "Data/Out")
savetxt(os.path.join(data_dir, "train.txt"), x_train, True, y_train)
savetxt(os.path.join(data_dir, "test.txt"), x_test, True, y_test)
print("Done")
采用:
train_labels_GT = y_train[:,1] #Get Ground truth
test_labels_GT = y_test[:,1]
print ('Writing train text file...')
data_dir = os.path.join(os.getcwd(), "Data/Out")
savetxt(os.path.join(data_dir, "train.txt"), x_train, True, train_labels_GT)
savetxt(os.path.join(data_dir, "test.txt"), x_test, True, test_labels_GT)
print("Done")
然后,一切都正确完成。 希望这会对某人有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.