GVKun编程网logo

Python numpy 模块-union1d() 实例源码(python中numpy模块)

3

如果您想了解Pythonnumpy模块-union1d()实例源码的相关知识,那么本文是一篇不可错过的文章,我们将对python中numpy模块进行全面详尽的解释,并且为您提供关于Jupyter中的N

如果您想了解Python numpy 模块-union1d() 实例源码的相关知识,那么本文是一篇不可错过的文章,我们将对python中numpy模块进行全面详尽的解释,并且为您提供关于Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable、numpy.random.random & numpy.ndarray.astype & numpy.arange、numpy.ravel()/numpy.flatten()/numpy.squeeze()、Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性的有价值的信息。

本文目录一览:

Python numpy 模块-union1d() 实例源码(python中numpy模块)

Python numpy 模块-union1d() 实例源码(python中numpy模块)

Python numpy 模块,union1d() 实例源码

我们从Python开源项目中,提取了以下39个代码示例,用于说明如何使用numpy.union1d()

项目:Endemicpy    作者:j-i-l    | 项目源码 | 文件源码
  1. def __init__(self, source, **params):
  2. #_Graph.__init__(self)
  3. self.is_static = False
  4. if isinstance(source, str): # it is a file
  5. self._load(source, **params)
  6. else: # source must be an EventQueue then
  7. # to do: read from event queue
  8. # should also get self.starts,...
  9. pass
  10. self.t_start = params.get(''t_start'', np.min(self.starts))
  11. self.t_stop = params.get(''t_stop'', np.max(self.stops))
  12. # Todo: Ideally only use self.all_nodes
  13. self.all_nodes = list(np.union1d(self.node1s, self.node2s))
  14. all_nodes = list(np.union1d(self.node1s, self.node2s))
  15. n = len(self.all_nodes)
  16.  
  17. def get_id(an_id):
  18. return all_nodes.index(an_id)
  19. v_get_id = np.vectorize(get_id)
  20.  
  21. self.node1s = v_get_id(self.node1s)
  22. self.node2s = v_get_id(self.node2s)
  23. # Now we need to remap the node ids
  24. _Graph.__init__(self, n=n)
项目:yt    作者:yt-project    | 项目源码 | 文件源码
  1. def uunion1d(arr1, arr2):
  2. """Find the union of two arrays.
  3.  
  4. A wrapper around numpy.intersect1d that preserves units. All input arrays
  5. must have the same units. See the documentation of numpy.intersect1d for
  6. full details.
  7.  
  8. Examples
  9. --------
  10. >>> A = yt.YTArray([1,2,3],''cm'')
  11. >>> B = yt.YTArray([2,3,4],''cm'')
  12. >>> uunion1d(A,B)
  13. YTArray([ 1.,2.,3.,4.]) cm
  14.  
  15. """
  16. v = np.union1d(arr1, arr2)
  17. v = validate_numpy_wrapper_units(v, [arr1, arr2])
  18. return v
项目:asammdf    作者:danielhrisca    | 项目源码 | 文件源码
  1. def __apply_func(self, other, func_name):
  2.  
  3. if isinstance(other, Signal):
  4. time = np.union1d(self.timestamps, other.timestamps)
  5. s = self.interp(time).samples
  6. o = other.interp(time).samples
  7. func = getattr(s, func_name)
  8. s = func(o)
  9. elif other is None:
  10. s = self.samples
  11. time = self.timestamps
  12. else:
  13. func = getattr(self.samples, func_name)
  14. s = func(other)
  15. time = self.timestamps
  16. return Signal(s,
  17. time,
  18. self.unit,
  19. self.name,
  20. self.info)
项目:Theano-Deep-learning    作者:GeekLiB    | 项目源码 | 文件源码
  1. def test_confusion_matrix():
  2. # Defining numpy implementation of confusion matrix
  3. def numpy_conf_mat(actual, pred):
  4. order = numpy.union1d(actual, pred)
  5. colA = numpy.matrix(actual).T
  6. colP = numpy.matrix(pred).T
  7. oneHotA = colA.__eq__(order).astype(''int64'')
  8. oneHotP = colP.__eq__(order).astype(''int64'')
  9. conf_mat = numpy.dot(oneHotA.T, oneHotP)
  10. conf_mat = numpy.asarray(conf_mat)
  11. return [conf_mat, order]
  12.  
  13. x = tensor.vector()
  14. y = tensor.vector()
  15. f = theano.function([x, y], confusion_matrix(x, y))
  16. list_inputs = [[[0, 1, 2, 0], [0, 0, 2]],
  17. [[2, 1], 2]]]
  18.  
  19. for case in list_inputs:
  20. a = numpy.asarray(case[0])
  21. b = numpy.asarray(case[1])
  22. out_exp = numpy_conf_mat(a, b)
  23. outs = f(case[0], case[1])
  24. for exp, out in zip(out_exp, outs):
  25. utt.assert_allclose(exp, out)
项目:beprof    作者:DataMedSci    | 项目源码 | 文件源码
  1. def subtract(curve1, curve2, def_val=0):
  2. """
  3. Function calculates difference between curve1 and curve2
  4. and returns new object which domain is an union
  5. of curve1 and curve2 domains
  6. Returned object is of type type(curve1)
  7. and has same Metadata as curve1 object
  8.  
  9. :param curve1: first curve to calculate the difference
  10. :param curve2: second curve to calculate the difference
  11. :param def_val: default value for points that cannot be interpolated
  12. :return: new object of type type(curve1) with element-wise difference
  13. (using interpolation if necessary)
  14. """
  15. coord1 = np.union1d(curve1.x, curve2.x)
  16. y1 = curve1.evaluate_at_x(coord1, def_val)
  17. y2 = curve2.evaluate_at_x(coord1, def_val)
  18. coord2 = y1 - y2
  19. # the below is explained at the end of curve.Curve.change_domain()
  20. obj = curve1.__class__(np.dstack((coord1, coord2))[0], **curve1.__dict__[''Metadata''])
  21. return obj
项目:bnpy    作者:bnpy    | 项目源码 | 文件源码
  1. def relabelAllSequences(zBySeq, specialStateIDs):
  2. '''''' Relabel all sequences in provided list.
  3.  
  4. Returns
  5. -------
  6. zBySeq,relabelled so that each label in specialStateIDs
  7. Now corresponds to ids 0,1,... L-1
  8. and all other labels not in that set get ids L,L+1,...
  9. ''''''
  10. import copy
  11. zBySeq = copy.deepcopy(zBySeq)
  12. L = len(specialStateIDs)
  13.  
  14. uniqueVals = []
  15. for z in zBySeq:
  16. z += 1000
  17. for kID, kVal in enumerate(specialStateIDs):
  18. z[z == 1000 + kVal] = -1000 + kID
  19. uniqueVals = np.union1d(uniqueVals, np.unique(z))
  20.  
  21. for z in zBySeq:
  22. for kID, kVal in enumerate(sorted(uniqueVals)):
  23. z[z == kVal] = kID
  24.  
  25. return zBySeq
项目:orange-infrared    作者:markotoplak    | 项目源码 | 文件源码
  1. def multi_x_reader(self, spc_file):
  2. # use x-values as domain
  3. all_x = []
  4. for sub in spc_file.sub:
  5. x = sub.x
  6. # assume values in x do not repeat
  7. all_x = np.union1d(all_x, x)
  8. domain = Orange.data.Domain([Orange.data.ContinuousVariable.make("%f" % f) for f in all_x], None)
  9.  
  10. instances = []
  11. for sub in spc_file.sub:
  12. x, y = sub.x, sub.y
  13. newinstance = np.ones(len(all_x))*np.nan
  14. ss = np.searchsorted(all_x, x) # find positions to set
  15. newinstance[ss] = y
  16. instances.append(newinstance)
  17.  
  18. y_data = np.array(instances).astype(float, order=''C'')
  19. return Orange.data.Table.from_numpy(domain, y_data)
项目:SNPmatch    作者:Gregor-Mendel-Institute    | 项目源码 | 文件源码
  1. def pairwisescore(inFile_1, inFile_2, logDebug, outFile):
  2. (snpCHR1, snpPOS1, snpGT1, snpWEI1, DPmean1) = parseInput(inFile = inFile_1, logDebug = logDebug)
  3. (snpCHR2, snpPOS2, snpGT2, snpWEI2, DPmean2) = parseInput(inFile = inFile_2, logDebug = logDebug)
  4. snpmatch_stats = {}
  5. unique_1, unique_2, common, scores = 0, 0
  6. chrs = np.union1d(snpCHR1, snpCHR2)
  7. for i in chrs:
  8. perchrTarPosInd1 = np.where(snpCHR1 == i)[0]
  9. perchrTarPosInd2 = np.where(snpCHR2 == i)[0]
  10. log.info("Analysing chromosome %s positions", i)
  11. perchrtarSNPpos1 = snpPOS1[perchrTarPosInd1]
  12. perchrtarSNPpos2 = snpPOS2[perchrTarPosInd2]
  13. matchedAccInd1 = np.where(np.in1d(perchrtarSNPpos1, perchrtarSNPpos2))[0]
  14. matchedAccInd2 = np.where(np.in1d(perchrtarSNPpos2, perchrtarSNPpos1))[0]
  15. unique_1 = unique_1 + len(perchrTarPosInd1) - len(matchedAccInd1)
  16. unique_2 = unique_2 + len(perchrTarPosInd2) - len(matchedAccInd2)
  17. common = common + len(matchedAccInd1)
  18. scores = scores + np.sum(np.array(snpGT1[matchedAccInd1] == snpGT2[matchedAccInd2], dtype = int))
  19. snpmatch_stats[''unique''] = {"%s" % os.path.basename(inFile_1): [float(unique_1)/len(snpCHR1), len(snpCHR1)], "%s" % os.path.basename(inFile_2): [float(unique_2)/len(snpCHR2), len(snpCHR2)]}
  20. snpmatch_stats[''matches''] = [float(scores)/common, common]
  21. if not outFile:
  22. outFile = "genotyper"
  23. log.info("writing output in a file: %s" % outFile + ".matches.json")
  24. with open(outFile + ".matches.json", "w") as out_stats:
  25. out_stats.write(json.dumps(snpmatch_stats))
  26. log.info("finished!")
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def union1d(ar1, ar2):
  2. """
  3. Find the union of two arrays.
  4.  
  5. Return the unique,sorted array of values that are in either of the two
  6. input arrays.
  7.  
  8. Parameters
  9. ----------
  10. ar1,ar2 : array_like
  11. Input arrays. They are flattened if they are not already 1D.
  12.  
  13. Returns
  14. -------
  15. union1d : ndarray
  16. Unique,sorted union of the input arrays.
  17.  
  18. See Also
  19. --------
  20. numpy.lib.arraysetops : Module with a number of other functions for
  21. performing set operations on arrays.
  22.  
  23. Examples
  24. --------
  25. >>> np.union1d([-1,1],[-2,2])
  26. array([-2,-1,2])
  27.  
  28. To find the union of more than two arrays,use functools.reduce:
  29.  
  30. >>> from functools import reduce
  31. >>> reduce(np.union1d,([1,4,[3,[6,2]))
  32. array([1,6])
  33. """
  34. return unique(np.concatenate((ar1, ar2)))
项目:Caffe-Python-Data-Layer    作者:liuxianming    | 项目源码 | 文件源码
  1. def intersect_sim(array_1, array_2):
  2. """Calculate the simiarity of two arrays
  3. by using intersection / union
  4. """
  5. sim = float(np.intersect1d(array_1, array_2).size) / \\
  6. float(np.union1d(array_1, array_2).size)
  7. return sim
项目:unet-tensorflow-keras    作者:zizhaozhang    | 项目源码 | 文件源码
  1. def union_classes(eval_segm, gt_segm):
  2. eval_cl, _ = extract_classes(eval_segm)
  3. gt_cl, _ = extract_classes(gt_segm)
  4.  
  5. cl = np.union1d(eval_cl, gt_cl)
  6. n_cl = len(cl)
  7.  
  8. return cl, n_cl
项目:SOTA-Py    作者:mehrdadn    | 项目源码 | 文件源码
  1. def __init__(self, edges):
  2. self.edges = edges
  3. self.nodes = Nodes(len(numpy.union1d(self.edges.begin, self.edges.end)))
  4. for i in xrange(len(self.edges)):
  5. j = i if True else 0
  6. self.nodes.outgoing[self.edges.begin[i]].append(j)
  7. self.nodes.incoming[self.edges.end [i]].append(j)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def union1d(ar1, ar2)))
