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


Python numpy.rint方法代码示例

本文整理汇总了Python中numpy.rint方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.rint方法的具体用法?Python numpy.rint怎么用?Python numpy.rint使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在numpy的用法示例。


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

示例1: add_image

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import rint [as 别名]
def add_image(self, img):
        if self.print_progress and self.cur_images % self.progress_interval == 0:
            print('%d / %d\r' % (self.cur_images, self.expected_images), end='', flush=True)
            sys.stdout.flush()
        if self.shape is None:
            self.shape = img.shape
            self.resolution_log2 = int(np.log2(self.shape[1]))
            assert self.shape[0] in [1, 3]
            assert self.shape[1] == self.shape[2]
            assert self.shape[1] == 2**self.resolution_log2
            tfr_opt = tf.python_io.TFRecordOptions(tf.python_io.TFRecordCompressionType.NONE)
            for lod in range(self.resolution_log2 - 1):
                tfr_file = self.tfr_prefix + '-r%02d.tfrecords' % (self.resolution_log2 - lod)
                self.tfr_writers.append(tf.python_io.TFRecordWriter(tfr_file, tfr_opt))
        assert img.shape == self.shape
        for lod, tfr_writer in enumerate(self.tfr_writers):
            if lod:
                img = img.astype(np.float32)
                img = (img[:, 0::2, 0::2] + img[:, 0::2, 1::2] + img[:, 1::2, 0::2] + img[:, 1::2, 1::2]) * 0.25
            quant = np.rint(img).clip(0, 255).astype(np.uint8)
            ex = tf.train.Example(features=tf.train.Features(feature={
                'shape': tf.train.Feature(int64_list=tf.train.Int64List(value=quant.shape)),
                'data': tf.train.Feature(bytes_list=tf.train.BytesList(value=[quant.tostring()]))}))
            tfr_writer.write(ex.SerializeToString())
        self.cur_images += 1 
开发者ID:zalandoresearch,项目名称:disentangling_conditional_gans,代码行数:27,代码来源:dataset_tool.py

示例2: visualize_2D_trip

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import rint [as 别名]
def visualize_2D_trip(self,trip,tw_open,tw_close):
        plt.figure(figsize=(30,30))
        rcParams.update({'font.size': 22})
        # Plot cities
        colors = ['red'] # Depot is first city
        for i in range(len(tw_open)-1):
            colors.append('blue')
        plt.scatter(trip[:,0], trip[:,1], color=colors, s=200)
        # Plot tour
        tour=np.array(list(range(len(trip))) + [0])
        X = trip[tour, 0]
        Y = trip[tour, 1]
        plt.plot(X, Y,"--", markersize=100)
        # Annotate cities with TW
        tw_open = np.rint(tw_open)
        tw_close = np.rint(tw_close)
        time_window = np.concatenate((tw_open,tw_close),axis=1)
        for tw, (x, y) in zip(time_window,(zip(X,Y))):
            plt.annotate(tw,xy=(x, y))  
        plt.xlim(0,60)
        plt.ylim(0,60)
        plt.show()


    # Heatmap of permutations (x=cities; y=steps) 
开发者ID:MichelDeudon,项目名称:neural-combinatorial-optimization-rl-tensorflow,代码行数:27,代码来源:dataset.py

示例3: apply_float_operation

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import rint [as 别名]
def apply_float_operation(problem, fun):

    # save the original bounds of the problem
    _xl, _xu = problem.xl, problem.xu

    # copy the arrays of the problem and cast them to float
    xl, xu = problem.xl.astype(np.float), problem.xu.astype(np.float)

    # modify the bounds to match the new crossover specifications and set the problem
    problem.xl = xl - (0.5 - 1e-16)
    problem.xu = xu + (0.5 - 1e-16)

    # perform the crossover
    off = fun()

    # now round to nearest integer for all offsprings
    off = np.rint(off).astype(np.int)

    # reset the original bounds of the problem and design space values
    problem.xl = _xl
    problem.xu = _xu

    return off 
开发者ID:msu-coinlab,项目名称:pymoo,代码行数:25,代码来源:integer_from_float_operator.py

