该篇目主要是记录日常遇到的代码安全问题的记录
# 清空会话的RAM
del combined_list
gc.collect()# 重新读取上述合成的NPZ文件为一个新的文件
combined_arrays = []
for i in range(1, batch_count + 1): # 从1到batch_count+1,包括剩余的最后一个文件data = np.load(f"{npz_file_prefix}_{i}.npz")['combined_array']combined_arrays.append(data)# 合并所有的数组
final_combined_array = np.concatenate(combined_arrays, axis=0)# 保存为一个新的NPZ文件
np.savez('final_combined_data.npz', combined_array=final_combined_array)print("所有数据已合并并保存为 final_combined_data.npz")
报错如下:
Traceback (most recent call last):File "D:\Programs\Python\Python38\lib\code.py", line 90, in runcodeexec(code, self.locals)File "<input>", line 1, in <module>File "D:\Program Files\JetBrains\PyCharm 2022.1.2\plugins\python\helpers\pydev\_pydev_bundle\pydev_umd.py", line 198, in runfilepydev_imports.execfile(filename, global_vars, local_vars) # execute the scriptFile "D:\Program Files\JetBrains\PyCharm 2022.1.2\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfileexec(compile(contents+"\n", file, 'exec'), glob, loc)File "D:/pythonProject/PHM2010/informer0615/数据整合.py", line 88, in <module>data = np.load(f"{npz_file_prefix}_{i}.npz")['combined_array']File "D:\Programs\Python\Python38\lib\site-packages\numpy\lib\npyio.py", line 253, in __getitem__return format.read_array(bytes,File "D:\Programs\Python\Python38\lib\site-packages\numpy\lib\format.py", line 787, in read_arrayraise ValueError("Object arrays cannot be loaded when "
ValueError: Object arrays cannot be loaded when allow_pickle=False
原因如下:
这个错误是由于 NumPy 不能加载包含对象数组的 .npz 文件,因为默认情况下 allow_pickle 参数被设置为 False。为了修复这个问题,可以在加载数组时显式地设置 allow_pickle=True。但是,这样做存在一定的安全风险,尤其是当加载来自不受信任来源的数据时。因此,请确保数据来源是可信的。
修改方式如下:
# 清空会话的RAM
del combined_list
gc.collect()# 重新读取上述合成的NPZ文件为一个新的文件
combined_arrays = []
for i in range(1, batch_count + 1): # 从1到batch_count+1,包括剩余的最后一个文件data = np.load(f"{npz_file_prefix}_{i}.npz", allow_pickle=True)['combined_array']combined_arrays.append(data)# 合并所有的数组
final_combined_array = np.concatenate(combined_arrays, axis=0)# 保存为一个新的NPZ文件
np.savez('final_combined_data.npz', combined_array=final_combined_array)print("所有数据已合并并保存为 final_combined_data.npz")