from_struct_array¶
- class tensordict.from_struct_array(struct_array: ndarray, device: Optional[device] = None)¶
将结构化的 numpy 数组转换为 TensorDict。
生成的 TensorDict 的内容将与 numpy 数组共享相同的内存内容(这是一个零拷贝操作)。就地更改结构化的 numpy 数组的值将影响 TensorDict 的内容。
示例
>>> x = np.array( ... [("Rex", 9, 81.0), ("Fido", 3, 27.0)], ... dtype=[("name", "U10"), ("age", "i4"), ("weight", "f4")], ... ) >>> td = from_struct_array(x) >>> x_recon = td.to_struct_array() >>> assert (x_recon == x).all() >>> assert x_recon.shape == x.shape >>> # Try modifying x age field and check effect on td >>> x["age"] += 1 >>> assert (td["age"] == np.array([10, 4])).all()