在python中,采用基本TensorFlow API实现sin函数拟合,仅用5个或者7个样本拟合sin函数,并且添加正则化项。请给出详细的代码
时间: 2024-05-09 14:16:50 浏览: 85
Sure, here is the example code:
```python
import tensorflow as tf
import numpy as np
# Define the input data
x_train = np.linspace(-1.0, 1.0, num=5)
y_train = np.sin(x_train * np.pi)
# Define the placeholders for input and output
input_x = tf.placeholder(dtype=tf.float32, shape=[None])
output_y = tf.placeholder(dtype=tf.float32, shape=[None])
# Define the model
W = tf.Variable(tf.random_normal(shape=[1], stddev=0.01))
b = tf.Variable(tf.zeros(shape=[1]))
output = tf.add(tf.multiply(W, input_x), b)
# Add regularization to the loss function
l2_loss = tf.reduce_sum(tf.square(W))
loss = tf.reduce_mean(tf.square(output - output_y) + 0.01 * l2_loss)
# Define the optimizer
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
train_op = optimizer.minimize(loss)
# Train the model
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(1000):
_, loss_val = sess.run([train_op, loss], feed_dict={input_x: x_train, output_y: y_train})
if i % 100 == 0:
print(f"Epoch {i}, loss: {loss_val}")
# Predict on new data
x_test = np.linspace(-1.0, 1.0, num=20)
y_test = np.sin(x_test * np.pi)
output_val = sess.run(output, feed_dict={input_x: x_test})
print(f"Test loss: {np.mean(np.square(output_val - y_test))}")
```
This code defines a simple linear regression model using TensorFlow's basic API, with an L2 regularization term added to the loss function. It trains the model on five input-output pairs to fit the sinusoidal function, and then evaluates the performance on a set of test data by calculating the mean squared error. Hope this helps!
阅读全文