python paddle 线性回归
"""
简单线性回归
"""
import paddle.fluid as fluid
import paddle as pdl
import numpy as np
import matplotlib.pyplot as mp
train_data = np.array([[1.0], [2.0], [3.0], [4.0]]).astype("float32")
y_true = np.array([[2.0], [4.0], [6.0], [8.0]]).astype("float32")
x = fluid.layers.data(name="x", shape=[1], dtype="float32")
y = fluid.layers.data(name="y", shape=[1], dtype="float32")
model = fluid.layers.fc(input=x,
size=1,
act=None)
cost = fluid.layers.square_error_cost(input=model,
label=y)
avg_cost = fluid.layers.mean(cost)
optimizer = fluid.optimizer.SGD(learning_rate=0.01)
optimizer.minimize(avg_cost)
place = fluid.CPUPlace()
exe = fluid.Executor(place)
exe.run(fluid.default_startup_program())
costs = []
iters = []
values = []
params = {
"x": train_data, "y": y_true}
for i in range(200):
outs = exe.run(feed=params,
fetch_list=[model, avg_cost.name])
iters.append(i)
costs.append(outs[1][0])
values.append(outs[0][0])
print(i, ":", outs[1][0])
mp.title("Training cost", fontsize=24)
mp.xlabel("iter", fontsize=14)
mp.ylabel("cost", fontsize=14)
mp.plot(iters, costs, color="red", label="Training Costs")
mp.plot(iters, values, color="b", label="Predict Value")
mp.legend()
mp.grid(linestyle=":")
mp.show()
mp.savefig("train.png")