TF Learning: Tensorflow Basic Case, Classic Case Collection — Implementation based on Python programming code

 

directory

Introduction to using Tensorflow

1. TF: Output a sentence using Tensorflow

2. TF implements addition

3. TF realizes multiplication

4. TF implements computing functions

5. TF: Tensorflow completes a linear function calculation

The basic Tensorflow case

1. TF fits the plane according to 3d data

The classic case of Tensorflow


 

 

 

Tensorflow: An introduction to Tensorflow, installation, and usage

 

Introduction to using Tensorflow

1. TF: Output a sentence using Tensorflow

#TF: Output a sentence using Tensorflow
import tensorflow as tf
import numpy as np

greeting = tf.constant('Hello Google Tensorflow! ')
sess = tf.Session()           Start a session
result = sess.run(greeting)   Execute the greeting calculation module using sessions
print(result) 
sess.close()                  This is an explicit way to close a session
Copy the code

 

2. TF implements addition

Tensors and graphs are implemented in two ways: declare two constants A and b, and define an addition operation. You define a graph, you run it,

# -*- coding: utf-8 -*-

Tensors and graphs are implemented in two ways: declare two constants A and b, and define an addition operation. You define a graph, you run it,
import tensorflow as tf
import os
import numpy as np
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' 

#T1
a=tf.constant([1.0.1.4]) 
b=tf.constant([ 1 , 0 , 0 , 4 ]) 
result=a+b 
sess=tf. Session () 
print (sess.run(result)) 
sess.close
#T2
with  tf.Session()  as  sess:
    a=tf.constant([ 1 , 0 , 1 , 4 ])
    b=tf.constant([ 1 , 0 , 0 , 4 ])
    result=a+b
    print (sess.run(result))


#2 constants and variables
The basic units in TensorFlow are Constant, Variable, and Placeholder. Constants are defined with immutable values and dimensions, while variables are defined with mutable values and immutable dimensions. In neural networks, variables can be used as matrices to store weights and other information, while constants can be used as variables to store hyperparameters or other structural information. Next we define constants and variables separately
# different constants are declared (tf.constant())
a = tf.constant( 2 , tf.int16)  Different integer data is declared
b = tf.constant( 4 , tf.float32)  Different floating-point data is declared
c = tf.constant( 8 , tf.float32)  
# declare different variables (tf.variable ())
d = tf. Variable ( 2 , tf.int16) 
e = tf. Variable ( 4 , tf.float32)  
f = tf. Variable ( 8 , tf.float32)   

g = tf.constant(np.zeros(shape=( 2 , 2 ), dtype=np.float32))# declaration combines TensorFlow with Numpy

h = tf.zeros([ 11 ], tf.int16)  # Produce a matrix of all zeros
i = tf.ones([ 2 , 2 ], tf.float32)  # Generate a matrix of all 1s
j = tf.zeros([ 1000 , 4 , 3 ], tf.float64)  
k = tf. Variable (tf.zeros([ 2 , 2 ], tf.float32))  
l = tf. Variable (tf.zeros([ 5 , 6 , 5 ], tf.float32))

Declare a matrix of variables with 2 rows and 3 columns. The values of the variables are normally distributed with standard deviation of 1 and are randomly generated
w1=tf.Variable(tf.random_normal([2.3],stddev=1,seed=1))
The truncated_normal() function truncates normally distributed random numbers. It only keeps random numbers in the range of [mean-2*stddev,mean+2*stddev]
# Case application: Apply variables to define weight matrices and bias vectors in neural networks
weights = tf.Variable(tf.truncated_normal([256 * 256.10])) 
biases = tf. Variable (tf.zeros([10])) 
print (weights.get_shape().as_list()) 
print (biases.get_shape().as_list())
Copy the code

 

3. TF realizes multiplication

The use of Tensorflow session, defining two matrices, two methods output the product of two matrices

import tensorflow as tf

matrix1 = tf.constant([[3.20]]) 
matrix2 = tf.constant([[6],      
                       [100]])
product = tf.matmul(matrix1, matrix2)  

# method 1, general method
sess = tf.Session()        
result = sess.run(product)
print(result)
sess.close()             

# # method 2
# with tf.Session() as sess: #
# result2 = sess.run(product)
# print(result2)
Copy the code

 

4. TF implements computing functions

TF: Tensorflow defines variables + constants to implement output counting function

The output

Code design

#TF: Tensorflow defines variables + constants for output counting

import tensorflow as tf

state = tf.Variable(0, name='Parameter_name_counter')  
#print(state.name)
one = tf.constant(1)   

new_value = tf.add(state, one)  
update = tf.assign(state, new_value)

init = tf.global_variables_initializer()  

with tf.Session() as sess:  
    sess.run(init)        
    for _ in range(8):
        sess.run(update)
        print(sess.run(state))
Copy the code

 

5. TF: Tensorflow completes a linear function calculation

#TF: Tensorflow performs a linear function calculation
# Idea: TF splics different calculation modules into a flow chart like building blocks, completes a linear function calculation, and executes it in an implicit session.
matrix1 = tf.constant([[3..3.]])           Declare matrix1 to be a 1*2 row vector of TF
matrix2 = tf.constant([[2.], [2.]])          Declare a 2*1 column vector whose matrix2 is TF
product = tf.matmul(matrix1, matrix2)       # Multiply two operators as a new example
linear = tf.add(product, tf.constant(2.0))  # concatenate product with a scalar 2. As the final linear example

Execute linear directly in the session, which is equivalent to splicing all the above separate examples into a flow chart
with tf.Session() as sess:
    result = sess.run(linear)
    print(result)
Copy the code

 

 

The basic Tensorflow case

1. TF fits the plane according to 3d data

The Python program generates some three-dimensional data and then fits it with a plane.

import tensorflow as tf
import numpy as np

Use NumPy to generate phony data, 100 points in total.
x_data = np.float32(np.random.rand(2.100)) # random input
y_data = np.dot([0.100.0.200], x_data) + 0.300

Construct a linear model
# 
b = tf.Variable(tf.zeros([1]))
W = tf.Variable(tf.random_uniform([1.2] -1.0.1.0))
y = tf.matmul(W, x_data) + b

# Minimize variance
loss = tf.reduce_mean(tf.square(y - y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)

Initialize variables
init = tf.initialize_all_variables()

# Start graph
sess = tf.Session()
sess.run(init)

# Fit the plane
for step in xrange(0.201):
    sess.run(train)
    if step % 20= =0:
        print step, sess.run(W), sess.run(b)

W: [[0.100 0.200]], B: [0.300]
Copy the code

 

 

The classic case of Tensorflow

Later updates…