Tensor张量不难,Tensor基础入门篇

习惯了Numpy,用的也非常顺手,但是用上了TensorFlow难免就会接触到Tensor,对不熟悉的东西难免有畏惧感,今天就简单的看看Tenfor有哪些操作,以后看见了也不用害怕了

主要内容

  • Tensor的基本操作
  • Tensor和Numpy之间相互转换
  • Tensor相对于Numpy有哪些优点
  • 怎么处理Dataset数据集中的Tensor

Tensor的基本操作

  • 首先Tensor中的矩阵可以做加法、乘法
  • 可以对Tensor中的数据进行平方等操作
  • 可以统计Tensor中数据的中和
    代码实现:
import tensorflow as tf
print(tf.add([1, 2], [3, 4]))
print(tf.matmul([[2],[1]], [[2, 3]])) # 乘法
print(tf.square(2) + tf.square(3))
print(tf.reduce_sum([[1, 2, 3],[4, 5, 6]]))

Tensor和Numpy之间相互转换

  • Tensor可以像Numpy一样查看基本属性
    代码:
x = tf.matmul([[2]], [[2, 3]])
print(x)
print(x.shape)
print(x.dtype)
  • Numpy转换为Tensor
import numpy as np

ndarray = np.ones([3, 3])
tensor = tf.multiply(ndarray, 42) #用tensor加入运算,就直接变化
print(type(tensor))
  • Tensor转换Numpy的方法
a =  np.add(tensor, 1)
print(type(a))
b = tensor.numpy()
print(type(b))

Tensor相对于Numpy有哪些优点

  • Tensor数据默认会自动放在GPU内存中(如果有GPU)
  • Numpy数据默认会放在内存中,相对Tensor更慢
  • Tensor也可以指定将数据存放在的内存
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.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)

处理Dataset数据集中的Tensor

我只有图片地址,我想通过tensor读取图片,并做归一化处理

def preprocess_mask(image):
    image = tf.image.decode_jpeg(image, channels=3)
    image = tf.image.resize(image, [128, 128])
    image = image//255.0  # normalize to [0,1] range
    return image

def load_and_preprocess_image(path):
  image = tf.io.read_file(path)
  return preprocess_image(image)

AUTOTUNE = tf.data.experimental.AUTOTUNE
path_ds = tf.data.Dataset.from_tensor_slices(img_path) 
image_ds = path_ds.map(load_and_preprocess_image, num_parallel_calls=AUTOTUNE)
  • img_path:是图片
  • path_ds:就是通过from_tensor_slices方法读入的DataSet
  • load_and_preprocess_image:读取图片
  • preprocess_mask:处理图片
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。