精華區beta NTUCH-HW 關於我們 聯絡資訊
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt x_data=np.linspace(-0.5,0.5,200)[:,np.newaxis] noise=np.random.normal(0,0.02,x_data.shape) y_data=np.square(x_data)+noise x=tf.placeholder(tf.float32,[None,1]) y=tf.placeholder(tf.float32,[None,1]) wei1=tf.Variable(tf.random_normal([1,10])) bias1=tf.Variable(tf.zeros([1,10])) wx1=tf.matmul(x,wei1)+bias1 L1=tf.nn.tanh(wx1)#激活函數 wei2=tf.Variable(tf.random_normal([10,1]))#入10出1 bias2=tf.Variable(tf.zeros([1,1])) wx2=tf.matmul(L1,wei2)+bias2 prediction=tf.nn.tanh(wx2) #二次代價 loss=tf.reduce_mean(tf.square(y-prediction)) train_step=tf.train.GradientDescentOptimizer(0.1).minimize(loss) ini=tf.global_variables_initializer() with tf.Session() as sess: sess.run(ini) for _ in range(2000): sess.run(train_step,feed_dict={x:x_data,y:y_data}) pre_value=sess.run(prediction,feed_dict={x:x_data}) plt.figure() plt.scatter(x_data,y_data) plt.plot(x_data,pre_value,'g-',lw=4) plt.show()