如果把神经网络比作电脑,那么层结构就好比硬件,而网络参数就好比软件;那么由一系列层结构和其内部的函数,构成了函数簇。所谓函数簇,就是一些列的函数,复杂的网络拥有复杂的函数簇,其能表达的信息也相应更多。在1989年,就有人证明过拥有至少一层隐藏层的神经网络可以逼近任何函数,所以,我们也可以将神经网络看成是一个函数逼近器。
现用基于Tensorflow编写一个拟合COS函数的网络,实际上它可以逼近任何函数,不过需要细心的调参和一些适当的训练技巧,本文只是那COS函数举个例子。同时使用mpl库的animation模块绘制逼近过程的动画。具体说明可看代码和注释:
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from matplotlib import animation #超参数 lr = 0.01 step = 5000 x_data = np.linspace(-1,1,300)[:, np.newaxis] #shape = (300,1) noise = np.random.normal(0, 0.05, x_data.shape) y_data = np.square(x_data) - 0.3*np.exp(x_data - 0.5) + np.cos(10*x_data) + noise xs = tf.placeholder(tf.float32, [None, 1]) ys = tf.placeholder(tf.float32, [None, 1]) w1 = tf.Variable(tf.random_normal([1, 30])) b1 = tf.Variable(tf.zeros([1, 30]) + 0.1) z1 = tf.matmul(xs, w1) + b1 out1 = tf.nn.relu(z1) w2 = tf.Variable(tf.random_normal([30,10])) b2 = tf.Variable(tf.zeros([1, 10]) + 0.1) z2 = tf.matmul(out1, w2) + b2 out2 = tf.nn.relu(z2) w3 = tf.Variable(tf.random_normal([10,1])) b3 = tf.Variable(tf.zeros([1, 1]) + 0.1) z3 = tf.matmul(out2, w3) + b3 out3 = z3 #损失函数为MSE,优化算法采用梯度下降法 loss = tf.reduce_mean(tf.reshape(tf.square(ys-out3),[-1]))#tf.reduce_mean 函数用于计算张量tensor沿着指定的数轴(tensor的某一维度)上的的平均值,主要用作降维或者计算tensor(图像)的平均值。 train = tf.train.GradientDescentOptimizer(lr).minimize(loss) init = tf.initialize_all_variables() #init = tf.global_variables_initializer() 这个语句也可以 sess = tf.Session() sess.run(init) #记录结果 tt = [] for i in range(step): loss_value,_ = sess.run([loss, train], feed_dict={xs:x_data, ys:y_data}) if i%50==0: print('loss: ',loss_value) tt.append(sess.run(out3,{xs:x_data})) #可视化训练过程 fig = plt.figure() ax = fig.add_subplot(1,1,1) line, = ax.plot([], [], lw=2) def update(n): xx = np.linspace(-1,1,300) yy = tt[n] line.set_data(xx,yy) return line ax.scatter(x_data, y_data, c="r",s=1) pred = sess.run(out3, feed_dict={xs:x_data}) plt.plot(x_data, pred) anima = animation.FuncAnimation(fig,update,frames=int(step/50),interval=300) #anima.save('dynamic_fitting.gif') plt.show()效果如下所示