import numpy as np import cvxpy as cp ## PROBLEM 3 # Create data m = 30 n = 10 np.random.seed(2020) A = np.random.randn(m, n) y = np.random.randn(m) # Set up CVX problem x = cp.Variable(n) objective = cp.Minimize(0.5*cp.norm(A@x - y,2)) constraints = [0 <= x] prob = cp.Problem(objective, constraints) # The optimal objective value is returned by `prob.solve()` result = prob.solve() # The optimal value for x is stored in `x.value` xstar = x.value # The optimal Lagrange multiplier for a constraint is stored in # `constraint.dual_value` lambdastar = constraints[0].dual_value ## PROBLEM 4 # Create data from sklearn import datasets np.random.seed(2020) # Set random seed so results are repeatable x,y = datasets.make_circles(n_samples=100,noise=.05,factor=.5 ) # Create a function h, where h takes as input a vector x and outputs a the # result of an SVM classifier with a quadratic kernel trained on the data above # Plot the decision boundary. import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap # Begin by creating the mesh [x_min, x_max]x[y_min, y_max]. h = .02 # step size in the mesh x_delta = (x[:,0].max() - x[:,0].min())*0.05 # add 5% white space to border y_delta = (x[:,1].max() - x[:,1].min())*0.05 x_min, x_max = x[:,0].min() - x_delta, x[:,0].max() + x_delta y_min, y_max = x[:,1].min() - y_delta, x[:,1].max() + y_delta xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) #Z = h(np.c_[xx.ravel(), yy.ravel()]) # Create color maps cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA']) cmap_bold = ListedColormap(['#FF0000', '#00FF00']) plt.figure() # Put the classifier results #Z = Z.reshape(xx.shape) #plt.pcolormesh(xx, yy, Z, cmap=cmap_light) # Plot the training points plt.scatter(x[:,0], x[:,1], c=y, cmap=cmap_bold) # Show the plot plt.xlim(xx.min(), xx.max()) plt.ylim(yy.min(), yy.max()) plt.title("SVM classifier") plt.show() ## PROBLEM 5 # Construct the problem N = 1000 # Population size S = 10 # Number of infected individuals M = 100 # Number of tests K = 10 # Number of splits of each sample # Define x0 ind0 = np.random.choice(N,S,0) # index subset x0 = np.zeros(N) x0[ind0] = np.random.rand(S) # Define A A = np.zeros((M,N)) for i in np.arange(N): ind = np.random.choice(M,K,0) A[ind,i] = 1 y = A @ x0