首页 > 解决方案 > Python 分类器

问题描述

我开始了 python 的职业生涯。我无法处理这个问题

我的代码:

import pandas as pd
import numpy as np
from sklearn.naive_bayes import GaussianNB
import matplotlib.pyplot as plt
dFrame=pd.read_csv('...', header='infer', sep=" ")
#importing the necessary packages
from sklearn.model_selection import train_test_split
feature_cols=["Attr1", "Attr2", "Attr3", "Attr4"]
X=dFrame[feature_cols]
y=dFrame['Decision']
y=dFrame.Decision
X_train, X_test, y_train, y_test = train_test_split(X,y)
NB = GaussianNB()
NB.fit(X_train, y_train)
y_predict = NB.predict(X_test)
print("Accuracy NB: {:.2f}".format(NB.score(X_test, y_test)))

print("Means:", NB. theta_ )
print("Standard deviations:" , NB.sigma_ )
print(X_train)
print(y_train)
def plot_ellipse ( ax , mu , sigma , color = "k" , label = None ):

    import matplotlib.patches
# Compute eigenvalues and associated eigenvectors
    vals , vecs =np.linalg.eigh(sigma)

    # Compute "tilt" of ellipse using first eigenvector
    x , y = vecs[:, 0]
    theta = np.degrees (np.arctan2 ( y , x ))

 # Eigenvalues give length of ellipse along each eigenvector
    w,h = 2 * np.sqrt ( vals )
    ax . tick_params ( axis = 'both' , which = 'major' , labelsize = 20 )
    ellipse = matplotlib.patches.Ellipse ( mu, w, h, theta, color = color, label = label )  # color="k")
    ellipse . set_clip_box ( ax . bbox )
    ellipse . set_alpha ( 0.2 )
    ax . add_artist ( ellipse )
    return ellipse

错误文字:

Traceback (most recent call last):
  File "D:/PhytonProjekty/untitled/proba.py", line 47, in <module>
    plot_ellipse (plt.gca (),NB.theta_[0], np.identity(2)*NB.sigma_[0],color = "red" )
ValueError: operands could not be broadcast together with shapes (2,2) (4,) 

数据表: 在此处输入图像描述 谢谢您的帮助

标签: pythonpandasplotscikit-learnclassification

解决方案


错误在np.identity(2)*NB.sigma_[0].

你有四个特点所以,NB.sigma_[0]是形状(4,)。您想(2, 2)通过使用将它与形状的单位矩阵相乘np.identity(2)。所以矩阵乘法不起作用,因此出现错误。

你想做类似的事情吗

np.identity(4)*NB.sigma_[0]

?


推荐阅读