当前位置: 首页>>代码示例>>Python>>正文


Python numpy.around函数代码示例

本文整理汇总了Python中numpy.around函数的典型用法代码示例。如果您正苦于以下问题:Python around函数的具体用法?Python around怎么用?Python around使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了around函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: plot_density

def plot_density(count_trips,count,title):
    grid = np.zeros((config.bins,config.bins))
    for (i,j),z in np.ndenumerate(grid):
        try:
            grid[j,i] = float(count[(i,j)]) / float(count_trips[(i,j)])
        except:
            grid[j,i] = 0
        #print "----"
        #print grid[i,j], i, j
        #print count[(i,j)]
        #print count_trips[(i,j)]
    grid = np.flipud(grid) #to counter matshow vertical flip
    fig, ax = plt.subplots(figsize=(10, 10))
    ax.matshow(grid, cmap='spectral')
    ax.xaxis.set_ticks_position('bottom')
    ax.set_xlabel('Longitude')
    ax.set_ylabel('Latitude')
    xticks = np.linspace(config.minlong,config.maxlong,num=round(config.bins/2))
    yticks = np.linspace(config.minlat,config.maxlat,num=round(config.bins/2))
    yticks = yticks[::-1]
    xticks = np.around(xticks,decimals=1)
    yticks = np.around(yticks,decimals=1)
    xspace = np.linspace(0,config.bins-1,config.bins/2)
    yspace = np.linspace(0,config.bins-1,config.bins/2)
    plt.xticks(xspace,xticks)
    plt.yticks(yspace,yticks)
    for (i,j),z in np.ndenumerate(grid):
        ax.text(j, i, '{:0.2f}'.format(z), ha='center', va='center')
    plt.title(title)
    plt.show()
开发者ID:od0,项目名称:HW2,代码行数:30,代码来源:A.py

示例2: test_logvecadd

    def test_logvecadd(self):
        vec1 = log(array([1, 2, 3, 4]))
        vec2 = log(array([5, 6, 7, 8]))

        sumvec = array([1.79175947, 2.07944154, 2.30258509, 2.48490665])
        self.assertTrue(
            array_equal(around(MarkovModel._logvecadd(vec1, vec2), decimals=3), around(sumvec, decimals=3)))
开发者ID:BioGeek,项目名称:biopython,代码行数:7,代码来源:test_MarkovModel.py

示例3: _get_initial_classes

    def _get_initial_classes(self):
        images = map(lambda f: cv2.imread(path.join(self._root, f)), self._files)
        self._avg_pixels = np.array([], dtype=np.uint8)

        # extract parts from each image for all of our 6 categories
        for i in range(0, self._n_objects):
            rects = self._rects[:, i]
            
            # compute maximum rectangle
            rows = np.max(rects['f2'] - rects['f0'])
            cols = np.max(rects['f3'] - rects['f1'])

            # extract annotated rectangles
            im_rects = map(lambda (im, r): im[r[0]:r[2],r[1]:r[3],:], zip(images, rects))

            # resize all rectangles to the max size & average all the rectangles
            im_rects = np.array(map(lambda im: cv2.resize(im, (cols, rows)), im_rects), dtype=np.float)
            avgs = np.around(np.average(im_rects, axis = 0))

            # average the resulting rectangle to compute 
            mn = np.around(np.array(cv2.mean(avgs), dtype='float'))[:-1].astype('uint8')

            if(self._avg_pixels.size == 0):
                self._avg_pixels = mn
            else:
                self._avg_pixels = np.vstack((self._avg_pixels, mn))
开发者ID:fierval,项目名称:retina,代码行数:26,代码来源:regions_detect_knn.py

示例4: test_make_tone_irregular

def test_make_tone_irregular():
    fq = 15066
    db = 82
    fs = 200101
    dur = 0.7
    risefall = 0.0015
    calv = 0.888
    caldb = 99
    npts = int(fs*dur)

    tone, timevals = tools.make_tone(fq, db, dur, risefall, fs, caldb, calv)

    print 'lens', npts, len(tone), len(timevals)
    assert len(tone) == npts
    assert len(timevals) == npts

    spectrum = np.fft.rfft(tone)
    peak_idx = (abs(spectrum - max(spectrum))).argmin()
    freq_idx = np.around(fq*(float(npts)/fs))
    assert peak_idx == freq_idx

    print 'intensities', (20 * np.log10(tools.signal_amplitude(tone, fs)/calv)) + caldb, db
    assert np.around((20 * np.log10(tools.signal_amplitude(tone, fs)/calv)) + caldb, 1) == db

    print 'durs', np.around(timevals[-1], 5), dur - (1./fs)
    assert dur - 2*(1./fs) < timevals[-1] <= dur - (1./fs)
开发者ID:boylea,项目名称:sparkle,代码行数:26,代码来源:test_audiotools.py

示例5: test_metrics_correctness_with_iterator

  def test_metrics_correctness_with_iterator(self):
    layers = [
        keras.layers.Dense(8, activation='relu', input_dim=4,
                           kernel_initializer='ones'),
        keras.layers.Dense(1, activation='sigmoid', kernel_initializer='ones')
    ]

    model = testing_utils.get_model_from_layers(layers, (4,))

    model.compile(
        loss='binary_crossentropy',
        metrics=['accuracy', metrics_module.BinaryAccuracy()],
        optimizer='rmsprop',
        run_eagerly=testing_utils.should_run_eagerly())

    np.random.seed(123)
    x = np.random.randint(10, size=(100, 4)).astype(np.float32)
    y = np.random.randint(2, size=(100, 1)).astype(np.float32)
    dataset = dataset_ops.Dataset.from_tensor_slices((x, y))
    dataset = dataset.batch(10)
    iterator = dataset_ops.make_one_shot_iterator(dataset)
    outs = model.evaluate(iterator, steps=10)
    self.assertEqual(np.around(outs[1], decimals=1), 0.5)
    self.assertEqual(np.around(outs[2], decimals=1), 0.5)

    y = np.zeros((100, 1), dtype=np.float32)
    dataset = dataset_ops.Dataset.from_tensor_slices((x, y))
    dataset = dataset.repeat(100)
    dataset = dataset.batch(10)
    iterator = dataset_ops.make_one_shot_iterator(dataset)
    outs = model.evaluate(iterator, steps=10)
    self.assertEqual(outs[1], 0.)
    self.assertEqual(outs[2], 0.)
开发者ID:adit-chandra,项目名称:tensorflow,代码行数:33,代码来源:training_dataset_test.py

示例6: save2mat

	def save2mat(self, i):
		global samples0, samples1;
		std0 = np.around(np.std(samples0), 5);
		std1 = np.around(np.std(samples1), 5);
		print 'std0:', std0, 'std1', std1;

		scipy.io.savemat('./data/'+folder_name+'/'+filename+'_'+str(i)+'.mat', mdict={'s0':samples0, 's1':samples1, 'timestamp': self.timestamp, 'fs':self.sdr.sample_rate, 'ref_addr':ref_addr});
开发者ID:TuringTW,项目名称:SoftwareRadar,代码行数:7,代码来源:go_mat.py

示例7: test_circmean_against_scipy

def test_circmean_against_scipy():
    # testing against scipy.stats.circmean function
    # the data is the same as the test before, but in radians
    data = np.array([0.89011792, 1.1693706, 0.6981317, 1.90240888, 0.54105207,
                     6.24827872])
    answer = scipy.stats.circmean(data)
    assert_equal(np.around(answer, 2), np.around(circmean(data), 2))
开发者ID:bernie-simon,项目名称:astropy,代码行数:7,代码来源:test_circstats.py

示例8: receivers_setup

	def receivers_setup(self, pr, pz, Tiempo):

		self.receiver_r         = np.int32(np.around(np.array(pr)/self.dr))
		self.receiver_z         = np.int32(np.around(np.array(pz)/self.dz))

		self.N_z                = np.size(self.receiver_z,0)
		self.receivers_signals  = np.zeros((Tiempo,self.N_z), dtype=np.float32)
开发者ID:cageo,项目名称:Iturraran-Viveros-2013,代码行数:7,代码来源:FD25D_CL.py

示例9: test_obtain_shape_from_bb

def test_obtain_shape_from_bb():
    s = sdm2.obtain_shape_from_bb(np.array([[26, 49], [350, 400]]))
    assert ((np.around(s.points) == np.around(initial_shape[3].points)).
            all())
    assert (s.n_dims == 2)
    assert (s.n_landmark_groups == 0)
    assert (s.n_points == 68)
开发者ID:yymath,项目名称:menpo,代码行数:7,代码来源:sdm_test.py

示例10: us_grid

def us_grid(resolution=.5, sparse=True):
    resolution = .5
    bounds = USA.bounds
    # Grid boundaries are determined by nearest degree.
    min_long = np.floor(bounds[0])
    min_lat  = np.floor(bounds[1])
    max_long = np.ceil(bounds[2])
    max_lat  = np.ceil(bounds[3])
    # Division should be close to an integer.
    # Add one to number of points to include the end
    # This is robust only to resolutions that "evenly" divide the range.
    nPointsLong = np.around((max_long - min_long) / resolution) + 1
    nPointsLat  = np.around((max_lat  - min_lat ) / resolution) + 1
    long_points = np.linspace(min_long, max_long, nPointsLong)
    lat_points  = np.linspace(min_lat,  max_lat,  nPointsLat )

    outline = contiguous_outline2('../tiger/cb_2013_us_nation_20m.shp')

    for i, (xi, yi) in enumerate(product(range(len(long_points)-1),
                                         range(len(lat_points)-1))):
        cell = box(long_points[xi], lat_points[yi],
                   long_points[xi+1], lat_points[yi+1])
        if sparse:
            # Add cell only if it intersects contiguous USA
            if cell.intersects(outline):
                yield cell
        else:
            yield cell
开发者ID:chebee7i,项目名称:twitter,代码行数:28,代码来源:usoutline.py

示例11: test_pmf_accuracy

def test_pmf_accuracy():
    """Compare accuracy of the probability mass function.

    Compare the results with the accuracy check proposed in [Hong2013]_,
    equation (15).
    """
    [p1, p2, p3] = np.around(np.random.random_sample(size=3), decimals=2)
    [n1, n2, n3] = np.random.random_integers(1, 10, size=3)
    nn = n1 + n2 + n3
    l1 = [p1 for i in range(n1)]
    l2 = [p2 for i in range(n2)]
    l3 = [p3 for i in range(n3)]
    p = l1 + l2 + l3
    b1 = binom(n=n1, p=p1)
    b2 = binom(n=n2, p=p2)
    b3 = binom(n=n3, p=p3)
    k = np.random.randint(0, nn + 1)
    chi_bn = 0
    for j in range(0, k+1):
        for i in range(0, j+1):
            chi_bn += b1.pmf(i) * b2.pmf(j - i) * b3.pmf(k - j)
    pb = PoiBin(p)
    chi_pb = pb.pmf(k)
    assert np.all(np.around(chi_bn, decimals=10) == np.around(chi_pb,
                                                              decimals=10))
开发者ID:tsakim,项目名称:poibin,代码行数:25,代码来源:test_poibin.py

示例12: _symmetrical_uncertainty

def _symmetrical_uncertainty(X, Y):
    """Symmetrical uncertainty, Press et al., 1988."""
    from Orange.preprocess._relieff import contingency_table
    X, Y = np.around(X), np.around(Y)
    cont = contingency_table(X, Y)
    ig = InfoGain().from_contingency(cont, 1)
    return 2 * ig / (_entropy(cont.sum(0)) + _entropy(cont.sum(1)))
开发者ID:675801717,项目名称:orange3,代码行数:7,代码来源:score.py

示例13: _plotRound

 def _plotRound(self, values):
     """
     A function round an array-like object while maintaining the
     amount of entries. This is needed for the isolines since we
     want the labels to look pretty (=rounding), but we do not
     know the spacing of the lines. A fixed number of digits after
     rounding might lead to reduced array size.
     """
     inVal   = numpy.unique(numpy.sort(numpy.array(values)))
     output  = inVal[1:] * 0.0
     digits  = -1
     limit   = 10
     lim     = inVal * 0.0 + 10
     # remove less from the numbers until same length,
     # more than 10 significant digits does not really
     # make sense, does it?
     while len(inVal) > len(output) and digits < limit:
         digits += 1
         val     = ( numpy.around(numpy.log10(numpy.abs(inVal))) * -1) + digits + 1
         val     = numpy.where(val < lim, val,  lim)
         val     = numpy.where(val >-lim, val, -lim)
         output  = numpy.zeros(inVal.shape)
         for i in range(len(inVal)):
             output[i] = numpy.around(inVal[i],decimals=int(val[i]))
         output = numpy.unique(output)
     return output
