TensorFlow:Larger-Scale Machine Learning on Heterogeous Distributed Systenms
(TensforFlow:异构分布式系统的大规模机器学习)中介绍了Tensorflow系统的框架的设计和实现pip install --upgrade tensorflow==2.0.0
如果不知道怎么做,可以看文章【深度学习】【TensorFlow 】查看Tensorflow和python对应版本、将现有的TensorFlow更新到指定的版本
(tensorflow2_7) C:\Users\xxx>python
Python 3.7.11 (default, Jul 27 2021, 09:42:29) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
>>> tf.__version__
'2.0.0'
>>> tf.executing_eagerly()# 检测当前是否在eager模式下
True
例如:
对于代码:
import tensorflow as tf
a = tf.constant(2,name="input_a")
b = tf.constant(3,name="input_b")
c = tf.add(a,b,name="add_c")
sess = tf.Session()
print(sess.run(c))
sess.close()
运行结果为:
提示没有这个Session()函数
(tensorflow2_7) C:\Users\xxx\Desktop\english_cx\shen_du_xue_xi\3_1>python first.py
2021-11-08 20:46:09.709836: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
Traceback (most recent call last):
File "first.py", line 7, in <module>
sess = tf.Session()
AttributeError: module 'tensorflow' has no attribute 'Session'
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
如果刚开始学习Tensorflow,不用理会1.x
tf.constant(value,dtype,shape)
>>> import tensorflow as tf
>>> tf.constant([[1,2],[3,4]])
<tf.Tensor: id=2, shape=(2, 2), dtype=int32, numpy=
array([[1, 2],
[3, 4]])>
>>> import tensorflow as tf
>>> tf.constant(1.0)
<tf.Tensor: id=14, shape=(), dtype=float32, numpy=1.0>
>>> tf.constant(1.)
<tf.Tensor: id=16, shape=(), dtype=float32, numpy=1.0>
>>> tf.constant(1.0, dtype = tf.float64)
<tf.Tensor: id=18, shape=(), dtype=float64, numpy=1.0>
shape=()
:可以看作是0维张量,也就是一个数字,一个标量dtype = tf.float64
:创建张量时,指定张量元素的数据类型,这里要加上tf作为前缀,表示这是tensorflow中的数据类型>>> import tensorflow as tf
>>> import numpy as np
>>> tf.constant(np.array([1,2]))
<tf.Tensor: id=20, shape=(2,), dtype=int32, numpy=array([1, 2])>
>>> tf.constant(np.array([1.0,2.0]))
<tf.Tensor: id=22, shape=(2,), dtype=float64, numpy=array([1., 2.])>
>>> tf.constant(np.array([1.0,2.0]),dtype=tf.float32)
<tf.Tensor: id=24, shape=(2,), dtype=float32, numpy=array([1., 2.], dtype=float32)>
>>> import tensorflow as tf
>>> tf.constant(True)
<tf.Tensor: id=33, shape=(), dtype=bool, numpy=True>
>>> a = tf.constant([True,False])
>>> tf.cast(a, tf.int32)
<tf.Tensor: id=36, shape=(2,), dtype=int32, numpy=array([1, 0])>
>>> a = tf.constant([-1,0,1,2])
>>> tf.cast(a, tf.bool)
<tf.Tensor: id=39, shape=(4,), dtype=bool, numpy=array([ True, False, True, True])>
>>> import tensorflow as tf
>>> tf.constant("hello")
<tf.Tensor: id=41, shape=(), dtype=string, numpy=b'hello'>
numpy=b'hello'
中的b意思是这是一个字节串,因为在python3中字符串默认是Unicode编码,因此要转换为字节串,在原先的字符串前加上一个b>>> import tensorflow as tf
>>> a = tf.constant([[1,2],[3,4]])
>>> a.numpy() # 输出一个numpy数组
array([[1, 2],
[3, 4]])
>>> type(a)
<class 'tensorflow.python.framework.ops.EagerTensor'>
# 表示是一个eager模式下的张量
>>> print(a)
tf.Tensor(
[[1 2]
[3 4]], shape=(2, 2), dtype=int32)
数据类型 | 描述 |
---|---|
tf.int8 | 8位有符号整数 |
tf.int16 | 16位有符号整数 |
tf.int32 | 32位有符号整数 |
tf.int64 | 64位有符号整数 |
tf.uint8 | 8位无符号整数 |
tf.float32 | 32位浮点数 |
tf.float64 | 64位浮点数 |
tf.string | 字符串(非Unicode编码的字节数组) |
tf.bool | 布尔型 |
tf.comples64 | 复数,实部和虚部分分别为32位浮点型 |
程序格式为:
>>> import tensorflow as tf
>>> a = tf.constant(np.array([1,2]))
>>> b = tf.cast(a, dtype = tf.float32)
>>> b.dtype
tf.float32
>>> a = tf.constant(123456789,dtype = tf.int32)
>>> tf.cast(a,tf.int16)
<tf.Tensor: id=31, shape=(), dtype=int16, numpy=-13035>
tf.convert_to_tensor(数组/列表/数字/布尔型/字符串)
>>> import tensorflow as tf
>>> import numpy as np
>>> na = np.arange(12).reshape(3,4)
>>> ta = tf.convert_to_tensor(na)
>>> type(na)
<class 'numpy.ndarray'>
>>> type(ta)
<class 'tensorflow.python.framework.ops.EagerTensor'>
>>> ta
<tf.Tensor: id=43, shape=(3, 4), dtype=int32, numpy=
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])>
>>> na
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
#接上
>>> tf.is_tensor(na)
False
>>> tf.is_tensor(ta)
True
>>> isinstance(ta,tf.Tensor)
True
>>> isinstance(na,np.ndarray)
True
tf.zeros(shape,dtype=tf.float32)
tf.ones(shape,dtype=tf.float32)
例如:
>>> import tensorflow as tf
>>> tf.ones(shape=(2,1))
<tf.Tensor: id=47, shape=(2, 1), dtype=float32, numpy=
array([[1.],
[1.]], dtype=float32)>
>>> tf.ones([6])
<tf.Tensor: id=51, shape=(6,), dtype=float32, numpy=array([1., 1., 1., 1., 1., 1.], dtype=float32)>
>>> tf.ones([2,3],tf.int32)
<tf.Tensor: id=59, shape=(2, 3), dtype=int32, numpy=
array([[1, 1, 1],
[1, 1, 1]])>
tf.fill(dims,value)
>>> import tensorflow as tf
>>> tf.fill([2,3],9)
<tf.Tensor: id=63, shape=(2, 3), dtype=int32, numpy=
array([[9, 9, 9],
[9, 9, 9]])>
>>> tf.fill([2,3],9.0)
<tf.Tensor: id=67, shape=(2, 3), dtype=float32, numpy=
array([[9., 9., 9.],
[9., 9., 9.]], dtype=float32)>
>>> import tensorflow as tf
>>> tf.constant(9,shape=[2,3])
<tf.Tensor: id=71, shape=(2, 3), dtype=int32, numpy=
array([[9, 9, 9],
[9, 9, 9]])>
>>> tf.constant(9,shape=(2,3))
<tf.Tensor: id=75, shape=(2, 3), dtype=int32, numpy=
array([[9, 9, 9],
[9, 9, 9]])>
>>> tf.fill(dims=[2,3],value=9)
<tf.Tensor: id=79, shape=(2, 3), dtype=int32, numpy=
array([[9, 9, 9],
[9, 9, 9]])>
>>> tf.constant(value=9,shape=[2,3])
<tf.Tensor: id=83, shape=(2, 3), dtype=int32, numpy=
array([[9, 9, 9],
[9, 9, 9]])>
tf.random.normal(shape,mean,stddev,dtype)
例如;创建一个2*2的张量,其元素服从标准正态分布的张量
>>> import tensorflow as tf
>>> tf.random.normal([2,2])
<tf.Tensor: id=90, shape=(2, 2), dtype=float32, numpy=
array([[ 0.48454306, 0.7746329 ],
[ 2.2181435 , -0.62854046]], dtype=float32)>
例如:创建一个三位张量,其元素服从正太分布
>>> import tensorflow as tf
>>> tf.random.normal(shape=[3,3],mean=0,stddev=1,dtype=tf.float32)
<tf.Tensor: id=97, shape=(3, 3), dtype=float32, numpy=
array([[ 1.8088632 , 0.49246895, 0.8497273 ],
[-1.1053319 , -3.4912257 , 0.03176761],
[ 1.0519494 , -0.9557805 , 0.4212218 ]], dtype=float32)>
tf.random.truncated_normal(shape,mean,stddev,dtype)
>>> import tensorflow as tf
>>> tf.random.set_seed(8)
>>> tf.random.normal([2,2])
<tf.Tensor: id=104, shape=(2, 2), dtype=float32, numpy=
array([[ 1.2074401 , -0.7452463 ],
[ 0.6908678 , -0.76359874]], dtype=float32)>
>>> tf.random.normal([2,2])
<tf.Tensor: id=111, shape=(2, 2), dtype=float32, numpy=
array([[ 1.6407531 , -0.41693485],
[-2.174734 , 0.14891738]], dtype=float32)>
>>> tf.random.set_seed(8)
>>> tf.random.normal([2,2])
<tf.Tensor: id=118, shape=(2, 2), dtype=float32, numpy=
array([[ 1.2074401 , -0.7452463 ],
[ 0.6908678 , -0.76359874]], dtype=float32)>
tf.random.uniform(shape,minval,maxval,dtype)
>>> import tensorflow as tf
>>> tf.random.uniform(shape=[3,3],minval=0,maxval=10,dtype='int32')
<tf.Tensor: id=123, shape=(3, 3), dtype=int32, numpy=
array([[6, 8, 3],
[9, 5, 1],
[8, 6, 1]])>
>>> import tensorflow as tf
>>> import numpy as np
>>> x = tf.constant([[1,2],[3,4],[5,6]])
>>> tf.random.shuffle(x)
<tf.Tensor: id=126, shape=(3, 2), dtype=int32, numpy=
array([[1, 2],
[5, 6],
[3, 4]])>
>>> y = [1,2,3,4,5,6]
>>> tf.random.shuffle(y)
<tf.Tensor: id=129, shape=(6,), dtype=int32, numpy=array([1, 5, 4, 2, 3, 6])>
>>> z = np.arange(5)
>>> tf.random.shuffle(z)
<tf.Tensor: id=132, shape=(5,), dtype=int32, numpy=array([3, 1, 2, 4, 0])>
tf.range(start,limit,delta=1,dtype)
>>> import tensorflow as tf
>>> tf.range(10)
<tf.Tensor: id=137, shape=(10,), dtype=int32, numpy=array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])>
>>> tf.range(10,delta=2)
<tf.Tensor: id=142, shape=(5,), dtype=int32, numpy=array([0, 2, 4, 6, 8])>
>>> tf.range(1,10,delta=2)
<tf.Tensor: id=147, shape=(5,), dtype=int32, numpy=array([1, 3, 5, 7, 9])>
>>> import tensorflow as tf
>>> tf.constant([[1,2],[3,4]])
<tf.Tensor: id=149, shape=(2, 2), dtype=int32, numpy=
array([[1, 2],
[3, 4]])>
>>> a = tf.constant([[1,2],[3,4]])
>>> a.ndim
2
>>> a.shape
TensorShape([2, 2])
>>> a.dtype
tf.int32
>>> import tensorflow as tf
>>> tf.constant([[1,2],[3,4]])
<tf.Tensor: id=149, shape=(2, 2), dtype=int32, numpy=
array([[1, 2],
[3, 4]])>
>>> a = tf.constant([[1,2],[3,4]])
>>> tf.shape(a)
<tf.Tensor: id=152, shape=(2,), dtype=int32, numpy=array([2, 2])>
>>> tf.size(a)
<tf.Tensor: id=154, shape=(), dtype=int32, numpy=4>
>>> tf.rank(a)
<tf.Tensor: id=156, shape=(), dtype=int32, numpy=2>
1、可以在JupyterNotbook中直接使用_______命令,来更新Tensorflow版本。
C.!pip install --upgrade tensorflow
2、下列说法中,错误的是__A__。
A.Python列表中的元素必须使用相同的数据类型
B.TensorFlow张量可以运行于GPU和TPU上
C.Python列表不适合用来做多维数组数值计算
D.NumPy数组不支持GPU运算
7、运行下面程序,结果正确的是__A__。
import tensorflow as tf
import numpy as np
tf.constant(np.array([1.0, 2.0]))
A.
4个班级合并为两个班,每个班十组,逻辑上发生改变,物理上的位置不变
tf.reshape(tensor,shape)
例如:直接创建一个24序列的张量,然后将其转换为(2,3,4)形状的张量
>>> import tensorflow as tf
>>> a = tf.range(24)
>>> a
<tf.Tensor: id=161, shape=(24,), dtype=int32, numpy=
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23])>
>>> b = tf.reshape(a,[2,3,4])
>>> b
<tf.Tensor: id=164, shape=(2, 3, 4), dtype=int32,
numpy=
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])>
例如:创建一个形状(2,3,4)的数组,然后将其转化为张量
>>> import tensorflow as tf
>>> b = tf.reshape(tf.range(24),[2,3,4])
>>> tf.constant(np.arange(24).reshape(2,3,4))
<tf.Tensor: id=166, shape=(2, 3, 4), dtype=int32,
numpy=
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])>
>>> tf.reshape(b,(4,-1))
<tf.Tensor: id=169, shape=(4, 6), dtype=int32, numpy=
array([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23]])>
tf.expend_dims(input,axis)
>>> import tensorflow as tf
>>> t = tf.constant([1,2])
>>> t
<tf.Tensor: id=2, shape=(2,), dtype=int32, numpy=array([1, 2])>
>>> t1 = tf.expand_dims(t,1)
<tf.Tensor: id=5, shape=(2, 1), dtype=int32, numpy=
array([[1],
[2]])>
>>> t2 = tf.expand_dims(t,0)
>>> t2
<tf.Tensor: id=8, shape=(1, 2), dtype=int32, numpy=array([[1, 2]])>
>>> t3 = tf.expand_dims(t,-1)
>>> t3
<tf.Tensor: id=11, shape=(2, 1), dtype=int32, numpy=
array([[1],
[2]])>
tf.squeeze(input, axis)
例如:
如果一个张量的形状为:(1,2,1,3,1)
,使用tf.shape(tf.squeeze(t))
,就会将其中长度为1的维度全部删除,得到的张量形状为(2,3)
;也可以指明删除的轴,tf.shape(tf.squeeze(t,[2,4]))
,得到的结果为张量形状为(1,2,3)
tf.transpose(a,perm)
例子:二维数组的例子
>>> import tensorflow as tf
>>> x = tf.constant([[1,2,3],[4,5,6]])
>>> x
<tf.Tensor: id=13, shape=(2, 3), dtype=int32, numpy=
array([[1, 2, 3],
[4, 5, 6]])>
>>> tf.transpose(x,perm=[1,0])
<tf.Tensor: id=16, shape=(3, 2), dtype=int32, numpy=
array([[1, 4],
[2, 5],
[3, 6]])>
例子,三维数组的例子
>>> import tensorflow as tf
>>> a = tf.range(24)
>>> b = tf.reshape(a,[2,3,4])
>>> b
<tf.Tensor: id=23, shape=(2, 3, 4), dtype=int32, numpy=
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])>
>>> tf.transpose(b,(1,0,2))
<tf.Tensor: id=26, shape=(3, 2, 4), dtype=int32, numpy=
array([[[ 0, 1, 2, 3],
[12, 13, 14, 15]],
[[ 4, 5, 6, 7],
[16, 17, 18, 19]],
[[ 8, 9, 10, 11],
[20, 21, 22, 23]]])>
tf.concat(tensors,axis)
>>> import tensorflow as tf
>>> t1 = [[1,2,3],[4,5,6]]
>>> t2 = [[7,8,9],[10,11,12]]
>>> tf.concat([t1,t2],0)
<tf.Tensor: id=31, shape=(4, 3), dtype=int32, numpy=
array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]])>
>>> tf.concat([t1,t2],1)
<tf.Tensor: id=36, shape=(2, 6), dtype=int32, numpy=
array([[ 1, 2, 3, 7, 8, 9],
[ 4, 5, 6, 10, 11, 12]])>
tf.split(value,num_or_size_spluts,axis=0)
[1,2,1]
:就表示分割成三个张量,长度分别是1,2,1例如:在轴axis=0轴上分割,平均分割两份
>>> import tensorflow as tf
>>> x = tf.range(24)
>>> x = tf.reshape(x,[4,6])
>>> x
<tf.Tensor: id=43, shape=(4, 6), dtype=int32, numpy=
array([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23]])>
>>> tf.split(x,2,0)
[<tf.Tensor: id=47, shape=(2, 6), dtype=int32, numpy=
array([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11]])>, <tf.Tensor: id=48, shape=(2, 6), dtype=int32, numpy=
array([[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23]])>]
例如:在轴axis=0轴上分割,分割三份,比例为1:2:1
>>> import tensorflow as tf
>>> x = tf.range(24)
>>> x = tf.reshape(x,[4,6])
>>> x
<tf.Tensor: id=43, shape=(4, 6), dtype=int32, numpy=
array([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23]])>
>>> tf.split(x,[1,2,1],0)
[<tf.Tensor: id=53, shape=(1, 6), dtype=int32, numpy=array([[0, 1, 2, 3, 4, 5]])>, <tf.Tensor: id=54, shape=(2, 6), dtype=int32, numpy=
array([[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17]])>, <tf.Tensor: id=55, shape=(1, 6), dtype=int32, numpy=array([[18,
19, 20, 21, 22, 23]])>]
例如:在轴axis=1轴上分割,分割两份,比例为2:4
>>> import tensorflow as tf
>>> x = tf.range(24)
>>> x = tf.reshape(x,[4,6])
>>> x
<tf.Tensor: id=43, shape=(4, 6), dtype=int32, numpy=
array([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23]])>
>>> tf.split(x,[2,4],1)
[<tf.Tensor: id=61, shape=(4, 2), dtype=int32, numpy=
array([[ 0, 1],
[ 6, 7],
[12, 13],
[18, 19]])>, <tf.Tensor: id=62, shape=(4, 4), dtype=int32, numpy=
array([[ 2, 3, 4, 5],
[ 8, 9, 10, 11],
[14, 15, 16, 17],
[20, 21, 22, 23]])>]
tf.stack(values,axis)
例如:
>>> import tensorflow as tf
>>> x = tf.constant([1,2,3])
>>> y = tf.constant([4,5,6])
>>> tf.stack((x,y),axis=0)
<tf.Tensor: id=67, shape=(2, 3), dtype=int32, numpy=
array([[1, 2, 3],
[4, 5, 6]])>
>>> tf.stack((x,y),axis=1)
<tf.Tensor: id=69, shape=(3, 2), dtype=int32, numpy=
array([[1, 4],
[2, 5],
[3, 6]])>
tf.unstack(values,axis)
* values:要分解的张量
* axis:分解的轴,消失的轴
>>> import tensorflow as tf
>>> c = tf.constant([[1,2,3],[4,5,6]])
>>> c
<tf.Tensor: id=71, shape=(2, 3), dtype=int32, numpy=
array([[1, 2, 3],
[4, 5, 6]])>
>>> tf.unstack(c,axis=0)
[<tf.Tensor: id=73, shape=(3,), dtype=int32, numpy=array([1, 2, 3])>,
<tf.Tensor: id=74, shape=(3,), dtype=int32, numpy=array([4, 5, 6])>]
>>> tf.unstack(c,axis=1)
[<tf.Tensor: id=77, shape=(2,), dtype=int32, numpy=array([1, 4])>,
<tf.Tensor: id=78, shape=(2,), dtype=int32, numpy=array([2, 5])>,
<tf.Tensor: id=79, shape=(2,), dtype=int32, numpy=array([3, 6])>]
a[1]
b[1][1]
b[1,1]
c[1][1][1]
c[1,1,1]
(60000,28,28)
mnist[0]
:取第1张图片中的数据mnist[0][1]
:取第1张图片中的第2行mnist[0][1][2]
:取第1张图片中的第2行的第3列起始位置:结束位置:步长
>>> import tensorflow as tf
>>> a = tf.range(10)
>>> a[::]
<tf.Tensor: id=90, shape=(10,), dtype=int32, numpy=array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])>
>>> a[::2] # 读取所有的偶数
<tf.Tensor: id=95, shape=(5,), dtype=int32, numpy=array([0, 2, 4, 6, 8])>
>>> a[1::2] # 读取所有的奇数
<tf.Tensor: id=100, shape=(5,), dtype=int32, numpy=array([1, 3, 5, 7, 9])>
>>> a[::-1] # 从最后以恶搞元素开始
<tf.Tensor: id=105, shape=(10,), dtype=int32, numpy=array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])>
>>> a[::-2]
<tf.Tensor: id=110, shape=(5,), dtype=int32, numpy=array([9, 7, 5, 3, 1])>
>>>import tensorflow as tf
>>> TRAIN_URL = "http://download.tensorflow.org/data/iris_training.csv"
>>> train_path = tf.keras.utils.get_file("iris_training.csv",TRAIN_URL)
>>> import pandas as pd
>>> df_iris = pd.read_csv(train_path)
>>> import numpy as np
>>> np_iris = np.array(df_iris)
>>> iris = tf.convert_to_tensor(np_iris)
>>> iris.shape
TensorShape([120, 5])
>>> iris[0,:] # 读取第一个样本中所有列
<tf.Tensor: id=4, shape=(5,), dtype=float64, numpy=array([6.4, 2.8, 5.6, 2.2, 2. ])>
>>> iris[0:5,0:4] # 前5个样本的所有属性
<tf.Tensor: id=8, shape=(5, 4), dtype=float64, numpy=
array([[6.4, 2.8, 5.6, 2.2],
[5. , 2.3, 3.3, 1. ],
[4.9, 2.5, 4.5, 1.7],
[4.9, 3.1, 1.5, 0.1],
[5.7, 3.8, 1.7, 0.3]])>
>>> iris[:,0] # 表示读取所有样本的第一个属性
<tf.Tensor: id=12, shape=(120,), dtype=float64, numpy=
array([6.4, 5. , 4.9, 4.9, 5.7, 4.4, 5.4, 6.9, 6.7, 5.1, 5.2, 6.9, 5.8,
5.4, 7.7, 6.3, 6.8, 7.6, 6.4, 5.7, 6.7, 6.4, 5.4, 6.1, 7.2, 5.2,
5.8, 5.9, 5.4, 6.7, 6.3, 5.1, 6.4, 6.8, 6.2, 6.9, 6.5, 5.8, 5.1,
4.8, 7.9, 5.8, 6.7, 5.1, 4.7, 6. , 4.8, 7.7, 4.6, 7.2, 5. , 6.6,
6.1, 5. , 7. , 6. , 7.4, 5.8, 6.2, 5. , 5.6, 6.7, 6.3, 6.4, 6.2,
7.3, 4.4, 7.2, 6.5, 5. , 4.7, 6.6, 5.5, 7.7, 6.1, 4.9, 5.5, 5.7,
6. , 6.4, 5.4, 6.1, 6.5, 5.6, 6.3, 4.9, 6.8, 5.7, 6. , 5. , 6.5,
6.1, 5.1, 4.6, 6.5, 4.6, 4.6, 7.7, 5.9, 5.1, 4.9, 4.9, 4.5, 5.8,
5. , 5.2, 5.3, 5. , 5.6, 4.8, 6.3, 5.7, 5.
, 6.3, 5. , 5.5, 5.7,
4.4, 4.8, 5.5])>
mnist[0,::,::]
:第一张图片mnist[0,::,::]
:第一张图片 (为了更加简洁,可以为1个:)mnist[0:10,:,:]
:前10张图片mnist[0:20,0:28:2,:]
:前20张图片的所有的行,隔行采样mnist[:,0:28:2,0:28:2]
:对所有的图片,隔行采样,并且隔列采样lena[:,:,0]
:R通道的图片lena[:,:,2]
:B通道的图片image[0,:,:,0]
:第1张图片的R通道image[0:2,:,:,2]
:前2张图片的B通道image[0:2,0:512:2,:,2]
:对前2张图片的B通道图片隔行采样*gather()函数:用一个索引列表,将给定张量中,对应索引值的元素提取出来
gather(params,indices)
例如:
>>>import tensorflow as tf
>>> a = tf.range(5)
>>> tf.gather(a, indices=[0,2,3])
<tf.Tensor: id=19, shape=(3,), dtype=int32, numpy=array([0, 2, 3])>
gather(params,axis,indices)
>>>import tensorflow as tf
>>> b = tf.reshape(a,[4,5])
>>> b
<tf.Tensor: id=25, shape=(4, 5), dtype=int32, numpy=
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])>
>>> tf.gather(b,axis=0,indices=[0,2,3])
<tf.Tensor: id=28, shape=(3, 5), dtype=int32, numpy=
array([[ 0, 1, 2, 3, 4],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])>
>>> tf.gather(b,axis=1,indices=[0,2,3])
<tf.Tensor: id=31, shape=(4, 3), dtype=int32, numpy=
array([[ 0, 2, 3],
[ 5, 7, 8],
[10, 12, 13],
[15, 17, 18]])>
>>>import tensorflow as tf
>>> b = tf.reshape(a,[4,5])
>>> b
<tf.Tensor: id=25, shape=(4, 5), dtype=int32, numpy=
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])>
>>> tf.gather_nd(b,[[0,0],[1,1],[2,3]])
<tf.Tensor: id=37, shape=(3,), dtype=int32, numpy=array([ 0, 6, 13])>
# 等同于
>>> b[0,0]
<tf.Tensor: id=41, shape=(), dtype=int32, numpy=0
>>> b[1,1]
<tf.Tensor: id=45, shape=(), dtype=int32, numpy=6
>>> b[2,3]
<tf.Tensor: id=49, shape=(), dtype=int32, numpy=13>
tf.gather_nd(lena,[[0,0],[1,1],[2,3]])
tf.gather_nd(mnist,[[0],[2],[3]])
算术操作 | 描述 |
---|---|
tf.add(s,y) | 将x和y逐元素相加 |
tf.subtract(x,y) | 将x和y逐元素相减 |
tf.multiply(x,y) | 将x和y逐元素相乘 |
tf.divide(x,y) | 将x和y逐元素相除 |
tf.math.mod(x,y) | 对x逐元素取模 |
>>> import tensorflow as tf
>>> a = tf.constant([0,1,2])
>>> b = tf.constant([3,4,5])
>>> tf.add(a,b)
<tf.Tensor: id=3, shape=(3,), dtype=int32, numpy=array([3, 5, 7])>
算术操作 | 描述 |
---|---|
tf.pow(x,y) | 对x求y的幂次方 |
tf.square(x) | 对x逐元素求计算平方 |
tf.aqrt(x) | 对x逐元素开平方根(要求x浮点数) |
tf.exp(x) | 计算e的x次方(要求x浮点数) |
tf.math.log(x) | 计算自然对数,底数为e(要求x浮点数) |
>>> import tensorflow as tf
>>> x = tf.range(4)
>>> x
<tf.Tensor: id=7, shape=(4,), dtype=int32, numpy=array([0, 1, 2, 3])>
>>> tf.pow(x,2)
<tf.Tensor: id=9, shape=(4,), dtype=int32, numpy=array([0, 1, 4, 9])>
>>> import tensorflow as tf
>>> x = tf.constant([[2,2],[3,3]])
>>> y = tf.constant([[8,16],[2,3]])
>>> tf.pow(x,y)
<tf.Tensor: id=20, shape=(2, 2), dtype=int32, numpy=
array([[ 256, 65536],
[ 9, 27]])>
>>> x = tf.constant([1.,4.,9.,16.]) # 如果这里都是整数,下式中的0.5就会出现报错,必须是浮点数类型
>>> tf.pow(x,0.5)
<tf.Tensor: id=35, shape=(4,), dtype=float32, numpy=array([1., 2., 3., 4.], dtype=float32)>
>>> import tensorflow as tf
>>> x = tf.constant([1,2,3,4])
>>> tf.square(x)
<tf.Tensor: id=37, shape=(4,), dtype=int32, numpy=array([ 1, 4, 9, 16])>
>>> x = tf.constant([1.,4.,9.,16.])
>>> tf.sqrt(x)
<tf.Tensor: id=39, shape=(4,), dtype=float32, numpy=array([1., 2., 3., 4.], dtype=float32)>
>>> f = tf.constant([[1.,9.],[16.,100.]])
>>> tf.sqrt(f)
<tf.Tensor: id=41, shape=(2, 2), dtype=float32, numpy=
array([[ 1., 3.],
[ 4., 10.]], dtype=float32)>
>>> import tensorflow as tf
>>> tf.exp(1.)
<tf.Tensor: id=44, shape=(), dtype=float32, numpy=2.7182817>
>>> x = tf.exp(3.)
>>> tf.math.log(x)
<tf.Tensor: id=47, shape=(), dtype=float32, numpy=3.0>
>>> import tensorflow as tf
>>> x = tf.constant(256.)
>>> y = tf.constant(2.)
>>> tf.math.log(x)/tf.math.log(y)
<tf.Tensor: id=52, shape=(), dtype=float32, numpy=8.0>
>>> x = tf.constant([[1.,9.],[16.,100.]])
>>> y = tf.constant([[2.,3.],[2.,10.]])
>>> tf.math.log(x)/tf.math.log(y)
<tf.Tensor: id=57, shape=(2, 2), dtype=float32, numpy=
array([[0., 2.],
[4., 2.]], dtype=float32)>
函数 | 描述 |
---|---|
tf.sign(x) | 返回x的符号 |
tf.abs(x) | 对x逐元素求绝对值 |
tf.negative(x) | 对x逐元素求相反数,y=-x |
tf.reciproca(x) | 取x的倒数 |
tf.logical_not(x) | 对x逐元素求得逻辑非 |
tf.ceil(x) | 向上取整 |
tf.floor(x) | 向下取整 |
tf.rint(x) | 取最接近得整数 |
tf.round(x) | 对x逐元素求舍入最接近得整数 |
tf.maximum(x,y) | 返回两tensor中的最大值 |
tf.minimum(x.y) | 返回两tensor中的最小值 |
函数 | 描述 |
---|---|
tf.cos(x) | 三角函数cos |
tf.sin(x) | 三角函数sin |
tf.tan(x) | 三角函数tan |
tf.acos(x) | 反三角函数arccos |
tf.asin(x) | 反三角函数arcsin |
tf.atan(x) | 反三角函数arctan |
运算符 | 构造方法 | 运算符 | 构造方法 |
---|---|---|---|
x+y | tf.add() | x&y | tf.logical_and() |
x-y | tf.subtract() | x|y | tf.logical_or() |
x*y | tf.multiply() | x^y | tf.logical_xor() |
x/y(python2.0) | tf.divide() | ~x | tf.logical_not() |
x/y(python3.0) | tf.truediv() | xtf.less() |
|
X//y(python) | tf.floordiv() | x<=y | tf.less_equal() |
x%y | tf.math.mod() | x>y | tf.equal() |
x**y | tf.pow() | x>=y | tf.greater_equal() |
-x | tf.neg() | ||
abs(x) | tf.abs() |
>>> import tensorflow as tf
>>> a = tf.constant([0,1,2,3])
>>> b = tf.constant([4,5,6,7])
>>> a+b
<tf.Tensor: id=60, shape=(4,), dtype=int32, numpy=array([ 4, 6, 8, 10])>
>>> a-b
<tf.Tensor: id=61, shape=(4,), dtype=int32, numpy=array([-4, -4, -4, -4])>
>>> a*b
<tf.Tensor: id=62, shape=(4,), dtype=int32, numpy=array([ 0, 5, 12, 21])>
>>> a/b
<tf.Tensor: id=65, shape=(4,), dtype=float64, numpy=array([0. , 0.2 , 0.33333333, 0.42857143])>
>>> a = tf.constant([0,1,2,3])
>>> b = 2
>>> a%b
<tf.Tensor: id=69, shape=(4,), dtype=int32, numpy=array([0, 1, 0, 1])>
>>> a = tf.constant([[0,1,2,3],[0,-1,-2,-3]])
>>> b = 2
>>> a//b
<tf.Tensor: id=72, shape=(2, 4), dtype=int32, numpy=
array([[ 0, 0, 1, 1],
[ 0, -1, -1, -2]])>
>>> a = tf.constant([0,1,2,3])
>>> b = 2
>>> a**b
<tf.Tensor: id=75, shape=(4,), dtype=int32, numpy=array([0, 1, 4, 9])>
>>> import tensorflow as tf
>>> a = tf.constant([1,2,3])
>>> a
<tf.Tensor: id=76, shape=(3,), dtype=int32, numpy=array([1, 2, 3])>
>>> b = tf.constant(np.arange(12).reshape(4,3))
>>> b
<tf.Tensor: id=77, shape=(4, 3), dtype=int32, numpy=
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])>
>>> a+b
<tf.Tensor: id=78, shape=(4, 3), dtype=int32, numpy=
array([[ 1, 3, 5],
[ 4, 6, 8],
[ 7, 9, 11],
[10, 12, 14]])>
>>> c = tf.constant(np.arange(12).reshape(2,2,3))
>>> c
<tf.Tensor: id=79, shape=(2, 2, 3), dtype=int32, numpy=
array([[[ 0, 1, 2],
[ 3, 4, 5]],
[[ 6, 7, 8],
[ 9, 10, 11]]])>
>>> a+c
<tf.Tensor: id=80, shape=(2, 2, 3), dtype=int32, numpy=
array([[[ 1, 3, 5],
[ 4, 6, 8]],
[[ 7, 9, 11],
[10, 12, 14]]])>
>>> a*c
<tf.Tensor: id=81, shape=(2, 2, 3), dtype=int32, numpy=
array([[[ 0, 2, 6],
[ 3, 8, 15]],
[[ 6, 14, 24],
[ 9, 20, 33]]])>
tf.constant();tf.convert_to_tensor
Tensor.numpy()
>>> import tensorflow as tf
>>> import numpy as np
>>> nd = np.ones([2,2])
>>> t = tf.multiply(nd,36)
>>> t
<tf.Tensor: id=84, shape=(2, 2), dtype=float64, numpy=
array([[36., 36.],
[36., 36.]])>
>>> np.add(nd,t)
array([[37., 37.],
[37., 37.]])
tf.multiply(),*运算符
;对应元素相等tf.matmul(),@运算符
矩阵乘法>>> import tensorflow as tf
>>> print("TensorFlow version: ",tf.__version__)
TensorFlow version: 2.0.0
# 先创建两个张量a和b
>>> import numpy as np
>>> a = tf.constant(np.arange(6),shape=(2,3))
>>> a
<tf.Tensor: id=87, shape=(2, 3), dtype=int32, numpy=
array([[0, 1, 2],
[3, 4, 5]])>
>>> b = tf.constant(np.arange(6),shape=(3,2))
>>> b
<tf.Tensor: id=90, shape=(3, 2), dtype=int32, numpy=
array([[0, 1],
[2, 3],
[4, 5]])>
>>> tf.matmul(a,b)
<tf.Tensor: id=91, shape=(2, 2), dtype=int32, numpy=
array([[10, 13],
[28, 40]])>
>>> a@b
<tf.Tensor: id=92, shape=(2, 2), dtype=int32, numpy=
array([[10, 13],
[28, 40]])>
>>> import tensorflow as tf
>>> import numpy as np
>>> a = tf.random.normal([2,3,5])
>>> b = tf.random.normal([5,4])
>>> tf.matmul(a,b)
<tf.Tensor: id=105, shape=(2, 3, 4), dtype=float32, numpy=
array([[[ 0.66367817, -1.8407946 , -5.1079473 , 1.115813 ],
[-1.0903633 , 2.9237514 , 1.0623133 , 0.25142556],
[ 0.19272862, -1.9880747 , -7.018299 , 1.1446145 ]],
[[ 1.5938025 , -3.0838017 , 2.6247544 , -2.5586433 ],
[-1.4260333 , 0.4984906 , -0.7839435 , 0.8160777 ],
[-0.18613842, 2.533684 , 3.4380057 , 0.7654592 ]]],
dtype=float32)>
>>> import tensorflow as tf
>>> import numpy as np
>>> a = tf.constant(np.arange(12),shape=(2,2,3))
>>> a
<tf.Tensor: id=108, shape=(2, 2, 3), dtype=int32,
numpy=
array([[[ 0, 1, 2],
[ 3, 4, 5]],
[[ 6, 7, 8],
[ 9, 10, 11]]])>
>>> b = tf.constant(np.arange(12),shape=(2,3,2))
>>> b
<tf.Tensor: id=111, shape=(2, 3, 2), dtype=int32,
numpy=
array([[[ 0, 1],
[ 2, 3],
[ 4, 5]],
[[ 6, 7],
[ 8, 9],
[10, 11]]])>
>>> tf.matmul(a,b)
<tf.Tensor: id=112, shape=(2, 2, 2), dtype=int32,
numpy=
array([[[ 10, 13],
[ 28, 40]],
[[172, 193],
[244, 274]]])>
>>> import tensorflow as tf
>>> import numpy as np
>>> a = tf.constant(np.arange(24),shape=(2,2,2,3))
>>> a
<tf.Tensor: id=115, shape=(2, 2, 2, 3), dtype=int32, numpy=
array([[[[ 0, 1, 2],
[ 3, 4, 5]],
[[ 6, 7, 8],
[ 9, 10, 11]]],
[[[12, 13, 14],
[15, 16, 17]],
[[18, 19, 20],
[21, 22, 23]]]])>
>>> b = tf.constant(np.arange(24),shape=(2,2,3,2))
>>> b
<tf.Tensor: id=118, shape=(2, 2, 3, 2), dtype=int32, numpy=
array([[[[ 0, 1],
[ 2, 3],
[ 4, 5]],
[[ 6, 7],
[ 8, 9],
[10, 11]]],
[[[12, 13],
[14, 15],
[16, 17]],
[[18, 19],
[20, 21],
[22, 23]]]])>
>>> tf.matmul(a,b)
<tf.Tensor: id=119, shape=(2, 2, 2, 2), dtype=int32, numpy=
array([[[[ 10, 13],
[ 28, 40]],
[[ 172, 193],
[ 244, 274]]],
[[[ 550, 589],
[ 676, 724]],
[[1144, 1201],
[1324, 1390]]]])>
函数 | 描述 |
---|---|
tf.reduce_sum(input_tensor,axis) | 求和 |
tf.reduce_mean(input_tensor,axis) | 求平均值 |
tf.reduce_max(input_tensor,axis) | 求最大值 |
tf.reduce_min(input_tensor,axis) | 求最小值 |
>>> import tensorflow as tf
>>> a = tf.constant([[1,5,3],[4,2,6]])
>>> a
<tf.Tensor: id=120, shape=(2, 3), dtype=int32, numpy=
array([[1, 5, 3],
[4, 2, 6]])>
>>> tf.reduce_sum(a,axis=0)
<tf.Tensor: id=122, shape=(3,), dtype=int32, numpy=array([5, 7, 9])>
>>> tf.reduce_sum(a,axis=1)
<tf.Tensor: id=124, shape=(2,), dtype=int32, numpy=array([ 9, 12])>
>>> tf.reduce_sum(a)
<tf.Tensor: id=126, shape=(), dtype=int32, numpy=21>
tf.cast()
将张量类型转化为浮点型>>> import tensorflow as tf
>>> a = tf.constant([[1,5,3],[4,2,6]])
>>> a
<tf.Tensor: id=120, shape=(2, 3), dtype=int32, numpy=
array([[1, 5, 3],
[4, 2, 6]])>
>>> tf.reduce_mean(a,axis=0) # 这里有所不对,因为a张量是32位整型,所以求出的均值也是32位整型,不能显示小数
<tf.Tensor: id=128, shape=(3,), dtype=int32, numpy=array([2, 3, 4])>
>>> a = tf.constant([[1.,5.,3.],[4.,2.,6.]])
>>> tf.reduce_mean(a,axis=0)
<tf.Tensor: id=131, shape=(3,), dtype=float32, numpy=array([2.5, 3.5, 4.5], dtype=float32)>
>>> a = tf.constant([[1,5,3],[4,2,6]])
>>> tf.reduce_mean(tf.cast(a,tf.float32),axis=0)
<tf.Tensor: id=135, shape=(3,), dtype=float32, numpy=array([2.5, 3.5, 4.5], dtype=float32)>
>>> import tensorflow as tf
>>> a = tf.constant([[1,5,3],[4,2,6]])
>>> tf.reduce_max(a,axis=0)
<tf.Tensor: id=138, shape=(3,), dtype=int32, numpy=array([4, 5, 6])>
>>> tf.reduce_max(a,axis=1)
<tf.Tensor: id=140, shape=(2,), dtype=int32, numpy=array([5, 6])>
>>> tf.reduce_max(a)
<tf.Tensor: id=142, shape=(), dtype=int32, numpy=6>
>>> import tensorflow as tf
>>> a = tf.constant([[1,5,3],[4,2,6]])
>>> tf.argmax(a,axis=0)
<tf.Tensor: id=144, shape=(3,), dtype=int64, numpy=array([1, 0, 1], dtype=int64)>
>>> tf.argmax(a,axis=1)
<tf.Tensor: id=146, shape=(2,), dtype=int64, numpy=array([1, 2], dtype=int64)>
>>> tf.argmax(a)
<tf.Tensor: id=148, shape=(3,), dtype=int64, numpy=array([1, 0, 1], dtype=int64)>
>>> import tensorflow as tf
>>> print(tf.__version__)
2.0.0
>>> gpus = tf.config.experimental.list_physical_devices(device_type='GPU')
>>> cpus = tf.config.experimental.list_physical_devices(device_type='CPU')
>>> print(gpus)
[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]
>>> print(cpus)
[PhysicalDevice(name='/physical_device:CPU:0', device_type='CPU')]
>>> with tf.device('/cpu:0'):
... cpu_a = tf.random.normal([10000,1000])
... cpu_b = tf.random.normal([1000,2000])
... cpu_c = tf.matmul(cpu_a,cpu_b)
...
>>> print("cpu_a:",cpu_a.device)
cpu_a: /job:localhost/replica:0/task:0/device:CPU:0
>>> print("cpu_b:",cpu_b.device)
cpu_b: /job:localhost/replica:0/task:0/device:CPU:0
>>> print("cpu_c:",cpu_c.device)
cpu_c: /job:localhost/replica:0/task:0/device:CPU:0
>>> tf.test.is_gpu_available()
True
>>> with tf.device('/gpu:0'):
... gpu_a = tf.random.normal([10000,1000])
... gpu_b = tf.random.normal([1000,2000])
... gpu_c = tf.matmul(gpu_a,gpu_b)
...
>>> print("gpu_a:",gpu_a.device)
gpu_a: /job:localhost/replica:0/task:0/device:GPU:0
>>> print("gpu_b:",gpu_b.device)
gpu_b: /job:localhost/replica:0/task:0/device:GPU:0
>>> print("gpu_c:",gpu_c.device)
gpu_c: /job:localhost/replica:0/task:0/device:GPU:0
下面给出上述所有的代码:
# 1 导入Tensroflow,查看版本
import tensorflow as tf
print(tf.__version__)
# 2 查看当前主机上得运算设备
gpus = tf.config.experimental.list_physical_devices(device_type='GPU')
cpus = tf.config.experimental.list_physical_devices(device_type='CPU')
print(gpus)
print(cpus)
# 3 指定在CPU上执行
with tf.device('/cpu:0'):
cpu_a = tf.random.normal([10000,1000])
cpu_b = tf.random.normal([1000,2000])
cpu_c = tf.matmul(cpu_a,cpu_b)
print("cpu_a:",cpu_a.device)
print("cpu_b:",cpu_b.device)
print("cpu_c:",cpu_c.device)
# 4 指定在GPU上执行
# 4.1 查看GPU是否可用
tf.test.is_gpu_available()
# 4.2 指定在GPU上执行随机数操作
with tf.device('/gpu:0'):
gpu_a = tf.random.normal([10000,1000])
gpu_b = tf.random.normal([1000,2000])
gpu_c = tf.matmul(gpu_a,gpu_b)
print("gpu_a:",gpu_a.device)
print("gpu_b:",gpu_b.device)
print("gpu_c:",gpu_c.device)
# 1 导入Tensroflow,查看版本
import tensorflow as tf
# 5 创建函数cpu_run()和gpu_run()
# 函数cpu_run()
def cpu_run():
with tf.device('/cpu:0'):
cpu_a = tf.random.normal([10000,1000])
cpu_b = tf.random.normal([1000,2000])
c = tf.matmul(cpu_a,cpu_b)
return c
# 函数gpu_run()
def gpu_run():
with tf.device('/gpu:0'):
gpu_a = tf.random.normal([10000,1000])
gpu_b = tf.random.normal([1000,2000])
c = tf.matmul(gpu_a,gpu_b)
return c
# 1 导入Tensroflow,查看版本
import tensorflow as tf
# 动态分配显存
gpus = tf.config.experimental.list_physical_devices(device_type='GPU')
tf.config.experimental.set_memory_growth(gpus[0], True)
# 5 创建函数cpu_run()和gpu_run()
# 函数cpu_run()
def cpu_run():
with tf.device('/cpu:0'):
cpu_a = tf.random.normal([10000,1000])
cpu_b = tf.random.normal([1000,2000])
c = tf.matmul(cpu_a,cpu_b)
return c
# 函数gpu_run()
def gpu_run():
with tf.device('/gpu:0'):
gpu_a = tf.random.normal([10000,1000])
gpu_b = tf.random.normal([1000,2000])
c = tf.matmul(gpu_a,gpu_b)
return c
# 6 比较在CPU和GPU上执行乘法操作的时间
# 6.1 导入timeit模块
import timeit
# 6.2 使用timeit工具来统计执行10次的时间
cpu_time = timeit.timeit(cpu_run,number=10)
gpu_time = timeit.timeit(gpu_run,number=10)
print("cpu:",cpu_time," gpu:",gpu_time)
输出结果为:
cpu: 2.2233819 gpu: 0.24505219999999994
修改代码执行100次,输出结果为:
cpu: 17.637937400000002 gpu: 0.2524400999999976
[1] 神经网络与深度学习——TensorFlow实践