問題:有人可以幫助我調整這兩種資料生成方法,以便下面的 nn-model 可以使用它們嗎?當使用 appraoch (2)numpy并torch.from_numpy(x)發生運行時錯誤(“預期的標量型別 Float 但發現 Double ”)
對于資料生成,我有以下兩種方法:
import torch
import torch.nn as nn
import numpy as np
def get_training_data_1():
x = torch.randn(batch_size, n_in)
y = torch.tensor([[1.0], [0.0], [0.0], [1.0], [1.0], [1.0], [0.0], [0.0], [1.0], [1.0]])
return x,y
def get_training_data_2():
x = np.random.rand(batch_size, n_in)
y = np.array([[1.0], [0.0], [0.0], [1.0], [1.0], [1.0], [0.0], [0.0], [1.0], [1.0]])
x = torch.from_numpy(x)
y = torch.from_numpy(y)
return x,y
n_in, n_h, n_out, batch_size = 2, 5, 1, 10
x, y = get_training_data_2()
使用此模型numpy時,我在使用方法(2)和時遇到問題torch.from_numpy(x),而使用方法(1)時可以
#---- Create a NN-model
model = nn.Sequential( nn.Linear(n_in, n_h), # hidden layer
nn.ReLU(), # activation layer
nn.Linear(n_h, n_out), # output layer
nn.Sigmoid() ) # final 0, 1 rounding
#---- Construct the loss function
criterion = torch.nn.MSELoss()
#---- Construct the optimizer (Stochastic Gradient Descent in this case)
optimizer = torch.optim.SGD(model.parameters(), lr = 0.1)
#---- Gradient Descent
for epoch in range(1501):
y_pred = model(x) # Forward pass: Compute predicted y by passing x to the model
loss = criterion(y_pred, y) # Compute and print loss
if epoch%50 == 0:
print(epoch, loss.item())
optimizer.zero_grad() # Zero gradients, perform a backward pass, and update the weights.
loss.backward() # perform a backward pass (backpropagation)
optimizer.step() # Update the parameters
uj5u.com熱心網友回復:
默認的浮點型別torch是float32(即單精度)。在 NumPy 中,默認值為float64(雙精度)。嘗試更改get_training_data_2,以便在將 numpy 陣列numpy.float32轉換為 Torch 張量之前顯式設定它們的資料型別:
def get_training_data_2():
x = np.random.rand(batch_size, n_in).astype(np.float32)
y = np.array([[1.0], [0.0], [0.0], [1.0], [1.0], [1.0], [0.0], [0.0], [1.0], [1.0]],
dtype=np.float32)
x = torch.from_numpy(x)
y = torch.from_numpy(y)
return x,y
筆記。使用較新的 NumPy 隨機 API,您可以float32直接生成樣本,而不是將float64值轉換為float32.
def get_training_data_2(rng):
x = rng.random(size=(batch_size, n_in), dtype=np.float32)
y = np.array([[1.0], [0.0], [0.0], [1.0], [1.0], [1.0], [0.0], [0.0], [1.0], [1.0]],
dtype=np.float32)
x = torch.from_numpy(x)
y = torch.from_numpy(y)
return x,y
rng = np.random.default_rng()
x, y = get_training_data_2(rng)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/436258.html
上一篇:如何將[('US',144),('CA',37)]轉換為['US','CA']
下一篇:谷歌colab記憶體問題
