[曲线拟合]使用Tensorflow拟合COS函数

这篇博客通过Tensorflow实现了一个神经网络来拟合COS函数,展示了神经网络如何作为函数逼近器。文章中详细介绍了网络结构、超参数设置,并利用matplotlib的animation模块动态展示逼近过程。通过梯度下降法优化损失函数,逐步调整网络权重,最终得到逼近COS函数的模型。
摘要由CSDN通过智能技术生成

如果把神经网络比作电脑,那么层结构就好比硬件,而网络参数就好比软件;那么由一系列层结构和其内部的函数,构成了函数簇。所谓函数簇,就是一些列的函数,复杂的网络拥有复杂的函数簇,其能表达的信息也相应更多。在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()

效果如下所示
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值