PyTorch 实现与追问

题集来源:Alireza Dirafzoon(alirezadir)收录项目:AIMLInterviews查看原题集

题目来源
Devinterview 其中第 85—146 题的题目索引来自 Devinterview,答案由 AIMLInterviews 重新撰写;原文的 50 题补充部分在此收录为 62 道,含拆分追问。

题目目录

156 道原题
  1. Implement the following function without Python loops: ```python def normalize_rows(x: torch.Tensor, eps: float = 1e-8) -> torch.Tensor: """Standardize each row to zero mean and unit variance.""" ... ``` Requirements: - x has shape [batch_size, num_features]. - Preserve x's device and dtype. - Avoid division by zero. - Do not modify x in place.

    原题
  2. What should happen when a row has zero variance?

    原题
  3. How would this change for [B, C, H, W]?

    原题

    此追问承接前面的逐行标准化函数;四维输入未指定归一化的维度。

  4. view, reshape, squeeze, and unsqueeze?

    原题
  5. When can broadcasting be wrong?

    原题
  6. Write a reusable preprocessing component that replaces non-finite values, standardizes features using training statistics, works on CPU or GPU, saves its state, and prevents validation leakage.

    原题
  7. Implement binary precision, recall, and F1 from logits. Inputs may be on GPU, targets may contain only one class, no autograd graph should be created, and the result should contain Python floats.

    原题
  8. Implement one training epoch and a complete evaluation pass with correct modes, gradient handling, device placement, sample-weighted loss, empty-loader behavior, and final predictions.

    原题
  9. Review the following code: ```python def evaluate(model, loader): model.train() losses = [] for x, y in loader: prediction = model(x) loss = torch.nn.CrossEntropyLoss()(prediction, y) losses.append(loss) return torch.tensor(losses).mean().item() ```

    原题
  10. Write a function that splits a sequence into batches while optionally retaining the final incomplete batch.

    原题