paddlepaddle逻辑回归
时间: 2024-01-16 08:17:13 浏览: 154
以下是使用PaddlePaddle实现逻辑回归的示例代码:
```python
import paddle.fluid as fluid
import numpy as np
# 定义训练数据
train_data = np.array([[1.0, 2.0], [5.0, 10.0],10.0, .0], [13.0, 26.0]]).astype('float32')
train_label = np.array([0, 0, 1, 1]).astype('float32')
# 定义输入和标签
x = fluid.layers.data(name='x', shape=[2], dtype='float32')
y = fluid.layers.data(name='y', shape=[1], dtype='float32')
# 定义网络结构
y_predict = fluid.layers.fc(input=x, size=1, act=None)
# 定义损失函数
cost = fluid.layers.sigmoid_cross_entropy_with_logits(y_predict, 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())
# 开始训练
for i in range(1000):
outs = exe.run(
feed={'x': train_data, 'y': train_label},
fetch_list=[avg_cost])
if i % 100 == 0:
print("Iter: {}, Cost: {}".format(i, outs[0]))
# 预测新数据
test_data = np.array([[3.0, 6.0], [15.0, 30.0]]).astype('float32')
results = exe.run(
feed={'x': test_data},
fetch_list=[y_predict])
print("Predictions: ", results[0])
```
以上代码实现了一个简单的二分类逻辑回归模型,使用SGD优化器进行参数优化,训练1000次后输出损失值,并使用训练好的模型对新数据进行预测。
阅读全文