using PyPlot, Convex, ECOS
srand(323)
#srand(999)
U,V,K = loaddata(100)
n = length(V)
X = [ones(n) U]
y = V
y[V.==2] = -1
U_p = U[y.==1,:]
U_n = U[y.==-1,:]
## least squares classifier
theta = Variable(3);
obj = sumsquares(1-y.*(X*theta)) + 0.1*sumsquares(theta[2:end])
#obj = sumsquares(X*theta-y) + 0.1*sumsquares(theta[2:end])
problem = minimize(obj)
solve!(problem, ECOSSolver())
theta_opt = evaluate(theta)
# separating plane
s1 = -5:0.1:5
s2 = - ( theta_opt[1] + s1*theta_opt[2] ) / theta_opt[3]
s2p = - ( 1 + theta_opt[1] + s1*theta_opt[2] ) / theta_opt[3]
s2n = - ( -1 + theta_opt[1] + s1*theta_opt[2] ) / theta_opt[3]
s2_ls = s2
figure()
plot(U_p[:,1], U_p[:,2], "o", alpha=0.5)
plot(U_n[:,1], U_n[:,2], "v", alpha=0.5)
plot(s1,s2)
plot(s1,s2p, ":")
plot(s1,s2n, ":")
grid("on")
axis("square")
xlim(-5, 5)
ylim(-5, 5)
title("Least squares classifier")
## logistic regression
theta = Variable(3);
obj = logisticloss(-y.*(X*theta)) + 0.1*sumsquares(theta[2:end])
problem = minimize(obj)
solve!(problem, ECOSSolver())
theta_opt = evaluate(theta)
# separating plane
s1 = -5:0.1:5
s2 = - ( theta_opt[1] + s1*theta_opt[2] ) / theta_opt[3]
s2_lr = s2
figure()
plot(U_p[:,1], U_p[:,2], "o", alpha=0.5)
plot(U_n[:,1], U_n[:,2], "v", alpha=0.5)
plot(s1,s2)
grid("on")
axis("square")
xlim(-5, 5)
ylim(-5, 5)
title("Logistic regression")
## support vector machine
theta = Variable(3);
obj = sum(max(0,1-y.*(X*theta))) + 0.1*sumsquares(theta[2:end])
problem = minimize(obj)
solve!(problem, ECOSSolver())
theta_opt = evaluate(theta)
# separating plane
s1 = -5:0.1:5
s2 = - ( theta_opt[1] + s1*theta_opt[2] ) / theta_opt[3]
s2p = - ( 1 + theta_opt[1] + s1*theta_opt[2] ) / theta_opt[3]
s2n = - ( -1 + theta_opt[1] + s1*theta_opt[2] ) / theta_opt[3]
s2_svm = s2
figure()
plot(U_p[:,1], U_p[:,2], "o", alpha=0.5, label="Positive data")
plot(U_n[:,1], U_n[:,2], "v", alpha=0.5, label="Negative data")
plot(s1,s2, label=L"$\theta^Tx=0$")
plot(s1,s2p, ":", label=L"$\theta^Tx=-1$")
plot(s1,s2n, ":", label=L"$\theta^Tx=1$")
grid("on")
axis("square")
legend()
xlim(-5, 5)
ylim(-5, 5)
title("Support vector machine")
figure()
plot(U_p[:,1], U_p[:,2], "o", alpha=0.5, label="Positive data")
plot(U_n[:,1], U_n[:,2], "v", alpha=0.5, label="Negative data")
plot(s1,s2_ls, label="Least squares classifier")
plot(s1,s2_lr, label="Logistic regression")
plot(s1,s2_svm, label="Support vector machine")
grid("on")
axis("square")
legend()
xlim(-5, 5)
ylim(-5, 5)