當前位置: 首頁>>代碼示例>>Python>>正文


Python numpy.size方法代碼示例

本文整理匯總了Python中numpy.size方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.size方法的具體用法?Python numpy.size怎麽用?Python numpy.size使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在numpy的用法示例。


在下文中一共展示了numpy.size方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: draw_boxes_frame

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import size [as 別名]
def draw_boxes_frame(frame, frame_size, boxes_dicts, class_names, input_size):
  """Draws detected boxes in a video frame"""
  boxes_dict = boxes_dicts[0]
  resize_factor = (frame_size[0] / input_size[1], frame_size[1] / input_size[0])
  for cls in range(len(class_names)):
    boxes = boxes_dict[cls]
    color = (0, 0, 255)
    if np.size(boxes) != 0:
      for box in boxes:
        xy = box[:4]
        xy = [int(xy[i] * resize_factor[i % 2]) for i in range(4)]
        cv2.rectangle(frame, (xy[0], xy[1]), (xy[2], xy[3]), color[::-1], 2)
        (test_width, text_height), baseline = cv2.getTextSize(class_names[cls],
                                                              cv2.FONT_HERSHEY_SIMPLEX,
                                                              0.75, 1)
        cv2.rectangle(frame,
                      (xy[0], xy[1]),
                      (xy[0] + test_width, xy[1] - text_height - baseline),
                      color[::-1],
                      thickness=cv2.FILLED)
        cv2.putText(frame, class_names[cls], (xy[0], xy[1] - baseline), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 0), 1) 
開發者ID:kcosta42,項目名稱:Tensorflow-YOLOv3,代碼行數:23,代碼來源:utils.py

示例2: initialize

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import size [as 別名]
def initialize(context, eps = 10, window_length = 50):
    
    #init    
    context.stocks = STOCKS
    context.sids = SIDS
    #context.sids = [context.symbol(symb) for symb in context.stocks]
    context.m = np.size(STOCKS)
    context.price = {}
    context.b_t = np.ones(context.m)/float(context.m)
    context.prev_weights = np.ones(context.m)/float(context.m)
    context.eps = eps
    context.init = True
    context.days = 0
    context.window_length = window_length
    
    add_history(window_length, '1d', 'price')
    
    #set commision and slippage
    #context.set_commision(commission.PerShare(cost=0))
    #context.set_slippage(slippage.VolumeShareSlippage(volume_limit=0.25, price_impact=0.1)) 
開發者ID:vsmolyakov,項目名稱:fin,代碼行數:22,代碼來源:olmar.py

示例3: analyze

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import size [as 別名]
def analyze(context=None, results=None):
        
    f, (ax1, ax2, ax3) = plt.subplots(3, sharex = True)        
    ax1.plot(results.portfolio_value, linewidth = 2.0, label = 'porfolio')
    ax1.set_title('On-Line Moving Average Reversion')
    ax1.set_ylabel('Portfolio value (USD)')
    ax1.legend(loc=0)
    ax1.grid(True)
            
    ax2.plot(results['AAPL'], color = 'b', linestyle = '-', linewidth = 2.0, label = 'AAPL')
    ax2.plot(results['MSFT'], color = 'r', linestyle = '-', linewidth = 2.0, label = 'MSFT')
    ax2.set_ylabel('stock price (USD)')
    ax2.legend(loc=0)
    ax2.grid(True)
    
    ax3.semilogy(results['step_size'], color = 'b', linestyle = '-', linewidth = 2.0, label = 'step-size')
    ax3.semilogy(results['variability'], color = 'r', linestyle = '-', linewidth = 2.0, label = 'variability')
    ax3.legend(loc=0)
    ax3.grid(True)
    
    plt.show() 
開發者ID:vsmolyakov,項目名稱:fin,代碼行數:23,代碼來源:olmar.py

示例4: set_frame

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import size [as 別名]
def set_frame(frame):
    # convert 3x6 world_frame matrix into three line_data objects which is 3x2 (row:point index, column:x,y,z)
    lines_data = [frame[:,[0,2]], frame[:,[1,3]], frame[:,[4,5]]]
    ax = plt.gca()
    lines = ax.get_lines()
    for line, line_data in zip(lines[:3], lines_data):
        x, y, z = line_data
        line.set_data(x, y)
        line.set_3d_properties(z)

    global history, count
    # plot history trajectory
    history[count] = frame[:,4]
    if count < np.size(history, 0) - 1:
        count += 1
    zline = history[:count,-1]
    xline = history[:count,0]
    yline = history[:count,1]
    lines[-1].set_data(xline, yline)
    lines[-1].set_3d_properties(zline)
    # ax.plot3D(xline, yline, zline, 'blue') 
開發者ID:hbd730,項目名稱:quadcopter-simulation,代碼行數:23,代碼來源:quadPlot.py

示例5: flush

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import size [as 別名]
def flush(self):
        """
        Composes the vector.
        Returns:
            The composed vector.
        """
        if self.__data__ is None:
            self.__data__ = result = np.empty(self.__total_size__, dtype=self.__dtype__)
            offset = 0
        else:
            offset = self.__data__.size
            self.__data__ = result = np.empty(self.__total_size__ + self.__data__.size, dtype=self.__dtype__)

        for i in self.__transactions__:
            s = i.size
            result[offset:offset + s] = i.reshape(-1)
            offset += s
        self.__transactions__ = []

        return result 
開發者ID:pyscf,項目名稱:pyscf,代碼行數:22,代碼來源:kpts_helper.py

示例6: si_c

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import size [as 別名]
def si_c(self, ww, use_numba_impl=False):
    from numpy.linalg import solve
    """ 
    This computes the correlation part of the screened interaction W_c
    by solving <self.nprod> linear equations (1-K chi0) W = K chi0 K 
    or v_{ind}\sim W_{c} = (1-v\chi_{0})^{-1}v\chi_{0}v
    scr_inter[w,p,q], where w in ww, p and q in 0..self.nprod 
    """

    if not hasattr(self, 'pab2v_den'):
      self.pab2v_den = einsum('pab->apb', self.pb.get_ac_vertex_array())

    si0 = np.zeros((ww.size, self.nprod, self.nprod), dtype=self.dtypeComplex)
    if use_numba and use_numba_impl:

        # numba implementation suffer from some continuous array issue
        # for example in test test_0087_o2_gw.py
        # use only for expeimental test
        si_correlation_numba(si0, ww, self.x, self.kernel_sq, self.ksn2f, self.ksn2e,
                             self.pab2v_den, self.nprod, self.norbs, self.bsize,
                             self.nspin, self.nfermi, self.vstart)
    else:
        si_correlation(rf0_den(self, ww), si0, ww, self.kernel_sq, self.nprod)
    return si0 
開發者ID:pyscf,項目名稱:pyscf,代碼行數:26,代碼來源:gw.py

示例7: __repr__

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import size [as 別名]
def __repr__(self):
        """x.__repr__() <==> repr(x)."""
        if not hasattr(self, "__repr"):
            params = self.params or {}
            parsed_params = []
            for k, v in params.items():
                sk = str(k)
                if np.ndim(v) != 0 and np.size(v) > MAX_VALUES_TO_REPR:
                    tv = type(v)
                    sv = f"<{tv.__module__}.{tv.__name__}>"
                else:
                    sv = str(v)
                parsed_params.append(f"{sk}={sv}")
            str_params = ", ".join(parsed_params)
            self.__repr = f"{self.name}({str_params})"

        return self.__repr 
開發者ID:quatrope,項目名稱:feets,代碼行數:19,代碼來源:core.py

示例8: read_image_pair

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import size [as 別名]
def read_image_pair(pair_path, resize_or_crop=None, image_size=(256,256)):
    image_blur = cv2.imread(pair_path[0], cv2.IMREAD_COLOR)
    image_blur = image_blur / 255.0 * 2.0 - 1.0
    image_real = cv2.imread(pair_path[1], cv2.IMREAD_COLOR)
    image_real = image_real / 255.0 * 2.0 - 1.0

    if resize_or_crop != None: 
        assert image_size != None

    if resize_or_crop == 'resize':
        image_blur = cv2.resize(image_blur, image_size, interpolation=cv2.INTER_AREA)
        image_real = cv2.resize(image_real, image_size, interpolation=cv2.INTER_AREA)
    elif resize_or_crop == 'crop':
        image_blur = cv2.crop(image_blur, image_size)
        image_real = cv2.crop(image_real, image_size)
    else:
        raise

    if np.size(np.shape(image_blur)) == 3:
        image_blur = np.expand_dims(image_blur, axis=0)
    if np.size(np.shape(image_real)) == 3:
        image_real = np.expand_dims(image_real, axis=0)
    image_blur = np.array(image_blur, dtype=np.float32)
    image_real = np.array(image_real, dtype=np.float32)
    return image_blur, image_real 
開發者ID:LeeDoYup,項目名稱:DeblurGAN-tf,代碼行數:27,代碼來源:data_loader.py

示例9: read_image

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import size [as 別名]
def read_image(path, resize_or_crop=None, image_size=(256,256)):
    image = cv2.imread(path, cv2.IMREAD_COLOR)
    image = image/255.0 * 2.0 - 1.0

    assert resize_or_crop != None
    assert image_size != None

    if resize_or_crop == 'resize':
        image = cv2.resize(image, image_size, interpolation=cv2.INTER_AREA)
    elif resize_or_crop == 'crop':
        image = cv2.crop(image, image_size)

    if np.size(np.shape(image)) == 3: 
        image = np.expand_dims(image, axis=0)

    image = np.array(image, dtype=np.float32)
    return image 
開發者ID:LeeDoYup,項目名稱:DeblurGAN-tf,代碼行數:19,代碼來源:data_loader.py

示例10: test_count_nonzero_axis_consistent

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import size [as 別名]
def test_count_nonzero_axis_consistent(self):
        # Check that the axis behaviour for valid axes in
        # non-special cases is consistent (and therefore
        # correct) by checking it against an integer array
        # that is then casted to the generic object dtype
        from itertools import combinations, permutations

        axis = (0, 1, 2, 3)
        size = (5, 5, 5, 5)
        msg = "Mismatch for axis: %s"

        rng = np.random.RandomState(1234)
        m = rng.randint(-100, 100, size=size)
        n = m.astype(object)

        for length in range(len(axis)):
            for combo in combinations(axis, length):
                for perm in permutations(combo):
                    assert_equal(
                        np.count_nonzero(m, axis=perm),
                        np.count_nonzero(n, axis=perm),
                        err_msg=msg % (perm,)) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:24,代碼來源:test_numeric.py

示例11: test_count_uses_size_on_exception

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import size [as 別名]
def test_count_uses_size_on_exception():
    class RaisingObjectException(Exception):
        pass

    class RaisingObject(object):

        def __init__(self, msg='I will raise inside Cython'):
            super(RaisingObject, self).__init__()
            self.msg = msg

        def __eq__(self, other):
            # gets called in Cython to check that raising calls the method
            raise RaisingObjectException(self.msg)

    df = DataFrame({'a': [RaisingObject() for _ in range(4)],
                    'grp': list('ab' * 2)})
    result = df.groupby('grp').count()
    expected = DataFrame({'a': [2, 2]}, index=pd.Index(
        list('ab'), name='grp'))
    tm.assert_frame_equal(result, expected)


# size
# -------------------------------- 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:26,代碼來源:test_function.py