示例4: get_kconserv

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import rint [as 别名]
def get_kconserv(cell, kpts):
    r'''Get the momentum conservation array for a set of k-points.

    Given k-point indices (k, l, m) the array kconserv[k,l,m] returns
    the index n that satifies momentum conservation,

        (k(k) - k(l) + k(m) - k(n)) \dot a = 2n\pi

    This is used for symmetry e.g. integrals of the form
        [\phi*[k](1) \phi[l](1) | \phi*[m](2) \phi[n](2)]
    are zero unless n satisfies the above.
    '''
    nkpts = kpts.shape[0]
    a = cell.lattice_vectors() / (2*np.pi)

    kconserv = np.zeros((nkpts,nkpts,nkpts), dtype=int)
    kvKLM = kpts[:,None,None,:] - kpts[:,None,:] + kpts
    for N, kvN in enumerate(kpts):
        kvKLMN = np.einsum('wx,klmx->wklm', a, kvKLM - kvN)
        # check whether (1/(2pi) k_{KLMN} dot a) is an integer
        kvKLMN_int = np.rint(kvKLMN)
        mask = np.einsum('wklm->klm', abs(kvKLMN - kvKLMN_int)) < 1e-9
        kconserv[mask] = N
    return kconserv 
开发者ID:pyscf,项目名称:pyscf,代码行数:26,代码来源:kpts_helper.py

示例5: __init__

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import rint [as 别名]
def __init__(self, **kw):
    """  
      Constructor of affine, equidistant 3d mesh class
      ucell : unit cell vectors (in coordinate space)
      Ecut  : Energy cutoff to parametrize the discretization 
    """
    from scipy.fftpack import next_fast_len
    
    self.ucell = kw['ucell'] if 'ucell' in kw else 30.0*np.eye(3) # Not even unit cells vectors are required by default
    self.Ecut = Ecut = kw['Ecut'] if 'Ecut' in kw else 50.0 # 50.0 Hartree by default
    luc = np.sqrt(np.einsum('ix,ix->i', self.ucell, self.ucell))
    self.shape = nn = np.array([next_fast_len( int(np.rint(l * np.sqrt(Ecut)/2))) for l in luc], dtype=int)
    self.size  = np.prod(self.shape)
    gc = self.ucell/(nn) # This is probable the best for finite systems, for PBC use nn, not (nn-1)
    self.dv = np.abs(np.dot(gc[0], np.cross(gc[1], gc[2] )))
    rr = [np.array([gc[i]*j for j in range(nn[i])]) for i in range(3)]
    self.rr = rr
    self.origin = kw['origin'] if 'origin' in kw else np.zeros(3) 
开发者ID:pyscf,项目名称:pyscf,代码行数:20,代码来源:mesh_affine_equ.py

示例6: _hrv_get_rri

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import rint [as 别名]
def _hrv_get_rri(peaks=None, sampling_rate=1000, interpolate=False, **kwargs):

    rri = np.diff(peaks) / sampling_rate * 1000

    if interpolate is False:
        return rri

    else:

        # Minimum sampling rate for interpolation
        if sampling_rate < 10:
            sampling_rate = 10

        # Compute length of interpolated heart period signal at requested sampling rate.
        desired_length = int(np.rint(peaks[-1] / sampling_rate * sampling_rate))

        rri = signal_interpolate(
            peaks[1:],  # Skip first peak since it has no corresponding element in heart_period
            rri,
            x_new=np.arange(desired_length),
            **kwargs
        )
        return rri, sampling_rate 
开发者ID:neuropsychology,项目名称:NeuroKit,代码行数:25,代码来源:hrv_utils.py

示例7: read_segments_as_bool_vec

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import rint [as 别名]
def read_segments_as_bool_vec(segments_file):
  """ [ bool_vec ] = read_segments_as_bool_vec(segments_file)
   using kaldi 'segments' file for 1 wav, format : '<utt> <rec> <t-beg> <t-end>'
   - t-beg, t-end is in seconds,
   - assumed 100 frames/second,
  """
  segs = np.loadtxt(segments_file, dtype='object,object,f,f', ndmin=1)
  # Sanity checks,
  assert(len(segs) > 0) # empty segmentation is an error,
  assert(len(np.unique([rec[1] for rec in segs ])) == 1) # segments with only 1 wav-file,
  # Convert time to frame-indexes,
  start = np.rint([100 * rec[2] for rec in segs]).astype(int)
  end = np.rint([100 * rec[3] for rec in segs]).astype(int)
  # Taken from 'read_lab_to_bool_vec', htk.py,
  frms = np.repeat(np.r_[np.tile([False,True], len(end)), False],
                   np.r_[np.c_[start - np.r_[0, end[:-1]], end-start].flat, 0])
  assert np.sum(end-start) == np.sum(frms)
  return frms 
开发者ID:jefflai108,项目名称:Attentive-Filtering-Network,代码行数:20,代码来源:kaldi_io.py

示例8: get_C_hat_transpose

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import rint [as 别名]
def get_C_hat_transpose():
    probs = []
    net.eval()
    for batch_idx, (data, target) in enumerate(train_gold_deterministic_loader):
        # we subtract 10 because we added 10 to gold so we could identify which example is gold in train_phase2
        data, target = torch.autograd.Variable(data.cuda(), volatile=True),\
                       torch.autograd.Variable((target - num_classes).cuda(), volatile=True)

        # forward
        output = net(data)
        pred = F.softmax(output)
        probs.extend(list(pred.data.cpu().numpy()))

    probs = np.array(probs, dtype=np.float32)
    preds = np.argmax(probs, axis=1)
    C_hat = np.zeros([num_classes, num_classes])
    for i in range(len(train_data_gold.train_labels)):
        C_hat[int(np.rint(train_data_gold.train_labels[i] - num_classes)), preds[i]] += 1

    C_hat /= (np.sum(C_hat, axis=1, keepdims=True) + 1e-7)
    C_hat = C_hat * 0.99 + np.full_like(C_hat, 1/num_classes) * 0.01  # smoothing

    return C_hat.T.astype(np.float32) 
开发者ID:mmazeika,项目名称:glc,代码行数:25,代码来源:train_confusion.py

示例9: extract_segments

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import rint [as 别名]
def extract_segments(wavs, segments=None):
    """ This function returns generator of segmented audio as
        (utterance id, numpy.float32 array)
        TODO?: sampling rate is not converted.
    """
    if segments is not None:
        # segments should be sorted by rec-id
        for seg in segments:
            wav = wavs[seg['rec']]
            data, samplerate = load_wav(wav)
            st_sample = np.rint(seg['st'] * samplerate).astype(int)
            et_sample = np.rint(seg['et'] * samplerate).astype(int)
            yield seg['utt'], data[st_sample:et_sample]
    else:
        # segments file not found,
        # wav.scp is used as segmented audio list
        for rec in wavs:
            data, samplerate = load_wav(wavs[rec])
            yield rec, data 
开发者ID:hitachi-speech,项目名称:EEND,代码行数:21,代码来源:kaldi_data.py

示例10: __init__

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import rint [as 别名]
def __init__(self, matrix_size, input_size, low=0, high=1, round_values=False):
        """Init function.

        @param matrix_size It defines the matrix size 
        @param input_size it defines the vector input size.
        @param low boundary for the random initialization 
        @param high boundary for the random initialization
        @param round_values it is possible to initialize the 
        weights to the closest integer value.
        """
        self._matrix_size = matrix_size
        self._input_size = input_size
        self._weights_matrix = np.random.uniform(low=low, high=high, size=(matrix_size, matrix_size, input_size))

        if (round_values == True):
            self._weights_matrix = np.rint(self._weights_matrix) 
开发者ID:mpatacchiola,项目名称:pyERA,代码行数:18,代码来源:som.py

示例11: setUp

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import rint [as 别名]
def setUp(self):
        M = 4
        N = 10000
        seed= 0
        sampling_frequency = 30000
        X = np.random.RandomState(seed=seed).normal(0, 1, (M, N))
        geom = np.random.RandomState(seed=seed).normal(0, 1, (M, 2))
        self._X = X
        self._geom = geom
        self._sampling_frequency = sampling_frequency
        self.RX = se.NumpyRecordingExtractor(timeseries=X, sampling_frequency=sampling_frequency, geom=geom)
        self.SX = se.NumpySortingExtractor()
        L = 200
        self._train1 = np.rint(np.random.RandomState(seed=seed).uniform(0, N, L)).astype(int)
        self.SX.add_unit(unit_id=1, times=self._train1)
        self.SX.add_unit(unit_id=2, times=np.random.RandomState(seed=seed).uniform(0, N, L))
        self.SX.add_unit(unit_id=3, times=np.random.RandomState(seed=seed).uniform(0, N, L)) 
