计算图概念
TensorFlow在计算前要先定义“结点”。结点是运算的定义,在定义完计算之后才能对定义开始计算
张量定义
张量不是一个具体的数,它保存的是计算时的过程,储存了大小、类别
tf运行开启会话(tf.session):在定义完计算图后,需要通过开启会话分配计算资源
初始化变量:在计算图中定义的所有variable变量在会话中都要进行初始化。可以使用统一初始化方法 tf_global_variables_initializer()初始化所有variable变量
example:
神经网络简述
神经网络输入:特征向量
输入和输出之间:hidden layer(隐藏层)
神经元是最小单元,它有多个输入只有一个输出。从左往右是神经网络前向传播过程。通过tf.matmul计算权重参数
TensorFlow随机生成函数
神经网络正向传播和反向传播训练逻辑
placeholder使用:placeholder是占位符,在计算图中如果直接定义张量消耗的内存资源大,可用占位符在运行到此处时用指定的值替代
example:
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import tensorflow as tf
from numpy.random import RandomState
batch_size=8
if __name__ == "__main__":
#sess=tf.Session()
# a=tf.constant([1,2],name="a")
# b=tf.constant([2,3],name="b")
# result=a+b
# w1=tf.Variable(tf.random_normal([2,3],stddev=1))
# w2=tf.Variable(tf.random_normal([3,1],stddev=1))
# x=tf.constant([[0.7,0.9]])
# a=tf.matmul(x,w1)
# y=tf.matmul(a,w2)
# sess=tf.Session()
# init_op=tf.global_variables_initializer()
# sess.run(init_op)
# print(sess.run(y))
# w1=tf.Variable(tf.random_normal([2,3],stddev=1))
# w2=tf.Variable(tf.random_normal([3,1],stddev=1))
# x=tf.placeholder(tf.float32,shape=(1,2),name='input')#占位,避免每次申请张量占用空间
# a=tf.matmul(x,w1)
# y=tf.matmul(a,w2)
# sess=tf.Session()
# init_ops=tf.global_variables_initializer()
# sess.run(init_ops)
# print(sess.run(y,feed_dict={x:[[0.7,0.9]]}))
# print(y)
w1=tf.Variable(tf.random_normal([2,3],stddev=1))
w2=tf.Variable(tf.random_normal([3,1],stddev=1))
x=tf.placeholder(tf.float32,shape=(None,2),name='x-input')#none动态定义大小
y_=tf.placeholder(tf.float32,shape=(None,1),name='y-input')
a=tf.matmul(x,w1)
y=tf.matmul(a,w2)
y=tf.sigmoid(y)
cross_entropy=-tf.reduce_mean(y_*tf.log(tf.clip_by_value(y,1e-10,1.0))
+(1-y)*tf.log(tf.clip_by_value(1-y,1e-10,1.0)))
lr=0.0001
train_step=tf.train.AdamOptimizer(lr).minimize(cross_entropy)
rdm=RandomState(1)
dataset_size=128
X=rdm.rand(dataset_size,2)
Y=[[int(x1+x2<1)] for (x1,x2) in X]
sess=tf.Session()
init_op=tf.global_variables_initializer()
sess.run(init_op)
print(sess.run(w1))
print(sess.run(w2))
Step=5000
for i in range(Step):
start=(i*batch_size)%dataset_size
end=min(start+batch_size,dataset_size)
sess.run(train_step,feed_dict={x:X[start:end],y_:Y[start:end]})
if i%600==0:
total_loss=sess.run(cross_entropy,feed_dict={x:X,y_:Y})
print("After %d training step,loss is %g" %(i,total_loss))