numpy.argmax

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

177 Examples 7

Example 1

Project: hyperopt-nnet Source File: nnet.py
Function: predict
    def predict(self, X, chunk=256):
        preds = []
        for i in range(0, len(X), chunk):
            t0 = time_module.time()
            Xi = X[i: i + chunk]
            for layer in self.layers:
                Xi = layer(Xi)
            preds.extend(np.argmax(Xi, axis=1))
            t1 = time_module.time()
            if t1 - t0 > .1:
                print 'WARNING: predicting single chunk took', (t1 - t0)
                print 'ETA = %s' % ((len(X) - i) / 256. *  (t1 - t0))
        assert len(preds) == len(X), (len(preds), len(X))
        return preds

Example 2

Project: suiron Source File: functions.py
def cnn_to_raw(y, min_arduino=40.0, max_arduino=150.0):
    # Get highest index value and map
    # it back
    y_ = y[np.argmax(y)]

    # degrees to output
    y_ = arduino_map(y_, 0.0, 1.0, min_arduino, max_arduino)

    return y_

Example 3

Project: treelearn Source File: classifier_ensemble.py
Function: predict
    def predict(self, X, return_probs=False):
        """Every classifier in the ensemble votes for a class. 
           If we're doing stacking, then pass the votes as features into 
           the stacking classifier, otherwise return the majority vote."""
        if self.need_to_fit:
            raise RuntimeError("Trying to call 'predict' before 'fit'")
        
        if self.stacking_model:
            majority_indices = np.argmax(self._predict_stacked_probs(X), axis=1)
        else: 
            majority_indices = np.argmax(self._predict_votes(X), axis=1)        
        return np.array([self.class_list[i] for i in majority_indices])

Example 4

Project: GMM Source File: GMMModel.py
    @classmethod
    def resultPredict(cls, gmmObj, data):
        """
        Get the result of predict
        Return responsibility matrix and cluster labels .
        """
        responsibility_matrix = data.map(lambda m: gmmObj.predict(m))
        cluster_labels = responsibility_matrix.map(lambda b: np.argmax(b))
        return responsibility_matrix, cluster_labels

Example 5

Project: hessianfree Source File: loss_funcs.py
Function: loss
    @output_loss
    def loss(self, output, targets):
        return np.logical_and(np.argmax(output, axis=-1) !=
                              np.argmax(targets, axis=-1),
                              np.logical_not(np.isnan(np.sum(targets,
                                                             axis=-1))))

Example 6

Project: orange Source File: test_svm.py
def multiclass_from1vs1(dec_values, class_var):
    n_class = len(class_var.values)
    votes = [0] * n_class
    p = 0
    for i in range(n_class - 1):
        for j in range(i + 1, n_class):
            val = dec_values[p]
            if val > 0:
                votes[i] += 1
            else:
                votes[j] += 1
            p += 1
    max_i = np.argmax(votes)
    return class_var(int(max_i))

Example 7

Project: apogee Source File: isomodel.py
Function: mode
    def mode(self,jk):
        """
        NAME:
           mode
        PURPOSE:
           return the moden of the M_x distribution at this J-K
        INPUT:
           jk - J-Ks
        OUTPUT:
           mode
        HISTORY:
           2012-11-09 - Written - Bovy (IAS)
        """
        #First calculate the PDF
        xs, lnpdf= self.calc_pdf(jk,nxs=1001)
        return xs[numpy.argmax(lnpdf)]

Example 8

Project: peregrine Source File: tracking.py
  def update_bit_sync(self, corr, ms):
    dot = corr * self.prev_corr
    self.prev_corr = corr
    if dot < 0:
      self.hist[self.bit_phase % 20] += -dot
      self.bit_phase_count += 1
      if self.bit_phase_count == self.thres:
        self.synced = True
        self.bit_phase_ref = np.argmax(self.hist)
        self.hist = np.zeros(20)
        self.bit_phase_count = 0

Example 9

Project: DeepClassificationBot Source File: train.py
def get_top_n_error(preds, y, n):
    index_of_true = np.argmax(y, axis=1)
    index_of_preds = np.argsort(preds, axis=1)
    correct = 0

    for i in range(len(index_of_true)):
        for j in range(1, n + 1):
            if index_of_true[i] == index_of_preds[i, -j]:
                correct = correct + 1
                break

    total = len(y)
    accuracy = correct / total
    return accuracy

Example 10

Project: async-deep-rl Source File: emulator.py
Function: next
    def next(self, action):
        """ Get the next state, reward, and game over signal """
        reward, new_screen_image_rgb = self.action_repeat(np.argmax(action))
        self.screen_images_processed[:, :, 0:3] = \
            self.screen_images_processed[:, :, 1:4]
        self.screen_images_processed[:, :, 3] = self.process_frame_pool()
        self.show_screen(new_screen_image_rgb)
        terminal = self.is_terminal()
        self.lives = self.ale.lives()
        return np.copy(self.screen_images_processed), reward, terminal #get_reshaped_state(), reward, terminal

Example 11

Project: kaggle-heart Source File: utils.py
Function: accuracy
def accuracy(y, t):
    if t.ndim == 2:
        t = np.argmax(t, axis=1)

    predictions = np.argmax(y, axis=1)
    return np.mean(predictions == t)

Example 12

Project: deep-learning-samples Source File: assign6.py
Function: character_s
def characters(probabilities):
    """
    Turn a 1-hot encoding or a probability distribution over the possible
    characters back into its (most likely) character representation.
    """
    return [id2char(c) for c in np.argmax(probabilities, 1)]

Example 13

Project: DeepLearning-OCR Source File: util.py
def get_sample_weight(label, whole_set):
	if label.ndim < 3: # in case output_size==1
		return None
	ret = []
	for i in label:
		ret.append([])
		tag = False
		for j in i:
			cha = whole_set[np.argmax(j)]
			weight = 0
			if cha == 'empty' and tag == False:
				weight = 1 # TODO
				tag = True 
			if cha != 'empty':
				weight = 1
			ret[-1].append(weight)
	ret = np.asarray(ret)
	return ret

Example 14

Project: discrete_sieve Source File: remainder.py
def order2(px_y, py):
    k_y, k_x = px_y.shape
    othery = range(k_y)
    topy = othery.pop(np.argmax(py))
    order = np.array([np.arange(k_x) for _ in range(k_y)])
    for j in othery:
        # Try to line up with first one
        best_roll = []
        for dir in [1, -1]:
            for l in range(k_x):
                this_order = np.roll(order[j][::dir], l)
                v = np.sum(np.abs(np.cuemsum(px_y[j, this_order]) - np.cuemsum(px_y[topy])))
                print 'test!', this_order, v, dir
                best_roll.append((v, l, dir))
        best_v, best_l, best_dir = min(best_roll)
        order[j] = np.roll(order[j][::dir], best_l)
    return order

Example 15

Project: statsmodels Source File: util.py
def eigval_decomp(sym_array):
    """
    Returns
    -------
    W: array of eigenvectors
    eigva: list of eigenvalues
    k: largest eigenvector
    """
    #check if symmetric, do not include shock period
    eigva, W = decomp.eig(sym_array, left=True, right=False)
    k = np.argmax(eigva)
    return W, eigva, k

Example 16

Project: kaggle_diabetic_retinopathy Source File: metrics.py
Function: accuracy
def accuracy(y, t):
    if t.ndim == 2:
        t = np.argmax(t, axis=1)
    if y.ndim == 2:
        y = np.argmax(y, axis=1)

    return np.mean(y == t)

Example 17

Project: cloudless Source File: localization.py
def sort_predictions(classes, predictions, bboxes):
    """ Sorts predictions from most probable to least, generate extra metadata about them. """
    results = []
    for idx, pred in enumerate(predictions):
        results.append({
            "class_idx": np.argmax(pred),
            "class": classes[np.argmax(pred)],
            "prob": pred[np.argmax(pred)],
            "fname": get_region_filename(idx),
            "coords": bboxes[idx],
        })
    results.sort(key=itemgetter("prob"), reverse=True)

    return results

Example 18

Project: pymir Source File: Pitch.py
def naivePitch(spectrum):
	"""
	Compute the pitch by using the naive pitch estimation method, i.e. get the pitch name for the most
	prominent frequency.
	Only returns MIDI pitch number
	"""
	maxFrequencyIndex = numpy.argmax(spectrum)
	maxFrequency = maxFrequencyIndex * (spectrum.sampleRate / 2.0) / len(spectrum)
	return frequencyToMidi(maxFrequency)

Example 19

Project: slots Source File: slots.py
Function: best
    def best(self):
        '''
        Return current 'best' choice of bandit.

        Returns
        -------
        int
            Index of bandit
        '''

        if len(self.choices) < 1:
            print('slots: No trials run so far.')
            return None
        else:
            return np.argmax(self.wins/(self.pulls+0.1))

Example 20

Project: assoc-space Source File: __init__.py
    def most_similar_to_vector(self, vec):
        """
        Finds the term most similar to the given vector, returning a
        (term, similarity) tuple. This method is much faster than
        terms_similar_to_vector.
        """
        sim = self.assoc.dot(vec)
        index = np.argmax(sim)
        return self.labels[index], sim[index]

Example 21

Project: PyDataLondon2016 Source File: 5_mlp_q_learning_half_pong_player.py
    def _choose_next_action(self, binary_image):
        if (not self._playback_mode) and (random.random() <= self._probability_of_random_action):
            return random.randrange(self.ACTIONS_COUNT)
        else:
            # let the net choose our action
            output = self._session.run(self._output_layer, feed_dict={self._input_layer: [binary_image]})
            return np.argmax(output)

Example 22

Project: facenet Source File: mnist_center_loss.py
Function: error_rate
def error_rate(predictions, labels):
    """Return the error rate based on dense predictions and sparse labels."""
    return 100.0 - (
        100.0 *
        np.sum(np.argmax(predictions, 1) == labels) /
        predictions.shape[0])

Example 23

Project: Chimp Source File: policies.py
Function: action
    def action(self, obs):
        """
        Returns the actions with the highes Q value given observation obs
        """
        q_vals = self.learner.forward(obs)
        return np.argmax(q_vals)

Example 24

Project: energywise Source File: plotter_new.py
def gen_holidays(d):
    """A generator that yields federal holidays in the timeframe of the building record d (in chronological order)."""
    times = d["times"]
    holidays = yfhol(the_year)
    holidays = holidays.items()
    holinames, holidates = zip(*holidays)
    mymap = dict(zip(holidates, holinames))

    is_midnight     = (lambda x: x.hour == 0)
    days, new_times = get_periods(d, 24, is_midnight, "kwhs")
    for t in new_times:
        date = t[0].date()
        if date in holidates:
            left_side  = np.argmax(times == t[0])
            right_side = np.argmax(times == t[-1])
            
            yield (left_side, right_side), mymap[date]

Example 25

Project: mystic Source File: surface.py
Function: max
    def _max(self):
        import numpy as np
        x = self.x
        z = self.z
        mz = np.argmax(z)
        return x[mz],z[mz]

Example 26

Project: caffe-tensorflow Source File: classify.py
Function: display_results
def display_results(image_paths, probs):
    '''Displays the classification results given the class probability for each image'''
    # Get a list of ImageNet class labels
    with open('imagenet-classes.txt', 'rb') as infile:
        class_labels = map(str.strip, infile.readlines())
    # Pick the class with the highest confidence for each image
    class_indices = np.argmax(probs, axis=1)
    # Display the results
    print('\n{:20} {:30} {}'.format('Image', 'Classified As', 'Confidence'))
    print('-' * 70)
    for img_idx, image_path in enumerate(image_paths):
        img_name = osp.basename(image_path)
        class_name = class_labels[class_indices[img_idx]]
        confidence = round(probs[img_idx, class_indices[img_idx]] * 100, 2)
        print('{:20} {:30} {} %'.format(img_name, class_name, confidence))

Example 27

Project: chaco Source File: datamapper.py
    def _calc_data_extents(self):
        """
        Computes ((minX, minY), (width, height)) of self._data; sets self._extent and
        returns nothing.
        """
        if len(self._data) == 0:
            self._extents = ((0,0), (0,0))
        else:
            value = self._data
            min_indices = argmin(value, axis=0)
            max_indices = argmax(value, axis=0)
            x = value[min_indices[0], 0] - self._extents_delta
            y = value[min_indices[1], 1] - self._extents_delta
            maxX = value[max_indices[0], 0] + self._extents_delta
            maxY = value[max_indices[1], 1] + self._extents_delta
            self._extents = ((x, y), (maxX-x, maxY-y))
        return

Example 28

Project: diagnose-heart Source File: dsb_utils.py
def gaussian_moments_fake(data, normalize_height = False):
    """Returns (height, x, y, width_x, width_y)
    the gaussian parameters of a 2D distribution by calculating its
    moments """
    total = data.sum()
    x,y = np.unravel_index(np.argmax(data), data.shape)
    col = data[:, int(y)]
    width_x = np.sqrt(abs((np.arange(col.size)-y)**2*col).sum()/col.sum())
    row = data[int(x), :]
    width_y = np.sqrt(abs((np.arange(row.size)-x)**2*row).sum()/row.sum())
    height = data.max() if not normalize_height else 1
    width = (width_x + width_y)/2
    return height, x, y, width, width, 0.0

Example 29

Project: EDeN Source File: rna_structure.py
Function: acquisition
    def _acquisition(self, scores, uncertainties,
                     exploration_vs_exploitation_tradeoff=0.1):
        acquisition_vals = \
            [self._acquisition_func(score,
                                    uncertainty,
                                    exploration_vs_exploitation_tradeoff)
             for score, uncertainty in zip(scores, uncertainties)]
        maximal_id = np.argmax(acquisition_vals)
        return maximal_id

Example 30

Project: spectral Source File: classifiers.py
    def classify_spectrum(self, x):
        '''
        Classifies a pixel into one of the trained classes.

        Arguments:

            `x` (list or rank-1 ndarray):

                The unclassified spectrum.

        Returns:

            `classIndex` (int):

                The index for the :class:`~spectral.TrainingClass`
                to which `x` is classified.
        '''
        y = self.input(x)
        return self.indices[np.argmax(y)]

Example 31

Project: BayesianOptimization Source File: tests_helper_functions.py
def brute_force_maximum(MESH, GP, kind='ucb', kappa=1.0, xi=1e-6):
    uf = UtilityFunction(kind=kind, kappa=kappa, xi=xi)

    mesh_vals = uf.utility(MESH, GP, 2)
    max_val = mesh_vals.max()
    max_arg_val = MESH[np.argmax(mesh_vals)]

    return max_val, max_arg_val

Example 32

Project: learning-dl Source File: cnn_ocr.py
Function: accuracy
def Accuracy(label, pred):
    label = label.T.reshape((-1, ))
    hit = 0
    total = 0
    for i in range(pred.shape[0] / 4):
        ok = True
        for j in range(4):
            k = i * 4 + j
            if np.argmax(pred[k]) != int(label[k]):
                ok = False
                break
        if ok:
            hit += 1
        total += 1
    return 1.0 * hit / total

Example 33

Project: IkaLog Source File: start.py
Function: find_best_match
    def find_best_match(self, frame, matchers_list):
        """
        Return stat.ink id (e.g. arowana) or None
        """

        if len(matchers_list) == 0:
            return None

        results = list(map(lambda e:e.match_score(frame), matchers_list))
        match_scores = list(map(lambda e:e[1], results))
        index = np.argmax(match_scores)

        if results[index][0]:
            return  matchers_list[index].id_
        return None

Example 34

Project: tfdeploy Source File: tfdeploy.py
Function: argmax
@Operation.factory
def ArgMax(a, dim):
    """
    Argmax op.
    """
    return np.argmax(a, axis=dim),

Example 35

Project: keraflow Source File: test_objectives.py
Function: test_accuracy
def test_accuracy():
    def cat_acc(y_pred, y_true):
        return np.expand_dims(np.equal(np.argmax(y_pred, axis=-1), np.argmax(y_true, axis=-1)), -1),

    objectives_test(objectives.accuracy,
                    cat_acc,
                    np_pred=[[0,0,.9], [0,.9,0], [.9,0,0]],
                    np_true=[[0,0,1], [0,0,1], [0,0,1]])

    def bi_acc(y_pred, y_true):
        return np.equal(np.round(y_pred), y_true)

    objectives_test(objectives.accuracy,
                    bi_acc,
                    np_pred=[[0], [0.6], [0.7]],
                    np_true=[[0], [1], [1]])