项目:yt    作者:yt-project    | 项目源码 | 文件源码
  1. def test_numpy_wrappers():
  2. a1 = YTArray([1, 3], ''cm'')
  3. a2 = YTArray([2, 3, 4, 5, 6], ''cm'')
  4. catenate_answer = [1, 6]
  5. intersect_answer = [2, 3]
  6. union_answer = [1, 6]
  7.  
  8. assert_array_equal(YTArray(catenate_answer, ''cm''), uconcatenate((a1, a2)))
  9. assert_array_equal(catenate_answer, np.concatenate((a1, a2)))
  10.  
  11. assert_array_equal(YTArray(intersect_answer, uintersect1d(a1, a2))
  12. assert_array_equal(intersect_answer, np.intersect1d(a1, a2))
  13.  
  14. assert_array_equal(YTArray(union_answer, uunion1d(a1, a2))
  15. assert_array_equal(union_answer, np.union1d(a1, a2))
项目:yt    作者:yt-project    | 项目源码 | 文件源码
  1. def test_boolean_spheres_overlap():
  2. r"""Test to make sure that boolean objects (spheres,overlap)
  3. behave the way we expect.
  4.  
  5. Test overlapping spheres.
  6. """
  7. ds = fake_amr_ds()
  8. sp1 = ds.sphere([0.45, 0.45, 0.45], 0.15)
  9. sp2 = ds.sphere([0.55, 0.55, 0.55], 0.15)
  10. # Get indices of both.
  11. i1 = sp1["index","morton_index"]
  12. i2 = sp2["index","morton_index"]
  13. # Make some booleans
  14. bo1 = sp1 & sp2
  15. bo2 = sp1 - sp2
  16. bo3 = sp1 | sp2
  17. bo4 = ds.union([sp1, sp2])
  18. bo5 = ds.intersection([sp1, sp2])
  19. # Now make sure the indices also behave as we expect.
  20. lens = np.intersect1d(i1, i2)
  21. apple = np.setdiff1d(i1, i2)
  22. both = np.union1d(i1, i2)
  23. b1 = bo1["index","morton_index"]
  24. b1.sort()
  25. b2 = bo2["index","morton_index"]
  26. b2.sort()
  27. b3 = bo3["index","morton_index"]
  28. b3.sort()
  29. assert_array_equal(b1, lens)
  30. assert_array_equal(b2, apple)
  31. assert_array_equal(b3, both)
  32. b4 = bo4["index","morton_index"]
  33. b4.sort()
  34. b5 = bo5["index","morton_index"]
  35. b5.sort()
  36. assert_array_equal(b3, b4)
  37. assert_array_equal(b1, b5)
  38. bo6 = sp1 ^ sp2
  39. b6 = bo6["index", "morton_index"]
  40. b6.sort()
  41. assert_array_equal(b6, np.setxor1d(i1, i2))
项目:yt    作者:yt-project    | 项目源码 | 文件源码
  1. def test_boolean_regions_overlap():
  2. r"""Test to make sure that boolean objects (regions,overlap)
  3. behave the way we expect.
  4.  
  5. Test overlapping regions.
  6. """
  7. ds = fake_amr_ds()
  8. re1 = ds.region([0.55]*3, [0.5]*3, [0.6]*3)
  9. re2 = ds.region([0.6]*3, [0.55]*3, [0.65]*3)
  10. # Get indices of both.
  11. i1 = re1["index","morton_index"]
  12. i2 = re2["index","morton_index"]
  13. # Make some booleans
  14. bo1 = re1 & re2
  15. bo2 = re1 - re2
  16. bo3 = re1 | re2
  17. bo4 = ds.union([re1, re2])
  18. bo5 = ds.intersection([re1, re2])
  19. # Now make sure the indices also behave as we expect.
  20. cube = np.intersect1d(i1, i2)
  21. bite_cube = np.setdiff1d(i1, cube)
  22. assert_array_equal(b2, bite_cube)
  23. assert_array_equal(b3, b5)
  24. bo6 = re1 ^ re2
  25. b6 = bo6["index", i2))
项目:yt    作者:yt-project    | 项目源码 | 文件源码
  1. def test_boolean_slices_overlap():
  2. r"""Test to make sure that boolean objects (slices,overlap)
  3. behave the way we expect.
  4.  
  5. Test overlapping slices.
  6. """
  7. ds = fake_amr_ds()
  8. sl1 = ds.r[:,:,0.25]
  9. sl2 = ds.r[:,0.75,:]
  10. # Get indices of both.
  11. i1 = sl1["index","morton_index"]
  12. i2 = sl2["index","morton_index"]
  13. # Make some booleans
  14. bo1 = sl1 & sl2
  15. bo2 = sl1 - sl2
  16. bo3 = sl1 | sl2
  17. bo4 = ds.union([sl1, sl2])
  18. bo5 = ds.intersection([sl1, sl2])
  19. # Now make sure the indices also behave as we expect.
  20. line = np.intersect1d(i1, i2)
  21. orig = np.setdiff1d(i1, line)
  22. assert_array_equal(b2, orig)
  23. assert_array_equal(b3, b5)
  24. bo6 = sl1 ^ sl2
  25. b6 = bo6["index", i2))
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def union1d(ar1, ar2)))
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def union1d(ar1, ar2)))
项目:sentence-classification    作者:bgmartins    | 项目源码 | 文件源码
  1. def _wmd(self, i, row, X_train):
  2. """Compute the WMD between training sample i and given test row.
  3.  
  4. Assumes that `row` and train samples are sparse BOW vectors summing to 1.
  5. """
  6. union_idx = np.union1d(X_train[i].indices, row.indices) - 1
  7. W_minimal = self.W_embed[union_idx]
  8. W_dist = euclidean_distances(W_minimal)
  9. bow_i = X_train[i, union_idx].A.ravel()
  10. bow_j = row[:, union_idx].A.ravel()
  11. return emd(bow_i, bow_j, W_dist)
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def union1d(ar1, ar2)))
项目:biclustlib    作者:padilha    | 项目源码 | 文件源码
  1. def _match_score(predicted_biclustering, reference_biclustering, bicluster_attr):
  2. k = len(predicted_biclustering.biclusters)
  3. return sum(max(len(np.intersect1d(getattr(bp, bicluster_attr), getattr(bt, bicluster_attr))) /
  4. len(np.union1d(getattr(bp, bicluster_attr)))
  5. for bt in reference_biclustering.biclusters)
  6. for bp in predicted_biclustering.biclusters) / k
项目:biclustlib    作者:padilha    | 项目源码 | 文件源码
  1. def liu_wang_match_score(predicted_biclustering, reference_biclustering):
  2. """Liu & Wang match score.
  3.  
  4. Reference
  5. ---------
  6. Liu,X.,& Wang,L. (2006). Computing the maximum similarity bi-clusters of gene expression data.
  7. Bioinformatics,23(1),50-56.
  8.  
  9. Horta,D.,& Campello,R. J. G. B. (2014). Similarity measures for comparing biclusterings.
  10. IEEE/ACM Transactions on computational Biology and Bioinformatics,11(5),942-954.
  11.  
  12. Parameters
  13. ----------
  14. predicted_biclustering : biclustlib.model.Biclustering
  15. Predicted biclustering solution.
  16.  
  17. reference_biclustering : biclustlib.model.Biclustering
  18. Reference biclustering solution.
  19.  
  20. Returns
  21. -------
  22. lw_match_score : float
  23. Liu and Wang match score between 0.0 and 1.0.
  24. """
  25. check = check_biclusterings(predicted_biclustering, reference_biclustering)
  26.  
  27. if isinstance(check, float):
  28. return check
  29.  
  30. k = len(predicted_biclustering.biclusters)
  31.  
  32. return sum(max((len(np.intersect1d(bp.rows, br.rows)) + len(np.intersect1d(bp.cols, br.cols))) /
  33. (len(np.union1d(bp.rows, br.rows)) + len(np.union1d(bp.cols, br.cols)))
  34. for br in reference_biclustering.biclusters)
  35. for bp in predicted_biclustering.biclusters) / k
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def union1d(ar1, ar2)))
项目:SNPmatch    作者:Gregor-Mendel-Institute    | 项目源码 | 文件源码
  1. def crossGenotyper(args):
  2. ## Get the VCF file (filtered may be) generated by GATK.
  3. ## inputs:
  4. # 1) VCF file
  5. # 2) Parent1 and Parent2
  6. # 3) SNP matrix (hdf5 file)
  7. # 4) Bin length,default as 200Kbp
  8. # 5) Chromosome length
  9. log.info("loading genotype data for parents")
  10. if args[''father''] is not None:
  11. log.info("input files: %s and %s" % (args[''parents''], args[''father'']))
  12. if not os.path.isfile(args[''parents'']) and os.path.isfile(args[''father'']):
  13. die("either of the input files do not exists,please provide VCF/bed file for parent genotype information")
  14. (p1snpCHR, p1snpPOS, p1snpGT, p1snpWEI, p1DPmean) = snpmatch.parseInput(inFile = args[''parents''], logDebug = args[''logDebug''])
  15. (p2snpCHR, p2snpPOS, p2snpGT, p2snpWEI, p2DPmean) = snpmatch.parseInput(inFile = args[''father''], logDebug = args[''logDebug''])
  16. commonCHRs_ids = np.union1d(p1snpCHR, p2snpCHR)
  17. commonSNPsCHR = np.zeros(0, dtype=commonCHRs_ids.dtype)
  18. commonSNPsPOS = np.zeros(0, dtype=int)
  19. snpsP1 = np.zeros(0, dtype=''int8'')
  20. snpsP2 = np.zeros(0, dtype=''int8'')
  21. for i in commonCHRs_ids:
  22. perchrP1inds = np.where(p1snpCHR == i)[0]
  23. perchrP2inds = np.where(p2snpCHR == i)[0]
  24. perchrPositions = np.union1d(p1snpPOS[perchrP1inds], p2snpPOS[perchrP2inds])
  25. commonSNPsCHR = np.append(commonSNPsCHR, np.repeat(i, len(perchrPositions)))
  26. commonSNPsPOS = np.append(commonSNPsPOS, perchrPositions)
  27. perchrsnpsP1 = np.repeat(-1, len(perchrPositions)).astype(''int8'')
  28. perchrsnpsP2 = np.repeat(-1, len(perchrPositions)).astype(''int8'')
  29. perchrsnpsP1_inds = np.where(np.in1d(p1snpPOS[perchrP1inds], perchrPositions))[0]
  30. perchrsnpsP2_inds = np.where(np.in1d(p2snpPOS[perchrP2inds], perchrPositions))[0]
  31. snpsP1 = np.append(snpsP1, snpmatch.parseGT(p1snpGT[perchrsnpsP1_inds]))
  32. snpsP2 = np.append(snpsP2, snpmatch.parseGT(p2snpGT[perchrsnpsP2_inds]))
  33. log.info("done!")
  34. else:
  35. parents = args[''parents'']
  36. ## need to filter the SNPs present in C and M
  37. if not args[''hdf5accFile'']:
  38. snpmatch.die("needed a HDF5 genotype file and not specified")
  39. log.info("loading HDF5 file")
  40. g_acc = genotype.load_hdf5_genotype_data(args[''hdf5accFile''])
  41. ## die if either parents are not in the dataset
  42. #import ipdb; ipdb.set_trace()
  43. try:
  44. indP1 = np.where(g_acc.accessions == parents.split("x")[0])[0][0]
  45. indP2 = np.where(g_acc.accessions == parents.split("x")[1])[0][0]
  46. except:
  47. snpmatch.die("parents are not in the dataset")
  48. snpsP1 = g_acc.snps[:,indP1]
  49. snpsP2 = g_acc.snps[:,indP2]
  50. commonSNPsCHR = np.array(g_acc.chromosomes)
  51. commonSNPsPOS = np.array(g_acc.positions)
  52. log.info("done!")
  53. log.info("running cross genotyper")
  54. crossGenotypeWindows(commonSNPsCHR, commonSNPsPOS, snpsP1, snpsP2, args[''inFile''], args[''binLen''], args[''outFile''], args[''logDebug''])
