GVKun编程网logo

Python numpy 模块-cast() 实例源码(python casting)

7

在这篇文章中,我们将带领您了解Pythonnumpy模块-cast()实例源码的全貌,包括pythoncasting的相关情况。同时,我们还将为您介绍有关Electron/Mongoose/Mongo

在这篇文章中,我们将带领您了解Python numpy 模块-cast() 实例源码的全貌,包括python casting的相关情况。同时,我们还将为您介绍有关Electron / Mongoose / MongoDB Cast 错误:“错误:有效负载验证失败:video_buffer:对于值“Uint8Array..”,Cast to Buffer 失败、herbetr 遇到 Cannot cast java.lang.Character to java.lang.Stringat java.lang.Class.cast、java.util.LinkedHashMap cannot be cast to xxx 和 net.sf.ezmorph.bean.MorphDynaBean cannot be cast ...、java中的类型安全问题-Type safety: Unchecked cast from Object to ... 或者 Type safety: Unchecked cast from T...的知识,以帮助您更好地理解这个主题。

本文目录一览:

Python numpy 模块-cast() 实例源码(python casting)

Python numpy 模块-cast() 实例源码(python casting)

Python numpy 模块,cast() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用numpy.cast()

项目:odin    作者:imito    | 项目源码 | 文件源码
  1. def glorot_normal(shape, gain=1.0, c01b=False):
  2. orig_shape = shape
  3. if c01b:
  4. if len(shape) != 4:
  5. raise RuntimeError(
  6. "If c01b is True,only shapes of length 4 are accepted")
  7. n1, n2 = shape[0], shape[3]
  8. receptive_field_size = shape[1] * shape[2]
  9. else:
  10. if len(shape) < 2:
  11. shape = (1,) + tuple(shape)
  12. n1, n2 = shape[:2]
  13. receptive_field_size = np.prod(shape[2:])
  14.  
  15. std = gain * np.sqrt(2.0 / ((n1 + n2) * receptive_field_size))
  16. return np.cast[floatX](
  17. get_rng().normal(0.0, std, size=orig_shape))
项目:GELUs    作者:hendrycks    | 项目源码 | 文件源码
  1. def adamax_updates(params, cost, lr=0.001, mom1=0.9, mom2=0.999):
  2. updates = []
  3. grads = T.grad(cost, params)
  4. for p, g in zip(params, grads):
  5. mg = th.shared(np.cast[th.config.floatX](p.get_value() * 0.))
  6. v = th.shared(np.cast[th.config.floatX](p.get_value() * 0.))
  7. if mom1>0:
  8. v_t = mom1*v + (1. - mom1)*g
  9. updates.append((v,v_t))
  10. else:
  11. v_t = g
  12. mg_t = T.maximum(mom2*mg, abs(g))
  13. g_t = v_t / (mg_t + 1e-6)
  14. p_t = p - lr * g_t
  15. updates.append((mg, mg_t))
  16. updates.append((p, p_t))
  17. return updates
项目:GELUs    作者:hendrycks    | 项目源码 | 文件源码
  1. def adam_updates(params, params)
  2. t = th.shared(np.cast[th.config.floatX](1.))
  3. for p, grads):
  4. v = th.shared(np.cast[th.config.floatX](p.get_value() * 0.))
  5. mg = th.shared(np.cast[th.config.floatX](p.get_value() * 0.))
  6. v_t = mom1*v + (1. - mom1)*g
  7. mg_t = mom2*mg + (1. - mom2)*T.square(g)
  8. v_hat = v_t / (1. - mom1 ** t)
  9. mg_hat = mg_t / (1. - mom2 ** t)
  10. g_t = v_hat / T.sqrt(mg_hat + 1e-8)
  11. p_t = p - lr * g_t
  12. updates.append((v, v_t))
  13. updates.append((mg, p_t))
  14. updates.append((t, t+1))
  15. return updates
项目:deligan    作者:val-iisc    | 项目源码 | 文件源码
  1. def adam_updates(params, t+1))
  2. return updates
项目:deligan    作者:val-iisc    | 项目源码 | 文件源码
  1. def get_output_for(self, input, deterministic=False, **kwargs):
  2. if deterministic:
  3. norm_features = (input-self.avg_batch_mean.dimshuffle(*self.dimshuffle_args)) / T.sqrt(1e-6 + self.avg_batch_var).dimshuffle(*self.dimshuffle_args)
  4. else:
  5. batch_mean = T.mean(input,axis=self.axes_to_sum).flatten()
  6. centered_input = input-batch_mean.dimshuffle(*self.dimshuffle_args)
  7. batch_var = T.mean(T.square(centered_input),axis=self.axes_to_sum).flatten()
  8. batch_stdv = T.sqrt(1e-6 + batch_var)
  9. norm_features = centered_input / batch_stdv.dimshuffle(*self.dimshuffle_args)
  10.  
  11. # BN updates
  12. new_m = 0.9*self.avg_batch_mean + 0.1*batch_mean
  13. new_v = 0.9*self.avg_batch_var + T.cast((0.1*input.shape[0])/(input.shape[0]-1),th.config.floatX)*batch_var
  14. self.bn_updates = [(self.avg_batch_mean, new_m), (self.avg_batch_var, new_v)]
  15.  
  16. if hasattr(self, ''g''):
  17. activation = norm_features*self.g.dimshuffle(*self.dimshuffle_args)
  18. else:
  19. activation = norm_features
  20. if hasattr(self, ''b''):
  21. activation += self.b.dimshuffle(*self.dimshuffle_args)
  22.  
  23. return self.nonlinearity(activation)
项目:deligan    作者:val-iisc    | 项目源码 | 文件源码
  1. def get_output_for(self, ''b''):
  2. activation += self.b.dimshuffle(*self.dimshuffle_args)
  3.  
  4. return self.nonlinearity(activation)
项目:structured-output-ae    作者:sbelharbi    | 项目源码 | 文件源码
  1. def __call__(self, learning_rate):
  2. """Update the learning rate according to the exponential decay
  3. schedule.
  4.  
  5. """
  6. if self._count == 0.:
  7. self._base_lr = learning_rate.get_vale()
  8. self._count += 1
  9.  
  10. if not self._min_reached:
  11. new_lr = self._base_lr * (self.decay_factor ** (-self._count))
  12. if new_lr <= self.min_lr:
  13. self._min_reached = True
  14. new_lr = self._min_reached
  15. else:
  16. new_lr = self.min_lr
  17.  
  18. learning_rate.set_value(np.cast[theano.config.floatX](new_lr))
项目:NMT    作者:tuzhaopeng    | 项目源码 | 文件源码
  1. def as_floatX(variable):
  2. """
  3. This code is taken from pylearn2:
  4. Casts a given variable into dtype config.floatX
  5. numpy ndarrays will remain numpy ndarrays
  6. python floats will become 0-D ndarrays
  7. all other types will be treated as theano tensors
  8. """
  9.  
  10. if isinstance(variable, float):
  11. return numpy.cast[theano.config.floatX](variable)
  12.  
  13. if isinstance(variable, numpy.ndarray):
  14. return numpy.cast[theano.config.floatX](variable)
  15.  
  16. return theano.tensor.cast(variable, theano.config.floatX)
项目:NMT    作者:tuzhaopeng    | 项目源码 | 文件源码
  1. def as_floatX(variable):
  2. """
  3. This code is taken from pylearn2:
  4. Casts a given variable into dtype config.floatX
  5. numpy ndarrays will remain numpy ndarrays
  6. python floats will become 0-D ndarrays
  7. all other types will be treated as theano tensors
  8. """
  9.  
  10. if isinstance(variable, theano.config.floatX)
项目:merlin    作者:CSTR-Edinburgh    | 项目源码 | 文件源码
  1. def parameter_prediction(self, test_set_x): #,batch_size
  2. """ This function is to predict the output of NN
  3.  
  4. :param test_set_x: input features for a testing sentence
  5. :type test_set_x: python array variable
  6. :returns: predicted features
  7.  
  8. """
  9.  
  10.  
  11. n_test_set_x = test_set_x.shape[0]
  12.  
  13. test_out = theano.function([], self.final_layer.output,
  14. givens={self.x: test_set_x, self.is_train: np.cast[''int32''](0)}, on_unused_input=''ignore'')
  15.  
  16. predict_parameter = test_out()
  17.  
  18. return predict_parameter
  19.  
  20. ## the function to output activations at a hidden layer
项目:merlin    作者:CSTR-Edinburgh    | 项目源码 | 文件源码
  1. def generate_hidden_layer(self, test_set_x, bn_layer_index):
  2. """ This function is to predict the bottleneck features of NN
  3.  
  4. :param test_set_x: input features for a testing sentence
  5. :type test_set_x: python array variable
  6. :returns: predicted bottleneck features
  7.  
  8. """
  9.  
  10. n_test_set_x = test_set_x.shape[0]
  11.  
  12. test_out = theano.function([], self.rnn_layers[bn_layer_index].output,
  13. givens={self.x: test_set_x, on_unused_input=''ignore'')
  14.  
  15. predict_parameter = test_out()
  16.  
  17. return predict_parameter
项目:merlin    作者:CSTR-Edinburgh    | 项目源码 | 文件源码
  1. def parameter_prediction(self,
  2. givens={self.x: test_set_x[0:n_test_set_x], on_unused_input=''ignore'')
  3.  
  4. predict_parameter = test_out()
  5.  
  6. return predict_parameter
项目:merlin    作者:CSTR-Edinburgh    | 项目源码 | 文件源码
  1. def parameter_prediction_S2S(self, test_set_d):
  2. """ This function is to predict the output of NN
  3.  
  4. :param test_set_x: input features for a testing sentence
  5. :param test_set_d: phone durations for a testing sentence
  6. :type test_set_x: python array variable
  7. :type test_set_d: python array variable
  8. :returns: predicted features
  9.  
  10. """
  11.  
  12. n_test_set_x = test_set_x.shape[0]
  13.  
  14. test_out = theano.function([],
  15. givens={self.x: test_set_x[0:n_test_set_x], self.d: test_set_d[0:n_test_set_x], on_unused_input=''ignore'')
  16.  
  17. predict_parameter = test_out()
  18.  
  19. return predict_parameter
项目:merlin    作者:CSTR-Edinburgh    | 项目源码 | 文件源码
  1. def generate_hidden_layer(self, on_unused_input=''ignore'')
  2.  
  3. predict_parameter = test_out()
  4.  
  5. return predict_parameter
项目:gandlf    作者:codekansas    | 项目源码 | 文件源码
  1. def get_training_data(num_samples):
  2. """Generates some training data."""
  3.  
  4. # As (x,y) Cartesian coordinates.
  5. x = np.random.randint(0, 2, size=(num_samples, 2))
  6.  
  7. y = x[:, 0] + 2 * x[:, 1] # 2-digit binary to integer.
  8. y = np.cast[''int32''](y)
  9.  
  10. x = np.cast[''float32''](x) * 1.6 - 0.8 # Scales to [-1,1].
  11. x += np.random.uniform(-0.1, 0.1, size=x.shape)
  12.  
  13. y_ohe = np.cast[''float32''](np.eye(4)[y])
  14. y = np.cast[''float32''](np.expand_dims(y, -1))
  15.  
  16. return x, y, y_ohe
项目:PIC    作者:ameroyer    | 项目源码 | 文件源码
  1. def pcnn_norm(x, colorspace="RGB", reverse=False):
  2. """normalize the input from and to [-1,1].
  3.  
  4. Args:
  5. x: input image array (3D or 4D)
  6. colorspace (str): Source/target colorspace,depending on the value of `reverse`
  7. reverse (bool,optional): If False,converts the input from the given colorspace to float in the range [-1,1].
  8. Otherwise,converts the input to the valid range for the given colorspace. Defaults to False.
  9.  
  10. Returns:
  11. x_norm: normalized input
  12. """
  13. if colorspace == "RGB":
  14. return np.cast[np.uint8](x * 127.5 + 127.5) if reverse else np.cast[np.float32]((x - 127.5) / 127.5)
  15. elif colorspace == "lab":
  16. if x.shape[-1] == 1:
  17. return (x * 50. + 50.) if reverse else np.cast[np.float32]((x - 50.) / 50.)
  18. else:
  19. a = np.array([50., +0.5, -0.5], dtype=np.float32)
  20. b = np.array([50., 127.5, 127.5], dtype=np.float32)
  21. return np.cast[np.float64](x * b + a) if reverse else np.cast[np.float32]((x - a) / b)
  22. else:
  23. raise ValueError("UnkNown colorspace" % colorspace)
项目:Theano-MPI    作者:uoguelph-mlrg    | 项目源码 | 文件源码
  1. def __init__(self, n_in, n_out, prob_drop=0.5, verbose=False):
  2.  
  3. self.verbose = verbose
  4. self.prob_drop = prob_drop
  5. self.prob_keep = 1.0 - prob_drop
  6. self.flag_on = theano.shared(np.cast[theano.config.floatX](1.0))
  7. self.flag_off = 1.0 - self.flag_on
  8.  
  9. seed_this = DropoutLayer.seed_common.randint(0, 2**31-1)
  10. mask_rng = theano.tensor.shared_randomstreams.RandomStreams(seed_this)
  11. self.mask = mask_rng.binomial(n=1, p=self.prob_keep, size=input.shape)
  12.  
  13. self.output = \\
  14. self.flag_on * T.cast(self.mask, theano.config.floatX) * input + \\
  15. self.flag_off * self.prob_keep * input
  16.  
  17. DropoutLayer.layers.append(self)
  18.  
  19. if self.verbose:
  20. print ''dropout layer with P_drop: '' + str(self.prob_drop)
项目:DeepEnhancer    作者:minxueric    | 项目源码 | 文件源码
  1. def load_data(dataset):
  2. if dataset.split(''.'')[-1] == ''gz'':
  3. f = gzip.open(dataset, ''r'')
  4. else:
  5. f = open(dataset, ''r'')
  6. train_set, valid_set, test_set = pkl.load(f)
  7. f.close()
  8.  
  9. def shared_dataset(data_xy, borrow=True):
  10. data_x, data_y = data_xy
  11. shared_x = theano.shared(
  12. np.asarray(data_x, dtype=theano.config.floatX),
  13. borrow=borrow)
  14. shared_y = theano.shared(
  15. np.asarray(data_y,
  16. borrow=borrow)
  17. return shared_x, T.cast(shared_y, ''int32'')
  18.  
  19. train_set_x, train_set_y = shared_dataset(train_set)
  20. valid_set_x, valid_set_y = shared_dataset(valid_set)
  21. test_set_x, test_set_y = shared_dataset(test_set)
  22.  
  23. return [(train_set_x, train_set_y),
  24. (valid_set_x, valid_set_y),
  25. (test_set_x, test_set_y )]
项目:DeepEnhancer    作者:minxueric    | 项目源码 | 文件源码
  1. def adam(loss, params, learning_rate, beta1=0.9, beta2=0.999, epsilon=1e-8):
  2. grads = T.grad(loss, params)
  3. updates = OrderedDict()
  4. t_prev = theano.shared(np.cast[theano.config.floatX](0))
  5. t = t_prev + 1
  6. a_t = learning_rate * T.sqrt(1-beta2**t)/(1-beta1**t)
  7. for param, grad in zip(params, grads):
  8. value = param.get_value(borrow=True)
  9. m_prev = theano.shared(
  10. np.zeros(value.shape, dtype=value.dtype),
  11. broadcastable=param.broadcastable)
  12. v_prev = theano.shared(
  13. np.zeros(value.shape,
  14. broadcastable=param.broadcastable)
  15. m_t = beta1 * m_prev + (1 - beta1) * grad
  16. v_t = beta2 * v_prev + (1 - beta2) * grad ** 2
  17. step = a_t * m_t / (T.sqrt(v_t) + epsilon)
  18.  
  19. updates[m_prev] = m_t
  20. updates[v_prev] = v_t
  21. updates[param] = param - step
  22. updates[t_prev] = t
  23. return updates
项目:deep-learning-models    作者:kuleshov    | 项目源码 | 文件源码
  1. def get_output_for(self, ''b''):
  2. activation += self.b.dimshuffle(*self.dimshuffle_args)
  3.  
  4. return self.nonlinearity(activation)
项目:tefla    作者:openAGI    | 项目源码 | 文件源码
  1. def one_hot(labels, num_classes, name=''one_hot''):
  2. """Transform numeric labels into onehot_labels.
  3. Args:
  4. labels: [batch_size] target labels.
  5. num_classes: total number of classes.
  6. scope: Optional scope for op_scope.
  7. Returns:
  8. one hot encoding of the labels.
  9. """
  10. with tf.op_scope(name):
  11. batch_size = labels.get_shape()[0]
  12. indices = tf.expand_dims(tf.range(0, batch_size), 1)
  13. labels = tf.cast(tf.expand_dims(labels, 1), indices.dtype)
  14. concated = tf.concat(1, [indices, labels])
  15. onehot_labels = tf.sparse_to_dense(
  16. concated, tf.pack([batch_size, num_classes]), 1.0, 0.0)
  17. onehot_labels.set_shape([batch_size, num_classes])
  18. return onehot_labels
项目:opt-mmd    作者:dougalsutherland    | 项目源码 | 文件源码
  1. def adam_updates(params, t+1))
  2. return updates
项目:opt-mmd    作者:dougalsutherland    | 项目源码 | 文件源码
  1. def get_output_for(self, ''b''):
  2. activation += self.b.dimshuffle(*self.dimshuffle_args)
  3.  
  4. return self.nonlinearity(activation)
项目:weightnorm    作者:openai    | 项目源码 | 文件源码
  1. def adamax_updates(params, p_t))
  2. return updates
项目:weightnorm    作者:openai    | 项目源码 | 文件源码
  1. def adam_updates(params, t+1))
  2. return updates
项目:weightnorm    作者:openai    | 项目源码 | 文件源码
  1. def get_output_for(self,axis=self.axes_to_sum).flatten()
  2. batch_stdv = T.sqrt(1e-6 + batch_var)
  3. norm_features = centered_input / batch_stdv.dimshuffle(*self.dimshuffle_args)
  4.  
  5. # BN updates
  6. new_m = 0.9*self.avg_batch_mean + 0.1*batch_mean
  7. new_v = 0.9*self.avg_batch_var + T.cast((0.1*input.shape[0])/(input.shape[0]-1.), th.config.floatX)*batch_var
  8. self.bn_updates = [(self.avg_batch_mean, ''b''):
  9. activation += self.b.dimshuffle(*self.dimshuffle_args)
  10.  
  11. return self.nonlinearity(activation)
项目:MIX-plus-GAN    作者:yz-ignescent    | 项目源码 | 文件源码
  1. def adam_updates(params, t+1))
  2. return updates
项目:MIX-plus-GAN    作者:yz-ignescent    | 项目源码 | 文件源码
  1. def adam_conditional_updates(params, mincost, mom2=0.999): # if cost is less than mincost,don''t do update
  2. updates = []
  3. grads = T.grad(cost, ifelse(cost<mincost,v,v_t)))
  4. updates.append((mg,mg,mg_t)))
  5. updates.append((p,p,p_t)))
  6. updates.append((t,t,t+1)))
  7. return updates
项目:MIX-plus-GAN    作者:yz-ignescent    | 项目源码 | 文件源码
  1. def get_output_for(self, ''b''):
  2. activation += self.b.dimshuffle(*self.dimshuffle_args)
  3. if self.nonlinearity is not None:
  4. return self.nonlinearity(activation)
  5. else:
  6. return activation
项目:CNN-for-Chinese-spam-SMS    作者:idiomer    | 项目源码 | 文件源码
  1. def shared_dataset(data_xy, borrow=True):
  2. """ Function that loads the dataset into shared variables
  3.  
  4. The reason we store our dataset in shared variables is to allow
  5. Theano to copy it into the GPU memory (when code is run on GPU).
  6. Since copying data into the GPU is slow,copying a minibatch everytime
  7. is needed (the default behavIoUr if the data is not in a shared
  8. variable) would lead to a large decrease in performance.
  9. """
  10. data_x, data_y = data_xy
  11. shared_x = theano.shared(np.asarray(data_x,
  12. dtype=theano.config.floatX),
  13. borrow=borrow)
  14. shared_y = theano.shared(np.asarray(data_y,
  15. borrow=borrow)
  16. return shared_x, ''int32'')
项目:Humour-Detection    作者:srishti-1795    | 项目源码 | 文件源码
  1. def shared_dataset(data_xy, ''int32'')
项目:world_merlin    作者:pbaljeka    | 项目源码 | 文件源码
  1. def parameter_prediction(self, on_unused_input=''ignore'')
  2.  
  3. predict_parameter = test_out()
  4.  
  5. return predict_parameter
项目:world_merlin    作者:pbaljeka    | 项目源码 | 文件源码
  1. def parameter_prediction_S2S(self, on_unused_input=''ignore'')
  2.  
  3. predict_parameter = test_out()
  4.  
  5. return predict_parameter
项目:world_merlin    作者:pbaljeka    | 项目源码 | 文件源码
  1. def parameter_prediction(self, on_unused_input=''ignore'')
  2.  
  3. predict_parameter = test_out()
  4.  
  5. return predict_parameter
项目:DL-Benchmarks    作者:DL-Benchmarks    | 项目源码 | 文件源码
  1. def __init__(self, prob_drop=0.5):
  2.  
  3. self.prob_drop = prob_drop
  4. self.prob_keep = 1.0 - prob_drop
  5. self.flag_on = theano.shared(np.cast[theano.config.floatX](1.0))
  6. self.flag_off = 1.0 - self.flag_on # 1 during test
  7.  
  8. seed_this = DropoutLayer.seed_common.randint(0, theano.config.floatX) * input + \\
  9. self.flag_off * self.prob_keep * input
  10.  
  11. DropoutLayer.layers.append(self)
  12.  
  13. print ''dropout layer with P_drop: '' + str(self.prob_drop)
项目:mimicry.ai    作者:fizerkhan    | 项目源码 | 文件源码
  1. def parameter_prediction(self, on_unused_input=''ignore'')
  2.  
  3. predict_parameter = test_out()
  4.  
  5. return predict_parameter
项目:mimicry.ai    作者:fizerkhan    | 项目源码 | 文件源码
  1. def parameter_prediction_S2S(self, on_unused_input=''ignore'')
  2.  
  3. predict_parameter = test_out()
  4.  
  5. return predict_parameter
项目:mimicry.ai    作者:fizerkhan    | 项目源码 | 文件源码
  1. def parameter_prediction(self, on_unused_input=''ignore'')
  2.  
  3. predict_parameter = test_out()
  4.  
  5. return predict_parameter
项目:odin    作者:imito    | 项目源码 | 文件源码
  1. def categorical_accuracy(y_pred, y_true, top_k=1, reduction=tf.reduce_mean,
  2. name="CategoricalAccuracy"):
  3. """ Non-differentiable """
  4. with tf.variable_scope(name):
  5. if y_true.get_shape().ndims == y_pred.get_shape().ndims:
  6. y_true = tf.argmax(y_true, axis=-1)
  7. elif y_true.get_shape().ndims != y_pred.get_shape().ndims - 1:
  8. raise TypeError(''rank mismatch between y_true and y_pred'')
  9. if top_k == 1:
  10. # standard categorical accuracy
  11. top = tf.argmax(y_pred, axis=-1)
  12. y_true = tf.cast(y_true, top.dtype.base_dtype)
  13. match_values = tf.equal(top, y_true)
  14. else:
  15. match_values = tf.nn.in_top_k(y_pred, tf.cast(y_true, ''int32''),
  16. k=top_k)
  17. match_values = tf.cast(match_values, dtype=''float32'')
  18. return reduction(match_values)
项目:odin    作者:imito    | 项目源码 | 文件源码
  1. def to_llr(x, name="LogLikelihoodratio"):
  2. '''''' Convert a matrix of probabilities into log-likelihood ratio
  3. :math:`LLR = log(\\\\frac{prob(data|target)}{prob(data|non-target)})`
  4. ''''''
  5. if not is_tensor(x):
  6. x /= np.sum(x, axis=-1, keepdims=True)
  7. x = np.clip(x, 10e-8, 1. - 10e-8)
  8. return np.log(x / (np.cast(1., x.dtype) - x))
  9. else:
  10. with tf.variable_scope(name):
  11. x /= tf.reduce_sum(x, keepdims=True)
  12. x = tf.clip_by_value(x, 1. - 10e-8)
  13. return tf.log(x / (tf.cast(1., x.dtype.base_dtype) - x))
  14.  
  15.  
  16. # ===========================================================================
  17. # Speech task metrics
  18. # ===========================================================================
项目:odin    作者:imito    | 项目源码 | 文件源码
  1. def glorot_uniform(shape, n2 = shape[:2]
  2. receptive_field_size = np.prod(shape[2:])
  3.  
  4. std = gain * np.sqrt(2.0 / ((n1 + n2) * receptive_field_size))
  5. a = 0.0 - np.sqrt(3) * std
  6. b = 0.0 + np.sqrt(3) * std
  7. return np.cast[floatX](
  8. get_rng().uniform(low=a, high=b, size=orig_shape))
项目:odin    作者:imito    | 项目源码 | 文件源码
  1. def he_normal(shape, c01b=False):
  2. if gain == ''relu'':
  3. gain = np.sqrt(2)
  4.  
  5. if c01b:
  6. if len(shape) != 4:
  7. raise RuntimeError(
  8. "If c01b is True,only shapes of length 4 are accepted")
  9. fan_in = np.prod(shape[:3])
  10. else:
  11. if len(shape) <= 2:
  12. fan_in = shape[0]
  13. elif len(shape) > 2:
  14. fan_in = np.prod(shape[1:])
  15.  
  16. std = gain * np.sqrt(1.0 / fan_in)
  17. return np.cast[floatX](
  18. get_rng().normal(0.0, size=shape))
项目:odin    作者:imito    | 项目源码 | 文件源码
  1. def orthogonal(shape, gain=1.0):
  2. if gain == ''relu'':
  3. gain = np.sqrt(2)
  4.  
  5. if len(shape) < 2:
  6. raise RuntimeError("Only shapes of length 2 or more are supported,but "
  7. "given shape:%s" % str(shape))
  8.  
  9. flat_shape = (shape[0], np.prod(shape[1:]))
  10. a = get_rng().normal(0.0, flat_shape)
  11. u, _, v = np.linalg.svd(a, full_matrices=False)
  12. # pick the one with the correct shape
  13. q = u if u.shape == flat_shape else v
  14. q = q.reshape(shape)
  15. return np.cast[floatX](gain * q)
  16.  
  17.  
  18. # ===========================================================================
  19. # Fast initialization
  20. # ===========================================================================
项目:DeepMonster    作者:olimastro    | 项目源码 | 文件源码
  1. def adam_updates(params, t+1))
  2. return updates
项目:DeepMonster    作者:olimastro    | 项目源码 | 文件源码
  1. def get_output_for(self, set_bn_updates=True,axis=self.axes_to_sum).flatten()
  2. batch_stdv = T.sqrt(1e-6 + batch_var)
  3. norm_features = centered_input / batch_stdv.dimshuffle(*self.dimshuffle_args)
  4.  
  5. # BN updates
  6. if set_bn_updates:
  7. new_m = 0.9*self.avg_batch_mean + 0.1*batch_mean
  8. new_v = 0.9*self.avg_batch_var + T.cast((0.1*input.shape[0])/(input.shape[0]-1),th.config.floatX)*batch_var
  9. self.bn_updates = [(self.avg_batch_mean, ''b''):
  10. activation += self.b.dimshuffle(*self.dimshuffle_args)
  11.  
  12. return self.nonlinearity(activation)
项目:SE16-Task6-Stance-Detection    作者:nestle1993    | 项目源码 | 文件源码
  1. def shared_dataset(data_xy, ''int32'')
项目:SE16-Task6-Stance-Detection    作者:nestle1993    | 项目源码 | 文件源码
  1. def shared_dataset(data_xy, ''int32'')
项目:Attentive_reader    作者:caglar    | 项目源码 | 文件源码
  1. def __init__(self,
  2. init_momentum,
  3. averaging_coeff=0.95,
  4. stabilizer=1e-2,
  5. use_first_order=False,
  6. bound_inc=False,
  7. momentum_clipping=None):
  8. init_momentum = float(init_momentum)
  9. assert init_momentum >= 0.
  10. assert init_momentum <= 1.
  11. averaging_coeff = float(averaging_coeff)
  12. assert averaging_coeff >= 0.
  13. assert averaging_coeff <= 1.
  14. stabilizer = float(stabilizer)
  15. assert stabilizer >= 0.
  16.  
  17. self.__dict__.update(locals())
  18. del self.self
  19. self.momentum = sharedX(self.init_momentum)
  20.  
  21. self.momentum_clipping = momentum_clipping
  22. if momentum_clipping is not None:
  23. self.momentum_clipping = np.cast[config.floatX](momentum_clipping)
项目:Attentive_reader    作者:caglar    | 项目源码 | 文件源码
  1. def __init__(self,
  2. init_momentum=0.9,
  3. averaging_coeff=0.99,
  4. stabilizer=1e-4,
  5. update_param_norm_ratio=0.003,
  6. gradient_clipping=None):
  7. init_momentum = float(init_momentum)
  8. assert init_momentum >= 0.
  9. assert init_momentum <= 1.
  10. averaging_coeff = float(averaging_coeff)
  11. assert averaging_coeff >= 0.
  12. assert averaging_coeff <= 1.
  13. stabilizer = float(stabilizer)
  14. assert stabilizer >= 0.
  15.  
  16. self.__dict__.update(locals())
  17. del self.self
  18. self.momentum = sharedX(self.init_momentum)
  19. self.update_param_norm_ratio = update_param_norm_ratio
  20.  
  21. self.gradient_clipping = gradient_clipping
  22. if gradient_clipping is not None:
  23. self.gradient_clipping = np.cast[config.floatX](gradient_clipping)
项目:Attentive_reader    作者:caglar    | 项目源码 | 文件源码
  1. def as_floatX(variable):
  2. """
  3. This code is taken from pylearn2:
  4. Casts a given variable into dtype config.floatX
  5. numpy ndarrays will remain numpy ndarrays
  6. python floats will become 0-D ndarrays
  7. all other types will be treated as theano tensors
  8. """
  9.  
  10. if isinstance(variable, theano.config.floatX)

Electron / Mongoose / MongoDB Cast 错误:“错误:有效负载验证失败:video_buffer:对于值“Uint8Array..”,Cast to Buffer 失败

Electron / Mongoose / MongoDB Cast 错误:“错误:有效负载验证失败:video_buffer:对于值“Uint8Array..”,Cast to Buffer 失败

如何解决Electron / Mongoose / MongoDB Cast 错误:“错误:有效负载验证失败:video_buffer:对于值“Uint8Array..”,Cast to Buffer 失败

请帮忙!!!

我正在尝试使用 Mongoose 将视频剪辑的一个小 (

这是我的架构:

const newPayloadSchema = new Schema({

  video_buffer: Buffer,use_case: String,time_stamp: Number,})


module.exports = model(''Payload'',newPayloadSchema);

我创建要保存的对象是:

const payload =   {
                     video_buffer: buffer,use_case: "vid_clips",time_stamp: Date.Now()
                   }

console.log of payload.video_buffer 产生:-

{
[electron]   video_buffer: Uint8Array(1946814) [
[electron]      26,69,223,163,159,66,134,129,1,247,[electron]       1,242,4,243,8,130,132,... 1946714 more items
[electron]   ]}

正在保存...

const newPayload = new Payload(payload);
const PayloadSaved = await newPayload.save();

我收到此错误:

video_buffer: CastError: Cast to Buffer Failed for value "Uint8Array(1946814) [
[electron]        26,[electron]         1,[electron]       119,101,98,109,135,133,2,[electron]        24,83,128,103,255,[electron]        21,73,169,102,153,42,215,177,131,15,64,[electron]        77,67,104,114,111,87,65,[electron]        67,22,84,174,107,171,[electron]       169,115,197,203,9,28,[electron]       246,[electron]       ... 1946714 more items
[electron]     ]" at path "video_buffer"

我已经检查了 Schema 类型以及 Mongoose 文档所建议的方式。

我做错了什么???就是看不懂。

任何帮助将不胜感激!

herbetr 遇到 Cannot cast java.lang.Character to java.lang.Stringat java.lang.Class.cast

herbetr 遇到 Cannot cast java.lang.Character to java.lang.Stringat java.lang.Class.cast

sql.append("order by a.T_DATA_DATE desc,a.QUES_SUM desc");
        Query qu= HibernateUtil.currentSession().createSQLQuery(sql.toString())
                .addScalar("ruleCode", Hibernate.STRING)
                .addScalar("ruleId", Hibernate.STRING)
                .addScalar("schdType", Hibernate.STRING)
                .addScalar("chkDate", Hibernate.DATE)
                .addScalar("queType", Hibernate.STRING)
                .addScalar("chkResult", Hibernate.STRING)
                .addScalar("ruleName", Hibernate.STRING)
                .addScalar("selSum", Hibernate.INTEGER)
                .addScalar("quesSum", Hibernate.INTEGER)
                .addScalar("quesState", Hibernate.STRING)
                .addScalar("gBatch", Hibernate.STRING)
                .addScalar("gId", Hibernate.STRING)
                .addScalar("dataDate", Hibernate.STRING)
                .addScalar("quesId", Hibernate.STRING)
                .addScalar("bigClass", Hibernate.STRING)
                .addScalar("smallClass", Hibernate.STRING)
                .setCacheable(false);

java.util.LinkedHashMap cannot be cast to xxx 和 net.sf.ezmorph.bean.MorphDynaBean cannot be cast ...

java.util.LinkedHashMap cannot be cast to xxx 和 net.sf.ezmorph.bean.MorphDynaBean cannot be cast ...

java.util.LinkedHashMap cannot be cast to com.entity.Person

  使用mybatis, resultMap映射的是实体类Person, 查询出来的结果是一个ArrayList<Person>,然后结果存放在一个ListObject的data属性中,

 存放结果的类

public class ListObject {

    private Object data;

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

}

强制转换成List<Person> result = (List<Person>)result.getData();没有报错, 也拿到了数据,当使用for循环的时候报错  java.util.LinkedHashMap cannot be cast to com.entity.Person

ListObject result = method.query(name);
List<Person> result = (List<Person>)result.getData();
for(Person per : result){ sourceList.add(per .getId()); }

 解决方法:

  导入  net.sf.json 类,使用JSONObject中的方法, 先将数据转成json字符串, 在转成实体对象

ListObject result = method.query(name);
List<Person> result = (List<Person>)result.getData();
for(Object obj : result){ 
  
JSONObject jsonObject=JSONObject.fromObject(objectStr);
   Person per = (Person)JSONObject.toBean(jsonObject, Person.class);
  sourceList.add(per.getId());
}

主要就是两步

JSONObject jsonObject=JSONObject.fromObject(objectStr); // 将数据转成json字符串
Person per = (Person)JSONObject.toBean(jsonObject, Person.class); //将json转成需要的对象

  net.sf.ezmorph.bean.MorphDynaBean cannot be cast to xxx

当需要转换的json中包含有集合的时候, 需要先建一个map,将需要转换的对象中的集合中的对象放进map, 然后使用JSONObject.toBean(jsonObject,Person.class,maps);进行转换.

具体操作:

teacher类中有一个List<Student>  stu, 当需要转化teacher时, 就需要多写一个map对象

import java.util.List;
 
/**
 * @author xukai
 *
 */
public class Teacher {
 
    private String teaId;
 
    private String teaName;
 
    private List<Student> stu;
 
    public Teacher() {
    }
//getter setter
 
}
JSONObject jsonObectj = JSONObject.fromObject(teacher);
Map
<String, Class> map = new HashMap<String,Class>(); map.put("stu", Student.class); // key为teacher私有变量的属性名 如果有多个集合需要转换, 写多个map.put()即可
Teacher teacherBean = (Teacher) JSONObject.toBean(jsonObectj, Teacher.class, map);

主要就是在原先的方法基础上, 加一个map, 用来存集合转换的类型

java中的类型安全问题-Type safety: Unchecked cast from Object to ... 或者 Type safety: Unchecked cast from T...

java中的类型安全问题-Type safety: Unchecked cast from Object to ... 或者 Type safety: Unchecked cast from T...

首先,java语言室类型安全的,通常我们遇到这个问题是出现在 Object转化为目标类型 或者 Type转化为目标类型 时,

这个转化并不是安全的。这个问题普遍认为:因为使用了jdk1.5或者1.6的泛型,

request.getAttribute("***"); 得到的是一个默认为 Object的类型,当把他们转成 List<***> 时,或者

编译器认为有可能会出错,所以提示这个类型安全。

但是具体如何解除这个警告呢,以下是大家普遍用的取消警告的方法(注意:危险并没有真正解除)

  一:方法上添加 @SuppressWarnings("unchecked")

  二:Eclipse的 Window --> Preferences --> Java- --> Compiler --> Errors/Warning --> Generic types Unchecked generic type operation 设置为 Ignore

  三:Eclipse的 Window --> Preferences  --> Java --> Compiler Compiler compliance level 设置为小于1.5

关于Python numpy 模块-cast() 实例源码python casting的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于Electron / Mongoose / MongoDB Cast 错误:“错误:有效负载验证失败:video_buffer:对于值“Uint8Array..”,Cast to Buffer 失败、herbetr 遇到 Cannot cast java.lang.Character to java.lang.Stringat java.lang.Class.cast、java.util.LinkedHashMap cannot be cast to xxx 和 net.sf.ezmorph.bean.MorphDynaBean cannot be cast ...、java中的类型安全问题-Type safety: Unchecked cast from Object to ... 或者 Type safety: Unchecked cast from T...的相关知识,请在本站寻找。

本文标签: