无法将大小为1的数组重塑为形状(958,681)

时间:2019-04-28 11:41:40

标签: python euclidean-distance centroid

研究代码以产生最接近的质心分类。卡在方法和错误上。该代码应在随机数据上运行并显示NCC分类器的分类。通过fit_ncc方法,我得到了欧氏距离的mu;通过predict_ncc我应该得到了实际的欧氏距离。欧氏距离使make_plotn_clase向我显示了质心。

def make_data_twoclass(N=100):
    # generates some toy data
    mu = np.array([[0,3],[0,-3]]).T
    n_samples_per_class = int(N/2)
    C = np.array([[5.,4.],[4.,5.]])
    X = np.hstack((
            mvn(mu[:,0],C,n_samples_per_class).T, 
            mvn(mu[:,1],C,n_samples_per_class).T
        ))
    y = np.hstack((np.zeros((n_samples_per_class)),(np.ones((n_samples_per_class)))))
    return X.T,y.T

#get the mu
def fit_ncc(X,Y):

    zwischen=[]
    for i in range(50):
        zwischen.append(X[i])

    zwischen2=[]
    for i in range(50,100):
        zwischen2.append(X[i])


    mu1=[0.5*np.sum(zwischen,axis=0)]
    mu2=[0.5*np.sum(zwischen2,axis=0),1]
    mug=[]
    mug.append(mu1)
    mug.append(mu2)


    print(mu1)
    mu=[]
    mu=mu1[0]
    print(mu1[0])
    print(X.shape)



    #mu
    return mu
#get the euclidean distance
def predict_ncc(X,mu):

    for i in range(len(X)):
        for j in range(len(X[i])):
            Y_predicted=np.sqrt((X[i]-mu[0])**2+(X[j]-mu[1])**2)

            return Y_predicted[0]

def make_plot_nclass(X,y,mu=None):
    colors = "brymcwg"

    if mu is not None:
        # Plot the decision boundary.
        h = .02 # stepsize in mesh
        x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
        y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
        xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                         np.arange(y_min, y_max, h))
        Z = predict_ncc(np.c_[xx.ravel(), yy.ravel()],mu)
        Z = Z.reshape(xx.shape)
        cs = pl.contourf(xx, yy, Z, cmap=pl.cm.Paired,alpha=.6)

    # plot the data
    for class_idx, class_name in enumerate(np.unique(y)):
        idx = y == class_name
        pl.plot(X[idx, 0], X[idx, 1], colors[int(class_idx)%6]+'o')
        if mu is not None:
            pl.plot(mu[class_idx, 0],mu[class_idx, 1],colors[int(class_idx)%6]+'o',markersize=20)

    pl.axis('tight')
    pl.xlabel('$X_1$')
    pl.ylabel('$X_2$')  


pl.subplot(1,3,2)
X, Y = make_data_twoclass()
mu = fit_ncc(X,Y)
make_plot_nclass(X, Y,mu)
pl.title('Correlated features two class')

make_plot-nclass函数无需使用mu。但是,如果没有亩,我当然不会得到质心,

0 个答案:

没有答案