PaddlePaddle实现一个简单的回归模型,用来拟合一个多项式函数
import paddle
import numpy as np
import os
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import warnings
warnings.filterwarnings("ignore")
print(paddle.__version__)
def poly_function(datain):
temp = np.zeros(len(datain))
for i in range(len(datain)):
x = datain[i]
temp[i] = x * x * x * x + 2 * x * x * x - 1 * x * x + 0.5 * x
return temp
data = np.random.uniform(-1, 1, 800)
orderdata = np.sort(data)
label = poly_function(orderdata)
orderdata = orderdata.reshape(800, 1)
label = label.reshape(800, 1)
datas = np.concatenate((orderdata, label), axis=1)
class Regressor(paddle.nn.Layer):
def __init__(self):
super(Regressor, self).__init__()
self.fc = paddle.nn.Linear(1, 20)
self.ac1 = paddle.nn.Sigmoid()
self.fc2 = paddle.nn.Linear(20, 20)
self.ac2 = paddle.nn.LeakyReLU()
self.fc3 = paddle.nn.Linear(20, 1)
def forward(self, inputs):
x = self.fc(inputs)
x = self.ac1(x)
x = self.fc2(x)
x = self.ac2(x)
pred = self.fc3(x)
return pred
train_nums = []
loss_seq = []
import paddle.nn.functional as F
def train(model):
model.train()
BATCH_SIZE = 40
EPOCH_NUM = 1000
train_num = 0
optimizer = paddle.optimizer.Adam(learning_rate=0.0002, parameters=model.parameters())
for epoch_id in range(EPOCH_NUM):
np.random.shuffle(datas)
mini_batches = [datas[k: k + BATCH_SIZE] for k in range(0, len(datas), BATCH_SIZE)]
for batch_id, data in enumerate(mini_batches):
features_np = np.array(datas[:, 0], np.float32).reshape(800, 1)
labels_np = np.array(datas[:, 1], np.float32).reshape(800, 1)
features = paddle.to_tensor(features_np)
labels = paddle.to_tensor(labels_np)
y_pred = model(features)
loss = F.mse_loss(y_pred, label=labels)
loss_np = loss.detach().numpy()
loss.backward()
optimizer.step()
optimizer.clear_grad()
if batch_id % 30 == 0 and epoch_id % 50 == 0:
print("Pass:%d,Cost:%0.5f" % (epoch_id, loss_np))
train_num = train_num + BATCH_SIZE
train_nums.append(train_num)
loss_seq.append(loss_np)
model = Regressor()
train(model)
test_data = np.random.uniform(-1, 1, 200)
test_data = np.sort(test_data)
def test(data, model):
datanp = np.array(data, np.float32).reshape(len(data), 1)
features = paddle.to_tensor(datanp)
pred = model(features)
return pred
def showresult(test_data):
test_label = poly_function(test_data)
pred = test(test_data, model)
plt.clf()
plt.plot(test_data, test_label, color='red', label='ground truth')
plt.plot(test_data, pred.detach().numpy(), color='blue', label='predict')
plt.legend()
plt.savefig('result')
plt.show()
if __name__ == '__main__':
showresult(test_data)
|