UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach()

1、UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor).
在这里插入图片描述
解决:

theta_init_new = torch.tensor(theta, dtype=torch.float32, requires_grad=True)

改为

theta_init_new = torch.as_tensor(theta, dtype=torch.float32, requires_grad=True)

2、‘bool’ object is not iterable
在这里插入图片描述
解决:

  • 7
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
import torch import torch.nn as nn import numpy as np import torch.nn.functional as F import matplotlib.pyplot as plt from torch.autograd import Variable x=torch.tensor(np.array([[i] for i in range(10)]),dtype=torch.float32) y=torch.tensor(np.array([[i**2] for i in range(10)]),dtype=torch.float32) #print(x,y) x,y=(Variable(x),Variable(y))#将tensor包装一个可求导的变量 net=torch.nn.Sequential( nn.Linear(1,10,dtype=torch.float32),#隐藏层线性输出 torch.nn.ReLU(),#激活函数 nn.Linear(10,20,dtype=torch.float32),#隐藏层线性输出 torch.nn.ReLU(),#激活函数 nn.Linear(20,1,dtype=torch.float32),#输出层线性输出 ) optimizer=torch.optim.SGD(net.parameters(),lr=0.05)#优化器(梯度下降) loss_func=torch.nn.MSELoss()#最小均方差 #神经网络训练过程 plt.ion() plt.show()#动态学习过程展示 for t in range(2000): prediction=torch.tensor(net(x)),#把数据输入神经网络,输出预测值 loss=loss_func(prediction, y)#计算二者误差,注意这两个数的顺序 optimizer.zero_grad()#清空上一步的更新参数值 loss.backward()#误差反向传播,计算新的更新参数值 optimizer.step()#将计算得到的更新值赋给net.parameters()D:\Anaconda\python.exe D:\py\text.py D:\py\text.py:26: UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor). prediction=torch.tensor(net(x)),#把数据输入神经网络,输出预测值 Traceback (most recent call last): File "D:\py\text.py", line 27, in <module> loss=loss_func(prediction, y)#计算二者误差,注意这两个数的顺序 File "D:\Anaconda\lib\site-packages\torch\nn\modules\module.py", line 1194, in _call_impl return forward_call(*input, **kwargs) File "D:\Anaconda\lib\site-packages\torch\nn\modules\loss.py", line 536, in forward return F.mse_loss(input, target, reduction=self.reduction) File "D:\Anaconda\lib\site-packages\torch\nn\functional.py", line 3281, in mse_loss if not (target.size() == input.size()): AttributeError: 'tuple' object has no attribute 'size'
05-31
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值