def convert(imgf, labelf, outf, n): f = open(imgf, "rb") o = open(outf, "w") l = open(labelf, "rb") f.read(16) l.read(8) images = [] for i in range(n): image = [ord(l.read(1))] for j in range(28*28): image.append(ord(f.read(1))) images.append(image) for image in images: o.write(",".join(str(pix) for pix in image)+"\n") f.close() o.close() l.close() convert("MNIST/train-images.idx3-ubyte", "subject_train.csv", 60000) convert( "MNIST/train-labels.idx1-ubyte", "label_train.csv", 60000) convert("MNIST/t10k-images.idx3-ubyte","subject_test.csv", 10000) convert("MNIST/t10k-labels.idx1-ubyte", "label_test.csv", 10000) 如何修改代码,使train-images.idx3-ubyte,train-labels.idx1-ubyte,t10k-images.idx3-ubyte,t10k-labels.idx1-ubyte转化为csv文件。
时间: 2024-04-17 11:25:19 浏览: 95
MNIST-to-CSV:从http转换原始MNIST数据库
要修改代码将这些文件转化为CSV文件,你可以进行以下修改:
```python
def convert(imgf, labelf, outf, n):
f = open(imgf, "rb")
o = open(outf, "w")
l = open(labelf, "rb")
f.read(16)
l.read(8)
images = []
for i in range(n):
image = [ord(l.read(1))]
for j in range(28 * 28):
image.append(ord(f.read(1)))
images.append(image)
for image in images:
o.write(",".join(str(pix) for pix in image) + "\n")
f.close()
o.close()
l.close()
convert("MNIST/train-images.idx3-ubyte", "MNIST/train-labels.idx1-ubyte", "subject_train.csv", 60000)
convert("MNIST/t10k-images.idx3-ubyte", "MNIST/t10k-labels.idx1-ubyte", "subject_test.csv", 10000)
```
修改后的代码中,主要是将函数`convert`的调用参数中的文件路径修改为正确的路径。例如,将`"MNIST/train-images.idx3-ubyte"`作为第一个参数传递给`convert`函数,将`"MNIST/train-labels.idx1-ubyte"`作为第二个参数传递给`convert`函数,并将输出文件名修改为适当的CSV文件名。同样地,对于测试集的转换也需要进行相应的修改。
阅读全文