import tensorflow as tf
import numpy as np
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'

# list: 可以嵌套,内存中不连续存放,使用动态指针
# 数组,读写效率低下,不适合做数值运算

# numpy数组:元素类型相同,连续内存,只能在cpu运算

# 每个张量都是一个Tensor对象,是多维数组的载体
# CPU环境下,张量和NumPy共享同一块内存
# 多维张量在内存中是以一维数组的方式连续存储的

# tf.constant(value, dtype, shape)创建张量
#    num/list/numpy, datatype, [张量的形状]
# 张量的属性:ndim维度, size大小, dtype

# tf.convert_to_tensor(list/nums/num/bool/str) 转化为张量

tensor1 = tf.constant([[1,2],[3,4]])
print(tensor1)
print(tensor1.numpy())

#创建全1张量
ones = tf.ones(shape=(2,3), dtype = tf.int32) 
print("ones tensor: ", ones, "\n")

#创建全0张量
zeros = tf.zeros(shape=(4,4), dtype=tf.float32) 
print("zeros tensor: ", zeros, "\n")

 #创建元素值相同的张量
fills = tf.fill(dims=[3,3], value=10)
print("fill tensor: ", fills, "\n")

#创建元素相同的张量
constant = tf.constant(value=9, shape=[2,3]) 
print("constant tensor: ", constant, "\n")

# 创建正态分布随机张量  shape=形状, mean=均值,stddev=标准差,数据类型
normal = tf.random.normal(shape=[5,5], mean=0, stddev=1, dtype=tf.float32)
print("normal tensor: ", normal, "\n")

# 截断正态分布  截断标准为标准差两倍, 不会出现两倍标准差外的数 
normal_truncated = tf.random.truncated_normal(shape=[4,4], dtype=tf.float32)
print('normal_truncated tensor: ', normal_truncated, '\n')

# 设置随机种子 可以产生同样的张量
tf.random.set_seed(5)
seed_tensor1 = tf.random.normal([2,2])
print('seed_tensor1: ', seed_tensor1, '\n')
tf.random.set_seed(5)
seed_tensor2 = tf.random.normal([2,2])
print('seed_tensor2: ', seed_tensor2, '\n')

# 创建均匀分布张量
unifom = tf.random.uniform((3,3), 0, 10, 'float32')
print('unifom tensor: ', unifom, '\n')

# 沿第一维随机打乱
shuffle = np.arange(5)
shuffle = tf.random.shuffle(shuffle)
print("shuffle tensor: ", shuffle, '\n')

# 创建序列, start, end, step
range_tensor = tf.range(1, 10, 2)
print("range_tensor:", range_tensor,'\n')

# 张量形状的改变 tf.reshape(tensor, shape), shape中-1代表未知,需要自动推导
a = tf.range(24)
b = tf.reshape(a, [2,4,3])
print("reshape tensor: ",b, '\n')

# 张量维度的增加,改变了张量试图,不改变存储
expend_tensor = tf.constant([1,3,5])
print('expend_tensor0.shape: ',expend_tensor.shape)
expend_tensor = tf.expand_dims(expend_tensor, 1)
print('expand_tensor1.shape: ', expend_tensor.shape)
expend_tensor = tf.expand_dims(expend_tensor, 2)
print('expand_tensor2.shape: ', expend_tensor.shape)

# 张量维度的删除, 只能删除长度为1的维度
squ_tensor = tf.squeeze(expend_tensor,[2])
print("squ_tensor.shape: ", squ_tensor.shape)

# 张量交换维度
tran_tensor = tf.constant([[1,2,3],[4,5,6]])
tran_tensor = tf.transpose(tran_tensor,[1,0])
print('\n','tran_tensor:', tran_tensor)

# 拼接与分割
first = tf.constant([[1,2,3],[4,5,6]])
seconed = tf.constant([[7,8,9],[10,11,12]])
concat = tf.concat([first, seconed], 0)
print('concat_tensor: ', concat)

x = tf.range(24)
x = tf.reshape(x, [4,6])
x1, x2, x3 = tf.split(x, [1,2,1], 0)
print("x1:", x1,'\nx2: ',x2,'\nx3: ',x3)

# 堆叠和分解 axis=堆叠维度
st1 = tf.constant([1,2,3])
st2 = tf.constant([4,5,6])
stack_tensor = tf.stack((st1, st2), axis=1)
print("\nstack_tensor: ", stack_tensor)