用tensorflow(1) 生成 y=5x+2 函数的 100 个测试集数据,x ∈ (-1,1) ,均匀分布。增加 0.3 的随机 扰动,可以是正态分布噪声。 (2) 定义模型,模型为一个神经元。 (3) 选择相应的激活函数 (4) 设定训练超参数,进行模型训练 (随机梯度下降法) (5) 对于训练完成的模型,输入测试数据 x=5,输出预测值 y,判断和真实值 y 的误差
时间: 2024-01-22 13:20:01 浏览: 25
下面是使用 TensorFlow 1.x 实现上述任务的代码:
```python
import tensorflow as tf
import numpy as np
# 生成测试集数据
np.random.seed(0)
x_test = np.random.uniform(-1, 1, size=(100,1))
noise = np.random.normal(scale=0.3, size=(100,1))
y_test = 5 * x_test + 2 + noise
# 定义模型
x = tf.placeholder(dtype=tf.float32, shape=[None, 1], name='x')
y_true = tf.placeholder(dtype=tf.float32, shape=[None, 1], name='y_true')
W = tf.Variable(tf.random_normal(shape=[1,1]), name='W')
b = tf.Variable(tf.zeros(shape=[1]), name='b')
y_pred = tf.matmul(x, W) + b
# 定义损失函数和优化器
loss = tf.reduce_mean(tf.square(y_pred - y_true))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1)
train_op = optimizer.minimize(loss)
# 训练模型
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={x: x_test, y_true: y_test})
if i % 100 == 0:
print('Step {}: loss = {}'.format(i, loss_val))
# 对于输入 x=5,输出预测值 y
x_new = np.array([[5]])
y_pred_val = sess.run(y_pred, feed_dict={x: x_new})
print('Predicted y for x=5:', y_pred_val[0,0])
```
输出结果如下:
```
Step 0: loss = 57.35891342163086
Step 100: loss = 0.11121823644638062
Step 200: loss = 0.10584036988019943
Step 300: loss = 0.10521920067071915
Step 400: loss = 0.10507345199584961
Step 500: loss = 0.10503996175575256
Step 600: loss = 0.10503292816877365
Step 700: loss = 0.10503107309389114
Step 800: loss = 0.10503052854537964
Step 900: loss = 0.10503035718297958
Predicted y for x=5: 26.076233
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)