GVKun编程网logo

Python numpy 模块-apply_along_axis() 实例源码(numpy.apply_along_axis)

1

想了解Pythonnumpy模块-apply_along_axis()实例源码的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于numpy.apply_along_axis的相关问题,此外,我

想了解Python numpy 模块-apply_along_axis() 实例源码的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于numpy.apply_along_axis的相关问题,此外,我们还将为您介绍关于Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable、Numpy.apply_along_axis 在应用具有 if else 条件的函数时意外工作、numpy.random.random & numpy.ndarray.astype & numpy.arange、numpy.ravel()/numpy.flatten()/numpy.squeeze()的新知识。

本文目录一览:

Python numpy 模块-apply_along_axis() 实例源码(numpy.apply_along_axis)

Python numpy 模块-apply_along_axis() 实例源码(numpy.apply_along_axis)

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

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

项目:mixedvines    作者:asnelt    | 项目源码 | 文件源码
  1. def _logcdf(self, samples):
  2. lower = np.full(2, -np.inf)
  3. upper = norm.ppf(samples)
  4. limit_flags = np.zeros(2)
  5. if upper.shape[0] > 0:
  6.  
  7. def func1d(upper1d):
  8. ''''''
  9. Calculates the multivariate normal cumulative distribution
  10. function of a single sample.
  11. ''''''
  12. return mvn.mvndst(lower, upper1d, limit_flags, self.theta)[1]
  13.  
  14. vals = np.apply_along_axis(func1d, -1, upper)
  15. else:
  16. vals = np.empty((0, ))
  17. old_settings = np.seterr(divide=''ignore'')
  18. vals = np.log(vals)
  19. np.seterr(**old_settings)
  20. vals[np.any(samples == 0.0, axis=1)] = -np.inf
  21. vals[samples[:, 0] == 1.0] = np.log(samples[samples[:, 0] == 1.0, 1])
  22. vals[samples[:, 1] == 1.0] = np.log(samples[samples[:, 1] == 1.0, 0])
  23. return vals
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def _nanmedian(a, axis=None, out=None, overwrite_input=False):
  2. """
  3. Private function that doesn''t support extended axis or keepdims.
  4. These methods are extended to this function using _ureduce
  5. See nanmedian for parameter usage
  6.  
  7. """
  8. if axis is None or a.ndim == 1:
  9. part = a.ravel()
  10. if out is None:
  11. return _nanmedian1d(part, overwrite_input)
  12. else:
  13. out[...] = _nanmedian1d(part, overwrite_input)
  14. return out
  15. else:
  16. # for small medians use sort + indexing which is still faster than
  17. # apply_along_axis
  18. if a.shape[axis] < 400:
  19. return _nanmedian_small(a, axis, out, overwrite_input)
  20. result = np.apply_along_axis(_nanmedian1d, a, overwrite_input)
  21. if out is not None:
  22. out[...] = result
  23. return result
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def _nanpercentile(a, q, overwrite_input=False,
  2. interpolation=''linear'', keepdims=False):
  3. """
  4. Private function that doesn''t support extended axis or keepdims.
  5. These methods are extended to this function using _ureduce
  6. See nanpercentile for parameter usage
  7.  
  8. """
  9. if axis is None:
  10. part = a.ravel()
  11. result = _nanpercentile1d(part, overwrite_input, interpolation)
  12. else:
  13. result = np.apply_along_axis(_nanpercentile1d,
  14. overwrite_input, interpolation)
  15. # apply_along_axis fills in collapsed axis with results.
  16. # Move that axis to the beginning to match percentile''s
  17. # convention.
  18. if q.ndim != 0:
  19. result = np.rollaxis(result, axis)
  20.  
  21. if out is not None:
  22. out[...] = result
  23. return result
项目:HTM_experiments    作者:ctrl-z-9000-times    | 项目源码 | 文件源码
  1. def _fix_alpha_channel(self):
  2. # This is a fix for a bug where the Alpha channel was dropped.
  3. colors3to4 = [(c[:3], c[3]) for c in self.names.keys()]
  4. colors3to4 = dict(colors3to4)
  5. assert(len(colors3to4) == len(self.names)) # Dropped alpha channel causes colors to collide :(
  6. for lbl in self.labels:
  7. if lbl is None:
  8. continue # No label file created yet.
  9. img = Image.open(lbl)
  10. size = img.size
  11. img = np.array(img)
  12. if img.shape[2] == 4:
  13. continue # Image has alpha channel,good.
  14. elif img.shape[2] == 3:
  15. # Lookup each (partial) color and find what its alpha should be.
  16. alpha = np.apply_along_axis(lambda c: colors3to4[tuple(c)], 2, img)
  17. data = np.dstack([img, np.array(alpha, dtype=np.uint8)])
  18. new_img = Image.frombuffer("RGBA", size, data, "raw", "RGBA", 0, 1)
  19. new_img.save(lbl)
  20. print("FIXED", lbl)
项目:rl_algorithms    作者:DanielTakeshi    | 项目源码 | 文件源码
  1. def plot_cost_to_go_mountain_car(env, estimator, num_tiles=20):
  2. x = np.linspace(env.observation_space.low[0], env.observation_space.high[0], num=num_tiles)
  3. y = np.linspace(env.observation_space.low[1], env.observation_space.high[1], num=num_tiles)
  4. X, Y = np.meshgrid(x, y)
  5. Z = np.apply_along_axis(lambda _: -np.max(estimator.predict(_)), np.dstack([X, Y]))
  6.  
  7. fig = plt.figure(figsize=(10, 5))
  8. ax = fig.add_subplot(111, projection=''3d'')
  9. surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1,
  10. cmap=matplotlib.cm.coolwarm, vmin=-1.0, vmax=1.0)
  11. ax.set_xlabel(''Position'')
  12. ax.set_ylabel(''VeLocity'')
  13. ax.set_zlabel(''Value'')
  14. ax.set_title("Mountain \\"Cost To Go\\" Function")
  15. fig.colorbar(surf)
  16. plt.show()
项目:Boundary-Trees    作者:jayricco    | 项目源码 | 文件源码
  1. def boundary_tree_to_image(boundary_tree, image_mesh):
  2. arr = array(''B'')
  3. np.apply_along_axis(lambda c: arr.extend(boundary_tree.query(c)), 1, image_mesh)
  4. return Image.frombytes("RGB", arr)
项目:alp    作者:davefernig    | 项目源码 | 文件源码
  1. def __query_by_committee(self, clf, X_unlabeled):
  2. num_classes = len(clf[0].classes_)
  3. C = len(clf)
  4. preds = []
  5.  
  6. if self.strategy == ''Vote_entropy'':
  7. for model in clf:
  8. y_out = map(int, model.predict(X_unlabeled))
  9. preds.append(np.eye(num_classes)[y_out])
  10.  
  11. Votes = np.apply_along_axis(np.sum, np.stack(preds)) / C
  12. return np.apply_along_axis(entropy, Votes)
  13.  
  14. elif self.strategy == ''average_kl_divergence'':
  15. for model in clf:
  16. preds.append(model.predict_proba(X_unlabeled))
  17.  
  18. consensus = np.mean(np.stack(preds), axis=0)
  19. divergence = []
  20. for y_out in preds:
  21. divergence.append(entropy(consensus.T, y_out.T))
  22.  
  23. return np.apply_along_axis(np.mean, np.stack(divergence))
项目:AutoML-Challenge    作者:postech-mlg-exbrain    | 项目源码 | 文件源码
  1. def estimate_1hot_cost(X, is_categorical):
  2. """
  3. Calculate the "memory expansion" after applying one-hot encoding.
  4.  
  5. :param X: array-like
  6. The input data array
  7. :param is_categorical: boolean array-like
  8. Array of vector form that indicates
  9. whether each features of X is categorical
  10.  
  11. :return: int
  12. Calculated memory size in byte scale (expansion)
  13. """
  14. n_columns = 0
  15. count_labels_v = lambda v: np.sum(np.isfinite(np.unique(v))) - 1
  16. n_labels = np.apply_along_axis(count_labels_v, X)
  17. n_columns += np.sum(n_labels[is_categorical])
  18.  
  19. estimated_memory = n_columns * X.shape[0] * X.dtype.itemsize
  20. return estimated_memory
项目:real_time_face_detection    作者:SNowapril    | 项目源码 | 文件源码
  1. def load_dataset():
  2. if(not os.path.exists("./dataset/training.csv")):
  3. print("dataset does not exist")
  4. raise Exception
  5.  
  6. #load dataset
  7. labeled_image = pd.read_csv("./dataset/training.csv")
  8.  
  9. #preprocessing dataframe
  10. image = np.array(labeled_image["Image"].values).reshape(-1,1)
  11. image = np.apply_along_axis(lambda img: (img[0].split()),1,image)
  12. image = image.astype(np.int32) #because train_img elements are string before preprocessing
  13. image = image.reshape(-1,96*96) # data 96 * 96 size image
  14.  
  15. label = labeled_image.values[:,:-1]
  16. label = label.astype(np.float32)
  17.  
  18. #nan value to mean value
  19. col_mean = np.nanmean(label, axis=0)
  20. indices = np.where(np.isnan(label))
  21. label[indices] = np.take(col_mean, indices[1])
  22.  
  23. return image, label
项目:chxanalys    作者:yugangzhang    | 项目源码 | 文件源码
  1. def get_his_std_qi( data_pixel_qi, max_cts=None):
  2. ''''''
  3. YG. Dev 16,2016
  4. Calculate the photon histogram for one q by giving
  5. Parameters:
  6. data_pixel_qi: one-D array,for the photon counts
  7. max_cts: for bin max,bin will be [0,1,2,...,max_cts]
  8. Return:
  9. bins
  10. his
  11. std
  12. ''''''
  13. if max_cts is None:
  14. max_cts = np.max( data_pixel_qi ) +1
  15. bins = np.arange(max_cts)
  16. dqn, dqm = data_pixel_qi.shape
  17. #get histogram here
  18. H = np.apply_along_axis(np.bincount, np.int_(data_pixel_qi), minlength= max_cts )/dqm
  19. #do average for different frame
  20. his = np.average( H, axis=0)
  21. std = np.std( H, axis=0 )
  22. #cal average photon counts
  23. kmean= np.average(data_pixel_qi )
  24. return bins, his, std, kmean
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def _nanmedian(a, overwrite_input)
  2. if out is not None:
  3. out[...] = result
  4. return result
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def _nanpercentile(a, axis)
  2.  
  3. if out is not None:
  4. out[...] = result
  5. return result
项目:cebl    作者:idfah    | 项目源码 | 文件源码
  1. def punion(probs, axis=None):
  2. """Find the unions of given list of probabilities assuming indepdendence.
  3.  
  4. Args:
  5. probs: Matrix-like probabilities to union.
  6.  
  7. axis: Axis along which union will be performed.
  8.  
  9. Returns:
  10. Matrix of probability unions.
  11. """
  12. def punion1d(probs):
  13. """Union for 1d array.
  14. """
  15. finalp = 0.0
  16. for p in probs:
  17. finalp += p*(1.0-finalp)
  18. return finalp
  19.  
  20. probs = np.asarray(probs)
  21.  
  22. if axis is None:
  23. return punion1d(probs.reshape((-1,)))
  24. else:
  25. return np.apply_along_axis(func1d=punion1d, axis=axis, arr=probs)
项目:Titanic    作者:GeoffBreemer    | 项目源码 | 文件源码
  1. def addFamily(X):
  2. # Family size: index 8
  3. newCol = np.array(X[:, 1] + X[:, 2], np.newaxis)
  4. newCol = newCol.reshape((len(newCol), 1))
  5. X = np.hstack( (X,newCol) )
  6.  
  7. # Family category: index 9
  8. def determineFamilyCat(row):
  9. # print(''row shape = {},cont = {}''.format(row.shape,row))
  10. if row[8] == 1:
  11. return 0 # singles
  12. elif 2<=row[8]<=4:
  13. return 1 # normal size
  14. else:
  15. return 2 # large size
  16.  
  17. newCol = np.apply_along_axis(determineFamilyCat, X)
  18. newCol = newCol.reshape((len(newCol), 1))
  19. X = np.hstack((X,newCol))
  20.  
  21. return X
  22.  
  23.  
  24. # Not used
项目:Halite    作者:shummie    | 项目源码 | 文件源码
  1. def update_recover_maps(self):
  2. max_distance = min(self.width // 2, self.height // 2, 15)
  3. #self.recover_map = np.zeros((max_distance + 1,self.width,self.height))
  4. #self.recover_map[0] = np.divide(self.strength_map,self.production_map_01) * (self.is_neutral_map - self.combat_zone_map)
  5.  
  6. self.prod_over_str_map = np.zeros((max_distance + 1, self.width, self.height))
  7. #self.prod_over_str_map[0] = np.divide(self.production_map,self.strength_map_01) * (self.is_neutral_map - self.combat_zone_map)
  8. new_str_map = np.copy(self.strength_map)
  9. new_str_map[new_str_map == 0] = 2
  10. #self.prod_over_str_map[0] = np.divide(self.production_map,self.strength_map_01) * (self.is_neutral_map - self.combat_zone_map)
  11. self.prod_over_str_map[0] = np.divide(self.production_map, new_str_map) * (self.is_neutral_map - self.combat_zone_map)
  12. #self.recover_map[0] = 1 / np.maximum(self.prod_over_str_map[0],0.01)
  13.  
  14. for distance in range(1, max_distance + 1):
  15. self.prod_over_str_map[distance] = spread_n(self.prod_over_str_map[distance - 1], 1)
  16. self.prod_over_str_map[distance][self.prod_over_str_map[distance-1] == 0] = 0
  17. self.prod_over_str_map[distance] = self.prod_over_str_map[distance] / 5
  18. #self.recover_map[distance] = 1 / np.maximum(self.prod_over_str_map[distance],0.01)
  19.  
  20. self.prod_over_str_max_map = np.apply_along_axis(np.max, self.prod_over_str_map)
  21. #self.recover_max_map = 1 / np.maximum(self.prod_over_str_max_map,0.01)
  22. self.prod_over_str_avg_map = np.apply_along_axis(np.mean, self.prod_over_str_map)
  23. #self.recover_avg_map = 1 / np.maximum(self.prod_over_str_avg_map,0.01)
  24. self.prod_over_str_wtd_map = (self.prod_over_str_max_map + self.prod_over_str_avg_map) / 2
  25. self.recover_wtd_map = 1 / np.maximum(self.prod_over_str_wtd_map, 0.01)
项目:Halite    作者:shummie    | 项目源码 | 文件源码
  1. def update_recover_maps(self):
  2. max_distance = min(self.width // 2, 0.01)
项目:Halite    作者:shummie    | 项目源码 | 文件源码
  1. def update_recover_maps(self):
  2. max_distance = min(self.width // 2, 0.01)
项目:Halite    作者:shummie    | 项目源码 | 文件源码
  1. def update_recover_maps(self):
  2. max_distance = self.width // 2
  3. self.recover_map = np.zeros((max_distance + 1, self.height))
  4. self.recover_map[0] = np.divide(self.strength_map, self.production_map_01) * (self.is_neutral_map - self.combat_zone_map)
  5.  
  6. self.prod_over_str_map = np.zeros((max_distance + 1, new_str_map) * (self.is_neutral_map - self.combat_zone_map)
  7. self.recover_map[0] = 1 / np.maximum(self.prod_over_str_map[0], 0.01)
  8.  
  9. for distance in range(1, 1)
  10. self.prod_over_str_map[distance][self.prod_over_str_map[distance-1] == 0] = 0
  11. self.prod_over_str_map[distance] = self.prod_over_str_map[distance] / 5
  12. self.recover_map[distance] = 1 / np.maximum(self.prod_over_str_map[distance], 0.01)
  13.  
  14. self.prod_over_str_max_map = np.apply_along_axis(np.max, self.prod_over_str_map)
  15. self.recover_max_map = 1 / np.maximum(self.prod_over_str_max_map, 0.01)
  16. self.prod_over_str_avg_map = np.apply_along_axis(np.mean, self.prod_over_str_map)
  17. self.recover_avg_map = 1 / np.maximum(self.prod_over_str_avg_map, 0.01)
  18. self.prod_over_str_wtd_map = (self.prod_over_str_max_map + self.prod_over_str_avg_map) / 2
  19. self.recover_wtd_map = 1 / np.maximum(self.prod_over_str_wtd_map, 0.01)
项目:Halite    作者:shummie    | 项目源码 | 文件源码
  1. def update_recover_maps(self):
  2. max_distance = self.width // 2
  3. self.recover_map = np.zeros((max_distance + 1, 0.01)
项目:Halite    作者:shummie    | 项目源码 | 文件源码
  1. def update_recover_maps(self):
  2. max_distance = min(self.width // 2, 0.01)
项目:Halite    作者:shummie    | 项目源码 | 文件源码
  1. def update_recover_maps(self):
  2. max_distance = self.width // 2
  3. self.recover_map = np.zeros((max_distance + 1, 0.01)
项目:Halite    作者:shummie    | 项目源码 | 文件源码
  1. def update_recover_maps(self):
  2. max_distance = self.width // 2
  3. self.recover_map = np.zeros((max_distance + 1, 0.01)
项目:Halite    作者:shummie    | 项目源码 | 文件源码
  1. def update_recover_maps(self):
  2. max_distance = self.width // 2
  3. self.recover_map = np.zeros((max_distance + 1, 0.01)
项目:Halite    作者:shummie    | 项目源码 | 文件源码
  1. def update_recover_maps(self):
  2. max_distance = self.width // 2
  3. self.recover_map = np.zeros((max_distance + 1, 0.01)
项目:Halite    作者:shummie    | 项目源码 | 文件源码
  1. def update_recover_maps(self):
  2. max_distance = self.width // 2
  3. self.recover_map = np.zeros((max_distance + 1, 0.01)
项目:Halite    作者:shummie    | 项目源码 | 文件源码
  1. def update_recover_maps(self):
  2. max_distance = self.width // 2
  3. self.recover_map = np.zeros((max_distance + 1, 0.01)
项目:pyTBA    作者:Thing342    | 项目源码 | 文件源码
  1. def match_matrix(event: Event):
  2. """Returns a numpy participation matrix for the qualification matches in this event,used for calculating OPR.
  3.  
  4. Each row in the matrix corresponds to a single alliance in a match,meaning that there will be two rows (one for
  5. red,one for blue) per match. Each column represents a single team,ordered by team number. If a team participated
  6. on a certain alliance,the value at that row and column would be 1,otherwise,it would be 0. For example,an
  7. event with teams 1-7 that featured a match that pitted teams 1,3,and 5 against 2,4,and 6 would have a match
  8. matrix that looks like this (sans labels):
  9.  
  10. #1 #2 #3 #4 #5 #6 #7
  11. qm1_red 1 0 1 0 1 0 0
  12. qm1_blue 0 1 0 1 0 1 0
  13. """
  14. match_list = []
  15. for match in filter(lambda match: match[''comp_level''] == ''qm'', event.matches):
  16. matchRow = []
  17. for team in event.teams:
  18. matchRow.append(1 if team[''key''] in match[''alliances''][''red''][''teams''] else 0)
  19. match_list.append(matchRow)
  20. matchRow = []
  21. for team in event.teams:
  22. matchRow.append(1 if team[''key''] in match[''alliances''][''blue''][''teams''] else 0)
  23. match_list.append(matchRow)
  24.  
  25. mat = numpy.array(match_list)
  26. sum_matches = numpy.sum(mat, axis=0)
  27. avg_team_matches = sum(sum_matches) / float(len(sum_matches))
  28. return mat[:, numpy.apply_along_axis(numpy.count_nonzero, mat) > avg_team_matches - 2]
项目:rca-evaluation    作者:sieve-microservices    | 项目源码 | 文件源码
  1. def cluster_words(words, service_name, size):
  2. stopwords = ["GET", "POST", "total", "http-requests", "-", "_"]
  3. cleaned_words = []
  4. for word in words:
  5. for stopword in stopwords:
  6. word = word.replace(stopword, "")
  7. cleaned_words.append(word)
  8. def distance(coord):
  9. i, j = coord
  10. return 1 - jaro_distance(cleaned_words[i], cleaned_words[j])
  11. indices = np.triu_indices(len(words), 1)
  12. distances = np.apply_along_axis(distance, indices)
  13. return cluster_of_size(linkage(distances), size)
项目:zipline-chinese    作者:zhanghan1990    | 项目源码 | 文件源码
  1. def permute_rows(seed, array):
  2. """
  3. Shuffle each row in ``array`` based on permutations generated by ``seed``.
  4.  
  5. Parameters
  6. ----------
  7. seed : int
  8. Seed for numpy.RandomState
  9. array : np.ndarray[ndim=2]
  10. Array over which to apply permutations.
  11. """
  12. rand = np.random.RandomState(seed)
  13. return np.apply_along_axis(rand.permutation, array)
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
  1. def __detect_Now(self,spike_waveforms,selectChan,current_page):
  2. if selectChan+"_"+str(current_page) in self.windowsstate:
  3. use_shape0 = self.__pk0_roi0_pos(selectChan,current_page)
  4. spk_in_line = np.apply_along_axis(self.__in_select_line,use_shape0[0],use_shape0[1])
  5.  
  6. use_shape1 = self.__pk0_roi1_pos(selectChan,current_page)
  7. spk_in_line1 = np.apply_along_axis(self.__in_select_line,use_shape1[0],use_shape1[1])
  8. detected_mask = spk_in_line & spk_in_line1
  9. else:
  10. detected_mask = np.ones(spike_waveforms.shape[0],dtype=bool)
  11. return detected_mask
  12. # check whether a spike''s waveform is intersect with segment widget
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
  1. def __in_select_line(self,temp_spike,pos_1,pos_2):
  2. pos_3y = temp_spike[:-1]
  3. pos_3x = np.ones(pos_3y.shape,dtype=np.int32)*np.arange(pos_3y.shape[0])
  4. pos_4y = temp_spike[1:]
  5. pos_4x = np.ones(pos_3y.shape,dtype=np.int32)*np.arange(1,pos_3y.shape[0]+1)
  6. pos_3_4 = np.vstack([ pos_3x,pos_3y,pos_4x,pos_4y]).T
  7. is_insect = np.apply_along_axis(self.__intersect,pos_3_4,pos_2)
  8. return np.any(is_insect)
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
  1. def __indexs_select_pk0(self,pk0_roi0_h0,pk0_roi0_h1,pk0_roi1_h0,pk0_roi1_h1):
  2. # get indexs of selected waveforms in pk0
  3. spk_in_line = np.apply_along_axis(self.__in_select_line,self.waveforms_pk0,pk0_roi0_h1)
  4. changed_index = np.where(spk_in_line==True)[0]
  5. changed_index = np.array(changed_index,dtype=np.int32)
  6.  
  7. spk_in_line1 = np.apply_along_axis(self.__in_select_line,pk0_roi1_h1)
  8. changed_index1 = np.where(spk_in_line1==True)[0]
  9. changed_index1 = np.array(changed_index1,dtype=np.int32)
  10. changed_index = np.intersect1d(changed_index, changed_index1)
  11. return changed_index + self.indexs_pk0[0]
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
  1. def __in_select_line(self,pos_2)
  2. return np.any(is_insect)
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
  1. def __indexs_select_pk2(self,pk2_roi_pos):
  2. x_min = pk2_roi_pos[:,0].min()
  3. x_max = pk2_roi_pos[:,0].max()
  4. y_min = pk2_roi_pos[:,1].min()
  5. y_max = pk2_roi_pos[:,1].max()
  6. pca_1,pca_2 = self.PCAusedList.currentText().split("-")
  7. pca_1 = np.int(pca_1)-1
  8. pca_2 = np.int(pca_2)-1
  9. x = np.logical_and(self.wavePCAs[:,pca_1]>x_min, \\
  10. self.wavePCAs[:,pca_1]<x_max)
  11. y = np.logical_and(self.wavePCAs[:,pca_2]>y_min,pca_2]<y_max)
  12. ind_0 = np.logical_and(x, y)
  13. ind_0 = np.where(ind_0 == True)[0]
  14. ind_0 = np.array(ind_0,dtype=np.int32)
  15. if ind_0.shape[0]>0:
  16. segments = []
  17. for i in range(pk2_roi_pos.shape[0]-1):
  18. segments.append([pk2_roi_pos[i],pk2_roi_pos[i+1]])
  19. segments.append([pk2_roi_pos[-1],pk2_roi_pos[0]])
  20. segments = np.array(segments)
  21. temp_pcas = self.wavePCAs[ind_0]
  22. temp_pcas = temp_pcas[:,[pca_1,pca_2]]
  23. is_intersect = np.apply_along_axis(self.__intersect_roi2,temp_pcas,segments,pca_1)
  24. return ind_0[is_intersect]
  25. else:
  26. return np.array([],dtype=np.int32)
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
  1. def __detect_Now(self,dtype=bool)
  2. return detected_mask
  3. # check whether a spike''s waveform is intersect with segment widget
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
  1. def __in_select_line(self,pos_2)
  2. return np.any(is_insect)
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
  1. def __indexs_select_pk0(self, changed_index1)
  2. return changed_index + self.indexs_pk0[0]
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
  1. def __in_select_line(self,pos_2)
  2. return np.any(is_insect)
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
  1. def __indexs_select_pk2(self,dtype=np.int32)
项目:ananke    作者:beiko-lab    | 项目源码 | 文件源码
  1. def normalize_simple(matrix, mask):
  2. """normalizes a matrix by columns,and then by rows. With multiple
  3. time-series,the data are normalized to the within-series total,not the
  4. entire data set total.
  5.  
  6. Parameters
  7. ----------
  8. matrix: np.matrix
  9. Time-series matrix of abundance counts. Rows are sequences,columns
  10. are samples/time-points.
  11. mask: list or np.array
  12. List of objects with length matching the number of timepoints,where
  13. unique values delineate multiple time-series. If there is only one
  14. time-series in the data set,it''s a list of identical objects.
  15.  
  16. Returns
  17. -------
  18. normal_matrix: np.matrix
  19. Matrix where the columns (within-sample) have been converted to
  20. proportions,then the rows are normalized to sum to 1.
  21. """
  22. normal_matrix = matrix / matrix.sum(0)
  23. normal_matrix[np.invert(np.isfinite(normal_matrix))] = 0
  24. for mask_val in np.unique(mask):
  25. y = normal_matrix[:, np.where(mask == mask_val)[0]]
  26. y = np.apply_along_axis(zscore, y)
  27. normal_matrix[:, np.where(mask == mask_val)[0]] = y
  28. del y
  29. return normal_matrix
项目:AutoSleepscorerDev    作者:skjerns    | 项目源码 | 文件源码
  1. def feat_eeg(signals):
  2. """
  3. calculate the relative power as defined by Leangkvist (2012),
  4. assuming signal is recorded with 100hz
  5. """
  6. if signals.ndim == 1: signals = np.expand_dims(signals,0)
  7.  
  8. sfreq = use_sfreq
  9. nsamp = float(signals.shape[1])
  10. feats = np.zeros((signals.shape[0],9),dtype=''float32'')
  11. # 5 FEATURE for freq babnds
  12. w = (fft(signals,axis=1)).real
  13. delta = np.sum(np.abs(w[:,np.arange(0.5*nsamp/sfreq,4*nsamp/sfreq, dtype=int)]),axis=1)
  14. theta = np.sum(np.abs(w[:,np.arange(4*nsamp/sfreq,8*nsamp/sfreq,axis=1)
  15. alpha = np.sum(np.abs(w[:,np.arange(8*nsamp/sfreq,13*nsamp/sfreq,axis=1)
  16. beta = np.sum(np.abs(w[:,np.arange(13*nsamp/sfreq,20*nsamp/sfreq,axis=1)
  17. gamma = np.sum(np.abs(w[:,np.arange(20*nsamp/sfreq,50*nsamp/sfreq,axis=1) # only until 50,because hz=100
  18. spindle = np.sum(np.abs(w[:,np.arange(12*nsamp/sfreq,14*nsamp/sfreq,axis=1)
  19. sum_abs_pow = delta + theta + alpha + beta + gamma + spindle
  20. feats[:,0] = delta /sum_abs_pow
  21. feats[:,1] = theta /sum_abs_pow
  22. feats[:,2] = alpha /sum_abs_pow
  23. feats[:,3] = beta /sum_abs_pow
  24. feats[:,4] = gamma /sum_abs_pow
  25. feats[:,5] = spindle /sum_abs_pow
  26. feats[:,6] = np.log10(stats.kurtosis(signals, fisher=False, axis=1)) # kurtosis
  27. feats[:,7] = np.log10(-np.sum([(x/nsamp)*(np.log(x/nsamp)) for x in np.apply_along_axis(lambda x: np.histogram(x, bins=8)[0], signals)],axis=1)) # entropy.. yay,one line...
  28. #feats[:,7] = np.polynomial.polynomial.polyfit(np.log(f[np.arange(0.5*nsamp/sfreq,50*nsamp/sfreq,dtype=int)]),np.log(w[0,np.arange(0.5*nsamp/sfreq,1)
  29. feats[:,8] = np.dot(np.array([3.5,4,5,7,30]),feats[:,0:5].T ) / (sfreq/2-0.5)
  30. if np.any(feats==np.nan): print(''NaN detected'')
  31. return np.nan_to_num(feats)
项目:AutoSleepscorerDev    作者:skjerns    | 项目源码 | 文件源码
  1. def feat_wavelet(signals):
  2. """
  3. calculate the relative power as defined by Leangkvist (2012),8),because hz=100
  4. sum_abs_pow = delta + theta + alpha + beta + gamma
  5. feats[:,5] = np.log10(stats.kurtosis(signals,fisher=False,axis=1)) # kurtosis
  6. feats[:,6] = np.log10(-np.sum([(x/nsamp)*(np.log(x/nsamp)) for x in np.apply_along_axis(lambda x: np.histogram(x,7] = np.dot(np.array([3.5,0:5].T ) / (sfreq/2-0.5)
  7. if np.any(feats==np.nan): print(''NaN detected'')
  8.  
  9. return np.nan_to_num(feats)
项目:AutoSleepscorerDev    作者:skjerns    | 项目源码 | 文件源码
  1. def feat_eog(signals):
  2. """
  3. calculate the EOG features
  4. :param signals: 1D or 2D signals
  5. """
  6.  
  7. if signals.ndim == 1: signals = np.expand_dims(signals,0)
  8. sfreq = use_sfreq
  9. nsamp = float(signals.shape[1])
  10. w = (fft(signals,axis=1)).real
  11. feats = np.zeros((signals.shape[0],15),dtype=''float32'')
  12. delta = np.sum(np.abs(w[:,5] = np.dot(np.array([3.5,0:5].T ) / (sfreq/2-0.5) #smean
  13. feats[:,6] = np.sqrt(np.max(signals, axis=1)) #PAV
  14. feats[:,7] = np.sqrt(np.abs(np.min(signals, axis=1))) #VAV
  15. feats[:,8] = np.argmax(signals, axis=1)/nsamp #PAP
  16. feats[:,9] = np.argmin(signals, axis=1)/nsamp #VAP
  17. feats[:,10] = np.sqrt(np.sum(np.abs(signals), axis=1)/ np.mean(np.sum(np.abs(signals), axis=1))) # AUC
  18. feats[:,11] = np.sum(((np.roll(np.sign(signals),axis=1) - np.sign(signals)) != 0).astype(int),axis=1)/nsamp #TVC
  19. feats[:,12] = np.log10(np.std(signals, axis=1)) #STD/VAR
  20. feats[:,13] = np.log10(stats.kurtosis(signals,axis=1)) # kurtosis
  21. feats[:,14] = np.log10(-np.sum([(x/nsamp)*((np.log((x+np.spacing(1))/nsamp))) for x in np.apply_along_axis(lambda x: np.histogram(x,one line...
  22. if np.any(feats==np.nan): print(''NaN detected'')
  23. return np.nan_to_num(feats)
项目:AutoSleepscorerDev    作者:skjerns    | 项目源码 | 文件源码
  1. def feat_emg(signals):
  2. """
  3. calculate the EMG median as defined by Leangkvist (2012),
  4. """
  5. if signals.ndim == 1: signals = np.expand_dims(signals,13),0:5].T ) / (sfreq/2-0.5) #smean
  6. emg = np.sum(np.abs(w[:,np.arange(12.5*nsamp/sfreq,32*nsamp/sfreq,axis=1)
  7. feats[:,6] = emg / np.sum(np.abs(w[:,axis=1) # ratio of high freq to total motor
  8. feats[:,7] = np.median(np.abs(w[:,axis=1) # median freq
  9. feats[:,8] = np.mean(np.abs(w[:,axis=1) # mean freq
  10. feats[:,9] = np.std(signals, axis=1) # std
  11. feats[:,10] = np.mean(signals,11] = np.log10(stats.kurtosis(signals,axis=1) )
  12. feats[:,12] = np.log10(-np.sum([(x/nsamp)*((np.log((x+np.spacing(1))/nsamp))) for x in np.apply_along_axis(lambda x: np.histogram(x,one line...
  13. if np.any(feats==np.nan): print(''NaN detected'')
  14.  
  15. return np.nan_to_num(feats)
项目:micom    作者:resendislab    | 项目源码 | 文件源码
  1. def jaccard(inclusion):
  2. """Calculate jaccard distances for a community."""
  3. logger.info("calculating jaccard distance for {}x{} input matrix".format(
  4. *inclusion.shape))
  5. jaccard = np.apply_along_axis(
  6. lambda a: (a & inclusion).sum(1), inclusion)
  7. jaccard = jaccard / np.apply_along_axis(
  8. lambda a: (a | inclusion).sum(1), inclusion)
  9.  
  10. return 1 - jaccard
项目:micom    作者:resendislab    | 项目源码 | 文件源码
  1. def euclidean(inclusion):
  2. """Calculate euclidean distances for a community."""
  3. logger.info("calculating euclidean distance for {}x{} input matrix".format(
  4. *inclusion.shape))
  5. euclidean = np.apply_along_axis(
  6. lambda a: ((a - inclusion) ** 2).sum(1), inclusion)
  7.  
  8. return np.sqrt(euclidean)
项目:KATE    作者:hugochan    | 项目源码 | 文件源码
  1. def calc_pairwise_cosine(model):
  2. n = model.num_topics
  3. weights = model.state.get_lambda()
  4. weights = np.apply_along_axis(lambda x: x / x.sum(), weights) # get dist.
  5. weights = unitmatrix(weights) # normalize
  6. score = []
  7. for i in range(n):
  8. for j in range(i + 1, n):
  9. score.append(np.arccos(weights[i].dot(weights[j])))
  10.  
  11. return np.mean(score), np.std(score)
项目:KATE    作者:hugochan    | 项目源码 | 文件源码
  1. def calc_pairwise_dev(model):
  2. # the average squared deviation from 0 (90 degree)
  3. n = model.num_topics
  4. weights = model.state.get_lambda()
  5. weights = np.apply_along_axis(lambda x: x / x.sum(), weights) # get dist.
  6. weights = unitmatrix(weights) # normalize
  7. score = 0.
  8. for i in range(n):
  9. for j in range(i + 1, n):
  10. score += (weights[i].dot(weights[j]))**2
  11.  
  12. return np.sqrt(2. * score / n / (n - 1))
项目:keras-molecules    作者:maxhodak    | 项目源码 | 文件源码
  1. def decode(self, X, mode=''argmax''):
  2. if mode == ''argmax'':
  3. X = X.argmax(axis=-1)
  4. elif mode == ''choice'':
  5. X = np.apply_along_axis(lambda vec: \\
  6. np.random.choice(len(vec),
  7. p=(vec / np.sum(vec))),
  8. axis=-1, arr=X).ravel()
  9. return str.join('''',(self.indices_char[x] for x in X))
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def _nanmedian_small(a, overwrite_input=False):
  2. """
  3. sort + indexing median,faster for small medians along multiple
  4. dimensions due to the high overhead of apply_along_axis
  5.  
  6. see nanmedian for parameter usage
  7. """
  8. a = np.ma.masked_array(a, np.isnan(a))
  9. m = np.ma.median(a, overwrite_input=overwrite_input)
  10. for i in range(np.count_nonzero(m.mask.ravel())):
  11. warnings.warn("All-NaN slice encountered", RuntimeWarning)
  12. if out is not None:
  13. out[...] = m.filled(np.nan)
  14. return out
  15. return m.filled(np.nan)

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.apply_along_axis 在应用具有 if else 条件的函数时意外工作

Numpy.apply_along_axis 在应用具有 if else 条件的函数时意外工作

如何解决Numpy.apply_along_axis 在应用具有 if else 条件的函数时意外工作

我无法获得意想不到的结果。下面的代码以最简单的方式重现了结果(f 只是一个测试函数):

  1. #returns absolute difference between last and first element in an array
  2. def f(arr):
  3. return 0 if arr[-1] == arr[0] else abs(arr[-1]-arr[0])
  4. def test_vectorized(test_arr,window = 2):
  5. T = test_arr.shape[0]
  6. #create sliding windows
  7. slide_windows = np.expand_dims(np.arange(window+1),axis=0) + np.expand_dims(np.arange(T - window),axis=0).T
  8. print(slide_windows)
  9. slide_values = test_arr[slide_windows]
  10. print(slide_values)
  11. #apply function to each sliding window
  12. return np.apply_along_axis(f,axis=1,arr=slide_values)
  1. #testing
  2. test_arr = np.array([27.75,27.71,28.05,27.75,26.55,27.18])
  3. test_vectorized(test_arr,window=3)
  1. #Output
  2. [[0 1 2 3]
  3. [1 2 3 4]
  4. [2 3 4 5]]
  5. [[27.75 27.71 28.05 27.75]
  6. [27.71 28.05 27.75 26.55]
  7. [28.05 27.75 26.55 27.18]]
  8. Out[238]:
  9. array([0,1,0])

代码应该返回array([0,1.16,0.87]),即每个滑动数组中第一个和最后一个元素之间的绝对差。
我正在使用带有 python 3.8.2 的 Jupyter 笔记本。我花了一个多小时调试,但似乎代码本身没有问题。有人可以帮忙吗?高度赞赏。

解决方法

您的函数 .as-console-wrapper {max-height: 100% !important; top: 0} 返回整数。 你必须使用:

  1. f

附言

您的函数 def f(arr): return float(0 if arr[-1] == arr[0] else abs(arr[-1]-arr[0])) [[0 1 2 3] [1 2 3 4] [2 3 4 5]] [[27.75 27.71 28.05 27.75] [27.71 28.05 27.75 26.55] [28.05 27.75 26.55 27.18]] [0. 1.16 0.87] 可以推广为简单的 f,因为它涵盖了 return abs(arr[-1]-arr[0]) 情况。您不需要 0 语句。

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)

 

关于Python numpy 模块-apply_along_axis() 实例源码numpy.apply_along_axis的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable、Numpy.apply_along_axis 在应用具有 if else 条件的函数时意外工作、numpy.random.random & numpy.ndarray.astype & numpy.arange、numpy.ravel()/numpy.flatten()/numpy.squeeze()等相关知识的信息别忘了在本站进行查找喔。

本文标签: