Tensorflow framework to build neural network (2)

Computational graph (Graph): The computational process of building a neural network is a graph that carries one or more computing nodes. It only builds the network and does not operate.

The basic model of a neural network is a neuron, and the basic model of a neuron is actually the multiplication and addition operations in mathematics. We build the following computational graph:


In the above figure, x1, x2 represent the input, w1, w2 are the weights from x1 to y and x2 to y respectively, y=x1*w1+x2*w2.
The above calculation graph is realized by the program code:
 

import tensorflow as tf #Introduce modules
x = tf.constant([[1.0, 2.0]]) #define a two-order tensor equal to [[1.0, 2.0]]
w = tf.constant([[3.0], [4.0]])#Define a two-order tensor equal to [[3.0], [4.0]]
y=tf.matmul(x,w) #implement xw matrix multiplication
print (y) # output the result

Output result:


From the result, y is a tensor, and only the calculation graph that carries the calculation process is built, and there is no operation. If you want to get the operation result, you need to use "Session()".

Session: Execute node operations in the computational graph.

The code is implemented as follows:

import tensorflow as tf #Introduce modules
x = tf.constant([[1.0, 2.0]]) #define a two-order tensor equal to [[1.0, 2.0]]
w = tf.constant([[3.0], [4.0]])#Define a two-order tensor equal to [[3.0], [4.0]]
y=tf.matmul(x,w) #implement xw matrix multiplication
print (y) # output the result
with tf.Session() as sess:
   print (sess.run(y)) #Execute session output results

The results are as follows:


From the results of the second run, only the prompt that y is a tensor is printed before running the Session() session, and the result of y is 1.0*3.0 + 2.0*4.0 = 11.0 printed after running the Session() session. Execute Session() session to get matrix multiplication result.




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324421812&siteId=291194637