當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。