GVKun编程网logo

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

3

对于想了解Pythonnumpy模块-logical_xor()实例源码的读者,本文将是一篇不可错过的文章,我们将详细介绍python中numpy模块,并且为您提供关于Jupyter中的Numpy在打

对于想了解Python numpy 模块-logical_xor() 实例源码的读者,本文将是一篇不可错过的文章,我们将详细介绍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 模块-logical_xor() 实例源码(python中numpy模块)

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

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

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

项目:DVH    作者:glucee    | 项目源码 | 文件源码
  1. def calculate_plane_histogram(plane, doseplane, dosegridpoints,
  2. maxdose, dd, id, structure, hist):
  3. """Calculate the DVH for the given plane in the structure."""
  4. contours = [[x[0:2] for x in c[''data'']] for c in plane]
  5.  
  6. # If there is no dose for the current plane,go to the next plane
  7. if not len(doseplane):
  8. return (np.arange(0, maxdose), 0)
  9.  
  10. # Create a zero valued bool grid
  11. grid = np.zeros((dd[''rows''], dd[''columns'']), dtype=np.uint8)
  12.  
  13. # Calculate the histogram for each contour in the plane
  14. # and boolean xor to remove holes
  15. for i, contour in enumerate(contours):
  16. m = get_contour_mask(dd, contour)
  17. grid = np.logical_xor(m.astype(np.uint8), grid).astype(np.bool)
  18.  
  19. hist, vol = calculate_contour_dvh(
  20. grid, maxdose, structure)
  21. return (hist, vol)
项目:watermark    作者:lishuaijuly    | 项目源码 | 文件源码
  1. def _gene_signature(self,wm,size,key):
  2. ''''''????????????????????????''''''
  3. wm = cv2.resize(wm,(size,size))
  4. wU,_,wV = np.linalg.svd(np.mat(wm))
  5.  
  6.  
  7. sumU = np.sum(np.array(wU),axis=0)
  8. sumV = np.sum(np.array(wV),axis=0)
  9.  
  10. sumU_mid = np.median(sumU)
  11. sumV_mid = np.median(sumV)
  12.  
  13. sumU=np.array([1 if sumU[i] >sumU_mid else 0 for i in range(len(sumU)) ])
  14. sumV=np.array([1 if sumV[i] >sumV_mid else 0 for i in range(len(sumV)) ])
  15.  
  16. uv_xor=np.logical_xor(sumU,sumV)
  17.  
  18. np.random.seed(key)
  19. seq=np.random.randint(2,size=len(uv_xor))
  20.  
  21. signature = np.logical_xor(uv_xor, seq)
  22.  
  23. sqrts = int(np.sqrt(size))
  24. return np.array(signature,dtype=np.int8).reshape((sqrts,sqrts))
项目:watermark    作者:lishuaijuly    | 项目源码 | 文件源码
  1. def _gene_signature(self,(256,256))
  2. wU, seq)
  3. return np.array(signature,dtype=np.int8)
项目:watermark    作者:lishuaijuly    | 项目源码 | 文件源码
  1. def _gene_signature(self,wU,wV,key):
  2. ''''''????????????????????????''''''
  3. sumU = np.sum(wU,axis=0)
  4. sumV = np.sum(wV,dtype=np.int8)
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_truth_table_logical(self):
  2. # 2,3 and 4 serves as true values
  3. input1 = [0, 0, 3, 2]
  4. input2 = [0, 4, 2]
  5.  
  6. typecodes = (np.typecodes[''AllFloat'']
  7. + np.typecodes[''AllInteger'']
  8. + ''?'') # boolean
  9. for dtype in map(np.dtype, typecodes):
  10. arg1 = np.asarray(input1, dtype=dtype)
  11. arg2 = np.asarray(input2, dtype=dtype)
  12.  
  13. # OR
  14. out = [False, True, True]
  15. for func in (np.logical_or, np.maximum):
  16. assert_equal(func(arg1, arg2).astype(bool), out)
  17. # AND
  18. out = [False, False, True]
  19. for func in (np.logical_and, np.minimum):
  20. assert_equal(func(arg1, out)
  21. # XOR
  22. out = [False, False]
  23. for func in (np.logical_xor, np.not_equal):
  24. assert_equal(func(arg1, out)
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_NotImplemented_not_returned(self):
  2. # See gh-5964 and gh-2091. Some of these functions are not operator
  3. # related and were fixed for other reasons in the past.
  4. binary_funcs = [
  5. np.power, np.add, np.subtract, np.multiply, np.divide,
  6. np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
  7. np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
  8. np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
  9. np.logical_and, np.logical_or, np.logical_xor, np.maximum,
  10. np.minimum, np.mod
  11. ]
  12.  
  13. # These functions still return NotImplemented. Will be fixed in
  14. # future.
  15. # bad = [np.greater,np.greater_equal,np.less,np.less_equal,np.not_equal]
  16.  
  17. a = np.array(''1'')
  18. b = 1
  19. for f in binary_funcs:
  20. assert_raises(TypeError, f, a, b)
项目:dicompyler-core    作者:dicompyler    | 项目源码 | 文件源码
  1. def calculate_plane_histogram(plane,
  2. id, hist):
  3. """Calculate the DVH for the given plane in the structure."""
  4. contours = [[x[0:2] for x in c[''data'']] for c in plane]
  5.  
  6. # Create a zero valued bool grid
  7. grid = np.zeros((dd[''rows''], dtype=np.uint8)
  8.  
  9. # Calculate the dose plane mask for each contour in the plane
  10. # and boolean xor to remove holes
  11. for i, vol = calculate_contour_dvh(grid,
  12. structure)
  13. return (hist, vol)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_truth_table_logical(self):
  2. # 2, out)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_NotImplemented_not_returned(self):
  2. # See gh-5964 and gh-2091. Some of these functions are not operator
  3. # related and were fixed for other reasons in the past.
  4. binary_funcs = [
  5. np.power, b)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_truth_table_logical(self):
  2. # 2, out)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_NotImplemented_not_returned(self):
  2. # See gh-5964 and gh-2091. Some of these functions are not operator
  3. # related and were fixed for other reasons in the past.
  4. binary_funcs = [
  5. np.power, b)
项目:House-Pricing    作者:playing-kaggle    | 项目源码 | 文件源码
  1. def data_cleaning(file_path):
  2. data = pd.read_csv(file_path, index_col=False)
  3. data.drop([''Street'', ''Utilities'', ''Condition2'', ''RoofMatl'', ''Alley'',
  4. ''GarageYrBlt'', ''GarageCond'', ''PoolQC'', ''MiscFeature''],
  5. axis=1, inplace=True)
  6. # marked as NA in BsmtExposure and not NA in other Bsmt Attributes
  7. data.loc[np.logical_xor(data[''BsmtCond''].isnull(), data[''BsmtExposure''].isnull()), ''BsmtExposure''] = ''No''
  8. # LotFrontage''s N/A is assigned zero,will it cause problem?
  9. data.fillna(value={''MasVnrType'': ''None'', ''MasVnrArea'': 0, ''BsmtQual'': ''NoBsmt'', ''BsmtCond'': ''NoBsmt'',
  10. ''BsmtExposure'': ''NoBsmt'', ''BsmtFinType1'': ''NoBsmt'', ''BsmtFinType2'': ''NoBsmt'',
  11. ''Electrical'': ''SBrkr'', ''FireplaceQu'': ''NoFP'', ''GarageType'': ''Noga'',
  12. ''GarageFinish'': ''Noga'', ''GarageQual'': ''Noga'', ''Fence'': ''NoFence'', ''LotFrontage'': 0},
  13. inplace=True)
  14. data.loc[:, ''YrSold''] = 2016 - data.loc[:, ''YrSold'']
  15. data.loc[data.loc[:, ''PoolArea''] != 0, ''PoolArea''] = 1
  16. data.loc[:, ''Porch''] = np.sum(data.loc[:, [''EnclosedPorch'', ''3SsnPorch'', ''ScreenPorch'']], axis=1)
  17. data.drop([''EnclosedPorch'', ''ScreenPorch''], axis=1, inplace=True)
  18. data.replace({''BsmtFullBath'': {3: 2},
  19. ''LotShape'': {''IR3'': ''IR2''}},
  20. inplace=True)
  21. data.columns
  22. # examine columns containing NA value
  23. print(data)
  24. print(data.columns[np.sum(data.isnull(), axis=0) != 0])
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_truth_table_logical(self):
  2. # 2, out)
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_NotImplemented_not_returned(self):
  2. # See gh-5964 and gh-2091. Some of these functions are not operator
  3. # related and were fixed for other reasons in the past.
  4. binary_funcs = [
  5. np.power, b)
项目:Simple-User-Input-Sculpture-Generation    作者:ClaireKincaid    | 项目源码 | 文件源码
  1. def m_menu(self):
  2. """Runs the Mathmatically defined sculpture menu item."""
  3. sin, cos = np.sin, np.cos
  4. res = raw_input("Enter a functional deFinition of a volume (x**2+y**2+z**2 < 1) \\n")
  5. self.user_text = res
  6. self.volume_data = self.bool_ops()
  7. self.create_iso_surface(.7)
  8.  
  9. while True:
  10.  
  11. res = raw_input("Enter another functional deFinition of a volume (x**2+y**2+z**2 < 1) \\n")
  12. self.user_text = res
  13. self.sec_volume_data = self.bool_ops()
  14. self.create_iso_surface(.7, second=True)
  15. res = raw_input("Enter a boolean operation to do with the prevIoUs solid (a = and,o = or,n = not,x = xor):\\n")
  16. if res == "a":
  17. self.sec_volume_data = 0+ np.logical_and(my_sculpture.volume_data, my_sculpture.bool_ops())
  18. elif res == "o":
  19. self.sec_volume_data = 0+ np.logical_or(my_sculpture.volume_data, my_sculpture.bool_ops())
  20. elif res == "n":
  21. self.sec_volume_data = 0+ np.logical_not(my_sculpture.volume_data, my_sculpture.bool_ops())
  22. elif res == "x":
  23. self.sec_volume_data = 0+ np.logical_xor(my_sculpture.volume_data, my_sculpture.bool_ops())
  24. self.create_iso_surface(.7, second=True)
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_truth_table_logical(self):
  2. # 2, out)
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_NotImplemented_not_returned(self):
  2. # See gh-5964 and gh-2091. Some of these functions are not operator
  3. # related and were fixed for other reasons in the past.
  4. binary_funcs = [
  5. np.power, b)
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_truth_table_logical(self):
  2. # 2, out)
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_NotImplemented_not_returned(self):
  2. # See gh-5964 and gh-2091. Some of these functions are not operator
  3. # related and were fixed for other reasons in the past.
  4. binary_funcs = [
  5. np.power, b)
项目:capriqorn    作者:bio-phys    | 项目源码 | 文件源码
  1. def selectShell(ref_coords, coords, R, sw):
  2. """
  3. Return indices of the particles within the spherical shell of
  4. inner radius (R-sw) and outer radius R,ie the shell.
  5.  
  6. Parameters
  7. ----------
  8. ref_coords : array_like (n_atoms,n_dim)
  9. Reference atoms positions
  10. coords : array_like (n_atoms,n_dim)
  11. atoms positions
  12. R : float
  13. distance to any atoms
  14.  
  15. Returns
  16. -------
  17. array
  18. particle indices within shell
  19. """
  20. if R < sw:
  21. raise RuntimeError("selection radius smaller then shell width")
  22. body_query = get_selection(coords, ref_coords, R=R)
  23. core_query = get_selection(coords, R=R - sw)
  24. query = np.logical_xor(body_query, core_query)
  25. return np.where(query)
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def test_truth_table_logical(self):
  2. # 2, out)
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def test_NotImplemented_not_returned(self):
  2. # See gh-5964 and gh-2091. Some of these functions are not operator
  3. # related and were fixed for other reasons in the past.
  4. binary_funcs = [
  5. np.power, b)
项目:monogreedy    作者:jinjunqi    | 项目源码 | 文件源码
  1. def encodeMask(M):
  2. """
  3. Encode binary mask M using run-length encoding.
  4. :param M (bool 2D array) : binary mask to encode
  5. :return: R (object RLE) : run-length encoding of binary mask
  6. """
  7. [h, w] = M.shape
  8. M = M.flatten(order=''F'')
  9. N = len(M)
  10. counts_list = []
  11. pos = 0
  12. # counts
  13. counts_list.append(1)
  14. diffs = np.logical_xor(M[0:N-1], M[1:N])
  15. for diff in diffs:
  16. if diff:
  17. pos +=1
  18. counts_list.append(1)
  19. else:
  20. counts_list[pos] += 1
  21. # if array starts from 1. start with 0 counts for 0
  22. if M[0] == 1:
  23. counts_list = [0] + counts_list
  24. return {''size'': [h, w],
  25. ''counts'': counts_list ,
  26. }
项目:watermark    作者:lishuaijuly    | 项目源码 | 文件源码
  1. def _gene_signature(wm,key):
  2. ''''''
  3. ????????????????????????
  4. wm : ????
  5. size ??????????
  6. key ????????
  7. ''''''
  8. wm = cv2.resize(wm,wV = np.linalg.svd(np.mat(wm))
  9.  
  10. sumU = np.sum(np.array(wU),sqrts))
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_logical_and_or_xor(self):
  2. assert_array_equal(self.t | self.t, self.t)
  3. assert_array_equal(self.f | self.f, self.f)
  4. assert_array_equal(self.t | self.f, self.t)
  5. assert_array_equal(self.f | self.t, self.t)
  6. np.logical_or(self.t, self.t, out=self.o)
  7. assert_array_equal(self.o, self.t)
  8. assert_array_equal(self.t & self.t, self.t)
  9. assert_array_equal(self.f & self.f, self.f)
  10. assert_array_equal(self.t & self.f, self.f)
  11. assert_array_equal(self.f & self.t, self.f)
  12. np.logical_and(self.t, self.t)
  13. assert_array_equal(self.t ^ self.t, self.f)
  14. assert_array_equal(self.f ^ self.f, self.f)
  15. assert_array_equal(self.t ^ self.f, self.t)
  16. assert_array_equal(self.f ^ self.t, self.t)
  17. np.logical_xor(self.t, self.f)
  18.  
  19. assert_array_equal(self.nm & self.t, self.nm)
  20. assert_array_equal(self.im & self.f, False)
  21. assert_array_equal(self.nm & True, self.nm)
  22. assert_array_equal(self.im & False, self.f)
  23. assert_array_equal(self.nm | self.t, self.t)
  24. assert_array_equal(self.im | self.f, self.im)
  25. assert_array_equal(self.nm | True, self.t)
  26. assert_array_equal(self.im | False, self.im)
  27. assert_array_equal(self.nm ^ self.t, self.im)
  28. assert_array_equal(self.im ^ self.f, self.im)
  29. assert_array_equal(self.nm ^ True, self.im)
  30. assert_array_equal(self.im ^ False, self.im)
项目:MIL.pytorch    作者:gujiuxiang    | 项目源码 | 文件源码
  1. def encodeMask(M):
  2. """
  3. Encode binary mask M using run-length encoding.
  4. :param M (bool 2D array) : binary mask to encode
  5. :return: R (object RLE) : run-length encoding of binary mask
  6. """
  7. [h,
  8. }
项目:sverchok    作者:sverchok    | 项目源码 | 文件源码
  1. def xor_(a: Bool = True, b: Bool = False) -> Bool:
  2. return np.logical_xor(a, b)
项目:Auspex    作者:BBN-Q    | 项目源码 | 文件源码
  1. def count_matrices(data, start_state=None, threshold=None, display=False):
  2. num_clusters = 2
  3. if threshold is None:
  4. clust = clusterer(data)
  5. state = clust.fit_predict(data.reshape(-1, 1)).reshape(data.shape)
  6. else:
  7. logger.debug("Cluster data based on threshold = {}".format(threshold))
  8. state = data > threshold
  9.  
  10. init_state = state[:,:,0]
  11. final_state = state[:,1]
  12. switched = np.logical_xor(init_state, final_state)
  13.  
  14. init_state_frac = [np.mean(init_state == ct) for ct in range(num_clusters)]
  15. for ct, fraction in enumerate(init_state_frac):
  16. logger.debug("Initial fraction of state %d: %f" %(ct, fraction))
  17.  
  18. if start_state is not None and start_state in range(num_clusters):
  19. start_stt = start_state
  20. else:
  21. start_stt = np.argmax(init_state_frac)
  22. logger.debug("Start state set to state: {}".format(start_stt))
  23. logger.debug("Switched state is state: {}".format(1-start_stt))
  24.  
  25. # This array contains a 2x2 count_matrix for each coordinate tuple
  26. count_mat = np.zeros((init_state.shape[0], 2, 2))
  27.  
  28. # count_mat = np.zeros((2,2),dtype=np.int)
  29. count_mat[:,0,0] = np.logical_and(init_state == 0, np.logical_not(switched)).sum(axis=-1)
  30. count_mat[:,1] = np.logical_and(init_state == 0, switched).sum(axis=-1)
  31. count_mat[:,1,0] = np.logical_and(init_state == 1,1] = np.logical_and(init_state == 1, np.logical_not(switched)).sum(axis=-1)
  32.  
  33. return count_mat, start_stt
项目:Auspex    作者:BBN-Q    | 项目源码 | 文件源码
  1. def count_matrices_ber(data, display=None):
  2. num_clusters = 2
  3. if threshold is None:
  4. clust = clusterer(data)
  5. state = clust.fit_predict(data.reshape(-1, 1)).reshape((-1,2))
  6. else:
  7. logger.debug("Cluster data based on threshold = {}".format(threshold))
  8. state = data > threshold
  9. state = state.reshape((-1,2))
  10.  
  11. init_state = state[:, fraction))
  12.  
  13. if start_state is not None and start_state in range(num_clusters):
  14. start_stt = start_state
  15. else:
  16. start_stt = np.argmax(init_state_frac)
  17. logger.debug("Start state set to state: {}".format(start_stt))
  18. logger.debug("Switched state is state: {}".format(1-start_stt))
  19.  
  20. # This array contains a 2x2 count_matrix for each coordinate tuple
  21. count_mat = np.zeros((2,dtype=np.int)
  22. count_mat[0, np.logical_not(switched)).sum()
  23. count_mat[0, switched).sum()
  24. count_mat[1, np.logical_not(switched)).sum()
  25.  
  26. return count_mat, start_stt
项目:focal-loss    作者:unsky    | 项目源码 | 文件源码
  1. def encodeMask(M):
  2. """
  3. Encode binary mask M using run-length encoding.
  4. :param M (bool 2D array) : binary mask to encode
  5. :return: R (object RLE) : run-length encoding of binary mask
  6. """
  7. [h, w] = M.shape
  8. M = M.flatten(order=''F'')
  9. N = len(M)
  10. counts_list = []
  11. pos = 0
  12. # counts
  13. counts_list.append(1)
  14. diffs = np.logical_xor(M[0:N - 1], M[1:N])
  15. for diff in diffs:
  16. if diff:
  17. pos += 1
  18. counts_list.append(1)
  19. else:
  20. counts_list[pos] += 1
  21. # if array starts from 1. start with 0 counts for 0
  22. if M[0] == 1:
  23. counts_list = [0] + counts_list
  24. return {''size'': [h,
  25. ''counts'': counts_list,
  26. }
项目:focal-loss    作者:unsky    | 项目源码 | 文件源码
  1. def encodeMask(M):
  2. """
  3. Encode binary mask M using run-length encoding.
  4. :param M (bool 2D array) : binary mask to encode
  5. :return: R (object RLE) : run-length encoding of binary mask
  6. """
  7. [h,
  8. }
项目:Deformable-ConvNets    作者:msracver    | 项目源码 | 文件源码
  1. def encodeMask(M):
  2. """
  3. Encode binary mask M using run-length encoding.
  4. :param M (bool 2D array) : binary mask to encode
  5. :return: R (object RLE) : run-length encoding of binary mask
  6. """
  7. [h,
  8. }
项目:Deformable-ConvNets    作者:msracver    | 项目源码 | 文件源码
  1. def encodeMask(M):
  2. """
  3. Encode binary mask M using run-length encoding.
  4. :param M (bool 2D array) : binary mask to encode
  5. :return: R (object RLE) : run-length encoding of binary mask
  6. """
  7. [h,
  8. }
项目:TF-phrasecut-public    作者:chenxi116    | 项目源码 | 文件源码
  1. def compute_accuracy(scores, labels):
  2. is_pos = (labels != 0)
  3. is_neg = np.logical_not(is_pos)
  4. num_pos = np.sum(is_pos)
  5. num_neg = np.sum(is_neg)
  6. num_all = num_pos + num_neg
  7.  
  8. is_correct = np.logical_xor(scores < 0, is_pos)
  9. accuracy_all = np.sum(is_correct) / num_all
  10. accuracy_pos = np.sum(is_correct[is_pos]) / (num_pos + 1)
  11. accuracy_neg = np.sum(is_correct[is_neg]) / num_neg
  12. return accuracy_all, accuracy_pos, accuracy_neg
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_logical_and_or_xor(self):
  2. assert_array_equal(self.t | self.t, self.im)
项目:nupic-example-code    作者:htm-community    | 项目源码 | 文件源码
  1. def calcAnomaly(self, actual, predicted):
  2. """
  3. Calculates the anomaly of two SDRs
  4.  
  5. Uses the equation presented on the wiki:
  6. https://github.com/numenta/nupic/wiki/Anomaly-score-Memo
  7.  
  8. To put this in terms of the temporal pooler:
  9. A is the actual input array at a given timestep
  10. P is the predicted array that was produced from the prevIoUs timestep(s)
  11. [A - (A && P)] / [A]
  12. Rephrasing as questions:
  13. What bits are on in A that are not on in P?
  14. How does that compare to total on bits in A?
  15.  
  16. Outputs 0 is there''s no difference between P and A.
  17. Outputs 1 if P and A are totally distinct.
  18.  
  19. Not a perfect metric - it doesn''t credit proximity
  20. Next step: combine with a metric for a spatial pooler
  21. """
  22. combined = numpy.logical_and(actual, predicted)
  23. delta = numpy.logical_xor(actual,combined)
  24. delta_score = sum(delta)
  25. actual_score = float(sum(actual))
  26. return delta_score / actual_score
项目:gridded    作者:NOAA-ORR-ERD    | 项目源码 | 文件源码
  1. def points_in_polys(points, polys, polyy=None):
  2. """
  3. :param points: Numpy array of Nx2 points
  4. :param polys: Numpy array of N polygons of degree M represented
  5. by Mx2 points (NxMx2) for each point,see if respective poly
  6. contains it. Returns array of True/False
  7. """
  8.  
  9. result = np.zeros((points.shape[0],), dtype=bool)
  10. if isinstance(points, np.ma.masked_array):
  11. points = points.data
  12. if isinstance(polys, np.ma.masked_array):
  13. polys = polys.data
  14. if polyy is not None and isinstance(polyy, np.ma.masked_array):
  15. polyy = polyy.data
  16. pointsx = points[:, 0]
  17. pointsy = points[:, 1]
  18. v1x = v1y = v2x = v2y = -1
  19. for i in range(0, polys.shape[1]):
  20. if polyy is not None:
  21. v1x = polys[:, i - 1]
  22. v1y = polyy[:, i - 1]
  23. v2x = polys[:, i]
  24. v2y = polyy[:, i]
  25. else:
  26. v1x = polys[:, i - 1, 0]
  27. v1y = polys[:, 1]
  28. v2x = polys[:, i, 0]
  29. v2y = polys[:, 1]
  30. test1 = (v2y > pointsy) != (v1y > pointsy)
  31. test2 = np.zeros(points.shape[0], dtype=bool)
  32. m = np.where(test1 == 1)[0]
  33. test2[m] = pointsx[m] < \\
  34. (v1x[m] - v2x[m]) * (pointsy[m] - v2y[m]) / \\
  35. (v1y[m] - v2y[m]) + v2x[m]
  36. np.logical_and(test1, test2, test1)
  37. np.logical_xor(result, test1, result)
  38. return result
项目:Thrifty    作者:swkrueger    | 项目源码 | 文件源码
  1. def gold(bits, idx):
  2. """Generate the idx-th Gold code of length 2^bits - 1.
  3.  
  4. Parameters
  5. ----------
  6. bits : int
  7. Length of LFSR. The length of the gold code will be
  8. :math:`2^{\\\\mathtt{bits}} - 1`.
  9. idx : int
  10. Index of the code to generate within the set of gold codes,where
  11. :math:`0 \\\\le \\\\mathtt{idx} < 2^{\\\\mathtt{bits}} + 1`.
  12. """
  13. bits = int(bits)
  14. if bits not in TAPS:
  15. raise ValueError(''Preferred pairs for %d bits unkNown.'' % bits)
  16. seed = np.ones(bits, dtype=bool)
  17.  
  18. seq1 = lfsr(TAPS[bits][0], seed)
  19. seq2 = lfsr(TAPS[bits][1], seed)
  20.  
  21. if idx == 0:
  22. return seq1
  23. elif idx == 1:
  24. return seq2
  25. else:
  26. return np.logical_xor(seq1, np.roll(seq2, -idx + 2))
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_logical_and_or_xor(self):
  2. assert_array_equal(self.t | self.t, self.im)
项目:House-Pricing    作者:playing-kaggle    | 项目源码 | 文件源码
  1. def read_train(file_path):
  2. data = pd.read_csv(file_path, index_col=False)
  3.  
  4. data.drop([''Street'', inplace=True)
  5.  
  6. # marked as NA in BsmtExposure and not NA in other Bsmt Attributes
  7. data.loc[np.logical_xor(data[''BsmtCond''].isnull(), ''BsmtExposure''] = ''No''
  8.  
  9. # LotFrontage''s N/A is assigned zero,
  10. inplace=True)
  11.  
  12. data.loc[:, ''YrSold'']
  13.  
  14. data.loc[data.loc[:, ''PoolArea''] = 1
  15.  
  16. data.loc[:, inplace=True)
  17.  
  18. data.replace({''BsmtFullBath'': {3: 2}, ''LotShape'': {''IR3'': ''IR2''}}, inplace=True)
  19.  
  20. return data
项目:House-Pricing    作者:playing-kaggle    | 项目源码 | 文件源码
  1. def data_cleaning(file_path):
  2. data = pd.read_csv(file_path, ''YrSold'']
  3. data.loc[:, ''YearBuilt''] = 2016 - data.loc[:, ''YearBuilt'']
  4. data.loc[:, ''YearRemodAdd''] = 2016 - data.loc[:, ''YearRemodAdd'']
  5. data.loc[data.loc[:, ''PoolArea''] = ''Y''
  6. data.loc[data.loc[:, ''PoolArea''] == 0, ''PoolArea''] = ''N''
  7. data.loc[:,
  8. inplace=True)
  9. return data
  10. # data.columns
  11. # examine columns containing NA value
  12. # print(data)
  13. # print(data.columns[np.sum(data.isnull(),axis=0) != 0])
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_logical_and_or_xor(self):
  2. assert_array_equal(self.t | self.t, self.im)
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_logical_and_or_xor(self):
  2. assert_array_equal(self.t | self.t, self.im)
项目:python-machine-learning-book    作者:jeremyn    | 项目源码 | 文件源码
  1. def plot_xor():
  2. np.random.seed(0)
  3. X_xor = np.random.randn(200, 2)
  4. y_xor = np.logical_xor(X_xor[:, 0] > 0, X_xor[:, 1] > 0)
  5. y_xor = np.where(y_xor, 1, -1)
  6.  
  7. svm = SVC(kernel=''rbf'', random_state=0, gamma=0.1, C=10.0)
  8. svm.fit(X_xor, y_xor)
  9. plot_decision_regions(X_xor, y_xor, classifier=svm)
  10.  
  11. plt.legend(loc=''upper left'')
  12. plt.show()
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_logical_and_or_xor(self):
  2. assert_array_equal(self.t | self.t, self.im)
项目:crowddynamics    作者:jaantollander    | 项目源码 | 文件源码
  1. def shortest_path(mgrid, domain, targets, obstacles, buffer_radius):
  2. """Vector field guiding towards targets."""
  3. obstacles_buffered = obstacles.buffer(buffer_radius).intersection(domain)
  4.  
  5. dmap_targets = distance_map(mgrid, obstacles_buffered)
  6. dir_map_targets = direction_map(dmap_targets)
  7.  
  8. # Fill values between buffered region and obstacles
  9. mask = np.full(mgrid.shape, dtype=np.bool_)
  10. draw_geom(obstacles, mask, mgrid.indicer, True)
  11. fill_missing(np.logical_xor(mask, dir_map_targets[0].mask),
  12. *mgrid.values, *dir_map_targets)
  13.  
  14. return dir_map_targets, dmap_targets
项目:tensorflow-annex    作者:rwightman    | 项目源码 | 文件源码
  1. def from_xyxy(cls, xmin, ymin, xmax, ymax, correct_flipped=False):
  2. x_flipped = True if xmax >= 0 and xmin > xmax else False
  3. y_flipped = True if ymax >= 0 and ymin > ymax else False
  4. if correct_flipped:
  5. if np.logical_xor(x_flipped, y_flipped):
  6. assert False, "Invalid bounding Box"
  7. elif x_flipped and y_flipped:
  8. xmin, xmax = xmax, xmin
  9. ymin, ymax = ymax, ymin
  10. return cls(xmin, xmax - xmin + 1, ymax - ymin + 1)
项目:nnlib    作者:inejc    | 项目源码 | 文件源码
  1. def xor_data(num_examples, noise=None):
  2. X = randn(num_examples, 2)
  3.  
  4. if noise is None:
  5. X_ = X
  6. else:
  7. X_ = X + noise * randn(num_examples, 2)
  8.  
  9. y = np.logical_xor(X_[:, X_[:, 1] > 0).astype(int)
  10. return X, y
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def test_logical_and_or_xor(self):
  2. assert_array_equal(self.t | self.t, self.im)
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_half_ufuncs(self):
  2. """Test the varIoUs ufuncs"""
  3.  
  4. a = np.array([0, 2], dtype=float16)
  5. b = np.array([-2, 5, 3], dtype=float16)
  6. c = np.array([0, -1, -np.inf, np.nan, 6], dtype=float16)
  7.  
  8. assert_equal(np.add(a, b), [-2, 6, 8, 5])
  9. assert_equal(np.subtract(a, [2, -4, -1])
  10. assert_equal(np.multiply(a, [0, 16, 6])
  11. assert_equal(np.divide(a, 0.199951171875, 0.66650390625])
  12.  
  13. assert_equal(np.equal(a, [False, False])
  14. assert_equal(np.not_equal(a, [True, True])
  15. assert_equal(np.less(a, True])
  16. assert_equal(np.less_equal(a, True])
  17. assert_equal(np.greater(a, False])
  18. assert_equal(np.greater_equal(a, False])
  19. assert_equal(np.logical_and(a, True])
  20. assert_equal(np.logical_or(a, True])
  21. assert_equal(np.logical_xor(a, False])
  22. assert_equal(np.logical_not(a), False])
  23.  
  24. assert_equal(np.isnan(c), False])
  25. assert_equal(np.isinf(c), False])
  26. assert_equal(np.isfinite(c), True])
  27. assert_equal(np.signbit(b), False])
  28.  
  29. assert_equal(np.copysign(b, a), 3])
  30.  
  31. assert_equal(np.maximum(a, 3])
  32. x = np.maximum(b, c)
  33. assert_(np.isnan(x[3]))
  34. x[3] = 0
  35. assert_equal(x, 6])
  36. assert_equal(np.minimum(a, 2])
  37. x = np.minimum(b, 3])
  38. assert_equal(np.fmax(a, 3])
  39. assert_equal(np.fmax(b, c), 6])
  40. assert_equal(np.fmin(a, 2])
  41. assert_equal(np.fmin(b, 3])
  42.  
  43. assert_equal(np.floor_divide(a, 0])
  44. assert_equal(np.remainder(a, 2])
  45. assert_equal(np.square(b), [4, 25, 9])
  46. assert_equal(np.reciprocal(b), [-0.5, 0.25, 0.333251953125])
  47. assert_equal(np.ones_like(b), [1, 1])
  48. assert_equal(np.conjugate(b), b)
  49. assert_equal(np.absolute(b), 3])
  50. assert_equal(np.negative(b), -5, -3])
  51. assert_equal(np.sign(b), [-1, 1])
  52. assert_equal(np.modf(b), ([0, 0], b))
  53. assert_equal(np.frexp(b), ([-0.5, 0.625, 0.5, 0.75], 2]))
  54. assert_equal(np.ldexp(b, 2]), 10, 64, 12])

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 模块-logical_xor() 实例源码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 ()、数组基本属性等相关内容,可以在本站寻找。

本文标签: