python - 如何用pytorch实现Softmax回归?
问题描述
我正在做一个需要Softmax Regression
用Pytorch
. 作业说:
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
方法中应该写什么。我感谢任何帮助!
解决方案
据我了解,该作业希望您实现自己的 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, self.dim, keepdim=True)
value = exp_x/sum_exp_x
return value
推荐阅读
- labview - LabVIEW度数转换器程序
- c# - 希望将实体作为通用类型传递并提取通用功能
- flutter - Flutter 在弹出时隐藏键盘
- angular - 我无法迭代对象 Object
- python - 如何计算嵌套列表中多个交叉点的出现次数
- javascript - 分组和过滤 JSON 文件
- python - Pelican:在主页上包含文件的内容
- python - 是否有可能让 networkx dijkstra 避免某些边缘?
- javascript - 即使使用 --disable-web-security,Chrome 也会阻止具有相同来源的 iframe
- python - 如何将python整数转换为c整数?