Power spectral density shows how the strength of a signal is spread across different frequencies. It helps us understand the main rhythms or patterns in data.
To find the main frequencies in a sound recording.
To analyze heart rate signals to detect irregularities.
To study vibrations in machines for maintenance.
To explore patterns in stock market price changes.
Syntax
SciPy
from scipy.signal import welch
frequencies, power = welch(signal, fs=sample_rate, nperseg=segment_length)
signal is your data array.
fs is the sample rate (how many data points per second).
Examples
Calculate power spectral density with a sample rate of 1000 Hz.
SciPy
frequencies, power = welch(signal, fs=1000)
Calculate PSD with sample rate 500 Hz and segment length 256 points.
SciPy
frequencies, power = welch(signal, fs=500, nperseg=256)
Sample Program
This code creates a signal with two clear frequencies (5 Hz and 20 Hz). It then calculates the power spectral density using the Welch method and prints the first few frequency-power pairs. Finally, it shows a plot of power vs frequency.
SciPy
import numpy as np
from scipy.signal import welch
import matplotlib.pyplot as plt
# Create a signal with two frequencies: 5 Hz and 20 Hz
fs = 100# sample rate, 100 samples per second
T = 2# seconds
x = np.linspace(0, T, T*fs, endpoint=False)
signal = 0.5 * np.sin(2 * np.pi * 5 * x) + 0.3 * np.sin(2 * np.pi * 20 * x)
# Calculate power spectral density
frequencies, power = welch(signal, fs=fs, nperseg=128)
# Print first 5 frequency and power valuesfor f, p inzip(frequencies[:5], power[:5]):
print(f"Frequency: {f:.2f} Hz, Power: {p:.4f}")
# Plot the power spectral density
plt.semilogy(frequencies, power)
plt.title('Power Spectral Density')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Power')
plt.grid(True)
plt.show()
OutputSuccess
Important Notes
The power spectral density helps find hidden frequencies in noisy data.
Choosing nperseg affects frequency resolution and smoothness.
Summary
Power spectral density shows how signal power is spread across frequencies.
Use scipy.signal.welch to calculate it easily.
It helps find important rhythms or cycles in data.
Practice
(1/5)
1. What does the power spectral density (PSD) represent in signal analysis?
easy
A. The phase shift of a signal at various points
B. The total energy of a signal over time
C. How the power of a signal is distributed over different frequencies
D. The amplitude of a signal at a single point in time
Solution
Step 1: Understand the definition of PSD
Power spectral density shows how the power of a signal is spread across frequencies, not just total energy or amplitude at one time.
Step 2: Compare options with PSD meaning
Only How the power of a signal is distributed over different frequencies correctly describes PSD as power distribution over frequencies.
Final Answer:
How the power of a signal is distributed over different frequencies -> Option C
Quick Check:
PSD = power distribution over frequency [OK]
Hint: PSD shows power spread by frequency, not time or phase [OK]
Common Mistakes:
Confusing PSD with total signal energy
Thinking PSD shows amplitude at one time
Mixing PSD with phase information
2. Which of the following is the correct way to import the Welch method for PSD calculation from scipy?
easy
A. from scipy.signal import welch
B. import scipy.welch
C. from scipy import welch
D. import scipy.signal.welch as welch
Solution
Step 1: Recall scipy.signal module structure
The Welch method is inside scipy.signal, so we import it from there.
Step 2: Check import syntax correctness
Only 'from scipy.signal import welch' is valid Python syntax for this function.
Final Answer:
from scipy.signal import welch -> Option A
Quick Check:
Correct import = from scipy.signal import welch [OK]
Hint: Welch is in scipy.signal, import directly from there [OK]
Common Mistakes:
Trying to import welch directly from scipy
Using incorrect import syntax
Assuming welch is a standalone module
3. What will be the output type of the following code snippet?
from scipy.signal import welch
import numpy as np
fs = 100
x = np.sin(2 * np.pi * 10 * np.arange(1000) / fs)
freqs, psd = welch(x, fs)
print(type(freqs), type(psd))
medium
A. (, )
B. (, )
C. (, )
D. (, )
Solution
Step 1: Understand welch output types
The welch function returns two numpy arrays: frequencies and power spectral density values.
Step 2: Check printed types
Printing type(freqs) and type(psd) will show numpy.ndarray for both.
Final Answer:
(<class 'numpy.ndarray'>, <class 'numpy.ndarray'>) -> Option D
Quick Check:
welch returns arrays = numpy.ndarray [OK]
Hint: Welch returns frequency and PSD as numpy arrays [OK]
Common Mistakes:
Expecting lists instead of numpy arrays
Thinking output is a tuple of floats
Confusing output with single float values
4. Identify the error in this code snippet that calculates PSD:
from scipy.signal import welch
import numpy as np
fs = 50
x = np.random.randn(500)
freqs, psd = welch(x)
print(freqs)
medium
A. The print statement should be print(psd) instead
B. Missing sampling frequency (fs) argument in welch call
C. Random data cannot be used with welch
D. Import statement for welch is incorrect
Solution
Step 1: Check welch function call parameters
The welch function needs the sampling frequency (fs) to correctly compute frequencies.
Step 2: Identify missing argument
Here, fs=50 is defined but not passed to welch, causing incorrect frequency calculation.
Final Answer:
Missing sampling frequency (fs) argument in welch call -> Option B
Quick Check:
Pass fs to welch to get correct frequencies [OK]
Hint: Always pass fs to welch for correct frequency output [OK]
Common Mistakes:
Forgetting to pass fs argument
Assuming random data is invalid input
Confusing print output with error
5. You have a noisy signal sampled at 200 Hz. You want to find the dominant frequency component using scipy's Welch method. Which parameter adjustment helps improve frequency resolution in the PSD estimate?
hard
A. Increase the segment length (nperseg) to use longer data chunks
B. Decrease the sampling frequency (fs) to reduce data size
C. Use a smaller window type to reduce computation
D. Set detrend to False to keep original signal shape
Solution
Step 1: Understand frequency resolution in Welch method
Frequency resolution improves with longer segments (nperseg) because it provides finer frequency bins.
Step 2: Evaluate options for improving resolution
Increasing nperseg increases segment length, improving resolution. Decreasing fs reduces max frequency but not resolution. Window type affects leakage, not resolution. Detrend affects baseline, not resolution.
Final Answer:
Increase the segment length (nperseg) to use longer data chunks -> Option A
Quick Check:
Longer nperseg = better frequency resolution [OK]
Hint: Longer segments (nperseg) give finer frequency detail [OK]
Common Mistakes:
Reducing sampling frequency to improve resolution
Confusing window type with resolution effect
Ignoring segment length impact on frequency bins
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.