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


Python numpy.r_方法代码示例

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


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

示例1: zipf_distribution

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import r_ [as 别名]
def zipf_distribution(nbr_symbols, alpha):
  """Helper function: Create a Zipf distribution.

  Args:
    nbr_symbols: number of symbols to use in the distribution.
    alpha: float, Zipf's Law Distribution parameter. Default = 1.5.
      Usually for modelling natural text distribution is in
      the range [1.1-1.6].

  Returns:
    distr_map: list of float, Zipf's distribution over nbr_symbols.

  """
  tmp = np.power(np.arange(1, nbr_symbols + 1), -alpha)
  zeta = np.r_[0.0, np.cumsum(tmp)]
  return [x / zeta[-1] for x in zeta] 
开发者ID:akzaidi,项目名称:fine-lm,代码行数:18,代码来源:algorithmic.py

示例2: fit

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import r_ [as 别名]
def fit(self, Xs, Xt):
        '''
        Fit source and target using KMM (compute the coefficients)
        :param Xs: ns * dim
        :param Xt: nt * dim
        :return: Coefficients (Pt / Ps) value vector (Beta in the paper)
        '''
        ns = Xs.shape[0]
        nt = Xt.shape[0]
        if self.eps == None:
            self.eps = self.B / np.sqrt(ns)
        K = kernel(self.kernel_type, Xs, None, self.gamma)
        kappa = np.sum(kernel(self.kernel_type, Xs, Xt, self.gamma) * float(ns) / float(nt), axis=1)

        K = matrix(K)
        kappa = matrix(kappa)
        G = matrix(np.r_[np.ones((1, ns)), -np.ones((1, ns)), np.eye(ns), -np.eye(ns)])
        h = matrix(np.r_[ns * (1 + self.eps), ns * (self.eps - 1), self.B * np.ones((ns,)), np.zeros((ns,))])

        sol = solvers.qp(K, -kappa, G, h)
        beta = np.array(sol['x'])
        return beta 
开发者ID:jindongwang,项目名称:transferlearning,代码行数:24,代码来源:KMM.py

示例3: get_batch

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import r_ [as 别名]
def get_batch(self, X, y):
        if self.curr == 0:
            self.add_obs(X, y)
            return X, y

        if (self.curr < self.n) and (isinstance(self.X_reserve, list)):
            if not self.has_sparse:
                old_X = np.concatenate(self.X_reserve, axis=0)
            else:
                old_X = sp_vstack(self.X_reserve)
            old_y = np.concatenate(self.y_reserve, axis=0)
        else:
            old_X = self.X_reserve[:self.curr].copy()
            old_y = self.y_reserve[:self.curr].copy()

        if X.shape[0] == 0:
            return old_X, old_y
        else:
            self.add_obs(X, y)

        if not issparse(old_X) and not issparse(X):
            return np.r_[old_X, X], np.r_[old_y, y]
        else:
            return sp_vstack([old_X, X]), np.r_[old_y, y] 
开发者ID:david-cortes,项目名称:contextualbandits,代码行数:26,代码来源:utils.py

示例4: make_sessions

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import r_ [as 别名]
def make_sessions(data, session_th=30 * 60, is_ordered=False, user_key='user_id', item_key='item_id', time_key='ts'):
    """Assigns session ids to the events in data without grouping keys"""
    if not is_ordered:
        # sort data by user and time
        data.sort_values(by=[user_key, time_key], ascending=True, inplace=True)
    # compute the time difference between queries
    tdiff = np.diff(data[time_key].values)
    # check which of them are bigger then session_th
    split_session = tdiff > session_th
    split_session = np.r_[True, split_session]
    # check when the user chenges is data
    new_user = data['user_id'].values[1:] != data['user_id'].values[:-1]
    new_user = np.r_[True, new_user]
    # a new sessions stars when at least one of the two conditions is verified
    new_session = np.logical_or(new_user, split_session)
    # compute the session ids
    session_ids = np.cumsum(new_session)
    data['session_id'] = session_ids
    return data 
开发者ID:mquad,项目名称:hgru4rec,代码行数:21,代码来源:build_dataset.py

