Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Broadcasting #3

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open

Broadcasting #3

wants to merge 3 commits into from

Conversation

shahin1009
Copy link

Using broadcasting to subtract the average face from the training faces, makes the code more readable.
X = trainingFaces - np.tile(avgFace,(trainingFaces.shape[1],1)).T
to:
X = trainingFaces - avgFace.reshape(-1,1).

avgFace.reshape(-1,1) is an array with shape=(32256,1). For conducting the subtraction, numpy would broadcast this array to (322561,n) so the shape become equal to trainingFaces.shape.

@shahin1009
Copy link
Author

cvxpy pakage can manage the L1-norm optimization much faster than SLSQP method in scipy. The process of defining the problem is the same but I add comments to make it more readable.

more detail on CVXPY pakage:
https://pypi.org/project/cvxpy/

import cvxpy as cp
import numpy as np
import matplotlib.pyplot as plt

# defining parameters same as in the previous example
n = 1000 # dimension of s
p = 200 # number of measurements, dim(y)
Theta = np.random.randn(p,n)
y = np.random.randn(p)

# Creating cvxpy variables(the variable that we want to optimize)
s = cp.Variable(n) # s is the variable that we want to optimize

# Creating constraints (y = Theta * s)
constr = [Theta @ s == y] # y = Theta * s

# creating objective
obj = cp.norm(s,1) # minimize the L1 norm of s

# Solving the problem
prob = cp.Problem(cp.Minimize(obj),constr)
prob.solve()

s_L1_cvxpy = s.value # s_L1_cvxpy is the optimized solution
s_L2 = np.linalg.pinv(Theta) @ y # L2 solution from before

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant