if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--path', type=str, default=r"data/UCI HAR Dataset/UCI HAR Dataset", help='UCI dataset data path') parser.add_argument('--save', type=str, default='data/UCI_Smartphone_Raw.csv', help='save file name') args = parser.parse_args() data_path = args.path # read train subjects train_subjects = pd.read_csv(os.path.join(data_path, 'train/subject_train.txt'), header=None, names=['subject']) # read test subjects test_subjects = pd.read_csv(os.path.join(data_path, 'test/subject_test.txt'), header=None, names=['subject']) # concat subjects = pd.concat([train_subjects, test_subjects], axis=0) # read train labels train_labels = pd.read_csv(os.path.join(data_path, 'train/y_train.txt'), header=None, names=['label']) # read train labels test_labels = pd.read_csv(os.path.join(data_path, 'test/y_test.txt'), header=None, names=['label']) # labels labels = pd.concat([train_labels, test_labels], axis=0) final_dataframe = pd.concat([subjects, labels], axis=1) data = [] for name in COLUMNS: final_dataframe = pd.concat([final_dataframe, read_txt(name)], axis=1) final_dataframe.to_csv(args.save,index=False) 如何将文中txt文件改成mnist数据集数据,其他不做大修改
时间: 2024-04-17 12:25:21 浏览: 185
要将代码修改为使用MNIST数据集而不是txt文件,你需要进行以下修改:
1. 导入所需的库和模块:
```python
import numpy as np
import pandas as pd
from sklearn.datasets import fetch_openml
```
2. 加载MNIST数据集:
```python
mnist = fetch_openml('mnist_784', version=1, cache=True)
```
3. 将图像矩阵和标签分别存储为numpy数组:
```python
X = mnist.data
y = mnist.target
```
4. 创建一个包含所有数据的Pandas数据框:
```python
df = pd.DataFrame(X)
df['label'] = y
```
5. 将数据框保存为CSV文件:
```python
df.to_csv(args.save, index=False)
```
注意,这里我们使用了`args.save`作为保存文件名,这是根据你之前的代码中的`--save`命令行参数来决定的。
除了以上修改,你还需要删除以下代码块,因为MNIST数据集已经包含了图像数据和标签,不需要再读取其他文件:
```python
# read train subjects
train_subjects = pd.read_csv(os.path.join(data_path, 'train/subject_train.txt'), header=None, names=['subject'])
# read test subjects
test_subjects = pd.read_csv(os.path.join(data_path, 'test/subject_test.txt'), header=None, names=['subject'])
# concat
subjects = pd.concat([train_subjects, test_subjects], axis=0)
# read train labels
train_labels = pd.read_csv(os.path.join(data_path, 'train/y_train.txt'), header=None, names=['label'])
# read train labels
test_labels = pd.read_csv(os.path.join(data_path, 'test/y_test.txt'), header=None, names=['label'])
# labels
labels = pd.concat([train_labels, test_labels], axis=0)
final_dataframe = pd.concat([subjects, labels], axis=1)
data = []
for name in COLUMNS:
final_dataframe = pd.concat([final_dataframe, read_txt(name)], axis=1)
```
这些修改后的代码将直接将MNIST数据集转换为CSV文件,并保存到指定的路径中。
阅读全文