tensorflow安装教程
基础
import tensorflow as tf
print ( tf. __version__)
print ( tf. test. is_gpu_available( ) )
mammal = tf. Variable( "Elephant" , tf. string)
tf. print ( tf. rank( mammal) )
tf. print ( tf. shape( mammal) )
mystr = tf. Variable( [ "Hello" ] , tf. string)
tf. print ( tf. rank( mystr) )
tf. print ( tf. shape( mystr) )
mymat = tf. Variable( [ [ 7 ] , [ 11 ] ] , tf. int16)
tf. print ( tf. rank( mymat) )
tf. print ( tf. shape( mymat) )
tf. constant( [ 1 , 2 , 3 ] , dtype= tf. int16)
tf. zeros( ( 2 , 2 ) , dtype= tf. int16)
'''张量行列,数据类型,数据元素,
<tf.Tensor: shape=(2, 2), dtype=int16, numpy=
array([[0, 0],
[0, 0]], dtype=int16)>
tf.reduce_sum(a,axis=1) 按照某一列或者某一行进行相加或相减
a.get_shape() 查看维度
tf.reshape(a,(1,4)) 进行维度变换,有2*2变成1*4
b*5+1 数学运算
tf.matmul(a,b)
a[0,0];a[:,0];a[0,:] 进行索引
'''
rank_three_tensor= tf. ones( [ 3 , 4 , 5 ] )
matrix= tf. reshape( rank_three_tensor, [ 6 , 10 ] )
tf. strings. bytes_split( 'hello' )
help ( tf. strings. split)
tf. strings. split( 'hello world' )
tf. strings. to_hash_bucket( [ 'hello' , 'world' ] , num_buckets= 10 )
a= tf. random. uniform( ( 10 , 10 ) )
tf. debugging. assert_equal( x= a. shape, y= ( 10 , 10 ) )
tf. debugging. assert_equal( x= a. shape, y= ( 10 , 20 ) )
import tensorflow as tf
a = tf. random. uniform( shape= ( 10 , 5 ) , minval= 0 , maxval= 10 )
a
'''
<tf.Tensor: shape=(10, 5), dtype=float32, numpy=
array([[9.961878 , 1.8470013 , 3.929838 , 2.2912729 , 1.7339933 ],
[6.4265766 , 9.381182 , 8.765488 , 1.6121304 , 8.999815 ],
[9.099529 , 4.8890615 , 1.3474286 , 8.258262 , 3.9083278 ],
[6.2407184 , 8.197422 , 5.0943146 , 0.28501272, 4.248129 ],
[7.84971 , 4.96622 , 7.757106 , 1.4310932 , 3.4755325 ],
[6.9145956 , 4.892148 , 2.954824 , 8.441023 , 2.7998877 ],
[2.1173346 , 2.9841232 , 7.594227 , 3.4011757 , 5.2331567 ],
[0.66922545, 9.514647 , 8.365441 , 8.474672 , 5.8095217 ],
[1.0047925 , 8.470211 , 2.2050738 , 5.8963385 , 0.50420165],
[6.1093483 , 5.8107843 , 6.2560916 , 1.5023386 , 7.7845097 ]],
dtype=float32)>
'''
a = tf. constant( [ [ 1 , 2 ] , [ 3 , 4 ] ] )
b = tf. constant( [ [ 5 , 6 ] , [ 7 , 8 ] ] )
tf. print ( tf. math. add( a, b) )
tf. print ( tf. math. subtract( a, b) )
tf. print ( tf. math. multiply( a, b) )
tf. print ( tf. math. divide( a, b) )
'''
[[6 8]
[10 12]]
[[-4 -4]
[-4 -4]]
[[5 12]
[21 32]]
[[0.2 0.33333333333333331]
[0.42857142857142855 0.5]]
'''
x = tf. constant( [ 1.8 , 2.2 ] , dtype= tf. float32)
x1 = tf. dtypes. cast( x, tf. int32)
x1
常用层
tf.keras.layers tf.nn 在大多数情况下,可以使用Tensorflow封装的tf.keras.layers构建一些层建模,keras层非常有用 包括Dense,Conv2D,LSTM,BachNormalization,Dropout等。 tf.nn:底层的函数库,tf.keras.layers是基于tf.nn的高度封装。
a = tf. random. nuiform( shape= ( 10 , 100 , 50 ) , minval= - 0.5 , maxval= 0.5 )
x = tf. keras. layers. LSTM( 100 ) ( a)
x = tf. keras. layers. Dense( 10 ) ( x)
x = tf. nn. softmax( x)
三种建模方式
from tensorflow. keras import layers
model = tf. keras. Sequential( )
model. add( layers. Dense( 64 , activation= 'relu' ) )
model. add( layers. Dense( 64 , activation= 'relu' ) )
model. add( layers. Dense( 10 ) )
model = tf. keras. Seqential( [
layers. Dense( 64 , activation= 'relu' , input_shape= ( 32 , ) ) ,
layers. Dense( 64 , activation= 'relu' ) ,
layers. Dense( 10 )
] )
model. compile ( optimizer= tf. keras. optimizers. Adam( 0.01 ) ,
loss= tf. keras. losses. CategoricalCrossentropy( from_logits= True ) ,
metrics= [ 'accuracy' ] )
import numpy as np
data = np. random. random( ( 1000 , 32 ) )
labels = np. random. random( ( 1000 , 10 ) )
model. fit( data, labels, epochs= 10 , batch_size= 32 )
'''
tf.keras.Model.fit(用于训练模型)
- epochs:训练分为几个时期。每一个epoch是对整个输入数据的一次迭代(此操作以较小的批次完成)。
- batch_size:当传递NumPy数据时,模型将数据切成较小的批次,并在训练期间对这些批次进行迭代。该整数指定每个批次的大小。请注意,如果不能将样本总数除以批次大小,则最后一批可能会更小。
- validation_data:在模型训练时,监控在某些验证数据上监视其性能。传递此参数(输入和标签的元组)可以使模型在每个时期结束时以推断模式显示所传递数据的损失和度量。
'''
Functional model(函数模型) 函数式模型是一种创建模型的方法,该模型比tf.keras.Sequential更灵活。函数式模型可以处理具有非线性拓扑的模型,具有共享层的模型以及具有更多个输入或输出的模型等等 深度学习模型通常都是层的有向无环图(DAG)的主要塑像。因此,函数式模型是一种构建层图的方法。
inputs = tf. keras. Input( shape= ( 32 , ) )
x = layers. Dense( 64 , activation= 'relu' ) ( inputs)
x = layers. Dense( 64 , activation= 'relu' ) ( x)
predictions = layers. Dense( 10 ) ( x)
model = tf. keras. Model( inputs= inputs, outputs= predictions)
model. compile ( optimizer= tf. keras. optimizers. RMSprop( 0.001 ) ,
loss= tf. keras. losses. CategoricalCrossentropy( from_logits= True ) ,
metrics= [ 'accuracy' ] )
import numpy as np
data = np. random. random( ( 1000 , 32 ) )
labels = np. random. random( ( 1000 , 10 ) )
model. fit( data, labels, batch_size= 32 , epochs= 5 )
inputs1 = tf. keras. Input( shape= ( 32 , ) )
inputs2 = tf. keras. Input( shape= ( 32 , ) )
x1 = layers. Dense( 64 , activation= 'relu' ) ( inputs1)
x2 = layers. Dense( 64 , activation= 'relu' ) ( inputs2)
x = tf. concat( [ x1, x2] , axis= - 1 )
x = layers. Dense( 64 , activation= 'relu' ) ( x)
predictions = layers. Dense( 10 ) ( x)
model = tf. keras. Model( inputs= [ inputs1, inputs2] , outputs= predictions)
model. compile ( optimizer= tf. keras. optimizers. RMSprop( 0.001 ) ,
loss= tf. keras. losses. CategoricalCrossentropy( from_logits= True ) ,
metrics= [ 'accuracy' ] )
import numpy as np
data1 = np. random. random( ( 1000 , 32 ) )
data2 = np. random. random( ( 1000 , 32 ) )
labels = np. random. random( ( 1000 , 10 ) )
model. fit( ( data1, data2) , labels, batch_size= 32 , epochs= 5 )
Subclassing model(子类化模型) 通过子类化tf.keras.Model和定义自己的前向传播模型来构建完全可定制的模型。 和eager execution模式相辅相成。
from tensorflow. keras import layers
import tensorflow as tf
class MyModel ( tf. keras. Model) :
def __init__ ( self, num_classes= 10 ) :
super ( MyModel, self) . __init__( name= 'my_model' )
self. num_classes = num_classes
self. dense_1 = layers. Dense( 32 , activation= 'relu' )
self. dense_2 = layers. Dense( num_classes)
def call ( self, inputs) :
x = self. dense_1( inputs)
return self. dense_2( x)
model = MyModel( num_classes= 10 )
model. compile ( optimizer= tf. keras. optimizers. RMSprop( 0.001 ) ,
loss= tf. keras. losses. CategoricalCrossentropy( from_logits= True ) ,
metrics= [ 'accuracy' ] )
import numpy as np
data = np. random. random( ( 1000 , 32 ) )
labels = np. random. random( ( 1000 , 10 ) )
model. fit( data, labels, batch_size= 32 , epochs= 5 )