当前位置: 首页>>代码示例>>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;未经允许,请勿转载。