当前位置: 首页>>代码示例>>Python>>正文


Python numpy.ones函数代码示例

本文整理汇总了Python中numpy.ones函数的典型用法代码示例。如果您正苦于以下问题:Python ones函数的具体用法?Python ones怎么用?Python ones使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了ones函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: reset

    def reset(self):
        if self.Q_init:
            self.Q = self.Q_init * np.ones(self.n)
        else: # init with small random numbers to avoid ties
            self.Q = np.random.uniform(0, 1e-4, self.n)

        if self.alpha:
            self.update_action_value = self.update_action_value_constant_alpha
        else:
            self.update_action_value = self.update_action_value_sample_average

        if self.epsilon is not None:
            self.choose_action = self.choose_action_greedy
        elif self.tau:
            self.choose_action = self.choose_action_softmax
        else:
            print('Error: epsilon or tau must be set')
            sys.exit(-1)

        self.rewards = []
        self.rewards_seq = []
        self.actions = []
        self.k_actions = np.ones(self.n) # number of steps for each action
        self.k_reward = 1
        self.average_reward = 0
        self.optimal_actions = []
开发者ID:kokorotakey,项目名称:bandit,代码行数:26,代码来源:bandit.py

示例2: __init__

    def __init__(self,  n_mixtures, step_sizes=(0.001,), threshold=0.001):
        """
        Gaussian proposal function for the weights of a GMM.

        Parameters
        ----------
        n_mixtures
        step_sizes

        Notes
        ----------
        The proposal function works by projecting the weight vector w onto the simplex defined by
        w_1 + w_2 + ..... w_n = 1 , 0<=w_i<=1. The change of basis matrix is found by finding n-1 vectors lying on the plane
        and using gramm schmidt to get an orthonormal basis. A Gaussian proposal function in (n-1)-d space is
        used to find the next point on the simplex.
        """
        super(GaussianStepWeightsProposal, self).__init__()
        self.step_sizes = step_sizes
        self.n_mixtures = n_mixtures
        self.count_accepted = np.zeros((len(step_sizes),))
        self.count_illegal =  np.zeros((len(step_sizes),))
        self.count_proposed = np.zeros((len(step_sizes),))
        self.threshold = threshold


        if n_mixtures > 1:
            # get change of basis matrix mapping n dim coodinates to n-1 dim coordinates on simplex
            # x1 + x2 + x3 ..... =1
            points = np.random.dirichlet([1 for i in xrange(n_mixtures)], size=n_mixtures - 1)
            points = points.T
            self.plane_origin = np.ones((n_mixtures)) / float(n_mixtures)
            # get vectors parallel to plane from its center (1/n,1/n,....)
            parallel = points - np.ones(points.shape) / float(n_mixtures)
            # do gramm schmidt to get mutually orthonormal vectors (basis)
            self.e, _ = np.linalg.qr(parallel)
开发者ID:jeremy-ma,项目名称:gmmmc,代码行数:35,代码来源:gaussian_proposals.py

示例3: test_setitem_all

    def test_setitem_all(self):

        data = np.zeros((10, 10), dtype=np.uint8)
        T = Texture(data=data)
        T[...] = np.ones((10, 10, 1))
        assert len(T._pending_data) == 1
        assert np.allclose(data, np.ones((10, 10, 1)))
开发者ID:gbaty,项目名称:vispy,代码行数:7,代码来源:test_texture.py

示例4: test_multiple_problems

    def test_multiple_problems(self):
        if MPI:
            # split the comm and run an instance of the Problem in each subcomm
            subcomm = self.comm.Split(self.comm.rank)
            prob = Problem(Group(), impl=impl, comm=subcomm)

            size = 5
            value = self.comm.rank + 1
            values = np.ones(size)*value

            A1 = prob.root.add('A1', IndepVarComp('x', values))
            C1 = prob.root.add('C1', ABCDArrayComp(size))

            prob.root.connect('A1.x', 'C1.a')
            prob.root.connect('A1.x', 'C1.b')

            prob.setup(check=False)
            prob.run()

            # check the first output array and store in result
            self.assertTrue(all(prob['C1.c'] == np.ones(size)*(value*2)))
            result = prob['C1.c']

            # gather the results from the separate processes/problems and check
            # for expected values
            results = self.comm.allgather(result)
            self.assertEqual(len(results), self.comm.size)

            for n in range(self.comm.size):
                expected = np.ones(size)*2*(n+1)
                self.assertTrue(all(results[n] == expected))
开发者ID:theomission,项目名称:OpenMDAO,代码行数:31,代码来源:test_mpi.py

示例5: test_pes_multidim_error

def test_pes_multidim_error(Simulator, rng):
    """Test that PES works on error connections mapping from N to 1 dims.

    Note that the transform is applied before the learning rule, so the error
    signal should be 1-dimensional.
    """

    with nengo.Network() as net:
        err = nengo.Node(output=[0])
        ens1 = nengo.Ensemble(20, 3)
        ens2 = nengo.Ensemble(10, 1)

        # Case 1: ens -> ens, weights=False
        conn = nengo.Connection(ens1, ens2,
                                transform=np.ones((1, 3)),
                                solver=nengo.solvers.LstsqL2(weights=False),
                                learning_rule_type={"pes": nengo.PES()})
        nengo.Connection(err, conn.learning_rule["pes"])
        # Case 2: ens -> ens, weights=True
        conn = nengo.Connection(ens1, ens2,
                                transform=np.ones((1, 3)),
                                solver=nengo.solvers.LstsqL2(weights=True),
                                learning_rule_type={"pes": nengo.PES()})
        nengo.Connection(err, conn.learning_rule["pes"])
        # Case 3: neurons -> ens
        conn = nengo.Connection(ens1.neurons, ens2,
                                transform=np.ones((1, ens1.n_neurons)),
                                learning_rule_type={"pes": nengo.PES()})
        nengo.Connection(err, conn.learning_rule["pes"])

    with Simulator(net) as sim:
        sim.run(0.01)
开发者ID:4n6strider,项目名称:nengo,代码行数:32,代码来源:test_learning_rules.py

示例6: testLoad

  def testLoad(self):
    with self.cached_session():
      var = variables.Variable(np.zeros((5, 5), np.float32))
      self.evaluate(variables.global_variables_initializer())
      var.load(np.ones((5, 5), np.float32))

      self.assertAllClose(np.ones((5, 5), np.float32), self.evaluate(var))
开发者ID:adit-chandra,项目名称:tensorflow,代码行数:7,代码来源:variables_test.py

示例7: __init__

 def __init__(self,scales = [.3,.01,.01,.01,.01,.01]):
     pygame.init()
     pygame.joystick.init()
     self.controller = pygame.joystick.Joystick(0)
     self.controller.init()
     
     self.lStick = LeftStick(self.controller.get_axis(0),
                                self.controller.get_axis(1))
     self.rStick = RightStick(self.controller.get_axis(4),
                                  self.controller.get_axis(3))
     
     # dpad directions ordered as up down left right
     dPadDirs = getDirs(self.controller)
     
     self.dPad = DPad(dPadDirs)
     #self.dPad = DPad(self.controller.get_hat(0))
     self.trigger = Trigger(self.controller.get_axis(2))
     self.inUse = [False,False,False,False]
     
     length = 6
     self.offsets = np.zeros(length)
     self.uScale = np.ones(length)
     self.lScale = np.ones(length)
     self.driftLimit = .05
     self.calibrate()
     self.scales = np.array(scales)
     time.sleep(1)
     self.calibrate()
开发者ID:jon--lee,项目名称:vision-amt,代码行数:28,代码来源:xboxController.py

示例8: test_vec_to_sym_matrix

def test_vec_to_sym_matrix():
    # Check error if unsuitable size
    vec = np.ones(31)
    assert_raises_regex(ValueError, 'Vector of unsuitable shape',
                        vec_to_sym_matrix, vec)

    # Check error if given diagonal shape incompatible with vec
    vec = np.ones(3)
    diagonal = np.zeros(4)
    assert_raises_regex(ValueError, 'incompatible with vector',
                        vec_to_sym_matrix, vec, diagonal)

    # Check output value is correct
    vec = np.ones(6, )
    sym = np.array([[sqrt(2), 1., 1.], [1., sqrt(2), 1.],
                    [1., 1., sqrt(2)]])
    assert_array_almost_equal(vec_to_sym_matrix(vec), sym)

    # Check output value is correct with seperate diagonal
    vec = np.ones(3, )
    diagonal = np.ones(3)
    assert_array_almost_equal(vec_to_sym_matrix(vec, diagonal=diagonal), sym)

    # Check vec_to_sym_matrix is the inverse function of sym_matrix_to_vec
    # when diagonal is included
    assert_array_almost_equal(vec_to_sym_matrix(sym_matrix_to_vec(sym)), sym)

    # when diagonal is discarded
    vec = sym_matrix_to_vec(sym, discard_diagonal=True)
    diagonal = np.diagonal(sym) / sqrt(2)
    assert_array_almost_equal(vec_to_sym_matrix(vec, diagonal=diagonal), sym)
开发者ID:bthirion,项目名称:nilearn,代码行数:31,代码来源:test_connectivity_matrices.py

示例9: _compute_multipliers

    def _compute_multipliers(self, X, y):
        n_samples, n_features = X.shape

        K = self._gram_matrix(X)
        # Solves
        # min 1/2 x^T P x + q^T x
        # s.t.
        #  Gx \coneleq h
        #  Ax = b

        P = cvxopt.matrix(np.outer(y, y) * K)
        q = cvxopt.matrix(-1 * np.ones(n_samples))

        # -a_i \leq 0
        # TODO(tulloch) - modify G, h so that we have a soft-margin classifier
        G_std = cvxopt.matrix(np.diag(np.ones(n_samples) * -1))
        h_std = cvxopt.matrix(np.zeros(n_samples))

        # a_i \leq c
        G_slack = cvxopt.matrix(np.diag(np.ones(n_samples)))
        h_slack = cvxopt.matrix(np.ones(n_samples) * self._c)

        G = cvxopt.matrix(np.vstack((G_std, G_slack)))
        h = cvxopt.matrix(np.vstack((h_std, h_slack)))

        A = cvxopt.matrix(y, (1, n_samples))
        b = cvxopt.matrix(0.0)

        solution = cvxopt.solvers.qp(P, q, G, h, A, b)

        # Lagrange multipliers
        return np.ravel(solution['x'])
开发者ID:dabbabi-zayani,项目名称:Python-SVM,代码行数:32,代码来源:svm.py

示例10: poly2pwl

def poly2pwl(polycost, Pmin, Pmax, npts):
    """Converts polynomial cost variable to piecewise linear.

    Converts the polynomial cost variable C{polycost} into a piece-wise linear
    cost by evaluating at zero and then at C{npts} evenly spaced points between
    C{Pmin} and C{Pmax}. If C{Pmin <= 0} (such as for reactive power, where
    C{P} really means C{Q}) it just uses C{npts} evenly spaced points between
    C{Pmin} and C{Pmax}.
    """
    pwlcost = polycost
    ## size of piece being changed
    m, n = polycost.shape
    ## change cost model
    pwlcost[:, MODEL]  = PW_LINEAR * ones(m)
    ## zero out old data
    pwlcost[:, COST:COST + n] = zeros(pwlcost[:, COST:COST + n].shape)
    ## change number of data points
    pwlcost[:, NCOST]  = npts * ones(m)

    for i in range(m):
        if Pmin[i] == 0:
            step = (Pmax[i] - Pmin[i]) / (npts - 1)
            xx = range(Pmin[i], step, Pmax[i])
        elif Pmin[i] > 0:
            step = (Pmax[i] - Pmin[i]) / (npts - 2)
            xx = r_[0, range(Pmin[i], step, Pmax[i])]
        elif Pmin[i] < 0 & Pmax[i] > 0:        ## for when P really means Q
            step = (Pmax[i] - Pmin[i]) / (npts - 1)
            xx = range(Pmin[i], step, Pmax[i])
        yy = totcost(polycost[i, :], xx)
        pwlcost[i,      COST:2:(COST + 2*(npts-1)    )] = xx
        pwlcost[i,  (COST+1):2:(COST + 2*(npts-1) + 1)] = yy

    return pwlcost
开发者ID:charlie0389,项目名称:PYPOWER,代码行数:34,代码来源:poly2pwl.py

示例11: test_ovr_always_present

def test_ovr_always_present():
    """Test that ovr works with classes that are always present or absent
    """
    # Note: tests is the case where _ConstantPredictor is utilised
    X = np.ones((10, 2))
    X[:5, :] = 0
    y = np.zeros((10, 3))
    y[5:, 0] = 1
    y[:, 1] = 1
    y[:, 2] = 1

    [[int(i >= 5), 2, 3] for i in range(10)]
    ovr = OneVsRestClassifier(LogisticRegression())
    assert_warns(UserWarning, ovr.fit, X, y)
    y_pred = ovr.predict(X)
    assert_array_equal(np.array(y_pred), np.array(y))
    y_pred = ovr.decision_function(X)
    assert_equal(np.unique(y_pred[:, -2:]), 1)
    y_pred = ovr.predict_proba(X)
    assert_array_equal(y_pred[:, -1], np.ones(X.shape[0]))

    # y has a constantly absent label
    y = np.zeros((10, 2))
    y[5:, 0] = 1  # variable label
    ovr = OneVsRestClassifier(LogisticRegression())
    assert_warns(UserWarning, ovr.fit, X, y)
    y_pred = ovr.predict_proba(X)
    assert_array_equal(y_pred[:, -1], np.zeros(X.shape[0]))
开发者ID:jaguila,项目名称:cert,代码行数:28,代码来源:test_multiclass.py

示例12: balanceTrials

def balanceTrials(n_trials, randomize, factors, use_type='int'):
    n_factors = len(factors)
    n_levels = [0] * n_factors
    min_trials = 1.0 #needs to be float or the later ceiling operation will fail
    for f in range(0, n_factors):
        n_levels[f] = len(factors[f])
        min_trials *= n_levels[f] #simulates use of prod(n_levels) in the original code
    
    N = math.ceil(n_trials / min_trials)
    
    output = []
    len1 = min_trials
    len2 = 1
    index = numpy.random.uniform(0, 1, N * min_trials).argsort()
    
    for level, factor in zip(n_levels, factors):
        len1 /= level
        factor = numpy.array(factor, dtype=use_type)
        
        out = numpy.kron(numpy.ones((N, 1)), numpy.kron(numpy.ones((len1, len2)), factor).reshape(min_trials,)).astype(use_type).reshape(N*min_trials,)
        
        if randomize:
            out = [out[i] for i in index]
        
        len2 *= level
        output.append(out)
    
    return output
开发者ID:kedean,项目名称:gabor_generator,代码行数:28,代码来源:gabor_util.py

示例13: test_invalid_seed

def test_invalid_seed():
    seed = np.ones((5, 5))
    mask = np.ones((5, 5))
    assert_raises(ValueError, reconstruction, seed * 2, mask,
                  method='dilation')
    assert_raises(ValueError, reconstruction, seed * 0.5, mask,
                  method='erosion')
开发者ID:AbdealiJK,项目名称:scikit-image,代码行数:7,代码来源:test_reconstruction.py

示例14: world2pix

    def world2pix(self, lon, lat, energy, combine=False):
        """Convert world to pixel coordinates.

        Parameters
        ----------
        lon, lat, energy

        Returns
        -------
        x, y, z or array with (x, y, z) as columns
        """
        lon = lon.to('deg').value
        lat = lat.to('deg').value
        origin = 0  # convention for gammapy
        x, y, _ = self.wcs.wcs_world2pix(lon, lat, 0, origin)

        z = self.energy_axis.world2pix(energy)

        shape = (x * y * z).shape
        x = x * np.ones(shape)
        y = y * np.ones(shape)
        z = z * np.ones(shape)

        if combine:
            x = np.array(x).flat
            y = np.array(y).flat
            z = np.array(z).flat
            return np.column_stack([z, y, x])
        else:
            return x, y, z
开发者ID:JonathanDHarris,项目名称:gammapy,代码行数:30,代码来源:spectral_cube.py

示例15: test_stratified_kfold_no_shuffle

def test_stratified_kfold_no_shuffle():
    # Manually check that StratifiedKFold preserves the data ordering as much
    # as possible on toy datasets in order to avoid hiding sample dependencies
    # when possible
    X, y = np.ones(4), [1, 1, 0, 0]
    splits = StratifiedKFold(2).split(X, y)
    train, test = next(splits)
    assert_array_equal(test, [0, 2])
    assert_array_equal(train, [1, 3])

    train, test = next(splits)
    assert_array_equal(test, [1, 3])
    assert_array_equal(train, [0, 2])

    X, y = np.ones(7), [1, 1, 1, 0, 0, 0, 0]
    splits = StratifiedKFold(2).split(X, y)
    train, test = next(splits)
    assert_array_equal(test, [0, 1, 3, 4])
    assert_array_equal(train, [2, 5, 6])

    train, test = next(splits)
    assert_array_equal(test, [2, 5, 6])
    assert_array_equal(train, [0, 1, 3, 4])

    # Check if get_n_splits returns the number of folds
    assert_equal(5, StratifiedKFold(5).get_n_splits(X, y))
开发者ID:absolutelyNoWarranty,项目名称:scikit-learn,代码行数:26,代码来源:test_split.py


注:本文中的numpy.ones函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。