Skip to content

Instantly share code, notes, and snippets.

@Lxnus
Last active March 7, 2023 23:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lxnus/f5368ed8bdd76744866e8df385cf9303 to your computer and use it in GitHub Desktop.
Save Lxnus/f5368ed8bdd76744866e8df385cf9303 to your computer and use it in GitHub Desktop.
Interpolation & Convolution.
import numpy as np
import torch
import matplotlib.pyplot as plt
# Create a tensor
a = torch.tensor(data=[0, 0, -3, -1, 1, 3, 0, 0, 0], dtype=torch.float)
b = torch.tensor(data=[0, 0.5, 1.5, 3, 3.5, 3, 1.5, 0.5, 0], dtype=torch.float)
# We need a 3d tensor for interpolation
a = a.unsqueeze(0).unsqueeze(0)
b = b.unsqueeze(0).unsqueeze(0)
# Interpolate a and b for better convolution resolution
a = torch.nn.functional.interpolate(
input=a,
size=1000,
mode='linear'
).squeeze(0).squeeze(0)
b = torch.nn.functional.interpolate(
input=b,
size=1000,
mode='linear'
)
# Squeeze the tensor back to 1d
a = a.squeeze(0).squeeze(0)
b = b.squeeze(0).squeeze(0)
# Do a convolution: a * b
c = np.convolve(
a=a.numpy(),
v=b.numpy(),
mode='same'
)
# Plot the original data
plt.plot(a, 'r')
plt.plot(b, 'g')
plt.show()
# Plot the convolution
plt.plot(c, 'b')
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment