前言
这篇文章主要两个内容。
一,把上一篇关于requires_grad的内容补充一下。
二,介绍一下线性回归。
关闭张量计算
关闭张量计算。这个相对简单,阅读下面代码即可。
print("============关闭require_grad==============")
x = torch.randn(3, requires_grad=True)
print(x)
x.requires_grad_(False) # 关闭x的张量计算
print("关闭x的张量计算后的x:", x) # 没有requires_grad属性了
x = torch.randn(3, requires_grad=True)
print("新的带张量计算的x:", x)
y = x.detach() # 去出x的张量附加属性,返回普通张量
print("y没有张量属性:", y)
print("x还有张量属性:", x)
print("============区域内去除x的张量附加属性==============")
with torch.no_grad():
y = x+2
print("y没有张量属性:", y)
print("x还有张量属性:", x)
一个有趣的例子
代码1如下,代码可以正常运行。
x = torch.tensor(1.0)
y = torch.tensor(2.0)