我使用以下代码将数据集拆分为训练数据和测试数据以保存在文件中;
import numpy as np
from sklearn.cross_validation import train_test_split
a = (np.genfromtxt(open('dataset.csv','r'), delimiter=',', dtype='int')[1:])
a_train, a_test = train_test_split(a, test_size=0.33, random_state=0)
c1 = open('trainfile.csv', 'w')
arr1 = str(a_train)
c1.write(arr1)
c1.close
c2 = open('testfile.csv', 'w')
arr2 = str(a_test)
c2.write(arr2)
c2.close
但是我在文件中得到以下输出;
trainfile.csv:
[[ 675847 0 0 ..., 0 0 3]
[ 74937 0 0 ..., 0 0 3]
[ 65212 0 0 ..., 0 0 3]
...,
[ 18251 0 0 ..., 0 0 1]
[1131828 0 0 ..., 0 0 1]
[ 14529 0 0 ..., 0 0 1]]
这就是trainfile的全部内容。我也面临与 testfile.csv 的输出相同的问题。我想要的是整个训练和测试数据存储在文件中,而不是表示额外数据的句点。有建议吗?
最佳答案
这是因为您正在 numpy 数组上调用字符串方法 str
。使用numpy函数numpy.savetxt
反而。它看起来像
with open('testfile.csv', 'w') as FOUT:
np.savetxt(FOUT, a_test)
请注意,CSV 阅读器不一定能够读取该格式。如果这是您的意图,您可以使用 https://docs.python.org/2/library/csv.html .
关于python - 将训练和测试数据保存在文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23319167/