在看DANN的源码,看到这个:
def __init__(self):
super(CNNModel, self).__init__()
self.feature = nn.Sequential()
self.class_classifier = nn.Sequential()
self.domain_classifier = nn.Sequential()
self.feature.add_module…………
…………
def forward(self, input_data, alpha):
input_data = input_data.expand(input_data.data.shape[0], 3, 28, 28)
feature = self.feature(input_data)
feature = feature.view(-1, 50 * 4 * 4)
reverse_feature = ReverseLayerF.apply(feature, alpha)
class_output = self.class_classifier(feature)
domain_output = self.domain_classifier(reverse_feature)
没用过python2,对apply不熟,查了一下用法感觉没看懂,附一下其他需要的代码段:
class ReverseLayerF(Function):
@staticmethod
def forward(ctx, x, alpha):
ctx.alpha = alpha
return x.view_as(x)
@staticmethod
def backward(ctx, grad_output):
output = grad_output.neg() * ctx.alpha
return output, None
alpha = 2. / (1. + np.exp(-10 * p)) - 1
class_output, domain_output = my_net(input_data=inputv_img, alpha=alpha)
forward里reverse_feature = ReverseLayerF.apply(feature, alpha)这句不太明白,我看出来ReverseLayerF是单独为该处重写了前向传播和反向传播,但apply函数里也是只有两个变量没有函数名啊,这是怎么调用的?而且要改成python3要怎么写?
另外,单独写了几句试了试,居然还跑通了
feature = torch.rand([2,2])
alpha = 1000
reverse_feature = ReverseLayerF.apply(feature, alpha)
结果是调用了类内的forward()使得reverse_feature=feature,且ReverseLayerF.alpha=1000.
那么这个类名.apply()到底是什么?有没有人能解释一下