我在pytorch中有一些模型,我想手动访问和更改其可更新的权重。
如何正确完成?
理想情况下,我想要这些重量的张量。
在我看来
for parameter in model.parameters():
do_something_to_parameter(parameter)
不是正确的方法,因为
- 它不使用GPU,也无法
- 它甚至没有使用低级实现
手动访问模型的权重的正确方法是什么(不是通过loss.backward
和optimizer.step
)?
这是我的方法,您通常可以在此处输入任何模型,它将返回所有火炬的列表。
def flatten_model(modules):
def flatten_list(_2d_list):
flat_list = []
# Iterate through the outer list
for element in _2d_list:
if type(element) is list:
# If the element is of type list, iterate through the sublist
for item in element:
flat_list.append(item)
else:
flat_list.append(element)
return flat_list
ret = []
try:
for _, n in modules:
ret.append(loopthrough(n))
except:
try:
if str(modules._modules.items()) == "odict_items([])":
ret.append(modules)
else:
for _, n in modules._modules.items():
ret.append(loopthrough(n))
except:
ret.append(modules)
return flatten_list(ret)