示例12: test_responsive_units

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import size [as 別名]
def test_responsive_units(self):
        if self.test_data is None:
            return
        spike_times = self.test_data['spike_times']
        spike_clusters = self.test_data['spike_clusters']
        event_times = self.test_data['event_times']
        alpha = 0.5
        sig_units, stats, p_values, cluster_ids = bb.task.responsive_units(spike_times,
                                                                           spike_clusters,
                                                                           event_times,
                                                                           pre_time=[0.5, 0],
                                                                           post_time=[0, 0.5],
                                                                           alpha=alpha)
        num_clusters = np.size(np.unique(spike_clusters))
        self.assertTrue(np.size(sig_units) == 125)
        self.assertTrue(np.sum(p_values < alpha) == np.size(sig_units))
        self.assertTrue(np.size(cluster_ids) == num_clusters) 
開發者ID:int-brain-lab,項目名稱:ibllib,代碼行數:19,代碼來源:test_task.py

示例13: test_roc_between_two_events

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import size [as 別名]
def test_roc_between_two_events(self):
        if self.test_data is None:
            return
        spike_times = self.test_data['spike_times']
        spike_clusters = self.test_data['spike_clusters']
        event_times = self.test_data['event_times']
        event_groups = self.test_data['event_groups']
        auc_roc, cluster_ids = bb.task.roc_between_two_events(spike_times,
                                                              spike_clusters,
                                                              event_times,
                                                              event_groups,
                                                              pre_time=0.5,
                                                              post_time=0.5)
        num_clusters = np.size(np.unique(spike_clusters))
        self.assertTrue(np.sum(auc_roc < 0.3) == 24)
        self.assertTrue(np.sum(auc_roc > 0.7) == 10)
        self.assertTrue(np.size(cluster_ids) == num_clusters) 
開發者ID:int-brain-lab,項目名稱:ibllib,代碼行數:19,代碼來源:test_task.py

示例14: policy_improvement

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import size [as 別名]
def policy_improvement(self, actions, values, policy):
        new_policy = np.copy(policy)

        expected_action_returns = np.zeros((MAX_CARS + 1, MAX_CARS + 1, np.size(actions)))
        cooks = dict()
        with mp.Pool(processes=8) as p:
            for action in actions:
                k = np.arange(MAX_CARS + 1)
                all_states = ((i, j) for i, j in itertools.product(k, k))
                cooks[action] = partial(self.expected_return_pi, values, action)
                results = p.map(cooks[action], all_states)
                for v, i, j, a in results:
                    expected_action_returns[i, j, self.inverse_actions[a]] = v
        for i in range(expected_action_returns.shape[0]):
            for j in range(expected_action_returns.shape[1]):
                new_policy[i, j] = actions[np.argmax(expected_action_returns[i, j])]

        policy_change = (new_policy != policy).sum()
        print(f'Policy changed in {policy_change} states')
        return policy_change, new_policy

    # O(n^4) computation for all possible requests and returns 
開發者ID:ShangtongZhang,項目名稱:reinforcement-learning-an-introduction,代碼行數:24,代碼來源:car_rental_synchronous.py

示例15: _init_lenscale

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import size [as 別名]
def _init_lenscale(given_lenscale, learn_lenscale, input_dim):
    """Provide the lenscale variable and its initial value."""
    given_lenscale = (np.sqrt(1.0 / input_dim) if given_lenscale is None
                      else np.array(given_lenscale).squeeze()).astype(
                          np.float32)

    if learn_lenscale:
        lenscale = pos_variable(given_lenscale, name="kernel_lenscale")
        if np.size(given_lenscale) == 1:
            summary_scalar(lenscale)
        else:
            summary_histogram(lenscale)
    else:
        lenscale = given_lenscale

    lenscale_vec = tf.ones(input_dim, dtype=tf.float32) * lenscale
    init_lenscale = given_lenscale * np.ones(input_dim, dtype=np.float32)
    return lenscale_vec, init_lenscale 
開發者ID:gradientinstitute,項目名稱:aboleth,代碼行數:20,代碼來源:kernels.py


注:本文中的numpy.size方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。