Logistic Regression 模型训练
在为数据创建标签和特征之后,您已经可以开始构建能够从数据中学习的模型(训练)。但在训练之前,在本练习的最后一部分,您将把数据划分为训练集和测试集,在训练集上运行 Logistic Regression 模型,并最终检查基于训练集训练得到的模型在测试集上的准确率。
请记住,您的工作区中已提供 SparkContext sc,以及变量 samples。
本练习是课程的一部分
使用 PySpark 的大数据基础
练习说明
- 按 80:20 的比例将合并后的数据划分为训练集和测试集。
- 使用训练集训练 Logistic Regression 模型。
- 使用训练好的模型在测试集上生成预测标签。
- 使用
zip函数将测试集中的真实标签与预测结果的标签配对组合。 - 使用原始标签与预测标签计算模型的准确率,并打印结果。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Split the data into training and testing
train_samples,test_samples = samples.____([0.8, 0.2])
# Train the model
model = LogisticRegressionWithLBFGS.train(____)
# Create a prediction label from the test data
predictions = model.____(test_samples.map(lambda x: x.features))
# Combine original labels with the predicted labels
labels_and_preds = test_samples.map(lambda x: x.label).zip(____)
# Check the accuracy of the model on the test data
accuracy = labels_and_preds.filter(lambda x: x[0] == x[____]).count() / float(test_samples.count())
print("Model accuracy : {:.2f}".format(____))