0
点赞
收藏
分享

微信扫一扫

TensorFlow2 学习1. 张量

一、TensorFlow2.0

TensorFlow 2.0推荐使用Keras 构建和学习神经网络 。

1. 导入

从TensorFlow 2.0默认情况下会启用eager模式执行。 这为TensorFlow提供了一个更加互动的前端节。

from __future__ import absolute_import, division, print_function
import tensorflow as tf

2. 张量

i. 张量与ndarray互转

张量(TF.tensors)是TensorFlow的数据类型,类似NumPy ndarry,可以常驻Gpu中进行各种操作。
示例:

from __future__ import absolute_import, division, print_function
import tensorflow as tf

print(tf.add(1, 2)) # tf.Tensor(3, shape=(), dtype=int32)

print(tf.add([3, 8], [2, 5])) # tf.Tensor([ 5 13], shape=(2,), dtype=int32)
print(tf.square(6)) # tf.Tensor(36, shape=(), dtype=int32)
print(tf.reduce_sum([7, 8, 9])) # tf.Tensor(24, shape=(), dtype=int32)
print(tf.square(3) + tf.square(4)) # tf.Tensor(25, shape=(), dtype=int32)
  • 张量是不可变的
  • 张量支持GPU运算

张量与Numpy ndarrays可互相转换,TensorFlow操作自动将NumPy ndarrays转换为Tensors。
NumPy操作自动将Tensors转换为NumPy ndarrays,它们会共享内存。但如果Tensors在GPU的时候不能共享。

2. 示例

from __future__ import absolute_import, division, print_function
import tensorflow as tf
import numpy as np

ndarray = np.ones([2,2])
tensor = tf.multiply(ndarray, 36)
print(tensor)
'''
tf.Tensor(
[[36. 36.]
[36. 36.]], shape=(2, 2), dtype=float64)
'''
# 用np.add对tensorflow进行加运算
print(np.add(tensor, 1))
'''
[[37. 37.]
[37. 37.]]
'''
# 转换为numpy类型
print(tensor.numpy())
'''
[[36. 36.]
[36. 36.]]
'''

3. GPU加速

使用GPU进行计算可以加速许多TensorFlow操作。 如果没有任何注释,TensorFlow会自动决定是使用GPU还是CPU进行操作 - 如有必要,可以复制CPU和GPU内存之间的张量。 由操作产生的张量通常由执行操作的设备的存储器支持,例如:

from __future__ import absolute_import, division, print_function
import tensorflow as tf
import numpy as np
x = tf.random.uniform([3, 3])
print('Is GPU availabel: %s' % tf.test.is_gpu_available())
print('Is the Tensor on gpu #0: %s' % x.device.endswith('GPU:0'))
print(x.device)
'''
/job:localhost/replica:0/task:0/device:CPU:0
'''

demo:

from __future__ import absolute_import, division, print_function
import tensorflow as tf
import numpy as np

import time
def time_matmul(x):
start = time.time()
for loop in range(10):
tf.matmul(x, x)
result = time.time() - start
print('10 loops: {:0.2}ms'.format(1000*result))

# 强制使用CPU
print('On CPU:')
with tf.device('CPU:0'):
x = tf.random.uniform([1000, 1000])
# 使用断言验证当前是否为CPU0
assert x.device.endswith('CPU:0')
time_matmul(x)

# 如果存在GPU,强制使用GPU
if tf.test.is_gpu_available():
print('On GPU:')
with tf.device.endswith('GPU:0'):
x = tf.random.uniform([1000, 1000])
# 使用断言验证当前是否为GPU0
assert x.device.endswith('GPU:0')
time_matmul(x)

4. 创建数据集

# 从列表中获取tensor
ds_tensors = tf.data.Dataset.from_tensor_slices([6,5,4,3,2,1])
# 创建csv文件
import tempfile
_, filename = tempfile.mkstemp()
print(filename)

with open(filename, 'w') as f:
f.write("""Line 1
Line 2
Line 3""")
# 获取TextLineDataset数据集实例
ds_file = tf.data.TextLineDataset(filename)

应用转换

使用map,batch和shuffle等转换函数将转换应用于数据集记录。

ds_tensors = ds_tensors.map(tf.square).shuffle(2).batch(2)
ds_file = ds_file.batch(2)

迭代

print('ds_tensors中的元素:')
for x in ds_tensors:
print(x)
# 从文件中读取的对象创建的数据源
print('\nds_file中的元素:')
for x in ds_file:
print(x)

输出:

ds_tensors中的元素:
tf.Tensor([36 16], shape=(2,), dtype=int32)
tf.Tensor([25 4], shape=(2,), dtype=int32)
tf.Tensor([1 9], shape=(2,), dtype=int32)

ds_file中的元素:
tf.Tensor([b'Line 1' b'Line 2'], shape=(2,), dtype=string)
tf.Tensor([b'Line 3'], shape=(1,), dtype=string)


举报

相关推荐

0 条评论