Python ValueError:操作数无法与形状一起广播(180,180)(100,100)

时间:2018-06-11 15:58:06

标签: python

为什么我收到此错误?不知道为什么会这样。出现在我正在训练的视频中。我按照书籍做了2个变量的外部数组。这是代码行:P = cvxopt.matrix(np.outer(y,y)* K)。所以我根据位置参数配置了2个项目。

#!/usr/bin/env python3
import numpy as np
import cvxopt
import cvxopt.solvers
from numpy import linalg

def linear_kernel (x1,x2):
    return np.dot(x1, x2)

def polynominal_kernel(x,y,p=3):
    return(1+np.dot(x,y))**p
def gaussian_kernel(x, y, sigma=5.0):
    return np.exp(-linalg.norm(x-y)**2 / (2*(sigma**2)))

class SVM(object):
    def  __init__(self, kernel=linear_kernel, C=None):
        self.kernel=kernel
        self.C=C
        if self.C is not None: self.C = float(self.C)

    def fit(self, X, y):
        n_samples, n_features= X.shape

        K=np.zeros((n_samples, n_samples))
        for i in range(n_samples):
            for j in range (n_samples):
                K[i,j]=self.kernel(X[i], X[j])

        P=cvxopt.matrix(np.outer(y, y) * K)
        q=cvxopt.matrix(np.ones(n_samples) * -1)
        A=cvxopt.matrix(y, (1,n_samples))
        b=cvxopt.matrix(0.0)

        if self.C is None:
            G=cvxopt.matrix(np.diag(np.ones(n_samples)*-1))
            h=cvxopt.matrix(np.diag(np.zeros(n_samples)))
        else:
            tmp1=   np.diag(np.ones(n_samples)*-1)
            tmp2=np.identity(n_samples)
            G=cvxopt.matrix(np.vstack((tmp1,tmp2)))
        solution=cvxopt.solvers.qp(P,q,G,h,A,b) 
        a=np.ravel(solution['x'])

        sv=a>1e-5
        ind=np.arange(len(a)) [sv]
        self.a =a[sv]
        self.sv=X[sv]
        self.sv_y=y[sv]
        print("%d support vectors out of %d points" %(len(self.a), n_samples))

        self.b=0
        for n in range(len(self.a)):
            self.b +=self.sv_y[n]
            self.b -=np.sum(self.a*self.sv_y*K[ind[n],sv])
        self.b /=len(self.a)

        if self.kernel==linear_kernel:
            self.w=np.zeros(n_features)
            for n in range (len(self.a)):
                self.w +=self.a[n]*self.sv_y[n]*self.sv[n]
            else:
                self.w=None

0 个答案:

没有答案