import tensorflow as tf
会话打开
m_1 = tf.constant([[3,2]])
m_2 = tf.constant([[3],
[2]])
pr = tf.matmul(m_1,m_2)
with tf.Session() as s_1:
result = s_1.run(pr)
print(result)
[[13]]
第二种打开方式
s_2 = tf.Session()
result_2 = s_2.run(pr)
print(result_2)
s_2.close()
[[13]]
变量和常量
v_1 = tf.Variable(0,name='counter')
c_1 = tf.constant(1)
v_1.name
new_value = tf.add(v_1 ,c_1)
update = tf.assign(v_1,new_value)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for i in range(3):
sess.run(update)
print(sess.run(v_1))
print(v_1.name)
1
counter_6:0
2
counter_6:0
3
counter_6:0
placeholder
在run时需要传入的数值
holder_1 = tf.placeholder(tf.float32)
holder_2 = tf.placeholder(tf.float32)
result = tf.multiply(holder_1,holder_2)
with tf.Session() as sess:
print(sess.run(result,feed_dict = {holder_1:[8.],holder_2:[10.]}))
[80.]
激活函数
将线性转为非线性
定义一层
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_b = tf.matmul(inputs,Weights) + biases
if activation_function is None:
outputs = Wx_b
else:
outputs = activation_function(Wx_b)
return outputs
搞一个神经网络
import numpy as np
x_data = np.linspace(-1,1,400).reshape(-1,1)
noise = np.random.normal(1,0.05,x_data.shape).astype(np.float32)
y_data = np.square(x_data) + noise
xs = tf.placeholder(tf.float32,[None,1])
ys = tf.placeholder(tf.float32,[None,1])
l1 = add_layer(xs,1,10,activation_function=tf.nn.relu)
pre = add_layer(l1,10,1)
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-pre), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for step in range(2000):
sess.run(train_step,feed_dict = {xs:x_data,ys:y_data})
if step%50 == 0:
print(sess.run(loss,feed_dict = {xs:x_data,ys:y_data}))
ten可视化