Pytorch 期待1D张量但得到的是2D张量

我正在尝试从头开始用Python构建神经网络。输入张量的形状是[400,3],目标张量的形状是[400]。在计算权重导数时遇到了错误。以下是相关函数:

def sigmoid(z):    return 1 / (1 + torch.exp(-z))def nueral_net(data,weights,bias):    return sigmoid( ( data @ weights ) + bias )def loss_function(prediction,actual,m):    return (-1/m) * (torch.sum(actual * torch.log(prediction) + (1-actual)     * torch.log(1- prediction)))w = torch.randn(input_tensor.shape[1],1)b = torch.randn(1,1)predictions = nueral_net(input_tensor.float() , w, b) #应用模型loss = loss_function(predictions,target_tensor.unsqueeze(1),400)dw = (1/400) * torch.dot(input_tensor,(predictions - target_tensor).T)

运行这段代码会抛出以下错误:

RuntimeError                              Traceback (most recent call last)<ipython-input-26-632338d8fd16> in <module>      1 predictions = nueral_net(input_tensor.float() , w, b) #应用模型      2 loss = loss_function(predictions,target_tensor.unsqueeze(1),400)----> 3 dw = (1/400) * torch.dot(input_tensor,(predictions - target_tensor).T)      4 db = (1/400) * torch.sum(predictions - target_tensor)      5 #m = input_tensor.shape[0]    RuntimeError: 期待1D张量,但得到的是2D和2D张量

回答:

查看torch.dot的文档:
torch.dot(input, other, *, out=None)Tensor计算两个1D张量的点积。

注意:与NumPy的dot不同,torch.dot有意只支持计算具有相同元素数量的两个1D张量的点积。

参数
input (Tensor) – 点积中的第一个张量,必须是1D。
other (Tensor) – 点积中的第二个张量,必须是1D。

回到你的问题……input_tensor(predictions - target_tensor).T 都是2D的。
请将其改为1D

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注