How to Use NumPy for Signal Processing: Simple Guide
You can use
numpy for signal processing by applying its array operations and functions like numpy.fft for Fourier transforms and numpy.convolve for filtering signals. These tools help analyze and modify signals efficiently using simple code.Syntax
Here are some common NumPy functions used in signal processing:
numpy.fft.fft(signal): Computes the Fast Fourier Transform of a signal.numpy.fft.ifft(transformed_signal): Computes the inverse FFT to get back the original signal.numpy.convolve(signal, kernel, mode='same'): Applies convolution to filter or smooth a signal.numpy.abs(): Gets the magnitude of complex numbers, useful after FFT.
python
import numpy as np # FFT syntax transformed = np.fft.fft(signal) # Inverse FFT syntax original = np.fft.ifft(transformed) # Convolution syntax filtered = np.convolve(signal, kernel, mode='same')
Example
This example shows how to create a noisy signal, apply a simple moving average filter using convolution, and analyze its frequency content with FFT.
python
import numpy as np import matplotlib.pyplot as plt # Create a sample signal: sine wave + noise fs = 500 # Sampling frequency in Hz T = 1 # Duration in seconds t = np.linspace(0, T, fs, endpoint=False) signal = np.sin(2 * np.pi * 50 * t) + 0.5 * np.random.randn(fs) # Define a simple moving average filter kernel kernel_size = 5 kernel = np.ones(kernel_size) / kernel_size # Filter the signal using convolution filtered_signal = np.convolve(signal, kernel, mode='same') # Compute FFT of original and filtered signals fft_original = np.fft.fft(signal) fft_filtered = np.fft.fft(filtered_signal) # Frequency axis freq = np.fft.fftfreq(len(t), 1/fs) # Plot time domain signals plt.figure(figsize=(12, 8)) plt.subplot(3,1,1) plt.plot(t, signal, label='Noisy Signal') plt.legend() plt.subplot(3,1,2) plt.plot(t, filtered_signal, label='Filtered Signal', color='orange') plt.legend() # Plot frequency domain magnitude plt.subplot(3,1,3) plt.plot(freq[:fs//2], np.abs(fft_original)[:fs//2], label='Original FFT') plt.plot(freq[:fs//2], np.abs(fft_filtered)[:fs//2], label='Filtered FFT', color='orange') plt.legend() plt.xlabel('Frequency (Hz)') plt.tight_layout() plt.show()
Output
A plot with three graphs: (1) noisy sine wave signal over time, (2) filtered smoother signal over time, (3) magnitude of FFT showing frequency peaks before and after filtering.
Common Pitfalls
Some common mistakes when using NumPy for signal processing include:
- Not using the correct
modeinnp.convolve, which can change the output size unexpectedly. - Forgetting to interpret FFT results correctly, especially the symmetry and scaling of frequencies.
- Applying FFT on non-uniformly sampled data, which leads to incorrect frequency analysis.
- Ignoring the imaginary part of inverse FFT results due to numerical errors.
python
import numpy as np # Wrong convolution mode (output size changes unexpectedly) signal = np.array([1, 2, 3, 4]) kernel = np.array([1, 1]) wrong_conv = np.convolve(signal, kernel, mode='full') # Larger output right_conv = np.convolve(signal, kernel, mode='same') # Same size output print('Wrong convolution output:', wrong_conv) print('Right convolution output:', right_conv)
Output
Wrong convolution output: [1 3 5 7 4]
Right convolution output: [1 3 5 7]
Quick Reference
Here is a quick summary of useful NumPy functions for signal processing:
| Function | Purpose |
|---|---|
| numpy.fft.fft(signal) | Compute frequency spectrum of a signal |
| numpy.fft.ifft(transformed_signal) | Reconstruct signal from frequency data |
| numpy.convolve(signal, kernel, mode='same') | Filter or smooth signals by convolution |
| numpy.abs() | Get magnitude of complex numbers (e.g., FFT results) |
| numpy.linspace(start, stop, num) | Create evenly spaced time or frequency points |
Key Takeaways
Use numpy.fft.fft and numpy.fft.ifft for frequency analysis and signal reconstruction.
Apply numpy.convolve with mode='same' to filter signals without changing their length.
Interpret FFT output carefully, focusing on magnitude and correct frequency bins.
Ensure your signal is uniformly sampled before applying FFT for accurate results.
Use simple kernels like moving averages for basic noise reduction with convolution.