1 Comment
User's avatar
Orith Loeb's avatar

Hi, Here's my solution:

# DDC-42: Softmax function, manual and PyTorch

import numpy as np

import torch

import matplotlib.pyplot as plt

# ---generating the x ---

x = np.linspace (-3, 3, 17)

# ---calculating softmax---

softmax_func = np.exp(x)/sum (np.exp(x))

# ---using torch.softmax function---

# --- convert NumPy array to PyTorch tensor---

x_tensor = torch.tensor (x, dtype = torch.float32)

# Apply softmax

y = torch.softmax(x_tensor, dim=0)

# ---plot---

plt.figure (figsize=(10,6))

plt.plot (x, softmax_func, linestyle = "-", color = "blue", label = "manual")

plt.scatter (x,y, linewidths =2, marker = "o", label= "torch", color = "red")

plt.xlabel ("x")

plt.ylabel (r"$\sigma(x)$")

plt.title ("softmax")

plt.legend()

plt.show()

Expand full comment