Variable
See the Variables Guide.
Inherits From: Variable
A variable maintains state in the graph across calls to run()
. You add a
variable to the graph by constructing an instance of the class Variable
.
The Variable()
constructor requires an initial value for the variable,
which can be a Tensor
of any type and shape. The initial value defines the
type and shape of the variable. After construction, the type and shape of
the variable are fixed. The value can be changed using one of the assign
methods.
If you want to change the shape of a variable later you have to use an
assign
Op with validate_shape=False
.
Just like any Tensor
, variables created with Variable()
can be used as
inputs for other Ops in the graph. Additionally, all the operators
overloaded for the Tensor
class are carried over to variables, so you can
also add nodes to the graph by just doing arithmetic on variables.
import tensorflow as tf # Create a variable. w = tf.Variable(<initial-value>, name=<optional-name>) # Use the variable in the graph like any Tensor. y = tf.matmul(w, ...another variable or tensor...) # The overloaded operators are available too. z = tf.sigmoid(w + y) # Assign a new value to the variable with `assign()` or a related method. w.assign(w + 1.0) w.assign_add(1.0)
When you launch the graph, variables have to be explicitly initialized before
you can run Ops that use their value. You can initialize a variable by
running its initializer op, restoring the variable from a save file, or
simply running an assign
Op that assigns a value to the variable. In fact,
the variable initializer op is just an assign
Op that assigns the
variable's initial value to the variable itself.
# Launch the graph in a session. with tf.compat.v1.Session() as sess: # Run the variable initializer. sess.run(w.initializer) # ...you now can run ops that use the value of 'w'...
The most common initialization pattern is to use the convenience function
global_variables_initializer()
to add an Op to the graph that initializes
all the variables. You then run that Op after launching the graph.
# Add an Op to initialize global variables. init_op = tf.compat.v1.global_variables_initializer() # Launch the graph in a session. with tf.compat.v1.Session() as sess: # Run the Op that initializes global variables. sess.run(init_op) # ...you can now run any Op that uses variable values...
If you need to create a variable with an initial value dependent on another
variable, use the other variable's initialized_value()
. This ensures that
variables are initialized in the right order.
All variables are automatically collected in the graph where they are
created. By default, the constructor adds the new variable to the graph
collection GraphKeys.GLOBAL_VARIABLES
. The convenience function
global_variables()
returns the contents of that collection.
When building a machine learning model it is often convenient to distinguish
between variables holding the trainable model parameters and other variables
such as a global step
variable used to count training steps. To make this
easier, the variable constructor supports a trainable=<bool>
parameter. If
True
, the new variable is also added to the graph collection
GraphKeys.TRAINABLE_VARIABLES
. The convenience function
trainable_variables()
returns the contents of this collection. The
various Optimizer
classes use this collection as the default list of
variables to optimize.
WARNING: tf.Variable objects by default have a non-intuitive memory model. A
Variable is represented internally as a mutable Tensor which can
non-deterministically alias other Tensors in a graph. The set of operations
which consume a Variable and can lead to aliasing is undetermined and can
change across TensorFlow versions. Avoid writing code which relies on the
value of a Variable either changing or not changing as other operations
happen. For example, using Variable objects or simple functions thereof as
predicates in a tf.cond
is dangerous and error-prone:
v = tf.Variable(True) tf.cond(v, lambda: v.assign(False), my_false_fn) # Note: this is broken.
Here, adding use_resource=True
when constructing the variable will
fix any nondeterminism issues:
v = tf.Variable(True, use_resource=True) tf.cond(v, lambda: v.assign(False), my_false_fn)
To use the replacement for variables which does not have these issues:
use_resource=True
when constructing tf.Variable
;tf.compat.v1.get_variable_scope().set_use_resource(True)
inside a
tf.compat.v1.variable_scope
before the tf.compat.v1.get_variable()
call.__init__
__init__( initial_value=None, trainable=None, collections=None, validate_shape=True, caching_device=None, name=None, variable_def=None, dtype=None, expected_shape=None, import_scope=None, constraint=None, use_resource=None, synchronization=tf.VariableSynchronization.AUTO, aggregation=tf.compat.v1.VariableAggregation.NONE, shape=None )
Creates a new variable with value initial_value
.
The new variable is added to the graph collections listed in collections
,
which defaults to [GraphKeys.GLOBAL_VARIABLES]
.
If trainable
is True
the variable is also added to the graph collection
GraphKeys.TRAINABLE_VARIABLES
.
This constructor creates both a variable
Op and an assign
Op to set the
variable to its initial value.
initial_value
: A Tensor
, or Python object convertible to a Tensor
,
which is the initial value for the Variable. The initial value must have
a shape specified unless validate_shape
is set to False. Can also be a
callable with no argument that returns the initial value when called. In
that case, dtype
must be specified. (Note that initializer functions
from init_ops.py must first be bound to a shape before being used here.)trainable
: If True
, also adds the variable to the graph collection
GraphKeys.TRAINABLE_VARIABLES
. This collection is used as the default
list of variables to use by the Optimizer
classes. Defaults to True
,
unless synchronization
is set to ON_READ
, in which case it defaults
to False
.collections
: List of graph collections keys. The new variable is added to
these collections. Defaults to [GraphKeys.GLOBAL_VARIABLES]
.validate_shape
: If False
, allows the variable to be initialized with a
value of unknown shape. If True
, the default, the shape of
initial_value
must be known.caching_device
: Optional device string describing where the Variable
should be cached for reading. Defaults to the Variable's device. If not
None
, caches on another device. Typical use is to cache on the device
where the Ops using the Variable reside, to deduplicate copying through
Switch
and other conditional statements.name
: Optional name for the variable. Defaults to 'Variable'
and gets
uniquified automatically.variable_def
: VariableDef
protocol buffer. If not None
, recreates the
Variable object with its contents, referencing the variable's nodes in
the graph, which must already exist. The graph is not changed.
variable_def
and the other arguments are mutually exclusive.dtype
: If set, initial_value will be converted to the given type. If
None
, either the datatype will be kept (if initial_value
is a
Tensor), or convert_to_tensor
will decide.expected_shape
: A TensorShape. If set, initial_value is expected to have
this shape.import_scope
: Optional string
. Name scope to add to the Variable.
Only
used when initializing from protocol buffer.constraint
: An optional projection function to be applied to the variable
after being updated by an Optimizer
(e.g. used to implement norm
constraints or value constraints for layer weights). The function must
take as input the unprojected Tensor representing the value of the
variable and return the Tensor for the projected value (which must have
the same shape). Constraints are not safe to use when doing asynchronous
distributed training.use_resource
: whether to use resource variables.synchronization
: Indicates when a distributed a variable will be
aggregated. Accepted values are constants defined in the class
tf.VariableSynchronization
. By default the synchronization is set to
AUTO
and the current DistributionStrategy
chooses when to
synchronize.aggregation
: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class
tf.VariableAggregation
.shape
: (optional) The shape of this variable. If None, the shape of
initial_value
will be used. When setting this argument to
tf.TensorShape(None)
(representing an unspecified shape), the variable
can be assigned with values of different shapes.ValueError
: If both variable_def
and initial_value are specified.ValueError
: If the initial value is not specified, or does not have a
shape and validate_shape
is True
.RuntimeError
: If eager execution is enabled.aggregation
constraint
Returns the constraint function associated with this variable.
The constraint function that was passed to the variable constructor.
Can be None
if no constraint was passed.
device
The device of this variable.
dtype
The DType
of this variable.
graph
The Graph
of this variable.
initial_value
Returns the Tensor used as the initial value for the variable.
Note that this is different from initialized_value()
which runs
the op that initializes the variable before returning its value.
This method returns the tensor that is used by the op that initializes
the variable.
A Tensor
.
initializer
The initializer operation for this variable.
name
The name of this variable.
op
The Operation
of this variable.
shape
The TensorShape
of this variable.
A TensorShape
.
synchronization
trainable
__abs__
__abs__( x, name=None )
Computes the absolute value of a tensor.
Given a tensor of integer or floating-point values, this operation returns a tensor of the same type, where each element contains the absolute value of the corresponding element in the input.
Given a tensor x
of complex numbers, this operation returns a tensor of type
float32
or float64
that is the absolute value of each element in x
. All
elements in x
must be complex numbers of the form \(a + bj\). The
absolute value is computed as \( \sqrt{a^2 + b^2}\). For example:
x = tf.constant([[-2.25 + 4.75j], [-3.25 + 5.75j]]) tf.abs(x) # [5.25594902, 6.60492229]
x
: A Tensor
or SparseTensor
of type float16
, float32
, float64
,
int32
, int64
, complex64
or complex128
.name
: A name for the operation (optional).A Tensor
or SparseTensor
the same size, type, and sparsity as x
with
absolute values.
Note, for complex64
or complex128
input, the returned Tensor
will be
of type float32
or float64
, respectively.
__add__
__add__( a, *args, **kwargs )
Dispatches to add for strings and add_v2 for all other types.
__and__
__and__( a, *args, **kwargs )
Returns the truth value of x AND y element-wise.
NOTE: math.logical_and
supports broadcasting. More about broadcasting
here
x
: A Tensor
of type bool
.y
: A Tensor
of type bool
.name
: A name for the operation (optional).A Tensor
of type bool
.
__div__
__div__( a, *args, **kwargs )
Divide two values using Python 2 semantics.
Used for Tensor.div.
x
: Tensor
numerator of real numeric type.y
: Tensor
denominator of real numeric type.name
: A name for the operation (optional).x / y
returns the quotient of x and y.
__eq__
__eq__(other)
Compares two variables element-wise for equality.
__floordiv__
__floordiv__( a, *args, **kwargs )
Divides x / y
elementwise, rounding toward the most negative integer.
The same as tf.compat.v1.div(x,y)
for integers, but uses
tf.floor(tf.compat.v1.div(x,y))
for
floating point arguments so that the result is always an integer (though
possibly an integer represented as floating point). This op is generated by
x // y
floor division in Python 3 and in Python 2.7 with
from __future__ import division
.
x
and y
must have the same type, and the result will have the same type
as well.
x
: Tensor
numerator of real numeric type.y
: Tensor
denominator of real numeric type.name
: A name for the operation (optional).x / y
rounded down.
TypeError
: If the inputs are complex.__ge__
__ge__( a, *args, **kwargs )
Returns the truth value of (x >= y) element-wise.
NOTE: math.greater_equal
supports broadcasting. More about broadcasting
here
x
: A Tensor
. Must be one of the following types: float32
, float64
, int32
, uint8
, int16
, int8
, int64
, bfloat16
, uint16
, half
, uint32
, uint64
.y
: A Tensor
. Must have the same type as x
.name
: A name for the operation (optional).A Tensor
of type bool
.
__getitem__
__getitem__( var, slice_spec )
Creates a slice helper object given a variable.
This allows creating a sub-tensor from part of the current contents
of a variable. See tf.Tensor.getitem
for detailed examples
of slicing.
This function in addition also allows assignment to a sliced range.
This is similar to __setitem__
functionality in Python. However,
the syntax is different so that the user can capture the assignment
operation for grouping or passing to sess.run()
.
For example,
import tensorflow as tf A = tf.Variable([[1,2,3], [4,5,6], [7,8,9]], dtype=tf.float32) with tf.compat.v1.Session() as sess: sess.run(tf.compat.v1.global_variables_initializer()) print(sess.run(A[:2, :2])) # => [[1,2], [4,5]] op = A[:2,:2].assign(22. * tf.ones((2, 2))) print(sess.run(op)) # => [[22, 22, 3], [22, 22, 6], [7,8,9]]
Note that assignments currently do not support NumPy broadcasting semantics.
var
: An ops.Variable
object.slice_spec
: The arguments to Tensor.__getitem__
.The appropriate slice of "tensor", based on "slice_spec".
As an operator. The operator also has a assign()
method
that can be used to generate an assignment operator.
ValueError
: If a slice range is negative size.TypeError
: TypeError: If the slice indices aren't int, slice,
ellipsis, tf.newaxis or int32/int64 tensors.__gt__
__gt__( a, *args, **kwargs )
Returns the truth value of (x > y) element-wise.
NOTE: math.greater
supports broadcasting. More about broadcasting
here
x
: A Tensor
. Must be one of the following types: float32
, float64
, int32
, uint8
, int16
, int8
, int64
, bfloat16
, uint16
, half
, uint32
, uint64
.y
: A Tensor
. Must have the same type as x
.name
: A name for the operation (optional).A Tensor
of type bool
.
__invert__
__invert__( a, *args, **kwargs )
Returns the truth value of NOT x element-wise.
x
: A Tensor
of type bool
.name
: A name for the operation (optional).A Tensor
of type bool
.
__iter__
__iter__()
Dummy method to prevent iteration.
Do not call.
NOTE(mrry): If we register getitem as an overloaded operator, Python will valiantly attempt to iterate over the variable's Tensor from 0 to infinity. Declaring this method prevents this unintended behavior.
TypeError
: when invoked.__le__
__le__( a, *args, **kwargs )
Returns the truth value of (x <= y) element-wise.
NOTE: math.less_equal
supports broadcasting. More about broadcasting
here
x
: A Tensor
. Must be one of the following types: float32
, float64
, int32
, uint8
, int16
, int8
, int64
, bfloat16
, uint16
, half
, uint32
, uint64
.y
: A Tensor
. Must have the same type as x
.name
: A name for the operation (optional).A Tensor
of type bool
.
__lt__
__lt__( a, *args, **kwargs )
Returns the truth value of (x < y) element-wise.
NOTE: math.less
supports broadcasting. More about broadcasting
here
x
: A Tensor
. Must be one of the following types: float32
, float64
, int32
, uint8
, int16
, int8
, int64
, bfloat16
, uint16
, half
, uint32
, uint64
.y
: A Tensor
. Must have the same type as x
.name
: A name for the operation (optional).A Tensor
of type bool
.
__matmul__
__matmul__( a, *args, **kwargs )
Multiplies matrix a
by matrix b
, producing a
* b
.
The inputs must, following any transpositions, be tensors of rank >= 2 where the inner 2 dimensions specify valid matrix multiplication arguments, and any further outer dimensions match.
Both matrices must be of the same type. The supported types are:
float16
, float32
, float64
, int32
, complex64
, complex128
.
Either matrix can be transposed or adjointed (conjugated and transposed) on
the fly by setting one of the corresponding flag to True
. These are False
by default.
If one or both of the matrices contain a lot of zeros, a more efficient
multiplication algorithm can be used by setting the corresponding
a_is_sparse
or b_is_sparse
flag to True
. These are False
by default.
This optimization is only available for plain matrices (rank-2 tensors) with
datatypes bfloat16
or float32
.
# 2-D tensor `a` # [[1, 2, 3], # [4, 5, 6]] a = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3]) # 2-D tensor `b` # [[ 7, 8], # [ 9, 10], # [11, 12]] b = tf.constant([7, 8, 9, 10, 11, 12], shape=[3, 2]) # `a` * `b` # [[ 58, 64], # [139, 154]] c = tf.matmul(a, b) # 3-D tensor `a` # [[[ 1, 2, 3], # [ 4, 5, 6]], # [[ 7, 8, 9], # [10, 11, 12]]] a = tf.constant(np.arange(1, 13, dtype=np.int32), shape=[2, 2, 3]) # 3-D tensor `b` # [[[13, 14], # [15, 16], # [17, 18]], # [[19, 20], # [21, 22], # [23, 24]]] b = tf.constant(np.arange(13, 25, dtype=np.int32), shape=[2, 3, 2]) # `a` * `b` # [[[ 94, 100], # [229, 244]], # [[508, 532], # [697, 730]]] c = tf.matmul(a, b) # Since python >= 3.5 the @ operator is supported (see PEP 465). # In TensorFlow, it simply calls the `tf.matmul()` function, so the # following lines are equivalent: d = a @ b @ [[10.], [11.]] d = tf.matmul(tf.matmul(a, b), [[10.], [11.]])
a
: Tensor
of type float16
, float32
, float64
, int32
, complex64
,
complex128
and rank > 1.b
: Tensor
with same type and rank as a
.transpose_a
: If True
, a
is transposed before multiplication.transpose_b
: If True
, b
is transposed before multiplication.adjoint_a
: If True
, a
is conjugated and transposed before
multiplication.adjoint_b
: If True
, b
is conjugated and transposed before
multiplication.a_is_sparse
: If True
, a
is treated as a sparse matrix.b_is_sparse
: If True
, b
is treated as a sparse matrix.name
: Name for the operation (optional).A Tensor
of the same type as a
and b
where each inner-most matrix is
the product of the corresponding matrices in a
and b
, e.g. if all
transpose or adjoint attributes are False
:
output
[..., i, j] = sum_k (a
[..., i, k] * b
[..., k, j]),
for all indices i, j.
Note
: This is matrix product, not element-wise product.ValueError
: If transpose_a and adjoint_a, or transpose_b and adjoint_b
are both set to True.__mod__
__mod__( a, *args, **kwargs )
Returns element-wise remainder of division. When x < 0
xor y < 0
is
true, this follows Python semantics in that the result here is consistent
with a flooring divide. E.g. floor(x / y) * y + mod(x, y) = x
.
NOTE: math.floormod
supports broadcasting. More about broadcasting
here
x
: A Tensor
. Must be one of the following types: int32
, int64
, bfloat16
, half
, float32
, float64
.y
: A Tensor
. Must have the same type as x
.name
: A name for the operation (optional).A Tensor
. Has the same type as x
.
__mul__
__mul__( a, *args, **kwargs )
Dispatches cwise mul for "DenseDense" and "DenseSparse".
__ne__
__ne__(other)
Compares two variables element-wise for equality.
__neg__
__neg__( a, *args, **kwargs )
Computes numerical negative value element-wise.
I.e., \(y = -x\).
x
: A Tensor
. Must be one of the following types: bfloat16
, half
, float32
, float64
, int32
, int64
, complex64
, complex128
.name
: A name for the operation (optional).A Tensor
. Has the same type as x
.
__or__
__or__( a, *args, **kwargs )
Returns the truth value of x OR y element-wise.
NOTE: math.logical_or
supports broadcasting. More about broadcasting
here
x
: A Tensor
of type bool
.y
: A Tensor
of type bool
.name
: A name for the operation (optional).A Tensor
of type bool
.
__pow__
__pow__( a, *args, **kwargs )
Computes the power of one value to another.
Given a tensor x
and a tensor y
, this operation computes \(x^y\) for
corresponding elements in x
and y
. For example:
x = tf.constant([[2, 2], [3, 3]]) y = tf.constant([[8, 16], [2, 3]]) tf.pow(x, y) # [[256, 65536], [9, 27]]
x
: A Tensor
of type float16
, float32
, float64
, int32
, int64
,
complex64
, or complex128
.y
: A Tensor
of type float16
, float32
, float64
, int32
, int64
,
complex64
, or complex128
.name
: A name for the operation (optional).A Tensor
.
__radd__
__radd__( a, *args, **kwargs )
Dispatches to add for strings and add_v2 for all other types.
__rand__
__rand__( a, *args, **kwargs )
Returns the truth value of x AND y element-wise.
NOTE: math.logical_and
supports broadcasting. More about broadcasting
here
x
: A Tensor
of type bool
.y
: A Tensor
of type bool
.name
: A name for the operation (optional).A Tensor
of type bool
.
__rdiv__
__rdiv__( a, *args, **kwargs )
Divide two values using Python 2 semantics.
Used for Tensor.div.
x
: Tensor
numerator of real numeric type.y
: Tensor
denominator of real numeric type.name
: A name for the operation (optional).x / y
returns the quotient of x and y.
__rfloordiv__
__rfloordiv__( a, *args, **kwargs )
Divides x / y
elementwise, rounding toward the most negative integer.
The same as tf.compat.v1.div(x,y)
for integers, but uses
tf.floor(tf.compat.v1.div(x,y))
for
floating point arguments so that the result is always an integer (though
possibly an integer represented as floating point). This op is generated by
x // y
floor division in Python 3 and in Python 2.7 with
from __future__ import division
.
x
and y
must have the same type, and the result will have the same type
as well.
x
: Tensor
numerator of real numeric type.y
: Tensor
denominator of real numeric type.name
: A name for the operation (optional).x / y
rounded down.
TypeError
: If the inputs are complex.__rmatmul__
__rmatmul__( a, *args, **kwargs )
Multiplies matrix a
by matrix b
, producing a
* b
.
The inputs must, following any transpositions, be tensors of rank >= 2 where the inner 2 dimensions specify valid matrix multiplication arguments, and any further outer dimensions match.
Both matrices must be of the same type. The supported types are:
float16
, float32
, float64
, int32
, complex64
, complex128
.
Either matrix can be transposed or adjointed (conjugated and transposed) on
the fly by setting one of the corresponding flag to True
. These are False
by default.
If one or both of the matrices contain a lot of zeros, a more efficient
multiplication algorithm can be used by setting the corresponding
a_is_sparse
or b_is_sparse
flag to True
. These are False
by default.
This optimization is only available for plain matrices (rank-2 tensors) with
datatypes bfloat16
or float32
.
# 2-D tensor `a` # [[1, 2, 3], # [4, 5, 6]] a = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3]) # 2-D tensor `b` # [[ 7, 8], # [ 9, 10], # [11, 12]] b = tf.constant([7, 8, 9, 10, 11, 12], shape=[3, 2]) # `a` * `b` # [[ 58, 64], # [139, 154]] c = tf.matmul(a, b) # 3-D tensor `a` # [[[ 1, 2, 3], # [ 4, 5, 6]], # [[ 7, 8, 9], # [10, 11, 12]]] a = tf.constant(np.arange(1, 13, dtype=np.int32), shape=[2, 2, 3]) # 3-D tensor `b` # [[[13, 14], # [15, 16], # [17, 18]], # [[19, 20], # [21, 22], # [23, 24]]] b = tf.constant(np.arange(13, 25, dtype=np.int32), shape=[2, 3, 2]) # `a` * `b` # [[[ 94, 100], # [229, 244]], # [[508, 532], # [697, 730]]] c = tf.matmul(a, b) # Since python >= 3.5 the @ operator is supported (see PEP 465). # In TensorFlow, it simply calls the `tf.matmul()` function, so the # following lines are equivalent: d = a @ b @ [[10.], [11.]] d = tf.matmul(tf.matmul(a, b), [[10.], [11.]])
a
: Tensor
of type float16
, float32
, float64
, int32
, complex64
,
complex128
and rank > 1.b
: Tensor
with same type and rank as a
.transpose_a
: If True
, a
is transposed before multiplication.transpose_b
: If True
, b
is transposed before multiplication.adjoint_a
: If True
, a
is conjugated and transposed before
multiplication.adjoint_b
: If True
, b
is conjugated and transposed before
multiplication.a_is_sparse
: If True
, a
is treated as a sparse matrix.b_is_sparse
: If True
, b
is treated as a sparse matrix.name
: Name for the operation (optional).A Tensor
of the same type as a
and b
where each inner-most matrix is
the product of the corresponding matrices in a
and b
, e.g. if all
transpose or adjoint attributes are False
:
output
[..., i, j] = sum_k (a
[..., i, k] * b
[..., k, j]),
for all indices i, j.
Note
: This is matrix product, not element-wise product.ValueError
: If transpose_a and adjoint_a, or transpose_b and adjoint_b
are both set to True.__rmod__
__rmod__( a, *args, **kwargs )
Returns element-wise remainder of division. When x < 0
xor y < 0
is
true, this follows Python semantics in that the result here is consistent
with a flooring divide. E.g. floor(x / y) * y + mod(x, y) = x
.
NOTE: math.floormod
supports broadcasting. More about broadcasting
here
x
: A Tensor
. Must be one of the following types: int32
, int64
, bfloat16
, half
, float32
, float64
.y
: A Tensor
. Must have the same type as x
.name
: A name for the operation (optional).A Tensor
. Has the same type as x
.
__rmul__
__rmul__( a, *args, **kwargs )
Dispatches cwise mul for "DenseDense" and "DenseSparse".
__ror__
__ror__( a, *args, **kwargs )
Returns the truth value of x OR y element-wise.
NOTE: math.logical_or
supports broadcasting. More about broadcasting
here
x
: A Tensor
of type bool
.y
: A Tensor
of type bool
.name
: A name for the operation (optional).A Tensor
of type bool
.
__rpow__
__rpow__( a, *args, **kwargs )
Computes the power of one value to another.
Given a tensor x
and a tensor y
, this operation computes \(x^y\) for
corresponding elements in x
and y
. For example:
x = tf.constant([[2, 2], [3, 3]]) y = tf.constant([[8, 16], [2, 3]]) tf.pow(x, y) # [[256, 65536], [9, 27]]
x
: A Tensor
of type float16
, float32
, float64
, int32
, int64
,
complex64
, or complex128
.y
: A Tensor
of type float16
, float32
, float64
, int32
, int64
,
complex64
, or complex128
.name
: A name for the operation (optional).A Tensor
.
__rsub__
__rsub__( a, *args, **kwargs )
Returns x - y element-wise.
NOTE: Subtract
supports broadcasting. More about broadcasting
here
x
: A Tensor
. Must be one of the following types: bfloat16
, half
, float32
, float64
, uint8
, int8
, uint16
, int16
, int32
, int64
, complex64
, complex128
.y
: A Tensor
. Must have the same type as x
.name
: A name for the operation (optional).A Tensor
. Has the same type as x
.
__rtruediv__
__rtruediv__( a, *args, **kwargs )
__rxor__
__rxor__( a, *args, **kwargs )
Logical XOR function.
x ^ y = (x | y) & ~(x & y)
Inputs are tensor and if the tensors contains more than one element, an element-wise logical XOR is computed.
x = tf.constant([False, False, True, True], dtype = tf.bool) y = tf.constant([False, True, False, True], dtype = tf.bool) z = tf.logical_xor(x, y, name="LogicalXor") # here z = [False True True False]
x
: A Tensor
type bool.y
: A Tensor
of type bool.A Tensor
of type bool with the same size as that of x or y.
__sub__
__sub__( a, *args, **kwargs )
Returns x - y element-wise.
NOTE: Subtract
supports broadcasting. More about broadcasting
here
x
: A Tensor
. Must be one of the following types: bfloat16
, half
, float32
, float64
, uint8
, int8
, uint16
, int16
, int32
, int64
, complex64
, complex128
.y
: A Tensor
. Must have the same type as x
.name
: A name for the operation (optional).A Tensor
. Has the same type as x
.
__truediv__
__truediv__( a, *args, **kwargs )
__xor__
__xor__( a, *args, **kwargs )
Logical XOR function.
x ^ y = (x | y) & ~(x & y)
Inputs are tensor and if the tensors contains more than one element, an element-wise logical XOR is computed.
x = tf.constant([False, False, True, True], dtype = tf.bool) y = tf.constant([False, True, False, True], dtype = tf.bool) z = tf.logical_xor(x, y, name="LogicalXor") # here z = [False True True False]
x
: A Tensor
type bool.y
: A Tensor
of type bool.A Tensor
of type bool with the same size as that of x or y.
assign
assign( value, use_locking=False, name=None, read_value=True )
Assigns a new value to the variable.
This is essentially a shortcut for assign(self, value)
.
value
: A Tensor
. The new value for this variable.use_locking
: If True
, use locking during the assignment.name
: The name of the operation to be createdread_value
: if True, will return something which evaluates to the new
value of the variable; if False will return the assign op.A Tensor
that will hold the new value of this variable after
the assignment has completed.
assign_add
assign_add( delta, use_locking=False, name=None, read_value=True )
Adds a value to this variable.
This is essentially a shortcut for assign_add(self, delta)
.
delta
: A Tensor
. The value to add to this variable.use_locking
: If True
, use locking during the operation.name
: The name of the operation to be createdread_value
: if True, will return something which evaluates to the new
value of the variable; if False will return the assign op.A Tensor
that will hold the new value of this variable after
the addition has completed.
assign_sub
assign_sub( delta, use_locking=False, name=None, read_value=True )
Subtracts a value from this variable.
This is essentially a shortcut for assign_sub(self, delta)
.
delta
: A Tensor
. The value to subtract from this variable.use_locking
: If True
, use locking during the operation.name
: The name of the operation to be createdread_value
: if True, will return something which evaluates to the new
value of the variable; if False will return the assign op.A Tensor
that will hold the new value of this variable after
the subtraction has completed.
batch_scatter_update
batch_scatter_update( sparse_delta, use_locking=False, name=None )
Assigns tf.IndexedSlices
to this variable batch-wise.
Analogous to batch_gather
. This assumes that this variable and the
sparse_delta IndexedSlices have a series of leading dimensions that are the
same for all of them, and the updates are performed on the last dimension of
indices. In other words, the dimensions should be the following:
num_prefix_dims = sparse_delta.indices.ndims - 1
batch_dim = num_prefix_dims + 1
sparse_delta.updates.shape = sparse_delta.indices.shape + var.shape[
batch_dim:]
where
sparse_delta.updates.shape[:num_prefix_dims]
== sparse_delta.indices.shape[:num_prefix_dims]
== var.shape[:num_prefix_dims]
And the operation performed can be expressed as:
var[i_1, ..., i_n,
sparse_delta.indices[i_1, ..., i_n, j]] = sparse_delta.updates[
i_1, ..., i_n, j]
When sparse_delta.indices is a 1D tensor, this operation is equivalent to
scatter_update
.
To avoid this operation one can looping over the first ndims
of the
variable and using scatter_update
on the subtensors that result of slicing
the first dimension. This is a valid option for ndims = 1
, but less
efficient than this implementation.
sparse_delta
: tf.IndexedSlices
to be assigned to this variable.use_locking
: If True
, use locking during the operation.name
: the name of the operation.A Tensor
that will hold the new value of this variable after
the scattered assignment has completed.
TypeError
: if sparse_delta
is not an IndexedSlices
.count_up_to
count_up_to(limit)
Increments this variable until it reaches limit
. (deprecated)
Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Prefer Dataset.range instead.
When that Op is run it tries to increment the variable by 1
. If
incrementing the variable would bring it above limit
then the Op raises
the exception OutOfRangeError
.
If no error is raised, the Op outputs the value of the variable before the increment.
This is essentially a shortcut for count_up_to(self, limit)
.
limit
: value at which incrementing the variable raises an error.A Tensor
that will hold the variable value before the increment. If no
other Op modifies this variable, the values produced will all be
distinct.
eval
eval(session=None)
In a session, computes and returns the value of this variable.
This is not a graph construction method, it does not add ops to the graph.
This convenience method requires a session where the graph
containing this variable has been launched. If no session is
passed, the default session is used. See tf.compat.v1.Session
for more
information on launching a graph and on sessions.
v = tf.Variable([1, 2]) init = tf.compat.v1.global_variables_initializer() with tf.compat.v1.Session() as sess: sess.run(init) # Usage passing the session explicitly. print(v.eval(sess)) # Usage with the default session. The 'with' block # above makes 'sess' the default session. print(v.eval())
session
: The session to use to evaluate this variable. If none, the
default session is used.A numpy ndarray
with a copy of the value of this variable.
experimental_ref
experimental_ref()
Returns a hashable reference object to this Variable.
Warning: Experimental API that could be changed or removed.
The primary usecase for this API is to put variables in a set/dictionary.
We can't put variables in a set/dictionary as variable.__hash__()
is no
longer available starting Tensorflow 2.0.
import tensorflow as tf x = tf.Variable(5) y = tf.Variable(10) z = tf.Variable(10) # The followings will raise an exception starting 2.0 # TypeError: Variable is unhashable if Variable equality is enabled. variable_set = {x, y, z} variable_dict = {x: 'five', y: 'ten'}
Instead, we can use variable.experimental_ref()
.
variable_set = {x.experimental_ref(), y.experimental_ref(), z.experimental_ref()} print(x.experimental_ref() in variable_set) ==> True variable_dict = {x.experimental_ref(): 'five', y.experimental_ref(): 'ten', z.experimental_ref(): 'ten'} print(variable_dict[y.experimental_ref()]) ==> ten
Also, the reference object provides .deref()
function that returns the
original Variable.
x = tf.Variable(5) print(x.experimental_ref().deref()) ==> <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=5>
from_proto
from_proto( variable_def, import_scope=None )
Returns a Variable
object created from variable_def
.
gather_nd
gather_nd( indices, name=None )
Gather slices from params
into a Tensor with shape specified by indices
.
See tf.gather_nd for details.
indices
: A Tensor
. Must be one of the following types: int32
, int64
.
Index tensor.name
: A name for the operation (optional).A Tensor
. Has the same type as params
.
get_shape
get_shape()
Alias of Variable.shape
.
initialized_value
initialized_value()
Returns the value of the initialized variable. (deprecated)
Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.
You should use this instead of the variable itself to initialize another variable with a value that depends on the value of this variable.
# Initialize 'v' with a random tensor. v = tf.Variable(tf.random.truncated_normal([10, 40])) # Use `initialized_value` to guarantee that `v` has been # initialized before its value is used to initialize `w`. # The random values are picked only once. w = tf.Variable(v.initialized_value() * 2.0)
A Tensor
holding the value of this variable after its initializer
has run.
load
load( value, session=None )
Load new value into this variable. (deprecated)
Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Prefer Variable.assign which has equivalent behavior in 2.X.
Writes new value to variable's memory. Doesn't add ops to the graph.
This convenience method requires a session where the graph
containing this variable has been launched. If no session is
passed, the default session is used. See tf.compat.v1.Session
for more
information on launching a graph and on sessions.
v = tf.Variable([1, 2]) init = tf.compat.v1.global_variables_initializer() with tf.compat.v1.Session() as sess: sess.run(init) # Usage passing the session explicitly. v.load([2, 3], sess) print(v.eval(sess)) # prints [2 3] # Usage with the default session. The 'with' block # above makes 'sess' the default session. v.load([3, 4], sess) print(v.eval()) # prints [3 4]
value
: New variable valuesession
: The session to use to evaluate this variable. If none, the
default session is used.ValueError
: Session is not passed and no default sessionread_value
read_value()
Returns the value of this variable, read in the current context.
Can be different from value() if it's on another device, with control dependencies, etc.
A Tensor
containing the value of the variable.
scatter_add
scatter_add( sparse_delta, use_locking=False, name=None )
Adds tf.IndexedSlices
to this variable.
sparse_delta
: tf.IndexedSlices
to be added to this variable.use_locking
: If True
, use locking during the operation.name
: the name of the operation.A Tensor
that will hold the new value of this variable after
the scattered addition has completed.
TypeError
: if sparse_delta
is not an IndexedSlices
.scatter_div
scatter_div( sparse_delta, use_locking=False, name=None )
Divide this variable by tf.IndexedSlices
.
sparse_delta
: tf.IndexedSlices
to divide this variable by.use_locking
: If True
, use locking during the operation.name
: the name of the operation.A Tensor
that will hold the new value of this variable after
the scattered division has completed.
TypeError
: if sparse_delta
is not an IndexedSlices
.scatter_max
scatter_max( sparse_delta, use_locking=False, name=None )
Updates this variable with the max of tf.IndexedSlices
and itself.
sparse_delta
: tf.IndexedSlices
to use as an argument of max with this
variable.use_locking
: If True
, use locking during the operation.name
: the name of the operation.A Tensor
that will hold the new value of this variable after
the scattered maximization has completed.
TypeError
: if sparse_delta
is not an IndexedSlices
.scatter_min
scatter_min( sparse_delta, use_locking=False, name=None )
Updates this variable with the min of tf.IndexedSlices
and itself.
sparse_delta
: tf.IndexedSlices
to use as an argument of min with this
variable.use_locking
: If True
, use locking during the operation.name
: the name of the operation.A Tensor
that will hold the new value of this variable after
the scattered minimization has completed.
TypeError
: if sparse_delta
is not an IndexedSlices
.scatter_mul
scatter_mul( sparse_delta, use_locking=False, name=None )
Multiply this variable by tf.IndexedSlices
.
sparse_delta
: tf.IndexedSlices
to multiply this variable by.use_locking
: If True
, use locking during the operation.name
: the name of the operation.A Tensor
that will hold the new value of this variable after
the scattered multiplication has completed.
TypeError
: if sparse_delta
is not an IndexedSlices
.scatter_nd_add
scatter_nd_add( indices, updates, name=None )
Applies sparse addition to individual values or slices in a Variable.
The Variable has rank P
and indices
is a Tensor
of rank Q
.
indices
must be integer tensor, containing indices into self.
It must be shape [d_0, ..., d_{Q-2}, K]
where 0 < K <= P
.
The innermost dimension of indices
(with length K
) corresponds to
indices into elements (if K = P
) or slices (if K < P
) along the K
th
dimension of self.
updates
is Tensor
of rank Q-1+P-K
with shape:
[d_0, ..., d_{Q-2}, self.shape[K], ..., self.shape[P-1]].
For example, say we want to add 4 scattered elements to a rank-1 tensor to 8 elements. In Python, that update would look like this:
v = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8]) indices = tf.constant([[4], [3], [1] ,[7]]) updates = tf.constant([9, 10, 11, 12]) add = v.scatter_nd_add(indices, updates) with tf.compat.v1.Session() as sess: print sess.run(add)
The resulting update to v would look like this:
[1, 13, 3, 14, 14, 6, 7, 20]
See tf.scatter_nd
for more details about how to make updates to
slices.
indices
: The indices to be used in the operation.updates
: The values to be used in the operation.name
: the name of the operation.A Tensor
that will hold the new value of this variable after
the scattered addition has completed.
scatter_nd_sub
scatter_nd_sub( indices, updates, name=None )
Applies sparse subtraction to individual values or slices in a Variable.
Assuming the variable has rank P
and indices
is a Tensor
of rank Q
.
indices
must be integer tensor, containing indices into self.
It must be shape [d_0, ..., d_{Q-2}, K]
where 0 < K <= P
.
The innermost dimension of indices
(with length K
) corresponds to
indices into elements (if K = P
) or slices (if K < P
) along the K
th
dimension of self.
updates
is Tensor
of rank Q-1+P-K
with shape:
[d_0, ..., d_{Q-2}, self.shape[K], ..., self.shape[P-1]].
For example, say we want to add 4 scattered elements to a rank-1 tensor to 8 elements. In Python, that update would look like this:
v = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8]) indices = tf.constant([[4], [3], [1] ,[7]]) updates = tf.constant([9, 10, 11, 12]) op = v.scatter_nd_sub(indices, updates) with tf.compat.v1.Session() as sess: print sess.run(op)
The resulting update to v would look like this:
[1, -9, 3, -6, -6, 6, 7, -4]
See tf.scatter_nd
for more details about how to make updates to
slices.
indices
: The indices to be used in the operation.updates
: The values to be used in the operation.name
: the name of the operation.A Tensor
that will hold the new value of this variable after
the scattered subtraction has completed.
scatter_nd_update
scatter_nd_update( indices, updates, name=None )
Applies sparse assignment to individual values or slices in a Variable.
The Variable has rank P
and indices
is a Tensor
of rank Q
.
indices
must be integer tensor, containing indices into self.
It must be shape [d_0, ..., d_{Q-2}, K]
where 0 < K <= P
.
The innermost dimension of indices
(with length K
) corresponds to
indices into elements (if K = P
) or slices (if K < P
) along the K
th
dimension of self.
updates
is Tensor
of rank Q-1+P-K
with shape:
[d_0, ..., d_{Q-2}, self.shape[K], ..., self.shape[P-1]].
For example, say we want to add 4 scattered elements to a rank-1 tensor to 8 elements. In Python, that update would look like this:
v = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8]) indices = tf.constant([[4], [3], [1] ,[7]]) updates = tf.constant([9, 10, 11, 12]) op = v.scatter_nd_assign(indices, updates) with tf.compat.v1.Session() as sess: print sess.run(op)
The resulting update to v would look like this:
[1, 11, 3, 10, 9, 6, 7, 12]
See tf.scatter_nd
for more details about how to make updates to
slices.
indices
: The indices to be used in the operation.updates
: The values to be used in the operation.name
: the name of the operation.A Tensor
that will hold the new value of this variable after
the scattered assignment has completed.
scatter_sub
scatter_sub( sparse_delta, use_locking=False, name=None )
Subtracts tf.IndexedSlices
from this variable.
sparse_delta
: tf.IndexedSlices
to be subtracted from this variable.use_locking
: If True
, use locking during the operation.name
: the name of the operation.A Tensor
that will hold the new value of this variable after
the scattered subtraction has completed.
TypeError
: if sparse_delta
is not an IndexedSlices
.scatter_update
scatter_update( sparse_delta, use_locking=False, name=None )
Assigns tf.IndexedSlices
to this variable.
sparse_delta
: tf.IndexedSlices
to be assigned to this variable.use_locking
: If True
, use locking during the operation.name
: the name of the operation.A Tensor
that will hold the new value of this variable after
the scattered assignment has completed.
TypeError
: if sparse_delta
is not an IndexedSlices
.set_shape
set_shape(shape)
Overrides the shape for this variable.
shape
: the TensorShape
representing the overridden shape.sparse_read
sparse_read( indices, name=None )
Gather slices from params axis axis according to indices.
This function supports a subset of tf.gather, see tf.gather for details on usage.
indices
: The index Tensor
. Must be one of the following types: int32
,
int64
. Must be in range [0, params.shape[axis])
.name
: A name for the operation (optional).A Tensor
. Has the same type as params
.
to_proto
to_proto(export_scope=None)
Converts a Variable
to a VariableDef
protocol buffer.
export_scope
: Optional string
. Name scope to remove.A VariableDef
protocol buffer, or None
if the Variable
is not
in the specified name scope.
value
value()
Returns the last snapshot of this variable.
You usually do not need to call this method as all ops that need the value
of the variable call it automatically through a convert_to_tensor()
call.
Returns a Tensor
which holds the value of the variable. You can not
assign a new value to this tensor as it is not a reference to the variable.
To avoid copies, if the consumer of the returned value is on the same device as the variable, this actually returns the live value of the variable, not a copy. Updates to the variable are seen by the consumer. If the consumer is on a different device it will get a copy of the variable.
A Tensor
containing the value of the variable.


Looking for you next wardrobe favorite? Well, look no further because this crop tee is printed and sewn to fit you just right. To top that off, the original all-over design is definitely worth showing off, so don’t hesitate to own one of these tees – they’re meant to be adored.
• 95% polyester, 5% elastane (fabric composition may vary by 1%)
• Premium knit mid-weight jersey
• Four-way stretch fabric that stretches and recovers on the cross and lengthwise grains
• Regular fit
ADDITIONAL INFORMATION
Weight
15000 g
Dimensions
20 × 102 × 62 cm
REVIEWS
There are no reviews yet.
BE THE FIRST TO REVIEW “HOLA 3 PIECE SETTING”
Your email address will not be published. Required fields are marked *
MAECENAS IACULIS
Vestibulum curae torquent diam diam commodo parturient penatibus nunc dui adipiscing convallis bulum parturient suspendisse parturient a.Parturient in parturient scelerisque nibh lectus quam a natoque adipiscing a vestibulum hendrerit et pharetra fames nunc natoque dui.
MAECENAS IACULIS
Vestibulum penatibus nunc dui adipiscing convallis bulum parturient suspendisse.
Abitur parturient praesent lectus quam a natoque adipiscing a vestibulum hendre.
Scelerisque adipiscing bibendum sem vestibulum et in a a a purus lectus faucibus lobortis tincidunt purus lectus nisl class eros.Condimentum a et ullamcorper dictumst mus et tristique elementum nam inceptos hac parturient scelerisque vestibulum amet elit ut volutpat.


offers foolproof deep cloning of objects, arrays, numbers, strings, maps, sets, promises, etc. in JavaScript.
npm install clone
(It also works with browserify, ender or standalone. You may want to use the
option noParse
in browserify to reduce the resulting file size, since usually
Buffer
s are not needed in browsers.)
var clone = require('clone');
var a, b;
a = { foo: { bar: 'baz' } }; // initial value of a
b = clone(a); // clone a -> b
a.foo.bar = 'foo'; // change a
console.log(a); // show a
console.log(b); // show b
This will print:
{ foo: { bar: 'foo' } }
{ foo: { bar: 'baz' } }
clone masters cloning simple objects (even with custom prototype), arrays, Date objects, and RegExp objects. Everything is cloned recursively, so that you can clone dates in arrays in objects, for example.
clone(val, circular, depth)
val
-- the value that you want to clone, any type allowed
circular
-- boolean
Call clone
with circular
set to false
if you are certain that obj
contains no circular references. This will give better performance if
needed. There is no error if undefined
or null
is passed as obj
.
depth
-- depth to which the object is to be cloned (optional,
defaults to infinity)
prototype
-- sets the prototype to be used when cloning an object.
(optional, defaults to parent prototype).
includeNonEnumerable
-- set to true
if the non-enumerable properties
should be cloned as well. Non-enumerable properties on the prototype chain
will be ignored. (optional, defaults to false
)
clone.clonePrototype(obj)
obj
-- the object that you want to cloneDoes a prototype clone as described by Oran Looney.
var a, b;
a = { hello: 'world' };
a.myself = a;
b = clone(a);
console.log(b);
This will print:
{ hello: "world", myself: [Circular] }
So, b.myself
points to b
, not a
. Neat!
npm test
Some special objects like a socket or process.stdout
/stderr
are known to not
be cloneable. If you find other objects that cannot be cloned, please open an
issue.
If you encounter any bugs or issues, feel free to open an issue at github or send me an email to<EMAIL_ADDRESS>I also always like to hear from you, if you’re using my code.
Copyright © 2011-2016 Paul Vorbach and contributors.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


WebGL2 is nearly 100% backward compatible with WebGL1. If you only use WebGL1 features then then there are only 2 differences.
You use "webgl2"
instead of "webgl"
when calling getContext
var gl = someCanvas.getContext("webgl2");
Note: there is no "experimental-webgl2". The browser vendors got together and decided no more prefixing things because websites get dependent on the prefix.
Many extensions are a standard part of WebGL2 and so not available as extensions
For example Vertex Array Objects OES_vertex_array_object
is a
standard feature of WebGL2. So for example in WebGL1 you'd do this
var ext = gl.getExtension("OES_vertex_array_object");
if (!ext) {
// tell user they don't have the required extension or work around it
} else {
var someVAO = ext.createVertexArrayOES();
}
In WebGL2 you'd do this
var someVAO = gl.createVertexArray();
Because it just exists.
Otherwise all your WebGL1 stuff should just work.
That being said to take advantage of most WebGL2 features you'll need to make some changes.
The biggest change is you should upgrade your shaders to GLSL 3.00 ES. To do that the first line of your shaders needs to be
#version 300 es
NOTE: THIS HAS TO BE THE FIRST LINE! No comments, no blank lines before it allowed.
In other words this is bad
// BAD!!!! +---There's a new line here!
// BAD!!!! V
var vertexShaderSource = `
#version 300 es
..
`;
This is bad too
<!-- BAD!! V<- there's a new line here
<script id="vs" type="notjs">
#version 300 es
...
</script>
This is good
var vertexShaderSource = `#version 300 es
...
`;
This is good too
<script id="vs" type="notjs">#version 300 es
...
</script>
Or you could make your shader compiling functions strip the first blank lines.
There are several changes you'll need to make to your shaders on top of adding the version string above
attribute
-> in
In GLSL 100 you might have
attribute vec4 a_position;
attribute vec2 a_texcoord;
attribute vec3 a_normal;
In GLSL 300 es that becomes
in vec4 a_position;
in vec2 a_texcoord;
in vec3 a_normal;
varying
to in
/ out
In GLSL 100 you might declare a varying in both the vertex and fragment shaders like this
varying vec2 v_texcoord;
varying vec3 v_normal;
In GLSL 300 es in the vertex shader the varyings become
out vec2 v_texcoord;
out vec3 v_normal;
And in the fragment shader they become
in vec2 v_texcoord;
in vec3 v_normal;
gl_FragColor
In GLSL 100 your fragment shader would set the special
variable gl_FragColor
to set the output of the shader.
gl_FragColor = vec4(1, 0, 0, 1); // red
In GLSL 300 es you declare your own output variable and then set it.
out vec4 myOutputColor;
void main() {
myOutputColor = vec4(1, 0, 0, 1); // red
}
Note: You can pick any name you want but names can not start with
gl_
so you can't just make out vec4 gl_FragColor
texture2D
-> texture
etc.In GLSL 100 you'd get a color from a texture like this
uniform sampler2D u_some2DTexture;
uniform samplerCube u_someCubeTexture;
...
vec4 color1 = texture2D(u_some2DTexture, ...);
vec4 color2 = textureCube(u_someCubeTexture, ...);
In GLSL 300es the texture functions automatically know
what to do based on the sampler type so now it's just
texture
uniform sampler2D u_some2DTexture;
uniform samplerCube u_someCubeTexture;
...
vec4 color1 = texture(u_some2DTexture, ...);
vec4 color2 = texture(u_someCubeTexture, ...);
In WebGL1 many features were optional extensions. In WebGL2 all of the following are standard features
gl_FragDepth
(EXT_frag_depth)in WebGL1 textures that were not a power of 2 could not have mips. In WebGL2 that limit is removed. Non-power of 2 texture work exactly the same as power of 2 textures.
Of all the features above the one feature I personally think you should always ALWAYS use is vertex array objects. Everything else it really depends on what you're trying to do but vertex array objects in particular seem like a basic feature that should always be used.
In WebGL1 without vertex array objects all the data about attributes was global WebGL state.
Before each thing you wanted to draw you needed to setup all the attirbutes and if you
were drawing indexed data you needed to set the ELEMENT_ARRAY_BUFFER
.
With Vertex Array Objects that entire attributeState
above becomes a Vertex Array.
In other words
var someVAO = gl.createVertexArray();
Makes a new instance of the thing above called attributeState
.
gl.bindVertexArray(someVAO);
Is equivilent to
glState.attributeState = someVAO;
What that means is you should setup all of your attributes at init time now.
// at init time
for each model / geometry / ...
var vao = gl.createVertexArray()
gl.bindVertexArray(vao);
for each attribute
gl.enableVertexAttribArray(...);
gl.bindBuffer(gl.ARRAY_BUFFER, bufferForAttribute);
gl.vertexAttribPointer(...);
if indexed geometry
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
gl.bindVertexArray(null);
Then at render time to use a particular geometry all you need to do is
gl.bindVertexArray(vaoForGeometry);
In WebGL1 the init loop object would have appeared at render time.
There are a few caveats though:
attribute locations are program dependent.
If you're going to use the same geometry with multiple programs consider manually assinging attribute locations. In GLSL 300 es you can do this in the shader
For example:
layout(location = 0) in vec4 a_position;
layout(location = 1) in vec2 a_texcoord;
layout(location = 2) in vec3 a_normal;
layout(location = 3) in vec4 a_color;
Sets the locations of the 4 attributes. This means you can force them to be comptible across multiple shader programs. If one program doesn't need all attributes the attributes they do need will still be assigned to the same locations
If you don't do this you'll need different VAOs for different shader programs when using same geometry OR you'll need to just do the WebGL1 thing and not use VAOs and always setup attributes at render time.
Always unbind the VAO when you're done
gl.bindVertexArray(null);
This just comes from my own experience. If you look above
the ELEMENT_ARRAY_BUFFER
state is part of a Vertex Array.
So, I ran into this issue. I created some geometry, then
I created a VAO for that geometry and set up the attributes
and ELEMENT_ARRAY_BUFFER
. I then created some more
geometry. When that geometry setup its indices, because
I still had the previous VAO bound setting up the indices
effected the ELEMENT_ARRAY_BUFFER
binding for the previous
VAO. It took me several hours to debug.
So, my suggestion is never leave a VAO bound if you're done
with it. Either immediately bind the next VAO you're going
to use or if you're done bind null
That's my personal short list of things to be aware of when switching from WebGL1 to WebGL2. There's even more stuff you can do in WebGL2 though.


Iconic Beatles album cover photographer Freeman dies
LONDON, Nov 9 — Photographer Robert Freeman, who helped define The Beatles’ mop top look on their early album covers, has died, the legendary Liverpool band said Saturday. He was 82.
“Besides being a great professional he was imaginative and a true original thinker,” Paul McCartney wrote in a blog post.
“I will miss this wonderful man but will always cherish the fond memories I have of him.”
Freeman’s photographs first made the covers of the quartet’s “Meet the Beatles!” and “Beatles for Sale” albums, which came out at the height of the Beatlemania that swept the world in the mid-1960s.
For the slightly comical cover of Help!, John Lennon, McCartney, George Harrison and Ringo Starr were meant to spell out the title in flag semaphore.
Freeman decided to rearrange their arm positions to give the cover a better look, with the group spelling out gibberish in the end — but it hardly hurt sales.
On Rubber Soul, the slightly distorted look of the band’s portrait foreshadowed the psychodelic era that was to define both the band’s later sound and the late 1960s.
In his blog, McCartney explained that it was created by accident when a card the picture was being projected onto fell backwards, warping the image.
McCartney said Freeman assured the band he could reproduce the exact same image on the cover.
“God bless Robert Freeman,” Ringo Starr tweeted. “Peace and love to all his family.”
Lennon was stabbed to death by a crazed fan outside his Manhattan apartment building in 1980 when he was 40, and Harrison died of lung cancer at the age of 58 in 2001.
Freeman went on to photograph other pop culture icons such as Andy Warhol and Muhammed Ali. — AFP


I have definitely been a victim of asking poor or bad questions. As a complete beginner to programming, It was hard for me to ask questions when I’m not even sure on how to phrase it to begin with.
One of the best things you can do when asking your question is by showing your code and being very clear about what you want to achieve. Additionally, providing picture illustrations such as snippets of your code or pseudo code will help the reader to understand and have a better visulazation of your program.
The last thing you want to do when you submit your question is to proof read it. Being dyslexic, I have a tendency to repeat words in a sentence or have typos without even noticing it at all. I have to make it a point to proof read anything I type at least twice to ensure that the reader could comprehend what I’m trying to say.