tensorflow2.0笔记-基本概念

本文介绍了TensorFlow 2.0中张量的基本操作,包括加法、乘法、平方及张量与NumPy数组之间的转换。同时,详细讲解了如何利用GPU加速计算,以及tf.data.Dataset API的使用方法,包括创建数据集、使用map、batch、shuffle等函数对数据集进行转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文是在学习tensorflow2.0官方教程时的一个笔记,原始教程请见[张量与操作]。(https://www.tensorflow.org/tutorials/customization/basics)

1 导入tensorflow

import tensorflow as tf

2 张量

2.1 张量计算

张量类似于numpy中的多数组。下面是add(加)、square(平方),reduce_sum(求和)。张量和numpy数组的区别在于张量便于gpu加速、张量是不可变的。具体张量的理解可参考https://blog.youkuaiyun.com/pandamax/article/details/63684633

print(tf.add(1, 2))
print(tf.add([1, 2], [3, 4]))
print(tf.square(5))
print(tf.reduce_sum([1, 2, 3]))

# Operator overloading is also supported
print(tf.square(2) + tf.square(3))

运行结果

tf.Tensor(3, shape=(), dtype=int32)
tf.Tensor([4 6], shape=(2,), dtype=int32)
tf.Tensor(25, shape=(), dtype=int32)
tf.Tensor(6, shape=(), dtype=int32)
tf.Tensor(13, shape=(), dtype=int32)

2.2 numpy和张量之间是兼容的

tf的运算可以自动转换为bunpy,反之亦然。张量使用. NumPy()方法显式地转换为NumPy ndarrays。这些转换通常很便宜,因为数组和tf张量共享底层的内存表示,如果可能的话。然而,并不总是共享底层的,因为tf张量可能驻留在GPU内存中,而NumPy数组总是由主机内存支持,并且转换涉及从GPU到主机内存的拷贝。

import numpy as np

ndarray = np.ones([3, 3])

print("TensorFlow operations convert numpy arrays to Tensors automatically")
tensor = tf.multiply(ndarray, 42)
print(tensor)


print("And NumPy operations convert Tensors to numpy arrays automatically")
print(np.add(tensor, 1))

print("The .numpy() method explicitly converts a Tensor to a numpy array")
print(tensor.numpy())

TensorFlow operations convert numpy arrays to Tensors automatically
tf.Tensor(
[[42. 42. 42.]
[42. 42. 42.]
[42. 42. 42.]], shape=(3, 3), dtype=float64)
And NumPy operations convert Tensors to numpy arrays automatically
[[43. 43. 43.]
[43. 43. 43.]
[43. 43. 43.]]
The .numpy() method explicitly converts a Tensor to a numpy array
[[42. 42. 42.]
[42. 42. 42.]
[42. 42. 42.]]

2.3 gpu加速

许多TensorFlow操作使用GPU加速计算。无需任何注释,TensorFlow自动决定是使用GPU还是CPU执行操作——如果需要的话,在CPU和GPU内存之间复制张量。操作产生的张量通常由执行操作的设备的内存支持,例如:

x = tf.random.uniform([3, 3])

print("Is there a GPU available: "),
print(tf.config.experimental.list_physical_devices("GPU"))

print("Is the Tensor on GPU #0:  "),
print(x.device.endswith('GPU:0'))

这里没有GPU,会输出以下结果

Is there a GPU available:
[]
Is the Tensor on GPU #0:
False

在TensorFlow中,位置指的是如何分配(放置)设备上的单个操作来执行。如前所述,当没有提供明确的指导时,TensorFlow会自动决定执行操作的设备,并在需要时将张量复制到该设备。但是,可以使用tf.device context manager将TensorFlow操作显式地放在特定的设备上,例如:

import time

def time_matmul(x):
  start = time.time()
  for loop in range(100):
    tf.matmul(x, x)

  result = time.time()-start

  print("10 loops: {:0.2f}ms".format(1000*result))

# Force execution on CPU
print("On CPU:")
with tf.device("CPU:0"):
  x = tf.random.uniform([1000, 1000])
  assert x.device.endswith("CPU:0")
  time_matmul(x)

# Force execution on GPU #0 if available
if tf.config.experimental.list_physical_devices("GPU"):
  print("On GPU:")
  with tf.device("GPU:0"): # Or GPU:1 for the 2nd GPU, GPU:2 for the 3rd etc.
    x = tf.random.uniform([1000, 1000])
    assert x.device.endswith("GPU:0")
    time_matmul(x)

运行结果
On CPU:
10 loops: 2482.79ms
On GPU:
10 loops: 2.50ms

3 数据集

这一部分介绍 tf.data.Dataset API

3.1 创建dataset
# 根据slice创建dataset
ds_tensors = tf.data.Dataset.from_tensor_slices([1, 2, 3, 4, 5, 6])

# 这里是在colab上运行程序的,所以需要挂载自己的云端硬盘
import os
from google.colab import drive
drive.mount('/content/drive')
path = "/content/drive/My Drive/text.txt"
# 生成存储一个txt文本
with open(path, 'w') as f:
  f.write("""Line 1
     Line 2
Line 3
  """)
# 根据textline创建dataset
ds_file = tf.data.TextLineDataset(path)
print(ds_tensors)
print(ds_file)

运行结果:

Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).
<BatchDataset shapes: (None,), types: tf.int32>
<TextLineDatasetV2 shapes: (), types: tf.string>

3.2 使用map、batch、shuffle等函数对dataset进行转换

map:将一种运算映射到数据库上的元素,运算可以自行定义
batch:对数据进行打包,如下例中的2指打包后每份的元素个数为2
shuffle:随机打乱数据库中的元素,其中的buffer_size不是很好解释,可参见https://juejin.im/post/5b855d016fb9a01a1a27d035

# 对ds_tensors 中的数据平方后,进行打乱(buffersize为2),然后进行分包
ds_tensors = ds_tensors.map(tf.square).shuffle(2).batch(2)

# 对ds_file中的元素进行分包
ds_file = ds_file.batch(2)
print('Elements of ds_tensors:')
for x in ds_tensors:
  print(x.numpy())
print('\nElements in ds_file:')
for x in ds_file:
  print(x)

运行结果:

Elements of ds_tensors:
[4 9]
[16 1]
[36 25]
Elements in ds_file:
tf.Tensor([b’Line 1’ b’ Line 2’], shape=(2,), dtype=string)
tf.Tensor([b’Line 3’ b’ '], shape=(2,), dtype=string)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值