项目:yt    作者:yt-project    | 项目源码 | 文件源码
  1. def test_boolean_cylinders_overlap():
  2. r"""Test to make sure that boolean objects (cylinders,overlap)
  3. behave the way we expect.
  4.  
  5. Test overlapping cylinders.
  6. """
  7. ds = fake_amr_ds()
  8. cyl1 = ds.disk([0.45]*3, [1, 0.2, 0.2)
  9. cyl2 = ds.disk([0.55]*3, 0.2)
  10. # Get indices of both.
  11. i1 = cyl1["index","morton_index"]
  12. i2 = cyl2["index","morton_index"]
  13. # Make some booleans
  14. bo1 = cyl1 & cyl2
  15. bo2 = cyl1 - cyl2
  16. bo3 = cyl1 | cyl2
  17. bo4 = ds.union([cyl1, cyl2])
  18. bo5 = ds.intersection([cyl1, cyl2])
  19. # Now make sure the indices also behave as we expect.
  20. vlens = np.intersect1d(i1, i2)
  21. bite_disk = np.setdiff1d(i1, vlens)
  22. assert_array_equal(b2, bite_disk)
  23. assert_array_equal(b3, b5)
  24. bo6 = cyl1 ^ cyl2
  25. b6 = bo6["index", i2))
  26. del ds
项目:yt    作者:yt-project    | 项目源码 | 文件源码
  1. def test_boolean_mix_periodicity():
  2. r"""Test that a hybrid boolean region behaves as we expect.
  3.  
  4. This also tests nested logic and that periodicity works.
  5. """
  6. ds = fake_amr_ds()
  7. re = ds.region([0.5]*3, [0.0]*3, [1]*3) # whole thing
  8. sp = ds.sphere([0.95]*3, 0.3) # wraps around
  9. cyl = ds.disk([0.05]*3,1,1], 0.1, 0.4) # wraps around
  10. # Get original indices
  11. rei = re["index","morton_index"]
  12. spi = sp["index","morton_index"]
  13. cyli = cyl["index","morton_index"]
  14. # Make some booleans
  15. # whole Box minux spherical bites at corners
  16. bo1 = re - sp
  17. # sphere plus cylinder
  18. bo2 = sp | cyl
  19. # a jumble,the region minus the sp+cyl
  20. bo3 = re - (sp | cyl)
  21. # Now make sure the indices also behave as we expect.
  22. bo4 = ds.union([re, sp, cyl])
  23. bo5 = ds.intersection([re, cyl])
  24. expect = np.setdiff1d(rei, spi)
  25. ii = bo1["index","morton_index"]
  26. ii.sort()
  27. assert_array_equal(expect, ii)
  28. #
  29. expect = np.union1d(spi, cyli)
  30. ii = bo2["index", cyli)
  31. expect = np.setdiff1d(rei, expect)
  32. ii = bo3["index", ii)
  33. b4 = bo4["index","morton_index"]
  34. b5.sort()
  35. ii = np.union1d(np.union1d(rei, cyli), spi)
  36. ii.sort()
  37. assert_array_equal(ii, b4)
  38. ii = np.intersect1d(np.intersect1d(rei, b5)
  39.  
  40. bo6 = (re ^ sp) ^ cyl
  41. b6 = bo6["index", np.setxor1d(np.setxor1d(rei, spi), cyli))
项目:yt    作者:yt-project    | 项目源码 | 文件源码
  1. def test_boolean_ray_region_overlap():
  2. r"""Test to make sure that boolean objects (ray,region,overlap)
  3. behave the way we expect.
  4.  
  5. Test overlapping ray and region. This also checks that the original
  6. objects don''t change as part of constructing the booleans.
  7. """
  8. ds = fake_amr_ds()
  9. re = ds.Box([0.25]*3, [0.75]*3)
  10. ra = ds.ray([0]*3, [1]*3)
  11. # Get indices of both.
  12. i1 = re["index","morton_index"]
  13. i2 = ra["index","morton_index"]
  14. # Make some booleans
  15. bo1 = re & ra
  16. bo2 = re - ra
  17. bo3 = re | ra
  18. bo4 = ds.union([re, ra])
  19. bo5 = ds.intersection([re, ra])
  20. # Now make sure the indices also behave as we expect.
  21. short_line = np.intersect1d(i1, i2)
  22. cube_minus_line = np.setdiff1d(i1, short_line)
  23. assert_array_equal(b2, cube_minus_line)
  24. assert_array_equal(b3, b5)
  25. bo6 = re ^ ra
  26. b6 = bo6["index", i2))
项目:yt    作者:yt-project    | 项目源码 | 文件源码
  1. def test_boolean_rays_overlap():
  2. r"""Test to make sure that boolean objects (rays,overlap)
  3. behave the way we expect.
  4.  
  5. Test non-overlapping rays.
  6. """
  7. ds = fake_amr_ds()
  8. ra1 = ds.ray([0]*3, [1]*3)
  9. ra2 = ds.ray([0]*3, [0.5]*3)
  10. # Get indices of both.
  11. i1 = ra1["index","morton_index"]
  12. i1.sort()
  13. i2 = ra2["index","morton_index"]
  14. i2.sort()
  15. ii = np.concatenate((i1, i2))
  16. ii.sort()
  17. # Make some booleans
  18. bo1 = ra1 & ra2
  19. bo2 = ra1 - ra2
  20. bo3 = ra1 | ra2
  21. bo4 = ds.union([ra1, ra2])
  22. bo5 = ds.intersection([ra1, ra2])
  23. # Now make sure the indices also behave as we expect.
  24. short_line = np.intersect1d(i1, i2)
  25. short_line_b = np.setdiff1d(i1, i2)
  26. full_line = np.union1d(i1, short_line_b)
  27. assert_array_equal(b3, full_line)
  28. b4 = bo4["index", i1)
  29. assert_array_equal(b3, b5)
  30. bo6 = ra1 ^ ra2
  31. b6 = bo6["index", i2))
项目:yt    作者:yt-project    | 项目源码 | 文件源码
  1. def test_boolean_ray_slice_overlap():
  2. r"""Test to make sure that boolean objects (rays and slices,overlap)
  3. behave the way we expect.
  4.  
  5. Test overlapping rays and slices.
  6. """
  7. ds = fake_amr_ds()
  8. sl = ds.r[:,0.25]
  9. ra = ds.ray([0, 0.25], 0.25])
  10. # Get indices of both.
  11. i1 = sl["index","morton_index"]
  12. i1.sort()
  13. i2 = ra["index","morton_index"]
  14. i1.sort()
  15. ii = np.concatenate((i1, i2))
  16. ii.sort()
  17. # Make some booleans
  18. bo1 = sl & ra
  19. bo2 = sl - ra
  20. bo3 = sl | ra
  21. bo4 = ds.union([sl, ra])
  22. bo5 = ds.intersection([sl, ra])
  23. # Now make sure the indices also behave as we expect.
  24. line = np.intersect1d(i1, i2)
  25. sheet_minus_line = np.setdiff1d(i1, i2)
  26. sheet = np.union1d(i1, sheet_minus_line)
  27. assert_array_equal(b3, sheet)
  28. b4 = bo4["index", b5)
  29. bo6 = sl ^ ra
  30. b6 = bo6["index", i2))
项目:Master-R-CNN    作者:Mark110    | 项目源码 | 文件源码
  1. def sample_rpn_outputs_wrt_gt_Boxes(Boxes, scores, gt_Boxes, is_training=False, only_positive=False):
  2. """sample Boxes for refined output"""
  3. Boxes, batch_inds = sample_rpn_outputs(Boxes, is_training, only_positive)
  4.  
  5. if gt_Boxes.size > 0:
  6. overlaps = cython_bBox.bBox_overlaps(
  7. np.ascontiguousarray(Boxes[:, 0:4], dtype=np.float),
  8. np.ascontiguousarray(gt_Boxes[:, dtype=np.float))
  9. gt_assignment = overlaps.argmax(axis=1) # B
  10. max_overlaps = overlaps[np.arange(Boxes.shape[0]), gt_assignment] # B
  11. fg_inds = np.where(max_overlaps >= cfg.FLAGS.fg_threshold)[0]
  12.  
  13. mask_fg_inds = np.where(max_overlaps >= cfg.FLAGS.mask_threshold)[0]
  14. if mask_fg_inds.size > cfg.FLAGS.masks_per_image:
  15. mask_fg_inds = np.random.choice(mask_fg_inds, size=cfg.FLAGS.masks_per_image, replace=False)
  16.  
  17. if True:
  18. gt_argmax_overlaps = overlaps.argmax(axis=0) # G
  19. fg_inds = np.union1d(gt_argmax_overlaps, fg_inds)
  20.  
  21. fg_rois = int(min(fg_inds.size, cfg.FLAGS.rois_per_image * cfg.FLAGS.fg_roi_fraction))
  22. if fg_inds.size > 0 and fg_rois < fg_inds.size:
  23. fg_inds = np.random.choice(fg_inds, size=fg_rois, replace=False)
  24.  
  25. # Todo: sampling strategy
  26. bg_inds = np.where((max_overlaps < cfg.FLAGS.bg_threshold))[0]
  27. bg_rois = max(min(cfg.FLAGS.rois_per_image - fg_rois, fg_rois * 3), 64)
  28. if bg_inds.size > 0 and bg_rois < bg_inds.size:
  29. bg_inds = np.random.choice(bg_inds, size=bg_rois, replace=False)
  30.  
  31. keep_inds = np.append(fg_inds, bg_inds)
  32. else:
  33. bg_inds = np.arange(Boxes.shape[0])
  34. bg_rois = min(int(cfg.FLAGS.rois_per_image * (1-cfg.FLAGS.fg_roi_fraction)), 64)
  35. if bg_rois < bg_inds.size:
  36. bg_inds = np.random.choice(bg_inds, replace=False)
  37.  
  38. keep_inds = bg_inds
  39. mask_fg_inds = np.arange(0)
  40.  
  41. return Boxes[keep_inds, :], scores[keep_inds], batch_inds[keep_inds],\\
  42. Boxes[mask_fg_inds, scores[mask_fg_inds], batch_inds[mask_fg_inds]
项目:prml    作者:Yevgnen    | 项目源码 | 文件源码
  1. def fit(self, X, T, max_iter=int(1e3), tol=1e-5):
  2. """Use training data ``X`` and ``T`` to fit a SVC models."""
  3. n_samples = X.shape[0]
  4. n_dual_vars = 2 * n_samples
  5. # Compute the Gram matrix of training data
  6. K = self.kernel.inner(X, X)
  7.  
  8. # The equality constraints: H(x) = 0
  9. ones = np.ones(n_samples)
  10. A = np.concatenate((ones, -ones))
  11. cons = ({''type'': ''eq'', ''fun'': lambda x: A.dot(x), ''jac'': lambda x: A})
  12.  
  13. # The inequality constaints: 0 <= G(x) <= C
  14. bnds = [(0, self.C) for i in range(n_dual_vars)]
  15.  
  16. # The target function: (1/2)*x''*Q*x + p''*x
  17. Q = np.array(np.bmat([[K, -K], [-K, K]]))
  18. p = self.eps - A * np.concatenate((T, T))
  19. lagrange = lambda x: (0.5 * x.dot(Q).dot(x) + p.dot(x), Q.dot(x) + p)
  20.  
  21. # Solve the quadratic program
  22. opt_solution = minimize(lagrange,
  23. np.zeros(n_dual_vars),
  24. method=''SLSQP'',
  25. constraints=cons,
  26. bounds=bnds,
  27. tol=tol,
  28. jac=True,
  29. options={''maxiter'': max_iter,
  30. ''disp'': True})
  31.  
  32. self.dual_var = np.array([None, None], dtype=np.object)
  33. self.dual_var[0] = opt_solution.x[:n_samples]
  34. self.dual_var[1] = opt_solution.x[n_samples:]
  35.  
  36. self.sv_indices = np.array([None, dtype=np.object)
  37. self.sv_indices[0] = np.nonzero((1 - np.isclose(self.dual_var[0], 0)))[
  38. 0]
  39. self.sv_indices[1] = np.nonzero((1 - np.isclose(self.dual_var[1], 0)))[
  40. 0]
  41.  
  42. self.union_sv_inices = np.union1d(*self.sv_indices)
  43.  
  44. self.inner_sv_indices = np.array([None, dtype=np.object)
  45. self.inner_sv_indices[0] = np.nonzero(
  46. (1 - np.isclose(self.dual_var[0], 0)) *
  47. (1 - np.isclose(self.dual_var[0], self.C)))[0]
  48. self.inner_sv_indices[1] = np.nonzero(
  49. (1 - np.isclose(self.dual_var[1], 0)) *
  50. (1 - np.isclose(self.dual_var[1], self.C)))[0]
  51.  
  52. return self
项目:asammdf    作者:danielhrisca    | 项目源码 | 文件源码
  1. def select(self, channels, dataframe=False):
  2. """ return the channels listed in *channels* argument
  3.  
  4. Parameters
  5. ----------
  6. channels : list
  7. list of channel names to be filtered
  8. dataframe: bool
  9. return a pandas DataFrame instead of a list of Signals; in this
  10. case the signals will be interpolated using the union of all
  11. timestamps
  12.  
  13. Returns
  14. -------
  15. signals : list
  16. lsit of *Signal* objects based on the input channel list
  17.  
  18. """
  19.  
  20. # group channels by group index
  21. gps = {}
  22. for ch in channels:
  23. if ch in self.channels_db:
  24. for group, index in self.channels_db[ch]:
  25. if group not in gps:
  26. gps[group] = []
  27. gps[group].append(index)
  28. else:
  29. message = (''MDF filter error: ''
  30. ''Channel "{}" not found,it will be ignored'')
  31. warn(message.format(ch))
  32. continue
  33.  
  34. # append filtered channels to new MDF
  35. signals = {}
  36. for group in gps:
  37. grp = self.groups[group]
  38. data = self._load_group_data(grp)
  39. for index in gps[group]:
  40. signal = self.get(group=group, index=index, data=data)
  41. signals[signal.name] = signal
  42.  
  43. signals = [signals[channel] for channel in channels]
  44.  
  45. if dataframe:
  46. times = [s.timestamps for s in signals]
  47. t = reduce(np.union1d, times).flatten().astype(np.float64)
  48. signals = [s.interp(t) for s in signals]
  49. times = None
  50.  
  51. pandas_dict = {''t'': t}
  52. for sig in signals:
  53. pandas_dict[sig.name] = sig.samples
  54.  
  55. signals = DataFrame.from_dict(pandas_dict)
  56.  
  57. return signals
项目:deepgestures_lasagne    作者:nneverova    | 项目源码 | 文件源码
  1. def gesture_overlap_csv(csvpathgt, csvpathpred, seqlenght):
  2. """ Evaluate this sample against the ground truth file """
  3. maxGestures = 20
  4.  
  5. # Get the list of gestures from the ground truth and frame activation
  6. gtGestures = []
  7. binvec_gt = numpy.zeros((maxGestures, seqlenght))
  8. with open(csvpathgt, ''rb'') as csvfilegt:
  9. csvgt = csv.reader(csvfilegt)
  10. for row in csvgt:
  11. binvec_gt[int(row[0])-1, int(row[1])-1:int(row[2])-1] = 1
  12. gtGestures.append(int(row[0]))
  13.  
  14. # Get the list of gestures from prediction and frame activation
  15. predGestures = []
  16. binvec_pred = numpy.zeros((maxGestures, seqlenght))
  17. with open(csvpathpred, ''rb'') as csvfilepred:
  18. csvpred = csv.reader(csvfilepred)
  19. for row in csvpred:
  20. binvec_pred[int(row[0])-1, int(row[1])-1:int(row[2])-1] = 1
  21. predGestures.append(int(row[0]))
  22.  
  23. # Get the list of gestures without repetitions for ground truth and predicton
  24. gtGestures = numpy.unique(gtGestures)
  25. predGestures = numpy.unique(predGestures)
  26.  
  27. bgt = (numpy.argmax(binvec_gt,axis=0)+1) * (numpy.max(binvec_gt,axis=0)>0)
  28. bpred = (numpy.argmax(binvec_pred,axis=0)+1) * (numpy.max(binvec_pred,axis=0)>0)
  29.  
  30. # Find false positives
  31. falsePos=numpy.setdiff1d(gtGestures,numpy.union1d(gtGestures,predGestures)))
  32.  
  33. # Get overlaps for each gesture
  34. overlaps = []
  35. for idx in gtGestures:
  36. intersec = sum(binvec_gt[idx-1] * binvec_pred[idx-1])
  37. aux = binvec_gt[idx-1] + binvec_pred[idx-1]
  38. union = sum(aux > 0)
  39. overlaps.append(intersec/union)
  40.  
  41. # Use real gestures and false positive gestures to calculate the final score
  42. return sum(overlaps)/(len(overlaps)+len(falsePos))
项目:pysynphot    作者:spacetelescope    | 项目源码 | 文件源码
  1. def MergeWaveSets(waveset1, waveset2):
  2. """Return the union of the two wavelength sets.
  3.  
  4. The union is computed using `numpy.union1d`,unless one or
  5. both of them is `None`.
  6.  
  7. The merged result may sometimes contain numbers which are nearly
  8. equal but differ at levels as small as 1E-14. Having values this
  9. close together can cause problems due to effectively duplicate
  10. wavelength values. Therefore,wavelength values having differences
  11. smaller than or equal to ``pysynphot.spectrum.MERGETHRESH``
  12. (defaults to 1E-12) are considered as the same.
  13.  
  14. Parameters
  15. ----------
  16. waveset1,waveset2 : array_like or `None`
  17. Wavelength sets to combine.
  18.  
  19. Returns
  20. -------
  21. MergedWaveSet : array_like or `None`
  22. Merged wavelength set. It is `None` if both inputs are such.
  23.  
  24. """
  25. if waveset1 is None and waveset2 is not None:
  26. MergedWaveSet = waveset2
  27. elif waveset2 is None and waveset1 is not None:
  28. MergedWaveSet = waveset1
  29. elif waveset1 is None and waveset2 is None:
  30. MergedWaveSet = None
  31. else:
  32. MergedWaveSet = N.union1d(waveset1, waveset2)
  33.  
  34. # The merged wave sets may sometimes contain numbers which are nearly
  35. # equal but differ at levels as small as 1e-14. Having values this
  36. # close together can cause problems down the line so here we test
  37. # whether any such small differences are present,with a small
  38. # difference defined as less than MERGETHRESH.
  39. #
  40. # If small differences are present we make a copy of the union''ed array
  41. # with the lower of the close together pairs removed.
  42. delta = MergedWaveSet[1:] - MergedWaveSet[:-1]
  43.  
  44. if not (delta > MERGETHRESH).all():
  45. newlen = len(delta[delta > MERGETHRESH]) + 1
  46. newmerged = N.zeros(newlen, dtype=MergedWaveSet.dtype)
  47. newmerged[:-1] = MergedWaveSet[:-1][delta > MERGETHRESH]
  48. newmerged[-1] = MergedWaveSet[-1]
  49.  
  50. MergedWaveSet = newmerged
  51.  
  52. return MergedWaveSet
项目:spdb    作者:jhuapl-boss    | 项目源码 | 文件源码
  1. def get_ids_in_region(
  2. self, cutout_fcn, resource, resolution, corner, extent,
  3. t_range=[0, version=0):
  4. """
  5. Method to get all the ids within a defined region.
  6.  
  7. Args:
  8. cutout_fcn (function): SpatialDB''s cutout method. Provided for naive search of ids in sub-regions
  9. resource (project.BossResource): Data model info based on the request or target resource
  10. resolution (int): the resolution level
  11. corner ((int,int,int)): xyz location of the corner of the region
  12. extent ((int,int)): xyz extents of the region
  13. t_range (optional[list[int]]): time range,defaults to [0,1]
  14. version (optional[int]): Reserved for future use. Defaults to 0
  15.  
  16. Returns:
  17. (dict): { ''ids'': [''1'',''4'',''8''] }
  18.  
  19. """
  20.  
  21. # Identify sub-region entirely contained by cuboids.
  22. cuboids = Region.get_cuboid_aligned_sub_region(
  23. resolution, extent)
  24.  
  25. # Get all non-cuboid aligned sub-regions.
  26. non_cuboid_list = Region.get_all_partial_sub_regions(
  27. resolution, extent)
  28.  
  29. # Do cutouts on each partial region and build id set.
  30. id_set = np.array([], dtype=''uint64'')
  31. for partial_region in non_cuboid_list:
  32. extent = partial_region.extent
  33. if extent[0] == 0 or extent[1] == 0 or extent[2] == 0:
  34. continue
  35. id_arr = self._get_ids_from_cutout(
  36. cutout_fcn,
  37. partial_region.corner, partial_region.extent,
  38. t_range, version)
  39. # Todo: do a unique first? perf test
  40. id_set = np.union1d(id_set, id_arr)
  41.  
  42. # Get ids from dynamo for sub-region that''s 100% cuboid aligned.
  43. obj_key_list = self._get_object_keys(
  44. resource, cuboids, t_range)
  45. cuboid_ids = self.obj_ind.get_ids_in_cuboids(obj_key_list, version)
  46. cuboid_ids_arr = np.asarray([int(id) for id in cuboid_ids], dtype=''uint64'')
  47.  
  48. # Union ids from cuboid aligned sub-region.
  49. id_set = np.union1d(id_set, cuboid_ids_arr)
  50.  
  51. # Convert ids back to strings for transmission via HTTP.
  52. ids_as_str = [''%d'' % n for n in id_set]
  53.  
  54. return { ''ids'': ids_as_str }
项目:FastMaskRCNN    作者:CharlesShang    | 项目源码 | 文件源码
  1. def sample_rpn_outputs_wrt_gt_Boxes(Boxes, gt_assignment] # B
  2. fg_inds = np.where(max_overlaps >= cfg.FLAGS.fg_threshold)[0]
  3. if _DEBUG and np.argmax(overlaps[fg_inds],axis=1).size < gt_Boxes.size/5.0:
  4. print("gt_size")
  5. print(gt_Boxes)
  6. gt_height = (gt_Boxes[:,2]-gt_Boxes[:,0])
  7. gt_width = (gt_Boxes[:,3]-gt_Boxes[:,1])
  8. gt_dim = np.vstack((gt_height, gt_width))
  9. print(np.transpose(gt_dim))
  10. #print(gt_height)
  11. #print(gt_width)
  12.  
  13. print(''SAMPLE: %d after overlaps by %s'' % (len(fg_inds),cfg.FLAGS.fg_threshold))
  14. print("detected object no.")
  15. print(np.argmax(overlaps[fg_inds],axis=1))
  16. print("total object")
  17. print(gt_Boxes.size/5.0)
  18.  
  19. mask_fg_inds = np.where(max_overlaps >= cfg.FLAGS.mask_threshold)[0]
  20. if mask_fg_inds.size > cfg.FLAGS.masks_per_image:
  21. mask_fg_inds = np.random.choice(mask_fg_inds, 8)#64
  22. if bg_inds.size > 0 and bg_rois < bg_inds.size:
  23. bg_inds = np.random.choice(bg_inds, replace=False)
  24.  
  25. keep_inds = np.append(fg_inds, bg_inds)
  26. #print(gt_Boxes[np.argmax(overlaps[fg_inds],axis=1),4])
  27. else:
  28. bg_inds = np.arange(Boxes.shape[0])
  29. bg_rois = min(int(cfg.FLAGS.rois_per_image * (1-cfg.FLAGS.fg_roi_fraction)), 8)#64
  30. if bg_rois < bg_inds.size:
  31. bg_inds = np.random.choice(bg_inds, batch_inds[mask_fg_inds]
项目:decoding_challenge_cortana_2016_3rd    作者:kingjr    | 项目源码 | 文件源码
  1. def _get_points(self):
  2. # in case only one or no source is enabled
  3. if not (self.src1 and self.src1.enabled):
  4. if (self.src2 and self.src2.enabled):
  5. return self.src2.points
  6. else:
  7. return np.zeros((5, 3))
  8. elif not (self.src2 and self.src2.enabled):
  9. return self.src1.points
  10.  
  11. # Average method
  12. if self.method == ''Average'':
  13. if len(np.union1d(self.src1.use, self.src2.use)) < 5:
  14. error(None, "Need at least one source for each point.",
  15. "Marker Average Error")
  16. return np.zeros((5, 3))
  17.  
  18. pts = (self.src1.points + self.src2.points) / 2.
  19. for i in np.setdiff1d(self.src1.use, self.src2.use):
  20. pts[i] = self.src1.points[i]
  21. for i in np.setdiff1d(self.src2.use, self.src1.use):
  22. pts[i] = self.src2.points[i]
  23.  
  24. return pts
  25.  
  26. # Transform method
  27. idx = np.intersect1d(self.src1.use, self.src2.use, assume_unique=True)
  28. if len(idx) < 3:
  29. error(None, "Need at least three shared points for trans"
  30. "formation.", "Marker Interpolation Error")
  31. return np.zeros((5, 3))
  32.  
  33. src_pts = self.src1.points[idx]
  34. tgt_pts = self.src2.points[idx]
  35. est = fit_matched_points(src_pts, tgt_pts, out=''params'')
  36. rot = np.array(est[:3]) / 2.
  37. tra = np.array(est[3:]) / 2.
  38.  
  39. if len(self.src1.use) == 5:
  40. trans = np.dot(translation(*tra), rotation(*rot))
  41. pts = apply_trans(trans, self.src1.points)
  42. elif len(self.src2.use) == 5:
  43. trans = np.dot(translation(* -tra), rotation(* -rot))
  44. pts = apply_trans(trans, self.src2.points)
  45. else:
  46. trans1 = np.dot(translation(*tra), rotation(*rot))
  47. pts = apply_trans(trans1, self.src1.points)
  48. trans2 = np.dot(translation(* -tra), rotation(* -rot))
  49. for i in np.setdiff1d(self.src2.use, self.src1.use):
  50. pts[i] = apply_trans(trans2, self.src2.points[i])
  51.  
  52. return pts
项目:TFMaskRCNN    作者:hillox    | 项目源码 | 文件源码
  1. def sample_rpn_outputs_wrt_gt_Boxes(Boxes, batch_inds[mask_fg_inds]

Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable

Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable

如何解决Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: ''numpy.ndarray'' object is not callable?

晚安, 尝试打印以下内容时,我在 jupyter 中遇到了 numpy 问题,并且得到了一个 错误: 需要注意的是python版本是3.8.8。 我先用 spyder 测试它,它运行正确,它给了我预期的结果

使用 Spyder:

import numpy as np
    for i in range (5):
        n = np.random.rand ()
    print (n)
Results
0.6604903457995978
0.8236300859753154
0.16067650689842816
0.6967868357083673
0.4231597934445466

现在有了 jupyter

import numpy as np
    for i in range (5):
        n = np.random.rand ()
    print (n)
-------------------------------------------------- ------
TypeError Traceback (most recent call last)
<ipython-input-78-0c6a801b3ea9> in <module>
       2 for i in range (5):
       3 n = np.random.rand ()
---->  4 print (n)

       TypeError: ''numpy.ndarray'' object is not callable

感谢您对我如何在 Jupyter 中解决此问题的帮助。

非常感谢您抽出宝贵时间。

阿特,约翰”

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

numpy.random.random & numpy.ndarray.astype & numpy.arange

numpy.random.random & numpy.ndarray.astype & numpy.arange

今天看到这样一句代码:

xb = np.random.random((nb, d)).astype(''float32'') #创建一个二维随机数矩阵(nb行d列)
xb[:, 0] += np.arange(nb) / 1000. #将矩阵第一列的每个数加上一个值

要理解这两句代码需要理解三个函数

1、生成随机数

numpy.random.random(size=None) 

size为None时,返回float。

size不为None时,返回numpy.ndarray。例如numpy.random.random((1,2)),返回1行2列的numpy数组

 

2、对numpy数组中每一个元素进行类型转换

numpy.ndarray.astype(dtype)

返回numpy.ndarray。例如 numpy.array([1, 2, 2.5]).astype(int),返回numpy数组 [1, 2, 2]

 

3、获取等差数列

numpy.arange([start,]stop,[step,]dtype=None)

功能类似python中自带的range()和numpy中的numpy.linspace

返回numpy数组。例如numpy.arange(3),返回numpy数组[0, 1, 2]

numpy.ravel()/numpy.flatten()/numpy.squeeze()

numpy.ravel()/numpy.flatten()/numpy.squeeze()

numpy.ravel(a, order=''C'')

  Return a flattened array

numpy.chararray.flatten(order=''C'')

  Return a copy of the array collapsed into one dimension

numpy.squeeze(a, axis=None)

  Remove single-dimensional entries from the shape of an array.

 

相同点: 将多维数组 降为 一维数组

不同点:

  ravel() 返回的是视图(view),意味着改变元素的值会影响原始数组元素的值;

  flatten() 返回的是拷贝,意味着改变元素的值不会影响原始数组;

  squeeze()返回的是视图(view),仅仅是将shape中dimension为1的维度去掉;

 

ravel()示例:

 1 import matplotlib.pyplot as plt
 2 import numpy as np
 3 
 4 def log_type(name,arr):
 5     print("数组{}的大小:{}".format(name,arr.size))
 6     print("数组{}的维度:{}".format(name,arr.shape))
 7     print("数组{}的维度:{}".format(name,arr.ndim))
 8     print("数组{}元素的数据类型:{}".format(name,arr.dtype))
 9     #print("数组:{}".format(arr.data))
10     
11 a = np.floor(10*np.random.random((3,4)))
12 print(a)
13 log_type(''a'',a)
14 
15 a1 = a.ravel()
16 print("a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19 
20 print(a)
21 log_type(''a'',a)

 

flatten()示例

 1 import matplotlib.pyplot as plt
 2 import numpy as np
 3 
 4 def log_type(name,arr):
 5     print("数组{}的大小:{}".format(name,arr.size))
 6     print("数组{}的维度:{}".format(name,arr.shape))
 7     print("数组{}的维度:{}".format(name,arr.ndim))
 8     print("数组{}元素的数据类型:{}".format(name,arr.dtype))
 9     #print("数组:{}".format(arr.data))
10     
11 a = np.floor(10*np.random.random((3,4)))
12 print(a)
13 log_type(''a'',a)
14 
15 a1 = a.flatten()
16 print("修改前a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19 print("修改后a1:{}".format(a1))
20 
21 print("a:{}".format(a))
22 log_type(''a'',a)

 

squeeze()示例:

1. 没有single-dimensional entries的情况

 1 import matplotlib.pyplot as plt
 2 import numpy as np
 3 
 4 def log_type(name,arr):
 5     print("数组{}的大小:{}".format(name,arr.size))
 6     print("数组{}的维度:{}".format(name,arr.shape))
 7     print("数组{}的维度:{}".format(name,arr.ndim))
 8     print("数组{}元素的数据类型:{}".format(name,arr.dtype))
 9     #print("数组:{}".format(arr.data))
10     
11 a = np.floor(10*np.random.random((3,4)))
12 print(a)
13 log_type(''a'',a)
14 
15 a1 = a.squeeze()
16 print("修改前a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19 print("修改后a1:{}".format(a1))
20 
21 print("a:{}".format(a))
22 log_type(''a'',a)

从结果中可以看到,当没有single-dimensional entries时,squeeze()返回额数组对象是一个view,而不是copy。

 

2. 有single-dimentional entries 的情况

 1 import matplotlib.pyplot as plt
 2 import numpy as np
 3 
 4 def log_type(name,arr):
 5     print("数组{}的大小:{}".format(name,arr.size))
 6     print("数组{}的维度:{}".format(name,arr.shape))
 7     print("数组{}的维度:{}".format(name,arr.ndim))
 8     print("数组{}元素的数据类型:{}".format(name,arr.dtype))
 9     #print("数组:{}".format(arr.data))
10 
11 a = np.floor(10*np.random.random((1,3,4)))
12 print(a)
13 log_type(''a'',a)
14 
15 a1 = a.squeeze()
16 print("修改前a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19 print("修改后a1:{}".format(a1))
20 
21 print("a:{}".format(a))
22 log_type(''a'',a)

 

Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性

Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性

一、Numpy数组创建

 part 1:np.linspace(起始值,终止值,元素总个数

 

import numpy as np
''''''
numpy中的ndarray数组
''''''

ary = np.array([1, 2, 3, 4, 5])
print(ary)
ary = ary * 10
print(ary)

''''''
ndarray对象的创建
''''''
# 创建二维数组
# np.array([[],[],...])
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(a)

# np.arange(起始值, 结束值, 步长(默认1))
b = np.arange(1, 10, 1)
print(b)

print("-------------np.zeros(数组元素个数, dtype=''数组元素类型'')-----")
# 创建一维数组:
c = np.zeros(10)
print(c, ''; c.dtype:'', c.dtype)

# 创建二维数组:
print(np.zeros ((3,4)))

print("----------np.ones(数组元素个数, dtype=''数组元素类型'')--------")
# 创建一维数组:
d = np.ones(10, dtype=''int64'')
print(d, ''; d.dtype:'', d.dtype)

# 创建三维数组:
print(np.ones( (2,3,4), dtype=np.int32 ))
# 打印维度
print(np.ones( (2,3,4), dtype=np.int32 ).ndim)  # 返回:3(维)

 

结果图:

 

part 2 :np.linspace ( 起始值,终止值,元素总个数)

 

import numpy as np
a = np.arange( 10, 30, 5 )

b = np.arange( 0, 2, 0.3 )

c = np.arange(12).reshape(4,3)

d = np.random.random((2,3))  # 取-1到1之间的随机数,要求设置为诶2行3列的结构

print(a)
print(b)
print(c)
print(d)

print("-----------------")
from numpy import pi
print(np.linspace( 0, 2*pi, 100 ))

print("-------------np.linspace(起始值,终止值,元素总个数)------------------")
print(np.sin(np.linspace( 0, 2*pi, 100 )))

 

结果图:

 

 

 

 

二、Numpy的ndarray对象属性:

数组的结构:array.shape

数组的维度:array.ndim

元素的类型:array.dtype

数组元素的个数:array.size

数组的索引(下标):array[0]

 

''''''
数组的基本属性
''''''
import numpy as np

print("--------------------案例1:------------------------------")
a = np.arange(15).reshape(3, 5)
print(a)
print(a.shape)     # 打印数组结构
print(len(a))      # 打印有多少行
print(a.ndim)     # 打印维度
print(a.dtype)    # 打印a数组内的元素的数据类型
# print(a.dtype.name)
print(a.size)    # 打印数组的总元素个数


print("-------------------案例2:---------------------------")
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a)

# 测试数组的基本属性
print(''a.shape:'', a.shape)
print(''a.size:'', a.size)
print(''len(a):'', len(a))
# a.shape = (6, )  # 此格式可将原数组结构变成1行6列的数据结构
# print(a, ''a.shape:'', a.shape)

# 数组元素的索引
ary = np.arange(1, 28)
ary.shape = (3, 3, 3)   # 创建三维数组
print("ary.shape:",ary.shape,"\n",ary )

print("-----------------")
print(''ary[0]:'', ary[0])
print(''ary[0][0]:'', ary[0][0])
print(''ary[0][0][0]:'', ary[0][0][0])
print(''ary[0,0,0]:'', ary[0, 0, 0])

print("-----------------")


# 遍历三维数组:遍历出数组里的每个元素
for i in range(ary.shape[0]):
    for j in range(ary.shape[1]):
        for k in range(ary.shape[2]):
            print(ary[i, j, k], end='' '')
            

 

结果图:

 

今天关于Python numpy 模块-union1d() 实例源码python中numpy模块的介绍到此结束,谢谢您的阅读,有关Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable、numpy.random.random & numpy.ndarray.astype & numpy.arange、numpy.ravel()/numpy.flatten()/numpy.squeeze()、Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性等更多相关知识的信息可以在本站进行查询。

本文标签: