0
# Core Tensor Operations
1
2
Fundamental tensor creation, manipulation, and mathematical operations that form the foundation of TensorFlow computations. These operations provide the building blocks for constructing complex machine learning models and numerical computations.
3
4
## Capabilities
5
6
### Tensor Creation
7
8
Create tensors from various data sources including constants, variables, and Python data structures.
9
10
```python { .api }
11
def constant(value, dtype=None, shape=None, name="Const"):
12
"""
13
Creates a constant tensor from tensor-like objects.
14
15
Parameters:
16
- value: A constant value (or list) of output type dtype or a list of values of type dtype
17
- dtype: The type of the elements of the resulting tensor
18
- shape: Optional dimensions of resulting tensor
19
- name: Optional name for the operation
20
21
Returns:
22
A Constant Tensor
23
"""
24
25
def Variable(initial_value, trainable=None, validate_shape=True,
26
caching_device=None, name=None, variable_def=None, dtype=None,
27
import_scope=None, constraint=None, synchronization=tf.VariableSynchronization.AUTO,
28
aggregation=tf.VariableAggregation.NONE, shape=None,
29
experimental_enable_variable_lifting=True):
30
"""
31
Creates a new variable with value initial_value.
32
33
Parameters:
34
- initial_value: A Tensor, or Python object convertible to a Tensor
35
- trainable: If True, GradientTapes automatically watch uses of this Variable
36
- validate_shape: If False, allows the variable to be initialized with a value of unknown shape
37
- caching_device: Optional device string describing where the Variable should be cached
38
- name: Optional name for the variable
39
- dtype: If set, initial_value will be converted to the given type
40
- constraint: An optional projection function to be applied to the variable after being updated
41
- synchronization: Indicates when a distributed a variable will be aggregated
42
- aggregation: Indicates how a distributed variable will be aggregated
43
- shape: The shape of this variable
44
- experimental_enable_variable_lifting: Whether to enable variable lifting optimization
45
46
Returns:
47
A Variable
48
"""
49
50
def zeros(shape, dtype=tf.float32, name=None):
51
"""
52
Creates a tensor with all elements set to zero.
53
54
Parameters:
55
- shape: A list of integers, a tuple of integers, or a 1-D Tensor of type int32
56
- dtype: The type of an element in the resulting Tensor
57
- name: A name for the operation
58
59
Returns:
60
A Tensor with all elements set to zero
61
"""
62
63
def ones(shape, dtype=tf.float32, name=None):
64
"""
65
Creates a tensor with all elements set to one.
66
67
Parameters:
68
- shape: A list of integers, a tuple of integers, or a 1-D Tensor of type int32
69
- dtype: The type of an element in the resulting Tensor
70
- name: A name for the operation
71
72
Returns:
73
A Tensor with all elements set to one
74
"""
75
76
def fill(dims, value, name=None):
77
"""
78
Creates a tensor filled with a scalar value.
79
80
Parameters:
81
- dims: A Tensor of type int32. 1-D. Represents the shape of the output tensor
82
- value: A Tensor. 0-D (scalar). Value to fill the returned tensor
83
- name: A name for the operation
84
85
Returns:
86
A Tensor
87
"""
88
89
def reshape(tensor, shape, name=None):
90
"""
91
Reshapes a tensor.
92
93
Parameters:
94
- tensor: A Tensor
95
- shape: A Tensor of type int32. Defines the shape of the output tensor
96
- name: A name for the operation
97
98
Returns:
99
A Tensor. Has the same type as tensor
100
"""
101
102
def transpose(a, perm=None, conjugate=False, name="transpose"):
103
"""
104
Transposes a tensor.
105
106
Parameters:
107
- a: A Tensor
108
- perm: A permutation of the dimensions of a
109
- conjugate: Setting it to True is mathematically equivalent to tf.math.conj(tf.transpose(input))
110
- name: A name for the operation
111
112
Returns:
113
A transposed Tensor
114
"""
115
116
def eye(num_rows, num_columns=None, batch_shape=None, dtype=tf.float32, name=None):
117
"""
118
Construct an identity matrix, or a batch of matrices.
119
120
Parameters:
121
- num_rows: Non-negative int32 scalar Tensor giving the number of rows in each batch matrix
122
- num_columns: Optional non-negative int32 scalar Tensor giving the number of columns
123
- batch_shape: A list or tuple of Python integers or a 1-D int32 Tensor
124
- dtype: The type of an element in the resulting Tensor
125
- name: A name for this Op
126
127
Returns:
128
A Tensor of shape batch_shape + [num_rows, num_columns]
129
"""
130
```
131
132
### Type Conversion and Casting
133
134
Convert tensors between different data types and formats.
135
136
```python { .api }
137
def convert_to_tensor(value, dtype=None, dtype_hint=None, name=None):
138
"""
139
Converts the given value to a Tensor.
140
141
Parameters:
142
- value: An object whose type has a registered Tensor conversion function
143
- dtype: Optional element type for the returned tensor
144
- dtype_hint: Optional element type for the returned tensor, used when dtype is None
145
- name: Optional name to use if a new Tensor is created
146
147
Returns:
148
A Tensor based on value
149
"""
150
151
def cast(x, dtype, name=None):
152
"""
153
Casts a tensor to a new type.
154
155
Parameters:
156
- x: A Tensor or SparseTensor or IndexedSlices of numeric type
157
- dtype: The destination type
158
- name: A name for the operation
159
160
Returns:
161
A Tensor or SparseTensor or IndexedSlices with same shape as x and requested dtype
162
"""
163
164
def to_float(x, name="ToFloat"):
165
"""
166
Casts a tensor to type float32.
167
168
Parameters:
169
- x: A Tensor or SparseTensor or IndexedSlices
170
- name: A name for the operation
171
172
Returns:
173
A Tensor or SparseTensor or IndexedSlices with same shape as x with type float32
174
"""
175
176
def to_double(x, name="ToDouble"):
177
"""
178
Casts a tensor to type float64.
179
180
Parameters:
181
- x: A Tensor or SparseTensor or IndexedSlices
182
- name: A name for the operation
183
184
Returns:
185
A Tensor or SparseTensor or IndexedSlices with same shape as x with type float64
186
"""
187
188
def to_int32(x, name="ToInt32"):
189
"""
190
Casts a tensor to type int32.
191
192
Parameters:
193
- x: A Tensor or SparseTensor or IndexedSlices
194
- name: A name for the operation
195
196
Returns:
197
A Tensor or SparseTensor or IndexedSlices with same shape as x with type int32
198
"""
199
200
def to_int64(x, name="ToInt64"):
201
"""
202
Casts a tensor to type int64.
203
204
Parameters:
205
- x: A Tensor or SparseTensor or IndexedSlices
206
- name: A name for the operation
207
208
Returns:
209
A Tensor or SparseTensor or IndexedSlices with same shape as x with type int64
210
"""
211
```
212
213
### Shape Manipulation
214
215
Operations for inspecting and manipulating tensor shapes and dimensions.
216
217
```python { .api }
218
def shape(input, name=None, out_type=tf.int32):
219
"""
220
Returns the shape of a tensor.
221
222
Parameters:
223
- input: A Tensor or SparseTensor
224
- name: A name for the operation
225
- out_type: The desired output type
226
227
Returns:
228
A Tensor of type out_type
229
"""
230
231
def size(input, name=None, out_type=tf.int32):
232
"""
233
Returns the size of a tensor.
234
235
Parameters:
236
- input: A Tensor or SparseTensor
237
- name: A name for the operation
238
- out_type: The desired output type
239
240
Returns:
241
A Tensor of type out_type
242
"""
243
244
def rank(input, name=None):
245
"""
246
Returns the rank of a tensor.
247
248
Parameters:
249
- input: A Tensor or SparseTensor
250
- name: A name for the operation
251
252
Returns:
253
A Tensor of type int32
254
"""
255
256
def reshape(tensor, shape, name=None):
257
"""
258
Reshapes a tensor.
259
260
Parameters:
261
- tensor: A Tensor
262
- shape: A Tensor of type int32. Defines the shape of the output tensor
263
- name: A name for the operation
264
265
Returns:
266
A Tensor. Has the same type as tensor
267
"""
268
269
def squeeze(input, axis=None, name=None):
270
"""
271
Removes dimensions of size 1 from the shape of a tensor.
272
273
Parameters:
274
- input: A Tensor. The input to squeeze
275
- axis: An optional list of ints. If specified, only squeezes the dimensions listed
276
- name: A name for the operation
277
278
Returns:
279
A Tensor. Has the same type as input
280
"""
281
282
def expand_dims(input, axis, name=None):
283
"""
284
Inserts a dimension of 1 into a tensor's shape.
285
286
Parameters:
287
- input: A Tensor
288
- axis: 0-D (scalar). Specifies the dimension index at which to expand
289
- name: A name for the operation
290
291
Returns:
292
A Tensor with the same data as input, but its shape has an additional dimension of size 1
293
"""
294
```
295
296
### Tensor Utilities
297
298
Utility functions for tensor inspection and manipulation.
299
300
```python { .api }
301
def identity(input, name=None):
302
"""
303
Return a tensor with the same shape and contents as input.
304
305
Parameters:
306
- input: A Tensor
307
- name: A name for this operation
308
309
Returns:
310
A Tensor. Has the same type as input
311
"""
312
313
def stop_gradient(input, name=None):
314
"""
315
Stops gradient computation.
316
317
Parameters:
318
- input: A Tensor or IndexedSlices
319
- name: A name for the operation
320
321
Returns:
322
A Tensor or IndexedSlices. Has the same type as input
323
"""
324
325
def is_tensor(x):
326
"""
327
Checks whether x is a tensor or "tensor-like".
328
329
Parameters:
330
- x: A python object to check
331
332
Returns:
333
True if x is a tensor or "tensor-like", False if not
334
"""
335
336
def name_scope(name, default_name=None, values=None):
337
"""
338
A context manager for use when defining a Python op.
339
340
Parameters:
341
- name: The name argument that is passed to the op function
342
- default_name: The default name to use if the name argument is None
343
- values: The list of Tensor arguments that are passed to the op function
344
345
Returns:
346
A context manager that yields the current name scope
347
"""
348
```
349
350
## Usage Examples
351
352
```python
353
import tensorflow as tf
354
355
# Create tensors
356
x = tf.constant([1, 2, 3, 4])
357
y = tf.Variable([1.0, 2.0, 3.0, 4.0])
358
z = tf.zeros((2, 3))
359
identity_matrix = tf.eye(4)
360
361
# Type conversion
362
x_float = tf.cast(x, tf.float32)
363
x_tensor = tf.convert_to_tensor([1, 2, 3])
364
365
# Shape manipulation
366
print(tf.shape(x)) # [4]
367
print(tf.size(x)) # 4
368
print(tf.rank(x)) # 1
369
370
# Reshape operations
371
reshaped = tf.reshape(x, (2, 2))
372
expanded = tf.expand_dims(x, axis=0) # Shape: (1, 4)
373
squeezed = tf.squeeze(expanded) # Shape: (4,)
374
375
# Utilities
376
identity_x = tf.identity(x)
377
no_grad_x = tf.stop_gradient(x)
378
```