利用tensorflow构建一个简单的神经网络计算函数参数值

#coding:utf-8
import tensorflow as tf
import numpy as np
BATCH_SZIE=8
SEED=23455
X=np.random.RandomState(SEED).rand(32,2)
Y_=[[2*x1+9*x2+(np.random.RandomState(SEED).rand()/10.0-0.05)] for x1 ,x2 in X]

#定义神经网络的输入、参数和输出,定义前向传播过程
x=tf.placeholder(tf.float32,shape=(None,2))
y_=tf.placeholder(tf.float32,shape=(None,1))
w1=tf.Variable(tf.random_normal([2,1],stddev=1,seed=1))
y=tf.matmul(x,w1)
#定义神经网络的损失函数和反向传播算法
loss_mce=tf.reduce_mean(tf.square(y_-y))
train_step=tf.train.GradientDescentOptimizer(0.001).minimize(loss_mce)
#生成会话
with tf.Session() as sess:
    init_top=tf.global_variables_initializer()
    sess.run(init_top)
    STEPS=20000
    for i in range(STEPS):
        start=(i*BATCH_SZIE)%32
        end=(i*BATCH_SZIE )%32 +BATCH_SZIE
        sess.run(train_step,feed_dict={x:X[start:end],y_:Y_[start:end]})
        if i %500 ==0:
            print('After %d training steps , w1 is :'%i)
            print(sess.run(w1))
    print('Finall w1 is \n ', sess.run(w1))

你可能感兴趣的:(python)