开发者ID:TimHarvey2,项目名称:CoolProp,代码行数:26,代码来源:Plots.py

示例14: __init__

	def __init__(self, parser, k, startIndex=-1, parallel = True, batch=True):
		if startIndex==-1:
			startIndex = k
		self.Data = parser
		self.names = self.Data.getNames()
		self.k = k
		self.clusters = KMeans(k, n_jobs=1 - 2*(not parallel),n_init=10)
		self.props = self.Data.getProperties()
		self.artefacts = np.atleast_2d(self.Data.getList(self.props[0]))
		for attr in self.Data.getProperties()[1:]:
			self.artefacts = np.append(self.artefacts,np.atleast_2d(self.Data.getList(attr)),axis=0)
		self.artefacts = self.artefacts.T
		self.times = self.Data.getList()
		zipped = zip(self.times,self.artefacts,self.names)
		zipped = sorted(zipped,key=lambda x: x[0])
		unzipped = zip(*zipped)
		self.times = list(unzipped[0])
		self.artefacts = np.array(unzipped[1])
		self.names = list(unzipped[2])
		if batch:
			self.trainAll()
			self.currentIndex = len(self.names)-1
		else:
			self.currentIndex = startIndex
			self.noveltyList = np.zeros(len(self.artefacts))
			while self.currentIndex+1 < len(self.names) and self.times[self.currentIndex+1]==self.times[self.currentIndex]:
				self.currentIndex +=1
			
			while self.currentIndex < len(self.names):
				self.train()
				newArtefacts = [self.currentIndex+1]
				while newArtefacts[-1]+1 < len(self.names) and self.times[newArtefacts[-1]+1]==self.times[newArtefacts[0]]:
					newArtefacts.append(newArtefacts[-1]+1)
				novelties = []
				for i,a in enumerate(self.names[newArtefacts[0]:newArtefacts[-1]+1]):
					dist,cluster = self.novelty(a,normedDistance=False)
					time=self.times[self.names.index(a)]
					novelties.append((dist/self.sizes[cluster],cluster,time,a))
					self.noveltyList[self.currentIndex+i] = novelties[-1][0]
				novelties = sorted(novelties,key=lambda x: x[0])
				scales = {}
				translates = {}
				for k in self.Data.pastCalc.keys():
					if k in self.props:
						scales[k] = self.Data.pastCalc[k]['std']
						translates[k] = self.Data.pastCalc[k]['avg']
				for n in novelties[::-1]:
					cent = np.copy(self.centroids[n[1]])
					art = np.copy(self.artefacts[self.names.index(n[3])])
					c = self.clusters.predict(art)[0]
					for i,v in enumerate(self.props):
						cent[i] = np.around(cent[i] * scales[v] + translates[v],decimals=1)
						art[i] = np.around(art[i] * scales[v] + translates[v],decimals=1)
					print 'Closest cluster to',n[3],'(released',str(n[2])+') was #'+str(n[1]),'with distance',str(n[0])+'. Actual cluster was',str(c)+'.'
					if n[0] > 1:
						print 'Attrs:	  RAM	 ROM   CPU	 DDia  DWid  DLen	Wid   Len	 Dep	Vol	Mass   DPI'
						print 'Cluster:',cent
						print 'Design: ',art
						print 'Diff:   ',art-cent
				self.increment(len(newArtefacts))
开发者ID:Kazjon,项目名称:SurpriseEval,代码行数:60,代码来源:Novelty.py

示例15: print_errors

    def print_errors(self):
        """
            Print all errors metrics.

            Note:
                For better printing format, install :mod:`prettytable`.

        """

        self.calc_metrics()

        try:
            from prettytable import PrettyTable

            table = PrettyTable(["Error", "Value"])
            table.align["Error"] = "l"
            table.align["Value"] = "l"

            for error in sorted(self.dict_errors.keys()):
                table.add_row([error, np.around(self.dict_errors[error], decimals=8)])

            print()
            print(table.get_string(sortby="Error"))
            print()

        except ImportError:
            print("For better table format install 'prettytable' module.")

            print()
            for error in sorted(self.dict_errors.keys()):
                print(error, np.around(self.dict_errors[error], decimals=8))
            print()
开发者ID:ExtremeLearningMachines,项目名称:acba.elm,代码行数:32,代码来源:mltools.py


注:本文中的numpy.around函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。