Tensorflow 数据类型转换
程序开发
2023-09-14 11:32:28
Tensorflow 数据类型转换
1.Numpy ==> Tensor
import tensorflow as tf
import numpy as np
# 数据类型转换
# np ==> tensor tf.convert_to_tensor
a_np = np.arange(5)
print(a_np.dtype)
a_tensor = tf.convert_to_tensor(a_np)
print(a_tensor)
a_tensor = tf.convert_to_tensor(a_np, dtype=tf.int32)
print(a_tensor)
2.Tensor <==> Tensor
# tensor 之间的类型转换 tf.cast
# tf.int32 ==> tf.float32
a_tensor_float32 = tf.cast(a_tensor, dtype=tf.float32)
print(a_tensor_float32)
# tf.float32 ==> tf.float64
a_tensor_float64 = tf.cast(a_tensor_float32, dtype=tf.double)
print(a_tensor_float64)
# tf.float64 ==> tf.int32
a_tensor_int32 = tf.cast(a_tensor_float64, dtype=tf.int32)
print(a_tensor_int32)
# tf.int32 ==> tf.bool
b_int = tf.constant([0, 1])
print(b_int)
b_bool = tf.cast(b_int, dtype=tf.bool)
print(b_bool)
# tf.bool ==> tf.int32
b_int = tf.cast(b_bool, dtype=tf.int32)
print(b_int)
3.Tensor ==> Numpy
# tensor 数据类型转换成 numpy
a = np.random.random([2, 2])
a_tensor = tf.convert_to_tensor(a, dtype=tf.float32)
print(a_tensor)
# tensor ==> numpy numpy()
print(a_tensor.numpy())
a = tf.ones([])
print(a.numpy())
# tensor ⇒ int
# 必须是标量
print(int(a))
# 必须是标量
print(float(a))
标签:
上一篇:
Anaconda3与PyCharm安装配置保姆教程
下一篇:
相关文章
-
无相关信息