def desenha_grade(ax, valores, x0=0.0, y0=0.0, cor=AZUL, alpha=0.25, tamanho=1.0, texto=True):
"""Desenha uma matriz como uma grade de células, com o canto superior esquerdo em (x0, y0)."""
valores = np.atleast_2d(valores)
linhas, colunas = valores.shape
for i in range(linhas):
for j in range(colunas):
x, y = x0 + j * tamanho, y0 - (i + 1) * tamanho
ax.add_patch(Rectangle((x, y), tamanho, tamanho, facecolor=cor, alpha=alpha, edgecolor=TINTA, lw=1))
if texto:
ax.text(x + tamanho / 2, y + tamanho / 2, f"{valores[i, j]:g}", ha="center", va="center",
color=TINTA, fontsize=10)
escalar = torch.tensor(7)
vetor = torch.tensor([3, 1, 4, 1])
matriz = torch.arange(12).reshape(3, 4)
tensor3d = torch.arange(36).reshape(3, 3, 4)
fig, axes = plt.subplots(1, 4, figsize=(17, 4.2), width_ratios=[0.6, 1.3, 1.3, 1.8])
desenha_grade(axes[0], escalar.numpy(), 0, 1, cor="#cde2fb", alpha=1)
desenha_grade(axes[1], vetor.numpy(), 0, 1, cor="#cde2fb", alpha=1)
desenha_grade(axes[2], matriz.numpy(), 0, 3, cor="#cde2fb", alpha=1)
for k, cor in zip(range(2, -1, -1), ["#bfe9d8", "#f9d0bf", "#cde2fb"]): # desenha do fundo para a frente
desenha_grade(axes[3], tensor3d[k].numpy(), 0.6 * k, 3 + 0.6 * k, cor=cor, alpha=1, texto=(k == 0))
titulos = [f"Escalar (0D)\nshape {tuple(escalar.shape)}", f"Vetor (1D)\nshape {tuple(vetor.shape)}",
f"Matriz (2D)\nshape {tuple(matriz.shape)}", f"Tensor 3D\nshape {tuple(tensor3d.shape)}"]
limites = [(-0.3, 1.3, -0.3, 1.3), (-0.3, 4.3, -0.3, 1.3), (-0.3, 4.3, -0.3, 3.3), (-0.3, 5.7, -0.3, 4.6)]
for ax, titulo, (x0, x1, y0, y1) in zip(axes, titulos, limites):
ax.set(xlim=(x0, x1), ylim=(y0, y1), title=titulo)
ax.set_aspect("equal")
ax.axis("off")
axes[2].annotate("", xy=(4.15, 0), xytext=(4.15, 3), arrowprops={"arrowstyle": "->", "color": TINTA})
axes[2].text(4.25, 1.5, "dim 0\n(linhas)", va="center", fontsize=9, color=TINTA)
axes[2].annotate("", xy=(4, -0.2), xytext=(0, -0.2), arrowprops={"arrowstyle": "->", "color": TINTA})
axes[2].text(2, -0.45, "dim 1 (colunas)", ha="center", va="top", fontsize=9, color=TINTA)
axes[3].text(2.8, 4.45, "dim 0: 3 camadas empilhadas", ha="center", fontsize=9, color=TINTA)
plt.tight_layout()
plt.show()