Bird
Raised Fist0
Signal Processingdata~7 mins

Short-Time Fourier Transform (STFT) in Signal Processing

Choose your learning style10 modes available
Introduction

The Short-Time Fourier Transform helps us see how the frequencies in a signal change over time. It breaks a long signal into small pieces and finds the frequencies in each piece.

Analyzing how the pitch of a song changes over time.
Detecting spoken words in an audio recording.
Finding patterns in heartbeats from medical signals.
Monitoring machine sounds to detect faults over time.
Syntax
Signal Processing
STFT(signal, window, step_size, n_fft)

# signal: the input signal array
# window: the size of each small piece
# step_size: how much to move the window each time
# n_fft: number of points for the Fourier transform

The window size controls the time resolution and frequency resolution trade-off.

Step size controls how much the window moves forward each time, affecting overlap.

Examples
Compute STFT with window size 256, moving 128 samples each step, and 256 FFT points.
Signal Processing
stft_result = STFT(signal, window=256, step_size=128, n_fft=256)
Use a larger window for better frequency detail but less time detail.
Signal Processing
stft_result = STFT(signal, window=512, step_size=256, n_fft=512)
Sample Program

This code creates a signal with two different frequencies in two time halves. It then calculates the STFT and shows how frequency content changes over time in a color plot.

Signal Processing
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import stft

# Create a sample signal: 2 seconds, 1000 Hz sample rate
fs = 1000
T = 2
t = np.linspace(0, T, T*fs, endpoint=False)

# Signal with two frequencies changing over time
signal = np.sin(2*np.pi*50*t) * (t < 1) + np.sin(2*np.pi*120*t) * (t >= 1)

# Compute STFT
f, time_segments, Zxx = stft(signal, fs=fs, window='hann', nperseg=256, noverlap=128)

# Plot the magnitude of STFT
plt.pcolormesh(time_segments, f, np.abs(Zxx), shading='gouraud')
plt.title('STFT Magnitude')
plt.ylabel('Frequency [Hz]')
plt.xlabel('Time [sec]')
plt.colorbar(label='Magnitude')
plt.tight_layout()
plt.show()
OutputSuccess
Important Notes

STFT gives a 2D view: time on one axis, frequency on the other.

Choosing window size is a balance: smaller windows show time changes better, larger windows show frequency details better.

Summary

STFT breaks a signal into small time pieces and finds frequencies in each piece.

It helps us see how frequencies change over time in signals like audio or sensor data.

Window size and step size affect the detail and smoothness of the analysis.

Practice

(1/5)
1. What is the main purpose of the Short-Time Fourier Transform (STFT) in signal processing?
easy
A. To compress a signal into fewer data points
B. To analyze how frequencies change over time in a signal
C. To remove noise from a signal completely
D. To convert a signal from digital to analog form

Solution

  1. Step 1: Understand STFT function

    STFT breaks a signal into small time segments and finds frequency content in each segment.
  2. Step 2: Identify main goal

    This helps us see how frequencies change over time, unlike a normal Fourier transform which shows overall frequencies.
  3. Final Answer:

    To analyze how frequencies change over time in a signal -> Option B
  4. Quick Check:

    STFT = frequency changes over time [OK]
Hint: STFT = frequency analysis in short time windows [OK]
Common Mistakes:
  • Confusing STFT with noise removal
  • Thinking STFT compresses data
  • Mixing STFT with analog conversion
2. Which of the following is the correct Python function call to compute STFT using the scipy library on a signal array named signal with a window size of 256?
easy
A. scipy.stft(signal, nperseg=256)
B. scipy.stft(signal, window=256)
C. scipy.signal.fft(signal, window=256)
D. scipy.signal.stft(signal, nperseg=256)

Solution

  1. Step 1: Recall scipy STFT syntax

    The STFT function is in scipy.signal as stft(), and the window size is set by nperseg parameter.
  2. Step 2: Match correct syntax

    scipy.signal.stft(signal, nperseg=256) uses scipy.signal.stft(signal, nperseg=256), which is correct syntax.
  3. Final Answer:

    scipy.signal.stft(signal, nperseg=256) -> Option D
  4. Quick Check:

    Correct function and parameter = scipy.signal.stft(signal, nperseg=256) [OK]
Hint: Use scipy.signal.stft with nperseg for window size [OK]
Common Mistakes:
  • Using scipy.stft instead of scipy.signal.stft
  • Confusing fft() with stft()
  • Passing window size as 'window' instead of 'nperseg'
3. Given the following Python code using scipy.signal.stft, what is the shape of the output array Zxx?
import numpy as np
from scipy.signal import stft
signal = np.sin(2 * np.pi * 5 * np.linspace(0, 1, 100))
f, t, Zxx = stft(signal, nperseg=20)
print(Zxx.shape)
medium
A. (11, 6)
B. (20, 5)
C. (50, 2)
D. (10, 10)

Solution

  1. Step 1: Calculate frequency bins

    With nperseg=20, frequency bins = nperseg//2 + 1 = 10 + 1 = 11 rows.
  2. Step 2: Calculate time segments

    Signal length=100, window=20, default no overlap means about 6 segments (100/20 rounded up).
  3. Final Answer:

    (11, 6) -> Option A
  4. Quick Check:

    Zxx shape = (freq bins, time segments) = (11, 6) [OK]
Hint: Output shape = (nperseg/2+1, number of windows) [OK]
Common Mistakes:
  • Confusing nperseg with output shape rows
  • Miscounting time segments
  • Assuming output shape equals input length
4. Identify the error in this STFT code snippet and choose the correct fix:
from scipy.signal import stft
signal = [1, 2, 3, 4, 5]
f, t, Zxx = stft(signal, nperseg=10)
print(Zxx)
medium
A. Error: nperseg is larger than signal length; fix by setting nperseg=5
B. Error: signal must be a numpy array; fix by converting signal to np.array(signal)
C. Error: stft requires window parameter; fix by adding window='hann'
D. No error; code runs fine

Solution

  1. Step 1: Check nperseg vs signal length

    Signal length is 5, but nperseg=10 is larger, which causes a warning or error in scipy.
  2. Step 2: Fix nperseg value

    Set nperseg to 5 or less to match signal length and avoid error.
  3. Final Answer:

    Error: nperseg is larger than signal length; fix by setting nperseg=5 -> Option A
  4. Quick Check:

    nperseg ≤ signal length to avoid error [OK]
Hint: nperseg must not exceed signal length [OK]
Common Mistakes:
  • Ignoring nperseg size error
  • Thinking signal type causes error
  • Adding unnecessary window parameter
5. You want to analyze a music clip with fast-changing notes using STFT. Which combination of window size and overlap will give you better time resolution but less frequency resolution?
hard
A. Large window size with high overlap
B. Large window size with low overlap
C. Small window size with high overlap
D. Small window size with low overlap

Solution

  1. Step 1: Understand window size effect

    Small window size improves time resolution but reduces frequency resolution.
  2. Step 2: Understand overlap effect

    High overlap keeps time segments close, improving time detail further.
  3. Final Answer:

    Small window size with high overlap -> Option C
  4. Quick Check:

    Better time resolution = small window + high overlap [OK]
Hint: Small window + high overlap = better time detail [OK]
Common Mistakes:
  • Choosing large window for better time resolution
  • Ignoring overlap effect
  • Assuming low overlap improves time resolution
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard