1.基本概念
2.Tensorflow结构
3.创建图和启动图
import tensorflow as tf
m1= tf. constant( [ [ 3 , 3 ] ] )
m2= tf. constant( [ [ 2 ] , [ 3 ] ] )
product= tf. matmul( m1, m2)
print ( product)
sess= tf. Session( )
result= sess. run( product)
print ( result)
sess. close
4.创建变量
import tensorflow as tf
x= tf. Variable( [ 1 , 2 ] )
a= tf. constant( [ 3 , 3 ] )
sub= tf. subtract( x, a)
add= tf. add( x, sub)
init= tf. global_variables_initializer( )
with tf. Session( ) as sees:
sees. run( init)
print ( sees. run( sub) )
print ( sees. run( add) )
state= tf. Variable( 0 , name= 'counter' )
new_value= tf. add( state, 1 )
update= tf. assign( state, new_value)
init= tf. global_variables_initializer( )
with tf. Session( ) as sees:
sees. run( init)
sees. run( state)
for _ in range ( 5 ) :
sees. run( update)
print ( sees. run( state) )
5.fetch and feed
import tensorflow as tf
input1= tf. constant( 3.0 )
input2= tf. constant( 2.0 )
input3= tf. constant( 5.0 )
add= tf. add( input2, input3)
mul= tf. multiply( input1, add)
with tf. Session( ) as sess:
result= sess. run( [ add, mul] )
print ( result)
input1= tf. placeholder( tf. float32)
input2= tf. placeholder( tf. float32)
mul= tf. multiply( input1, input2)
with tf. Session( ) as sees:
print ( sees. run( mul, feed_dict= { input1: [ 8.0 ] , input2: [ 2.0 ] } ) )
6.Tensorflow简单例子
import tensorflow as tf
import numpy as np
x_data= np. random. rand( 100 )
y_data= x_data* 0.01 + 0.2
k= tf. Variable( 0 . )
b= tf. Variable( 0 . )
y= k* x_data+ b
loss= tf. reduce_mean( tf. square( y_data- y) )
optimizer= tf. train. GradientDescentOptimizer( 0.2 )
train= optimizer. minimize( loss)
init= tf. global_variables_initializer( )
with tf. Session( ) as sees:
sees. run( init)
for step in range ( 501 ) :
sees. run( train)
if step% 20 == 0 :
print ( step, sees. run( [ k, b] ) )