gpt4 book ai didi

python - 如何修改Python中生成器的最后一个元素?

转载 作者:行者123 更新时间:2023-11-30 09:32:57 31 4
gpt4 key购买 nike

我有一个生成器,我想修改生成器的最后一个元素。我想用另一个元素替换最后一个元素。我知道如何检索最后一个元素,但不知道如何修改它。

解决这个问题的最佳方法是什么?

有关更多上下文,这就是我想要做的:

for child in alexnet.children():
for children_of_child in child.children():
print(children_of_child);

我的生成器对象是:children_of_child 对于第二个 child ,它的所有 child 都是:

Dropout(p=0.5)
Linear(in_features=9216, out_features=4096, bias=True)
ReLU(inplace)
Dropout(p=0.5)
Linear(in_features=4096, out_features=4096, bias=True)
ReLU(inplace)
Linear(in_features=4096, out_features=1000, bias=True)

我想用我自己的回归网络替换最后一层Linear(in_features=4096, out_features=1000,bias=True)。 `

最佳答案

由于您正在使用一个相当小的列表(即使 ResNet-150 在 RAM 方面也“相当小”),我会让它易于理解和维护。没有“明显”的方法来检测您距离耗尽发电机还差一步。

  1. 耗尽当前生成器,生成其输出列表。
  2. 根据需要替换最后一个元素。
  3. 围绕这个更改后的列表包装一个新的生成器。

执行此操作的“好”(?)方法是在原始版本中编写一个具有单元素前瞻功能的包装生成器:在每次调用 N 时,您已经拥有 包装器中的元素N。您从“真实”生成器(您发布的代码)中获取元素N+1。如果该元素存在,则正常返回元素N。如果该生成器已耗尽,则将最后一个元素替换为所需的元素,然后返回更改。

示例:

为了简单起见,我使用 range 代替原来的生成器。

def new_tail():
my_list = list(range(6))
my_list[-1] = "new last element"
for elem in my_list:
yield elem

for item in new_tail():
print(item)

输出:

0
1
2
3
4
new last element

这有帮助吗?

关于python - 如何修改Python中生成器的最后一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51270199/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com