TensorFlow里面的Tensor“张量”,到底是个什么鬼?
0维张量/标量 标量是一个数字
1维张量/向量 1维张量称为“向量”。
2维张量 2维张量称为矩阵
3维张量 公用数据存储在张量 时间序列数据 股价 文本数据 彩色图片(RGB)
在我的理解里,张量=容器,是一个由数字构成的立方体,三维即三个坐标轴的东东
入门级:1.数据类型
import tensorflow as tf
#一、定义:数据类型
#1.张量概念,使用constant创建的均为常量不可更改
#光print只能看到属性,需要调用session运行才能看到值
sess = tf.compat.v1.Session()
#创建一个布尔值
t = tf.constant([True, False])
#创建一个整形常0量 , 0阶tensor
t0 = tf.constant(3,dtype=tf.int32)
print(t0)
#print(sess.run(t0))
#创建一个浮点数的一维数组,1阶tensor
t1 = tf.constant([3.1,3.2,3.3],dtype=tf.float32)
print(t1)
#print(sess.run(t1))
#创建一个字符串的2*2数组,2阶tensor
t2 = tf.constant([['one','two'],['three','four']],dtype=tf.string)
print(t2)
#print(sess.run(t2))
#创建一个2*3*1的3阶张量
t3 = tf.constant([[[1],[2],[3]],[[4],[5],[6]]])
print(t3)
#print(sess.run(t3))
#2.graph构建
#首先创建两个常量节点
node1 = tf.constant(3.2)
node2 = tf.constant(4.8)
#adder操作
adder = node1 + node2
print(adder)
#print(sess.run(adder))
#3. 使用placeholder创建占位Tensor节点,该值可以在运行时输入
#a = tf.placeholder(tf.float32)
#b = tf.placeholder(tf.float32)
#adder_node = a + b
#print(a)
#print(b)
#print(adder_node)
#二、属性
#1. 在CPU创建,调用设备属性函数device
with tf.device('cpu'):
a = tf.constant([1])
print(a)
print(a.device)#查看设备属性
#2. 在GPU创建
with tf.device('gpu'):
b = tf.constant([1])
print(b)
print(b.device)#查看设备属性
#3.cpu转gpu
a1 = a.gpu
print(a1)
#4.gpu转cpu
b1 = b.cpu
print(b1)
#5. 获取数据类型numpy函数
print(a.numpy())
print(b.numpy())
#6. 获取属性shape
a_shape = a.shape
print(a_shape)
b_shape = b.shape
print(b_shape)
#7.获取维度的两种方法1.ndim 2.tf.rank()
print(a.ndim)
print(tf.rank(a))
print(b.ndim)
print(tf.rank(b))