在《Python数据科学手册》的第308页,如果按照书上写的代码运行
from sklearn.mixture import GMM # 1. Choose the model class
model = GMM(n_components=3,
covariance_type='full') # 2. Instantiate the model with hyperparameters
model.fit(X_iris) # 3. Fit to data. Notice y is not specified!
y_gmm = model.predict(X_iris) # 4. Determine cluster labels
会出现如下报错
ImportError Traceback (most recent call last)
<ipython-input-2-df85f2dd883f> in <module>
----> 1 from sklearn.mixture import GMM # 1. Choose the model class
2 model = GMM(n_components=3,
3 covariance_type='full') # 2. Instantiate the model with hyperparameters
4 model.fit(X_iris) # 3. Fit to data. Notice y is not specified!
5 y_gmm = model.predict(X_iris) # 4. Determine cluster labels
ImportError: cannot import name 'GMM' from 'sklearn.mixture'
这是因为导入高斯混合模型的代码不对,应该改为如下:
from sklearn.mixture import GaussianMixture #选择模型类
之后:
model =GaussianMixture(n_components = 3,covariance_type='full') #设置超参数,初始化模型
model.fit(X_iris) #拟合数据,注意不需要Y变量
y_gmm = model.predict(X_iris) #确定簇标签
#将簇标签添加到鸢尾花的DataFrame中,然后用Seaborn画出结果
iris['cluster'] = y_gmm
sns.lmplot("PCA1","PCA2",data=iris,hue='species',col='cluster',fit_reg=False)
就可以正确运行如下
这样问题就解决了
如果各位觉着有用的话劳您动动小手给我点个赞,谢谢啦