Python numpy.reshape() Examples
The following are 30
code examples of numpy.reshape().
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: util.py From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License | 6 votes |
def train_lr_rfeinman(densities_pos, densities_neg, uncerts_pos, uncerts_neg): """ TODO :param densities_pos: :param densities_neg: :param uncerts_pos: :param uncerts_neg: :return: """ values_neg = np.concatenate( (densities_neg.reshape((1, -1)), uncerts_neg.reshape((1, -1))), axis=0).transpose([1, 0]) values_pos = np.concatenate( (densities_pos.reshape((1, -1)), uncerts_pos.reshape((1, -1))), axis=0).transpose([1, 0]) values = np.concatenate((values_neg, values_pos)) labels = np.concatenate( (np.zeros_like(densities_neg), np.ones_like(densities_pos))) lr = LogisticRegressionCV(n_jobs=-1).fit(values, labels) return values, labels, lr
Example #2
Source File: dataset.py From Deep_VoiceChanger with MIT License | 6 votes |
def wave2input_image(wave, window, pos=0, pad=0): wave_image = np.hstack([wave[pos+i*sride:pos+(i+pad*2)*sride+dif].reshape(height+pad*2, sride) for i in range(256//sride)])[:,:254] wave_image *= window spectrum_image = np.fft.fft(wave_image, axis=1) input_image = np.abs(spectrum_image[:,:128].reshape(1, height+pad*2, 128), dtype=np.float32) np.clip(input_image, 1000, None, out=input_image) np.log(input_image, out=input_image) input_image += bias input_image /= scale if np.max(input_image) > 0.95: print('input image max bigger than 0.95', np.max(input_image)) if np.min(input_image) < 0.05: print('input image min smaller than 0.05', np.min(input_image)) return input_image
Example #3
Source File: images.py From neuropythy with GNU Affero General Public License v3.0 | 6 votes |
def parse_dataobj(self, dataobj, hdat={}): # first, see if we have a specified shape/size ish = next((hdat[k] for k in ('image_size', 'image_shape', 'shape') if k in hdat), None) if ish is Ellipsis: ish = None # make a numpy array of the appropriate dtype dtype = self.parse_type(hdat, dataobj=dataobj) try: dataobj = dataobj.dataobj except Exception: pass if dataobj is not None: arr = np.asarray(dataobj).astype(dtype) elif ish: arr = np.zeros(ish, dtype=dtype) else: arr = np.zeros([1,1,1,0], dtype=dtype) # reshape to the requested shape if need-be if ish and ish != arr.shape: arr = np.reshape(arr, ish) # then reshape to a valid (4D) shape sh = arr.shape if len(sh) == 2: arr = np.reshape(arr, (sh[0], 1, 1, sh[1])) elif len(sh) == 1: arr = np.reshape(arr, (sh[0], 1, 1)) elif len(sh) == 3: arr = np.reshape(arr, sh) elif len(sh) != 4: raise ValueError('Cannot convert n-dimensional array to image if n > 4') # and return return arr
Example #4
Source File: images.py From neuropythy with GNU Affero General Public License v3.0 | 6 votes |
def image_reslice(image, spec, method=None, fill=0, dtype=None, weights=None, image_type=None): ''' image_reslice(image, spec) yields a duplicate of the given image resliced to have the voxels indicated by the given image spec. Note that spec may be an image itself. Optional arguments that can be passed to image_interpolate() (asside from affine) are allowed here and are passed through. ''' if image_type is None and is_image(image): image_type = to_image_type(image) spec = to_image_spec(spec) image = to_image(image) # we make a big mesh and interpolate at these points... imsh = spec['image_shape'] (args, kw) = ([np.arange(n) for n in imsh[:3]], {'indexing': 'ij'}) ijk = np.asarray([u.flatten() for u in np.meshgrid(*args, **kw)]) ijk = np.dot(spec['affine'], np.vstack([ijk, np.ones([1,ijk.shape[1]])]))[:3] # interpolate here... u = image_interpolate(image, ijk, method=method, fill=fill, dtype=dtype, weights=weights) return to_image((np.reshape(u, imsh), spec), image_type=image_type)
Example #5
Source File: utils.py From Att-ChemdNER with Apache License 2.0 | 6 votes |
def set_values(name, param, pretrained): #{{{ """ Initialize a network parameter with pretrained values. We check that sizes are compatible. """ param_value = param.get_value() if pretrained.size != param_value.size: raise Exception( "Size mismatch for parameter %s. Expected %i, found %i." % (name, param_value.size, pretrained.size) ) param.set_value(np.reshape( pretrained, param_value.shape ).astype(np.float32)) #}}}
Example #6
Source File: gla_gpu.py From Deep_VoiceChanger with MIT License | 6 votes |
def auto_inverse(self, whole_spectrum): whole_spectrum = np.copy(whole_spectrum).astype(complex) whole_spectrum[whole_spectrum < 1] = 1 overwrap = self.buffer_size * 2 height = whole_spectrum.shape[0] parallel_dif = (height-overwrap) // self.parallel if height < self.parallel*overwrap: raise Exception('voice length is too small to use gpu, or parallel number is too big') spec = [self.inverse(whole_spectrum[range(i, i+parallel_dif*self.parallel, parallel_dif), :]) for i in tqdm.tqdm(range(parallel_dif+overwrap))] spec = spec[overwrap:] spec = np.concatenate(spec, axis=1) spec = spec.reshape(-1, self.wave_len) #Below code don't consider wave_len and wave_dif, I'll fix. wave = np.fft.ifft(spec, axis=1).real pad = np.zeros((wave.shape[0], 2), dtype=float) wave = np.concatenate([wave, pad], axis=1) dst = np.zeros((wave.shape[0]+3)*self.wave_dif, dtype=float) for i in range(4): w = wave[range(i, wave.shape[0], 4),:] w = w.reshape(-1) dst[i*self.wave_dif:i*self.wave_dif+len(w)] += w return dst*0.5
Example #7
Source File: core.py From neuropythy with GNU Affero General Public License v3.0 | 6 votes |
def cplus(*args): ''' cplus(a, b...) returns the sum of all the values as a numpy array object. Like numpy's add function or a+b syntax, plus will thread over the latest dimension possible. Additionally, cplus works correctly with sparse arrays. ''' n = len(args) if n == 0: return np.asarray(0) elif n == 1: return np.asarray(args[0]) elif n > 2: return reduce(plus, args) (a,b) = args if sps.issparse(a): if not sps.issparse(b): b = np.asarray(b) if len(b.shape) == 0: b = np.reshape(b, (1,1)) elif sps.issparse(b): a = np.asarray(a) if len(a.shape) == 0: a = np.reshape(a, (1,1)) else: a = np.asarray(a) b = np.asarray(b) return a + b
Example #8
Source File: util.py From neuropythy with GNU Affero General Public License v3.0 | 6 votes |
def point_on_segment(ac, b, atol=1e-8): ''' point_on_segment((a,b), c) yields True if point x is on segment (a,b) and False otherwise. Note that this differs from point_in_segment in that a point that if c is equal to a or b it is considered 'on' but not 'in' the segment. The option atol can be given and is used only to test for difference from 0; by default it is 1e-8. ''' (a,c) = ac abc = [np.asarray(u) for u in (a,b,c)] if any(len(u.shape) > 1 for u in abc): (a,b,c) = [np.reshape(u,(len(u),-1)) for u in abc] else: (a,b,c) = abc vab = b - a vbc = c - b vac = c - a dab = np.sqrt(np.sum(vab**2, axis=0)) dbc = np.sqrt(np.sum(vbc**2, axis=0)) dac = np.sqrt(np.sum(vac**2, axis=0)) return np.isclose(dab + dbc - dac, 0, atol=atol)
Example #9
Source File: tools_fri_doa_plane.py From FRIDA with MIT License | 6 votes |
def mtx_freq2visi(M, p_mic_x, p_mic_y): """ build the matrix that maps the Fourier series to the visibility :param M: the Fourier series expansion is limited from -M to M :param p_mic_x: a vector that constains microphones x coordinates :param p_mic_y: a vector that constains microphones y coordinates :return: """ num_mic = p_mic_x.size ms = np.reshape(np.arange(-M, M + 1, step=1), (1, -1), order='F') G = np.zeros((num_mic * (num_mic - 1), 2 * M + 1), dtype=complex, order='C') count_G = 0 for q in range(num_mic): p_x_outer = p_mic_x[q] p_y_outer = p_mic_y[q] for qp in range(num_mic): if not q == qp: p_x_qqp = p_x_outer - p_mic_x[qp] p_y_qqp = p_y_outer - p_mic_y[qp] norm_p_qqp = np.sqrt(p_x_qqp ** 2 + p_y_qqp ** 2) phi_qqp = np.arctan2(p_y_qqp, p_x_qqp) G[count_G, :] = (-1j) ** ms * sp.special.jv(ms, norm_p_qqp) * \ np.exp(1j * ms * phi_qqp) count_G += 1 return G
Example #10
Source File: core.py From neuropythy with GNU Affero General Public License v3.0 | 6 votes |
def apply_affine(aff, coords): ''' apply_affine(affine, coords) yields the result of applying the given affine transformation to the given coordinate or coordinates. This function expects coords to be a (dims X n) matrix but if the first dimension is neither 2 nor 3, coords.T is used; i.e.: apply_affine(affine3x3, coords2xN) ==> newcoords2xN apply_affine(affine4x4, coords3xN) ==> newcoords3xN apply_affine(affine3x3, coordsNx2) ==> newcoordsNx2 (for N != 2) apply_affine(affine4x4, coordsNx3) ==> newcoordsNx3 (for N != 3) ''' if aff is None: return coords (coords,tr) = (np.asanyarray(coords), False) if len(coords.shape) == 1: return np.squeeze(apply_affine(np.reshape(coords, (-1,1)), aff)) elif len(coords.shape) > 2: raise ValueError('cannot apply affine to ND-array for N > 2') if len(coords) == 2: aff = to_affine(aff, 2) elif len(coords) == 3: aff = to_affine(aff, 3) else: (coords,aff,tr) = (coords.T, to_affine(aff, coords.shape[1]), True) r = np.dot(aff, np.vstack([coords, np.ones([1,coords.shape[1]])]))[:-1] return r.T if tr else r
Example #11
Source File: util.py From neuropythy with GNU Affero General Public License v3.0 | 6 votes |
def point_in_segment(ac, b, atol=1e-8): ''' point_in_segment((a,b), c) yields True if point x is in segment (a,b) and False otherwise. Note that this differs from point_on_segment in that a point that if c is equal to a or b it is considered 'on' but not 'in' the segment. The option atol can be given and is used only to test for difference from 0; by default it is 1e-8. ''' (a,c) = ac abc = [np.asarray(u) for u in (a,b,c)] if any(len(u.shape) > 1 for u in abc): (a,b,c) = [np.reshape(u,(len(u),-1)) for u in abc] else: (a,b,c) = abc vab = b - a vbc = c - b vac = c - a dab = np.sqrt(np.sum(vab**2, axis=0)) dbc = np.sqrt(np.sum(vbc**2, axis=0)) dac = np.sqrt(np.sum(vac**2, axis=0)) return (np.isclose(dab + dbc - dac, 0, atol=atol) & ~np.isclose(dac - dab, 0, atol=atol) & ~np.isclose(dac - dbc, 0, atol=atol))
Example #12
Source File: core.py From neuropythy with GNU Affero General Public License v3.0 | 6 votes |
def jacobian(self, p, into=None): # transpose to be 3 x 2 x n p = np.transpose(np.reshape(p, (-1, 3, 2)), (1,2,0)) # First, get the two legs... (dx_ab, dy_ab) = p[1] - p[0] (dx_ac, dy_ac) = p[2] - p[0] (dx_bc, dy_bc) = p[2] - p[1] # now, the area is half the z-value of the cross-product... sarea0 = 0.5 * (dx_ab*dy_ac - dx_ac*dy_ab) # but we want to abs it dsarea0 = np.sign(sarea0) z = np.transpose([[-dy_bc,dx_bc], [dy_ac,-dx_ac], [-dy_ab,dx_ab]], (2,0,1)) z = times(0.5*dsarea0, z) m = numel(p) n = p.shape[2] ii = (np.arange(n) * np.ones([6, n])).T.flatten() z = sps.csr_matrix((z.flatten(), (ii, np.arange(len(ii)))), shape=(n, m)) return safe_into(into, z)
Example #13
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 #14
Source File: core.py From neuropythy with GNU Affero General Public License v3.0 | 6 votes |
def row_norms(ii, f=Ellipsis, squared=False): ''' row_norms(ii) yields a potential function h(x) that calculates the vector norms of the rows of the matrix formed by [x[i] for i in ii] (ii is a matrix of parameter indices). row_norms(ii, f) yield a potential function h(x) equivalent to compose(row_norms(ii), f). ''' try: (n,m) = ii # matrix shape given ii = np.reshape(np.arange(n*m), (n,m)) except Exception: ii = np.asarray(ii) f = to_potential(f) if is_const_potential(f): q = flattest(f.c) q = np.sum([q[i]**2 for i in ii.T], axis=0) return PotentialConstant(q if squared else np.sqrt(q)) F = reduce(lambda a,b: a + b, [part(Ellipsis, col)**2 for col in ii.T]) F = compose(F, f) if not squared: F = sqrt(F) return F
Example #15
Source File: core.py From neuropythy with GNU Affero General Public License v3.0 | 6 votes |
def col_norms(ii, f=Ellipsis, squared=False): ''' col_norms(ii) yields a potential function h(x) that calculates the vector norms of the columns of the matrix formed by [x[i] for i in ii] (ii is a matrix of parameter indices). col_norms(ii, f) yield a potential function h(x) equivalent to compose(col_norms(ii), f). ''' try: (n,m) = ii # matrix shape given ii = np.reshape(np.arange(n*m), (n,m)) except Exception: ii = np.asarray(ii) f = to_potential(f) if is_const_potential(f): q = flattest(f.c) q = np.sum([q[i]**2 for i in ii], axis=0) return PotentialConstant(q if squared else np.sqrt(q)) F = reduce(lambda a,b: a + b, [part(Ellipsis, col)**2 for col in ii]) F = compose(F, f) if not squared: F = sqrt(F) return F
Example #16
Source File: core.py From neuropythy with GNU Affero General Public License v3.0 | 6 votes |
def distances(a, b, shape, squared=False, axis=1): ''' distances(a, b, (n,d)) yields a potential function whose output is equivalent to the row-norms of reshape(a(x), (n,d)) - reshape(b(x), (n,d)). The shape argument (n,m) may alternately be a matrix of parameter indices, as can be passed to row_norms and col_norms. The following optional arguments are accepted: * squared (default: False) specifies whether the output should be the square distance or the distance. * axis (default: 1) specifies whether the rows (axis = 1) or columns (axis = 0) are treated as the vectors between which the distances should be calculated. ''' a = to_potential(a) b = to_potential(b) if axis == 1: return row_norms(shape, a - b, squared=squared) else: return col_norms(shape, a - b, squared=squared)
Example #17
Source File: custom_datasets.py From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __getitem__(self, index): img=self.adv_flat[self.sample_num,:] if(self.transp == False): # shuff is true for non-pgd attacks img = torch.from_numpy(np.reshape(img,(28,28))) else: img = torch.from_numpy(img).type(torch.FloatTensor) target = np.argmax(self.adv_dict["adv_labels"],axis=1)[self.sample_num] # doing this so that it is consistent with all other datasets # to return a PIL Image if self.transform is not None: img = self.transform(img) if self.target_transform is not None: target = self.target_transform(target) self.sample_num = self.sample_num + 1 return img, target
Example #18
Source File: custom_datasets.py From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __getitem__(self, index): img=self.adv_flat[self.sample_num,:] if(self.shuff == False): # shuff is true for non-pgd attacks img = torch.from_numpy(np.reshape(img,(3,32,32))) else: img = torch.from_numpy(img).type(torch.FloatTensor) target = np.argmax(self.adv_dict["adv_labels"],axis=1)[self.sample_num] # doing this so that it is consistent with all other datasets # to return a PIL Image if self.transform is not None: img = self.transform(img) if self.target_transform is not None: target = self.target_transform(target) self.sample_num = self.sample_num + 1 return img, target
Example #19
Source File: custom_datasets.py From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __getitem__(self, index): img=self.adv_flat[self.sample_num,:] if(self.shuff == False): # shuff is true for non-pgd attacks img = torch.from_numpy(np.reshape(img,(3,224,224))) else: img = torch.from_numpy(img).type(torch.FloatTensor) target = self.adv_dict["adv_labels"][self.sample_num] # doing this so that it is consistent with all other datasets # to return a PIL Image if self.transform is not None: img = self.transform(img) if self.target_transform is not None: target = self.target_transform(target) self.sample_num = self.sample_num + 1 return img, target
Example #20
Source File: custom_datasets.py From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __getitem__(self, index): img=self.adv_flat[self.sample_num,:] if(self.shuff == False): # shuff is true for non-pgd attacks img = torch.from_numpy(np.reshape(img,(3,32,32))) else: img = torch.from_numpy(img).type(torch.FloatTensor) target = np.argmax(self.adv_dict["adv_labels"],axis=1)[self.sample_num] # doing this so that it is consistent with all other datasets # to return a PIL Image if self.transform is not None: img = self.transform(img) if self.target_transform is not None: target = self.target_transform(target) self.sample_num = self.sample_num + 1 return img, target
Example #21
Source File: core.py From neuropythy with GNU Affero General Public License v3.0 | 6 votes |
def signed_face_areas(faces, axis=1): ''' signed_face_areas(faces) yields a potential function f(x) that calculates the signed area of each face represented by the simplices matrix faces. If faces is None, then the parameters must arrive in the form of a flattened (n x 3 x 2) matrix where n is the number of triangles. Otherwise, the faces matrix must be either (n x 3) or (n x 3 x s); if the former, each row must list the vertex indices for the faces where the vertex matrix is presumed to be shaped (V x 2). Alternately, faces may be a full (n x 3 x 2) simplex array of the indices into the parameters. The optional argument axis (default: 1) may be set to 0 if the faces argument is a matrix but the coordinate matrix will be (2 x V) instead of (V x 2). ''' faces = np.asarray(faces) if len(faces.shape) == 2: if faces.shape[1] != 3: faces = faces.T n = 2 * (np.max(faces) + 1) if axis == 0: tmp = np.reshape(np.arange(n), (2,-1)).T else: tmp = np.reshape(np.arange(n), (-1,2)) faces = np.reshape(tmp[faces.flat], (-1,3,2)) faces = faces.flatten() return compose(TriangleSignedArea2DPotential(), part(Ellipsis, faces))
Example #22
Source File: core.py From neuropythy with GNU Affero General Public License v3.0 | 6 votes |
def face_areas(faces, axis=1): ''' face_areas(faces) yields a potential function f(x) that calculates the unsigned area of each faces represented by the simplices matrix faces. If faces is None, then the parameters must arrive in the form of a flattened (n x 3 x 2) matrix where n is the number of triangles. Otherwise, the faces matrix must be either (n x 3) or (n x 3 x s); if the former, each row must list the vertex indices for the faces where the vertex matrix is presumed to be shaped (V x 2). Alternately, faces may be a full (n x 3 x 2) simplex array of the indices into the parameters. The optional argument axis (default: 1) may be set to 0 if the faces argument is a matrix but the coordinate matrix will be (2 x V) instead of (V x 2). ''' faces = np.asarray(faces) if len(faces.shape) == 2: if faces.shape[1] != 3: faces = faces.T n = 2 * (np.max(faces) + 1) if axis == 0: tmp = np.reshape(np.arange(n), (2,-1)).T else: tmp = np.reshape(np.arange(n), (-1,2)) faces = np.reshape(tmp[faces.flat], (-1,3,2)) faces = faces.flatten() return compose(TriangleArea2DPotential(), part(Ellipsis, faces))
Example #23
Source File: 4_multi_classification.py From deep-learning-note with MIT License | 5 votes |
def one_vs_all(X, y, num_labels, learning_rate): rows = X.shape[0] params = X.shape[1] # k X (n + 1) array for the parameters of each of the k classifiers all_theta = np.zeros((num_labels, params + 1)) # insert a column of ones at the beginning for the intercept term X = np.insert(X, 0, values=np.ones(rows), axis=1) # labels are 1-indexed instead of 0-indexed for i in range(1, num_labels + 1): theta = np.zeros(params + 1) y_i = np.array([1 if label == i else 0 for label in y]) y_i = np.reshape(y_i, (rows, 1)) # minimize the objective function fmin = minimize(fun=cost, x0=theta, args=(X, y_i, learning_rate), method='TNC', jac=gradient) all_theta[i-1,:] = fmin.x return all_theta
Example #24
Source File: img_segmentation.py From neural-pipeline with MIT License | 5 votes |
def dice(preds: torch.Tensor, trues: torch.Tensor) -> np.ndarray: preds_inner = preds.data.cpu().numpy().copy() trues_inner = trues.data.cpu().numpy().copy() preds_inner = np.reshape(preds_inner, (preds_inner.shape[0], preds_inner.size // preds_inner.shape[0])) trues_inner = np.reshape(trues_inner, (trues_inner.shape[0], trues_inner.size // trues_inner.shape[0])) intersection = (preds_inner * trues_inner).sum(1) scores = (2. * intersection + eps) / (preds_inner.sum(1) + trues_inner.sum(1) + eps) return scores
Example #25
Source File: img_segmentation.py From neural-pipeline with MIT License | 5 votes |
def jaccard(preds: torch.Tensor, trues: torch.Tensor): preds_inner = preds.cpu().data.numpy().copy() trues_inner = trues.cpu().data.numpy().copy() preds_inner = np.reshape(preds_inner, (preds_inner.shape[0], preds_inner.size // preds_inner.shape[0])) trues_inner = np.reshape(trues_inner, (trues_inner.shape[0], trues_inner.size // trues_inner.shape[0])) intersection = (preds_inner * trues_inner).sum(1) scores = (intersection + eps) / ((preds_inner + trues_inner).sum(1) - intersection + eps) return scores
Example #26
Source File: images.py From neuropythy with GNU Affero General Public License v3.0 | 5 votes |
def to_image(self, arr, hdat={}): # reshape the data object or create it empty if None was given: arr = self.parse_dataobj(arr, hdat) # get the affine aff = self.parse_affine(hdat, dataobj=arr) # get the keyword arguments kw = self.parse_kwargs(arr, hdat) # create an image of the appropriate type cls = self.image_type() img = cls(arr, aff, **kw) # post-process the image return self.postprocess_image(img, hdat)
Example #27
Source File: nnp.py From mlearn with BSD 3-Clause "New" or "Revised" License | 5 votes |
def load_weights(self, weights_filename): """ Load weights file of trained Neural Network Potential. Args weights_filename (str): The weights file. """ with open(weights_filename) as f: weights_lines = f.readlines() weight_param = pd.DataFrame([line.split() for line in weights_lines if "#" not in line]) weight_param.columns = ['value', 'type', 'index', 'start_layer', 'start_neuron', 'end_layer', 'end_neuron'] for layer_index in range(1, len(self.layer_sizes)): weights_group = weight_param[(weight_param['start_layer'] == str(layer_index - 1)) & (weight_param['end_layer'] == str(layer_index))] weights = np.reshape(np.array(weights_group['value'], dtype=np.float), (self.layer_sizes[layer_index - 1], self.layer_sizes[layer_index])) self.weights.append(weights) bs_group = weight_param[(weight_param['type'] == 'b') & (weight_param['start_layer'] == str(layer_index))] bs = np.array(bs_group['value'], dtype=np.float) self.bs.append(bs) self.weight_param = weight_param
Example #28
Source File: util.py From neuropythy with GNU Affero General Public License v3.0 | 5 votes |
def points_close(a,b, atol=1e-8): ''' points_close(a,b) yields True if points a and b are close to each other and False otherwise. ''' (a,b) = [np.asarray(u) for u in (a,b)] if len(a.shape) == 2 or len(b.shape) == 2: (a,b) = [np.reshape(u,(len(u),-1)) for u in (a,b)] return np.isclose(np.sqrt(np.sum((a - b)**2, axis=0)), 0, atol=atol)
Example #29
Source File: core.py From neuropythy with GNU Affero General Public License v3.0 | 5 votes |
def minimize(self, x0, **kwargs): ''' pf.minimize(x0) minimizes the given potential function starting at the given point x0; any additional options are passed along to scipy.optimize.minimize. ''' x0 = np.asarray(x0) kwargs = pimms.merge({'jac':self.jac(), 'method':'CG'}, kwargs) res = spopt.minimize(self.fun(), x0.flatten(), **kwargs) res.x = np.reshape(res.x, x0.shape) return res
Example #30
Source File: core.py From neuropythy with GNU Affero General Public License v3.0 | 5 votes |
def _diff_order(n): u0 = np.arange(n) d = int(np.ceil(np.sqrt(n))) mtx = np.reshape(np.pad(u0, [(0,d*d-n)], 'constant', constant_values=[(0,-1)]), (d,d)) h = int((d+1)/2) u = np.vstack([mtx[::2], mtx[1::2]]).T.flatten() return u[u >= 0]