Python numpy.eye() Examples
The following are 30 code examples for showing how to use numpy.eye(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
numpy
, or try the search function
.
Example 1
Project: NiBetaSeries Author: HBClab File: conftest.py License: MIT License | 9 votes |
def betaseries_file(tmpdir_factory, deriv_betaseries_fname=deriv_betaseries_fname): bfile = tmpdir_factory.mktemp("beta").ensure(deriv_betaseries_fname) np.random.seed(3) num_trials = 40 tgt_corr = 0.1 bs1 = np.random.rand(num_trials) # create another betaseries with a target correlation bs2 = minimize(lambda x: abs(tgt_corr - pearsonr(bs1, x)[0]), np.random.rand(num_trials)).x # two identical beta series bs_data = np.array([[[bs1, bs2]]]) # the nifti image bs_img = nib.Nifti1Image(bs_data, np.eye(4)) bs_img.to_filename(str(bfile)) return bfile
Example 2
Project: scanorama Author: brianhie File: time_align.py License: MIT License | 7 votes |
def time_align_visualize(alignments, time, y, namespace='time_align'): plt.figure() heat = np.flip(alignments + alignments.T + np.eye(alignments.shape[0]), axis=0) sns.heatmap(heat, cmap="YlGnBu", vmin=0, vmax=1) plt.savefig(namespace + '_heatmap.svg') G = nx.from_numpy_matrix(alignments) G = nx.maximum_spanning_tree(G) pos = {} for i in range(len(G.nodes)): pos[i] = np.array([time[i], y[i]]) mst_edges = set(nx.maximum_spanning_tree(G).edges()) weights = [ G[u][v]['weight'] if (not (u, v) in mst_edges) else 8 for u, v in G.edges() ] plt.figure() nx.draw(G, pos, edges=G.edges(), width=10) plt.ylim([-1, 1]) plt.savefig(namespace + '.svg')
Example 3
Project: FRIDA Author: LCAV File: point_cloud.py License: 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 4
Project: FRIDA Author: LCAV File: tools_fri_doa_plane.py License: MIT License | 6 votes |
def output_shrink(K, L): """ shrink the convolution output to half the size. used when both the annihilating filter and the uniform samples of sinusoids satisfy Hermitian symmetric. :param K: the annihilating filter size: K + 1 :param L: length of the (complex-valued) b vector :return: """ out_len = L - K if out_len % 2 == 0: half_out_len = np.int(out_len / 2.) mtx_r = np.hstack((np.eye(half_out_len), np.zeros((half_out_len, half_out_len)))) mtx_i = mtx_r else: half_out_len = np.int((out_len + 1) / 2.) mtx_r = np.hstack((np.eye(half_out_len), np.zeros((half_out_len, half_out_len - 1)))) mtx_i = np.hstack((np.eye(half_out_len - 1), np.zeros((half_out_len - 1, half_out_len)))) return linalg.block_diag(mtx_r, mtx_i)
Example 5
Project: FRIDA Author: LCAV File: tools_fri_doa_plane.py License: 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 6
Project: StructEngPy Author: zhuoju36 File: element.py License: MIT License | 6 votes |
def _N(self,s,r): """ Lagrange's interpolate function params: s,r:natural position of evalue point.2-array. returns: 2x(2x4) shape function matrix. """ la1=(1-s)/2 la2=(1+s)/2 lb1=(1-r)/2 lb2=(1+r)/2 N1=la1*lb1 N2=la1*lb2 N3=la2*lb1 N4=la2*lb2 N=np.hstack(N1*np.eye(2),N2*np.eye(2),N3*np.eye(2),N4*np.eye(2)) return N
Example 7
Project: kalman_filter_multi_object_tracking Author: srianant File: kalman_filter.py License: MIT License | 6 votes |
def __init__(self): """Initialize variable used by Kalman Filter class Args: None Return: None """ self.dt = 0.005 # delta time self.A = np.array([[1, 0], [0, 1]]) # matrix in observation equations self.u = np.zeros((2, 1)) # previous state vector # (x,y) tracking object center self.b = np.array([[0], [255]]) # vector of observations self.P = np.diag((3.0, 3.0)) # covariance matrix self.F = np.array([[1.0, self.dt], [0.0, 1.0]]) # state transition mat self.Q = np.eye(self.u.shape[0]) # process noise matrix self.R = np.eye(self.b.shape[0]) # observation noise matrix self.lastResult = np.array([[0], [255]])
Example 8
Project: dynamic-training-with-apache-mxnet-on-aws Author: awslabs File: test_ndarray.py License: Apache License 2.0 | 6 votes |
def test_output(): shape = (2,2) ones = mx.nd.ones(shape) zeros = mx.nd.zeros(shape) out = mx.nd.zeros(shape) mx.nd.ones(shape, out=out) assert_almost_equal(out.asnumpy(), ones.asnumpy()) mx.nd.zeros(shape, out=out) assert_almost_equal(out.asnumpy(), zeros.asnumpy()) mx.nd.full(shape, 2, out=out) assert_almost_equal(out.asnumpy(), ones.asnumpy() * 2) arange_out = mx.nd.arange(0, 20, dtype='int64') assert_almost_equal(arange_out.asnumpy(), np.arange(0, 20)) N_array = np.random.randint(1, high=8, size=10) M_array = np.random.randint(1, high=8, size=10) k_array = np.random.randint(-10, high=10, size=10) for i in range(10): N = N_array[i] M = M_array[i] k = k_array[i] assert_almost_equal(np.eye(N, M, k), mx.nd.eye(N, M, k).asnumpy()) assert_almost_equal(np.eye(N, k=k), mx.nd.eye(N, k=k).asnumpy())
Example 9
Project: DOTA_models Author: ringringyi File: swiftshader_renderer.py License: Apache License 2.0 | 6 votes |
def set_camera(self, fov_vertical, z_near, z_far, aspect): width = 2*np.tan(np.deg2rad(fov_vertical)/2.0)*z_near*aspect; height = 2*np.tan(np.deg2rad(fov_vertical)/2.0)*z_near; egl_program = self.egl_program c = np.eye(4, dtype=np.float32) c[3,3] = 0 c[3,2] = -1 c[2,2] = -(z_near+z_far)/(z_far-z_near) c[2,3] = -2.0*(z_near*z_far)/(z_far-z_near) c[0,0] = 2.0*z_near/width c[1,1] = 2.0*z_near/height c = c.T projection_matrix_o = glGetUniformLocation(egl_program, 'uProjectionMatrix') projection_matrix = np.eye(4, dtype=np.float32) projection_matrix[...] = c projection_matrix = np.reshape(projection_matrix, (-1)) glUniformMatrix4fv(projection_matrix_o, 1, GL_FALSE, projection_matrix)
Example 10
Project: DOTA_models Author: ringringyi File: rotation_utils.py License: Apache License 2.0 | 6 votes |
def rotate_camera_to_point_at(up_from, lookat_from, up_to, lookat_to): inputs = [up_from, lookat_from, up_to, lookat_to] for i in range(4): inputs[i] = normalize(np.array(inputs[i]).reshape((-1,))) up_from, lookat_from, up_to, lookat_to = inputs r1 = r_between(lookat_from, lookat_to) new_x = np.dot(r1, np.array([1, 0, 0]).reshape((-1, 1))).reshape((-1)) to_x = normalize(np.cross(lookat_to, up_to)) angle = np.arccos(np.dot(new_x, to_x)) if angle > ANGLE_EPS: if angle < np.pi - ANGLE_EPS: ax = normalize(np.cross(new_x, to_x)) flip = np.dot(lookat_to, ax) if flip > 0: r2 = get_r_matrix(lookat_to, angle) elif flip < 0: r2 = get_r_matrix(lookat_to, -1. * angle) else: # Angle of rotation is too close to 180 degrees, direction of rotation # does not matter. r2 = get_r_matrix(lookat_to, angle) else: r2 = np.eye(3) return np.dot(r2, r1)
Example 11
Project: OpenFermion-Cirq Author: quantumlib File: optimal_givens_decomposition_test.py License: Apache License 2.0 | 6 votes |
def test_givens_inverse(): r""" The Givens rotation in OpenFermion is defined as .. math:: \begin{pmatrix} \cos(\theta) & -e^{i \varphi} \sin(\theta) \\ \sin(\theta) & e^{i \varphi} \cos(\theta) \end{pmatrix}. confirm numerically its hermitian conjugate is it's inverse """ a = numpy.random.random() + 1j * numpy.random.random() b = numpy.random.random() + 1j * numpy.random.random() ab_rotation = givens_matrix_elements(a, b, which='right') assert numpy.allclose(ab_rotation.dot(numpy.conj(ab_rotation).T), numpy.eye(2)) assert numpy.allclose(numpy.conj(ab_rotation).T.dot(ab_rotation), numpy.eye(2))
Example 12
Project: OpenFermion-Cirq Author: quantumlib File: optimal_givens_decomposition_test.py License: Apache License 2.0 | 6 votes |
def test_circuit_generation_and_accuracy(): for dim in range(2, 10): qubits = cirq.LineQubit.range(dim) u_generator = numpy.random.random( (dim, dim)) + 1j * numpy.random.random((dim, dim)) u_generator = u_generator - numpy.conj(u_generator).T assert numpy.allclose(-1 * u_generator, numpy.conj(u_generator).T) unitary = scipy.linalg.expm(u_generator) circuit = cirq.Circuit() circuit.append(optimal_givens_decomposition(qubits, unitary)) fermion_generator = QubitOperator(()) * 0.0 for i, j in product(range(dim), repeat=2): fermion_generator += jordan_wigner( FermionOperator(((i, 1), (j, 0)), u_generator[i, j])) true_unitary = scipy.linalg.expm( get_sparse_operator(fermion_generator).toarray()) assert numpy.allclose(true_unitary.conj().T.dot(true_unitary), numpy.eye(2 ** dim, dtype=complex)) test_unitary = cirq.unitary(circuit) assert numpy.isclose( abs(numpy.trace(true_unitary.conj().T.dot(test_unitary))), 2 ** dim)
Example 13
Project: OpenFermion-Cirq Author: quantumlib File: analysis.py License: Apache License 2.0 | 6 votes |
def energy_from_opdm(opdm, constant, one_body_tensor, two_body_tensor): """ Evaluate the energy of an opdm assuming the 2-RDM is opdm ^ opdm :param opdm: single spin-component of the full spin-orbital opdm. :param constant: constant shift to the Hamiltonian. Commonly this is the nuclear repulsion energy. :param one_body_tensor: spatial one-body integrals :param two_body_tensor: spatial two-body integrals :return: """ spin_opdm = np.kron(opdm, np.eye(2)) spin_tpdm = 2 * wedge(spin_opdm, spin_opdm, (1, 1), (1, 1)) molecular_hamiltonian = generate_hamiltonian(constant=constant, one_body_integrals=one_body_tensor, two_body_integrals=two_body_tensor) rdms = InteractionRDM(spin_opdm, spin_tpdm) return rdms.expectation(molecular_hamiltonian).real
Example 14
Project: Kaggler Author: jeongyoonlee File: linear.py License: MIT License | 6 votes |
def netflix(es, ps, e0, l=.0001): """Combine predictions with the optimal weights to minimize RMSE. Args: es (list of float): RMSEs of predictions ps (list of np.array): predictions e0 (float): RMSE of all zero prediction l (float): lambda as in the ridge regression Returns: (tuple): - (np.array): ensemble predictions - (np.array): weights for input predictions """ m = len(es) n = len(ps[0]) X = np.stack(ps).T pTy = .5 * (n * e0**2 + (X**2).sum(axis=0) - n * np.array(es)**2) w = np.linalg.pinv(X.T.dot(X) + l * n * np.eye(m)).dot(pTy) return X.dot(w), w
Example 15
Project: transferlearning Author: jindongwang File: KMM.py License: MIT License | 6 votes |
def fit(self, Xs, Xt): ''' Fit source and target using KMM (compute the coefficients) :param Xs: ns * dim :param Xt: nt * dim :return: Coefficients (Pt / Ps) value vector (Beta in the paper) ''' ns = Xs.shape[0] nt = Xt.shape[0] if self.eps == None: self.eps = self.B / np.sqrt(ns) K = kernel(self.kernel_type, Xs, None, self.gamma) kappa = np.sum(kernel(self.kernel_type, Xs, Xt, self.gamma) * float(ns) / float(nt), axis=1) K = matrix(K) kappa = matrix(kappa) G = matrix(np.r_[np.ones((1, ns)), -np.ones((1, ns)), np.eye(ns), -np.eye(ns)]) h = matrix(np.r_[ns * (1 + self.eps), ns * (self.eps - 1), self.B * np.ones((ns,)), np.zeros((ns,))]) sol = solvers.qp(K, -kappa, G, h) beta = np.array(sol['x']) return beta
Example 16
Project: transferlearning Author: jindongwang File: TCA.py License: MIT License | 6 votes |
def fit(self, Xs, Xt): ''' Transform Xs and Xt :param Xs: ns * n_feature, source feature :param Xt: nt * n_feature, target feature :return: Xs_new and Xt_new after TCA ''' X = np.hstack((Xs.T, Xt.T)) X /= np.linalg.norm(X, axis=0) m, n = X.shape ns, nt = len(Xs), len(Xt) e = np.vstack((1 / ns * np.ones((ns, 1)), -1 / nt * np.ones((nt, 1)))) M = e * e.T M = M / np.linalg.norm(M, 'fro') H = np.eye(n) - 1 / n * np.ones((n, n)) K = kernel(self.kernel_type, X, None, gamma=self.gamma) n_eye = m if self.kernel_type == 'primal' else n a, b = np.linalg.multi_dot([K, M, K.T]) + self.lamb * np.eye(n_eye), np.linalg.multi_dot([K, H, K.T]) w, V = scipy.linalg.eig(a, b) ind = np.argsort(w) A = V[:, ind[:self.dim]] Z = np.dot(A.T, K) Z /= np.linalg.norm(Z, axis=0) Xs_new, Xt_new = Z[:, :ns].T, Z[:, ns:].T return Xs_new, Xt_new
Example 17
Project: pytorch-mri-segmentation-3D Author: Achilleas File: PP.py License: MIT License | 6 votes |
def quickSave(img, wmh, gif, n): nft_img = nib.Nifti1Image(img.squeeze(), np.eye(4)) nib.save(nft_img, n + '_img.nii.gz') nft_img = nib.Nifti1Image(wmh.squeeze(), np.eye(4)) nib.save(nft_img, n + '_wmh.nii.gz') if gif is not None: nft_img = nib.Nifti1Image(gif.squeeze(), np.eye(4)) nib.save(nft_img, n + '_gif.nii.gz') #------------------------------------------------------------------------------ #END OF SLICES PREPROCESSING #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ #3D PREPROCESSING #------------------------------------------------------------------------------ #go through every 3D object from training set and every patch of size NxNxN #save resulting 3D volumes in one of the two folders based on what the center pixel of the image is
Example 18
Project: ZIFA Author: epierson9 File: ZIFA.py License: MIT License | 6 votes |
def invertFast(A, d): """ given an array A of shape d x k and a d x 1 vector d, computes (A * A.T + diag(d)) ^{-1} Checked. """ assert(A.shape[0] == d.shape[0]) assert(d.shape[1] == 1) k = A.shape[1] A = np.array(A) d_vec = np.array(d) d_inv = np.array(1 / d_vec[:, 0]) inv_d_squared = np.dot(np.atleast_2d(d_inv).T, np.atleast_2d(d_inv)) M = np.diag(d_inv) - inv_d_squared * np.dot(np.dot(A, np.linalg.inv(np.eye(k, k) + np.dot(A.T, mult_diag(d_inv, A)))), A.T) return M
Example 19
Project: gandlf Author: codekansas File: xor.py License: MIT License | 6 votes |
def get_training_data(num_samples): """Generates some training data.""" # As (x, y) Cartesian coordinates. x = np.random.randint(0, 2, size=(num_samples, 2)) y = x[:, 0] + 2 * x[:, 1] # 2-digit binary to integer. y = np.cast['int32'](y) x = np.cast['float32'](x) * 1.6 - 0.8 # Scales to [-1, 1]. x += np.random.uniform(-0.1, 0.1, size=x.shape) y_ohe = np.cast['float32'](np.eye(4)[y]) y = np.cast['float32'](np.expand_dims(y, -1)) return x, y, y_ohe
Example 20
Project: gandlf Author: codekansas File: reversing_gan.py License: MIT License | 6 votes |
def get_mnist_data(binarize=False): """Puts the MNIST data in the right format.""" (X_train, y_train), (X_test, y_test) = mnist.load_data() if binarize: X_test = np.where(X_test >= 10, 1, -1) X_train = np.where(X_train >= 10, 1, -1) else: X_train = (X_train.astype(np.float32) - 127.5) / 127.5 X_test = (X_test.astype(np.float32) - 127.5) / 127.5 X_train = np.expand_dims(X_train, axis=-1) X_test = np.expand_dims(X_test, axis=-1) y_train = np.eye(10)[y_train] y_test = np.eye(10)[y_test] return (X_train, y_train), (X_test, y_test)
Example 21
Project: libTLDA Author: wmkouw File: suba.py License: MIT License | 5 votes |
def reg_cov(self, X): """ Regularize covariance matrix until non-singular. Parameters ---------- C : array square symmetric covariance matrix. Returns ------- C : array regularized covariance matrix. """ # Compute mean of data muX = np.mean(X, axis=0, keepdims=1) # Compute covariance matrix without regularization SX = np.cov((X - muX).T) # Initialize regularization parameter reg = 1e-6 # Keep going until non-singular while not self.is_pos_def(SX): # Compute covariance matrix with regularization SX = np.cov((X - muX).T) + reg*np.eye(X.shape[1]) # Increment reg reg *= 10 # Report regularization print('Final regularization parameter = {}'.format(reg)) return SX
Example 22
Project: libTLDA Author: wmkouw File: suba.py License: MIT License | 5 votes |
def reg_cov(self, X): """ Regularize covariance matrix until non-singular. Parameters ---------- C : array square symmetric covariance matrix. Returns ------- C : array regularized covariance matrix. """ # Number of data points N = X.shape[0] # Compute mean of data muX = np.mean(X, axis=0, keepdims=1) # Compute covariance matrix without regularization SX = np.dot((X - muX).T, (X - muX)) / N # Initialize regularization parameter reg = 1e-6 # Keep going until non-singular while not self.is_pos_def(SX): # Compute covariance matrix with regularization SX = np.dot((X - muX).T, (X - muX)) / N + reg*np.eye(X.shape[1]) # Increment reg reg *= 10 # Report regularization print('Final regularization parameter = {}'.format(reg)) return SX
Example 23
Project: Att-ChemdNER Author: lingluodlut File: theano_backend.py License: Apache License 2.0 | 5 votes |
def eye(size, dtype=None, name=None): '''Instantiates an identity matrix. ''' if dtype is None: dtype = floatx() return variable(np.eye(size), dtype, name)
Example 24
Project: FRIDA Author: LCAV File: tools_fri_doa_plane.py License: MIT License | 5 votes |
def extract_off_diag(mtx): """ extract off diagonal entries in mtx. The output vector is order in a column major manner. :param mtx: input matrix to extract the off diagonal entries :return: """ # we transpose the matrix because the function np.extract will first flatten the matrix # withe ordering convention 'C' instead of 'F'!! extract_cond = np.reshape((1 - np.eye(*mtx.shape)).T.astype(bool), (-1, 1), order='F') return np.reshape(np.extract(extract_cond, mtx.T), (-1, 1), order='F')
Example 25
Project: FRIDA Author: LCAV File: tools_fri_doa_plane.py License: MIT License | 5 votes |
def hermitian_expan(half_vec_len): """ expand a real-valued vector to a Hermitian symmetric vector. The input vector is a concatenation of the real parts with NON-POSITIVE indices and the imaginary parts with STRICTLY-NEGATIVE indices. :param half_vec_len: length of the first half vector :return: """ D0 = np.eye(half_vec_len) D1 = np.vstack((D0, D0[1:, ::-1])) D2 = np.vstack((D0, -D0[1:, ::-1])) D2 = D2[:, :-1] return D1, D2
Example 26
Project: FRIDA Author: LCAV File: tools_fri_doa_plane.py License: MIT License | 5 votes |
def coef_expan_mtx(K): """ expansion matrix for an annihilating filter of size K + 1 :param K: number of Dirac. The filter size is K + 1 :return: """ if K % 2 == 0: D0 = np.eye(np.int(K / 2. + 1)) D1 = np.vstack((D0, D0[1:, ::-1])) D2 = np.vstack((D0, -D0[1:, ::-1]))[:, :-1] else: D0 = np.eye(np.int((K + 1) / 2.)) D1 = np.vstack((D0, D0[:, ::-1])) D2 = np.vstack((D0, -D0[:, ::-1])) return D1, D2
Example 27
Project: StructEngPy Author: zhuoju36 File: element.py License: MIT License | 5 votes |
def __init__(self,node_i, node_j, E, A, rho, name=None, mass='conc', tol=1e-6): """ params: node_i,node_j: ends of link. E: elastic modulus A: section area rho: mass density mass: 'coor' as coordinate matrix or 'conc' for concentrated matrix tol: tolerance """ super(Link,self).__init__(node_i,node_j,A,rho,6,name,mass) l=self._length K_data=( (E*A/l,(0,0)), (-E*A/l,(0,1)), (-E*A/l,(1,0)), (E*A/l,(1,1)), ) m_data=( (1,(0,0)), (1,(1,1))*rho*A*l/2 ) data=[k[0] for k in K_data] row=[k[1][0] for k in K_data] col=[k[1][1] for k in K_data] self._Ke = spr.csr_matrix((data,(row,col)),shape=(12, 12)) self._Me=spr.eye(2)*rho*A*l/2 #force vector self._re =np.zeros((2,1))
Example 28
Project: StructEngPy Author: zhuoju36 File: element.py License: MIT License | 5 votes |
def _N(self,s): """ params: Hermite's interpolate function s:natural position of evalue point. returns: 3x(3x4) shape function matrix. """ N1=1-3*s**2+2*s**3 N2= 3*s**2-2*s**3 N3=s-2*s**2+s**3 N4= -s**2+s**3 N=np.hstack([np.eye(3)*N1,np.eye(3)*N2,np.eye(3)*N3,np.eye(3)*N4]) return N
Example 29
Project: StructEngPy Author: zhuoju36 File: element.py License: MIT License | 5 votes |
def __init__(self,node_i, node_j, node_k, node_l, t, E, mu, rho, name=None): """ node_i,node_j,node_k: corners of triangle. t: thickness E: elastic modulus mu: Poisson ratio rho: mass density """ super(Membrane4,self).__init__(node_i,node_j,node_k,node_l,t,E,mu,rho,8) self._t=t self._E=E self._mu=mu self._rho=rho elm_node_count=4 node_dof=2 Ke = quadpy.quadrilateral.integrate( lambda s: self._BtDB(s[0],s[1])*np.linalg.det(self._J(s[0],s[1])), quadpy.quadrilateral.rectangle_points([-1.0, 1.0], [-1.0, 1.0]), quadpy.quadrilateral.Stroud('C2 7-2') ) Ke=sp.sparse.csr_matrix(Ke) row=[] col=[] for i in range(elm_node_count): row+=[a for a in range(i*node_dof,i*node_dof+node_dof)] col+=[a for a in range(i*6,i*6+node_dof)] data=[1]*(elm_node_count*node_dof) G=sp.sparse.csr_matrix((data,(row,col)),shape=(elm_node_count*node_dof,elm_node_count*6)) self._Ke=G.transpose()*Ke*G #Concentrated mass matrix, may be wrong self._Me=G.transpose()*np.eye(node_dof*elm_node_count)*G*rho*self._area*t/4 self._re =np.zeros((elm_node_count*6,1))
Example 30
Project: neural-fingerprinting Author: StephanZheng File: cw_attacks.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def attack(self, X, Y): """ Perform the L_2 attack on the given images for the given targets. :param X: samples to generate advs :param Y: the original class labels If self.targeted is true, then the targets represents the target labels. If self.targeted is false, then targets are the original class labels. """ nb_classes = Y.shape[1] # random select target class for targeted attack y_target = np.copy(Y) if self.TARGETED: for i in range(Y.shape[0]): current = int(np.argmax(Y[i])) target = np.random.choice(other_classes(nb_classes, current)) y_target[i] = np.eye(nb_classes)[target] X_adv = np.zeros_like(X) for i in tqdm(range(0, X.shape[0], self.batch_size)): start = i end = i + self.batch_size end = np.minimum(end, X.shape[0]) X_adv[start:end] = self.attack_batch(X[start:end], y_target[start:end]) return X_adv