pytorch中的tf.keras.Input()等价物是什么


有人能告诉我pytorch中的tf.keras.Input((的等价物是什么吗?

在文件中,它说;启动Keras张量";,那么它只是创建了一个新的空张量吗?

感谢

PyTorch中没有与Keras的输入等效的东西。您所要做的就是将输入作为张量传递给PyTorch模型。

例如:如果你使用Conv网络:


# Keras Code
input_image = Input(shape=(32,32,3)) # An input image of 32x32x3 (HxWxC)
feature = Conv2D(16, activation='relu', kernel_size=(3, 3))(input_image)
# PyTorch code
input_tensor = torch.randn(1, 3, 32, 32) # An input tensor of shape BatchSizexChannelsxHeightxWidth
feature = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=(2, 2))(input_tensor)

如果是正常的致密层:

# Keras
dense_input = Input(shape=(1,))
features = Dense(100)(dense_input)
# PyTorch
input_tensor = torch.tensor([10]) # A 1x1 tensor with value 10
features = nn.Linear(1, 100)(input_tensor)

我创建一个自定义层来检查我的InputTensorShapeDeviceDtype,并像Tensorflow 一样使用它

from torch.nn import Module
class Input(Module):
def __init__(self, shape : tuple, device=torch.device('cpu'), dtype=torch.float32):

super().__init__()
self.shape = shape
self.device = device
self.dtype = dtype
def forward(self, x):
tensor_shape = tuple(x.shape[1:])
if x.device != self.device:
raise ValueError(f"Input tensor must be on device {self.device} but got device {x.device} instead")
if x.dtype != self.dtype:
raise ValueError(f"Input tensor must have data type {self.dtype} but got data type {x.dtype} instead")
if tensor_shape != self.shape:
raise ValueError(f"Input shape must be {self.shape} but got {tensor_shape} instead")

return (x.to(self.device, self.dtype))

使用子类模块

from torch.nn import Module
from torch.nn import Linear
from torch.nn import ReLU, Sigmoid
from torch import Tensor
INPUT_FEATURES = X.shape[1]

class TestModel(Module):
def __init__(self):
super().__init__()
self.InputLayer = Input(shape=(INPUT_FEATURES,))
self.HiddenLayer = Linear(in_features=INPUT_FEATURES, 
out_features=10)
self.ReLU = ReLU()
self.Sigmoid = Sigmoid()
self.OutputLayer = Linear(in_features=10,
out_features=1)

def forward(self, x : Tensor):
x = self.InputLayer(x)
z = self.HiddenLayer(x)
a = self.ReLU(z)
z = self.OutputLayer(a)
output = self.Sigmoid(z)
return (output)

按顺序使用

from torch.nn import Linear
from torch.nn import ReLU, Sigmoid
from torch.nn import Sequential
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
dtype = torch.float32
model = Sequential(
Input(shape=(2,), device=device, dtype=dtype),
Linear(2, 5),
ReLU(),
Linear(5, 1),
Sigmoid()
)

我希望它能有所帮助;(

最新更新