torch.randon
时间: 2023-08-07 16:11:39 浏览: 91
在PyTorch中,torch.rand()函数用于生成指定形状的随机张量,张量的元素值是在[0, 1)之间均匀分布的随机数。下面是一个使用torch.rand()函数生成随机张量的示例:
```python
import torch
# 生成一个形状为(2, 3)的随机张量
x = torch.rand(2, 3)
print(x)
```
输出类似于:
```
tensor([[0.8974, 0.3216, 0.5678],
[0.1234, 0.9876, 0.4567]])
```
在上面的示例中,我们使用torch.rand(2, 3)生成了一个形状为(2, 3)的随机张量x,并将其打印出来。
需要注意的是,torch.rand()函数会生成在[0, 1)之间均匀分布的随机数。如果需要生成其他分布的随机数,可以使用其他函数,例如torch.randn()用于生成服从标准正态分布的随机数。
相关问题
torch.randon函数
`torch.rand()`函数是用于生成指定大小的随机张量,张量中的每个元素都是从区间[0,1)的均匀分布中随机采样得到的。该函数的语法格式如下:
```python
torch.rand(*size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor
```
其中,参数`size`表示生成的随机张量的大小,可以是一个整数,也可以是一个元组;参数`out`表示输出张量,如果指定了该参数,则生成的随机张量将被保存到该张量中;参数`dtype`表示输出张量的数据类型,如果不指定,则默认为`torch.float32`;参数`layout`表示输出张量的布局,如果不指定,则默认为`torch.strided`;参数`device`表示输出张量所在的设备,如果不指定,则默认为当前设备;参数`requires_grad`表示输出张量是否需要梯度,如果不指定,则默认为`False`。
以下是一个生成随机张量的例子:
```python
import torch
# 生成一个大小为(2, 3)的随机张量
x = torch.rand(2, 3)
print(x)
```
输出结果如下:
```
tensor([[0.7645, 0.1867, 0.2389],
[0.2766, 0.5474, 0.9477]])
```
import torch import matplotlib.pyplot as plt def features(x): x = x.unsqueeze(1) return torch.cat([x ** i for i in range(1, 5)], 1) x_weight = torch.Tensor([-1.13, -2.14, 3.15, -0.01]).unsqueeze(1) b = torch.Tensor([0.512]) def target(x): return x.mm(x_weight) + b.item() def get_batch_data(batch_size): batch_x = torch.randon(batch_size) features_x = features(batch_x) target_y = target(features_x) return features_x, target_y class PR(torch.nn.Module): def __init__(self): super(PR, self).__init__() self.poly = torch.nn.Linear(4, 1) def forward(self, x): return self.poly(x) epochs = 10000 batch_size = 32 model = PR() criterion = torch.nn.MSELoss() optimizer = torch.optim.SGD(model.parameters(), 0.01) for i in range(epochs): batch_x, batch_y = get_batch_data(batch_size) out = model(batch_x) loss = criterion(out, batch_y) optimizer.zero_grad() loss.backward() optimizer.step() if(epochs % 100 == 0): print(f"Epoch:{i+1}/{epochs}, loss:{loss.item}") if(i%1000 == 0): predict = model(features(batch_x)) plt.plot(batch_x.data.numpy(), predict.squeeze(1).data.numpy(), c="r") loss = criterion(predict, batch_y) plt.title(f"Loss:{loss.item}") plt.xlabel("X") plt.ylabel("Y") plt.scatter(batch_x, batch_y) plt.show()哪里要改
在代码中,有一些小错误:
1. `torch.randon`应该是`torch.rand`,生成随机数的函数名称写错了。
2. `loss.item` 应该是`loss.item()`,需要调用这个方法来得到损失值。
3. 在if语句中,应该是`i % 100 == 0`而不是`epochs % 100 == 0`,因为epochs是循环次数,不会改变,而i是当前循环的次数。
修改后的代码如下:
```
import torch
import matplotlib.pyplot as plt
def features(x):
x = x.unsqueeze(1)
return torch.cat([x ** i for i in range(1, 5)], 1)
x_weight = torch.Tensor([-1.13, -2.14, 3.15, -0.01]).unsqueeze(1)
b = torch.Tensor([0.512])
def target(x):
return x.mm(x_weight) + b.item()
def get_batch_data(batch_size):
batch_x = torch.rand(batch_size) # 将 torch.randon 改为 torch.rand
features_x = features(batch_x)
target_y = target(features_x)
return features_x, target_y
class PR(torch.nn.Module):
def __init__(self):
super(PR, self).__init__()
self.poly = torch.nn.Linear(4, 1)
def forward(self, x):
return self.poly(x)
epochs = 10000
batch_size = 32
model = PR()
criterion = torch.nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), 0.01)
for i in range(epochs):
batch_x, batch_y = get_batch_data(batch_size)
out = model(batch_x)
loss = criterion(out, batch_y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if(i % 100 == 0): # 将 epochs % 100 == 0 改为 i % 100 == 0
print(f"Epoch:{i+1}/{epochs}, loss:{loss.item()}")
if(i % 1000 == 0):
predict = model(features(batch_x))
plt.plot(batch_x.data.numpy(), predict.squeeze(1).data.numpy(), c="r")
loss = criterion(predict, batch_y)
plt.title(f"Loss:{loss.item()}")
plt.xlabel("X")
plt.ylabel("Y")
plt.scatter(batch_x, batch_y)
plt.show()
```