构建简单神经网络
import tensorflow as tf
import numpy as np
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data*0.1 + 0.3
'''
机器学习要做的事情就是,让定义的Weight,biases初始值,通过不断学习,接近0.1,0.3这样所设定的值
'''
Weight = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
biases = tf.Variable(tf.zeros([1]))
y = Weight*x_data + biases
loss = tf.reduce_mean(tf.square(y-y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
init = tf.initialize_all_variables()
'''
神经网络就是定义一个图,使得图中的网络动起来
'''
'''sess就像一个指针,指向init中的每一个变量,这样就都被激活了'''
sess = tf.Session()
sess.run(init)
for step in range(201):
sess.run(train)
if step % 20 == 0:
print(step, sess.run(Weight), sess.run(biases))
'''
运行结果:
0 [0.7010317] [-0.00366911]
20 [0.26770934] [0.2167949]
40 [0.14662763] [0.2768668]
60 [0.11296372] [0.29356837]
80 [0.10360426] [0.29821184]
100 [0.10100207] [0.29950285]
120 [0.10027859] [0.2998618]
140 [0.10007747] [0.29996157]
160 [0.10002153] [0.29998934]
180 [0.10000598] [0.29999703]
200 [0.10000164] [0.2999992]
'''
Session 会话控制
'''session 会话控制'''
import numpy as np
import tensorflow as tf
matrix1 = tf.constant([[3, 3]])
matrix2 = tf.constant([[2],
[2]])
product = tf.matmul(matrix1,matrix2)
sess = tf.Session()
result = sess.run(product)
print(result)
sess.close()
with tf.Session() as sess:
print(sess.run(product))
'''
运行结果:
[[12]]
'''
Variable 变量
'''Variable 变量'''
import numpy as np
import tensorflow as tf
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):
sess.run(update)
print(sess.run(state))
'''
运行结果:
1
2
3
总结:
当你定义tf.Variable()时,一定要用init = tf.initialize_all_variables()进行初始化
当定义with tf.Session() as sess:时,一定要用sess.run(init)激活参数
'''
feeds 传入值(placeholder)
'''feeds 传入值'''
import tensorflow as tf
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.]}))
'''
运行结果:
[14.]
总结:
当用了placeholder后,就证明和sess.run(),feed_dict绑定了,只有当feed_dict给它赋值时才改变
'''
激活函数
'''
1.激活函数:就是现实总不会是像我们想像的那么美好,需要激活函数来帮助我们,eg:sigmoid(0,1),relu(大于0时为y=x,小于0为0),tanh(-1,1)
2.激活函数必须时可微的,将误差反向传递时只有这些可微的激活函数才能把误差传递回去
3.当你的神经网络只有两三层时,随便一个激活函数都可以掰弯它,但是当网络层数很深时,就需要慎重考虑了,
因为稍不留神就会导致梯度消失,梯度爆炸等情况。梯度爆炸在图像上是“悬崖式"的,它会导致下一次优化的值在悬崖的延长线上:非常远。
4.在卷积神经网络中推荐使用:relu
5.在循环神经网络中推荐使用:relu 、tanh
6.多标签分类用sigmoid,多类分类用softmax。relu最常用。
'''