Как получить доступ к выходным переменным из модулей: примеры кода на Python и JavaScript

Для доступа к выходным переменным модулей вы можете использовать разные методы в зависимости от языка программирования или платформы, с которой вы работаете. Вот несколько примеров:

  1. Python (PyTorch):

    import torch
    # Define a module
    class MyModule(torch.nn.Module):
    def __init__(self):
        super(MyModule, self).__init__()
        self.fc = torch.nn.Linear(10, 5)
    def forward(self, x):
        output = self.fc(x)
        return output
    # Create an instance of the module
    module = MyModule()
    # Forward pass
    input_data = torch.randn(1, 10)
    output = module(input_data)
    # Access the output variable
    print(output)
  2. Python (TensorFlow):

    import tensorflow as tf
    # Define a module
    class MyModule(tf.Module):
    def __init__(self):
        super(MyModule, self).__init__()
        self.dense = tf.keras.layers.Dense(5)
    @tf.function
    def __call__(self, x):
        output = self.dense(x)
        return output
    # Create an instance of the module
    module = MyModule()
    # Forward pass
    input_data = tf.random.uniform((1, 10))
    output = module(input_data)
    # Access the output variable
    print(output)
  3. JavaScript (TensorFlow.js):

    const tf = require('@tensorflow/tfjs');
    // Define a module
    class MyModule {
    constructor() {
    this.dense = tf.layers.dense({ units: 5 });
    }
    call(input) {
    const output = this.dense.apply(input);
    return output;
    }
    }
    // Create an instance of the module
    const module = new MyModule();
    // Forward pass
    const input = tf.randomNormal([1, 10]);
    const output = module.call(input);
    // Access the output variable
    output.print();

Эти примеры демонстрируют, как определить модуль, выполнить прямой проход и получить доступ к выходной переменной. Не забудьте адаптировать код к вашему конкретному варианту использования и платформе.