如何在 Spark 上使用 Azure 机器学习笔记本
重要
AKS 上的 Azure HDInsight 已于 2025 年 1 月 31 日停用。 了解更多信息,查看此公告。
需要将工作负荷迁移到 Microsoft Fabric 或等效的 Azure 产品,以避免工作负荷突然终止。
重要
此功能目前以预览版提供。 Microsoft Azure 预览版的补充使用条款 包含适用于 beta 版、预览版或尚未正式发布的 Azure 功能的更多法律条款。 有关此特定预览的信息,请参阅 AKS 上的 Azure HDInsight 预览信息。 有关问题或功能建议,请在 AskHDInsight 上提交请求,提供详细信息,并关注我们以获取 Azure HDInsight 社区 的更多更新。
机器学习是一项不断增长的技术,使计算机能够从过去的数据中自动学习。 机器学习使用各种算法来生成数学模型,并使预测使用历史数据或信息。 我们定义了一些参数的模型,学习是执行计算机程序,以使用训练数据或体验优化模型的参数。 该模型可能是预测,以便将来进行预测,或描述性地从数据中获取知识。
以下教程笔记本演示了在表格数据上训练机器学习模型的示例。 你可以导入此笔记本并自行运行。
将 CSV 上传到存储
在门户 JSON 视图中查找存储和容器名称
导航到主 HDI 存储>容器>基文件夹,> 上传 CSV
登录到群集并打开 Jupyter Notebook
导入 Spark MLlib 库以创建管道
import pyspark from pyspark.ml import Pipeline, PipelineModel from pyspark.ml.classification import LogisticRegression from pyspark.ml.feature import VectorAssembler, StringIndexer, IndexToString
将 CSV 读入 Spark 数据帧
df = spark.read.("abfss:///iris_csv.csv",inferSchema=True,header=True)
拆分用于训练和测试的数据
iris_train, iris_test = df.randomSplit([0.7, 0.3], seed=123)
创建管道并训练模型
assembler = VectorAssembler(inputCols=['sepallength', 'sepalwidth', 'petallength', 'petalwidth'],outputCol="features",handleInvalid="skip") indexer = StringIndexer(inputCol="class", outputCol="classIndex", handleInvalid="skip") classifier = LogisticRegression(featuresCol="features", labelCol="classIndex", maxIter=10, regParam=0.01) pipeline = Pipeline(stages=[assembler,indexer,classifier]) model = pipeline.fit(iris_train) # Create a test `dataframe` with predictions from the trained model test_model = model.transform(iris_test) # Taking an output from the test dataframe with predictions test_model.take(1)
评估模型准确性
import pyspark.ml.evaluation as ev evaluator = ev.MulticlassClassificationEvaluator(labelCol='classIndex') print(evaluator.evaluate(test_model,{evaluator.metricName: 'accuracy'}))