GVKun编程网logo

Python numpy 模块-argpartition() 实例源码(python numpy.arange)

1

本文将介绍Pythonnumpy模块-argpartition()实例源码的详细情况,特别是关于pythonnumpy.arange的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了

本文将介绍Python numpy 模块-argpartition() 实例源码的详细情况,特别是关于python numpy.arange的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些关于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 模块-argpartition() 实例源码(python numpy.arange)

Python numpy 模块-argpartition() 实例源码(python numpy.arange)

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

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

项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_partition_cdtype(self):
  2. d = np.array([(''galahad'', 1.7, 38), (''Arthur'', 1.8, 41),
  3. (''Lancelot'', 1.9, 38)],
  4. dtype=[(''name'', ''|S10''), (''height'', ''<f8''), (''age'', ''<i4'')])
  5.  
  6. tgt = np.sort(d, order=[''age'', ''height''])
  7. assert_array_equal(np.partition(d, range(d.size),
  8. order=[''age'', ''height'']),
  9. tgt)
  10. assert_array_equal(d[np.argpartition(d,
  11. order=[''age'', ''height''])],
  12. tgt)
  13. for k in range(d.size):
  14. assert_equal(np.partition(d, k, ''height''])[k],
  15. tgt[k])
  16. assert_equal(d[np.argpartition(d, ''height''])][k],
  17. tgt[k])
  18.  
  19. d = np.array([''galahad'', ''Arthur'', ''zebra'', ''Lancelot''])
  20. tgt = np.sort(d)
  21. assert_array_equal(np.partition(d, range(d.size)), tgt)
  22. for k in range(d.size):
  23. assert_equal(np.partition(d, k)[k], tgt[k])
  24. assert_equal(d[np.argpartition(d, k)][k], tgt[k])
项目:youtube-8m    作者:wangheda    | 项目源码 | 文件源码
  1. def format_lines(video_ids, predictions, labels, top_k):
  2. batch_size = len(video_ids)
  3. for video_index in range(batch_size):
  4. n_recall = max(int(numpy.sum(labels[video_index])), 1)
  5. # labels
  6. label_indices = numpy.argpartition(labels[video_index], -n_recall)[-n_recall:]
  7. label_predictions = [(class_index, predictions[video_index][class_index])
  8. for class_index in label_indices]
  9. label_predictions = sorted(label_predictions, key=lambda p: -p[1])
  10. label_str = "\\t".join(["%d\\t%f"%(x,y) for x,y in label_predictions])
  11. # predictions
  12. top_k_indices = numpy.argpartition(predictions[video_index], -top_k)[-top_k:]
  13. top_k_predictions = [(class_index, predictions[video_index][class_index])
  14. for class_index in top_k_indices]
  15. top_k_predictions = sorted(top_k_predictions, key=lambda p: -p[1])
  16. top_k_str = "\\t".join(["%d\\t%f"%(x,y in top_k_predictions])
  17. # compute PERR
  18. top_n_indices = numpy.argpartition(predictions[video_index], -n_recall)[-n_recall:]
  19. positives = [labels[video_index][class_index]
  20. for class_index in top_n_indices]
  21. perr = sum(positives) / float(n_recall)
  22. # URL
  23. url = "https://www.youtube.com/watch?v=" + video_ids[video_index].decode(''utf-8'')
  24. yield url + "\\t" + str(1-perr) + "\\t" + top_k_str + "\\t" + label_str + "\\n"
项目:cupy    作者:cupy    | 项目源码 | 文件源码
  1. def argpartition(a, kth, axis=-1):
  2. """Returns the indices that would partially sort an array.
  3.  
  4. Args:
  5. a (cupy.ndarray): Array to be sorted.
  6. kth (int or sequence of ints): Element index to partition by. If
  7. supplied with a sequence of k-th it will partition all elements
  8. indexed by k-th of them into their sorted position at once.
  9. axis (int or None): Axis along which to sort. Default is -1,which
  10. means sort along the last axis. If None is supplied,the array is
  11. flattened before sorting.
  12.  
  13. Returns:
  14. cupy.ndarray: Array of the same type and shape as ``a``.
  15.  
  16. .. note::
  17. For its implementation reason,`cupy.argpartition` fully sorts the
  18. given array as `cupy.argsort` does. It also does not support ``kind``
  19. and ``order`` parameters that ``numpy.argpartition`` supports.
  20.  
  21. .. seealso:: :func:`numpy.argpartition`
  22.  
  23. """
  24. return a.argpartition(kth, axis=axis)
项目:SlidingWindowVideoTDA    作者:ctralie    | 项目源码 | 文件源码
  1. def CSMToBinary(D, Kappa):
  2. """
  3. Turn a cross-similarity matrix into a binary cross-simlarity matrix
  4. If Kappa = 0,take all neighbors
  5. If Kappa < 1 it is the fraction of mutual neighbors to consider
  6. Otherwise Kappa is the number of mutual neighbors to consider
  7. """
  8. N = D.shape[0]
  9. M = D.shape[1]
  10. if Kappa == 0:
  11. return np.ones((N, M))
  12. elif Kappa < 1:
  13. NNeighbs = int(np.round(Kappa*M))
  14. else:
  15. NNeighbs = Kappa
  16. J = np.argpartition(D, NNeighbs, 1)[:, 0:NNeighbs]
  17. I = np.tile(np.arange(N)[:, None], (1, NNeighbs))
  18. V = np.ones(I.size)
  19. [I, J] = [I.flatten(), J.flatten()]
  20. ret = sparse.coo_matrix((V, (I, J)), shape=(N, M))
  21. return ret.toarray()
项目:DrQA    作者:facebookresearch    | 项目源码 | 文件源码
  1. def closest_docs(self, query, k=1):
  2. """Closest docs by dot product between query and documents
  3. in tfidf weighted word vector space.
  4. """
  5. spvec = self.text2spvec(query)
  6. res = spvec * self.doc_mat
  7.  
  8. if len(res.data) <= k:
  9. o_sort = np.argsort(-res.data)
  10. else:
  11. o = np.argpartition(-res.data, k)[0:k]
  12. o_sort = o[np.argsort(-res.data[o])]
  13.  
  14. doc_scores = res.data[o_sort]
  15. doc_ids = [self.get_doc_id(i) for i in res.indices[o_sort]]
  16. return doc_ids, doc_scores
项目:Y8M    作者:mpekalski    | 项目源码 | 文件源码
  1. def bottom_top_k_along_row(arr, ordered=True):
  2. """ bottom and top k of a 2d np.array,along the rows
  3. http://stackoverflow.com/questions/6910641/how-to-get-indices-of-n-maximum-values-in-a-numpy-array/18691983
  4. """
  5. assert k>0, "bottom_top_k_along_row/column() requires k>0."
  6. rows = arr.shape[0]
  7. if ordered:
  8. tmp = np.argsort(arr, axis=1)
  9. idx_bot = tmp[:, :k]
  10. idx_top = tmp[:,-k:]
  11. else:
  12. idx_bot = np.argpartition(arr, axis=1)[:,:k]
  13. idx_top = np.argpartition(arr, -k,-k:]
  14.  
  15. indices = np.concatenate((idx_bot, idx_top), axis=1)
  16. vals = arr[np.repeat(np.arange(rows), 2*k), indices.ravel()].reshape(rows,2*k)
  17. return vals, indices
项目:sequence-based-recommendations    作者:rdevooght    | 项目源码 | 文件源码
  1. def top_k_recommendations(self, sequence, k=10, exclude=None, **kwargs):
  2. if exclude is None:
  3. exclude = []
  4.  
  5. last_item = int(sequence[-1][0])
  6. if last_item not in self.prevIoUs_recommendations:
  7. self.get_all_recommendations(last_item)
  8.  
  9. all_recommendations = deepcopy(self.prevIoUs_recommendations[last_item])
  10. for s in sequence:
  11. all_recommendations[int(s[0])] = 0
  12. for i in exclude:
  13. all_recommendations[i] = 0
  14.  
  15. ranking = np.zeros(self.n_items)
  16. for i, x in enumerate(all_recommendations.most_common(k)):
  17. ranking[x[0]] = k-i
  18. return np.argpartition(-ranking, range(k))[:k]
项目:sequence-based-recommendations    作者:rdevooght    | 项目源码 | 文件源码
  1. def top_k_recommendations(self, user_id=None, exclude=None):
  2. '''''' Recieves a sequence of (id,rating),and produces k recommendations (as a list of ids)
  3. ''''''
  4.  
  5. if exclude is None:
  6. exclude = []
  7.  
  8. last_item = sequence[-1][0]
  9. output = np.dot(self.V_user_item[user_id, :], self.V_item_user.T) + np.dot(self.V_prev_next[last_item, self.V_next_prev.T)
  10.  
  11. # Put low similarity to viewed items to exclude them from recommendations
  12. output[[i[0] for i in sequence]] = -np.inf
  13. output[exclude] = -np.inf
  14.  
  15. # find top k according to output
  16. return list(np.argpartition(-output, range(k))[:k])
项目:sequence-based-recommendations    作者:rdevooght    | 项目源码 | 文件源码
  1. def top_k_recommendations(self,and produces k recommendations (as a list of ids)
  2. ''''''
  3.  
  4. if exclude is None:
  5. exclude = []
  6.  
  7. user_items = [i[0] for i in sequence]
  8. output = self.item_score(user_id, user_items)
  9.  
  10. # Put low similarity to viewed items to exclude them from recommendations
  11. output[[i[0] for i in sequence]] = -np.inf
  12. output[exclude] = -np.inf
  13.  
  14. # find top k according to output
  15. return list(np.argpartition(-output, range(k))[:k])
项目:sequence-based-recommendations    作者:rdevooght    | 项目源码 | 文件源码
  1. def top_k_recommendations(self,and produces k recommendations (as a list of ids)
  2. ''''''
  3.  
  4. if exclude is None:
  5. exclude = []
  6.  
  7. last_item = sequence[-1][0]
  8. output = self.bias + np.dot(self.V[user_id, self.H.T)
  9.  
  10. # Put low similarity to viewed items to exclude them from recommendations
  11. output[[i[0] for i in sequence]] = -np.inf
  12. output[exclude] = -np.inf
  13.  
  14. # find top k according to output
  15. return list(np.argpartition(-output, range(k))[:k])
项目:sequence-based-recommendations    作者:rdevooght    | 项目源码 | 文件源码
  1. def top_k_recommendations(self, **kwargs):
  2. '''''' Recieves a sequence of (id,and produces k recommendations (as a list of ids)
  3. ''''''
  4.  
  5. # Compile network if needed
  6. if not hasattr(self, ''predict_function''):
  7. self._compile_predict_function()
  8.  
  9. # Prepare RNN input
  10. X = np.zeros((1, self._input_size())) # input of the RNN
  11. X[0, :] = self._one_hot_encoding([i[0] for i in sequence])
  12.  
  13. # Run RNN
  14. output = self.predict_function(X.astype(theano.config.floatX))[0]
  15.  
  16. # Put low similarity to viewed items to exclude them from recommendations
  17. output[[i[0] for i in sequence]] = -np.inf
  18. output[exclude] = -np.inf
  19.  
  20. # find top k according to output
  21. return list(np.argpartition(-output, range(k))[:k])
项目:sequence-based-recommendations    作者:rdevooght    | 项目源码 | 文件源码
  1. def _compile_test_function(self):
  2. '''''' Differs from base test function because of the added softmax operation
  3. ''''''
  4. print("Compiling test...")
  5. deterministic_output = T.nnet.softmax(lasagne.layers.get_output(self.l_out, deterministic=True))
  6. if self.interactions_are_unique:
  7. deterministic_output *= (1 - self.exclude)
  8.  
  9. theano_test_function = theano.function(self.theano_inputs, deterministic_output, allow_input_downcast=True, name="Test_function", on_unused_input=''ignore'')
  10.  
  11. def precision_test_function(theano_inputs, k=10):
  12. output = theano_test_function(*theano_inputs)
  13. ids = np.argpartition(-output, range(k), axis=-1)[0, :k]
  14.  
  15. return ids
  16.  
  17. self.test_function = precision_test_function
  18. print("Compilation done.")
项目:sockeye    作者:awslabs    | 项目源码 | 文件源码
  1. def smallest_k(matrix: np.ndarray, k: int,
  2. only_first_row: bool = False) -> Tuple[Tuple[np.ndarray, np.ndarray], np.ndarray]:
  3. """
  4. Find the smallest elements in a numpy matrix.
  5.  
  6. :param matrix: Any matrix.
  7. :param k: The number of smallest elements to return.
  8. :param only_first_row: If true the search is constrained to the first row of the matrix.
  9. :return: The row indices,column indices and values of the k smallest items in matrix.
  10. """
  11. if only_first_row:
  12. flatten = matrix[:1, :].flatten()
  13. else:
  14. flatten = matrix.flatten()
  15.  
  16. # args are the indices in flatten of the k smallest elements
  17. args = np.argpartition(flatten, k)[:k]
  18. # args are the indices in flatten of the sorted k smallest elements
  19. args = args[np.argsort(flatten[args])]
  20. # flatten[args] are the values for args
  21. return np.unravel_index(args, matrix.shape), flatten[args]
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_partition_cdtype(self):
  2. d = np.array([(''galahad'', tgt[k])
项目:cebl    作者:idfah    | 项目源码 | 文件源码
  1. def probs(self, x):
  2. dists = np.hstack([self.distFunc(x, cls) for cls in self.trainData])
  3. indices = np.argpartition(dists, self.k,:self.k]
  4.  
  5. #start = 0
  6. #Votes = list()
  7. #for cls in self.trainData:
  8. # end = start + cls.shape[0]
  9. # Votes.append(np.sum(np.logical_and(start <= indices,indices < end),axis=1))
  10. # start = end
  11.  
  12. ends = np.cumsum([len(cls) for cls in self.trainData])
  13. starts = ends - np.array([len(cls) for cls in self.trainData])
  14. Votes = [np.sum(np.logical_and(start <= indices, indices < end), axis=1)
  15. for start, end in zip(starts, ends)]
  16. Votes = np.vstack(Votes).T
  17.  
  18. #probs = np.zeros((x.shape[0],self.nCls))
  19. #probs[np.arange(probs.shape[0]),np.argmax(Votes,axis=1)] = 1.0
  20. ##probs = util.softmax(Votes / float(self.k))
  21. probs = Votes / float(self.k)
  22.  
  23. return probs
项目:hyperstar    作者:nlpub    | 项目源码 | 文件源码
  1. def argmaxk_rows_opt1(arr, sort=False):
  2. """
  3. Optimized implementation. When sort=False it is equal to argmaxk_rows_basic. When sort=True and k << arr.shape[1],
  4. it is should be faster,because we argsort only subarray of k max elements from each row of arr (arr.shape[0] x k) instead of
  5. the whole array arr (arr.shape[0] x arr.shape[1]).
  6. """
  7. best_inds = np.argpartition(arr, kth=-k, -k:] # column indices of k max elements in each row (m x k)
  8. if not sort:
  9. return best_inds
  10. # generate row indices corresponding to best_ids (just current row id in each row) (m x k)
  11. rows = np.arange(best_inds.shape[0], dtype=np.intp)[:, np.newaxis].repeat(best_inds.shape[1], axis=1)
  12. best_elems = arr[rows, best_inds] # select k max elements from each row using advanced indexing (m x k)
  13. # indices which sort each row of best_elems in descending order (m x k)
  14. best_elems_inds = np.argsort(best_elems, ::-1]
  15. # reorder best_indices so that arr[i,sorted_best_inds[i,:]] will be sorted in descending order
  16. sorted_best_inds = best_inds[rows, best_elems_inds]
  17. return sorted_best_inds
项目:semihin    作者:HKUST-KNowComp    | 项目源码 | 文件源码
  1. def generateCosineNeighborgraph(hin,kNeighbors=10,tf_param={''word'':True, ''entity'':False, ''we_weight'':1}):
  2. X, newIds, entIds = GraphGenerator.getTFVectorX(hin,param=tf_param)
  3. cosX = cosine_similarity(X)
  4. #return sparse.csc_matrix(X.dot(X.transpose())),newIds
  5. n = cosX.shape[0]
  6. graph = np.zeros((n,n))
  7. tic = time.time()
  8. for i in range(n):
  9. for j in np.argpartition(-cosX[i],kNeighbors)[:kNeighbors]:
  10. if j == i:
  11. continue
  12. #graph[i,j] += cosX[i,j]
  13. #graph[j,i] += cosX[i,j]
  14. graph[i, j] += 1
  15. graph[j, i] += 1
  16. toc = time.time() - tic
  17.  
  18. return sparse.csc_matrix(graph), newIds
项目:semihin    作者:HKUST-KNowComp    | 项目源码 | 文件源码
  1. def generateCosineNeighborgraphfromX(X, kNeighbors=10):
  2. cosX = cosine_similarity(X)
  3. # return sparse.csc_matrix(X.dot(X.transpose())),newIds
  4. #print cosX.shape
  5. n = cosX.shape[0]
  6. graph = np.zeros((n, n))
  7. tic = time.time()
  8. for i in range(n):
  9. for j in np.argpartition(-cosX[i], kNeighbors)[:kNeighbors]:
  10. if j == i:
  11. continue
  12. # graph[i,j]
  13. # graph[j, i] += 1
  14. toc = time.time() - tic
  15. #print ''graph generation done in %f seconds.'' % toc
  16. return sparse.csc_matrix(graph)
项目:semihin    作者:HKUST-KNowComp    | 项目源码 | 文件源码
  1. def generate_laplacian_score_scalar(X_ent, X_word, kNeighbors):
  2. # Generate cosine similarity graph
  3. n = X_ent.shape[0]
  4. cosX = cosine_similarity(X_word)
  5. graph = np.zeros((n, n))
  6. for i in range(n):
  7. for j in np.argpartition(cosX[i], -kNeighbors)[-kNeighbors:]:
  8. if j == i:
  9. continue
  10. graph[i, j] = cosX[i, j]
  11. graph[j, i] = cosX[i, j]
  12.  
  13. D = sparse.diags([graph.sum(axis=0)], [0])
  14. L = D - graph
  15. f_tilde = X_ent - (float(X_ent.transpose() * D * np.ones((n, 1))) / D.sum().sum()) * np.ones((n, 1))
  16. score = float(f_tilde.transpose() * L * f_tilde) / float(f_tilde.transpose() * D * f_tilde + 1e-10)
  17. laplacian_score = score
  18. return laplacian_score
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_partition_cdtype(self):
  2. d = np.array([(''galahad'', tgt[k])
项目:harpreif    作者:harpribot    | 项目源码 | 文件源码
  1. def compute_nearest_neighbors(self, num_neighbors):
  2. result_list = []
  3. for key, value in self.im2index.iteritems():
  4. neighbor_list = [key]
  5. similarity_scores = self.similarity_mat[value]
  6. # removes best match as same as key
  7. ind = np.argpartition(similarity_scores, -(num_neighbors + 1))[-(num_neighbors + 1):-1]
  8. ind = ind[np.argsort(similarity_scores[ind])]
  9. neighbors = [self.index2im[x] for x in ind]
  10. neighbor_list.extend(neighbors)
  11.  
  12. result_list.append(neighbor_list)
  13.  
  14. # compute neighbor statistics
  15. NearestNeighbour.compute_neighbor_stats(result_list, num_neighbors)
  16.  
  17. # plot the TSNE plot
  18. self.plot_tsne()
  19.  
  20. return result_list
项目:marvin    作者:aikanor    | 项目源码 | 文件源码
  1. def _calculate_topk_ndces(self, k):
  2. """
  3. Calculate the indices of the k specialists with highest b-value,
  4. including the base classifier regardless of its b-value.
  5.  
  6. Args:
  7. k: int >= 0,approximately specifying the number of derived specialists to select.
  8. Precisely,the best k (by Wilson error bound) are taken,along with the
  9. base classifier if it is not already one of the best k.
  10.  
  11. Returns:
  12. A list containing the indices of the top k classifiers.
  13. The list always at least contains the base classifier''s index (i.e. 0).
  14. Therefore,the list is of length k if the base classifier is one of the top k,
  15. and length k+1 otherwise. If k is greater than the total number of derived
  16. specialists,returns all of them.
  17. """
  18. assert self.label_corrs is not None , "Label correlations must be calculated before top k indices."
  19. if k < len(self.label_corrs):
  20. topk_ndces = set(np.argpartition(-self.label_corrs, k)[:k]) #Only does a partial sort of b!
  21. else:
  22. topk_ndces = set(range(len(self.label_corrs)))
  23. topk_ndces.add(0)
  24. return list(topk_ndces & set(self._relevant_ndces))
项目:nonce2vec    作者:minimalparts    | 项目源码 | 文件源码
  1. def argsort(x, topn=None, reverse=False):
  2. """
  3. Return indices of the `topn` smallest elements in array `x`,in ascending order.
  4.  
  5. If reverse is True,return the greatest elements instead,in descending order.
  6.  
  7. """
  8. x = np.asarray(x) # unify code path for when `x` is not a np array (list,tuple...)
  9. if topn is None:
  10. topn = x.size
  11. if topn <= 0:
  12. return []
  13. if reverse:
  14. x = -x
  15. if topn >= x.size or not hasattr(np, ''argpartition''):
  16. return np.argsort(x)[:topn]
  17. # np >= 1.8 has a fast partial argsort,use that!
  18. most_extreme = np.argpartition(x, topn)[:topn]
  19. return most_extreme.take(np.argsort(x.take(most_extreme))) # resort topn into order
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_partition_cdtype(self):
  2. d = np.array([(''galahad'', tgt[k])
项目:DrQA_cn    作者:AmoseKang    | 项目源码 | 文件源码
  1. def closest_docs(self, doc_scores
项目:pylmnn    作者:johny-c    | 项目源码 | 文件源码
  1. def _select_target_neighbors(self):
  2. """Find the target neighbors of each sample,that stay fixed during training.
  3.  
  4. Returns
  5. -------
  6. array_like
  7. An array of neighbors indices for each sample with shape (n_samples,n_neighbors).
  8.  
  9. """
  10.  
  11. self.logger.info(''Finding target neighbors...'')
  12. target_neighbors = np.empty((self.X_.shape[0], self.n_neighbors_), dtype=int)
  13. for class_ in self.classes_:
  14. class_ind, = np.where(np.equal(self.y_, class_))
  15. dist = euclidean_distances(self.X_[class_ind], squared=True)
  16. np.fill_diagonal(dist, np.inf)
  17. neigh_ind = np.argpartition(dist, self.n_neighbors_ - 1, axis=1)
  18. neigh_ind = neigh_ind[:, :self.n_neighbors_]
  19. # argpartition doesn''t guarantee sorted order,so we sort again but only the k neighbors
  20. row_ind = np.arange(len(class_ind))[:, None]
  21. neigh_ind = neigh_ind[row_ind, np.argsort(dist[row_ind, neigh_ind])]
  22. target_neighbors[class_ind] = class_ind[neigh_ind]
  23.  
  24. return target_neighbors
项目:hred-latent-piecewise    作者:julianser    | 项目源码 | 文件源码
  1. def select_next_words(self, next_costs, next_probs, step_num, how_many):
  2. # Pick only on the first line (for the beginning of sampling)
  3. # This will avoid duplicate <q> token.
  4. if step_num == 0:
  5. flat_next_costs = next_costs[:1, :].flatten()
  6. else:
  7. # Set the next cost to infinite for finished utterances (they will be replaced)
  8. # by other utterances in the beam
  9. flat_next_costs = next_costs.flatten()
  10.  
  11. voc_size = next_costs.shape[1]
  12.  
  13. args = numpy.argpartition(flat_next_costs, how_many)[:how_many]
  14. args = args[numpy.argsort(flat_next_costs[args])]
  15.  
  16. return numpy.unravel_index(args, next_costs.shape), flat_next_costs[args]
项目:nmt    作者:Playinf    | 项目源码 | 文件源码
  1. def find_nbest(score, n, threshold=None):
  2. num_vars = score.shape[1]
  3.  
  4. score = score.flatten()
  5. nbest = np.argpartition(score, n)[:n]
  6.  
  7. beam_indices = nbest / num_vars
  8. var_indices = nbest % num_vars
  9. nbest_score = score[nbest]
  10.  
  11. if threshold:
  12. best = np.max(nbest_score)
  13. cond = nbest_score > best + threshold
  14. nbest_score = nbest_score[cond]
  15. beam_indices = beam_indices[cond]
  16. var_indices = var_indices[cond]
  17.  
  18. return nbest_score, beam_indices, var_indices
项目:ADEM    作者:mike-n-7    | 项目源码 | 文件源码
  1. def tfidf_retrieval(tfidf_vec, train_contexts_txt, train_responses_txt, output_file):
  2. print type(tfidf_vec)
  3. tfidf_vec = tfidf_vec.toarray()
  4. print tfidf_vec.shape
  5. prod_mat = np.dot(tfidf_vec, tfidf_vec.T)
  6. print prod_mat.shape
  7. prod_mat = prod_mat / mat_vector_2norm_squared(tfidf_vec)
  8. print prod_mat.shape
  9.  
  10. response_list = []
  11. for i in xrange(len(prod_mat)):
  12. row = prod_mat[i]
  13. # No idea what''s going on here. See the following page:
  14. # stackoverflow.com/questions/6910641/how-to-get-indices-of-n-maximum-values-in-a-numpy-array
  15. ind = np.argpartition(row, -2)[-2:]
  16. ind = ind[np.argsort(row[ind])][0]
  17. response_list.append(train_responses_txt[ind])
  18. print train_contexts_txt[i]
  19. print response_list[i]
  20.  
  21. with open(output_file, ''w'') as f1:
  22. for response in response_list:
  23. f1.write(response)
项目:workspace    作者:nojima    | 项目源码 | 文件源码
  1. def visualize_frequent_words(vectors_2d: np.ndarray, dataset: DataSet, ax: plt.Axes = None) -> None:
  2. word_ids, counts = np.unique(dataset.data, return_counts=True)
  3.  
  4. indices = np.argpartition(-counts, k)[:k]
  5. frequent_word_ids = word_ids[indices]
  6.  
  7. if ax is None:
  8. fig, ax = plt.subplots(figsize=(13, 13))
  9. else:
  10. fig = None
  11.  
  12. vectors_2d = vectors_2d[frequent_word_ids]
  13.  
  14. ax.scatter(vectors_2d[:, 0], vectors_2d[:, 1], s=2, alpha=0.25)
  15. for i, id in enumerate(frequent_word_ids):
  16. ax.annotate(dataset.vocabulary.to_word(id), (vectors_2d[i, vectors_2d[i, 1]))
  17.  
  18. if fig is not None:
  19. fig.tight_layout()
  20. fig.show()
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_partition_cdtype(self):
  2. d = np.array([(''galahad'', tgt[k])
项目:KanervaCoding    作者:JadenTravnik    | 项目源码 | 文件源码
  1. def GetFeatures(self, data):
  2. closestPrototypesIndxs = []
  3. D = self.layers[0] - (np.array(data)*self.stateScale + self.bias)
  4. D = np.sqrt(sum(D.T**2)) # a bottlenect for sure
  5. indexes = np.argpartition(D, self.c[0], axis=0)[:self.c[0]]
  6.  
  7. for i in range(1,len(self.layers)):
  8. D = np.sum(np.setxor1d(self.layers[i], indexes, True), axis=1)
  9. # phi = np.zeros(self.prototypeList[i])
  10. # phi[indexes] = 1
  11. # D = np.sum(np.logical_xor(self.layers[i],phi),axis=1)
  12. indexes = np.argpartition(D, self.c[i], axis=0)[:self.c[i]]
  13.  
  14.  
  15.  
  16. return indexes
项目:SerpentAI    作者:SerpentAI    | 项目源码 | 文件源码
  1. def process_frame_for_game_play(frame):
  2. """Assumes a grayscale frame"""
  3. histogram = skimage.exposure.histogram(frame[40:])
  4.  
  5. if np.unique(histogram[0]).size < 3:
  6. return None
  7.  
  8. max_indices = np.argpartition(histogram[0], -3)[-3:]
  9.  
  10. for index in sorted(max_indices)[:2]:
  11. frame[frame == index] = 0
  12.  
  13. threshold = skimage.filters.threshold_otsu(frame[40:])
  14. bw_frame = frame > threshold
  15.  
  16. return bw_frame
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_partition_cdtype(self):
  2. d = np.array([(''galahad'', tgt[k])
项目:youtube-8m    作者:wangheda    | 项目源码 | 文件源码
  1. def format_lines(video_ids, top_k):
  2. batch_size = len(video_ids)
  3. for video_index in range(batch_size):
  4. top_indices = numpy.argpartition(predictions[video_index], -top_k)[-top_k:]
  5. line = [(class_index, predictions[video_index][class_index])
  6. for class_index in top_indices]
  7. # print("Type - Test :")
  8. # print(type(video_ids[video_index]))
  9. # print(video_ids[video_index].decode(''utf-8''))
  10. line = sorted(line, key=lambda p: -p[1])
  11. yield video_ids[video_index].decode(''utf-8'') + "," + " ".join("%i %f" % pair
  12. for pair in line) + "\\n"
项目:youtube-8m    作者:wangheda    | 项目源码 | 文件源码
  1. def calculate_precision_at_equal_recall_rate(predictions, actuals):
  2. """Performs a local (numpy) calculation of the PERR.
  3.  
  4. Args:
  5. predictions: Matrix containing the outputs of the model.
  6. Dimensions are ''batch'' x ''num_classes''.
  7. actuals: Matrix containing the ground truth labels.
  8. Dimensions are ''batch'' x ''num_classes''.
  9.  
  10. Returns:
  11. float: The average precision at equal recall rate across the entire batch.
  12. """
  13. aggregated_precision = 0.0
  14. num_videos = actuals.shape[0]
  15. for row in numpy.arange(num_videos):
  16. num_labels = int(numpy.sum(actuals[row]))
  17. top_indices = numpy.argpartition(predictions[row],
  18. -num_labels)[-num_labels:]
  19. item_precision = 0.0
  20. for label_index in top_indices:
  21. if predictions[row][label_index] > 0:
  22. item_precision += actuals[row][label_index]
  23. item_precision /= top_indices.size
  24. aggregated_precision += item_precision
  25. aggregated_precision /= num_videos
  26. return aggregated_precision
项目:youtube-8m    作者:wangheda    | 项目源码 | 文件源码
  1. def top_k_triplets(predictions, k=20):
  2. """Get the top_k for a 1-d numpy array. Returns a sparse list of tuples in
  3. (prediction,class) format"""
  4. m = len(predictions)
  5. k = min(k, m)
  6. indices = numpy.argpartition(predictions, -k)[-k:]
  7. return [(index, predictions[index], labels[index]) for index in indices]
项目:youtube-8m    作者:wangheda    | 项目源码 | 文件源码
  1. def format_lines(video_ids," + " ".join("%i %f" % pair
  2. for pair in line) + "\\n"
项目:youtube-8m    作者:wangheda    | 项目源码 | 文件源码
  1. def format_lines(video_ids," + " ".join("%i %f" % pair
  2. for pair in line) + "\\n"
项目:youtube-8m    作者:wangheda    | 项目源码 | 文件源码
  1. def calculate_precision_at_equal_recall_rate(predictions,
  2. -num_labels)[-num_labels:]
  3. item_precision = 0.0
  4. for label_index in top_indices:
  5. if predictions[row][label_index] > 0:
  6. item_precision += actuals[row][label_index]
  7. item_precision /= top_indices.size
  8. aggregated_precision += item_precision
  9. aggregated_precision /= num_videos
  10. return aggregated_precision
项目:youtube-8m    作者:wangheda    | 项目源码 | 文件源码
  1. def top_k_triplets(predictions, labels[index]) for index in indices]
项目:youtube-8m    作者:wangheda    | 项目源码 | 文件源码
  1. def format_lines(video_ids," + " ".join("%i %f" % pair
  2. for pair in line) + "\\n"
项目:youtube-8m    作者:wangheda    | 项目源码 | 文件源码
  1. def format_lines(video_ids," + " ".join("%i %f" % pair
  2. for pair in line) + "\\n"
项目:youtube-8m    作者:wangheda    | 项目源码 | 文件源码
  1. def format_lines(video_ids," + " ".join("%i %f" % pair
  2. for pair in line) + "\\n"
项目:youtube-8m    作者:wangheda    | 项目源码 | 文件源码
  1. def calculate_precision_at_equal_recall_rate(predictions,
  2. -num_labels)[-num_labels:]
  3. item_precision = 0.0
  4. for label_index in top_indices:
  5. if predictions[row][label_index] > 0:
  6. item_precision += actuals[row][label_index]
  7. item_precision /= top_indices.size
  8. aggregated_precision += item_precision
  9. aggregated_precision /= num_videos
  10. return aggregated_precision
项目:youtube-8m    作者:wangheda    | 项目源码 | 文件源码
  1. def top_k_triplets(predictions, labels[index]) for index in indices]
项目:youtube-8m    作者:wangheda    | 项目源码 | 文件源码
  1. def format_lines(video_ids, predictions[video_index][class_index])
  2. for class_index in top_indices]
  3. line = sorted(line," + " ".join("%i %f" % pair
  4. for pair in line) + "\\n"
项目:wmd-relax    作者:src-d    | 项目源码 | 文件源码
  1. def __call__(self, words, weights, vocabulary_max):
  2. if len(words) < vocabulary_max * self.trigger_ratio:
  3. return words, weights
  4.  
  5. if not isinstance(words, numpy.ndarray):
  6. words = numpy.array(words)
  7.  
  8. # Tail optimization does not help with very large vocabularies
  9. if len(words) > vocabulary_max * 2:
  10. indices = numpy.argpartition(weights, len(weights) - vocabulary_max)
  11. indices = indices[-vocabulary_max:]
  12. words = words[indices]
  13. weights = weights[indices]
  14. return words, weights
  15.  
  16. # Vocabulary typically consists of these three parts:
  17. # 1) the core - we found it''s border - `core_end` - 15%
  18. # 2) the body - 70%
  19. # 3) the minor tail - 15%
  20. # (1) and (3) are roughly the same size
  21. # (3) can be safely discarded,(2) can be discarded with care,
  22. # (1) shall never be discarded.
  23.  
  24. sorter = numpy.argsort(weights)[::-1]
  25. weights = weights[sorter]
  26. trend_start = int(len(weights) * 0.2)
  27. trend_finish = int(len(weights) * 0.8)
  28. z = numpy.polyfit(numpy.arange(trend_start, trend_finish),
  29. numpy.log(weights[trend_start:trend_finish]),
  30. 1)
  31. exp_z = numpy.exp(z[1] + z[0] * numpy.arange(len(weights)))
  32. avg_error = numpy.abs(weights[trend_start:trend_finish] -
  33. exp_z[trend_start:trend_finish]).mean()
  34. tail_size = numpy.argmax((numpy.abs(weights - exp_z) < avg_error)[::-1])
  35. weights = weights[:-tail_size][:vocabulary_max]
  36. words = words[sorter[:-tail_size]][:vocabulary_max]
  37.  
  38. return words, weights

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 模块-argpartition() 实例源码python numpy.arange的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于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 ()、数组基本属性的相关知识,请在本站寻找。

本文标签: