numpy.round

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

200 Examples 7

Example 1

Project: pele
Source File: bulk_rigid_mindist.py
View license
    def finalize_best_match(self, x1, best_x2):
        ''' do final processing of the best match '''
        ca1 = CoordsAdapter(coords=x1)     
        ca2 = CoordsAdapter(coords=best_x2)
        dx = ca1.posRigid - ca2.posRigid
        dx = np.round(dx / self.boxvec) * self.boxvec
        self.transform.translate(best_x2, dx)

        dist = self.measure.get_dist(x1, best_x2)
#         if (dist - self.distbest) > 1e-6:
#             raise RuntimeError(dist, self.distbest, "Permutational alignment has increased the distance metric")        
        if self.verbose:
            print "finaldist", dist, "distmin", self.distbest
        return dist, best_x2

Example 2

Project: pele
Source File: maxneib_blj.py
View license
    def getEnergyGradient(self, coords):
        if self.periodic:
            coords -= np.round(coords / self.boxl) * self.boxl
        E, grad = fortranpot.maxneib_ljenergy_gradient(
                coords, self.ntypeA,
                self.epsA, self.sigA, 
                self.epsB, self.sigB, 
                self.epsAB, self.sigAB, 
                self.periodic, self.boxl, 
                self.rneib, self.rneib_crossover, self.max_neibs, self.neib_crossover, 
                self.epsneibs, self.only_AB_neibs)
        return E, grad

Example 3

Project: pele
Source File: maxneib_lj.py
View license
    def getEnergyGradient(self, coords):
        if self.periodic:
            coords -= np.round(coords / self.boxl) * self.boxl
        E, grad = fortranpot.maxneib_ljenergy_gradient(
                coords, self.eps, self.sig, self.periodic, self.boxl, 
                self.rneib, self.rneib_crossover, self.max_neibs, self.neib_crossover, 
                self.epsneibs)
        return E, grad

Example 4

Project: pvlib-python
Source File: test_location.py
View license
def test_get_solarposition(expected_solpos):
    from test_solarposition import golden_mst
    times = pd.date_range(datetime.datetime(2003,10,17,12,30,30),
                          periods=1, freq='D', tz=golden_mst.tz)
    ephem_data = golden_mst.get_solarposition(times, temperature=11)
    ephem_data = np.round(ephem_data, 3)
    expected_solpos.index = times
    expected_solpos = np.round(expected_solpos, 3)
    assert_frame_equal(expected_solpos, ephem_data[expected_solpos.columns])

Example 5

Project: pvlib-python
Source File: test_pvsystem.py
View license
def test_calcparams_desoto(cec_module_params):
    times = pd.DatetimeIndex(start='2015-01-01', periods=2, freq='12H')
    poa_data = pd.Series([0, 800], index=times)

    IL, I0, Rs, Rsh, nNsVth = pvsystem.calcparams_desoto(
                                  poa_data,
                                  temp_cell=25,
                                  alpha_isc=cec_module_params['alpha_sc'],
                                  module_parameters=cec_module_params,
                                  EgRef=1.121,
                                  dEgdT=-0.0002677)

    assert_series_equal(np.round(IL, 3), pd.Series([0.0, 6.036], index=times))
    assert_allclose(I0, 1.943e-9)
    assert_allclose(Rs, 0.094)
    assert_series_equal(np.round(Rsh, 3), pd.Series([np.inf, 19.65], index=times))
    assert_allclose(nNsVth, 0.473)

Example 6

Project: pvlib-python
Source File: test_pvsystem.py
View license
def test_PVSystem_calcparams_desoto(cec_module_params):
    module_parameters = cec_module_params.copy()
    module_parameters['EgRef'] = 1.121
    module_parameters['dEgdT'] = -0.0002677
    system = pvsystem.PVSystem(module_parameters=module_parameters)
    times = pd.DatetimeIndex(start='2015-01-01', periods=2, freq='12H')
    poa_data = pd.Series([0, 800], index=times)
    temp_cell = 25

    IL, I0, Rs, Rsh, nNsVth = system.calcparams_desoto(poa_data, temp_cell)

    assert_series_equal(np.round(IL, 3), pd.Series([0.0, 6.036], index=times))
    assert_allclose(I0, 1.943e-9)
    assert_allclose(Rs, 0.094)
    assert_series_equal(np.round(Rsh, 3), pd.Series([np.inf, 19.65], index=times))
    assert_allclose(nNsVth, 0.473)

Example 7

Project: python-oceans
Source File: RPSstuff.py
View license
def ms2hms(millisecs):
    """
    Converts milliseconds to integer hour, minute, seconds.

    Example
    -------
    >>> ms2hms(1e3 * 60)
    (0.0, 1.0, 0.0)

    """
    sec = np.round(millisecs / 1000)
    hour = np.floor(sec / 3600)
    mn = np.floor(np.remainder(sec, 3600) / 60)
    sec = np.round(np.remainder(sec, 60))
    return hour, mn, sec

Example 8

Project: pyspeckit
Source File: mapplot.py
View license
    def click(self,event):
        """
        Record location of downclick
        """
        if event.inaxes:
            self._clickX = np.round(event.xdata) - self._origin
            self._clickY = np.round(event.ydata) - self._origin

Example 9

Project: pyspeckit
Source File: gbt.py
View license
def round_to_resolution(frequency, resolution):
    """
    kind of a hack, but round the frequency to the nearest integer multiple of the resolution,
    then multiply it back into frequency space
    """
    # doesn't really work... divisor = 10**np.floor(np.log10(resolution))
    divisor = resolution
    return (np.round(frequency/divisor)) * divisor

Example 10

Project: python-qinfer
Source File: test_distributions.py
View license
    def test_lognormal_moments(self):
        """
        Distributions: Checks that the log normal
        distribution has the right moments.
        """
        mu, sig = 3, 2
        dist = LogNormalDistribution(mu=mu, sigma=sig)

        samples = dist.sample(150000)

        assert_sigfigs_equal(
            scipy.stats.lognorm.mean(1,3,2), 
            samples.mean(), 
            1)
        assert_sigfigs_equal(
            np.round(scipy.stats.lognorm.var(1,3,2)), 
            np.round(samples.var()), 
            1)

Example 11

Project: imageqa-public
Source File: valid_tool.py
View license
def splitData(trainInput, trainTarget, heldOutRatio, validNumber):
    s = np.round(trainInput.shape[0] * heldOutRatio)
    start = s * validNumber
    validInput = trainInput[start : start + s]
    validTarget = trainTarget[start : start + s]
    if validNumber == 0:
        trainInput = trainInput[s:]
        trainTarget = trainTarget[s:]
    else:
        trainInput = np.concatenate((trainInput[0:start], trainInput[start + s:]))
        trainTarget = np.concatenate((trainTarget[0:start], trainTarget[start + s:]))
    return trainInput, trainTarget, validInput, validTarget

Example 12

Project: tfdeploy
Source File: tfdeploy.py
View license
@Operation.factory
def Round(a):
    """
    Round op.
    """
    return np.round(a),

Example 13

Project: pygis
Source File: raster.py
View license
    def sample_pixel(self, points):
        # Round the points to the integer pixel locations.
        points = np.round(points)

        # Clamp to image
        points[:,0] = np.maximum(0, np.minimum(self.data.shape[1]-1, points[:,0]))
        points[:,1] = np.maximum(0, np.minimum(self.data.shape[0]-1, points[:,1]))

        # Sample
        values = []
        for p in points:
            values.append(self.data[p[1], p[0]])

        return np.array(values)

Example 14

Project: director
Source File: startup.py
View license
    def updateGrid(self, model):
        pos = self.jointController.q[:3]

        x = int(np.round(pos[0])) / 10
        y = int(np.round(pos[1])) / 10
        z = int(np.round(pos[2] - 0.85)) / 1

        t = vtk.vtkTransform()
        t.Translate((x*10,y*10,z))
        self.gridFrame.copyFrame(t)

Example 15

Project: scikit-image
Source File: test_texture.py
View license
    def test_contrast(self):
        result = greycomatrix(self.image, [1, 2], [0], 4,
                              normed=True, symmetric=True)
        result = np.round(result, 3)
        contrast = greycoprops(result, 'contrast')
        np.testing.assert_almost_equal(contrast[0, 0], 0.586)

Example 16

Project: scipy
Source File: test_mstats_extras.py
View license
    def test_trimmedmeanci(self):
        "Tests the confidence intervals of the trimmed mean."
        data = ma.array([545,555,558,572,575,576,578,580,
                         594,605,635,651,653,661,666])
        assert_almost_equal(ms.trimmed_mean(data,0.2), 596.2, 1)
        assert_equal(np.round(ms.trimmed_mean_ci(data,(0.2,0.2)),1),
                     [561.8, 630.6])

Example 17

Project: rayleigh
Source File: util.py
View license
def rgb2hex(rgb_number):
    """
    Args:
        - rgb_number (sequence of float)

    Returns:
        - hex_number (string)
    """
    return '#%02x%02x%02x' % tuple([np.round(val * 255) for val in rgb_number])

Example 18

Project: sfepy
Source File: geometry_element.py
View license
def _get_grid_3_8(n_nod):
    n1d = int(nm.round(n_nod**(1.0 / 3.0)))
    assert_((n1d**3) == n_nod)

    ii = nm.linspace(0.0, 1.0, n1d)

    ix, iy, iz = nm.mgrid[:n1d, :n1d, :n1d]
    coors = nm.c_[ii[ix].flat, ii[iy].flat, ii[iz].flat]

    return nm.ascontiguousarray(coors)

Example 19

Project: GPy
Source File: eq_ode1.py
View license
    def Kdiag(self, X):
        if hasattr(X, 'values'):
            index = np.int_(np.round(X[:, 1].values))
        else:
            index = np.int_(np.round(X[:, 1]))
        index = index.reshape(index.size,)
        X_flag = index[0] >= self.output_dim
        
        if X_flag: #Kuudiag        
            return np.ones(X[:,0].shape)
        else: #Kffdiag
            kdiag = self._Kdiag(X)
            return np.sum(kdiag, axis=1)

Example 20

Project: statsmodels
Source File: test_regression.py
View license
    def test_HC0_errors(self):
        #They are split up because the copied results do not have any DECIMAL_4
        #places for the last place.
        assert_almost_equal(self.res1.HC0_se[:-1],
                self.res2.HC0_se[:-1], DECIMAL_4)
        assert_approx_equal(np.round(self.res1.HC0_se[-1]), self.res2.HC0_se[-1])

Example 21

Project: klepto
Source File: rounding.py
View license
def simple_round_factory(tol):
  """helper function for simple_round (a factory for simple_round functions)"""
  def simple_round(*args, **kwds):
    argstype = type(args) 
    _args = list(args)
    _kwds = kwds.copy()
    for i,j in enumerate(args):
      if isinstance(j, float): _args[i] = round(j, tol) # don't round int
    for i,j in kwds.items():
      if isinstance(j, float): _kwds[i] = round(j, tol)
    return argstype(_args), _kwds
  return simple_round

Example 22

Project: msaf
Source File: greedycur.py
View license
    def sample(self, A, c):
        # set k to a value lower than the number of bases, usually
        # gives better results.
        k = np.round(c - c/5.0)
        greedy_mdl = GREEDY(A, k=k, num_bases=c)
        greedy_mdl.factorize(compute_h=False, compute_err=False, niter=1)        
        return greedy_mdl.select

Example 23

Project: moviepy
Source File: scroll.py
View license
def scroll(clip, h=None, w=None, x_speed=0, y_speed=0,
           x_start=0, y_start=0, apply_to="mask"):
    """ Scrolls horizontally or vertically a clip, e.g. to make end
        credits """
    if h is None: h = clip.h
    if w is None: w = clip.w
    
    xmax = clip.w-w-1
    ymax = clip.h-h-1

    def f(gf,t):
        x = max(0, min(xmax, x_start+ np.round(x_speed*t)))
        y = max(0, min(ymax, y_start+ np.round(y_speed*t)))
        return gf(t)[y:y+h, x:x+w]
    
    return clip.fl(f, apply_to = apply_to)

Example 24

Project: pompei
Source File: pompei.py
View license
def split_array(arr, nh, nw):
    """ Splits a 2D-ish array into a mosaic of smaller arrays.

    In short, this array:

    [ [ A ] ]

    is splitted like this

    [ [  [A11] [A12] ]
      [  [A21] [A22] ] ]

    """
    h,w,_ = arr.shape
    dh, dw = 1.0*h/nh, 1.0*w/nw 
    return [[ arr[ int(np.round(dh*i)): int(np.round(dh*(i+1))),
                     int(np.round(dw*j)): int(np.round(dw*(j+1)))]
              for j in range(int(nw))] for i in range(int(nh))]

Example 25

Project: pyvision
Source File: GaborJets.py
View license
    def extractJet(self,pt,subpixel=True):
        x = int(np.round(pt.X()))
        y = int(np.round(pt.Y()))
        x = max(min(x,self.data.shape[0]-1),0)
        y = max(min(y,self.data.shape[0]-1),0)
        jet = self.data[x,y,:]

        return GaborJet(jet,self.kernels,self.k,x,y,pt,subpixel)

Example 26

Project: horus
Source File: camera_intrinsics.py
View license
    def calibrate(self):
        error = 0
        ret, cmat, dvec, rvecs, tvecs = cv2.calibrateCamera(
            self.object_points, self.image_points, self.shape)

        if ret:
            # Compute calibration error
            for i in xrange(len(self.object_points)):
                imgpoints2, _ = cv2.projectPoints(
                    self.object_points[i], rvecs[i], tvecs[i], cmat, dvec)
                error += cv2.norm(self.image_points[i], imgpoints2, cv2.NORM_L2) / len(imgpoints2)
            error /= len(self.object_points)

        return ret, error, np.round(cmat, 3), np.round(dvec.ravel(), 3), rvecs, tvecs

Example 27

Project: quant_at
Source File: strat.py
View license
def position_forecast(curr, price, price_vol, notional_trading_capital,
                      percentage_vol_target, point_value, fx_rate, instrument_weight,
                      instrument_div_multiplier, fcast):
    """
    Given recent price, forecast and some other vars, return the position for a
    strategy (instrument) as integer. If '4' is returned that means 4
    contracts. No fractions are possible. If no forecast is passed maximum
    forecast is assumed to maximum long position will be returned. 
    """
    annual_cash_vol_target = notional_trading_capital * (percentage_vol_target/100.)
    daily_vol_target = annual_cash_vol_target / 16
    block_value = price * point_value / 100.
    instrument_ccy_vol = block_value * (price_vol/100.) * 100.
    instrument_value_vol = instrument_ccy_vol * fx_rate
    vol_scalar = daily_vol_target / instrument_value_vol
    sub_position = fcast * vol_scalar / util.LONG_RUN_FCAST
    port_instrument_pos = sub_position * (instrument_weight/100.) * instrument_div_multiplier
    port_instrument_pos = np.round(port_instrument_pos,0)
    return port_instrument_pos

Example 28

Project: tfr
Source File: tuning.py
View license
    def quantize(self, freqs):
        """
        Quantizes frequencies to nearest pitch bins (with optional division of
        bins).
        """
        return np.round(self.tuning.freq_to_pitch(freqs) * self.bin_division) / self.bin_division

Example 29

Project: AlephNull
Source File: test_algorithms.py
View license
    def handle_data(self, data):
        if self.target_shares == 0:
            assert 0 not in self.portfolio.positions
            self.target_shares = 1
        else:
            assert np.round(self.portfolio.portfolio_value * 0.002) == \
                self.portfolio.positions[0]['amount'] * self.sale_price, \
                "Orders not filled correctly."
            assert self.portfolio.positions[0]['last_sale_price'] == \
                data[0].price, "Orders not filled at current price."
        self.sale_price = data[0].price
        self.order_target_percent(0, .002)

Example 30

Project: AlephNull
Source File: test_algorithms.py
View license
    def handle_data(self, data):
        if self.target_shares == 0:
            assert 0 not in self.portfolio.positions
            self.order(0, 10)
            self.target_shares = 10
            return
        else:
            print self.portfolio
            assert self.portfolio.positions[0]['amount'] == \
                self.target_shares, "Orders not filled immediately."
            assert self.portfolio.positions[0]['last_sale_price'] == \
                data[0].price, "Orders not filled at current price."

        self.order_target_value(0, 20)
        self.target_shares = np.round(20 / data[0].price)

Example 31

Project: APGL
Source File: UtilProfile.py
View license
    def profileFitDiscretePowerLaw(self):
        #Test with a large vector x
        alpha = 2.5
        exponent = (1/(alpha-1))
        numPoints = 50000
        x = 10*numpy.random.rand(numPoints)**-exponent
        x = numpy.array(numpy.round(x), numpy.int)
        x = x[x<=500]
        x = x[x>=1]

        xmins = numpy.arange(1, 20)

        ProfileUtils.profile('Util.fitDiscretePowerLaw(x, xmins)', globals(), locals())

Example 32

Project: brut
Source File: dr1.py
View license
def bubble_params(bubbles=None):
    c = get_catalog()
    bubbles = bubbles or range(len(c))

    result = []
    for b in bubbles:
        args = _on_args(c, b)
        result.append([int(np.round(args[0])), args[0], args[1], args[2]])
    return result

Example 33

Project: brut
Source File: dr1.py
View license
def highest_quality_on_params():
    """Iterate over highest-confidence + examples
    yield tuples of (field_lon, lcen, bcen, r)
    """
    pth = os.path.join(os.path.dirname(__file__), 'data', 'best', 'data.pkl')
    data = pickle.load(open(pth))
    for k, (l, b, r) in data.items():
        if os.path.exists(os.path.join(os.path.dirname(pth), k)):
            yield int(np.round(l)), l, b, r

Example 34

Project: brut
Source File: test_dr1.py
View license
    @pytest.mark.parametrize('mod3', [0, 1, 2])
    def test_off_fields(self, mod3):
        from itertools import islice
        lc = self.LG(mod3)
        for p in islice(lc.negatives_iterator(), 0, 1000):
            self.assert_lon_valid(p[0], mod3)
            self.assert_lon_valid(int(np.round(p[1])), mod3)

Example 35

Project: ProxImaL
Source File: metrics.py
View license
    def eval(self, v):
        """Evaluate the metric
        """
        if self.decimals is None:
            return self._eval(v)
        else:
            return np.round(self._eval(v), decimals=self.decimals)

Example 36

Project: mir_eval
Source File: util.py
View license
def intervals_to_boundaries(intervals, q=5):
    """Convert interval times into boundaries.

    Parameters
    ----------
    intervals : np.ndarray, shape=(n_events, 2)
        Array of interval start and end-times
    q : int
        Number of decimals to round to. (Default value = 5)

    Returns
    -------
    boundaries : np.ndarray
        Interval boundary times, including the end of the final interval

    """

    return np.unique(np.ravel(np.round(intervals, decimals=q)))

Example 37

Project: cvxpy
Source File: relax_and_round.py
View license
def round_and_fix(prob):
    prob.solve()
    new_constr = []
    for var in prob.variables():
        if getattr(var, 'boolean', False):
            new_constr += [var == numpy.round(var.value)]
    return Problem(prob.objective,
                   prob.constraints + new_constr)

Example 38

Project: refinery
Source File: TestFromScratchGauss.py
View license
  def test_randexamplesbydist(self, nTrial=25):
    trialOutcomes = list()
    for trial in range(nTrial):
      initParams = dict(initname='randexamplesbydist', seed=trial, K=self.K)
      self.hmodel.init_global_params(self.Data, **initParams)
      muLocs = list()
      for k in range(self.K):
        mu = self.hmodel.obsModel.get_mean_for_comp(k)
        muLocs.append(int(np.round(mu[0])))
      muLocs = np.sort(muLocs)
      nMatch = np.sum( [muLocs[k] == k for k in range(self.K)])
      trialOutcomes.append(nMatch)
    trialOutcomes = np.asarray(trialOutcomes)
    assert np.sum(trialOutcomes == self.K) > 0.95 * nTrial
      

Example 39

Project: audiolazy
Source File: test_synth_numpy.py
View license
def test_adsr():
  rate = 44100
  dur = 3 * rate
  sustain_level = .8
  attack = np.linspace(0., 1., num=np.round(20e-3 * rate), endpoint=False)
  decay = np.linspace(1., sustain_level, num=np.round(30e-3 * rate),
                      endpoint=False)
  release = np.linspace(sustain_level, 0., num=np.round(50e-3 * rate),
                        endpoint=False)
  sustain_dur = dur - len(attack) - len(decay) - len(release)
  sustain = sustain_level * np.ones(sustain_dur)
  env = np.hstack([attack, decay, sustain, release])

  s, Hz = sHz(rate)
  ms = 1e-3 * s
  assert almost_eq(env, adsr(dur=3*s, a=20*ms, d=30*ms, s=.8, r=50*ms))

Example 40

Project: ProFET
Source File: FeatureGen.py
View license
def dict2df (seq_feature_dict, orientation='index',round=True,roundPrec=3):
  '''
  Takes a dict of dicts as input, returns a pandas DataFrame.
  NOTE: We also replace NaN with 0 ..
  As default, also rounds down data to {3} decimal places. (Saves on file size).

  '''
  from numpy import round
  Dframe = pd.DataFrame.from_dict(seq_feature_dict, orient=orientation)
  Dframe.replace([np.inf, -np.inf], 0) #Remove "infinities"
  Dframe.fillna(0, inplace=True) #Fill missing data
  if round==True:
    #Dframe.apply(npround)
    round(Dframe, decimals=roundPrec)
    #http://stackoverflow.com/questions/25272024/round-each-number-in-a-python-pandas-data-frame-by-2-decimals?rq=1
  return(Dframe)

Example 41

Project: deepchem
Source File: support_classifier.py
View license
  def predict_on_batch(self, support, test_batch):
    """Make predictions on batch of data."""
    n_samples = len(test_batch)
    padded_test_batch = NumpyDataset(*pad_batch(
        self.test_batch_size, test_batch.X, test_batch.y, test_batch.w,
        test_batch.ids))
    feed_dict = self.construct_feed_dict(padded_test_batch, support)
    # Get scores
    pred, scores = self.sess.run([self.pred_op, self.scores_op], feed_dict=feed_dict)
    y_pred_batch = np.round(scores)
    ########################################################### DEBUG
    # Remove padded elements
    y_pred_batch = y_pred_batch[:n_samples]
    ########################################################### DEBUG
    return y_pred_batch

Example 42

View license
    def _compute(self):
        """
        Compute the Marginal Utility of Information.
        """
        sp = ShannonPartition(self.dist)
        c, A, b, bounds = get_lp_form(self.dist, sp)
        ent = sum(sp.atoms.values())

        atoms = sp.atoms.values()
        ps = powerset(atoms)
        pnts = np.unique(np.round([sum(ss) for ss in ps], 7))
        pnts = [v for v in pnts if 0 <= v <= ent]

        maxui = [max_util_of_info(c, A, b, bounds, y) for y in pnts]
        mui = np.round(np.diff(maxui)/np.diff(pnts), 7)
        vals = np.array(np.unique(mui, return_index=True))
        self.profile = dict((pnts[int(row[1])], row[0]) for row in vals.T)
        self.widths = np.diff(list(self.profile.keys()) + [ent])

Example 43

