我有一些工作代码可以正确地将 csv 文件中的数据加载到 PyBrain 数据集中:
def old_get_dataset():
reader = csv.reader(open('test.csv', 'rb'))
header = reader.next()
fields = dict(zip(header, range(len(header))))
print header
# assume last field in csv is single target variable
# and all other fields are input variables
dataset = SupervisedDataSet(len(fields) - 1, 1)
for row in reader:
#print row[:-1]
#print row[-1]
dataset.addSample(row[:-1], row[-1])
return dataset
现在我正在尝试重写此代码以改用 numpy 的 loadtxt 函数。我相信 addSample 可以采用 numpy 数组,而不必一次添加一行数据。
假设我加载的 numpy 数组是 mxn 维的,我如何传入第一组 mx (n-1) 数据作为第一个参数,最后一列数据作为第二个参数?这就是我正在尝试的:
def get_dataset():
array = numpy.loadtxt('test.csv', delimiter=',', skiprows=1)
# assume last field in csv is single target variable
# and all other fields are input variables
number_of_columns = array.shape[1]
dataset = SupervisedDataSet(number_of_columns - 1, 1)
#print array[0]
#print array[:,:-1]
#print array[:,-1]
dataset.addSample(array[:,:-1], array[:,-1])
return dataset
但我收到以下错误:
Traceback (most recent call last):
File "C:\test.py", line 109, in <module>
(d, n, t) = main()
File "C:\test.py", line 87, in main
ds = get_dataset()
File "C:\test.py", line 45, in get_dataset
dataset.addSample(array[:,:-1], array[:,-1])
File "C:\Python27\lib\site-packages\pybrain\datasets\supervised.py",
line 45, in addSample self.appendLinked(inp, target)
File "C:\Python27\lib\site-packages\pybrain\datasets\dataset.py",
line 215, in appendLinked self._appendUnlinked(l, args[i])
File "C:\Python27\lib\site-packages\pybrain\datasets\dataset.py",
line 197, in _appendUnlinked self.data[label][self.endmarker[label], :] = row
ValueError: output operand requires a reduction, but reduction is not enabled
我怎样才能解决这个问题?