import tensorflow as tf
import numpy as np
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
#create data
x_data=np.random.rand(100).astype(np.float32)
y_data=x_data*0.1+0.3
### create tensorflow structure start###
Weights=tf.Variable(tf.random.uniform([1],-1.0,1.0)) #初始值为-1到1
biases=tf.Variable(tf.zeros([1])) #初始值为0
y=Weights*x_data+biases
loss=tf.reduce_mean(tf.square(y-y_data))
optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.5)#训练优化器 0.5 表示学习效率
train=optimizer.minimize(loss)# 减少误差
init=tf.initialize_all_variables()
### create tensorflow structure end###
sess=tf.Session()
sess.run(init) #激活
##训练
for step in range(201):
sess.run(train)
if step %20 ==0:
print(step,sess.run(Weights),sess.run(biases))
## session 的使用
matrix1=tf.constant([[3,3]])
matrix2=tf.constant([[2],
[2]])
product=tf.matmul(matrix1,matrix2) #矩阵乘法
#method 1
sess=tf.Session()
result=sess.run(product)
print(result)
sess.close()
#method 2 自动关闭sess
with tf.Session() as sess:
result2=sess.run(product)
print(result2)
### 3.variable
state=tf.Variable(0,name='counter')
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):
sess.run(update)
print(sess.run(state))
### 4.placeholder()
import tensorflow as tf
import numpy as np
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
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.],input2:[2.]})) #使用feed_dict 传入值
###5.激励函数
def add_layer(inputs,in_size,out_size,activation_function=None):
Weights=tf.Variable(tf.random_normal([in_size,out_size]))
biases=tf.Variable(tf.zeros([1,out_size])+0.1)
Wx_plus_b=tf.matmul(inputs,Weights)+biases
if activation_function is None:
outputs=Wx_plus_b
else:
outputs=activation_function(Wx_plus_b)
return outputs