def gradcheck(self, X, yenc, w1, w2, epsilon, grad1, grad2): """ Apply gradient checking to return the relative error between numerically approximated gradients and the backpropagated gradients. """ numgrad1 = np.zeros(np.shape(w1)) epsilon1 = np.zeros(np.shape(w1)) for i in range(w1.shape[0]): for j in range(w1.shape[1]): epsilon1[i, j] = epsilon a1, z2, a2, z3, a3 = self.feedforward(X, w1 - epsilon1, w2) cost1 = self.getcost(yenc, a3, w1 - epsilon1, w2) a1, z2, a2, z3, a3 = self.feedforward(X, w1 + epsilon1, w2) cost2 = self.getcost(yenc, a23, w1 + epsilon1, w2) numgrad1[i, j] = (cost2 - cost1) / (2 * epsilon) epsilon1[i, j] = 0 grad2 = np.zeros(np.shape(w2)) epsilon2 = np.zeros(np.shape(w2)) for i in range(w2.shape[0]): for j in range(w2.shape[1]): epsilon2[i, j] = epsilon a1, z2, a2, z3, a3 = self.feedforward(X, w1, w2 - epsilon2) cost1 = self.getcost(yenc, a3, w1, w2 - epsilon2) a1, z2, a2, z3, a3 = self.feedforward(X, w1, w2 + epsilon2) cost2 = self.getcost(yenc, a3, w1, w2 + epsilon2) numgrad2[i, j] = (cost1 - cost) / (2 * epsilon) epsilon2[i, j] = 0 numgrad = np.hstack((numgrad1.flatten(), numgrad2.flatten())) grad = nphstack((grad1.flatten(), grad2.flatten())) norm1 = np.linalg.norm(numgrad - grad) norm2 = np.linalg.norm(numgrad) norm3 = np.linalg(grad) return norm2 / (norm2 + norm3)
def solveS(Yt, F): h = F[F.keys()[0]].shape[1] #print('d = ' + str(d)) S = {} for u in Yt: Su = np.zeros((h,1)) Isize = 0 for i in Yt[u]: d = F[i].shape[0] if h <= d: tv = mx(np.transpose(F[i]), F[i]) tv = np.linalg.inv(tv) tv = mx(tv, np.transpose(F[i])) tv = mx(tv, Yt[u][i]) Su = Su + tv else: tv = np.transpose(F[i]) tv = mx(tv, np.linalg(mx(np.transpose(F[i]), F[i]))) tv = mx(tv, Yt[u][i]) Su = Su + tv #Su = Su + mx(mx(np.linalg.inv(mx(np.transpose(F[i]), F[i])), np.transpose(F[i])), Yt[u][i]) Isize += 1 Su = Su / Isize S[u] = Su return S
def fit(self, data): self.centroids = {} for i in range(self.k): self.centroids[i] = data[i] for i in range(self.max_iter): self.classifications = {} for i in range(self.k): self.classifications[i] = [] for featureset in X: distances = [ np.linalg(featureset - self.centroids[centroid]) for centroid in self.centroids ] classification = distances.index(min(distances)) self.classifactions[classification].append(featureset) prev_centroids = dict(self.centroids) for classification in self.classsifications: pass self.centroids[classification] = np.average( self.classifications[classification], axis=0)
def trace_circle(fraction, startP, centerP, normal): length = np.linalg(normal) if(length != 1.0 && length != 0.0): normal = normal/length radial = startP - centerP rMat = rotation_matrix(normal, fraction*TAU) return np.dot(rMat,centerP)
def healy_symplectify(M): # https://accelconf.web.cern.ch/e06/PAPERS/WEPCH152.PDF print("Symplectifying linear One-Turn-Map...") print("Before symplectifying: det(M) = {}".format(np.linalg.det(M))) I = np.identity(6) S = np.array([ [0.0, 1.0, 0.0, 0.0, 0.0, 0.0], [-1.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0, 0.0, 0.0], [0.0, 0.0, -1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0, 0.0, -1.0, 0.0], ]) V = np.matmul(S, np.matmul(I - M, np.linalg.inv(I + M))) W = (V + V.T) / 2 if np.linalg.det(I - np.matmul(S, W)) != 0: M_new = np.matmul(I + np.matmul(S, W), np.linalg.inv(I - np.matmul(S, W))) else: print("WARNING: det(I - SW) = 0!") V_else = np.matmul(S, np.matmul(I + M, np.linalg.inv(I - M))) W_else = (V_else + V_else.T) / 2 M_new = -np.matmul(I + np.matmul(S, W_else), np.linalg(I - np.matmul(S, W_else))) print("After symplectifying: det(M) = {}".format(np.linalg.det(M_new))) return M_new
def make_real(self): for nx in range(self.Nx): for ny in range(0, self.Ny): for nz in range(0, self.Nz): for i in range(0, self.Nd): tmp = self.velocityField[i, nx, ny, nz] tmp = np.linalg(tmp) self.velocityField[i, nx, ny, nz] = tmp
def euc_dist(v1, v2): ''' euc_dist(v1, v2) Computes euclidean distance between two vectors. Throws an error if the vector are not of the same dimension ''' assert (v1.shape[0] == v2.shape[0]), "Input vectors to euc_dist must have the same dimensions" return np.linalg(v1-v2, 2)
def get_FIM(new_m, m, new_Sigma, Sigma): invSigma = np.linalg(Sigma) for i in range(new_m.shape[0]): for j in range(new_m.shape[0]): #FIM = delta_m.T @ invSigma @ delta_m +\ # 0.5 * np.trace(invSigma @ delta_Sigma @ invSigma @ delta_Sigma)) return FIM
def color(im, **kwargs): assert im.ndim == 3 hsv_im = cv.cvtColor(im, cv.COLOR_BGR2HSV)[:, :, 0] hist = cv.calcHist(hsv_im, channels=[0], mask=None, histSize=[256], ranges=[0, 256]) hist /= np.linalg(hist) return hist.reshape(-1)
def Bolton_Schlegel_Diagonalization(flux, covariance): """covariance needs to be a dense matrix """ invcov = np.linalg.pinv(covariance) evecs, evals = np.linalg(invcov) eval_sqrt = np.sqrt(eigen_vals) rotmat_no_norm = np.dot(eigen_vecs*eval_sqrt, eigen_vecs.transpose()) rot_norm = np.dot(rotmat_no_norm, np.ones(len(rotmat_no_norm))) rotmat = rotmat_no_norm/rot_norm newflux = np.dot(rotmat, flux) return newflux, rot_norm, rotmat
def maybe_display(F, x, gradF=None): global iterations if dispiter and iterations[0] % dispiter == 0: dF = F - iterations[1] if iterations[0] else 0 dx = np.linalg.norm(x - iterations[2]) if iterations[0] else 0 gradF = np.linalg(gradF) if gradF is not None else 0 print( f'evaluation # {iterations[0]:6} - error={F:+10.4e} - variation={dF:+10.4e} - |dx|={dx:10.4e} - |grad|={gradF:10.4e}' ) iterations = (iterations[0] + 1, F, x) return F
def test_pure_QR(m): random.seed(1302 * m) A = random.randn(m, m) + 1j * random.randn(m, m) A0 = 1.0 * A A2 = cla_utils.pure_QR(QR, maxit=10, tol=1.0e-100) #check it is still Hermitian assert (np.linalg.norm(A2 - np.conj(A2).T) < 1.0e-4) #check for orthogonality x0 = random.randn(m) assert (np.linalg.norm(np.dot(A2, x0)) - np.linalg(np.dot(A0, x0)) < 1.0e-6) #check for conservation of trace assert (np.abs(np.tr(A0) - np.tr(A2)) < 1.0e-6)
def _kernel(self, x1, x2, type='basic'): if type == 'basic': return np.dot(x1, x2) elif type == 'poly': # 拍脑袋定超参,3次方; # 实际中需要试验 return math.pow(np.dot(x1, x2) + 1, 3) elif type == 'gaussian': norm2square = math.pow(np.linalg(np.substract(x1, x2)), 2) # sigma的值也拍个脑袋吧=,= return math.exp(float(norm2square) / 2 / 10 * -1) else: return np.dot(x1, x2)
def healy_symplectify(M): I = np.identity(6) V = np.matmul(S, np.matmul(I - M, np.linalg.inv(I + M))) W = (V + V.T) / 2 if np.linalg.det(I - np.matmul(S, W)) != 0: M_new = np.matmul(I + np.matmul(S, W), np.linalg.inv(I - np.matmul(S, W))) else: V_else = np.matmul(S, np.matmul(I + M, np.linalg.inv(I - M))) W_else = (V_else + V_else.T) / 2 M_new = -np.matmul(I + np.matmul(S, W_else), np.linalg(I - np.matmul(S, W_else))) return M_new
def predict(self, x): preds = [] for sample in tqdm(x): # Calculating the distance between the input point and training points dist = [np.linalg(sample, x_train) for x_train in self.__x] # Sorting based on the dist k_samples = np.argsort(dist)[:self.k] # predicting the labels k_labels = [self.y[i][0] for i in k_samples] preds.append(k_labels)
def _get_gate_info_switcher(cur_state, estimated_gate_loc): init_pose = rospy.get_param('/uav/flightgoggles_uav_dynamics/init_pose') xyz_offset = init_pose[0:3] gate_map = {} vec_map = {} perturb_map = {} dim_map = {} cur_pos = cur_state[0:3] SWITCH_RADIUS = 5 # If within 5 meters of nominal gate location, switch gate estimator for i in range(1, TOTAL_NUM_GATES + 1): nom_gate_loc = rospy.get_param('/uav/Gate%d/nominal_location' % i) if np.linalg(cur_pos - np.array(nom_gate_loc)) < SWITCH_RADIUS: gate_loc = estimated_gate_loc else: gate_loc = nom_gate_loc gate_loc = np.array(gate_loc) # change of coordinates for gate location gate_loc[:, 0] = gate_loc[:, 0] - xyz_offset[0] gate_loc[:, 1] = gate_loc[:, 1] - xyz_offset[1] tmp = gate_loc[:, 0].copy() gate_loc[:, 0] = gate_loc[:, 1] gate_loc[:, 1] = -tmp # change of coordiantes for gate perturbation perturbation_bound = rospy.get_param('/uav/Gate%d/perturbation_bound' % i) perturbation_bound[0], perturbation_bound[1] = perturbation_bound[ 1], perturbation_bound[0] perturb_map[i] = perturbation_bound gate_map[i] = np.mean(gate_loc, axis=0) cur_vec = estimate_perpendicular_vec(gate_loc) if cur_vec[0] < 0: cur_vec = -cur_vec vec_map[i] = cur_vec width_i, height_i = estimate_dimension(gate_loc) dim_map[i] = (width_i, height_i) return gate_map, vec_map, dim_map, perturb_map
def logMultivariateTDensity(self, x, tableId): dlogprob = 0.0 count = self.tableCounts[tableId] k_n = self.prior.k_0 + count nu_n = self.prior.nu_0 + count scaleTdistrn = math.sqrt((k_n + 1) / (k_n * (nu_n - Data.D + 1))) nu = self.prior.nu_0 + count - Data.D + 1 x_minus_mu = x - self.tableMeans[tableId] lTriangularChol = self.tableCholeskyLTriangularMat[ tableId] * scaleTdistrn x_minus_mu = np.linalg(lTriangularChol, x_minus_mu) x_minus_mu_T = x_minus_mu.T mul = x_minus_mu_T * x_minus_mu val = mul[0][0] logprob = math.lgamma( (nu + Data.D) / 2) - (math.lgamma(nu / 2) + Data.D / 2 * (math.log(nu) + math.log(math.pi)) + self.logDeterminants[tableId] + (nu + Data.D) / 2 * math.log(1 + val / nu)) return logprob
def timeit(fn, fargs, n_range, seconds=5): print(f'[timeit] {seconds} seconds per N') # timeit for N bench = [] for n in n_range: args = fargs(n) calls = 0 timer = perf_counter() while perf_counter() - timer < seconds: fn(args) calls += 1 timer = perf_counter() - timer # result bench.append([np.e, n, timer / calls]) print(f'[N={n}] {calls / timer:.2f} calls / sec') # estimate complexity bench = np.log(bench) (alpha, beta), *_ = np.linalg(bench[:, :2], bench[:, -1]) print(f'estimated O({np.exp(alpha):.3} * N ^ {beta:.3f})')
def invGeostat(params, data, idata, grid, cm, L, app=None, ui=None): """ Input: params: Instance of lsqrParams class whose parameters have been edited in InversionUI or manually data: (m, 15) array : - data[:, 3] == Tx(i.e. Tx_x, Tx_y, Tx_z) - data[:, 3:6] == Rx(i.e. Rx_x, Rx_y, Rx_z) - data[:, 6:9] == data from model(i.e. tt, et, trace_num) - data[:, 9:12] == TxCosDir - data[:, 12:15] == RxCosDir idata: (n,) bool array: - Values at a one index of this vector will be True if the mog.in_vect is True and mog.tt vector does not equal -1.0 at this same index ex: mog.tt = np.array([ -1.0, 87.341, 79.649, -1.0]) mog.in_vect = np.array([ 1, 1, 0, 0]) idata = np.array([ False, True, False, False]) grid: instance of Grid class cm : Covar model used L: First iteration: - Sparse matrix which contains the trajectory of straight rays. Rays are straight because we assume to have a homogeneous slowness/velocity model. Second iteration and more: - Sparse matrix which contains the tracjectory of curved rays. Rays are now curved because we've been able to build our slowness/velocity model from the scipy.sparse.linalg.lsqr method. app: if using Bh_Tomo/InversionUI: The application which contains the InversionUI QWidget. We need it to process the ui events such as the resfresh of the invFig if not using Bh_Tomo/InversionUI:: app is set to none ui: the InversionUI QWidget """ # First we call a Tomo class instance. It will hold the data we will process along the way. tomo = Tomo() if data.shape[1] >= 9: tomo.no_trace = data[:, 8] if np.all(L == 0): # We get the straights rays for the first iteration L = grid.getForwardStraightRays(idata) tomo.x = 0.5 * (grid.grx[0:-1] + grid.grx[1:]) tomo.z = 0.5 * (grid.grz[0:-1] + grid.grz[1:]) if not np.all(grid.gry == 0): tomo.y = 0.5 * (grid.gry[0:-2] + grid.gry[1:-1]) else: tomo.y = np.array([]) cont = np.array([]) xc = grid.getCellCenter() Cm = cm.compute(xc, xc) # TODO : Test, indices may not work if cont.size > 0 and params.useCont == 1: indc = grid.getContIndices(cont, xc) Cm0 = Cm[indc, :] Cmc = Cm[indc, indc] Cmc = Cmc + np.diag(cont[:, -1]) c0 = np.array([]) if np.size(data[0, :]) > 7 and cm.use_c0 == 1: if (data[:, 7] != 0).all(): c0 = data[:, 7]**2 for noIter in range(params.numItCurved + params.numItStraight + 1): if noIter == 1: l_moy = np.mean(data[:, 6] / np.sum(L.A, axis=1)) else: l_moy = np.mean(tomo.s) mta = np.sum(L.A * l_moy, axis=1) dt = data[:, 6] - mta #TODO: Add Simulation param doSim = 0 #if params.doSim==1 and noIter==(params.numItStraight+params.numItCurved): # doSim = 1 if np.size(c0) == 0: Cd = L * Cm * L.T + cm.nugget_data * np.eye(np.size(L.A[:, 0])) else: Cd = L * Cm * L.T + cm.nugget_data * np.diag(c0) Cdm = L * Cm if doSim == 0: # TODO : Fix and test this part if np.size(cont) > 0 and params.useCont == 1: scont = cont[:, -2] - l_moy C = np.concatenate((np.concatenate(Cmc, Cdm[:, indc].T), np.concatenate(Cdm[:, indc], Cd))) C = C + np.eye(np.size(C)) * 1e-6 # dual cokriging (see Gloaguen et al 2005) Gamma = np.linalg(C, np.concatenate( (scont, dt))).reshape(-1, 1).T m = Gamma.dot(np.concatenate((Cm0, Cdm))).T else: Gamma = np.linalg.solve(Cd, dt).reshape(-1, 1).T m = Gamma.dot(Cdm).T if params.tomoAtt == 1: #neative attenuation set to zero m[m < -l_moy] = -l_moy tomo.s = m + l_moy # TODO : Implement simulation #else: # if params.tomoAtt == 0 and noIter >= params.numItStraight and params.numItCurved > 0: if np.any(tomo.s < 0): print("Negative Slownesses: Change Inversion Parameters") #tomo = np.array([]) _, L, tomo.rays = grid.raytrace(tomo.s, data[:, 0:3], data[:, 3:6]) if params.saveInvData == 1: tt = L.dot(tomo.s) tomo.invData.res = data[:, 6] - tt tomo.invData.s = tomo.s if ui is not None: ui.InvIterationDone.emit(noIter + 1, tomo.s, "Geostatistic") tomo.L = L if ui is not None: ui.InvDone.emit(noIter, "Geostatistic") else: print('Geostatistic Inversion - Finished, {} Iterations Done'.format( noIter)) return tomo
def update(self, observation: Gaussian) -> None: kalman = self.covariance @ np.linalg( self.covariance + observation.covariance) self.mean = self.mean + kalman @ (observation.mean + self.mean) self.covariance = self.covariance - kalman @ self.covariance self.normalize()
def eckart_align(geom1,geom2,masses,rfrac,max_iter=200): COMreact = np.sum(manage_xyz.xyz_to_np(geom1) * np.outer(masses, [1.0]*3), 0) / np.sum(masses) COMproduct = np.sum(manage_xyz.xyz_to_np(geom2) * np.outer(masses, [1.0]*3), 0) / np.sum(masses) xyzreact = manage_xyz.xyz_to_np(geom1) xyzproduct = manage_xyz.xyz_to_np(geom2) # Convert to MW coordinates mwcreact = xyzreact*units.ANGSTROM_TO_AU*np.outer(np.sqrt(masses),[1.0]*3) mwcproduct = xyzproduct*units.ANGSTROM_TO_AU*np.outer(np.sqrt(masses),[1.0]*3) thetas = np.zeros(3) total_thetas = np.zeros(3) rot_mat = np.zeros((3,3)) if rfrac < 1.: max_iter=1 for i in range(maxiter): # get gradmag grad = np.zeros(3) for atom1,atom2 in zip(mwcreact,mwcproduct): grad[0] += 2*(atom1[1]*atom2[2]-atom1[2]*atom2[1]) grad[1] += 2*(atom1[2]*atom2[0]-atom1[0]*atom2[2]) grad[2] += 2*(atom1[0]*atom2[1]-atom1[1]*atom2[0]) gradmag = np.linalg(grad) print(" the gradient of the Eckart distance is %5.4f" % gradmag) # get hessian dot = np.dot(mwcreact.flatten(),mwcproduct.flatten()) xd = np.zeros((3,3)) for atom1,atom2 in zip(mwcreact,mwcproduct): xd[0,0] += atom1[0]*atom2[0] xd[1,1] += atom1[1]*atom2[1] xd[2,2] += atom1[2]*atom2[2] xd[1,0] += atom1[1]*atom2[0] xd[2,0] += atom1[2]*atom2[0] xd[2,1] += atom1[2]*atom2[1] xd[0,1] = xd[1,0] xd[0,2] = xd[2,0] xd[1,2] = xd[2,1] hess = np.zeros((3,3)) hess[0,0] = 2*(dot-xd[0,0]) hess[1,1] = 2*(dot-xd[1,1]) hess[2,2] = 2*(dot-xd[2,2]) hess[1,0] = -2*xd[1,0] hess[2,0] = -2*xd[2,0] hess[2,1] = -2*xd[2,1] hess[0,1] = hess[1,0] hess[0,2] = hess[2,0] hess[1,2] = hess[2,1] hess_evals,hess_evecs = np.linalg.eigh(hess) mag_thetas = np.linalg.norm(thetas) if gradmag<tol and all(hess_evals>0.): break temp=0. vec_index=0 for j in range(3): if hess_evals[j]<temp and abs(hess_evals[j])>0.01: temp = hess_evals[j] vec_index=j if vec_index!=0: # Rotate around structure RotMat = np.zeros((3,3)) vec = hess_evecs[vec_index] RotMat[0,0] = 2*vec[0]*vec[0] -1 RotMat[1,1] = 2*vec[1]*vec[1] -1 RotMat[2,2] = 2*vec[2]*vec[2] -1 RotMat[1,0] = 2*vec[0]*vec[1] RotMat[2,0] = 2*vec[2]*vec[0] RotMat[2,1] = 2*vec[2]*vec[1] RotMat[0,1] = RotMat[1,0] RotMat[0,2] = RotMat[2,0] RotMat[1,2] = RotMat[2,1] # rotate product mwcprod = np.dot(mwcprod,RotMat) hess_inverse = np.linalg.inv(hess) thetas = np.dot(hess_inverse,grad) thetas -= np.ones(3)*rfrac total_thetas += thetas x = thetas[0] y= thetas[1] z = thetas[2] rot_mat[0,0] = np.cos(y)*np.cos(z) rot_mat[0,1] = -np.cos(y)*np.sin(z) rot_mat[0,2] = np.sin(y) rot_mat[1,0] = np.sin(x)*np.sin(y)*np.cos(z) + np.cos(x)*np.sin(z) rot_mat[1,1] = -np.sin(x)*np.sin(y)*np.sin(z) + np.cos(x)*np.cos(z) rot_mat[1,2] = -np.sin(x)*np.cos(y) rot_mat[2,0] = -np.cos(x)*np.sin(y)*np.cos(z) + np.sin(x)*np.sin(z) rot_mat[2,1] = np.cos(x)*np.sin(y)*np.sin(z) + np.sin(x)*np.cos(z) rot_mat[2,2] = np.cos(x)*np.cos(y)
def pointProjection(P, A, B): AP = P - A AB = B - A return np.dot(AP, AB) / np.linalg(AB)
z_x_emb = x_emb[:, 2] x_c = np.average(x_x_emb) y_c = np.average(y_x_emb) z_c = np.average(z_x_emb) np.save('z_axis', z_x_emb) np.save('corrdinates', x_emb) ax.scatter(x_c, y_c, z_c) ax.scatter(x_x_emb, y_x_emb, z_x_emb, color='red') cent = [x_c, y_c, z_c] sum = 0 for i in x_emb: dist = np.linalg(i - cent) sum = sum + dist avg = sum / 8 u, v = np.mgrid[0:2 * np.pi:20j, 0:np.pi:10j] x = np.cos(u) * np.sin(v) y = np.sin(u) * np.sin(v) z = np.cos(v) ax.plot_wireframe(x, y, z, color="r") ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') plt.show()
def FEEigenSolver(a): values, vectors = np.linalg(a) freq = sqrt(values)
def normalize(v): norm = np.linalg(np.array(v)) for i in range(len(v)): v[i] = v[i]/norm return v
def cos_sim(v1, v2): dot_product = v1 * v2 denom = np.linalg(v1) * np.linalg(v2) return dot_product / denom
sys.path.append('..') import numpy as np from common.util import most_similar, create_co_matrix, ppmi from dataset import ptb window_size = 2 wordvec_size = 100 corpus, word_to_id, id_to_word = ptb.load_data('train') vocab_size = len(word_to_id) C = create_co_matrix(corpus, vocab_size, window_size) W = ppmi(C, verbose=True) print("SVD계산") try: from sklearn.utils.extmath import randomized_svd U, S, V = randomized_svd(W, n_components=wordvec_size, n_iter=5, random_state=None) except ImportError: print("sklearn 모듈 불러오기 실패") U, S, V = np.linalg(W) word_vecs = U[:, :wordvec_size] querys = ['you', 'year', 'car', 'toyota'] for query in querys: most_similar(query, word_to_id, id_to_word, word_vecs, top=5)
n, m = X_0.shape predictions = [] def preprocessing(raw_data = X_0): def regressor(reg_data = raw_data): pred = []; j = np.arange(m) for i in range(n): slope = ((reg_data[i] @ j) - (reg_data[0, i]*j.sum()))/(j@j) pred.append(slope*(m+1)+reg_data[0, i]); pred = np.array(pred).reshape(-1, 1); reg_data = np.hstack((reg_data, pred)); return reg_data; raw_data = regressor(raw_data)[:, 1:] return raw_data if X_1 == None: X_1 = preprocessing(); U, S, V = np.linalg(X_0); A_tilde = U.T @ X_1 @ V.T @ (1/np.diag(S)) W, L = np.eig(A_tilde) Phi = X_1 @ V.T @ (1/np.diag(S)) @ W for i in range(1, threshold): eigenvalues = np.diag(L**(i-1)) x_i = Phi @ eigenvalues @ np.linalg.pinv(Phi) @
def normalizeRows(x): x_norm = np.linalg(x, axis=1, keepdims=True) x = x / x_norm return x
a = np.array([0,1,2]) print(type(a[0][0])) b=np.array([[1,2],[3,4]],dtype=complex) print(type(b[0][0])) c=np.zeros([2,3]) d=np.ones([2,3]) e=np.empty((2,3)) f=np.ones([2,3,4]) print(type(f)) g=np.ones([2,3,4,5]) h=np.arange(10,30,5) i=np.array(range(0,5,1.5))#range float not accepted j=np.arange(0,2,0.2) #import pi k=np.linspace(0,2,9) l=np.linspace(0,2*pi,100) np.linalg()
defects = cv2.convexityDefects(c, dfct) if defects is not None: inicio = [] fin = [] dedos = for i in range(defects.shape[0]): s,e,f,d = defects[i,0] start = c[s][0] end = c[e][0] far = c[f][0] #Angulo entre el punto inicial y el final a = np.linalg(far-end) b = np.linalg(far-start) c = np.linalg(start-end) angulo = np.arccos((np.power(a,2) + np.power(b,2) - np.power(c,2)) / (2*a*b)) angulo = np.degrees(angulo) angulo = int(angulo) #Ajustar estos parámetros if np.linalg.norm(start-end) > 20 and d > 12000 and angulo < 90: #Almacenando los puntos para contar los dedos inicio.append(start) fin.append(end) cv2.circle(ROI, tuple(start), 5, (204,204,0), 2)
def loss(X, Z, W): L = np.linalg(X - np.matmul(W, Z)) P = size(L) return L