1. Import tensorflow
Import tensorflow as TF
Ii. Define a computing Diagram
(1) constant Initialization
Constant_name = TF. Constant (value)
(2) variable Initialization
Create variable:
Name_variable = TF. Variable (value, name)
Initialization of individual variables:
Init_op = name_variable.initializer ()
Initialize all variables:
Init_op = TF. global_variables_initializer ()
Note: If the variable type is used, an error occurs when no initialization value is performed.
3. Create a session
Creating a computing graph only creates a static computing model and executes a dialog to provide data and obtain results. Sessions have and manage all the resources when tensorflow is running. After all calculations are completed, you need to disable the session to help the system Recycle resources.
Sess = TF. Session () # create a session
Actual Operation:
# Create a session and manage it through the context manager in Python
With TF. Session () as sess:
# Use the created session to calculate the result of interest
Print (sess. Run (result ))
# Disable sessions and release resources when you no longer need to call Functions
Sess. Close ()
Note: If a variable exists, you need to add an init initialization variable to run successfully and call the Run Command of the session to initialize the parameter:
Init = TF. global_variables_initializer ()
Sess. Run (init)
Example: Output 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 through variable assignment
Import tensorflow as tfvalue = TF. Variable (0, name = "value ")
Sum = TF. Variable (0, name = "sum ")
One = TF. Constant (1) new_value = TF. Add (value, one) update_value = TF. Assign (value, new_value) # variable update
New_sum = TF. Add (sum, value)
Update_sum = TF. Assign (sum, new_sum) Init = TF. global_variables_initializer () with TF. Session () as sess:
Sess. Run (init)
For _ in range (10 ):
Sess. Run (update_value)
Sess. Run (update_sum)
Print ("1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 =", end = "")
Print (sess. Run (SUM) ### output ###
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
How to Write a complete basic tensorflow Program