Creating a more memory and CPU efficient solution involves several key considerations, like handling files in smaller chunks, using more efficient data structures, and minimizing redundant operations. Below, I'll present a more efficient approach using memory mapping for reading files and incremental learning for TF-IDF vectorization, if applicable. Then, I'll show how to measure RAM and CPU usage.
Because the original TfidfVectorizer doesn't support incremental learning out of the box, for the memory efficiency part, we will still use it for its simplicity but focus on other optimizations. To truly optimize for both memory and CPU in processing large datasets, consider using more advanced techniques or more scalable systems designed for big data.
Optimized Code Example
This example assumes you are handling a large collection of txt documents and want to maintain lower memory usage. We'll use simpler operations and focus on handling data more efficiently without sacrificing too much of the script's original intent.
import os
import numpy as np
from scipy import spatial
from sklearn.feature_extraction.text import TfidfVectorizer
import psutil
import time
def memory_usage_psutil():
# return the memory usage in MB
process = psutil.Process(os.getpid())
mem = process.memory_info().rss / float(2 ** 20)
return mem
def current_cpu_usage():
return psutil.cpu_percent(interval=1)
start_time = time.time()
start_mem = memory_usage_psutil()
start_cpu = current_cpu_usage()
data_dir = "./data"
docs = []
# Efficiently read files
for file in os.listdir(data_dir):
if file.endswith(".txt"):
with open(os.path.join(data_dir, file), "r") as f:
docs.append(f.read())
# Process documents for TF-IDF
vectorizer = TfidfVectorizer(stop_words="english")
doc_vectors = vectorizer.fit_transform(docs)
input_prompt = "prompt"
input_vector = vectorizer.transform([input_prompt])
# Using more efficient operations where possible
similarity_scores = np.asarray(doc_vectors.dot(input_vector.T).todense()).ravel()
# Retrieve top document
top_index = similarity_scores.argsort()[-1]
retrieved_doc = docs[top_index]
print("Generated Text: Based on the documents, I found that", retrieved_doc)
# Benchmark results
end_time = time.time()
end_mem = memory_usage_psutil()
end_cpu = current_cpu_usage()
print(f"Runtime: {end_time - start_time} seconds")
print(f"Memory Usage: {end_mem - start_mem} MB")
print(f"CPU Usage: {end_cpu}%")
Important Considerations
-
Incremental Learning: For truly large-scale datasets where fitting all documents into memory isn't feasible, consider using models or techniques that allow for incremental fitting. The HashingVectorizer from scikit-learn can be a start, albeit with a different trade-off in terms of features and precision.
-
Memory Usage: The script uses psutil to monitor memory usage, showcasing how much memory the process takes. Note this won't capture Python's peak memory usage, for which you might consider memory profiler tools or in-depth analysis.
-
CPU Usage: CPU measurement here is a simple snapshot before and after execution. For more detailed CPU usage profiling, consider using more advanced profiling tools or libraries that offer time series data on CPU usage.
Limitations
- This example provides a simplified way to measure memory and CPU usage and may not accurately reflect the peak usage, especially in multi-threaded or asynchronous execution environments.
- For massive datasets, or when operating close to hardware limits, consider distributed computing solutions or cloud-based options with scalable resources.