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


Python numpy.hsplit方法代碼示例

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


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

示例1: calculate_diff_stress

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import hsplit [as 別名]
def calculate_diff_stress(self, x, u, nu, side=1):
        """
        Calculate the derivative of the Von Mises stress given the densities x,
        displacements u, and young modulus nu. Optionally, provide the side
        length (default: 1).
        """
        rho = self.penalized_densities(x)
        EB = self.E(nu).dot(self.B(side))
        EBu = sum([EB.dot(u[:, i][self.edofMat]) for i in range(u.shape[1])])
        s11, s22, s12 = numpy.hsplit((EBu * rho / float(u.shape[1])).T, 3)
        drho = self.diff_penalized_densities(x)
        ds11, ds22, ds12 = numpy.hsplit(
            ((1 - rho) * drho * EBu / float(u.shape[1])).T, 3)
        vm_stress = numpy.sqrt(s11**2 - s11 * s22 + s22**2 + 3 * s12**2)
        if abs(vm_stress).sum() > 1e-8:
            dvm_stress = (0.5 * (1. / vm_stress) * (2 * s11 * ds11 -
                ds11 * s22 - s11 * ds22 + 2 * s22 * ds22 + 6 * s12 * ds12))
            return dvm_stress
        return 0 
開發者ID:zfergus,項目名稱:fenics-topopt,代碼行數:21,代碼來源:von_mises_stress.py

示例2: MAXPooling

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import hsplit [as 別名]
def MAXPooling(Array,activation=1, ksize=2):
    assert len(Array) % ksize == 0

    V2list = np.vsplit(Array, len(Array) / ksize)

    VerticalElements = list()
    HorizontalElements = list()

    for x in V2list:
        H2list = np.hsplit(x, len(x[0]) / ksize)
        HorizontalElements.clear()
        for y in H2list:
            # y should be a two-two square
            HorizontalElements.append(y.max())
        VerticalElements.append(np.array(HorizontalElements))

    return np.array(np.array(VerticalElements)/activation,dtype=int) 
開發者ID:jneless,項目名稱:EyerissF,代碼行數:19,代碼來源:Pooling.py

示例3: test_var_rep

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import hsplit [as 別名]
def test_var_rep():
    if debug_mode:
        if "VAR repr. A" not in to_test:  # pragma: no cover
            return
        print("\n\nVAR REPRESENTATION", end="")
    for ds in datasets:
        for dt in ds.dt_s_list:
            if debug_mode:
                print("\n" + dt_s_tup_to_string(dt) + ": ", end="")

            exog = (results_sm_exog[ds][dt].exog is not None)
            exog_coint = (results_sm_exog_coint[ds][dt].exog_coint is not None)

            err_msg = build_err_msg(ds, dt, "VAR repr. A")
            obtained = results_sm[ds][dt].var_rep
            obtained_exog = results_sm_exog[ds][dt].var_rep
            obtained_exog_coint = results_sm_exog_coint[ds][dt].var_rep
            p = obtained.shape[0]
            desired = np.hsplit(results_ref[ds][dt]["est"]["VAR A"], p)
            assert_allclose(obtained, desired, rtol, atol, False, err_msg)
            if exog:
                assert_equal(obtained_exog, obtained, "WITH EXOG" + err_msg)
            if exog_coint:
                assert_equal(obtained_exog_coint, obtained, "WITH EXOG_COINT" + err_msg) 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:26,代碼來源:test_vecm.py

示例4: bbox_overlaps

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import hsplit [as 別名]
def bbox_overlaps(bboxes, ref_bboxes):
    """
    ref_bboxes: N x 4;
    bboxes: K x 4

    return: K x N
    """
    refx1, refy1, refx2, refy2 = np.vsplit(np.transpose(ref_bboxes), 4)
    x1, y1, x2, y2 = np.hsplit(bboxes, 4)
    
    minx = np.maximum(refx1, x1)
    miny = np.maximum(refy1, y1)
    maxx = np.minimum(refx2, x2)
    maxy = np.minimum(refy2, y2)
    
    inter_area = (maxx - minx + 1) * (maxy - miny + 1)
    ref_area = (refx2 - refx1 + 1) * (refy2 - refy1 + 1)
    area = (x2 - x1 + 1) * (y2 - y1 + 1)
    iou = inter_area / (ref_area + area - inter_area)
    
    return iou 
開發者ID:dd604,項目名稱:refinedet.pytorch,代碼行數:23,代碼來源:ds_utils.py

示例5: _sample_incidents

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import hsplit [as 別名]
def _sample_incidents(rng, params):
  """Generates new crimeincident occurrences across locations.

  Args:
    rng: A numpy RandomState() object acting as a random number generator.
    params: A Params instance for this environment.

  Returns:
    incidents_occurred: a list of integers of number of incidents for each
    location.
    that could be discovered by attention.
    reported_incidents: a list of integers of a number of incidents reported
    directly.
  """
  # pylint: disable=g-complex-comprehension
  crimes = [
      rng.poisson([
          params.incident_rates[i] * params.discovered_incident_weight,
          params.incident_rates[i] * params.reported_incident_weight
      ]) for i in range(params.n_locations)
  ]
  incidents_occurred, reported_incidents = np.hsplit(np.asarray(crimes), 2)
  return incidents_occurred.flatten(), reported_incidents.flatten() 
開發者ID:google,項目名稱:ml-fairness-gym,代碼行數:25,代碼來源:attention_allocation.py

示例6: test_joint_space_warp_missing

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import hsplit [as 別名]
def test_joint_space_warp_missing(args):
    meta, X, _, fixed_vars = args

    S = sp.JointSpace(meta)

    X_w = S.warp([fixed_vars])
    assert X_w.dtype == sp.WARPED_DTYPE

    # Test bounds
    lower, upper = S.get_bounds().T
    assert np.all((lower <= X_w) | np.isnan(X_w))
    assert np.all((X_w <= upper) | np.isnan(X_w))

    for param, xx in zip(S.param_list, np.hsplit(X_w, S.blocks[:-1])):
        xx, = xx
        if param in fixed_vars:
            x_orig = S.spaces[param].unwarp(xx).item()
            S.spaces[param].validate(x_orig)
            assert close_enough(x_orig, fixed_vars[param])

            # check other direction
            x_w2 = S.spaces[param].warp(fixed_vars[param])
            assert close_enough(xx, x_w2)
        else:
            assert np.all(np.isnan(xx)) 
開發者ID:uber,項目名稱:bayesmark,代碼行數:27,代碼來源:space_test.py

示例7: test_debug

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import hsplit [as 別名]
def test_debug(self):
		image = imageio.imread("./temp/dump.png")
		grid_n = 6
		img_size = image.shape[1] // grid_n
		img_ch = image.shape[-1]

		images = np.vsplit(image, grid_n)
		images = [np.hsplit(i, grid_n) for i in images]
		images = np.reshape(np.array(images), [grid_n*grid_n, img_size, img_size, img_ch])

		with tf.Graph().as_default():
			with tf.Session() as sess:
				v_images_placeholder = tf.placeholder(dtype=tf.float32)
				v_images = tf.contrib.gan.eval.preprocess_image(v_images_placeholder)
				v_logits = tf.contrib.gan.eval.run_inception(v_images)
				v_score = tf.contrib.gan.eval.classifier_score_from_logits(v_logits)
				score, logits = sess.run([v_score, v_logits], feed_dict={v_images_placeholder:images})


		imageio.imwrite("./temp/inception_logits.png", logits) 
開發者ID:Octavian-ai,項目名稱:BigGAN-TPU-TensorFlow,代碼行數:22,代碼來源:inception_score.py

示例8: visualize_wave

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import hsplit [as 別名]
def visualize_wave(self, y):
        """Effect that flashes to the beat with scrolling coloured bits"""
        if self.current_freq_detects["beat"]:
            output = np.zeros((3,config.settings["devices"][self.board]["configuration"]["N_PIXELS"]))
            output[0][:]=colour_manager.colour(config.settings["devices"][self.board]["effect_opts"]["Wave"]["color_flash"])[0]
            output[1][:]=colour_manager.colour(config.settings["devices"][self.board]["effect_opts"]["Wave"]["color_flash"])[1]
            output[2][:]=colour_manager.colour(config.settings["devices"][self.board]["effect_opts"]["Wave"]["color_flash"])[2]
            self.wave_wipe_count = config.settings["devices"][self.board]["effect_opts"]["Wave"]["wipe_len"]
        else:
            output = np.copy(self.prev_output)
            #for i in range(len(self.prev_output)):
            #    output[i] = np.hsplit(self.prev_output[i],2)[0]
            output = np.multiply(self.prev_output,config.settings["devices"][self.board]["effect_opts"]["Wave"]["decay"])
            for i in range(self.wave_wipe_count):
                output[0][i]=colour_manager.colour(config.settings["devices"][self.board]["effect_opts"]["Wave"]["color_wave"])[0]
                output[0][-i]=colour_manager.colour(config.settings["devices"][self.board]["effect_opts"]["Wave"]["color_wave"])[0]
                output[1][i]=colour_manager.colour(config.settings["devices"][self.board]["effect_opts"]["Wave"]["color_wave"])[1]
                output[1][-i]=colour_manager.colour(config.settings["devices"][self.board]["effect_opts"]["Wave"]["color_wave"])[1]
                output[2][i]=colour_manager.colour(config.settings["devices"][self.board]["effect_opts"]["Wave"]["color_wave"])[2]
                output[2][-i]=colour_manager.colour(config.settings["devices"][self.board]["effect_opts"]["Wave"]["color_wave"])[2]
            #output = np.concatenate([output,np.fliplr(output)], axis=1)
            if self.wave_wipe_count > config.settings["devices"][self.board]["configuration"]["N_PIXELS"]//2:
                self.wave_wipe_count = config.settings["devices"][self.board]["configuration"]["N_PIXELS"]//2
            self.wave_wipe_count += config.settings["devices"][self.board]["effect_opts"]["Wave"]["wipe_speed"]
        return output 
開發者ID:not-matt,項目名稱:Systematic-LEDs,代碼行數:27,代碼來源:main.py

示例9: load_digits_and_labels

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import hsplit [as 別名]
def load_digits_and_labels(big_image):
    """ Returns all the digits from the 'big' image and creates the corresponding labels for each image"""

    # Load the 'big' image containing all the digits:
    digits_img = cv2.imread(big_image, 0)

    # Get all the digit images from the 'big' image:
    number_rows = digits_img.shape[1] / SIZE_IMAGE
    rows = np.vsplit(digits_img, digits_img.shape[0] / SIZE_IMAGE)

    digits = []
    for row in rows:
        row_cells = np.hsplit(row, number_rows)
        for digit in row_cells:
            digits.append(digit)
    digits = np.array(digits)

    # Create the labels for each image:
    labels = np.repeat(np.arange(NUMBER_CLASSES), len(digits) / NUMBER_CLASSES)
    return digits, labels 
開發者ID:PacktPublishing,項目名稱:Mastering-OpenCV-4-with-Python,代碼行數:22,代碼來源:knn_handwritten_digits_recognition_k_training_testing_preprocessing_hog.py

示例10: load_digits_and_labels

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import hsplit [as 別名]
def load_digits_and_labels(big_image):
    """Returns all the digits from the 'big' image and creates the corresponding labels for each image"""

    # Load the 'big' image containing all the digits:
    digits_img = cv2.imread(big_image, 0)

    # Get all the digit images from the 'big' image:
    number_rows = digits_img.shape[1] / SIZE_IMAGE
    rows = np.vsplit(digits_img, digits_img.shape[0] / SIZE_IMAGE)

    digits = []
    for row in rows:
        row_cells = np.hsplit(row, number_rows)
        for digit in row_cells:
            digits.append(digit)
    digits = np.array(digits)

    # Create the labels for each image:
    labels = np.repeat(np.arange(NUMBER_CLASSES), len(digits) / NUMBER_CLASSES)
    return digits, labels 
開發者ID:PacktPublishing,項目名稱:Mastering-OpenCV-4-with-Python,代碼行數:22,代碼來源:knn_handwritten_digits_recognition_introduction.py

示例11: find_closest_cluster

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import hsplit [as 別名]
def find_closest_cluster(query, ref, min_correlation=-1):
    """
    For each collection in query, identifies the collection in ref that is most similar

    query and ref are both dictionaries of CellCollections, keyed by a "partition id"

    Returns a list containing the best matches for each collection in query that meet the 
    min_correlation threshold.  Each member of the list is itself a list containing the 
    id of the query collection and the id of its best match in ref
    """
    query_centroids, query_ids = compute_centroids(query)
    ref_centroids, ref_ids = compute_centroids(ref)
    print('number of reference partions %d, number of query partions %d' % (len(ref_ids),len(query_ids)))
    all_correlations = np.corrcoef(np.concatenate((ref_centroids, query_centroids), axis=1), rowvar=False)

    # At this point, we have the correlations of everything vs everything.  We only care about query vs ref
    # Extract the top-right corner of the matrix
    nref = len(ref)
    corr = np.hsplit(np.vsplit(all_correlations, (nref, ))[0], (nref,))[1]
    best_match = zip(range(corr.shape[1]), np.argmax(corr, 0))
    # At this point, best_match is: 1) using indices into the array rather than ids, 
    # and 2) not restricted by the threshold.  Fix before returning
    return ( (query_ids[q], ref_ids[r]) for q, r in best_match if corr[r,q] >= min_correlation ) 