开发者ID:SpikeInterface,项目名称:spikeextractors,代码行数:19,代码来源:test_numpy_extractors.py

示例12: __init__

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import rint [as 别名]
def __init__(self, file_path: PathType):
        super().__init__(file_path)
        cluster_classes = self._getfield("cluster_class")
        classes = cluster_classes[:, 0]
        spike_times = cluster_classes[:, 1]
        par = self._getfield("par")
        sample_rate = par[0, 0][np.where(np.array(par.dtype.names) == 'sr')[0][0]][0][0]

        self.set_sampling_frequency(sample_rate)
        self._unit_ids = np.unique(classes[classes > 0]).astype('int')

        self._spike_trains = {}
        for uid in self._unit_ids:
            mask = (classes == uid)
            self._spike_trains[uid] = np.rint(spike_times[mask]*(sample_rate/1000))
        self._unsorted_train = np.rint(spike_times[classes == 0] * (sample_rate / 1000)) 
开发者ID:SpikeInterface,项目名称:spikeextractors,代码行数:18,代码来源:waveclussortingextractor.py

示例13: optimize_model

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import rint [as 别名]
def optimize_model(task, param_name, test_size: float, binary=False) -> None:
    x, y = task.create_train_data()

    def objective(trial):
        train_x, test_x, train_y, test_y = train_test_split(x, y, test_size=test_size)
        param = redshells.factory.get_optuna_param(param_name, trial)
        model = task.create_model()
        model.set_params(**param)
        model.fit(train_x, train_y)
        predictions = model.predict(test_x)

        if binary:
            predictions = np.rint(predictions)

        return 1.0 - sklearn.metrics.accuracy_score(test_y, predictions)

    study = optuna.create_study()
    study.optimize(objective, n_trials=100)
    task.dump(dict(best_params=study.best_params, best_value=study.best_value)) 
开发者ID:m3dev,项目名称:redshells,代码行数:21,代码来源:utils.py

示例14: get_k_mesh_by_cell

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import rint [as 别名]
def get_k_mesh_by_cell(self, kpoints_per_reciprocal_angstrom, cell=None):
        """
            get k-mesh density according to the box size.

            Args:
                kpoints_per_reciprocal_angstrom: (float) number of k-points per reciprocal angstrom (i.e. per 2*pi*box_length)
                cell: (list/ndarray) 3x3 cell. If not set, the current cell is used.
        """
        if cell is None:
            if self.structure is None:
                raise AssertionError('structure not set')
            cell = self.structure.cell
        latlens = np.linalg.norm(cell, axis=-1)
        kmesh = np.rint( 2 * np.pi / latlens * kpoints_per_reciprocal_angstrom)
        if kmesh.min() <= 0:
            raise AssertionError("kpoint per angstrom too low")
        return [int(k) for k in kmesh] 
开发者ID:pyiron,项目名称:pyiron,代码行数:19,代码来源:generic.py

示例15: BGR2YCbCr

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import rint [as 别名]
def BGR2YCbCr(im):
    mat = np.array([[24.966, 128.553, 65.481],[112, -74.203, -37.797], [-18.214, -93.786, 112]])
    mat = mat.T
    offset = np.array([[[16, 128, 128]]])
    if im.dtype == 'uint8':
        mat = mat/255
        out = np.dot(im,mat) + offset
        out = np.clip(out, 0, 255)
        out = np.rint(out).astype('uint8')
    elif im.dtype == 'float':
        mat = mat/255
        offset = offset/255
        out = np.dot(im, mat) + offset
        out = np.clip(out, 0, 1)
    else:
        assert False
    return out 
开发者ID:JalaliLabUCLA,项目名称:Jalali-Lab-Implementation-of-RAISR,代码行数:19,代码来源:Functions.py


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