• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python tensor.dtensor3函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: variables

	def variables(self):
		# Define parameters 'w'
		w = {}
		for i in ['wz','bz','logsd','wx','bx']:
			w[i] = T.dmatrix(i)
		
		# Define variables 'x' and 'z'
		z = {'eps':T.dtensor3('eps')}
		x = {'x':T.dtensor3('x')}
		
		return w, x, z
开发者ID:Beronx86,项目名称:anglepy,代码行数:11,代码来源:DBN_scan.py


示例2: test_fail

 def test_fail(self):
     """
     Test that conv2d fails for dimensions other than 2 or 3.
     """
     try:
         conv.conv2d(T.dtensor4(), T.dtensor3())
         self.fail()
     except:
         pass
     try:
         conv.conv2d(T.dtensor3(), T.dvector())
         self.fail()
     except:
         pass
开发者ID:hamelphi,项目名称:Theano,代码行数:14,代码来源:test_conv.py


示例3: build_model

    def build_model(self, train_x, train_mask_x, train_mask_out, train_target,
                    test_x, test_mask_x, test_mask_out, test_target):
        self.train_x = train_x
        self.train_mask_x = train_mask_x
        self.train_mask_out = train_mask_out
        self.train_target = train_target
        self.test_x = test_x
        self.test_mask_x = test_mask_x
        self.test_mask_out = test_mask_out
        self.test_target = test_target
        self.index = T.iscalar('index')
        self.num_batch_test = T.iscalar('index')
        self.b_slice = slice(self.index * self.num_batch, (self.index + 1) * self.num_batch)

        sym_x = T.dtensor3()
        sym_mask_x = T.dmatrix()
        sym_target = T.dtensor3()
        sym_mask_out = T.dtensor3()
        # sym_mask_out = T.dtensor3() should not be useful since output is still zero
        # TODO think about this if it is true

        out = lasagne.layers.get_output(self.model, inputs={self.l_in: sym_x, self.mask_input: sym_mask_x})
        out_out = self.get_output_y(out)
        loss = T.mean(lasagne.objectives.squared_error(out_out, sym_target)) / self.num_batch

        out_test = lasagne.layers.get_output(self.model, inputs={self.l_in: sym_x, self.mask_input: sym_mask_x})
        out_out_test = self.get_output_y(out_test)
        loss_test = T.mean(lasagne.objectives.squared_error(out_out_test, sym_target)) / self.num_batch_test

        all_params = [self.W] + [self.b] +lasagne.layers.get_all_params(self.model)
        all_grads_target = [T.clip(g, -3, 3) for g in T.grad(loss, all_params)]
        all_grads_target = lasagne.updates.total_norm_constraint(all_grads_target, 3)
        updates_target = adam(all_grads_target, all_params)

        train_model = theano.function([self.index],
                                      [loss, out_out],
                                      givens={sym_x: self.train_x[self.b_slice],
                                              sym_mask_x: self.train_mask_x[self.b_slice],
                                              sym_target: self.train_target[self.b_slice],
                                              },
                                      updates=updates_target)
        test_model = theano.function([self.num_batch_test],
                                     [loss_test, out_out_test],
                                     givens={sym_x: self.test_x,
                                             sym_mask_x: self.test_mask_x,
                                             sym_target: self.test_target,
                                             })

        return train_model, test_model
开发者ID:Enny1991,项目名称:MasterThesis,代码行数:49,代码来源:predictive_RAE_log.py


示例4: build_model

    def build_model(self, train_x, train_mask_x, train_mask_out, train_target,
                    test_x, test_mask_x, test_mask_out, test_target):
        self.train_x = train_x
        self.train_mask_x = train_mask_x
        self.train_mask_out = train_mask_out
        self.train_target = train_target
        self.test_x = test_x
        self.test_mask_x = test_mask_x
        self.test_mask_out = test_mask_out
        self.test_target = test_target
        self.index = T.iscalar('index')
        self.num_batch_test = T.iscalar('index')
        self.b_slice = slice(self.index * self.num_batch, (self.index + 1) * self.num_batch)

        sym_x = T.dtensor3()
        sym_mask_x = T.dmatrix()
        sym_target = T.dtensor3()
        # sym_mask_out = T.dtensor3() should not be useful since output is still zero
        # TODO think about this if it is true

        output = lasagne.layers.get_output(self.model, inputs={self.l_in: sym_x, self.mask_input: sym_mask_x})
        theta = self.get_output_y(output)
        log_px = self.get_log_x(sym_target, theta)
        log_px_sum_time = log_px.sum(axis=1, dtype=theano.config.floatX) # sum over tx
        loss = - T.sum(log_px_sum_time) / self.num_batch # average over batch
        ##
        log_px_test = self.get_log_x(sym_target, theta)
        log_px_sum_time_test = log_px_test.sum(axis=1, dtype=theano.config.floatX) # sum over time
        loss_test = - T.sum(log_px_sum_time_test) / self.num_batch_test  # average over batch
        # loss = T.mean(lasagne.objectives.squared_error(mu, sym_target))
        all_params = [self.W_y_theta] + [self.b_y_theta] + lasagne.layers.get_all_params(self.model)
        all_grads_target = [T.clip(g, -3, 3) for g in T.grad(loss, all_params)]
        all_grads_target = lasagne.updates.total_norm_constraint(all_grads_target, 3)
        updates_target = adam(all_grads_target, all_params)

        train_model = theano.function([self.index],
                                      [loss, theta, log_px],
                                      givens={sym_x: self.train_x[self.b_slice],
                                              sym_mask_x: self.train_mask_x[self.b_slice],
                                              sym_target: self.train_target[self.b_slice]},
                                      updates=updates_target)
        test_model = theano.function([self.num_batch_test],
                                     [loss_test, theta],
                                     givens={sym_x: self.test_x,
                                             sym_mask_x: self.test_mask_x,
                                             sym_target: self.test_target})

        return train_model, test_model
开发者ID:Enny1991,项目名称:MasterThesis,代码行数:48,代码来源:predictive_RAE.py


示例5: testPredictFunc

def testPredictFunc():
    """
    Test the network predict function
    """
    network = LSTMP2H()

    symPremise = T.dtensor3("inputPremise")
    symHypothesis = T.dtensor3("inputHypothesis")
    premiseSent = np.random.randn(1,1,2)
    hypothesisSent = np.random.randn(1,1,2)

    predictFunc = network.predictFunc(symPremise, symHypothesis)
    labels = network.predict(premiseSent, hypothesisSent, predictFunc)

    for l in labels:
        print "Label: %s" %(l)
开发者ID:BinbinBian,项目名称:LSTM-NLI,代码行数:16,代码来源:functionality.py


示例6: trainer_tester

def trainer_tester(mapping,train_data,test_data):
	data = theano.shared(train_data)
	test_data = theano.shared(test_data)
	init_weights = 0.1*np.random.randn(len(mapping),2,100)
	W = theano.shared(init_weights)

	matches = T.wmatrix('matches')
	weights = T.dtensor3('weights')
	t_matches = T.wmatrix('t_matches')
	delta   = theano.shared(np.zeros(init_weights.shape))

	cost, accuracy = cost_fn(matches,weights)
	log_loss_fn = log_loss(t_matches,weights)
	grad = T.grad(cost,wrt=weights)
	train = theano.function(
			inputs = [],
			outputs = cost,
			givens  = { matches: data, weights: W },
			updates = [
				(W, W - 0.1*( grad + 0.5 * delta )),
				(delta, 0.1*( grad + 0.5 * delta ))
			]
		)
	test = theano.function(
			inputs = [],
			outputs = [log_loss_fn],
			givens  = { t_matches: test_data, weights: W }
		)
	return train,test,W
开发者ID:shawntan,项目名称:march-madness-2014,代码行数:29,代码来源:model.py


示例7: test_simple_3d

    def test_simple_3d(self):
        """Increments or sets part of a tensor by a scalar using full slice and
        a partial slice depending on a scalar.
        """
        a = tt.dtensor3()
        increment = tt.dscalar()
        sl1 = slice(None)
        sl2_end = tt.lscalar()
        sl2 = slice(sl2_end)
        sl3 = 2

        for do_set in [True, False]:
            print "Set", do_set

            if do_set:
                resut = tt.set_subtensor(a[sl1, sl3, sl2], increment)
            else:
                resut = tt.inc_subtensor(a[sl1, sl3, sl2], increment)

            f = theano.function([a, increment, sl2_end], resut)

            val_a = numpy.ones((5, 3, 4))
            val_inc = 2.3
            val_sl2_end = 2

            expected_result = numpy.copy(val_a)
            result = f(val_a, val_inc, val_sl2_end)

            if do_set:
                expected_result[:, sl3, :val_sl2_end] = val_inc
            else:
                expected_result[:, sl3, :val_sl2_end] += val_inc

            self.assertTrue(numpy.array_equal(result, expected_result))
开发者ID:DeepLearningIndia,项目名称:Theano,代码行数:34,代码来源:test_inc_subtensor.py


示例8: test_max_pool_2d_3D

    def test_max_pool_2d_3D(self):
        rng = numpy.random.RandomState(utt.fetch_seed())

        maxpoolshps = [(1,2)]
        imval = rng.rand(2,3,4)
        images = tensor.dtensor3()

        for maxpoolshp in maxpoolshps:
            for ignore_border in [True,False]:
                #print 'maxpoolshp =', maxpoolshp
                #print 'ignore_border =', ignore_border
                numpy_output_val = self.numpy_max_pool_2d(imval, maxpoolshp, ignore_border)

                output = max_pool_2d(images, maxpoolshp, ignore_border)
                output_val = function([images], output)(imval)
                assert numpy.all(output_val == numpy_output_val)

                c = tensor.sum(output)
                c_val = function([images], c)(imval)

                g = tensor.grad(c, images)
                g_val = function([images],
                        [g.shape,
                            tensor.min(g, axis=(0,1,2)),
                            tensor.max(g, axis=(0,1,2))]
                        )(imval)
开发者ID:NicolasBouchard,项目名称:Theano,代码行数:26,代码来源:test_downsample.py


示例9: __init__

    def __init__(self,retina=None,config=None,name=None,input_variable=None): 
        self.retina = retina 
        self.config = config
        self.state = None
        if name is None:
            name = str(uuid.uuid4())
        self.name = self.config.get('name',name)
        # 3d version
        self._I = T.dtensor3(self.name+"_I")
        self._preceding_V = T.dmatrix(self.name+"_preceding_V") # initial condition for sequence
        self._b_0 = T.dscalar(self.name+"_b_0")
        self._a_0 = T.dscalar(self.name+"_a_0")
        self._a_1 = T.dscalar(self.name+"_a_1")
        self._k = T.iscalar(self.name+"_k_bip") # number of iteration steps
        def bipolar_step(input_image,
                        preceding_V,b_0, a_0, a_1):
            V = (input_image * b_0 - preceding_V * a_1) / a_0
            return V

        # The order in theano.scan has to match the order of arguments in the function bipolar_step
        self._result, self._updates = theano.scan(fn=bipolar_step,
                                      outputs_info=[self._preceding_V],
                                      sequences = [self._I],
                                      non_sequences=[self._b_0, self._a_0, self._a_1],
                                      n_steps=self._k)
        self.output_varaible = self._result[0]
        # The order of arguments presented here is arbitrary (will be inferred by the symbols provided),
        #  but function calls to compute_V_bip have to match this order!
        self.compute_V = theano.function(inputs=[self._I,self._preceding_V,
                                                      self._b_0, self._a_0, self._a_1,
                                                      self._k], 
                                              outputs=self._result, 
                                              updates=self._updates)
开发者ID:jahuth,项目名称:retina,代码行数:33,代码来源:vision.py


示例10: make_minimizer

def make_minimizer(Model):
    L, y = T.ivector('L'), T.dvector('y')
    mu, eps = T.dscalar('mu'), T.dscalar('eps')
    R, eta = T.dtensor3('R'),  T.dvector('eta')

    model = Model(L, y, mu, R, eta, eps)
    return theano.function([L, y, mu, R, eta, eps], model.minimize())
开发者ID:pminervini,项目名称:knowledge-propagation,代码行数:7,代码来源:momentum.py


示例11: UV12_input

def UV12_input(V1=Th.dmatrix(),
               STAs=Th.dmatrix(),
               STCs=Th.dtensor3(),
               N_spikes=Th.dvector(),
               **other):
    other.update(locals())
    return named(**other)
开发者ID:kolia,项目名称:subunits,代码行数:7,代码来源:QuadPoiss.py


示例12: preprocess_state

    def preprocess_state(self, state): #TODO: Display to cross check.
        """
        Preprocess a sequence of frames that make up a state.

        Args:
        -----
            state: A sequence of frames.

        Returns:
        --------
            Preprocessed state    
        """
        N, m, n = self.agent_params['state_frames'], self.game_params['crop_hei'], self.game_params['crop_wid']
        factor = self.game_params['factor']
        maxed = np.zeros((N, m, n), dtype='float64')

        # max pool and downsample
        maxed[0] = state[0].reshape(m, n)
        for i in xrange(1, len(state)):
            maxed[i] = np.max(np.asarray(state[i - 1: i]), axis=0).reshape(m, n)

        x = tn.dtensor3('x')
        f = thn.function([x], downsample.max_pool_2d(x, factor))
        downsampled = f(maxed)

        if self.ale_params['display_state']:
            s = downsampled[-1].reshape(m / factor[0], n / factor[1])
            plt.figure(1)
            plt.clf()
            plt.imshow(s, 'gray')
            plt.pause(0.005)
        
        return downsampled.reshape(1, np.prod(downsampled.shape[0:])) #Stack
开发者ID:pperezrubio,项目名称:Atari,代码行数:33,代码来源:game_client.py


示例13: test_max_pool_2d_3D

    def test_max_pool_2d_3D(self):
        rng = numpy.random.RandomState(utt.fetch_seed())
        maxpoolshps = [(1, 2)]
        imval = rng.rand(2, 3, 4)
        images = tensor.dtensor3()

        for maxpoolshp, ignore_border, mode in product(maxpoolshps,
                                                       [True, False],
                                                       ['max', 'sum',
                                                        'average_inc_pad',
                                                        'average_exc_pad']):
                # print 'maxpoolshp =', maxpoolshp
                # print 'ignore_border =', ignore_border
                numpy_output_val = self.numpy_max_pool_2d(imval, maxpoolshp,
                                                          ignore_border,
                                                          mode)
                output = max_pool_2d(images, maxpoolshp, ignore_border,
                                     mode=mode)
                output_val = function([images], output)(imval)
                assert numpy.all(output_val == numpy_output_val), (
                    "output_val is %s, numpy_output_val is %s"
                    % (output_val, numpy_output_val))
                c = tensor.sum(output)
                c_val = function([images], c)(imval)
                g = tensor.grad(c, images)
                g_val = function([images],
                                 [g.shape,
                                 tensor.min(g, axis=(0, 1, 2)),
                                 tensor.max(g, axis=(0, 1, 2))]
                                 )(imval)
开发者ID:harlouci,项目名称:Theano,代码行数:30,代码来源:test_downsample.py


示例14: linear_parameterization

def linear_parameterization( T  = Th.dtensor3() , u  = Th.dvector() , 
                                     **other ):
#                                b = Th.dvector() ,  ub = Th.dvector(), **other ): 
#    U = ( Th.sum( T*ub  , axis=2 ).T * b  ).T + Th.sum( T*u , axis=2 )
    U = Th.sum( T*u , axis=2 )    # U = Th.tensordot(T,u,axes=0)
    other.update(locals())
    return named( **other )
开发者ID:kolia,项目名称:subunits,代码行数:7,代码来源:QuadPoiss.py


示例15: test_max_pool_3d_3D

    def test_max_pool_3d_3D(self):
        rng = numpy.random.RandomState(utt.fetch_seed())
        maxpoolshps = ((1, 1, 1), (3, 2, 1))
        imval = rng.rand(4, 5, 6)
        images = tensor.dtensor3()

        for maxpoolshp, ignore_border, mode in product(maxpoolshps,
                                                       [True, False],
                                                       ['max', 'sum',
                                                        'average_inc_pad',
                                                        'average_exc_pad']):
                # print 'maxpoolshp =', maxpoolshp
                # print 'ignore_border =', ignore_border
                numpy_output_val = self.numpy_max_pool_nd(imval, maxpoolshp,
                                                          ignore_border,
                                                          mode=mode)
                output = pool_3d(images, maxpoolshp, ignore_border,
                                 mode=mode)
                output_val = function([images], output)(imval)
                utt.assert_allclose(output_val, numpy_output_val)

                def mp(input):
                    return pool_3d(input, maxpoolshp, ignore_border,
                                   mode=mode)
                utt.verify_grad(mp, [imval], rng=rng)
开发者ID:wgapl,项目名称:Theano,代码行数:25,代码来源:test_pool.py


示例16: make_theano_tensors

def make_theano_tensors(list_of_datasets):
    theano_tensor = [TT.dscalar(), TT.dvector(), TT.dmatrix(), TT.dtensor3()]
    res = []
    for d_set in list_of_datasets:
        dim = len(np.array(d_set).shape)
        theano_t = deepcopy(theano_tensor[dim])
        res.append(theano_t)
    return res
开发者ID:JeanKossaifi,项目名称:copula_ordinal_regression,代码行数:8,代码来源:utils.py


示例17: linear_reparameterization

def linear_reparameterization( T  = Th.dtensor3('T') , u  = Th.dvector('u') , 
#                               V1 = Th.dmatrix('V1') , V2 = Th.dvector('V2') ,
#                            STAs = Th.dmatrix('STAs'), STCs = Th.dtensor3('STCs'),
#                            N_spikes = Th.dvector('N_spikes'), 
                            **other):
    other['U'] = Th.sum( T*u , axis=2 )
#    other[name] = Th.tensordot(T,u,axes=0)
    return other
开发者ID:kolia,项目名称:subunits,代码行数:8,代码来源:QuadPoiss_old.py


示例18: UV

 def UV( lU   = Th.dmatrix('lU')  , lV1  = Th.dmatrix('lV1') , V2 = Th.dvector('V2') ,
         STAs = Th.dmatrix('STAs'), STCs = Th.dtensor3('STCs'), **other):
     U  = Th.exp(lU + 1e-10)
     V1 = Th.exp(lV1+ 1e-10)
     return [{'theta': Th.dot( U.T , V1[i] ) ,
              'M'  :   Th.dot( V1[i] * U.T , (V2 * U.T).T ),
              'STA':   STAs[i,:],
              'STC':   STCs[i,:,:]} for i in range(N)]
开发者ID:kolia,项目名称:subunits,代码行数:8,代码来源:QuadPoiss_old.py


示例19: test_wrong_input

    def test_wrong_input(self):
        # Make sure errors are raised when image and kernel are not 4D tensors

        self.assertRaises(Exception, self.validate, (3, 2, 8, 8), (4, 2, 5, 5),
                          'valid', input=T.dmatrix())
        self.assertRaises(Exception, self.validate, (3, 2, 8, 8), (4, 2, 5, 5),
                          'valid', filters=T.dvector())
        self.assertRaises(Exception, self.validate, (3, 2, 8, 8), (4, 2, 5, 5),
                          'valid', input=T.dtensor3())
开发者ID:DEVESHTARASIA,项目名称:Theano,代码行数:9,代码来源:test_conv.py


示例20: __build_center

 def __build_center(self):
     # We only want to compile our theano functions once
     imgv = T.dtensor3("imgv")
     # Get the mean
     u = T.mean(imgv, 0)
     # Get the standard deviation
     s = T.std(T.std(imgv, 0), 0)
     # Subtract our mean
     return function(inputs=[imgv], outputs=[(imgv - u) / s])
开发者ID:tkaplan,项目名称:MLTextParser,代码行数:9,代码来源:ImgPreprocessing.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python tensor.dtensor4函数代码示例发布时间:2022-05-27
下一篇:
Python tensor.dscalars函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap