Wuhuwill commited on
Commit
25b6d23
·
verified ·
1 Parent(s): fa1cc41

Upload ProDiff/preprocess_data_temporal.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. ProDiff/preprocess_data_temporal.py +185 -0
ProDiff/preprocess_data_temporal.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import h5py
3
+ import numpy as np
4
+ from tqdm import tqdm
5
+ import os
6
+
7
+ def create_h5_temporal_split(csv_path, train_h5_path, test_h5_path, train_ratio=0.8):
8
+ """
9
+ 使用时间分割策略:每个用户的轨迹按时间分割,前80%用于训练,后20%用于测试
10
+ 这样可以测试模型对同一用户未来轨迹的预测能力,同时保留所有用户的路径模式
11
+ """
12
+ print(f"Loading data from {csv_path}...")
13
+ try:
14
+ df = pd.read_csv(csv_path, parse_dates=['datetime'])
15
+ except Exception as e:
16
+ print(f"Error reading or parsing CSV: {e}")
17
+ return
18
+
19
+ print("Sorting data by user and time...")
20
+ df.sort_values(by=['userid', 'datetime'], inplace=True)
21
+
22
+ all_user_ids = df['userid'].unique()
23
+ print(f"Total users: {len(all_user_ids)}")
24
+ print(f"Using temporal split: {train_ratio*100:.0f}% for training, {(1-train_ratio)*100:.0f}% for testing")
25
+
26
+ # 为训练集和测试集创建HDF5文件
27
+ train_sample_count = 0
28
+ test_sample_count = 0
29
+
30
+ with h5py.File(train_h5_path, 'w') as train_h5f, h5py.File(test_h5_path, 'w') as test_h5f:
31
+
32
+ for user_id in tqdm(all_user_ids, desc="Processing users"):
33
+ user_df = df[df['userid'] == user_id].sort_values('datetime')
34
+
35
+ # 按时间分割:前train_ratio用于训练,后面用于测试
36
+ split_point = int(len(user_df) * train_ratio)
37
+
38
+ train_user_df = user_df.iloc[:split_point]
39
+ test_user_df = user_df.iloc[split_point:]
40
+
41
+ # 处理训练数据(如果有足够的数据点)
42
+ if len(train_user_df) > 0:
43
+ timestamps = train_user_df['datetime'].apply(lambda x: x.timestamp()).values
44
+ latitudes = train_user_df['lat'].values
45
+ longitudes = train_user_df['lng'].values
46
+
47
+ train_user_group = train_h5f.create_group(f"{user_id}_train")
48
+ train_user_group.create_dataset('hours', data=timestamps, dtype='float64')
49
+ train_user_group.create_dataset('latitudes', data=latitudes, dtype='float64')
50
+ train_user_group.create_dataset('longitudes', data=longitudes, dtype='float64')
51
+ train_sample_count += len(timestamps)
52
+
53
+ # 处理测试数据(如果有足够的数据点)
54
+ if len(test_user_df) > 0:
55
+ timestamps = test_user_df['datetime'].apply(lambda x: x.timestamp()).values
56
+ latitudes = test_user_df['lat'].values
57
+ longitudes = test_user_df['lng'].values
58
+
59
+ test_user_group = test_h5f.create_group(f"{user_id}_test")
60
+ test_user_group.create_dataset('hours', data=timestamps, dtype='float64')
61
+ test_user_group.create_dataset('latitudes', data=latitudes, dtype='float64')
62
+ test_user_group.create_dataset('longitudes', data=longitudes, dtype='float64')
63
+ test_sample_count += len(timestamps)
64
+
65
+ print(f"\nData processing complete!")
66
+ print(f"Training samples: {train_sample_count}")
67
+ print(f"Testing samples: {test_sample_count}")
68
+ print(f"Train file saved to: {train_h5_path}")
69
+ print(f"Test file saved to: {test_h5_path}")
70
+
71
+ def create_h5_mixed_split(csv_path, train_h5_path, test_h5_path, full_test_users=5, temporal_ratio=0.8):
72
+ """
73
+ 混合分割策略:
74
+ - 少数用户完全作为测试集(测试跨用户泛化)
75
+ - 其余用户按时间分割(测试时间泛化)
76
+ """
77
+ print(f"Loading data from {csv_path}...")
78
+ try:
79
+ df = pd.read_csv(csv_path, parse_dates=['datetime'])
80
+ except Exception as e:
81
+ print(f"Error reading or parsing CSV: {e}")
82
+ return
83
+
84
+ print("Sorting data by user and time...")
85
+ df.sort_values(by=['userid', 'datetime'], inplace=True)
86
+
87
+ all_user_ids = df['userid'].unique()
88
+
89
+ # 随机选择几个用户完全作为测试集
90
+ np.random.seed(42) # 固定随机种子确保可重复
91
+ full_test_user_ids = set(np.random.choice(all_user_ids, size=full_test_users, replace=False))
92
+ temporal_split_user_ids = set(all_user_ids) - full_test_user_ids
93
+
94
+ print(f"Total users: {len(all_user_ids)}")
95
+ print(f"Users for temporal split: {len(temporal_split_user_ids)}")
96
+ print(f"Users completely in test set: {len(full_test_user_ids)}")
97
+ print(f"Full test users: {sorted(full_test_user_ids)}")
98
+
99
+ train_sample_count = 0
100
+ test_sample_count = 0
101
+
102
+ with h5py.File(train_h5_path, 'w') as train_h5f, h5py.File(test_h5_path, 'w') as test_h5f:
103
+
104
+ # 处理时间分割的用户
105
+ for user_id in tqdm(temporal_split_user_ids, desc="Processing temporal split users"):
106
+ user_df = df[df['userid'] == user_id].sort_values('datetime')
107
+
108
+ split_point = int(len(user_df) * temporal_ratio)
109
+ train_user_df = user_df.iloc[:split_point]
110
+ test_user_df = user_df.iloc[split_point:]
111
+
112
+ # 训练数据
113
+ if len(train_user_df) > 0:
114
+ timestamps = train_user_df['datetime'].apply(lambda x: x.timestamp()).values
115
+ latitudes = train_user_df['lat'].values
116
+ longitudes = train_user_df['lng'].values
117
+
118
+ train_user_group = train_h5f.create_group(f"{user_id}_temporal")
119
+ train_user_group.create_dataset('hours', data=timestamps, dtype='float64')
120
+ train_user_group.create_dataset('latitudes', data=latitudes, dtype='float64')
121
+ train_user_group.create_dataset('longitudes', data=longitudes, dtype='float64')
122
+ train_sample_count += len(timestamps)
123
+
124
+ # 测试数据
125
+ if len(test_user_df) > 0:
126
+ timestamps = test_user_df['datetime'].apply(lambda x: x.timestamp()).values
127
+ latitudes = test_user_df['lat'].values
128
+ longitudes = test_user_df['lng'].values
129
+
130
+ test_user_group = test_h5f.create_group(f"{user_id}_temporal")
131
+ test_user_group.create_dataset('hours', data=timestamps, dtype='float64')
132
+ test_user_group.create_dataset('latitudes', data=latitudes, dtype='float64')
133
+ test_user_group.create_dataset('longitudes', data=longitudes, dtype='float64')
134
+ test_sample_count += len(timestamps)
135
+
136
+ # 处理完全作为测试集的用户
137
+ for user_id in tqdm(full_test_user_ids, desc="Processing full test users"):
138
+ user_df = df[df['userid'] == user_id].sort_values('datetime')
139
+
140
+ timestamps = user_df['datetime'].apply(lambda x: x.timestamp()).values
141
+ latitudes = user_df['lat'].values
142
+ longitudes = user_df['lng'].values
143
+
144
+ test_user_group = test_h5f.create_group(f"{user_id}_full")
145
+ test_user_group.create_dataset('hours', data=timestamps, dtype='float64')
146
+ test_user_group.create_dataset('latitudes', data=latitudes, dtype='float64')
147
+ test_user_group.create_dataset('longitudes', data=longitudes, dtype='float64')
148
+ test_sample_count += len(timestamps)
149
+
150
+ print(f"\nMixed split processing complete!")
151
+ print(f"Training samples: {train_sample_count}")
152
+ print(f"Testing samples: {test_sample_count}")
153
+ print(f"Train file saved to: {train_h5_path}")
154
+ print(f"Test file saved to: {test_h5_path}")
155
+
156
+ if __name__ == '__main__':
157
+ # 配置
158
+ # 直接使用新的轨迹数据文件
159
+ CSV_DATA_PATH = 'data/matched_trajectory_data.csv'
160
+ output_dir = 'data'
161
+
162
+ print(f"将使用输入文件: {CSV_DATA_PATH}")
163
+ print("将使用时间分割策略生成 train_temporal.h5 和 test_temporal.h5")
164
+
165
+ # 定义输出路径
166
+ TRAIN_H5_PATH = os.path.join(output_dir, 'train_temporal.h5')
167
+ TEST_H5_PATH = os.path.join(output_dir, 'test_temporal.h5')
168
+
169
+ # 运行转换
170
+ create_h5_temporal_split(CSV_DATA_PATH, TRAIN_H5_PATH, TEST_H5_PATH)
171
+
172
+ # 验证生成的文件
173
+ print("\n验证生成的HDF5文件...")
174
+ try:
175
+ with h5py.File(TRAIN_H5_PATH, 'r') as h5f:
176
+ print(f"训练集包含 {len(h5f.keys())} 个用户组")
177
+ if h5f.keys():
178
+ sample_key = list(h5f.keys())[0]
179
+ sample_group = h5f[sample_key]
180
+ print(f"示例用户组 '{sample_key}':")
181
+ for dset_name in sample_group.keys():
182
+ dset = sample_group[dset_name]
183
+ print(f" - {dset_name}: {dset.shape}")
184
+ except Exception as e:
185
+ print(f"验证文件时出错: {e}")