# 基于tensorflow的一元二次方程回归预测

## 0.检测tensorflow环境

```import tensorflow as tf
hello = tf.constant('hello world')
session = tf.Session()
session.run(hello)```

image.png

## 1.数据准备

image.png

```import numpy as np

X = np.linspace(-1, 1, 300)[:, np.newaxis].astype('float32')
noise = np.random.normal(0, 0.05, X.shape).astype('float32')
y = np.square(X) - 0.5 + noise```

image.png

## 2.搭建神经网络

```import tensorflow as tf

Weights_1 = tf.Variable(tf.random_normal([1, 10]))
biases_1 = tf.Variable(tf.zeros([1, 10]) + 0.1)
Wx_plus_b_1 = tf.matmul(X, Weights_1) + biases_1
outputs_1 = tf.nn.relu(Wx_plus_b_1)
Weights_2 = tf.Variable(tf.random_normal([10, 1]))
biases_2 = tf.Variable(tf.zeros([1, 1]) + 0.1)
Wx_plus_b_2 = tf.matmul(outputs_1, Weights_2) + biases_2
outputs_2 = Wx_plus_b_2
loss = tf.reduce_mean(tf.square(y - outputs_2))
train = optimizer.minimize(loss)```

image.png

image.png

image.png

## 3.变量初始化

```init = tf.global_variables_initializer()
session = tf.Session()
session.run(init)```

image.png

## 4.模型训练

```for step in range(201):
session.run(train)
if step % 20 == 0:
print(step, 'loss:', session.run(loss))```

0 loss: 0.23739298 20 loss: 0.0074774586 40 loss: 0.0032493745 60 loss: 0.0026177235 80 loss: 0.0025075015 100 loss: 0.002472407 120 loss: 0.0024537172 140 loss: 0.002427246 160 loss: 0.002398049 180 loss: 0.002373801 200 loss: 0.002357695

## 5.完整代码

```import numpy as np
import tensorflow as tf

X = np.linspace(-1, 1, 300)[:, np.newaxis].astype('float32')
noise = np.random.normal(0, 0.05, X.shape).astype('float32')
y = np.square(X) - 0.5 + noise

Weights = tf.Variable(tf.random_normal([in_size, out_size]))
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
Wx_plus_b = tf.matmul(inputs, Weights) + biases
if not activation_function:
return Wx_plus_b
else:
return activation_function(Wx_plus_b)

layer_1 = addConnect(X, 1, 10, tf.nn.relu)
loss = tf.reduce_mean(tf.square(y - predict_y))
train = optimizer.minimize(loss)

init = tf.global_variables_initializer()
session = tf.Session()
session.run(init)

for step in range(201):
session.run(train)
if step % 20 == 0:
print(step, 'loss:', session.run(loss))```

0 loss: 0.28191957 20 loss: 0.011470509 40 loss: 0.0044303066 60 loss: 0.003392854 80 loss: 0.0031887146 100 loss: 0.0030761429 120 loss: 0.0029888747 140 loss: 0.0029117232 160 loss: 0.0028402375 180 loss: 0.0027794265 200 loss: 0.0027436544

image.png

120 篇文章26 人订阅

0 条评论

## 相关文章

### skimage与PIL与png

skimage 与 png png 图像 有 png-8，png-24， png-32 之分，后面的数字代表一个 颜色用几位来存储，png-24就是我们常见的 ...

28370

7320

30360

12820

30950

20370

40810

34040