从实践看神经网络拟合任何函数

1 理论

理论部分看 Multilayer Feedforward Networks are
Universal Approximators ,公式比较繁琐,英文看起来晦涩。
总的来说就是,多层神经网络在任意的的隐层节点和专属压缩函数(看做非线性激活函数),能够逼近任意Borel 测量函数.

2 实践

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import keras
from keras.models import Sequential
from keras.layers import Dense,Dropout
from keras.optimizers import RMSprop

np.random.seed(1)
x1 = 2*np.random.normal(size = (1000))
np.random.seed(10)
x2 = np.random.normal(size = (1000))
x = np.array((x1,x2)).T
y = x1**2 + 2*x2**2 -0.2*np.cos(3*np.pi*x1) -0.4*np.cos(4*np.pi*x2)
y = y.reshape(y.shape[0], 1)

def standard(data):
    mu = np.mean(data)
    std = np.std(data)
    return (data - mu)/std
x_scale = standard(x)

model = Sequential()
model.add(Dense(100, activation = 'linear', input_shape = (2,)))
model.add(Dense(50, activation = 'linear'))
model.add(Dense(50, activation = 'linear'))
model.add(Dense(10, activation = 'linear'))
model.add(Dense(1, activation = 'linear'))
model.summary()

model.compile(loss = 'mse', optimizer = RMSprop(),)
model.fit(x_scale, y, batch_size = 64, epochs = 1000, verbose =0 )
y_hap = model.predict(x_scale)
print(np.sum(np.square(y-y_hap)))
plt.plot(np.arange(len(y)),y,'r')
plt.plot(np.arange(len(y_hap)),y_hap,'g')
plt.legend(loc = 'best')
plt.show()

结果: MSE:40648。
从实践看神经网络拟合任何函数_第1张图片

如果采用 sigmoid 作为压缩函数:

model = Sequential()
model.add(Dense(20, activation = 'sigmoid', input_shape = (2,)))
#model.add(Dropout(0.2))
model.add(Dense(20, activation = 'sigmoid'))
#model.add(Dropout(0.2))
model.add(Dense(1, activation = 'linear'))
model.summary()

结果:
mse:188
从实践看神经网络拟合任何函数_第2张图片

即使只使用一个非线性激活函数 relu,也有不错效果:

model = Sequential()
model.add(Dense(100, activation = 'linear', input_shape = (2,)))
model.add(Dense(50, activation = 'linear'))
model.add(Dense(50, activation = 'linear'))
model.add(Dense(10, activation = 'relu'))
model.add(Dense(1, activation = 'linear'))
model.summary()

结果:
mse:468
从实践看神经网络拟合任何函数_第3张图片


参考:
1 知乎问题 神经网络为什么可以(理论上)拟合任何函数?;
2 知乎 神经网络的激活函数都采用非线性函数,如阈值型或S型,为何不采用线性激活函数呢?

你可能感兴趣的:(深度学习,神经网络)