Saving and loading data (scipy.io) - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When saving or loading data with scipy.io, we want to know how the time needed changes as the data size grows.
We ask: How does the time to save or load data grow when the data gets bigger?
Analyze the time complexity of the following code snippet.
import numpy as np
from scipy import io
data = np.random.rand(1000, 1000) # Create a large array
io.savemat('datafile.mat', {'array': data}) # Save data to a .mat file
loaded = io.loadmat('datafile.mat') # Load data back from the file
This code creates a large array, saves it to a file, and then loads it back into memory.
- Primary operation: Reading or writing each element of the array to or from disk.
- How many times: Once for each element in the array (all 1,000,000 elements).
As the data size grows, the time to save or load grows roughly in proportion to the number of elements.
| Input Size (n x n) | Approx. Operations |
|---|---|
| 10 x 10 | 100 |
| 100 x 100 | 10,000 |
| 1000 x 1000 | 1,000,000 |
Pattern observation: Doubling the size in each dimension multiplies the total operations by the square, so time grows linearly with total elements.
Time Complexity: O(n)
This means the time to save or load data grows directly with the number of elements in the data.
[X] Wrong: "Saving or loading data takes the same time no matter how big the data is."
[OK] Correct: The time depends on how many elements are saved or loaded, so bigger data takes more time.
Understanding how saving and loading time grows helps you handle large datasets efficiently and shows you know how data size affects performance.
"What if we compressed the data before saving? How would the time complexity change?"
Practice
scipy.io.savemat in data science?Solution
Step 1: Understand the function purpose
scipy.io.savematis designed to save Python data into MATLAB's .mat file format.Step 2: Compare options with function use
Only To save Python variables into a MATLAB .mat file correctly describes saving Python variables into a .mat file. Other options describe unrelated tasks.Final Answer:
To save Python variables into a MATLAB .mat file -> Option BQuick Check:
savemat saves data = A [OK]
- Confusing savemat with loadmat
- Thinking savemat loads data
- Assuming it works with CSV files
data.mat using scipy?Solution
Step 1: Identify the correct function for loading .mat files
The function to load MATLAB files in scipy isloadmat.Step 2: Check syntax correctness
data = io.loadmat('data.mat') usesio.loadmat('data.mat'), which is the correct syntax. Other options use incorrect function names.Final Answer:
data = io.loadmat('data.mat') -> Option AQuick Check:
loadmat loads .mat files = A [OK]
- Using savemat to load data
- Using non-existent functions like readmat
- Missing parentheses or quotes
import numpy as np
from scipy import io
arr = np.array([1, 2, 3])
io.savemat('test.mat', {'array': arr})
data = io.loadmat('test.mat')
print(data['array'])Solution
Step 1: Understand how savemat stores arrays
When saving a 1D numpy array,savematstores it as a 2D array with shape (1, n) by default.Step 2: Check the loaded data shape
Loading back withloadmatreturns a 2D array with shape (1, 3), so printing shows [[1 2 3]].Final Answer:
[[1 2 3]] -> Option AQuick Check:
1D array saved as 2D row = [[1 2 3]] [OK]
- Expecting 1D array output
- Confusing row vs column shape
- Assuming KeyError due to wrong key
from scipy import io
my_data = {'x': [1, 2, 3]}
io.savemat('file.mat', my_data)
loaded = io.loadmat('file.mat')
print(loaded['my_data'])Solution
Step 1: Check keys saved in .mat file
The dictionary key 'x' is saved, not the variable name 'my_data'. So loaded dict has key 'x', not 'my_data'.Step 2: Understand the cause of KeyError
Trying to access loaded['my_data'] causes KeyError because that key does not exist.Final Answer:
KeyError because 'my_data' is not a key in loaded dict -> Option CQuick Check:
Access saved keys, not variable names [OK]
- Assuming variable name is key in loaded dict
- Confusing syntax errors with runtime errors
- Expecting automatic key renaming
a and b into a single .mat file and later load them back. Which code correctly saves and loads these arrays so you can access them by their variable names?Solution
Step 1: Save multiple arrays with a dictionary
Use a dictionary with keys as variable names and values as arrays insavemat. io.savemat('multi.mat', {'a': a, 'b': b}) data = io.loadmat('multi.mat') print(data['a'], data['b']) does this correctly.Step 2: Load and access arrays by keys
After loading, access arrays by their keys 'a' and 'b' in the loaded dictionary. io.savemat('multi.mat', {'a': a, 'b': b}) data = io.loadmat('multi.mat') print(data['a'], data['b']) prints them correctly.Final Answer:
io.savemat('multi.mat', {'a': a, 'b': b}) data = io.loadmat('multi.mat') print(data['a'], data['b']) -> Option DQuick Check:
Save/load dict with keys = variable access [OK]
- Passing list instead of dict to savemat
- Trying to access nested keys incorrectly
- Passing multiple args to savemat instead of one dict
