如有不对请及时指出,非常感谢!
项目一
基于PaddlePaddle2.0-构建线性回归模型
理论可以看原文,非常详细,而且很细节(太菜了看不懂)
下面对代码解析和白话理解!
import numpy # 导入第三方库
num_inputs=2
num_examples=500
true_w=[1.2,2.5]
true_b=6.8
features = numpy.random.normal(0,1,(num_examples, num_inputs)).astype('float32') # 从正态(高斯)分布中抽取随机样本。
labels = features[:,0]*true_w[0]+features[:,1]*true_w[1]+true_b # 对正态数据进行加权处理
labels = labels + numpy.random.normal(0,0.001,labels.shape[0]) # 添加ε
labels = labels.astype('float32') # 转换数据为float32
labels = numpy.expand_dims(labels,axis=-1) #注意:需要在最后增加一个维度
print(labels.shape)
(500, 1)
print('features大小:', features.shape)
print('features[:,0]小:', features[:,0].shape)
features大小: (500, 2)
features[:,0]小: (500,)
numpy.random.normal
函数
numpy.random.normal(loc=0.0, scale=1.0, size=None)
从正态(高斯)分布中抽取随机样本。
import paddle # 导入第三方库
train_data=paddle.to_tensor(features) # 训练集转换为paddle Tensor
y_true=paddle.to_tensor(labels) # 测试集转换为paddle Tensor
model=paddle.nn.Linear(in_features=2, out_features=1) # 定义线性网络
paddle.nn.Linear(in_features, out_features, weight_attr=None, bias_attr=None, name=None)
:线性变换层-输出 官方文档传送门
# 查看网络
paddle.summary(model, (2,))
---------------------------------------------------------------------------
Layer (type) Input Shape Output Shape Param #
===========================================================================
Linear-1 [[2]] [1] 3
===========================================================================
Total params: 3
Trainable params: 3
Non-trainable params: 0
---------------------------------------------------------------------------
Input size (MB): 0.00
Forward/backward pass size (MB): 0.00
Params size (MB): 0.00
Estimated Total Size (MB): 0.00
---------------------------------------------------------------------------
{'total_params': 3, 'trainable_params': 3}
# 随机梯度下降算法的优化器
sgd_optimizer=paddle.optimizer.SGD(learning_rate=0.001, parameters=model.parameters())
# loss计算
mse_loss=paddle.nn.MSELoss()
for i in range(5000): # 设置500个epoch
y_predict = model(train_data) # 训练集喂进模型
loss=mse_loss(y_predict, y_true) # 计算loss
loss.backward() # 反向传播
# 优化器进行优化
sgd_optimizer.step()
sgd_optimizer.clear_grad()
print(model.weight.numpy()) # 输出w的值
print(model.bias.numpy()) # 输出b的值
print(loss.numpy()) # 输出loss
[[1.1999037]
[2.4999018]]
[6.799708]
[1.0670032e-06]
设定w1 = 1.2 ,w2 = 2.5 ,b = 6.8
实际w1 = 1.99, w2 = 2.499,b = 6.799
效果比较好,拟合程度高
项目二
基于PaddlePaddle2.0-构建softmax分类器
理论可以看原文,非常详细,而且很细节(太菜了看不懂)
下面对代码解析和白话理解!
paddle.vision.datasets.MNIST
MNIST 数据集 官方api传送门
import paddle
train_dataset