# 用神经网络进行多元非线性函数的拟合

python 专栏收录该内容
43 篇文章 1 订阅
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

train_feature=np.zeros((10000,2))
train_label=np.zeros((10000,1))
x=np.linspace(-np.pi,np.pi,100)
y=np.linspace(-np.pi,np.pi,100)

for i in range(100):
for j in range(100):
train_feature[i*100+j][0]=x[i]
train_feature[i*100+j][1]=y[j]
train_label[i*100+j][0]=-2*np.cos(x[i])*np.sin(y[j])

X, Y = np.meshgrid(x, y)

# 搭建神经网络
# 定义x y
x = tf.placeholder(tf.float32, [None, 2])
y = tf.placeholder(tf.float32, [None, 1])

Weights_L1 = tf.Variable(tf.random_normal([2, 128]))
# 偏置矩阵
biases_L1 = tf.Variable(tf.zeros([1, 128]))
Wx_plus_b_L1 = tf.matmul(x, Weights_L1) + biases_L1
# 激活函数私有tanh
L1 = tf.nn.tanh(Wx_plus_b_L1)

Weights_L2 = tf.Variable(tf.random_normal([128, 128]))
# 偏置矩阵
biases_L2 = tf.Variable(tf.zeros([1, 128]))
Wx_plus_b_L2 = tf.matmul(L1, Weights_L2) + biases_L2
# 激活函数私有tanh
L2 = tf.nn.tanh(Wx_plus_b_L2)

# 定义神经网络输出层
Weights_L3 = tf.Variable(tf.random_normal([128, 1]))
biases_L3 = tf.Variable(tf.zeros([1, 1]))
Wx_plus_b_L3 = tf.matmul(L2, Weights_L3) + biases_L3
prediction = Wx_plus_b_L3

# 代价函数
loss = tf.reduce_mean(tf.square(y - prediction))

train_step = tf.train.MomentumOptimizer(0.01, 0.9).minimize(loss)

sess = tf.Session()
sess.run(tf.global_variables_initializer())
print(sess.run(loss, feed_dict={x: train_feature, y: train_label}))
for i in range(10000):
sess.run(train_step, feed_dict={x: train_feature, y: train_label})
if i%100==0:
print(sess.run(loss, feed_dict={x: train_feature, y: train_label}))

print("**********************************************************")
print(sess.run(loss, feed_dict={x: train_feature, y: train_label}))
pred=sess.run(prediction, feed_dict={x: train_feature})
#预测值画图
plt.contourf(X, Y, pred.reshape(100,100),8,cmap=plt.cm.hot)
#理论值画图
plt.contour(X, Y, train_label.reshape(100,100),8,colors='k')
plt.show()
#理论值与预测值的均方误差
print(np.mean(np.square(pred-train_label)))


• 0
点赞
• 0
评论
• 21
收藏
• 一键三连
• 扫一扫，分享海报

01-13

05-13
11-06
02-01 3830
12-31
11-12 2455
©️2021 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客

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