Python numpy.pi() Examples
The following are 30
code examples of numpy.pi().
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: mel_features.py From sklearn-audio-transfer-learning with ISC License | 8 votes |
def periodic_hann(window_length): """Calculate a "periodic" Hann window. The classic Hann window is defined as a raised cosine that starts and ends on zero, and where every value appears twice, except the middle point for an odd-length window. Matlab calls this a "symmetric" window and np.hanning() returns it. However, for Fourier analysis, this actually represents just over one cycle of a period N-1 cosine, and thus is not compactly expressed on a length-N Fourier basis. Instead, it's better to use a raised cosine that ends just before the final zero value - i.e. a complete cycle of a period-N cosine. Matlab calls this a "periodic" window. This routine calculates it. Args: window_length: The number of points in the returned window. Returns: A 1D np.array containing the periodic hann window. """ return 0.5 - (0.5 * np.cos(2 * np.pi / window_length * np.arange(window_length)))
Example #2
Source File: point_cloud.py From FRIDA with MIT License | 7 votes |
def doa(self, receiver, source): ''' Computes the direction of arrival wrt a source and receiver ''' s_ind = self.key2ind(source) r_ind = self.key2ind(receiver) # vector from receiver to source v = self.X[:,s_ind] - self.X[:,r_ind] azimuth = np.arctan2(v[1], v[0]) elevation = np.arctan2(v[2], la.norm(v[:2])) azimuth = azimuth + 2*np.pi if azimuth < 0. else azimuth elevation = elevation + 2*np.pi if elevation < 0. else elevation return np.array([azimuth, elevation])
Example #3
Source File: spectrum_painter.py From spectrum_painter with MIT License | 7 votes |
def convert_image(self, filename): pic = img.imread(filename) # Set FFT size to be double the image size so that the edge of the spectrum stays clear # preventing some bandfilter artifacts self.NFFT = 2*pic.shape[1] # Repeat image lines until each one comes often enough to reach the desired line time ffts = (np.flipud(np.repeat(pic[:, :, 0], self.repetitions, axis=0) / 16.)**2.) / 256. # Embed image in center bins of the FFT fftall = np.zeros((ffts.shape[0], self.NFFT)) startbin = int(self.NFFT/4) fftall[:, startbin:(startbin+pic.shape[1])] = ffts # Generate random phase vectors for the FFT bins, this is important to prevent high peaks in the output # The phases won't be visible in the spectrum phases = 2*np.pi*np.random.rand(*fftall.shape) rffts = fftall * np.exp(1j*phases) # Perform the FFT per image line, then concatenate them to form the final signal timedata = np.fft.ifft(np.fft.ifftshift(rffts, axes=1), axis=1) / np.sqrt(float(self.NFFT)) linear = timedata.flatten() linear = linear / np.max(np.abs(linear)) return linear
Example #4
Source File: vertcoord.py From aospy with Apache License 2.0 | 6 votes |
def to_radians(arr, is_delta=False): """Force data with units either degrees or radians to be radians.""" # Infer the units from embedded metadata, if it's there. try: units = arr.units except AttributeError: pass else: if units.lower().startswith('degrees'): warn_msg = ("Conversion applied: degrees -> radians to array: " "{}".format(arr)) logging.debug(warn_msg) return np.deg2rad(arr) # Otherwise, assume degrees if the values are sufficiently large. threshold = 0.1*np.pi if is_delta else 4*np.pi if np.max(np.abs(arr)) > threshold: warn_msg = ("Conversion applied: degrees -> radians to array: " "{}".format(arr)) logging.debug(warn_msg) return np.deg2rad(arr) return arr
Example #5
Source File: distributions.py From DOTA_models with Apache License 2.0 | 6 votes |
def gaussian_pos_log_likelihood(unused_mean, logvar, noise): """Gaussian log-likelihood function for a posterior in VAE Note: This function is specialized for a posterior distribution, that has the form of z = mean + sigma * noise. Args: unused_mean: ignore logvar: The log variance of the distribution noise: The noise used in the sampling of the posterior. Returns: The log-likelihood under the Gaussian model. """ # ln N(z; mean, sigma) = - ln(sigma) - 0.5 ln 2pi - noise^2 / 2 return - 0.5 * (logvar + np.log(2 * np.pi) + tf.square(noise))
Example #6
Source File: distributions.py From DOTA_models with Apache License 2.0 | 6 votes |
def diag_gaussian_log_likelihood(z, mu=0.0, logvar=0.0): """Log-likelihood under a Gaussian distribution with diagonal covariance. Returns the log-likelihood for each dimension. One should sum the results for the log-likelihood under the full multidimensional model. Args: z: The value to compute the log-likelihood. mu: The mean of the Gaussian logvar: The log variance of the Gaussian. Returns: The log-likelihood under the Gaussian model. """ return -0.5 * (logvar + np.log(2*np.pi) + \ tf.square((z-mu)/tf.exp(0.5*logvar)))
Example #7
Source File: core.py From neuropythy with GNU Affero General Public License v3.0 | 6 votes |
def cos_edge(f=Ellipsis, width=np.pi, offset=0, scale=1): ''' cos_edge() yields a potential function g(x) that calculates 0 for x < pi/2, 1 for x > pi/2, and 0.5*(1 + cos(pi/2*(1 - x))) for x between -pi/2 and pi/2. The full formulat of the cosine well is, including optional arguments: scale/2 * (1 + cos(pi*(0.5 - (x - offset)/width) The following optional arguments may be given: * width (default: pi) specifies that the frequency of the cos-curve should be pi/width; the width is the distance between the points on the cos-curve with the value of 1. * offset (default: 0) specifies the offset of the minimum value of the coine curve on the x-axis. * scale (default: 1) specifies the height of the cosine well. ''' f = to_potential(f) freq = np.pi/2 (xmn,xmx) = (offset - width/2, offset + width/2) F = piecewise(scale, ((-np.inf, xmn), 0), ((xmn,xmx), scale/2 * (1 + cos(np.pi*(0.5 - (identity - offset)/width))))) if is_const_potential(f): return const_potential(F.value(f.c)) elif is_identity_potential(f): return F else: return compose(F, f)
Example #8
Source File: core.py From neuropythy with GNU Affero General Public License v3.0 | 6 votes |
def cos_well(f=Ellipsis, width=np.pi/2, offset=0, scale=1): ''' cos_well() yields a potential function g(x) that calculates 0.5*(1 - cos(x)) for -pi/2 <= x <= pi/2 and is 1 outside of that range. The full formulat of the cosine well is, including optional arguments: scale / 2 * (1 - cos((x - offset) / (width/pi))) The following optional arguments may be given: * width (default: pi) specifies that the frequency of the cos-curve should be pi/width; the width is the distance between the points on the cos-curve with the value of 1. * offset (default: 0) specifies the offset of the minimum value of the coine curve on the x-axis. * scale (default: 1) specifies the height of the cosine well. ''' f = to_potential(f) freq = np.pi/width*2 (xmn,xmx) = (offset - width/2, offset + width/2) F = piecewise(scale, ((xmn,xmx), scale/2 * (1 - cos(freq * (identity - offset))))) if is_const_potential(f): return const_potential(F.value(f.c)) elif is_identity_potential(f): return F else: return compose(F, f)
Example #9
Source File: core.py From neuropythy with GNU Affero General Public License v3.0 | 6 votes |
def vertex_eccen(m, property=None): p = vertex_prop(m, property) if p is None: ecc0 = next((m[k] for kk in _vertex_angle_prefixes for k in [kk + 'eccentricity'] if k in m), None) if ecc0 is not None: return ecc0 ecc0 = next((m[k] for kk in _vertex_angle_prefixes for k in [kk + 'rho'] if k in m), None) if ecc0 is not None: return 180.0/np.pi*ecc0 return None return p
Example #10
Source File: nav_env.py From DOTA_models with Apache License 2.0 | 6 votes |
def get_loc_axis(self, node, delta_theta, perturb=None): """Based on the node orientation returns X, and Y axis. Used to sample the map in egocentric coordinate frame. """ if type(node) == tuple: node = np.array([node]) if perturb is None: perturb = np.zeros((node.shape[0], 4)) xyt = self.to_actual_xyt_vec(node) x = xyt[:,[0]] + perturb[:,[0]] y = xyt[:,[1]] + perturb[:,[1]] t = xyt[:,[2]] + perturb[:,[2]] theta = t*delta_theta loc = np.concatenate((x,y), axis=1) x_axis = np.concatenate((np.cos(theta), np.sin(theta)), axis=1) y_axis = np.concatenate((np.cos(theta+np.pi/2.), np.sin(theta+np.pi/2.)), axis=1) # Flip the sampled map where need be. y_axis[np.where(perturb[:,3] > 0)[0], :] *= -1. return loc, x_axis, y_axis, theta
Example #11
Source File: ffft_test.py From OpenFermion-Cirq with Apache License 2.0 | 6 votes |
def _fourier_transform_single_fermionic_modes( amplitudes: List[complex]) -> List[complex]: """Fermionic Fourier transform of a list of single Fermionic modes. Args: amplitudes: List of amplitudes for each Fermionic mode. Return: List representing a new, Fourier transformed amplitudes of the input amplitudes. """ def fft(k, n): unit = np.exp(-2j * np.pi * k / n) return sum(unit**j * amplitudes[j] for j in range(n)) / np.sqrt(n) n = len(amplitudes) return [fft(k, n) for k in range(n)]
Example #12
Source File: ffft_test.py From OpenFermion-Cirq with Apache License 2.0 | 6 votes |
def test_ffft_equal_to_bogoliubov(size): def fourier_transform_matrix(): root_of_unity = np.exp(-2j * np.pi / size) return np.array([[root_of_unity ** (j * k) for k in range(size)] for j in range(size)]) / np.sqrt(size) qubits = LineQubit.range(size) ffft_circuit = cirq.Circuit( ffft(qubits), strategy=cirq.InsertStrategy.EARLIEST) ffft_matrix = ffft_circuit.unitary( qubits_that_should_be_present=qubits) bogoliubov_circuit = cirq.Circuit( bogoliubov_transform(qubits, fourier_transform_matrix()), strategy=cirq.InsertStrategy.EARLIEST) bogoliubov_matrix = bogoliubov_circuit.unitary( qubits_that_should_be_present=qubits) cirq.testing.assert_allclose_up_to_global_phase( ffft_matrix, bogoliubov_matrix, atol=1e-8 )
Example #13
Source File: rotation_utils.py From DOTA_models with 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 #14
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 #15
Source File: test_xrft.py From xrft with MIT License | 6 votes |
def test_cross_phase_2d(self, dask): Ny, Nx = (32, 16) x = np.linspace(0, 1, num=Nx, endpoint=False) y = np.ones(Ny) f = 6 phase_offset = np.pi/2 signal1 = np.cos(2*np.pi*f*x) # frequency = 1/(2*pi) signal2 = np.cos(2*np.pi*f*x - phase_offset) da1 = xr.DataArray(data=signal1*y[:,np.newaxis], name='a', dims=['y','x'], coords={'y':y, 'x':x}) da2 = xr.DataArray(data=signal2*y[:,np.newaxis], name='b', dims=['y','x'], coords={'y':y, 'x':x}) with pytest.raises(ValueError): xrft.cross_phase(da1, da2, dim=['y','x']) if dask: da1 = da1.chunk({'x': 16}) da2 = da2.chunk({'x': 16}) cp = xrft.cross_phase(da1, da2, dim=['x']) actual_phase_offset = cp.sel(freq_x=f).values npt.assert_almost_equal(actual_phase_offset, phase_offset)
Example #16
Source File: __init__.py From neuropythy with GNU Affero General Public License v3.0 | 6 votes |
def test_cmag(self): ''' test_cmag() ensures that the neuropythy.vision cortical magnification function is working. ''' import neuropythy.vision as vis logging.info('neuropythy: Testing areal cortical magnification...') dset = ny.data['benson_winawer_2018'] sub = dset.subjects['S1202'] hem = [sub.lh, sub.rh][np.random.randint(2)] cm = vis.areal_cmag(hem.midgray_surface, 'prf_', mask=('inf-prf_visual_area', 1), weight='prf_variance_explained') # cmag should get smaller in general ths = np.arange(0, 2*np.pi, np.pi/3) es = [0.5, 1, 2, 4] x = np.diff([np.mean(cm(e*np.cos(ths), e*np.sin(ths))) for e in es]) self.assertTrue((x < 0).all())
Example #17
Source File: AngleConstraints.py From fullrmc with GNU Affero General Public License v3.0 | 5 votes |
def _get_export(self, frameIndex, propertiesLUT, format='%s'): # create data, metadata and header frame = propertiesLUT['frames-name'][frameIndex] data = propertiesLUT['frames-data'][frameIndex] # compute categories names = self.engine.get_original_data("allNames", frame=frame) elements = self.engine.get_original_data("allElements", frame=frame) atom2 = self.__anglesList[0] atom1 = self.__anglesList[1] atom3 = self.__anglesList[2] lower = self.__anglesList[3]*180./np.pi upper = self.__anglesList[4]*180./np.pi consData = data["angles"]*180./np.pi header = ['atom_1_index', 'atom_2_index', 'atom_3_index', 'atom_1_element', 'atom_2_element', 'atom_3_element', 'atom_1_name', 'atom_2_name', 'atom_3_name', 'lower_limit', 'upper_limit', 'value'] data = [] for idx in xrange(self.__anglesList[0].shape[0]): #if self._atomsCollector.is_collected(idx): # continue if self._atomsCollector.is_collected(atom1[idx]): continue if self._atomsCollector.is_collected(atom2[idx]): continue if self._atomsCollector.is_collected(atom3[idx]): continue data.append([str(atom1[idx]),str(atom2[idx]),str(atom3[idx]), elements[atom1[idx]],elements[atom2[idx]],elements[atom3[idx]], names[atom1[idx]],names[atom2[idx]],names[atom3[idx]], format%lower[idx], format%upper[idx], format%consData[idx]] ) # save return header, data
Example #18
Source File: common_gates.py From OpenFermion-Cirq with Apache License 2.0 | 5 votes |
def Ryxxy(rads: float) -> cirq.PhasedISwapPowGate: """Returns a gate with the matrix exp(-i rads (Y⊗X - X⊗Y) / 2).""" pi = sympy.pi if isinstance(rads, sympy.Basic) else np.pi return cirq.PhasedISwapPowGate(exponent=2 * rads / pi)
Example #19
Source File: common_gates.py From OpenFermion-Cirq with Apache License 2.0 | 5 votes |
def Rxxyy(rads: float) -> cirq.ISwapPowGate: """Returns a gate with the matrix exp(-i rads (X⊗X + Y⊗Y) / 2).""" pi = sympy.pi if isinstance(rads, sympy.Basic) else np.pi return cirq.ISwapPowGate(exponent=-2 * rads / pi)
Example #20
Source File: ImproperAngleConstraints.py From fullrmc with GNU Affero General Public License v3.0 | 5 votes |
def _get_export(self, frameIndex, propertiesLUT, format='%s'): # create data, metadata and header frame = propertiesLUT['frames-name'][frameIndex] data = propertiesLUT['frames-data'][frameIndex] # compute categories names = self.engine.get_original_data("allNames", frame=frame) elements = self.engine.get_original_data("allElements", frame=frame) atom2 = self.__anglesList[0] atom1 = self.__anglesList[1] atom3 = self.__anglesList[2] atom4 = self.__anglesList[3] lower = self.__anglesList[4]*180./np.pi upper = self.__anglesList[5]*180./np.pi consData = data["angles"]*180./np.pi header = ['atom_1_index', 'atom_2_index', 'atom_3_index', 'atom_4_index', 'atom_1_element', 'atom_2_element', 'atom_3_element','atom_4_element', 'atom_1_name', 'atom_2_name', 'atom_3_name', 'atom_4_name', 'lower_limit', 'upper_limit', 'value'] data = [] for idx in xrange(self.__anglesList[0].shape[0]): #if self._atomsCollector.is_collected(idx): # continue if self._atomsCollector.is_collected(atom1[idx]): continue if self._atomsCollector.is_collected(atom2[idx]): continue if self._atomsCollector.is_collected(atom3[idx]): continue if self._atomsCollector.is_collected(atom4[idx]): continue data.append([str(atom1[idx]),str(atom2[idx]),str(atom3[idx]),str(atom4[idx]), elements[atom1[idx]],elements[atom2[idx]],elements[atom3[idx]],elements[atom4[idx]], names[atom1[idx]],names[atom2[idx]],names[atom3[idx]],names[atom4[idx]], format%lower[idx], format%upper[idx], format%consData[idx]] ) # save return header, data
Example #21
Source File: fermionic_simulation.py From OpenFermion-Cirq with Apache License 2.0 | 5 votes |
def _decompose_(self, qubits): r = 2 * abs(self.weights[0]) / np.pi theta = _arg(self.weights[0]) / np.pi yield cirq.Z(qubits[0])**-theta yield cirq.ISwapPowGate(exponent=-r * self.exponent)(*qubits) yield cirq.Z(qubits[0])**theta yield cirq.CZPowGate(exponent=-self.weights[1] * self.exponent / np.pi)(*qubits)
Example #22
Source File: AngleConstraints.py From fullrmc with GNU Affero General Public License v3.0 | 5 votes |
def compute_standard_error(self, data): """ Compute the standard error (StdErr) of data not satisfying constraint conditions. .. math:: StdErr = \\sum \\limits_{i}^{C} ( \\theta_{i} - \\theta_{i}^{min} ) ^{2} \\int_{0}^{\\theta_{i}^{min}} \\delta(\\theta-\\theta_{i}) d \\theta + ( \\theta_{i} - \\theta_{i}^{max} ) ^{2} \\int_{\\theta_{i}^{max}}^{\\pi} \\delta(\\theta-\\theta_{i}) d \\theta Where:\n :math:`C` is the total number of defined angles constraints. \n :math:`\\theta_{i}^{min}` is the angle constraint lower limit set for constraint i. \n :math:`\\theta_{i}^{max}` is the angle constraint upper limit set for constraint i. \n :math:`\\theta_{i}` is the angle computed for constraint i. \n :math:`\\delta` is the Dirac delta function. \n :math:`\\int_{0}^{\\theta_{i}^{min}} \\delta(\\theta-\\theta_{i}) d \\theta` is equal to 1 if :math:`0 \\leqslant \\theta_{i} \\leqslant \\theta_{i}^{min}` and 0 elsewhere.\n :math:`\\int_{\\theta_{i}^{max}}^{\\pi} \\delta(\\theta-\\theta_{i}) d \\theta` is equal to 1 if :math:`\\theta_{i}^{max} \\leqslant \\theta_{i} \\leqslant \\pi` and 0 elsewhere.\n :Parameters: #. data (numpy.array): Constraint's data to compute standardError. :Returns: #. standardError (number): The calculated standardError of the given data. """ return FLOAT_TYPE( np.sum(data["reducedAngles"]**2) )
Example #23
Source File: nav_env.py From DOTA_models with Apache License 2.0 | 5 votes |
def pre(self, inputs): inputs['imgs'] = image_pre(inputs['imgs'], self.task_params.modalities) if inputs['loc_on_map'] is not None: inputs['loc_on_map'] = inputs['loc_on_map'] - inputs['loc_on_map'][:,[0],:] if inputs['theta_on_map'] is not None: inputs['theta_on_map'] = np.pi/2. - inputs['theta_on_map'] return inputs
Example #24
Source File: dataset.py From PolarSeg with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __init__(self, in_dataset, grid_size, rotate_aug = False, flip_aug = False, ignore_label = 255, return_test = False, fixed_volume_space= False, max_volume_space = [50,np.pi,1.5], min_volume_space = [3,-np.pi,-3]): 'Initialization' self.point_cloud_dataset = in_dataset self.grid_size = np.asarray(grid_size) self.rotate_aug = rotate_aug self.flip_aug = flip_aug self.ignore_label = ignore_label self.return_test = return_test self.fixed_volume_space = fixed_volume_space self.max_volume_space = max_volume_space self.min_volume_space = min_volume_space
Example #25
Source File: nav_env.py From DOTA_models with Apache License 2.0 | 5 votes |
def _get_relative_goal_loc(goal_loc, loc, theta): r = np.sqrt(np.sum(np.square(goal_loc - loc), axis=1)) t = np.arctan2(goal_loc[:,1] - loc[:,1], goal_loc[:,0] - loc[:,0]) t = t-theta[:,0] + np.pi/2 return np.expand_dims(r,axis=1), np.expand_dims(t, axis=1)
Example #26
Source File: map_utils.py From DOTA_models with Apache License 2.0 | 5 votes |
def get_map_to_predict(src_locs, src_x_axiss, src_y_axiss, map, map_size, interpolation=cv2.INTER_LINEAR): fss = [] valids = [] center = (map_size-1.0)/2.0 dst_theta = np.pi/2.0 dst_loc = np.array([center, center]) dst_x_axis = np.array([np.cos(dst_theta), np.sin(dst_theta)]) dst_y_axis = np.array([np.cos(dst_theta+np.pi/2), np.sin(dst_theta+np.pi/2)]) def compute_points(center, x_axis, y_axis): points = np.zeros((3,2),dtype=np.float32) points[0,:] = center points[1,:] = center + x_axis points[2,:] = center + y_axis return points dst_points = compute_points(dst_loc, dst_x_axis, dst_y_axis) for i in range(src_locs.shape[0]): src_loc = src_locs[i,:] src_x_axis = src_x_axiss[i,:] src_y_axis = src_y_axiss[i,:] src_points = compute_points(src_loc, src_x_axis, src_y_axis) M = cv2.getAffineTransform(src_points, dst_points) fs = cv2.warpAffine(map, M, (map_size, map_size), None, flags=interpolation, borderValue=np.NaN) valid = np.invert(np.isnan(fs)) valids.append(valid) fss.append(fs) return fss, valids
Example #27
Source File: loss.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 5 votes |
def hybrid_forward(self, F, pred, target, sample_weight=None, epsilon=1e-08): target = _reshape_like(F, target, pred) if self._from_logits: loss = F.exp(pred) - target * pred else: loss = pred - target * F.log(pred + epsilon) if self._compute_full: # Using numpy's pi value stirling_factor = target * F.log(target)- target + 0.5 * F.log(2 * target * np.pi) target_gt_1 = target > 1 stirling_factor *= target_gt_1 loss += stirling_factor loss = _apply_weighting(F, loss, self._weight, sample_weight) return F.mean(loss)
Example #28
Source File: image.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 5 votes |
def __call__(self, src): """Augmenter body. Using approximate linear transfomation described in: https://beesbuzz.biz/code/hsv_color_transforms.php """ alpha = random.uniform(-self.hue, self.hue) u = np.cos(alpha * np.pi) w = np.sin(alpha * np.pi) bt = np.array([[1.0, 0.0, 0.0], [0.0, u, -w], [0.0, w, u]]) t = np.dot(np.dot(self.ityiq, bt), self.tyiq).T src = nd.dot(src, nd.array(t)) return src
Example #29
Source File: test_loss.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 5 votes |
def test_poisson_nllloss(): pred = mx.nd.random.normal(shape=(3, 4)) min_pred = mx.nd.min(pred) #This is necessary to ensure only positive random values are generated for prediction, # to avoid ivalid log calculation pred[:] = pred + mx.nd.abs(min_pred) target = mx.nd.random.normal(shape=(3, 4)) min_target = mx.nd.min(target) #This is necessary to ensure only positive random values are generated for prediction, # to avoid ivalid log calculation target[:] += mx.nd.abs(min_target) Loss = gluon.loss.PoissonNLLLoss(from_logits=True) Loss_no_logits = gluon.loss.PoissonNLLLoss(from_logits=False) #Calculating by brute formula for default value of from_logits = True # 1) Testing for flag logits = True brute_loss = np.mean(np.exp(pred.asnumpy()) - target.asnumpy() * pred.asnumpy()) loss_withlogits = Loss(pred, target) assert_almost_equal(brute_loss, loss_withlogits.asscalar()) #2) Testing for flag logits = False loss_no_logits = Loss_no_logits(pred, target) np_loss_no_logits = np.mean(pred.asnumpy() - target.asnumpy() * np.log(pred.asnumpy() + 1e-08)) if np.isnan(loss_no_logits.asscalar()): assert_almost_equal(np.isnan(np_loss_no_logits), np.isnan(loss_no_logits.asscalar())) else: assert_almost_equal(np_loss_no_logits, loss_no_logits.asscalar()) #3) Testing for Sterling approximation np_pred = np.random.uniform(1, 5, (2, 3)) np_target = np.random.uniform(1, 5, (2, 3)) np_compute_full = np.mean((np_pred - np_target * np.log(np_pred + 1e-08)) + ((np_target * np.log(np_target)-\ np_target + 0.5 * np.log(2 * np_target * np.pi))*(np_target > 1))) Loss_compute_full = gluon.loss.PoissonNLLLoss(from_logits=False, compute_full=True) loss_compute_full = Loss_compute_full(mx.nd.array(np_pred), mx.nd.array(np_target)) assert_almost_equal(np_compute_full, loss_compute_full.asscalar())
Example #30
Source File: real_nvp_utils.py From DOTA_models with Apache License 2.0 | 5 votes |
def standard_normal_ll(input_): """Log-likelihood of standard Gaussian distribution.""" res = -.5 * (tf.square(input_) + numpy.log(2. * numpy.pi)) return res