Python numpy.dot() Examples
The following are 30
code examples of numpy.dot().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
numpy
, or try the search function
.
Example #1
Source File: NLP.py From Financial-NLP with Apache License 2.0 | 7 votes |
def similarity_label(self, words, normalization=True): """ you can calculate more than one word at the same time. """ if self.model==None: raise Exception('no model.') if isinstance(words, string_types): words=[words] vectors=np.transpose(self.model.wv.__getitem__(words)) if normalization: unit_vector=unitvec(vectors,ax=0) # 这样写比原来那样速度提升一倍 #unit_vector=np.zeros((len(vectors),len(words))) #for i in range(len(words)): # unit_vector[:,i]=matutils.unitvec(vectors[:,i]) dists=np.dot(self.Label_vec_u, unit_vector) else: dists=np.dot(self.Label_vec, vectors) return dists
Example #2
Source File: nn.py From deep-learning-note with MIT License | 6 votes |
def train(self, inputs_list, targets_list): inputs = np.array(inputs_list, ndmin=2).T targets = np.array(targets_list, ndmin=2).T hidden_inputs = np.dot(self.wih, inputs) hidden_outputs = self.activation_function(hidden_inputs) final_inputs = np.dot(self.who, hidden_outputs) final_outputs = self.activation_function(final_inputs) output_errors = targets - final_outputs hidden_errors = np.dot(self.who.T, output_errors) self.who += self.lr * np.dot((output_errors * final_outputs * (1.0 - final_outputs)), np.transpose(hidden_outputs)) self.wih += self.lr * np.dot((hidden_errors * hidden_outputs * (1.0 - hidden_outputs)), np.transpose(inputs)) pass # query
Example #3
Source File: csys.py From StructEngPy with MIT License | 6 votes |
def __init__(self,origin, pt1, pt2, name=None): """ origin: 3x1 vector pt1: 3x1 vector pt2: 3x1 vector """ self.__origin=origin vec1 = np.array([pt1[0] - origin[0] , pt1[1] - origin[1] , pt1[2] - origin[2]]) vec2 = np.array([pt2[0] - origin[0] , pt2[1] - origin[1] , pt2[2] - origin[2]]) cos = np.dot(vec1, vec2)/np.linalg.norm(vec1)/np.linalg.norm(vec2) if cos == 1 or cos == -1: raise Exception("Three points should not in a line!!") self.__x = vec1/np.linalg.norm(vec1) z = np.cross(vec1, vec2) self.__z = z/np.linalg.norm(z) self.__y = np.cross(self.z, self.x) self.__name=uuid.uuid1() if name==None else name
Example #4
Source File: element.py From StructEngPy with MIT License | 6 votes |
def _BtDB(self,s,r): """ dot product of B^T, D, B params: s,r:natural position of evalue point.2-array. returns: 3x3 matrix. """ print(self._B(s,r).transpose(2,0,1).shape) print( np.matmul( np.dot(self._B(s,r).T,self._D), self._B(s,r).transpose(2,0,1)).shape ) print(self._D.shape) return np.matmul(np.dot(self._B(s,r).T,self._D),self._B(s,r).transpose(2,0,1)).transpose(1,2,0)
Example #5
Source File: csys.py From StructEngPy with MIT License | 6 votes |
def set_by_3pts(self,origin, pt1, pt2): """ origin: tuple 3 pt1: tuple 3 pt2: tuple 3 """ self.origin=origin vec1 = np.array([pt1[0] - origin[0] , pt1[1] - origin[1] , pt1[2] - origin[2]]) vec2 = np.array([pt2[0] - origin[0] , pt2[1] - origin[1] , pt2[2] - origin[2]]) cos = np.dot(vec1, vec2)/np.linalg.norm(vec1)/np.linalg.norm(vec2) if cos == 1 or cos == -1: raise Exception("Three points should not in a line!!") self.x = vec1/np.linalg.norm(vec1) z = np.cross(vec1, vec2) self.z = z/np.linalg.norm(z) self.y = np.cross(self.z, self.x)
Example #6
Source File: kalman_filter.py From kalman_filter_multi_object_tracking with MIT License | 6 votes |
def predict(self): """Predict state vector u and variance of uncertainty P (covariance). where, u: previous state vector P: previous covariance matrix F: state transition matrix Q: process noise matrix Equations: u'_{k|k-1} = Fu'_{k-1|k-1} P_{k|k-1} = FP_{k-1|k-1} F.T + Q where, F.T is F transpose Args: None Return: vector of predicted state estimate """ # Predicted state estimate self.u = np.round(np.dot(self.F, self.u)) # Predicted estimate covariance self.P = np.dot(self.F, np.dot(self.P, self.F.T)) + self.Q self.lastResult = self.u # same last predicted result return self.u
Example #7
Source File: __init__.py From StructEngPy with MIT License | 6 votes |
def resolve_modal_displacement(self,node_id,k): """ resolve modal node displacement. params: node_id: int. k: order of vibration mode. return: 6-array of local nodal displacement. """ if not self.is_solved: raise Exception('The model has to be solved first.') if node_id in self.__nodes.keys(): node=self.__nodes[node_id] T=node.transform_matrix return T.dot(self.mode_[node_id*6:node_id*6+6,k-1]).reshape(6) else: raise Exception("The node doesn't exists.")
Example #8
Source File: point_cloud.py From FRIDA with MIT License | 6 votes |
def classical_mds(self, D): ''' Classical multidimensional scaling Parameters ---------- D : square 2D ndarray Euclidean Distance Matrix (matrix containing squared distances between points ''' # Apply MDS algorithm for denoising n = D.shape[0] J = np.eye(n) - np.ones((n,n))/float(n) G = -0.5*np.dot(J, np.dot(D, J)) s, U = np.linalg.eig(G) # we need to sort the eigenvalues in decreasing order s = np.real(s) o = np.argsort(s) s = s[o[::-1]] U = U[:,o[::-1]] S = np.diag(s)[0:self.dim,:] self.X = np.dot(np.sqrt(S),U.T)
Example #9
Source File: point_cloud.py From FRIDA with MIT License | 6 votes |
def flatten(self, ind): ''' Transform the set of points so that the subset of markers given as argument is as close as flat (wrt z-axis) as possible. Parameters ---------- ind : list of bools Lists of marker indices that should be all in the same subspace ''' # Transform references to indices if needed ind = [self.key2ind(s) for s in ind] # center point cloud around the group of indices centroid = self.X[:,ind].mean(axis=1, keepdims=True) X_centered = self.X - centroid # The rotation is given by left matrix of SVD U,S,V = la.svd(X_centered[:,ind], full_matrices=False) self.X = np.dot(U.T, X_centered) + centroid
Example #10
Source File: generators.py From FRIDA with MIT License | 6 votes |
def gen_visibility(alphak, phi_k, pos_mic_x, pos_mic_y): """ generate visibility from the Dirac parameter and microphone array layout :param alphak: Diracs' amplitudes :param phi_k: azimuths :param pos_mic_x: a vector that contains microphones' x coordinates :param pos_mic_y: a vector that contains microphones' y coordinates :return: """ xk, yk = polar2cart(1, phi_k) num_mic = pos_mic_x.size visi = np.zeros((num_mic, num_mic), dtype=complex) for q in xrange(num_mic): p_x_outer = pos_mic_x[q] p_y_outer = pos_mic_y[q] for qp in xrange(num_mic): p_x_qqp = p_x_outer - pos_mic_x[qp] # a scalar p_y_qqp = p_y_outer - pos_mic_y[qp] # a scalar visi[qp, q] = np.dot(np.exp(-1j * (xk * p_x_qqp + yk * p_y_qqp)), alphak) return visi
Example #11
Source File: doa.py From FRIDA with MIT License | 6 votes |
def compute_mode(self): """ Pre-compute mode vectors from candidate locations (in spherical coordinates). """ if self.num_loc is None: raise ValueError('Lookup table appears to be empty. \ Run build_lookup().') self.mode_vec = np.zeros((self.max_bin,self.M,self.num_loc), dtype='complex64') if (self.nfft % 2 == 1): raise ValueError('Signal length must be even.') f = 1.0 / self.nfft * np.linspace(0, self.nfft / 2, self.max_bin) \ * 1j * 2 * np.pi for i in range(self.num_loc): p_s = self.loc[:, i] for m in range(self.M): p_m = self.L[:, m] if (self.mode == 'near'): dist = np.linalg.norm(p_m - p_s, axis=1) if (self.mode == 'far'): dist = np.dot(p_s, p_m) # tau = np.round(self.fs*dist/self.c) # discrete - jagged tau = self.fs * dist / self.c # "continuous" - smoother self.mode_vec[:, m, i] = np.exp(f * tau)
Example #12
Source File: tools_fri_doa_plane.py From FRIDA with MIT License | 6 votes |
def cov_mtx_est(y_mic): """ estimate covariance matrix :param y_mic: received signal (complex based band representation) at microphones :return: """ # Q: total number of microphones # num_snapshot: number of snapshots used to estimate the covariance matrix Q, num_snapshot = y_mic.shape cov_mtx = np.zeros((Q, Q), dtype=complex, order='F') for q in range(Q): y_mic_outer = y_mic[q, :] for qp in range(Q): y_mic_inner = y_mic[qp, :] cov_mtx[qp, q] = np.dot(y_mic_outer, y_mic_inner.T.conj()) return cov_mtx / num_snapshot
Example #13
Source File: dynamic.py From StructEngPy with MIT License | 6 votes |
def spectrum_analysis(model,n,spec): """ sepctrum analysis params: n: number of modes to use\n spec: a list of tuples (period,acceleration response) """ freq,mode=eigen_mode(model,n) M_=np.dot(mode.T,model.M) M_=np.dot(M_,mode) K_=np.dot(mode.T,model.K) K_=np.dot(K_,mode) C_=np.dot(mode.T,model.C) C_=np.dot(C_,mode) d_=[] for (m_,k_,c_) in zip(M_.diag(),K_.diag(),C_.diag()): sdof=SDOFSystem(m_,k_) T=sdof.omega_d() d_.append(np.interp(T,spec[0],spec[1]*m_)) d=np.dot(d_,mode) #CQC return d
Example #14
Source File: dynamic.py From StructEngPy with MIT License | 6 votes |
def Riz_mode(model:Model,n,F): """ Solve the Riz mode of the MDOF system\n n: number of modes to extract\n F: spacial load pattern """ # alpha=np.array(mode).T # #Grum-Schmidt procedure # beta=[] # for i in range(len(mode)): # beta_i=alpha[i] # for j in range(i): # beta_i-=np.dot(alpha[i],beta[j])/np.dot(alpha[j],alpha[j])*beta[j] # beta.append(beta_i) # mode_=np.array(beta).T pass
Example #15
Source File: display_graph.py From gated-graph-transformer-network with MIT License | 6 votes |
def prep_graph_display(states, options={}): clean_states = [x.tolist() for x in states] nstr, nid, nstate, estr = states flat_nid = nid.reshape([-1,nid.shape[-1]]) flat_estr = estr.reshape([-1,estr.shape[-1]]) flat_estr = flat_estr / (np.linalg.norm(flat_estr, axis=1, keepdims=True) + 1e-8) num_unique_colors = nid.shape[-1] + estr.shape[-1] id_denom = max(nid.shape[-1] - 1, 1) id_project_mat = np.array([list(cm_rainbow(i/id_denom)[:3]) for i in range(0,nid.shape[-1])]) estr_denom = estr.shape[-1] estr_project_mat = np.array([list(cm_rainbow((i+0.37)/estr_denom)[:3]) for i in range(estr.shape[-1])]) node_colors = np.dot(flat_nid, id_project_mat) edge_colors = np.dot(flat_estr, estr_project_mat) colormap = { "node_id": node_colors.reshape(nid.shape[:-1] + (3,)).tolist(), "edge_type": edge_colors.reshape(estr.shape[:-1] + (3,)).tolist(), } return json.dumps({ "states":clean_states, "colormap":colormap, "options":options })
Example #16
Source File: tools_fri_doa_plane.py From FRIDA with MIT License | 6 votes |
def mtx_updated_G(phi_recon, M, mtx_amp2visi_ri, mtx_fri2visi_ri): """ Update the linear transformation matrix that links the FRI sequence to the visibilities by using the reconstructed Dirac locations. :param phi_recon: the reconstructed Dirac locations (azimuths) :param M: the Fourier series expansion is between -M to M :param p_mic_x: a vector that contains microphones' x-coordinates :param p_mic_y: a vector that contains microphones' y-coordinates :param mtx_freq2visi: the linear mapping from Fourier series to visibilities :return: """ L = 2 * M + 1 ms_half = np.reshape(np.arange(-M, 1, step=1), (-1, 1), order='F') phi_recon = np.reshape(phi_recon, (1, -1), order='F') mtx_amp2freq = np.exp(-1j * ms_half * phi_recon) # size: (M + 1) x K mtx_amp2freq_ri = np.vstack((mtx_amp2freq.real, mtx_amp2freq.imag[:-1, :])) # size: (2M + 1) x K mtx_fri2amp_ri = linalg.lstsq(mtx_amp2freq_ri, np.eye(L))[0] # projection mtx_freq2visi to the null space of mtx_fri2amp mtx_null_proj = np.eye(L) - np.dot(mtx_fri2amp_ri.T, linalg.lstsq(mtx_fri2amp_ri.T, np.eye(L))[0]) G_updated = np.dot(mtx_amp2visi_ri, mtx_fri2amp_ri) + \ np.dot(mtx_fri2visi_ri, mtx_null_proj) return G_updated
Example #17
Source File: element.py From StructEngPy with MIT License | 5 votes |
def __init__(self,node_i,node_j,node_k,t,E,mu,rho,dof,name=None,tol=1e-6): super(Tri,self).__init__(2,dof,name) self._nodes=[node_i,node_j,node_k] #Initialize local CSys o=[(node_i.x+node_j.x+node_k.x)/3, (node_i.y+node_j.y+node_k.y)/3, (node_i.z+node_j.z+node_k.z)/3] pt1 = [ node_j.x, node_j.y, node_j.z ] pt2 = [ node_i.x, node_i.y, node_i.z ] self._local_csys = Cartisian(o, pt1, pt2) self._area=0.5*np.linalg.det(np.array([[1,1,1], [node_j.x-node_i.x,node_j.y-node_i.y,node_j.z-node_i.z], [node_k.x-node_i.x,node_k.y-node_i.y,node_k.z-node_i.z]])) self._t=t self._E=E self._mu=mu E=self._E mu=self._mu D0=E/(1-mu**2) self._D=np.array([[1,mu,0], [mu,1,0], [0,0,(1-mu)/2]])*D0 #3D to local 2D V=self._local_csys.transform_matrix x3D=np.array([[node_i.x,node_i.y,node_i.z], [node_j.x,node_j.y,node_j.z], [node_k.x,node_k.y,node_k.z]]) x2D=np.dot(x3D,V.T) self._x2D=x2D[:,:2]
Example #18
Source File: spark_test.py From deep-learning-note with MIT License | 5 votes |
def encrypt_mul(array): return np.dot(encrypted_float_c, array) # 注意,实际执行时,这里是 lazy 的
Example #19
Source File: element.py From StructEngPy with MIT License | 5 votes |
def _S(self,s,r): """ stress matrix """ return np.dot(self._D,self._B(s,r))
Example #20
Source File: element.py From StructEngPy with MIT License | 5 votes |
def _N(self,x): """ interpolate function. return: 3x1 array represent x,y """ x,y=x[0],x[1] L=np.array((3,1)) L[0]=self._abc(1,2).dot(np.array([1,x,y]))/2/self._area L[1]=self._abc(2,0).dot(np.array([1,x,y]))/2/self._area L[2]=self._abc(0,1).dot(np.array([1,x,y]))/2/self._area return L.reshape(3,1)
Example #21
Source File: 9_two_layer_net_naive.py From deep-learning-note with MIT License | 5 votes |
def predict(self, x): W1, W2 = self.params['W1'], self.params['W2'] b1, b2 = self.params['b1'], self.params['b2'] a1 = np.dot(x, W1) + b1 z1 = sigmoid(a1) a2 = np.dot(z1, W2) + b2 y = softmax(a2) return y
Example #22
Source File: structures.py From mmdetection with Apache License 2.0 | 5 votes |
def _polygon_area(self, x, y): """Compute the area of a component of a polygon. Using the shoelace formula: https://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates Args: x (ndarray): x coordinates of the component y (ndarray): y coordinates of the component Return: float: the are of the component """ # noqa: 501 return 0.5 * np.abs( np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))
Example #23
Source File: audio.py From Griffin_lim with MIT License | 5 votes |
def _linear_to_mel(spectrogram): global _mel_basis if _mel_basis is None: _mel_basis = _build_mel_basis() return np.dot(_mel_basis, spectrogram)
Example #24
Source File: audio.py From Griffin_lim with MIT License | 5 votes |
def _mel_to_linear(mel_spectrogram): global _inv_mel_basis if _inv_mel_basis is None: _inv_mel_basis = np.linalg.pinv(_build_mel_basis()) return np.maximum(1e-10, np.dot(_inv_mel_basis, mel_spectrogram))
Example #25
Source File: track.py From animal-tracking with Creative Commons Zero v1.0 Universal | 5 votes |
def angle_cos(p0, p1, p2): d1, d2 = (p0 - p1).astype('float'), (p2 - p1).astype('float') return np.abs(np.dot(d1, d2) / np.sqrt(np.dot(d1, d1) * np.dot(d2, d2)))
Example #26
Source File: mel_features.py From sklearn-audio-transfer-learning with ISC License | 5 votes |
def log_mel_spectrogram(data, audio_sample_rate=8000, log_offset=0.0, window_length_secs=0.025, hop_length_secs=0.010, **kwargs): """Convert waveform to a log magnitude mel-frequency spectrogram. Args: data: 1D np.array of waveform data. audio_sample_rate: The sampling rate of data. log_offset: Add this to values when taking log to avoid -Infs. window_length_secs: Duration of each window to analyze. hop_length_secs: Advance between successive analysis windows. **kwargs: Additional arguments to pass to spectrogram_to_mel_matrix. Returns: 2D np.array of (num_frames, num_mel_bins) consisting of log mel filterbank magnitudes for successive frames. """ window_length_samples = int(round(audio_sample_rate * window_length_secs)) hop_length_samples = int(round(audio_sample_rate * hop_length_secs)) fft_length = 2 ** int(np.ceil(np.log(window_length_samples) / np.log(2.0))) spectrogram = stft_magnitude( data, fft_length=fft_length, hop_length=hop_length_samples, window_length=window_length_samples) mel_spectrogram = np.dot(spectrogram, spectrogram_to_mel_matrix( num_spectrogram_bins=spectrogram.shape[1], audio_sample_rate=audio_sample_rate, **kwargs)) return np.log(mel_spectrogram + log_offset)
Example #27
Source File: 6_nn_basis.py From deep-learning-note with MIT License | 5 votes |
def forward(network, x): W1, W2, W3 = network['W1'], network['W2'], network['W3'] b1, b2, b3 = network['b1'], network['b2'], network['b3'] a1 = np.dot(x, W1) + b1 z1 = sigmoid(a1) a2 = np.dot(z1, W2) + b2 z2 = sigmoid(a2) a3 = np.dot(z2, W3) + b3 y = identity_function(a3) return y
Example #28
Source File: face_attack.py From Adversarial-Face-Attack with GNU General Public License v3.0 | 5 votes |
def distance_to_victim(self, img): emb = self.eval_embeddings([img]) dist = np.dot(emb, self.victim_embeddings.T).flatten() stats = np.percentile(dist, [10, 30, 50, 70, 90]) return stats
Example #29
Source File: kalman_filter.py From kalman_filter_multi_object_tracking with MIT License | 5 votes |
def correct(self, b, flag): """Correct or update state vector u and variance of uncertainty P (covariance). where, u: predicted state vector u A: matrix in observation equations b: vector of observations P: predicted covariance matrix Q: process noise matrix R: observation noise matrix Equations: C = AP_{k|k-1} A.T + R K_{k} = P_{k|k-1} A.T(C.Inv) u'_{k|k} = u'_{k|k-1} + K_{k}(b_{k} - Au'_{k|k-1}) P_{k|k} = P_{k|k-1} - K_{k}(CK.T) where, A.T is A transpose C.Inv is C inverse Args: b: vector of observations flag: if "true" prediction result will be updated else detection Return: predicted state vector u """ if not flag: # update using prediction self.b = self.lastResult else: # update using detection self.b = b C = np.dot(self.A, np.dot(self.P, self.A.T)) + self.R K = np.dot(self.P, np.dot(self.A.T, np.linalg.inv(C))) self.u = np.round(self.u + np.dot(K, (self.b - np.dot(self.A, self.u)))) self.P = self.P - np.dot(K, np.dot(C, K.T)) self.lastResult = self.u return self.u
Example #30
Source File: dynamic.py From StructEngPy with MIT License | 5 votes |
def Newmark_beta(model:Model,T,F,u0,v0,a0,beta=0.25,gamma=0.5): """ beta,gamma: parameters.\n u0,v0,a0: initial state.\n T: time list with uniform interval.\n F: list of time-dependent force vectors. """ dt=T[1]-T[0] b1=1/(beta*dt*dt) b2=-1/(beta*dt) b3=1/2/beta-1 b4=gamma*dt*b1 b5=1+gamma*dt*b2 b6=dt*(1+gamma*b3-gamma) K_=self.K+b4*self.C+b1*self.M u=[u0] v=[v0] a=[a0] tt=[0] for (t,ft) in zip(T,F): ft_=ft+np.dot(self.M,b1*u[-1]-b2*v[-1]-b3*a[-1])+np.dot(self.C,b4*u[-1]-b5*v[-1]-b6*a[-1]) ut=np.linalg.solve(K_,ft_) vt=b4*(ut-u[-1])+b5*v[-1]+b6*a[-1] at=b1*(ut-u[-1])+b2*v[-1]+b3*a[-1] u.append(ut) v.append(vt) a.append(at) tt.append(t) df=pd.DataFrame({'t':tt,'u':u,'v':v,'a':a}) return df