我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用numpy.single()。
def field_directions(field): """ Scene the shows the directions of a vector field. Parameters ---------- field: array (X, Y, N, 3) the vector field to plot where N is the number of peaks. Returns ---------- actors: list of vtkActor the scene actors. """ actors = [] for x in range(field.shape[0]): for y in range(field.shape[1]): line = numpy.zeros((2, 3), dtype=numpy.single) for vector in field[x, y]: line[1] = vector actors.append(pvtk.line(line, 0, linewidth=2)) actors[-1].SetPosition((x, y, 0)) return actors
def do(self, a, b): d = linalg.det(a) (s, ld) = linalg.slogdet(a) if asarray(a).dtype.type in (single, double): ad = asarray(a).astype(double) else: ad = asarray(a).astype(cdouble) ev = linalg.eigvals(ad) assert_almost_equal(d, multiply.reduce(ev, axis=-1)) assert_almost_equal(s * np.exp(ld), multiply.reduce(ev, axis=-1)) s = np.atleast_1d(s) ld = np.atleast_1d(ld) m = (s != 0) assert_almost_equal(np.abs(s[m]), 1) assert_equal(ld[~m], -inf)
def __init__(self, size=10, dtype=np.single): self.center = np.zeros([size, size], dtype) self.water = None self.sediment = None self.scour = None self.flowrate = None self.sedimentpct = None self.sedimentpct = None self.capacity = None self.avalanced = None self.minx = None self.miny = None self.maxx = None self.maxy = None self.zscale = 1 self.maxrss = 0.0 self.sequence = [0, 1, 2, 3] self.watermax = 1.0 self.flowratemax = 1.0 self.scourmax = 1.0 self.sedmax = 1.0 self.scourmin = 1.0
def load(path, dtype=numpy.single): """ Load an image. Parameters ---------- path: str the path to the data to be loaded. dtype: str type to which the data will be cast. Passing 'None' will not cast. Returns ------- image: Image the loaded image. """ # Load the image loader = get_loader(path) image = loader.load(path) # Cast the image if requested if dtype: image.data = image.data.astype(dtype) return image
def SGD(obj, t=0, lr=1e-2, l2reg=1e-2, momentum=0.0, _=0.0, nesterov=0): obj = regularize(obj, l2reg) lrW = lr #schedule(t, lr, l2reg) if not hasattr(obj, 'V'): obj.V = np.zeros_like(obj.W) nescale(obj.V, np.single(momentum) ) newtadd(obj.V, np.single(lrW ), obj.G) if not nesterov: newtadd(obj.W, -1, obj.V) else : newtadd(obj.W, np.single(-momentum), obj.V); newtadd(obj.W, np.single(-lrW), obj.G) #obj.V *= np.single(momentum) #obj.V -= np.single(lrW) * obj.G #if not nesterov: obj.W += obj.V #else : obj.W += np.single(momentum) * obj.V - np.single(lrW) * obj.G
def ADADELTA(obj, t=0, lr=1e-0, l2reg=1e-2, rho=0.95, eps=1e-8): obj = regularize(obj, l2reg) if not hasattr(obj, 'V'): obj.V = np.zeros_like(obj.W) if not hasattr(obj, 'D'): obj.D = np.zeros_like(obj.W) nescale(obj.V, np.single( rho) ) newsadd(obj.V, np.single(1.0-rho), obj.G ) nescale(obj.G, nedivsr(obj.D, np.single(eps), obj.V)) # must be careful later with G nescale(obj.D, np.single( rho) ) newsadd(obj.D, np.single(1.0-rho), obj.G ) newtadd(obj.W, -1, obj.G ) #obj.V = np.single(rho) * obj.V + np.single(1.0 - rho) * obj.G * obj.G #D = np.sqrt((obj.D + eps) / (obj.V + eps)) * obj.G #obj.D = np.single(rho) * obj.D + np.single(1.0 - rho) * D * D #obj.W -= D
def ADAM(obj, t=0, lr=1e-3, l2reg=1e-2, beta1=0.9, beta2=0.999, eps=1e-8): obj = regularize(obj, l2reg) lrW = lr #schedule(t, lr, l2reg) if not hasattr(obj, 'M'): obj.M = np.zeros_like(obj.W) if not hasattr(obj, 'V'): obj.V = np.zeros_like(obj.W) nescale(obj.M, np.single( beta1) ) newtadd(obj.M, np.single(1.0-beta1), obj.G ) nescale(obj.V, np.single( beta2) ) newsadd(obj.V, np.single(1.0-beta2), obj.G ) newtadd(obj.W, np.single( -lrW ), nesrdiv(obj.M, np.single(eps), obj.V)) #obj.M = np.single(beta1) * obj.M + np.single(1.0 - beta1) * obj.G #obj.V = np.single(beta2) * obj.V + np.single(1.0 - beta2) * obj.G * obj.G #obj.W -= np.single(lrW) * obj.M / (np.sqrt(obj.V) + np.single(eps))
def test_floats_from_string(self, level=rlevel): # Ticket #640, floats from string fsingle = np.single('1.234') fdouble = np.double('1.234') flongdouble = np.longdouble('1.234') assert_almost_equal(fsingle, 1.234) assert_almost_equal(fdouble, 1.234) assert_almost_equal(flongdouble, 1.234)
def test_compress_small_type(self, level=rlevel): # Ticket #789, changeset 5217. # compress with out argument segfaulted if cannot cast safely import numpy as np a = np.array([[1, 2], [3, 4]]) b = np.zeros((2, 1), dtype=np.single) try: a.compress([True, False], axis=1, out=b) raise AssertionError("compress with an out which cannot be " "safely casted should not return " "successfully") except TypeError: pass
def test_trace_subclass(self): # The class would need to overwrite trace to ensure single-element # output also has the right subclass. class MyArray(np.ndarray): pass b = np.arange(8).reshape((2, 2, 2)).view(MyArray) t = b.trace() assert isinstance(t, MyArray)
def test_export_record(self): dt = [('a', 'b'), ('b', 'h'), ('c', 'i'), ('d', 'l'), ('dx', 'q'), ('e', 'B'), ('f', 'H'), ('g', 'I'), ('h', 'L'), ('hx', 'Q'), ('i', np.single), ('j', np.double), ('k', np.longdouble), ('ix', np.csingle), ('jx', np.cdouble), ('kx', np.clongdouble), ('l', 'S4'), ('m', 'U4'), ('n', 'V3'), ('o', '?'), ('p', np.half), ] x = np.array( [(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, asbytes('aaaa'), 'bbbb', asbytes(' '), True, 1.0)], dtype=dt) y = memoryview(x) assert_equal(y.shape, (1,)) assert_equal(y.ndim, 1) assert_equal(y.suboffsets, EMPTY) sz = sum([np.dtype(b).itemsize for a, b in dt]) if np.dtype('l').itemsize == 4: assert_equal(y.format, 'T{b:a:=h:b:i:c:l:d:q:dx:B:e:@H:f:=I:g:L:h:Q:hx:f:i:d:j:^g:k:=Zf:ix:Zd:jx:^Zg:kx:4s:l:=4w:m:3x:n:?:o:@e:p:}') else: assert_equal(y.format, 'T{b:a:=h:b:i:c:q:d:q:dx:B:e:@H:f:=I:g:Q:h:Q:hx:f:i:d:j:^g:k:=Zf:ix:Zd:jx:^Zg:kx:4s:l:=4w:m:3x:n:?:o:@e:p:}') # Cannot test if NPY_RELAXED_STRIDES_CHECKING changes the strides if not (np.ones(1).strides[0] == np.iinfo(np.intp).max): assert_equal(y.strides, (sz,)) assert_equal(y.itemsize, sz)
def test_singleton(self): ftype = finfo(single) ftype2 = finfo(single) assert_equal(id(ftype), id(ftype2))
def get_real_dtype(dtype): return {single: single, double: double, csingle: single, cdouble: double}[dtype]
def get_complex_dtype(dtype): return {single: csingle, double: cdouble, csingle: csingle, cdouble: cdouble}[dtype]
def get_rtol(dtype): # Choose a safe rtol if dtype in (single, csingle): return 1e-5 else: return 1e-11
def test_types(self): def check(dtype): x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype) assert_equal(linalg.solve(x, x).dtype, dtype) for dtype in [single, double, csingle, cdouble]: yield check, dtype
def test_0_size(self): class ArraySubclass(np.ndarray): pass # Test system of 0x0 matrices a = np.arange(8).reshape(2, 2, 2) b = np.arange(6).reshape(1, 2, 3).view(ArraySubclass) expected = linalg.solve(a, b)[:, 0:0, :] result = linalg.solve(a[:, 0:0, 0:0], b[:, 0:0, :]) assert_array_equal(result, expected) assert_(isinstance(result, ArraySubclass)) # Test errors for non-square and only b's dimension being 0 assert_raises(linalg.LinAlgError, linalg.solve, a[:, 0:0, 0:1], b) assert_raises(ValueError, linalg.solve, a, b[:, 0:0, :]) # Test broadcasting error b = np.arange(6).reshape(1, 3, 2) # broadcasting error assert_raises(ValueError, linalg.solve, a, b) assert_raises(ValueError, linalg.solve, a[0:0], b[0:0]) # Test zero "single equations" with 0x0 matrices. b = np.arange(2).reshape(1, 2).view(ArraySubclass) expected = linalg.solve(a, b)[:, 0:0] result = linalg.solve(a[:, 0:0, 0:0], b[:, 0:0]) assert_array_equal(result, expected) assert_(isinstance(result, ArraySubclass)) b = np.arange(3).reshape(1, 3) assert_raises(ValueError, linalg.solve, a, b) assert_raises(ValueError, linalg.solve, a[0:0], b[0:0]) assert_raises(ValueError, linalg.solve, a[:, 0:0, 0:0], b)
def test_types(self): def check(dtype): x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype) assert_equal(linalg.eigvals(x).dtype, dtype) x = np.array([[1, 0.5], [-1, 1]], dtype=dtype) assert_equal(linalg.eigvals(x).dtype, get_complex_dtype(dtype)) for dtype in [single, double, csingle, cdouble]: yield check, dtype
def test_types(self): def check(dtype): x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype) w, v = np.linalg.eig(x) assert_equal(w.dtype, dtype) assert_equal(v.dtype, dtype) x = np.array([[1, 0.5], [-1, 1]], dtype=dtype) w, v = np.linalg.eig(x) assert_equal(w.dtype, get_complex_dtype(dtype)) assert_equal(v.dtype, get_complex_dtype(dtype)) for dtype in [single, double, csingle, cdouble]: yield check, dtype
def test_types(self): def check(dtype): x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype) u, s, vh = linalg.svd(x) assert_equal(u.dtype, dtype) assert_equal(s.dtype, get_real_dtype(dtype)) assert_equal(vh.dtype, dtype) s = linalg.svd(x, compute_uv=False) assert_equal(s.dtype, get_real_dtype(dtype)) for dtype in [single, double, csingle, cdouble]: yield check, dtype
def test_types(self): def check(dtype): x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype) assert_equal(np.linalg.det(x).dtype, dtype) ph, s = np.linalg.slogdet(x) assert_equal(s.dtype, get_real_dtype(dtype)) assert_equal(ph.dtype, dtype) for dtype in [single, double, csingle, cdouble]: yield check, dtype
def test_types(self): def check(dtype): x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype) w, v = np.linalg.eigh(x) assert_equal(w.dtype, get_real_dtype(dtype)) assert_equal(v.dtype, dtype) for dtype in [single, double, csingle, cdouble]: yield check, dtype
def __init__(self): super(EmptyDataSource, self).__init__() self._data = np.zeros((2, 2), dtype=np.single) self._data[0, 0] = -1.0 self._data[1, 1] = 1.0 self._xlines = [0, 1] self._ilines = [0, 1] self._samples = [] # changed to allow dims() calculate len(samples)
def init_water_and_sediment(self): if self.water is None: self.water = np.zeros(self.center.shape, dtype=np.single) if self.sediment is None: self.sediment = np.zeros(self.center.shape, dtype=np.single) if self.scour is None: self.scour = np.zeros(self.center.shape, dtype=np.single) if self.flowrate is None: self.flowrate = np.zeros(self.center.shape, dtype=np.single) if self.sedimentpct is None: self.sedimentpct = np.zeros(self.center.shape, dtype=np.single) if self.capacity is None: self.capacity = np.zeros(self.center.shape, dtype=np.single) if self.avalanced is None: self.avalanced = np.zeros(self.center.shape, dtype=np.single)
def fromFile(filename): if filename == '-': filename = sys.stdin g=Grid() g.center=np.loadtxt(filename,np.single) return g
def _sort(self, expfact): # keep unique vertices only by creating a set and sort first on x then on y coordinate # using rather slow python sort but couldn;t wrap my head around np.lexsort verts = sorted(list({ tuple(t) for t in self.center[::] })) x = set(c[0] for c in verts) y = set(c[1] for c in verts) nx = len(x) ny = len(y) self.minx = min(x) self.maxx = max(x) self.miny = min(y) self.maxy = max(y) xscale = (self.maxx-self.minx)/(nx-1) yscale = (self.maxy-self.miny)/(ny-1) # note: a purely flat plane cannot be scaled if (yscale != 0.0) and (abs(xscale/yscale) - 1.0 > 1e-3): raise ValueError("Mesh spacing not square %d x %d %.4f x %4.f"%(nx,ny,xscale,yscale)) self.zscale = 1.0 if abs(yscale) > 1e-6 : self.zscale = 1.0/yscale # keep just the z-values and null any ofsset # we might catch a reshape error that will occur if nx*ny != # of vertices (if we are not dealing with a heightfield but with a mesh with duplicate x,y coords, like an axis aligned cube self.center = np.array([c[2] for c in verts],dtype=np.single).reshape(nx,ny) self.center = (self.center-np.amin(self.center))*self.zscale if self.rainmap is not None: rmscale = np.max(self.center) self.rainmap = expfact + (1-expfact)*(self.center/rmscale)
def fromBlenderMesh(me, vg, expfact): g = Grid() g.center = np.asarray(list(tuple(v.co) for v in me.vertices), dtype=np.single ) g.rainmap = None if vg is not None: for v in me.vertices: vg.add([v.index],0.0,'ADD') g.rainmap=np.asarray(list( (v.co[0], v.co[1], vg.weight(v.index)) for v in me.vertices), dtype=np.single ) g._sort(expfact) return g
def _set_spacing(self, spacing): """ Set the image spacing. Parameters ---------- spacing: uplet the image spacing. """ self._spacing = numpy.asarray(spacing, dtype=numpy.single)
def _default_spacing(self): """ Return the default image spacing. """ dim = self._get_ndim() return numpy.ones(dim, dtype=numpy.single)
def get_scales(min_scale=0.2, max_scale=0.9,num_layers=6): """ Following the ssd arxiv paper, regarding the calculation of scales & ratios Parameters ---------- min_scale : float max_scales: float num_layers: int number of layers that will have a detection head anchor_ratios: list first_layer_ratios: list return ------ sizes : list list of scale sizes per feature layer ratios : list list of anchor_ratios per feature layer """ # this code follows the original implementation of wei liu # for more, look at ssd/score_ssd_pascal.py:310 in the original caffe implementation min_ratio = int(min_scale * 100) max_ratio = int(max_scale * 100) step = int(np.floor((max_ratio - min_ratio) / (num_layers - 2))) min_sizes = [] max_sizes = [] for ratio in xrange(min_ratio, max_ratio + 1, step): min_sizes.append(ratio / 100.) max_sizes.append((ratio + step) / 100.) min_sizes = [int(100*min_scale / 2.0) / 100.0] + min_sizes max_sizes = [min_scale] + max_sizes # convert it back to this implementation's notation: scales = [] for layer_idx in range(num_layers): scales.append([min_sizes[layer_idx], np.single(np.sqrt(min_sizes[layer_idx] * max_sizes[layer_idx]))]) return scales