When I run this code using IDLE in windows, it spawns a temporary cmd window that disappears shortly thereafter.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.mixture import GaussianMixture
# Step 1: Generate random data
np.random.seed(0)
# Create data from 3 different Gaussian distributions
data1 = np.random.normal(loc=[0, 0], scale=1.0, size=(100, 2))
data2 = np.random.normal(loc=[5, 5], scale=1.0, size=(100, 2))
data3 = np.random.normal(loc=[0, 5], scale=1.0, size=(100, 2))
X = np.vstack([data1, data2, data3]) # Combine into one dataset
# Step 2: Fit a Gaussian Mixture Model
gmm = GaussianMixture(n_components=3, random_state=0)
gmm.fit(X)
# Step 3: Predict the cluster for each point
labels = gmm.predict(X)
# Step 4: Plot the results
plt.figure(figsize=(8, 6))
plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis', s=40)
plt.title("GMM Clustering with 3 Components")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.grid(True)
plt.show()
if I run from cmd directly (python script.py
) then it behaves normally. It appears to be unique to GaussianMixture
- using HDBSCAN
, for example, does not show this behavior. This is particularly annoying in the context of running this from inside a Qt
GUI, since the command window plays havoc with the GUI itself.
Can anyone shed some light on what might be causing the issue, and what can be done about it while still allowing me to run from source directly in IDLE? I am using Python 3.12.10.
Running your code in Anaconda on Windows 10 with MKL (both command line and VSCode, Python 3.12.7 , scikit-learn 1.5.1) I got the warning "UserWarning: KMeans is known to have a memory leak on Windows with MKL, when there are less chunks than available threads. You can avoid it by setting the environment variable OMP_NUM_THREADS=2.".
Setting that environment variable, either at the command line or programmatically, clears up the warning. Your code then works fine and displays the plot.
The warning did not appear when I ran a similar script I developed using HDBSCAN.
I think it likely that the IDLE command window you saw is related to that warning. Setting OMP_NUM_THREADS=2 should clear it up.