當前位置: 首頁>>代碼示例>>Python>>正文


Python tensor.stack方法代碼示例

本文整理匯總了Python中theano.tensor.stack方法的典型用法代碼示例。如果您正苦於以下問題:Python tensor.stack方法的具體用法?Python tensor.stack怎麽用?Python tensor.stack使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在theano.tensor的用法示例。


在下文中一共展示了tensor.stack方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _create_observation_variable

# 需要導入模塊: from theano import tensor [as 別名]
# 或者: from theano.tensor import stack [as 別名]
def _create_observation_variable(individual_selections, choices, partsworth):
    """
    This function handles creating the PyMC3 observation variables.  It also gracefully handles missing observations in individual selections.

    `individual_selections` is a Series of the individuals selections made, starting from 0. It can contain NaNs which represent answer was not provided.

    `choices` is a DataFrame with a hierarchical index: level=0 enumerates the choices, and level=1 displays the profile at a specific choice.
    It's size is (n_questions, n_choices_per_question).

    `partsworth` is a slice of PyMC3 matrix. It represents the partsworth variables of a individual. Size is (n_profiles,)

    This computes the values exp(partsworth * profile_j) / sum[ exp(partsworth * profile_k ] for all j.
    """
    nan_mask = pd.notnull(individual_selections)
    return pm.Categorical("Obs_%s" % individual_selections.name,
                          tt.nnet.softmax(tt.stack([
                            tt.dot(choice.values, partsworth) for _, choice in choices[nan_mask.values].groupby(axis=1, level=0)
                          ], axis=0).T),
                          observed=individual_selections[nan_mask.values].values) 
開發者ID:CamDavidsonPilon,項目名稱:lifestyles,代碼行數:21,代碼來源:cbc_hb.py

示例2: __init__

# 需要導入模塊: from theano import tensor [as 別名]
# 或者: from theano.tensor import stack [as 別名]
def __init__(self):
        def f(x, u, i, terminal):
            if terminal:
                ctrl_cost = T.zeros_like(x[..., 0])
            else:
                ctrl_cost = T.square(u).sum(axis=-1)

            # x: (batch_size, 8)
            # x[..., 0:4]: qpos
            # x[..., 4:8]: qvel, time derivatives of qpos, not used in the cost.
            theta = x[..., 0]  # qpos[0]: angle of joint 0
            phi = x[..., 1]  # qpos[1]: angle of joint 1
            target_xpos = x[..., 2:4]  # qpos[2:4], target x & y coordinate
            body1_xpos = 0.1 * T.stack([T.cos(theta), T.sin(theta)], axis=1)
            tip_xpos_incr = 0.11 * T.stack([T.cos(phi), T.sin(phi)], axis=1)
            tip_xpos = body1_xpos + tip_xpos_incr
            delta = tip_xpos - target_xpos

            state_cost = T.sqrt(T.sum(delta * delta, axis=-1))
            cost = state_cost + ctrl_cost

            return cost

        super().__init__(f, state_size=8, action_size=2) 
開發者ID:HumanCompatibleAI,項目名稱:adversarial-policies,代碼行數:26,代碼來源:mujoco_costs.py

示例3: grad

# 需要導入模塊: from theano import tensor [as 別名]
# 或者: from theano.tensor import stack [as 別名]
def grad(self, inputs, gout):
        (gz,) = gout
        is_continuous = [(inputs[i].dtype in tensor.continuous_dtypes)
                         for i in range(len(inputs))]

        if _is_sparse_variable(gz):
            gz = dense_from_sparse(gz)

        split = tensor.Split(len(inputs))(gz, 1,
                                          tensor.stack(
                                              [x.shape[1]
                                               for x in inputs]))
        if not isinstance(split, list):
            split = [split]

        derivative = [SparseFromDense(self.format)(s) for s in split]

        def choose(continuous, derivative):
            if continuous:
                return derivative
            else:
                return None
        return [choose(c, d) for c, d in zip(is_continuous, derivative)] 
開發者ID:muhanzhang,項目名稱:D-VAE,代碼行數:25,代碼來源:basic.py

示例4: infer_shape

# 需要導入模塊: from theano import tensor [as 別名]
# 或者: from theano.tensor import stack [as 別名]
def infer_shape(self, node, in_shapes):
        shape_a = in_shapes[0]
        n = node.inputs[1]
        axis = node.inputs[2]
        if len(shape_a) == 1:
            return [(n,)]
        elif isinstance(axis, tensor.TensorConstant):
            out_shape = (list(shape_a[0: axis.data.item()]) + [n] +
                         list(shape_a[axis.data + 1:]))
        else:
            l = len(shape_a)
            shape_a = tensor.stack(shape_a)
            out_shape = tensor.concatenate((shape_a[0: axis], [n],
                                            shape_a[axis + 1:]))
            n_splits = [1] * l
            out_shape = tensor.split(out_shape, n_splits, l)
            out_shape = [a[0] for a in out_shape]
        return [out_shape] 
開發者ID:muhanzhang,項目名稱:D-VAE,代碼行數:20,代碼來源:fourier.py

示例5: errors4one

# 需要導入模塊: from theano import tensor [as 別名]
# 或者: from theano.tensor import stack [as 別名]
def errors4one(self, z, out, weight=None, distLabelType='12C'):
	distBins = config.distCutoffs[distLabelType]
	label8 = DistanceUtils.LabelsOfOneDistance(config.ContactDefinition, distBins)
	label15 = DistanceUtils.LabelsOfOneDistance(config.InteractionLimit, distBins)

	z3C = T.cast( T.ge(z, label8), 'int32') + T.cast( T.ge(z, label15), 'int32')
	o3C = T.cast( T.ge(out, label8), 'int32') + T.cast( T.ge(out, label15), 'int32')

	if weight is not None:
            err = T.sum( T.mul(weight, T.neq(o3C, z3C) ) )*1./T.sum(weight)
	else:
            err = T.mean( T.neq(o3C , z3C) ) 

	## err is s scalar, convert it to a tensor with ndim=1
	return T.stack([err] )

    ## this function returns a vector of errors, the size of this vector is equal to the sum of ValueDims for all the responses 
開發者ID:j3xugit,項目名稱:RaptorX-Contact,代碼行數:19,代碼來源:Model4DistancePrediction.py

示例6: parameter_stats

# 需要導入模塊: from theano import tensor [as 別名]
# 或者: from theano.tensor import stack [as 別名]
def parameter_stats(parameters, algorithm):
    vars_ = []
    for name, param in parameters.items():
        num_elements = numpy.product(param.get_value().shape)
        norm = param.norm(2) / num_elements ** 0.5
        trained_param = param in algorithm.gradients
        if trained_param:
            grad_norm = algorithm.gradients[param].norm(2) / num_elements ** 0.5
            step_norm = algorithm.steps[param].norm(2) / num_elements ** 0.5
            relative_step_norm = step_norm / grad_norm
        else:
            grad_norm = 0.
            step_norm = 0.
            relative_step_norm = 0.
        stats = tensor.stack(norm, grad_norm, step_norm, relative_step_norm)
        stats.name = name + '_stats'
        vars_.append(stats)
    return vars_ 
開發者ID:tombosc,項目名稱:cpae,代碼行數:20,代碼來源:theano_util.py

示例7: normalize_batch_in_training

# 需要導入模塊: from theano import tensor [as 別名]
# 或者: from theano.tensor import stack [as 別名]
def normalize_batch_in_training(x, gamma, beta,
                                reduction_axes, epsilon=0.0001):
    '''Compute mean and std for batch then apply batch_normalization on batch.
    '''
    var = x.var(reduction_axes)
    mean = x.mean(reduction_axes)

    target_shape = []
    for axis in range(ndim(x)):
        if axis in reduction_axes:
            target_shape.append(1)
        else:
            target_shape.append(x.shape[axis])
    target_shape = T.stack(*target_shape)

    broadcast_mean = T.reshape(mean, target_shape)
    broadcast_var = T.reshape(var, target_shape)
    broadcast_beta = T.reshape(beta, target_shape)
    broadcast_gamma = T.reshape(gamma, target_shape)
    normed = batch_normalization(x, broadcast_mean, broadcast_var,
                                 broadcast_beta, broadcast_gamma,
                                 epsilon)
    return normed, mean, var 
開發者ID:GUR9000,項目名稱:KerasNeuralFingerprint,代碼行數:25,代碼來源:theano_backend.py

示例8: new_episode

# 需要導入模塊: from theano import tensor [as 別名]
# 或者: from theano.tensor import stack [as 別名]
def new_episode(self, mem):
        g, g_updates = theano.scan(fn=self.new_attention_step,
            sequences=self.inp_c,
            non_sequences=[mem, self.q_q],
            outputs_info=T.zeros_like(self.inp_c[0][0])) 
        
        if (self.normalize_attention):
            g = nn_utils.softmax(g)
        
        e, e_updates = theano.scan(fn=self.new_episode_step,
            sequences=[self.inp_c, g],
            outputs_info=T.zeros_like(self.inp_c[0]))
        
        e_list = []
        for index in range(self.batch_size):
            e_list.append(e[self.fact_count_var[index] - 1, :, index])
        return T.stack(e_list).dimshuffle((1, 0)) 
開發者ID:YerevaNN,項目名稱:Dynamic-memory-networks-in-Theano,代碼行數:19,代碼來源:dmn_batch.py

示例9: select_finite_faults

# 需要導入模塊: from theano import tensor [as 別名]
# 或者: from theano.tensor import stack [as 別名]
def select_finite_faults(self):
        fault_points = T.vertical_stack(T.stack([self.ref_layer_points[0]], axis=0), self.rest_layer_points).T
        ctr = T.mean(fault_points, axis=1)
        x = fault_points - ctr.reshape((-1, 1))
        M = T.dot(x, x.T)
        U = T.nlinalg.svd(M)[2]
        rotated_x = T.dot(self.x_to_interpolate(), U)
        rotated_fault_points = T.dot(fault_points.T, U)
        rotated_ctr = T.mean(rotated_fault_points, axis=0)
        a_radius = (rotated_fault_points[:, 0].max() - rotated_fault_points[:, 0].min()) / 2 + self.inf_factor[
            self.n_surface_op[0] - 1]
        b_radius = (rotated_fault_points[:, 1].max() - rotated_fault_points[:, 1].min()) / 2 + self.inf_factor[
            self.n_surface_op[0] - 1]
        sel = T.lt((rotated_x[:, 0] - rotated_ctr[0]) ** 2 / a_radius ** 2 + (
                    rotated_x[:, 1] - rotated_ctr[1]) ** 2 / b_radius ** 2,
                   1)

        if "select_finite_faults" in self.verbose:
            sel = theano.printing.Print("scalar_field_iter")(sel)

        return sel 
開發者ID:cgre-aachen,項目名稱:gempy,代碼行數:23,代碼來源:theano_export.py

示例10: set_rest_ref_matrix

# 需要導入模塊: from theano import tensor [as 別名]
# 或者: from theano.tensor import stack [as 別名]
def set_rest_ref_matrix(self, number_of_points_per_surface):
        ref_positions = T.cumsum(T.concatenate((T.stack([0]), number_of_points_per_surface[:-1] + 1)))
        cum_rep = T.cumsum(T.concatenate((T.stack([0]), number_of_points_per_surface)))

        ref_points_init = T.zeros((cum_rep[-1], 3))
        ref_points_loop, update_ = theano.scan(self.repeat_list,
                                               outputs_info=[ref_points_init],
                                               sequences=[self.surface_points_all[ref_positions],
                                                          dict(input=cum_rep, taps=[0, 1])],
                                               non_sequences=[T.as_tensor(3)],

                                               return_list=False)

        #   ref_points_loop = theano.printing.Print('loop')(ref_points_loop)
        ref_points = ref_points_loop[-1]
        #  ref_points = T.repeat(self.surface_points_all[ref_positions], number_of_points_per_surface, axis=0)

        rest_mask = T.ones(T.stack([self.surface_points_all.shape[0]]), dtype='int16')
        rest_mask = T.set_subtensor(rest_mask[ref_positions], 0)
        rest_mask = T.nonzero(rest_mask)[0]
        rest_points = self.surface_points_all[rest_mask]
        return [ref_points, rest_points, ref_positions, rest_mask] 
開發者ID:cgre-aachen,項目名稱:gempy,代碼行數:24,代碼來源:theano_graph_pro.py

示例11: set_nugget_surface_points

# 需要導入模塊: from theano import tensor [as 別名]
# 或者: from theano.tensor import stack [as 別名]
def set_nugget_surface_points(self, ref_positions, rest_mask, number_of_points_per_surface):
        # ref_nugget = T.repeat(self.nugget_effect_scalar_T[ref_positions], number_of_points_per_surface)
        cum_rep = T.cumsum(T.concatenate((T.stack([0]), number_of_points_per_surface)))
        ref_nugget_init = T.zeros((cum_rep[-1], 1))
        ref_nugget_loop, update_ = theano.scan(self.repeat_list,
                                               outputs_info=[ref_nugget_init],
                                               sequences=[self.nugget_effect_scalar_T[ref_positions],
                                                          dict(input=cum_rep, taps=[0, 1])],
                                               non_sequences=[T.as_tensor(1)],
                                               return_list=False)

        # ref_nugget_loop = theano.printing.Print('loop')(ref_nugget_loop)
        ref_nugget = ref_nugget_loop[-1]

        rest_nugget = self.nugget_effect_scalar_T[rest_mask]
        nugget_rest_ref = ref_nugget.reshape((1, -1))[0] + rest_nugget
        return nugget_rest_ref 
開發者ID:cgre-aachen,項目名稱:gempy,代碼行數:19,代碼來源:theano_graph_pro.py

示例12: _old_normalize_batch_in_training

# 需要導入模塊: from theano import tensor [as 別名]
# 或者: from theano.tensor import stack [as 別名]
def _old_normalize_batch_in_training(x, gamma, beta,
                                     reduction_axes, epsilon=1e-3):
    '''Computes mean and std for batch then apply batch_normalization on batch.
    '''
    dev = theano.config.device
    use_cudnn = ndim(x) < 5 and reduction_axes == [0, 2, 3] and (dev.startswith('cuda') or dev.startswith('gpu'))
    if use_cudnn:
        broadcast_beta = beta.dimshuffle('x', 0, 'x', 'x')
        broadcast_gamma = gamma.dimshuffle('x', 0, 'x', 'x')
        try:
            normed, mean, stdinv = theano.sandbox.cuda.dnn.dnn_batch_normalization_train(
                x, broadcast_gamma, broadcast_beta, 'spatial', epsilon)
            var = T.inv(stdinv ** 2)
            return normed, T.flatten(mean), T.flatten(var)
        except AttributeError:
            pass

    var = x.var(reduction_axes)
    mean = x.mean(reduction_axes)

    target_shape = []
    for axis in range(ndim(x)):
        if axis in reduction_axes:
            target_shape.append(1)
        else:
            target_shape.append(x.shape[axis])
    target_shape = T.stack(*target_shape)

    broadcast_mean = T.reshape(mean, target_shape)
    broadcast_var = T.reshape(var, target_shape)
    broadcast_beta = T.reshape(beta, target_shape)
    broadcast_gamma = T.reshape(gamma, target_shape)
    normed = batch_normalization(x, broadcast_mean, broadcast_var,
                                 broadcast_beta, broadcast_gamma,
                                 epsilon)
    return normed, mean, var


# TODO remove this if statement when Theano without
# T.nnet.bn.batch_normalization_test is deprecated 
開發者ID:lingluodlut,項目名稱:Att-ChemdNER,代碼行數:42,代碼來源:theano_backend.py

示例13: stack

# 需要導入模塊: from theano import tensor [as 別名]
# 或者: from theano.tensor import stack [as 別名]
def stack(x):
    return T.stack(*x) 
開發者ID:lingluodlut,項目名稱:Att-ChemdNER,代碼行數:4,代碼來源:theano_backend.py

示例14: _grad

# 需要導入模塊: from theano import tensor [as 別名]
# 或者: from theano.tensor import stack [as 別名]
def _grad(mat):
    grad_y = (mat[idx1, :] - mat[idx2, :]) * h
    grad_x = (mat[:, idx1] - mat[:, idx2]) * h

    # Ret shape: 2x224x224
    return T.stack([grad_y, grad_x], axis=0) 
開發者ID:wiseodd,項目名稱:cnn-levelset,代碼行數:8,代碼來源:segmenter.py

示例15: pack

# 需要導入模塊: from theano import tensor [as 別名]
# 或者: from theano.tensor import stack [as 別名]
def pack(x):
    return T.stack(*x)

# VALUE MANIPULATION 
開發者ID:mathDR,項目名稱:reading-text-in-the-wild,代碼行數:6,代碼來源:theano_backend.py


注:本文中的theano.tensor.stack方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。