Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- # might need to add path to mingw-w64/bin for cvxopt to work
- # import os
- # os.environ["PATH"] += os.pathsep + ...
- import cvxopt
- def svmlin(X, t, C):
- # Linear SVM Classifier
- #
- # INPUT:
- # X : the dataset (num_samples x dim)
- # t : labeling (num_samples x 1)
- # C : penalty factor for slack variables (scalar)
- #
- # OUTPUT:
- # alpha : output of quadprog function (num_samples x 1)
- # sv : support vectors (boolean) (1 x num_samples)
- # w : parameters of the classifier (1 x dim)
- # b : bias of the classifier (scalar)
- # result : result of classification (1 x num_samples)
- # slack : points inside the margin (boolean) (1 x num_samples)
- #####Insert your code here for subtask 2a#####
- dim = X.shape(1)
- print(dim)
- N = t.size
- print("X",X.shape)
- H = np.zeros((N,N))
- for i in range(0, N):
- for j in range(0, N):
- H[i,j] = t[i]*t[j]*np.dot(X[i]*X[j])
- n = H.shape[1]
- print("n:", H.shape)
- P = cvxopt.matrix(H)
- print("P", P )
- q = cvxopt.matrix((-1)*np.ones(N))
- G = np.vstack([-np.eye(n), np.eye(n)]).astype('double')
- #G = G[:2,:]
- G = cvxopt.matrix(G)
- print("G", G)
- A = t.astype('double')[np.newaxis]
- #A = np.transpose(A)
- #A = np.matrix.transpose(A)
- print(np.size(A))
- print("wtf")
- A = cvxopt.matrix(A)
- print("A", A)
- b = cvxopt.matrix(np.zeros(1))
- z = np.zeros(N)
- c = C *np.ones(N)
- h = (np.hstack([z,c])).astype('double')
- print("h", h.shape, h)
- h = cvxopt.matrix(h)
- print(np.size(b))
- print(b)
- a = cvxopt.solvers.qp(P, q, G, h, A, b)
- print(a["z"])
- print("d")
- alpha = a["x"]
- sv = [None]*N
- for i in range(0,N):
- if a["x"][i]==0:
- sv[i] = False
- else:
- sv[i] = True
- w= np.zeros((1,))
- for i in range(0,N):
- w[0] = w[0] + alpha[i]*t[i]*X[i,0]
- w[1] = w[1] + alpha[i]*t[i]*X[i,1]
- print("w",w)
- b,nm, b1 = 0
- for i in range(0,N):
- if(alpha[i]<C and alpha[i]>0):
- nm = nm+1
- for i in range(0,N):
- b1 = b1 + alpha[i]*t[i]*X[i,0]
- b1 = b1 + alpha[i]*t[i]*X[i,1]
- b1 = b1
- result = 1
- slack = 1
- return alpha, sv, w, b, result, slack
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement