tensorflow1.4.0基本概念

最后发布时间:2020-12-11 13:05:49 浏览量:

实现y = x *2 - 1

图片alt

import tensorflow as tf
import numpy as np
print(tf.__version__) # 1.4.0
print(np.__version__) # 1.19.4

# create data
x_data = np.linspace(-1,1,5).astype(np.float32)
y_data = x_data*2-1

# crate tenaorflow structure
Weights = tf.Variable(tf.random_uniform([1],-1.0,1.0))
biases = tf.Variable(tf.zeros([1]))
y = x_data*Weights+biases

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

sess = tf.Session()
init = tf.initialize_all_variables();
sess.run(init)
for step in range(50):
    sess.run(train)
    if step % 10 ==0:
        print("loss=",sess.run(loss),
              " Weights=", step,sess.run(Weights),
              " biases=", sess.run(biases))

Session 使用

matrix1 = tf.constant([[3,3]]) # 1行两列 常量
matrix2 = tf.constant([[2],
                       [2]])
product = tf.matmul(matrix1,matrix2) # matrix multiply np.dot(m1,m2)

with tf.Session() as sess:
    result = sess.run(product)
    print(result)

Variable

state = tf.Variable(0,name="counter")
# print(state.name)
one = tf.constant(1)

new_value = tf.add(state ,one)

update = tf.assign(state,new_value)

init = tf.initialize_all_variables() # 初始化所有变量

with tf.Session() as sess:
    sess.run(init)
    for _ in range(3):
        print(sess.run(update))
        print(sess.run(state))

placeholder

input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)

output = tf.multiply(input1, input2)

with tf.Session() as sess:
    print(sess.run(output,feed_dict={input1:[7.,8], input2:[2.]}))

activation function

y = Wx
y = AF(Wx)

图片alt

图片alt