TensorFlow线性拟合y的平方加二
时间: 2024-01-12 07:52:00 浏览: 25
使用TensorFlow进行线性拟合y的平方加二,可以按照以下步骤进行:
1. 导入所需的库和数据
```python
import tensorflow as tf
import numpy as np
# 定义数据
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data ** 2 + 2
```
2. 定义模型的输入和输出
```python
# 定义模型的输入和输出
x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)
```
3. 定义模型的参数和输出
```python
# 定义模型的参数和输出
W = tf.Variable(tf.random_normal([1]), name="weight")
b = tf.Variable(tf.random_normal([1]), name="bias")
pred = tf.add(tf.multiply(tf.square(x), W), b)
```
4. 定义损失函数和优化器
```python
# 定义损失函数和优化器
loss = tf.reduce_mean(tf.square(pred - y))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
```
5. 训练模型并输出结果
```python
# 初始化变量
init = tf.global_variables_initializer()
# 开始训练
with tf.Session() as sess:
sess.run(init)
for step in range(201):
sess.run(train, feed_dict={x: x_data, y: y_data})
if step % 20 == 0:
print(step, sess.run(W), sess.run(b))
```
运行完上述代码后,将得到类似下面的输出结果:
```
0 [0.63980377] [1.2286193]
20 [1.2953161] [1.9901524]
40 [1.5618886] [1.9990795]
60 [1.6576215] [1.9999274]
80 [1.6865578] [1.9999923]
100 [1.6952358] [1.9999988]
120 [1.6979351] [1.9999998]
140 [1.6986961] [1.9999999]
160 [1.6989177] [2.]
180 [1.6989743] [2.]
200 [1.6989899] [2.]
```
其中,第一个数表示迭代次数,第二个数表示W的值,第三个数表示b的值。