问题描述
我正在处理一个Uni作业,需要用softmax Regression
实现Pytorch
。作业说:
Implement softmax Regression as an nn.Module and pipe its output with its output with torch.nn.softmax.
由于我是pytorch的新手,所以我不确定如何确切地做到这一点。到目前为止,我已经尝试过:
softmaxRegression(nn.Module)类:#从nn.Module继承!
def __init__(self,num_labels,num_features):
super(softmaxRegression,self).__init__()
self.linear = torch.nn.Linear(num_labels,num_features)
def forward(self,x):
# should return the probabilities for the classes,e.g.
# tensor([[ 0.1757,0.3948,0.4295],# [ 0.0777,0.3502,0.5721],# ...
# not sure what to do here
有人知道我该怎么做吗?我不确定forward
方法中应该写些什么。感谢您的帮助!
解决方法
据我了解,该任务希望您实现自己的Softmax函数版本。但是,我没有得到and pipe its output with torch.nn.Softmax
的意思。他们是不是要您返回自定义Softmax的输出以及自定义torch.nn.Softmax
来的nn.Module
?您可以这样做:
class SoftmaxRegression(nn.Module):
def __init__(self,dim=0):
super(SoftmaxRegression,self).__init__()
self.dim = dim
def forward(self,x):
means = torch.mean(x,self.dim,keepdim=True)[0]
exp_x= torch.exp(x-means)
sum_exp_x = torch.sum(exp_x,keepdim=True)
value = exp_x/sum_exp_x
return value