【问题标题】:How to implement Softmax regression with pytorch?如何用pytorch实现Softmax回归?
【发布时间】:2020-11-11 09:27:26
【问题描述】:

我正在从事一项 uni 任务,我需要使用 Pytorch 实现 Softmax Regression。作业说:

Implement Softmax Regression as an nn.Module and pipe its output with its output with torch.nn.Softmax.

由于我是 pytorch 的新手,我不知道该怎么做。到目前为止,我已经尝试过:

class 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 方法中应该写什么。感谢您的帮助!

【问题讨论】:

    标签: python pytorch regression softmax


    【解决方案1】:

    据我了解,作业希望您实现自己的 Softmax 函数版本。但是,我不明白and pipe its output with torch.nn.Softmax 是什么意思。他们是否要求您从自定义 nn.Module 返回自定义 Softmax 的输出以及 torch.nn.Softmax?你可以这样做:

    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, self.dim, keepdim=True)
            value = exp_x/sum_exp_x
            return value
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-12
      • 1970-01-01
      相关资源
      最近更新 更多