示例5: read_segments_as_bool_vec

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import r_ [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

示例6: load

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import r_ [as 别名]
def load(self):
        categories = ['comp.sys.ibm.pc.hardware', 'comp.sys.mac.hardware']
        newsgroups_train = fetch_20newsgroups(
            subset='train', remove=('headers', 'footers', 'quotes'), categories=categories)
        newsgroups_test = fetch_20newsgroups(
            subset='test', remove=('headers', 'footers', 'quotes'), categories=categories)
        vectorizer = TfidfVectorizer(stop_words='english', min_df=0.001, max_df=0.20)
        vectors = vectorizer.fit_transform(newsgroups_train.data)
        vectors_test = vectorizer.transform(newsgroups_test.data)
        x1 = vectors
        y1 = newsgroups_train.target
        x2 = vectors_test
        y2 = newsgroups_test.target
        x = np.array(np.r_[x1.todense(), x2.todense()])
        y = np.r_[y1, y2]
        return x, y 
开发者ID:sato9hara,项目名称:sgd-influence,代码行数:18,代码来源:DataModule.py

示例7: test_float64_pass

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import r_ [as 别名]
def test_float64_pass(self):
        # The number of units of least precision
        # In this case, use a few places above the lowest level (ie nulp=1)
        nulp = 5
        x = np.linspace(-20, 20, 50, dtype=np.float64)
        x = 10**x
        x = np.r_[-x, x]

        # Addition
        eps = np.finfo(x.dtype).eps
        y = x + x*eps*nulp/2.
        assert_array_almost_equal_nulp(x, y, nulp)

        # Subtraction
        epsneg = np.finfo(x.dtype).epsneg
        y = x - x*epsneg*nulp/2.
        assert_array_almost_equal_nulp(x, y, nulp) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:19,代码来源:test_utils.py

示例8: test_complex128_pass

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import r_ [as 别名]
def test_complex128_pass(self):
        nulp = 5
        x = np.linspace(-20, 20, 50, dtype=np.float64)
        x = 10**x
        x = np.r_[-x, x]
        xi = x + x*1j

        eps = np.finfo(x.dtype).eps
        y = x + x*eps*nulp/2.
        assert_array_almost_equal_nulp(xi, x + y*1j, nulp)
        assert_array_almost_equal_nulp(xi, y + x*1j, nulp)
        # The test condition needs to be at least a factor of sqrt(2) smaller
        # because the real and imaginary parts both change
        y = x + x*eps*nulp/4.
        assert_array_almost_equal_nulp(xi, y + y*1j, nulp)

        epsneg = np.finfo(x.dtype).epsneg
        y = x - x*epsneg*nulp/2.
        assert_array_almost_equal_nulp(xi, x + y*1j, nulp)
        assert_array_almost_equal_nulp(xi, y + x*1j, nulp)
        y = x - x*epsneg*nulp/4.
        assert_array_almost_equal_nulp(xi, y + y*1j, nulp) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:24,代码来源:test_utils.py

示例9: test_complex64_pass

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import r_ [as 别名]
def test_complex64_pass(self):
        nulp = 5
        x = np.linspace(-20, 20, 50, dtype=np.float32)
        x = 10**x
        x = np.r_[-x, x]
        xi = x + x*1j

        eps = np.finfo(x.dtype).eps
        y = x + x*eps*nulp/2.
        assert_array_almost_equal_nulp(xi, x + y*1j, nulp)
        assert_array_almost_equal_nulp(xi, y + x*1j, nulp)
        y = x + x*eps*nulp/4.
        assert_array_almost_equal_nulp(xi, y + y*1j, nulp)

        epsneg = np.finfo(x.dtype).epsneg
        y = x - x*epsneg*nulp/2.
        assert_array_almost_equal_nulp(xi, x + y*1j, nulp)
        assert_array_almost_equal_nulp(xi, y + x*1j, nulp)
        y = x - x*epsneg*nulp/4.
        assert_array_almost_equal_nulp(xi, y + y*1j, nulp) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:22,代码来源:test_utils.py

示例10: _audio_events_extraction

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import r_ [as 别名]
def _audio_events_extraction(audio_t, audio_fronts):
    """
    From detected fronts on the audio sync traces, outputs the synchronisation events
    related to tone in

    :param audio_t: numpy vector containing times of fronts
    :param audio_fronts: numpy vector containing polarity of fronts (1 rise, -1 fall)
    :return: numpy arrays t_ready_tone_in, t_error_tone_in
    """
    # make sure that there are no 2 consecutive fall or consecutive rise events
    assert(np.all(np.abs(np.diff(audio_fronts)) == 2))
    # take only even time differences: ie. from rising to falling fronts
    dt = np.diff(audio_t)[::2]
    # detect ready tone by length below 110 ms
    i_ready_tone_in = np.r_[np.where(dt <= 0.11)[0] * 2]
    t_ready_tone_in = audio_t[i_ready_tone_in]
    # error tones are events lasting from 400ms to 600ms
    i_error_tone_in = np.where(np.logical_and(0.4 < dt, dt < 1.2))[0] * 2
    t_error_tone_in = audio_t[i_error_tone_in]
    return t_ready_tone_in, t_error_tone_in 
开发者ID:int-brain-lab,项目名称:ibllib,代码行数:22,代码来源:ephys_fpga.py

示例11: raster_complete

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import r_ [as 别名]
def raster_complete(R, times, Clusters):
    '''
    Plot a rasterplot for the complete recording
    (might be slow, restrict R if so),
    ordered by insertion depth
    '''

    plt.imshow(R, aspect='auto', cmap='binary', vmax=T_BIN / 0.001 / 4,
               origin='lower', extent=np.r_[times[[0, -1]], Clusters[[0, -1]]])

    plt.xlabel('Time (s)')
    plt.ylabel('Cluster #; ordered by depth')
    plt.show()

    # plt.savefig('/home/mic/Rasters/%s.svg' %(trial_number))
    # plt.close('all')
    plt.tight_layout() 
开发者ID:int-brain-lab,项目名称:ibllib,代码行数:19,代码来源:simplest_raster_plot.py

示例12: trapz_inte_edge

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import r_ [as 别名]
def trapz_inte_edge(y, x):
    """ Trapezoidal integration including edge grids

    Parameters:
        y: Array of y-axis value
        x: Array of x-axis value

        Returns:
        Area corresponded to each y (or x) value
            For Example,
             Area corresponded to at y_n is
            ..math:
                0.5*y_n ((x_{n} - x_{n-1}) + (x_{n+1} - x_{n}))
             Area corresponded to at y_0 (start point(edge)) is
            ..math:
                0.5*y_0(x_{1} - x_{0})
    """
    weight_x_0 = 0.5 * (x[1] - x[0])
    weight_x_f = 0.5 * (x[-1] - x[-2])
    weight_x_n = 0.5 * (x[1:-1] - x[:-2]) + 0.5 * (x[2:] - x[1:-1])
    weight_x = np.r_[weight_x_0, weight_x_n, weight_x_f]
    return weight_x*y 
开发者ID:atmtools,项目名称:typhon,代码行数:24,代码来源:__init__.py

示例13: test_estimate_F0statistics

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import r_ [as 别名]
def test_estimate_F0statistics(self):
        f0stats = F0statistics()
        orgf0s = []
        for i in range(1, 4):
            orgf0s.append(200 * np.r_[np.random.rand(100 * i), np.zeros(100)])
        orgf0stats = f0stats.estimate(orgf0s)

        tarf0s = []
        for i in range(1, 8):
            tarf0s.append(300 * np.r_[np.random.rand(100 * i), np.zeros(100)])
        tarf0stats = f0stats.estimate(tarf0s)

        orgf0 = 200 * np.r_[np.random.rand(100 * i), np.zeros(100)]
        cvf0 = f0stats.convert(orgf0, orgf0stats, tarf0stats)

        assert len(orgf0) == len(cvf0) 
开发者ID:k2kobayashi,项目名称:sprocket,代码行数:18,代码来源:test_f0stats.py

示例14: extent

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import r_ [as 别名]
def extent(self):
        """Get the Footprint's extent (`x` then `y`)

        Example
        -------
        >>> minx, maxx, miny, maxy = fp.extent
        >>> plt.imshow(arr, extent=fp.extent)

        fp.extent from fp.bounds using numpy fancy indexing

        >>> minx, maxx, miny, maxy = fp.bounds[[0, 2, 1, 3]]
        """
        points = np.r_["1,0,2", self.coords]
        return np.asarray([
            points[:, 0].min(), points[:, 0].max(),
            points[:, 1].min(), points[:, 1].max(),
        ]) 
开发者ID:airware,项目名称:buzzard,代码行数:19,代码来源:_footprint.py

示例15: bounds

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import r_ [as 别名]
def bounds(self):
        """Get the Footprint's bounds (`min` then `max`)

        Example
        -------
        >>> minx, miny, maxx, maxy = fp.bounds

        fp.bounds from fp.extent using numpy fancy indexing

        >>> minx, miny, maxx, maxy = fp.extent[[0, 2, 1, 3]]
        """
        points = np.r_["1,0,2", self.coords]
        return np.asarray([
            points[:, 0].min(), points[:, 1].min(),
            points[:, 0].max(), points[:, 1].max(),
        ]) 
开发者ID:airware,项目名称:buzzard,代码行数:18,代码来源:_footprint.py


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