Example 36

Project: kaggle-cifar Source File: combine_pred.py
def evaluate_result( result, text ):
   # pre-condition check
   num_batches = len( result['labels'] )
   assert( num_batches == len(result['labels']) )
   # compute error
   num_cases = 0
   num_wrong = 0
   for ii in range( num_batches ):
     act_index = result['labels'][ii]
     num_cases_ii = act_index.shape[0] 
     assert( num_cases_ii == result['preds'][ii].shape[0] )
     num_cases += num_cases_ii
     pred_index = np.argmax( result['preds'][ii], 1 )
     for jj in range( num_cases_ii ):
        if pred_index[jj] != act_index[jj]:
           num_wrong += 1
   
   print text + "----Testing Error: %2.4f" % ( 1.0 *num_wrong / num_cases )
   return ( 1.0 *num_wrong / num_cases )

Example 37

Project: VQA-Keras-Visual-Question-Answering Source File: train.py
Function: val
def val():
    val_X, val_y, multi_val_y = get_val_data() 
    model = get_model(0.0, model_weights_filename)
    print "Accuracy on validation set:", model.evaluate(val_X, val_y)

    # Comparing prediction against multiple choice answers
    true_positive = 0
    preds = model.predict(val_X)
    pred_classes = [np.argmax(_) for _ in preds]
    for i,_ in enumerate(pred_classes):
        if _ in multi_val_y[i]:
            true_positive += 1
    print np.float(true_positive)/len(pred_classes)

Example 38

Project: pyscf Source File: mo_mapping.py
def mo_1to1map(s):
    '''Given <i|j>, search for the 1-to-1 mapping between i and j.

    Returns:
        a list [j-close-to-i for i in <bra|]
    '''
    s1 = abs(s)
    like_input = []
    for i in range(s1.shape[0]):
        k = numpy.argmax(s1[i])
        like_input.append(k)
        s1[:,k] = 0
    return like_input

Example 39

Project: fizz-buzz-tensorflow Source File: plots.py
Function: ct
def ct(data):
    """
    create a crosstab from the fizz buzz outputs
    """
    lookup = { "fizz" : 1, "buzz" : 2, "fizzbuzz" : 3 }
    grid = [[0 for _ in range(4)] for _ in range(4)]
    for i, output in enumerate(data):
        actual = np.argmax(fizz_buzz_encode(i+1))
        predicted = lookup.get(output, 0)
        grid[predicted][actual] += 1
    return grid

Example 40

Project: EasyTensorflow Source File: tf_functions.py
Function: predict
    def predict(self, teX, return_encoded = True):
        '''
        Uses the trained neural network to classify the samples based on their features.
        :param teX: Numpy array of features to be used for the classification.
        :param return_encoded: Boolean value denoting whether to decode the classifications if needed. Must have
            generated class list by encoding during the training.
        :return: Either encoded or decoded classifications for the input samples as a numpy array or list.
        '''

        # Use the neural network for predicting the classes.
        p = self.sess.run(self.predict_op, feed_dict={self.X: teX})

        # Decodes if desired.
        if not return_encoded:
            p = np.argmax(p, axis=1)
            return decode_classifications(p, self.class_list)

        return p

Example 41

Project: digit-classifier Source File: network.py
Function: predict
    def predict(self, x):
        """Predict the label of a single test example (image).

        Parameters
        ----------
        x : numpy.array

        Returns
        -------
        int
            Predicted label of example (image).

        """

        self._forward_prop(x)
        return np.argmax(self._activations[-1])

Example 42

Project: pyqtgraph Source File: ImageView.py
    def quickMinMax(self, data):
        """
        Estimate the min/max values of *data* by subsampling.
        """
        while data.size > 1e6:
            ax = np.argmax(data.shape)
            sl = [slice(None)] * data.ndim
            sl[ax] = slice(None, None, 2)
            data = data[sl]
        return nanmin(data), nanmax(data)

Example 43

Project: cowc Source File: SimpleSlidingWindowECCV.py
def getNextWindow(temp_p_map, threshold):
    
    p = WinProp()
    
    loc     = np.argmax(temp_p_map)
    p.y     = loc / temp_p_map.shape[1]
    p.x     = loc % temp_p_map.shape[1]
    p.val   = temp_p_map[p.y,p.x]
    
    if p.val > threshold:
        p.have_max = True
    else:
        p.have_max = False
    
    return p

Example 44

Project: refinery Source File: TestGaussObsModel.py
  def test_calc_local_params(self):
    ''' Calc soft assign responsibilities for all data items
        Verify that the items generated by each component are (usually) associated with that component.
    '''
    if self.obsM is None:
      return
    LP = self.obsM.calc_local_params(self.Data)
    lpr = LP['E_log_soft_ev']
    maxIDs = np.argmax(lpr, axis=1)
    for k in range(self.obsM.K):
      currange = range(k*self.nObsC, (k+1)*self.nObsC)
      nMatch = np.sum( maxIDs[currange]==k )
      assert nMatch > 0.95 * self.nObsC

Example 45

Project: semisup-learn Source File: scikitWQDA.py
Function: predict
	def predict(self, X):
		"""Perform classification on samples in X.

		Parameters
		----------
		X : array-like, shape = [n_samples, n_features]

		Returns
		-------
		y_pred : array, shape = [n_samples]
			Class labels for samples in X.
		"""
		return numpy.argmax(self._posterior(X), axis=1)

Example 46

Project: SnapSudoku Source File: train.py
Function: evaluate
    def evaluate(self, test_data):
        """
                Return the number of test inputs for which the neural
                network outputs the correct result. Note that the neural
                network's output is assumed to be the index of whichever
                neuron in the final layer has the highest activation.
        """
        test_results = [(np.argmax(self.feedforward(x)), y)
                        for (x, y) in test_data]
        return sum(int(x == y) for (x, y) in test_results)

Example 47

Project: mlxtend Source File: tf_softmax.py
    def _accuracy(self, y, tf_X, tf_w_, tf_b_):
        logits = tf.nn.softmax(tf.matmul(tf_X, tf_w_) +
                               tf_b_)
        y_pred = np.argmax(logits.eval(), axis=1)
        acc = np.sum(y == y_pred, axis=0) / float(y.shape[0])
        return acc

Example 48

Project: CNN_keras Source File: train_with_acc_2.py
Function: on_epoch_end
    def on_epoch_end(self, epoch, logs={}):
        print '\n————————————————————————————————————'
        graph.load_weights('tmp/weights.%02d.hdf5' % epoch)
        r = graph.predict({'input': X_test}, verbose=0)
        y_predict = array([argmax(i) for i in r['out']])
        length = len(y_predict) * 1.0
        acc = sum(y_predict == y_test) / length
        print 'Single picture test accuracy: %2.2f%%' % (acc * 100)
        print 'Theoretical accuracy: %2.2f%% ~  %2.2f%%' % ((5*acc-4)*100, pow(acc, 5)*100)
        print '————————————————————————————————————'

Example 49

Project: phillip Source File: thompson_dqn.py
Function: act
  def act(self, policy, verbose=False):
    if util.flip(self.epsilon):
      return random.randint(0, self.action_size)
    
    [qDists] = policy
    if verbose:
      print("qDists", qDists)
    
    samples = [random.normal(mean, std) for mean, std in qDists]
    return argmax(samples)

Example 50

Project: h-DQN Source File: test_naive_hierarchy.py
Function: update_meta
    def _update_meta(self):
        if 0 < len(self.meta_memory):
            exps = [random.choice(self.meta_memory) for _ in range(self.meta_n_samples)]
            for exp in exps:
                meta_reward = self.meta_controller.predict(exp.state, verbose=0)
                meta_reward[0][np.argmax(exp.goal)] = exp.reward
                self.meta_controller.fit(exp.state, meta_reward, verbose=0)
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3 Page 4