View license
def dimensionText( V, formatStr, roundingDigit=6, comma=False):
    try:
        s1 = remove_tailing_zeros(formatStr % {'value':V})
    except TypeError:
        s1 = remove_tailing_zeros(formatStr % V)
    Vrounded = numpy.round(V, roundingDigit)
    try:
        s2 = remove_tailing_zeros(formatStr % {'value':Vrounded})
    except TypeError:
        s2 = remove_tailing_zeros(formatStr % Vrounded)
    s =  s2 if len(s2) < len(s1) else s1
    if comma: s = s.replace('.',',')
    return s

Example 44

Project: mcmerge
Source File: merge.py
View license
    def erode_slope(self, filt_name, filt_factor):
        """
        Produced a smoothed version of the original height map sloped
        to meet the surrounding terrain.
        """
        
        ffun = getattr(filter, filter.filters[filt_name])
        
        return numpy.cast[self.height.dtype](numpy.round(ffun(self.height, filt_factor, self.chunk_padder, self.__padding)))

Example 45

Project: mcmerge
Source File: merge.py
View license
    def erode_valley(self, filt_name, filt_factor):
        """
        Produced a smoothed version of the original height map with a
        river valley added around the marked edge.
        """
        
        ffun = getattr(filter, filter.filters[filt_name])
        
        valley, erode_mask = self.with_valley(self.height)
        carved = self.with_river(valley)
        return numpy.cast[carved.dtype](numpy.round(ffun(carved, filt_factor, filter.pad, self.__padding))), erode_mask

Example 46

Project: mlp
Source File: model.py
View license
    def predict(self, X):
        # prediction = self.model.predict_classes(X, verbose=self.verbose)
        # prediction = np.array(prediction).reshape((X.shape[0], -1))
        # prediction = np.squeeze(prediction).astype('int')
        # return prediction
        prediction = self.model.predict_proba(X, verbose=self.verbose)
        if self.n_class == 1:
            return np.round(prediction[:,1])
        else:
            return np.round(prediction)

Example 47

Project: neupy
Source File: test_hebb.py
View license
    def test_with_weight_decay(self):
        hn = algorithms.HebbRule(
            n_inputs=2,
            n_outputs=1,
            n_unconditioned=1,
            step=1,
            verbose=False,
            decay_rate=0.1,
        )

        # Test learning limit
        hn.train(input_data, epochs=50)
        self.assertEqual(np.round(hn.weight[1, 0], 2), 10)

        hn.train(input_data, epochs=50)
        self.assertEqual(np.round(hn.weight[1, 0], 2), 10)

Example 48

Project: cgt
Source File: example_utils.py
View license
def train_val_test_slices(n, trainfrac, valfrac, testfrac):
    assert trainfrac+valfrac+testfrac==1.0
    ntrain = int(np.round(n*trainfrac))
    nval = int(np.round(n*valfrac))
    ntest = n - ntrain - nval
    return slice(0,ntrain), slice(ntrain,ntrain+nval), slice(ntrain+nval,ntrain+nval+ntest)

Example 49

Project: cgt
Source File: example_utils.py
View license
def train_val_test_slices(n, trainfrac, valfrac, testfrac):
    assert trainfrac+valfrac+testfrac==1.0
    ntrain = int(np.round(n*trainfrac))
    nval = int(np.round(n*valfrac))
    ntest = n - ntrain - nval
    return slice(0,ntrain), slice(ntrain,ntrain+nval), slice(ntrain+nval,ntrain+nval+ntest)

Example 50

Project: iGAN
Source File: ui_warp.py
View license
    def AddPoint(self, pos, im):
        x_c = int(np.round(pos.x()/self.scale))
        y_c=  int(np.round(pos.y()/self.scale))
        pnt = (x_c, y_c)
        print('add point (%d,%d)'%pnt)
        self.points1.append(pnt)
        self.points2.append(pnt)
        self.widths.append(self.width)

        self.im = cv2.resize(im, (self.npx, self.npx))#*255).astype(np.uint8)
        self.ims.append(self.im.copy())
        self.activeId = len(self.points1) - 1
        print('set active id =%d'%self.activeId)