用paddle实现逻辑回归案例
时间: 2024-09-30 16:10:20 浏览: 30
机器学习与深度学习-使用paddle实现随机梯度下降算法SGD对波士顿房价数据进行线性回归和预测.zip
PaddlePaddle,也称为飞桨,是中国阿里云推出的一个开源深度学习框架。下面是一个简单的逻辑回归案例示例,我们将使用PaddlePaddle来构建和训练一个逻辑回归模型:
首先,安装PaddlePaddle库(如果尚未安装):
```bash
pip install paddlepaddle
```
然后,导入必要的模块并准备数据集:
```python
import paddle
from paddle.nn import Linear
from paddle.dataset import classification
# 假设我们有特征x和标签y作为numpy数组
train_dataset = ... # 负责加载训练数据
test_dataset = ... # 负责加载测试数据
# 预处理数据,例如标准化、划分输入和标签
def preprocess(data):
feature, label = data
return paddle.to_tensor(feature), paddle.to_tensor(label)
train_loader = paddle.io.DataLoader(train_dataset, batch_size=32, shuffle=True, collate_fn=preprocess)
test_loader = paddle.io.DataLoader(test_dataset, batch_size=32, collate_fn=preprocess)
```
接下来,定义模型结构:
```python
class LogisticRegression(paddle.nn.Layer):
def __init__(self, input_dim):
super(LogisticRegression, self).__init__()
self.fc = Linear(input_dim, 1) # 输出层,因为是二分类问题所以设置为1个神经元
def forward(self, x):
y_pred = self.fc(x)
return y_pred
model = LogisticRegression(input_dim=x.shape[1])
```
配置优化器和损失函数:
```python
optimizer = paddle.optimizer.SGD(learning_rate=0.01, parameters=model.parameters())
loss_fn = paddle.nn.CrossEntropyLoss()
```
开始训练模型:
```python
num_epochs = 10
for epoch in range(num_epochs):
for i, (data) in enumerate(train_loader()):
x, y = data
y_pred = model(x)
loss = loss_fn(y_pred, y)
# 反向传播和更新权重
loss.backward()
optimizer.step()
optimizer.clear_grad()
print(f"Epoch {epoch+1}/{num_epochs}, Loss: {loss.numpy():.4f}")
```
最后,评估模型在测试集上的性能:
```python
correct = 0
total = 0
with paddle.no_grad():
for data in test_loader():
x, y = data
y_pred = model(x)
predicted_y = paddle.argmax(y_pred, axis=1)
correct += paddle.sum(predicted_y == y).numpy()
total += len(y)
accuracy = correct / total
print(f"Test accuracy: {accuracy * 100:.2f}%")
```
这就是使用PaddlePaddle实现逻辑回归的基本步骤。
阅读全文