numpy.argsort

Here are the examples of the python api numpy.argsort taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: orange
Source File: utils.py
View license
def uniform_linear_layout(points):
    """Layout the points (a list of floats in 0..1 range) in a uniform
    linear space while preserving the existing sorting order.

    """
    indices = numpy.argsort(points)
    space = numpy.asarray(linspace(len(points)))

    # invert the indices
    indices = invert_permutation_indices(indices)
#    assert((numpy.argsort(points) == numpy.argsort(space[indices])).all())
    points = space[indices]

    return points.tolist()

Example 2

Project: lhcb_trigger_ml
Source File: fasttree.py
View license
    @staticmethod
    def compute_best_splits(data, y, sample_weight):
        y_order = numpy.argsort(numpy.argsort(y))
        # converting to [-1, 1]
        y_order = numpy.linspace(-1, 1, len(y_order))[y_order]
        orders = numpy.argsort(data, axis=0)
        # answers = y[orders]
        pred_orders = y_order[orders]
        weights = sample_weight[orders]
        left_sum, right_sum = _compute_cumulative_sums(pred_orders * weights)

        left_weights, right_weights = _compute_cumulative_sums(weights + 1e-50)
        regularization = 0.01 * numpy.sum(sample_weight)
        # mean = 0, var = left_weights * right_weights
        costs = - numpy.abs(left_sum) / len(y)
        costs /= numpy.sqrt((left_weights + regularization) * (right_weights + regularization))
        return _compute_cuts_costs_positions(costs, data=data, orders=orders)

Example 3

Project: lhcb_trigger_ml
Source File: fasttree.py
View license
    @staticmethod
    def compute_best_splits(data, y, sample_weight):
        y_order = numpy.argsort(numpy.argsort(y))
        # converting to [-1, 1]
        y_order = numpy.linspace(-1, 1, len(y_order))[y_order]
        orders = numpy.argsort(data, axis=0)
        # answers = y[orders]
        pred_orders = y_order[orders]
        weights = sample_weight[orders]
        left_sum, right_sum = _compute_cumulative_sums(pred_orders * weights)

        left_weights, right_weights = _compute_cumulative_sums(weights + 1e-50)
        regularization = 0.01 * numpy.sum(sample_weight)
        # mean = 0, var = left_weights * right_weights
        costs = - numpy.abs(left_sum) / len(y)
        costs /= numpy.sqrt((left_weights + regularization) * (right_weights + regularization))
        return _compute_cuts_costs_positions(costs, data=data, orders=orders)

Example 4

Project: chainer
Source File: transpose.py
View license
    def backward(self, inputs, grad_outputs):
        gy = grad_outputs[0]
        inv_axes = self.axes
        if self.axes:
            axes = tuple(ax % len(self.axes) for ax in self.axes)
            inv_axes = tuple(numpy.argsort(axes))
        gx = gy.transpose(inv_axes)
        return gx,

Example 5

Project: forgi
Source File: cg_to_fornac.py
View license
def reorder_structs(pair_bitmaps):
    '''
    Order the structures according to their first PC as evaluated
    on the bitmap of the pairs.

    @param pair_bitmaps: An array of length n, corresponding to each potentially
        adjacent pair. 1 if that pair is adjacent, 0 if not.
    @return: An array indicating the new ordering of the structures.
    '''
    from sklearn.decomposition import PCA
    pca = PCA(n_components=1)
    one_d_bitmaps = pca.fit_transform(pair_bitmaps)[:,0]

    ix = np.argsort(one_d_bitmaps)
    return ix

Example 6

Project: attention-lvcsr
Source File: sort.py
View license
    def perform(self, node, inputs, output_storage):
        a = inputs[0]
        axis = inputs[1]
        z = output_storage[0]
        z[0] = theano._asarray(np.argsort(a, axis, self.kind, self.order),
                               dtype=node.outputs[0].dtype)

Example 7

Project: tensorflow-resnet
Source File: convert.py
View license
def print_prob(prob):
    #print prob
    pred = np.argsort(prob)[::-1]

    # Get top1 label
    top1 = synset[pred[0]]
    print "Top1: ", top1
    # Get top5 label
    top5 = [synset[pred[i]] for i in range(5)]
    print "Top5: ", top5
    return top1

Example 8

Project: visual-concepts
Source File: cap_eval_utils.py
View license
def compute_precision_score_mapping(thresh, prec, score):
  ind = np.argsort(thresh);
  thresh = thresh[ind];
  prec = prec[ind];
  for i in xrange(1, len(prec)):
    prec[i] = max(prec[i], prec[i-1]);
  
  indexes = np.unique(thresh, return_index=True)[1]
  indexes = np.sort(indexes);
  thresh = thresh[indexes]
  prec = prec[indexes]
  
  thresh = np.vstack((min(-1000, min(thresh)-1), thresh[:, np.newaxis], max(1000, max(thresh)+1)));
  prec = np.vstack((prec[0], prec[:, np.newaxis], prec[-1]));
  
  f = interp1d(thresh[:,0], prec[:,0])
  val = f(score)
  return val

Example 9

Project: glove-theano
Source File: utils.py
View license
def evaluate(word):
    ind = vocab[word]
    wordvec = W_norm[ind, :]
    dist = [distance.cosine(wordvec, vec) for vec in W_norm]
    indices = np.argsort(dist)
    closest_words = [vocab_i2w[ind] for ind in indices]
    closest_words = closest_words[1:10]
    print closest_words

Example 10

Project: GPy
Source File: pca.py
View license
    def __init__(self, X):
        self.mu = None
        self.sigma = None

        X = self.center(X)

        # self.X = input
        if X.shape[0] >= X.shape[1]:
            # print "N >= D: using primal"
            self.eigvals, self.eigvectors = self._primal_eig(X)
        else:
            # print "N < D: using dual"
            self.eigvals, self.eigvectors = self._dual_eig(X)
        self.sort = numpy.argsort(self.eigvals)[::-1]
        self.eigvals = self.eigvals[self.sort]
        self.eigvectors = self.eigvectors[:, self.sort]
        self.fracs = self.eigvals / self.eigvals.sum()
        self.Q = self.eigvals.shape[0]

Example 11

View license
def print_prob(prob):
    synset = class_names
    # print prob
    pred = np.argsort(prob)[::-1]
    # Get top1 label
    top1 = synset[pred[0]]
    print("Top1: ", top1, prob[pred[0]])
    # Get top5 label
    top5 = [(synset[pred[i]], prob[pred[i]]) for i in range(5)]
    print("Top5: ", top5)
    return top1

Example 12

Project: PyParticles
Source File: pseudo_bubble.py
View license
    def update_force( self , pset ):

        self.__Ix[:] = np.argsort( pset.X[:,0] )

        

        self.__occ.X_cla.set( self.__occ.dtype( pset.X ) , queue=self.__occ.CL_queue )
        self.__occ.get_by_name("Ix").set( self.__Ix , queue=self.__occ.CL_queue )
        
        self.__cl_program.pseudo_bubble( self.__occ.CL_queue , ( self.__size , ) , None ,
                                         self.__occ.X_cla.data ,
                                         self.__occ.M_cla.data ,
                                         self.__R ,
                                         self.__B ,
                                         self.__occ.A_cla.data )

        self.__occ.A_cla.get( self.__occ.CL_queue , self.__A )
                
        return self.__A

Example 13

Project: postpic
Source File: particles.py
View license
    def quantile(self, func, q, weights=1.0):
        '''
        The qth-quantile of the distribution.
        '''
        if q < 0 or q > 1:
            raise ValueError('Quantile q ({:}) must be in range [0, 1]'.format(q))
        w = self.weight() * weights
        data = func(self)
        sortidx = np.argsort(data)
        wcs = np.cumsum(w[sortidx])
        idx = np.searchsorted(wcs, wcs[-1]*np.asarray(q))
        return data[sortidx[idx]]

Example 14

Project: theano-bpr
Source File: bpr.py
View license
    def top_predictions(self, user_index, topn=10):
        """
          Returns the item indices of the top predictions
          for `user_index`. The number of predictions to return
          can be set via `topn`.
          This won't return any of the items associated with `user_index`
          in the training set.
        """
        return [ 
            item_index for item_index in numpy.argsort(self.predictions(user_index)) 
            if item_index not in self._train_dict[user_index]
        ][::-1][:topn]

Example 15

Project: pims
Source File: base_frames.py
View license
def _drop(get_frame, expected_axes, to_drop):
    # sort axes in descending order for correct function of np.take
    to_drop_inds = [list(expected_axes).index(a) for a in to_drop]
    indices = np.argsort(to_drop_inds)
    axes = [to_drop_inds[i] for i in reversed(indices)]
    to_drop = [to_drop[i] for i in reversed(indices)]
    result_axes = [a for a in expected_axes if a not in to_drop]

    def get_frame_dropped(**ind):
        result = get_frame(**ind)
        for (ax, name) in zip(axes, to_drop):
            result = np.take(result, ind[name], axis=ax)
        return result
    return get_frame_dropped, result_axes

Example 16

Project: dionis
Source File: dionis.py
View license
    def get_top_features(self, top = 10, clf_i = 0, top_features = {}):
        group = self.pickler.load('classifiers_' + str(clf_i))
        for i, clf in enumerate(group):
            args = np.argsort(clf.feature_importances_)[-top:][::-1]
            for arg in args:
                if arg not in top_features:
                    top_features[arg] = 1
                else:
                    top_features[arg] += 1
        print 'Best features and occurences:'
        print sorted(top_features.items(), key=lambda x: x[1], reverse = True)
        return top_features

Example 17

Project: tvb-library
Source File: connectivity.py
View license
    def _reorder_arrays(self, new_weights, interest_areas, new_tracts=None):
        """
        Returns ordered versions of the parameters according to the hemisphere permutation.
        """
        permutation = self.hemisphere_order_indices
        inverse_permutation = numpy.argsort(permutation)  # trick to invert a permutation represented as an array
        interest_areas = inverse_permutation[interest_areas]
        # see :meth"`ordered_weights` for why [p:][:p]
        new_weights = new_weights[inverse_permutation, :][:, inverse_permutation]

        if new_tracts is not None:
            new_tracts = new_tracts[inverse_permutation, :][:, inverse_permutation]

        return new_weights, interest_areas, new_tracts

Example 18

View license
def SortEigenDecomposition(e, v):
  if v.ndim < 2:
    return e, v
  else:
    perm = np.argsort(e, -1)
    return np.take(e, perm, -1), np.take(v, perm, -1)

Example 19

Project: pyBAST
Source File: wd.py
View license
    def plot_rez(self, hack=False):
        cla()
        x = [v['pos'][0][0] for k,v in self.rez.iteritems()]
        t = [float(v['observation time (day)']) for k,v in self.rez.iteritems()]
        tt = list(np.argsort(t))
        x = list(np.array(x)[tt])
        t = list(np.array(t)[tt])
        
        mint = min(t) ; maxt = max(t)
        c = [(y - mint)/(maxt - mint) for y in t]
        if hack:
            for i in x:
                i.E[0][0] = i.E[0][0]**2
                i.E[1][1] = i.E[1][1]**2
        
        draw_objects(x,colors=c,label=True,replot=True,show=False)
        xlim(-1.5,1.5)
        ylim(-1.5,1.5)

Example 20

Project: verif
Source File: Metric.py
View license
   def _computeObsFcst(self, obs, fcst):
      N = len(obs)
      # Compute obs quantiles
      Iobs = np.array(np.argsort(obs), 'float')
      qobs = Iobs / N

      # Compute the quantiles that the forecasts are relative
      # to the observations
      qfcst = np.zeros(N, 'float')
      sortobs = np.sort(obs)
      for i in range(0, N):
         I = np.where(fcst[i] < sortobs)[0]
         if(len(I) > 0):
            qfcst[i] = float(I[0]) / N
         else:
            qfcst[i] = 1
      return np.mean(abs(qfcst - qobs))

Example 21

Project: socialsent
Source File: graph_construction.py
View license
def similarity_matrix(embeddings, arccos=False, similarity_power=1, nn=25, **kwargs):
    """
    Constructs a similarity matrix from embeddings.
    nn argument controls the degree.
    """
    def make_knn(vec, nn=nn):
        vec[vec < vec[np.argsort(vec)[-nn]]] = 0
        return vec
    L = embeddings.m.dot(embeddings.m.T)
    if sparse.issparse(L):
        L = L.todense()
    if arccos:
        L = np.arccos(np.clip(-L, -1, 1))/np.pi
    else:
        L += 1
    np.fill_diagonal(L, 0)
    L = np.apply_along_axis(make_knn, 1, L)
    return L ** similarity_power

Example 22

Project: anet2016-cuhk
Source File: demo_server.py
View license
def build_cls_ret(scores, k):
    idx = np.argsort(scores)[::-1]

    top_k_results = []
    for i in xrange(k):
        k = idx[i]
        top_k_results.append({
            'name': lb_list[k],
            'score': str(scores[k])
        })

    return top_k_results

Example 23

Project: icu_rnn
Source File: evaluation.py
View license
def precision_at_k(Y_hats, Y_test, k):
    rows,cols = Y_hats.shape
    ranks = np.argsort(-1 * Y_hats, axis=1)
    numerator = 0.
    for i in xrange(rows):
        for j in xrange(k):
            numerator += Y_test[i, ranks[i,j]]

    p10 = numerator*1.0 / (rows * k)

    best_p10 = Y_test.sum()*1.0 / (rows*k)

    return p10, best_p10

Example 24

Project: orange3-text
Source File: base.py
View license
    @staticmethod
    def add_features(corpus, X, dictionary, compute_values=None):
        order = np.argsort([dictionary[i] for i in range(len(dictionary))])
        compute_values = np.array(compute_values)[order]
        corpus.extend_attributes(X[:, order],
                                 feature_names=(dictionary[i] for i in order),
                                 var_attrs={'hidden': True, 'skip-normalization': True},
                                 compute_values=compute_values)
        corpus.ngrams_corpus = matutils.Sparse2Corpus(X.T)

Example 25

Project: tensorlayer
Source File: tutorial_vgg19.py
View license
def print_prob(prob):
    synset = class_names
    # print prob
    pred = np.argsort(prob)[::-1]
    # Get top1 label
    top1 = synset[pred[0]]
    print("Top1: ", top1, prob[pred[0]])
    # Get top5 label
    top5 = [(synset[pred[i]], prob[pred[i]]) for i in range(5)]
    print("Top5: ", top5)
    return top1

Example 26

Project: online-hdp
Source File: onlinehdp.py
View license
    def optimal_ordering(self):
        """
        ordering the topics
        """
        idx = [i for i in reversed(np.argsort(self.m_lambda_sum))]
        self.m_varphi_ss = self.m_varphi_ss[idx]
        self.m_lambda = self.m_lambda[idx,:]
        self.m_lambda_sum = self.m_lambda_sum[idx]
        self.m_Elogbeta = self.m_Elogbeta[idx,:]

Example 27

Project: facerec
Source File: validation.py
View license
def shuffle(X, y):
    """ Shuffles two arrays by column (len(X) == len(y))
        
        Args:
        
            X [dim x num_data] input data
            y [1 x num_data] classes

        Returns:

            Shuffled input arrays.
    """
    idx = np.argsort([random.random() for i in range(len(y))])
    y = np.asarray(y)
    X = [X[i] for i in idx]
    y = y[idx]
    return (X, y)

Example 28

Project: barrista
Source File: visualize.py
View license
def _sorted_ar(inf, key):
    iters = []
    vals = []
    for values in inf:
        if values.has_key(key):
            iters.append(int(values['NumIters']))
            vals.append(float(values[key]))
    sortperm = np.argsort(iters)
    arr = np.array([iters, vals]).T
    return arr[sortperm, :]

Example 29

Project: aetros-cli
Source File: JobModel.py
View license
    def predict(self, model, input):
        prediction = model.predict(input)

        top5 = np.argsort(-prediction[0])[:5]

        result = []
        for i in top5:
            result.append({
                'class': self.get_dataset_class_label(self.get_first_output_layer(), i),
                'prediction': float(prediction[0][i])
            })

        return result

Example 30

Project: cvxpy
Source File: sum_largest.py
View license
    def _grad(self, values):
        """Gives the (sub/super)gradient of the atom w.r.t. each argument.

        Matrix expressions are vectorized, so the gradient is a matrix.

        Args:
            values: A list of numeric values for the arguments.

        Returns:
            A list of SciPy CSC sparse matrices or None.
        """
        # Grad: 1 for each of k largest indices.
        value = intf.from_2D_to_1D(values[0].flatten().T)
        indices = np.argsort(-value)[:int(self.k)]
        D = np.zeros((self.args[0].size[0]*self.args[0].size[1], 1))
        D[indices] = 1
        return [sp.csc_matrix(D)]

Example 31

Project: mindpark
Source File: histogram.py
View license
    def __call__(self, ax, domain, count):
        assert len(domain) == len(count)
        assert domain[0] < domain[-1]
        ax.set_axis_bgcolor(cm.get_cmap('viridis')(0))
        order = np.argsort(domain)
        domain, count = domain[order], count[order]
        resolution = min(len(domain), self._resolution)
        borders = np.linspace(domain[0], domain[-1], resolution)
        borders = np.digitize(borders, domain)
        groups = aggregate(count, borders, lambda x: np.mean(x, axis=0))
        self._plot_grid(ax, domain[borders - 1], groups)
        ax.set_yticks(np.arange(count.shape[1]))

Example 32

Project: energywise
Source File: plotter_new.py
View license
def gen_peaks(d, num_peaks = 3):
    """A generatore that yields the index of the highest peaks.
       
    Parameters:
    d -- The building record.
    num_peaks -- The number of peaks to be yielded.
    """
    kwhs, kwhs_oriflag   = d["kwhs"]
    
    inds = np.argsort(kwhs)[-num_peaks:]
    for ind in inds:
        yield ind

Example 33

View license
def print_top_words(vectorizer, clf, class_labels, n=10):
    """Prints features with the highest coefficient values, per class"""
    feature_names = vectorizer.get_feature_names()
    for i, class_label in enumerate(class_labels):
        topn = np.argsort(clf.coef_[i])[-n:]
        print("%s: %s" % (class_label,
              " ".join(feature_names[j] for j in topn)))

Example 34

Project: minirank
Source File: metrics.py
View license
def pairwise_disagreement(y_true, y_pred):
    """
    Number of pairwise inversions in a totally ordered 
    linear list. 
    """
    comb = itertools.combinations(range(y_true.size), 2)
    count = 0
    diff = 0.
    idx = np.argsort(y_true)
    y_pred = y_pred[idx]
    for (i, j) in comb:
        count += 1
        assert i < j
        if y_pred[i] >= y_pred[j]:
            diff += 1
    return diff / count

Example 35

View license
    def predict(self, covtest):
        """get the predictions.

        Parameters
        ----------
        X : ndarray, shape (n_trials, n_channels, n_channels)
            ndarray of SPD matrices.

        Returns
        -------
        pred : ndarray of int, shape (n_trials, 1)
            the prediction for each trials according to the closest centroid.
        """
        dist = self._predict_distances(covtest)
        neighbors_classes = self.classes_[numpy.argsort(dist)]
        out, _ = stats.mode(neighbors_classes[:, 0:self.n_neighbors], axis=1)
        return out.ravel()

Example 36

View license
    def force_partition(self, char_images):
        widths = []
        for image in char_images:
            widths.append(image.shape[1])
        # The part with the largest width needs to be separate further
        target_index = np.argsort(widths)[-1]
        target_img = char_images[target_index]
        del char_images[target_index]
        width = target_img.shape[1]
        if width % 2 == 1:
            char_images.insert(target_index, target_img[:, 0:(width + 1) / 2])
            char_images.insert(target_index + 1,
                               target_img[:, (width - 1) / 2:])
        else:
            char_images.insert(target_index, target_img[:, 0:width / 2 + 1])
            char_images.insert(target_index + 1, target_img[:, width / 2 - 1:])
        return char_images

Example 37

Project: trees
Source File: malware.py
View license
def visualizedistances(data, figname=None):
    D, L, N = data
    sorted_indexes = np.argsort(L[:,0])

    D2 = D[sorted_indexes, :]
    D2 = D2[:, sorted_indexes]

    plt.cla()
    plt.clf()
    plt.close()

    plt.imshow(D2, cmap=plt.cm.gray)
    plt.title('Distance matrix')
    plt.savefig(figname, bbox_inches='tight')

Example 38

Project: CorEx
Source File: corex.py
View license
    def sort_and_output(self):
        order = np.argsort(self.tcs)[::-1]  # Order components from strongest TC to weakest
        self.tcs = self.tcs[order]  # TC for each component
        self.alpha = self.alpha[order]  # Connections between X_i and Y_j
        self.p_y_given_x = self.p_y_given_x[order]  # Probabilistic labels for each sample
        self.log_marg = self.log_marg[order]  # Parameters defining the representation
        self.log_p_y = self.log_p_y[order]  # Parameters defining the representation
        self.log_z = self.log_z[order]  # -log_z can be interpreted as "surprise" for each sample
        if hasattr(self, 'mis'):
            self.mis = self.mis[order]

Example 39

Project: corex_topic
Source File: corex_topic.py
View license
    def sort_and_output(self, X):
        order = np.argsort(self.tcs)[::-1]  # Order components from strongest TC to weakest
        self.tcs = self.tcs[order]  # TC for each component
        self.alpha = self.alpha[order]  # Connections between X_i and Y_j
        self.log_p_y = self.log_p_y[order]  # Parameters defining the representation
        self.theta = self.theta[:, :, order]  # Parameters defining the representation

Example 40

Project: metric-learn
Source File: sandwich.py
View license
def visualize_class_separation(X, labels):
  _, (ax1,ax2) = plt.subplots(ncols=2)
  label_order = np.argsort(labels)
  ax1.imshow(pairwise_distances(X[label_order]), interpolation='nearest')
  ax2.imshow(pairwise_distances(labels[label_order,None]),
             interpolation='nearest')

Example 41

Project: snorkel
Source File: matcher_utils.py
View license
def tag_seqs(words, seqs, tags):
  """
  Given a list of words, a *list* of lists of indexes, and the corresponding tags
  This function substitutes the tags for the words coresponding to the index lists,
  taking care of shifting indexes appropriately after multi-word substitutions
  NOTE: this assumes non-overlapping seqs!
  """
  words_out = words
  dj = 0
  for i in np.argsort(seqs, axis=0):
    i = int(i[0]) if hasattr(i, '__iter__') else int(i)
    words_out = tag_seq(words_out, map(lambda j : j - dj, seqs[i]), tags[i])
    dj += len(seqs[i]) - 1
  return words_out

Example 42

Project: Kayak
Source File: matrix_ops.py
View license
    def _local_grad(self, parent, d_out_d_self):
        diff = lambda A, B : [a for a in A if a not in B]
        rank = lambda L : list(np.argsort(np.argsort(L)))
        val = [p.value for p in self._parents]
        axes = self.axes
        n_axes = len(axes[0])
        ignore_dims = [diff(range(val[i].ndim), axes[i]) for i in (0, 1)]
        ignore_ndims = [len(x) for x in ignore_dims]
        output_dims = (range(ignore_ndims[0]),
                       range(ignore_ndims[0], ignore_ndims[0] + ignore_ndims[1]))
        X, Y = parent, 1 - parent
        wrong_order = np.tensordot(val[Y], d_out_d_self, (ignore_dims[Y], output_dims[Y]))
        permutation = [None] * val[X].ndim
        for final, cur in zip(list(axes[X]) + ignore_dims[X],
                              rank(axes[Y]) + range(n_axes, val[X].ndim)):
            permutation[final] = cur

        return np.transpose(wrong_order, permutation)

Example 43

Project: pgmult
Source File: ctm.py
View license
def plot_sb_interpretable_results(sb_results, words):
    nwords = 5
    Sigma = sb_results[-1][-1]
    T = Sigma.shape[0]

    def get_topwords(topic):
        return words[np.argsort(sb_results[-1][0][:,topic])[-nwords:]]

    lim = np.abs(Sigma).max()
    plt.imshow(np.kron(Sigma,np.ones((50,50))), extent=(0,T,T,0), vmin=-lim, vmax=lim,
               cmap='RdBl')
    plt.colorbar()

    for t in range(T):
        print('Topic %d:' % t)
        print(get_topwords(t))
        print()

Example 44

Project: retrieval-2016-deepvision
Source File: rerank.py
View license
    def write_rankings(self,query,ranking,distances):

        if self.class_scores:
            new_top_r = list(np.array(ranking[0:self.top_n])[np.argsort(distances)[::-1]])
        else:
            new_top_r = list(np.array(ranking[0:self.top_n])[np.argsort(distances)])

        ranking[0:self.top_n] = new_top_r


        savefile = open(os.path.join(self.rankings_dir,os.path.basename(query.split('_query')[0]) +'.txt'),'w')

        for res in ranking:

            savefile.write(os.path.basename(res).split('.jpg')[0] + '\n')

        savefile.close()

Example 45

Project: Foxhound
Source File: iterators.py
View license
    def iterXY(self, X, Y):
        
        if self.shuffle:
            X, Y = shuffle(X, Y)

        for x_chunk, y_chunk in iter_data(X, Y, size=self.size*20):
            sort = np.argsort([len(x) for x in x_chunk])
            x_chunk = [x_chunk[idx] for idx in sort]
            y_chunk = [y_chunk[idx] for idx in sort]
            mb_chunks = [[x_chunk[idx:idx+self.size], y_chunk[idx:idx+self.size]] for idx in range(len(x_chunk))[::self.size]]
            py_rng.shuffle(mb_chunks)
            for xmb, ymb in mb_chunks:
                xmb = self.trXt(xmb)
                ymb = self.trYt(ymb)
                yield xmb, ymb

Example 46

Project: Passage
Source File: iterators.py
View license
    def iterXY(self, X, Y):
        
        if self.shuffle:
            X, Y = shuffle(X, Y)

        for x_chunk, y_chunk in iter_data(X, Y, size=self.size*20):
            sort = np.argsort([len(x) for x in x_chunk])
            x_chunk = [x_chunk[idx] for idx in sort]
            y_chunk = [y_chunk[idx] for idx in sort]
            mb_chunks = [[x_chunk[idx:idx+self.size], y_chunk[idx:idx+self.size]] for idx in range(len(x_chunk))[::self.size]]
            mb_chunks = shuffle(mb_chunks)
            for xmb, ymb in mb_chunks:
                xmb = padded(xmb)
                yield self.x_dtype(xmb), self.y_dtype(ymb)  

Example 47

Project: topic-explorer
Source File: cluster.py
View license
    def combine(self):
        """
        Merges the topic-word matric from multiple topic models.
        """
        if len(self.topic_range) < 1:
            raise IndexError("No topic range")
        else:
            keys = self.model_v.keys()
            return np.vstack(self.model_v[keys[i]].phi.T 
                for i in np.argsort(keys))
            """

Example 48

Project: pyParticleEst
Source File: filter.py
View license
    def find_best_particles(self, n=1):
        """
        Return particles with largest weights

        Args:
         - n (int): Number of particles to return

        Returns:
         - (array-like) with len=n, representing the n most likely estimates """
        indices = numpy.argsort(self.w)
        return indices[range(n)]

Example 49

Project: RSTParser
Source File: model.py
View license
    def predict(self, features):
        """ Predict parsing actions for a given set
            of features

        :type features: list
        :param features: feature list generated by
                         FeatureGenerator
        """
        vec = vectorize(features, self.vocab)
        predicted_output = self.clf.decision_function(vec)
        idxs = np.argsort(predicted_output[0])[::-1]
        possible_labels = []
        for index in idxs:
            possible_labels.append(self.labelmap[index])
        return possible_labels

Example 50

Project: scikit-feature
Source File: fisher_score.py
View license
def feature_ranking(score):
    """
    Rank features in descending order according to fisher score, the larger the fisher score, the more important the
    feature is
    """
    idx = np.argsort(score, 0)
    return idx[::-1]