python - 如何在 OO 中轻松高效地存储 numpy ufuncs 的模拟数据
问题描述
在 jupyter notebook 中,我对资源进行了 OO 建模,但在控制循环中,需要在多个对象上聚合数据,与 ufunc 和类似操作相比效率低下。
为了打包功能,我选择了 OO,但为了高效简洁的代码,我可能必须将数据提取到存储类中(可能)并将所有 ri[0] 行推入二维数组,在本例中为 (2,K)。该类不需要日志,只需要最后的条目。
K = 100
class Resource:
def __init__(self):
self.log = np.random( (5,K) )
# log gets filled during simulation
r0 = Resource()
r1 = Resource()
# while control loop:
#aggregate control data
for k in K:
total_row_0 = r0.log[0][k] + r1.log[0][k]
#do sth with the totals and loop again
这将大大提高性能,但如果单独存储,我很难将数据链接到类。你会如何处理这个问题?pandas DataFrames、np View 或 Shallow Copy?
[[...] #r0
[...] ]#r1 same data into one array, efficient but map back to class difficult
解决方案
这是我的看法:
import numpy as np
K = 3
class Res:
logs = 2
def __init__(self):
self.log = None
def set_log(self, view):
self.log = view
batteries = [Res(), Res()]
d = {'Res': np.random.random( (Res.logs * len(batteries), K) )}
for i in range(len(batteries)):
view = d['Res'].view()[i::len(batteries)][:]
batteries[i].set_log(view)
print(d)
batteries[1].log[1][2] = 1#test modifies view of last entry of second Res of second log
print(d)
推荐阅读
- ansible - 自定义动态库存
- timeout - SPARQL 在超时之前获取所有数据
- c++ - 在 C++ 类中声明多维数组的正确方法是什么
- angular - Angular WebAPI POST 服务调用替换了请求正文中的“+”字符
- java - 为什么 ArrayList 上的 contains() 方法总是返回 false?
- google-apps-script - Google Apps 脚本中是否有用于选择所选单元格左侧或右侧的所有列的功能?
- swift - SwiftUI - NavigationView 将详细信息指示器“>”添加到列表视图 - 如何删除?
- python - 为什么我的 acc 总是更高但我的 val_acc 很小?
- timestamp - 将 .txt 文件中的时间戳值导入 Teradata 表中的等效列(UTC 时间戳)
- node.js - 如何在网站上显示来自 s3 的图像?