開發者ID:nsalomonis,項目名稱:altanalyze,代碼行數:25,代碼來源:cluster_corr.py

示例12: openCoordinates

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import hsplit [as 別名]
def openCoordinates(directory, nbInstances, nbImages):

    zi = []
    zi_strainX = []
    zi_strainY = []
    testTime = time.time()
    coordinatesFile = getData.testReadFile(directory+'/coordinates.csv')
    if coordinatesFile is not None:
        instanceCoordinates = np.hsplit(coordinatesFile, nbInstances)
        for instance in range(nbInstances):
            try:
                imageCoordinates = np.asarray(np.vsplit(instanceCoordinates[instance], nbImages))
            except:
                return None, None, None
            zi.append(imageCoordinates[:,:,0:100])
            zi_strainX.append(imageCoordinates[:,:,100:200])
            zi_strainY.append(imageCoordinates[:,:,200:300])
        return zi, zi_strainX, zi_strainY
    else:
        return None, None, None 
開發者ID:ChrisEberl,項目名稱:Python_DIC,代碼行數:22,代碼來源:initData.py

示例13: trainBlock

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import hsplit [as 別名]
def trainBlock(array,row,col):
    arrayShape=array.shape
    print(arrayShape)
    rowPara=divmod(arrayShape[1],row)  #divmod(a,b)方法為除法取整,以及a對b的餘數
    colPara=divmod(arrayShape[0],col)
    extractArray=array[:colPara[0]*col,:rowPara[0]*row]  #移除多餘部分,規範數組,使其正好切分均勻
#    print(extractArray.shape)
    hsplitArray=np.hsplit(extractArray,rowPara[0])
    vsplitArray=flatten_lst([np.vsplit(subArray,colPara[0]) for subArray in hsplitArray])
    dataBlock=flatten_lst(vsplitArray)
    print("樣本量:%s"%(len(dataBlock)))  #此時切分的塊數據量,就為樣本數據量
    
    '''顯示查看其中一個樣本'''     
    subShow=dataBlock[-10]
    print(subShow,'\n',subShow.max(),subShow.std())
    fig=plt.figure(figsize=(20, 12))
    ax=fig.add_subplot(111)
    plt.xticks([x for x in range(subShow.shape[0]) if x%400==0])
    plt.yticks([y for y in range(subShow.shape[1]) if y%200==0])
    ax.imshow(subShow)    
    
    dataBlockStack=np.append(dataBlock[:-1],[dataBlock[-1]],axis=0) #將列表轉換為數組
    print(dataBlockStack.shape)
    return dataBlockStack 
開發者ID:richieBao,項目名稱:python-urbanPlanning,代碼行數:26,代碼來源:rf_NDVIEvolution.py

示例14: calculate_principle_stresses

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import hsplit [as 別名]
def calculate_principle_stresses(self, x, u, nu, side=1):
        """
        Calculate the principle stresses in the x, y, and shear directions.
        """
        rho = self.penalized_densities(x)
        EB = self.E(nu).dot(self.B(side))
        stress = sum([EB.dot(u[:, i][self.edofMat]) for i in range(u.shape[1])])
        stress *= rho / float(u.shape[1])
        return numpy.hsplit(stress.T, 3) 
開發者ID:zfergus,項目名稱:fenics-topopt,代碼行數:11,代碼來源:von_mises_stress.py

示例15: split2d

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import hsplit [as 別名]
def split2d(img, cell_size, flatten=True):
    h, w = img.shape[:2]
    sx, sy = cell_size
    cells = [np.hsplit(row, w//sx) for row in np.vsplit(img, h//sy)]
    cells = np.array(cells)
    if flatten:
        cells = cells.reshape(-1, sy, sx)
    return cells 
開發者ID:makelove,項目名稱:OpenCV-Python-Tutorial,代碼行數:10,代碼來源:digits.py


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