如何在 Spark 上使用 Azure Machine Learning Notebook
重要
AKS 上的 Azure HDInsight 於 2025 年 1 月 31 日淘汰。 透過此公告 深入瞭解。
您必須將工作負載移轉至 Microsoft Fabric 或對等 Azure 產品,以避免突然終止工作負載。
重要
這項功能目前為預覽狀態。 Microsoft Azure 預覽版的補充使用規定 包含適用於 Beta 版、預覽版或尚未正式發行之 Azure 功能的更合法條款。 如需此特定預覽的相關資訊,請參閱 Azure HDInsight 在 AKS 預覽上的資訊。 如需問題或功能建議,請在 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'}))