为什么要使用tensorflow??
- GPU加速
- 自动求导
- 神经网络API
创建Tensor
import numpy as np
import tensorflow as tf
# 通过numpy新建一个tensor
print(tf.convert_to_tensor(np.ones([2,3])))
'''
tf.Tensor(
[[1. 1. 1.]
[1. 1. 1.]], shape=(2, 3), dtype=float64)
'''
print(tf.convert_to_tensor(np.zeros([2,3])))
'''
tf.Tensor(
[[0. 0. 0.]
[0. 0. 0.]], shape=(2, 3), dtype=float64)
'''
# 通过list新建一个tensor
print(tf.convert_to_tensor([1, 2]))
'''
tf.Tensor([1 2], shape=(2,), dtype=int32)
'''
print(tf.convert_to_tensor([1,2.]))
'''有浮点型的会自动升级成浮点型
f.Tensor([1. 2.], shape=(2,), dtype=float32)
'''
print(tf.convert_to_tensor([[1],[2.]]))
'''
tf.Tensor(
[[1.]
[2.]], shape=(2, 1), dtype=float32)
'''
#通过zeros新建tensor #注意区别 传入的是shape
print(tf.zeros([]))
'''
tf.Tensor(0.0, shape=(), dtype=float32)
'''
print(tf.zeros([1]))
'''
tf.Tensor([0.], shape=(1,), dtype=float32)
'''
print(tf.zeros([2, 2]))
'''
tf.Tensor(
[[0. 0.]
[0. 0.]], shape=(2, 2), dtype=float32)
'''
#补充:zeros_like
a = tf.zeros([2,3,3])
print(tf.zeros_like(a))
print(tf.zeros(a.shape))
''' 通过输出结果,容易知道zeros_like(a) == zeros(a.shape)
tf.Tensor(
[[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]], shape=(2, 3, 3), dtype=float32)
'''
# ones 、 zeros 、fill 传入的都是形状 ,
# 但是fill有两个参数,fill(shape,fill_number)
#nomal
'''
shape: 输出张量的形状,必选
mean: 正态分布的均值,默认为0
stddev: 正态分布的标准差,默认为1.0
'''
print(tf.random.normal([2, 2]))
'''两行两列
tf.Tensor(
[[-0.04308414 -0.12444644]
[ 2.297514 0.08265623]], shape=(2, 2), dtype=float32)
'''
print(tf.random.normal([2, 2], mean=1, stddev=1))
'''
tf.Tensor(
[[ 0.5382552 -0.78469336]
[ 1.4849964 1.3553046 ]], shape=(2, 2), dtype=float32)
'''
print(tf.random.truncated_normal([2,2],mean=0,stddev=1))
'''
tf.Tensor(
[[-0.9349827 0.02447166]
[ 0.0598432 0.24900012]], shape=(2, 2), dtype=float32)
'''
#uniform
'''
默认是在 0 到 1 之间产生随机数,
也可以通过 minval 和 maxval 指定上下界
产生的值是均匀分布的
'''
print(tf.random.uniform([2, 2], minval=0, maxval=1))
'''
tf.Tensor(
[[0.7684654 0.3918556 ]
[0.13457572 0.8725331 ]], shape=(2, 2), dtype=float32)
'''
print(tf.random.uniform([2, 2], minval=0, maxval=100))
'''
tf.Tensor(
[[0.7684654 0.3918556 ]
[0.13457572 0.8725331 ]], shape=(2, 2), dtype=float32)
'''
# 例子 :0-9打散 ??? 没看懂
idx = tf.range(10)
idx = tf.random.shuffle(idx)
a = tf.random.normal([10,784])
b = tf.random.uniform([10],maxval=10,dtype=tf.int32)
tf.gather(a,idx)
tf.gather(b,idx)
#通过constant新建tensor
print(tf.constant(1))
'''
tf.Tensor(1, shape=(), dtype=int32)
'''
print(tf.constant(1.))
'''
tf.Tensor(1.0, shape=(), dtype=float32)
'''
print(tf.constant([1,2.]))
'''
tf.Tensor([1. 2.], shape=(2,), dtype=float32)
'''
# print(tf.constant([1,2.],[3]))#报错
tensor的索引和切片
- 按下标取
- 按numpy方式的下标取法
- start:end 使用冒号取(左闭右开)
一维
多维度
多维度进阶
- 省略号
为什么要使用省略号?
如上图所示,a[:,:,:,:,0]看起来特别不好看,直接使用省略号,使得代码更简洁好看。
- tensorflow张量索引
gather (a.shape : [4, 35, 8])
该函数的重要参数:
params, 传入的tensor
indices, 指定的索引
axis=0 指定轴
gather_n (可以写多个同级索引,用逗号隔开)
该函数的重要参数:
params, 传入的tensor
indices 指定de索引
boolean_mask
该函数的重要参数:
params, 传入的tensor
mask
axis 维度