# -*- coding: utf-8 -*- """ Transform the data type from ascii to ubyte format (8 bits unsigned binary) and save to new files, which would reduce the data size to 1/3, and would save the data transforming time when read by the python @author: Marmot """ import numpy as np import time from itertools import islice import pandas as pd # data_folder = '../../data/' set_list = ['train','testA','testB'] size_list = [10000,2000,2000] time1= time.time() for set_name,set_size in zip(set_list,size_list): output_file = data_folder + set_name + '_ubyte.txt' f = open(output_file, "w") f.close() Img_ind = 0 input_file = data_folder + set_name +'.txt' with open(input_file) as f: for content in f: Img_ind = Img_ind +1 print('transforming ' + set_name + ': ' + str(Img_ind).zfill(5)) line = content.split(',') title = line[0] + ' '+line[1] data_write = np.asarray(line[2].strip().split(' ')).astype(np.ubyte) data_write = (data_write + 1).astype(np.ubyte) if data_write.max()>255: print('too large') if data_write.min()<0: print('too small') f = open(output_file, "a") f.write(data_write.tobytes()) f.close() time2 = time.time() print('total elapse time:'+ str(time2- time1)) #%% generate train label list value_list =[] set_name = 'train' input_file = data_folder + set_name +'.txt' with open(input_file) as f: for content in f: line = content.split(',') value_list.append(float(line[1])) value_list = pd.DataFrame(value_list, columns=['value']) value_list.to_csv(data_folder + 'train_label.csv',index = False,header = False)
时间: 2024-02-14 14:22:18 浏览: 31
这段代码的主要功能是将数据集中的图像像素值从 ASCII 码转换为无符号 8 位二进制格式,并保存到新文件中,同时生成训练集标签列表。
代码首先定义了一个数据路径列表 `set_list` 和一个数据子集大小列表 `size_list`。然后通过循环遍历每个数据子集,对每个子集执行以下操作:
1. 定义了一个输出文件路径 `output_file`,并创建一个空文件;
2. 读取输入文件 `input_file`,遍历每个图像像素值,并将其转换为无符号 8 位二进制格式;
3. 将转换后的图像像素值写入输出文件中;
4. 遍历完成后,输出文件中将包含整个数据子集的所有图像像素值。
注意,代码中的 `data_folder` 变量指定了数据集所在的文件夹路径。
另外,代码的最后还生成了训练集标签列表。具体来说,代码读取训练集文件 `train.txt`,提取其中的标签信息,并将标签保存到一个 CSV 文件 `train_label.csv` 中,以供后续的模型训练使用。
相关问题
# -*- coding: utf-8 -*-不起作用
如果`# -*- coding: utf-8 -*-`在你的代码中不起作用,可能是因为你的代码中已经存在其他编码方式的声明,或者编码声明位置不正确。请确保`# -*- coding: utf-8 -*-`在代码文件的开头,并且没有其他编码声明在它之前。
另外,如果你使用的是Python 3.x版本,那么默认的编码方式已经是UTF-8,不需要额外的编码声明。你可以尝试移除`# -*- coding: utf-8 -*-`这行代码,看看问题是否解决。
如果你仍然遇到编码问题,可以尝试使用`encode()`方法将字符串转换为字节序列,并指定合适的编码方式。例如:
```python
my_string = "你好"
encoded_string = my_string.encode('utf-8')
```
这样可以将字符串编码为UTF-8字节序列。希望这些方法能够帮助你解决问题!
文件第1行代码:# -*- coding: utf-8 -*-
文件的第一行代码 "# -*- coding: utf-8 -*-" 是用来指定文件的编码方式为 UTF-8。在 Python 2 中,这一行的作用是告诉解释器以 UTF-8 编码方式解析文件中的字符。而在 Python 3 中,默认情况下,所有的源代码文件都被视为使用 UTF-8 编码,因此这一行在 Python 3 中并不是必需的。
UTF-8 是一种通用的字符编码方式,它可以表示几乎所有的字符,包括各种语言的字符和特殊符号。指定文件编码方式为 UTF-8 可以确保在文件中使用各种字符时不会出现编码错误。
如果你的代码中包含了特殊字符或其他非 ASCII 字符,建议在文件的第一行添加 "# -*- coding: utf-8 -*-" 这样的声明,以便告知解释器正确的编码方式。这样可以避免出现编码相关的错误和警告。
请注意,这个声明必须出现在文件的第一行,前面不能有任何其他内容,包括注释。否则,解释器可能无法正确解析该声明。