在python中, 采用基本TensorFlow API实现sin函数拟合,添加正则化项仅用5个或者7个样本拟合sin函数。给出详细的代码
时间: 2024-05-12 16:16:11 浏览: 69
以下是使用基本TensorFlow API拟合sin函数并添加正则化项的代码示例:
```python
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# 设置训练数据和样本数量
x_train = np.linspace(-1,1,5)[:,np.newaxis]
y_train = np.sin(x_train * np.pi)
# 定义输入占位符和输出占位符
x_input = tf.placeholder(dtype=tf.float32,shape=[None,1],name='x_input')
y_output = tf.placeholder(dtype=tf.float32,shape=[None,1],name='y_output')
# 定义模型参数
W1 = tf.Variable(tf.random_normal(shape=[1,10]),dtype=tf.float32,name='W1')
b1 = tf.Variable(tf.zeros(shape=[1,10]),dtype=tf.float32,name='b1')
W2 = tf.Variable(tf.random_normal(shape=[10,1]),dtype=tf.float32,name='W2')
b2 = tf.Variable(tf.zeros(shape=[1,1]),dtype=tf.float32,name='b2')
# 构建模型,采用正则化项
h1 = tf.nn.relu(tf.matmul(x_input,W1)+b1)
y_model = tf.matmul(h1,W2)+b2
regularizer = tf.contrib.layers.l2_regularizer(scale=0.1)(W1)
loss = tf.reduce_mean(tf.square(y_output-y_model)) + regularizer
# 采用Adam优化器进行训练
train_op = tf.train.AdamOptimizer(learning_rate=0.01).minimize(loss)
# 开始训练模型
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for epoch in range(1000):
sess.run(train_op,feed_dict={x_input:x_train,y_output:y_train})
if epoch % 100 == 0:
loss_val = sess.run(loss,feed_dict={x_input:x_train,y_output:y_train})
print("Epoch: %s, Loss: %s" % (epoch,loss_val))
# 预测并可视化结果
x_test = np.linspace(-1,1,100)[:,np.newaxis]
y_test = np.sin(x_test * np.pi)
y_pred = sess.run(y_model,feed_dict={x_input:x_test})
plt.plot(x_test,y_pred,label='predict')
plt.plot(x_test,y_test,label='true')
plt.legend()
plt.show()
```
在执行代码时,请确保已安装了必须的Python和TensorFlow库。该代码使用正则化项L2来避免过度拟合,并使用Adam优化器进行训练。最终,您将会得到sin函数的拟合结果图。
阅读全文