22
 правки
Изменения
→Примеры реализации алгоритмов с использованием Spark MLlib
Рассмотрим удобство использования Apache Spark на примере. Задача нашей модели предугадать захочет ли клиент оформить срочный вклад. Для этого воспользуемся [https://www.kaggle.com/rouseguy/bankbalanced| данными из Machine Learning Repository].
	Напишем нашу модель на Python. Для начала работы с Apache Spark его необходимо установить, выполнив 
 <font color = "orange">'''pip ''' '''install '''</font> pyspark
Считаем данные из нашего файла и выведем информацию о датасете на экран
 <font color = "orange">'''from '''</font> pyspark.sql <font color = "orange">'''import '''</font> SparkSession spark = SparkSession.builder.appName(<font color = "green">'ml-bank'</font>).getOrCreate() df = spark.read.csv(<font color = "green">'bank.csv'</font>, header = <font color = "blue">True</font>, inferSchema = <font color = "blue">True</font>)
 df.printSchema()
Результат:
  |-- deposit: string (nullable = true)
Как видно наши данные состоят из множества столбцов, содержащих числа и строки Для большей информации выведем наши данные с помощью таблицы pandas. Для примера выведем 7 первых значений
 <font color = "orange">'''import '''</font> pandas <font color = "orange">'''as '''</font> pd pd.DataFrame(df.take(<font color = "blue">7</font>), columns=df.columns).transpose()
[[Файл:SparkMLFirstTable.png]]
Нас будут интересовать только численные данные. Для них построим таблицу с основной информацией (количество/ среднее по всей таблице/ среднеквадратичное отклонение / минимальное значение / максимальное значение)
 numeric_features = [t[<font color = "blue">0</font>] <font color = "orange">'''for '''</font> t <font color = "orange">'''in '''</font> df.dtypes <font color = "orange">'''if '''</font> t[<font color = "blue">1</font>] == <font color = "green">'int'</font>]
 df.select(numeric_features).describe().toPandas().transpose()
[[Файл:SparkMLSecondTable.png]]
Оценим корреляцию между оставшимися данными
 <font color = "orange">'''from '''</font> pandas.plotting <font color = "orange">'''import '''</font> scatter_matrix
 numeric_data = df.select(numeric_features).toPandas()
 axs = scatter_matrix(numeric_data, figsize=(<font color = "blue">8</font>, <font color = "blue">8</font>))
 n = len(numeric_data.columns)
 <font color = "orange">'''for '''</font> i <font color = "orange">'''in '''</font> range(n):     v = axs[i, <font color = "blue">0</font>]     v.yaxis.label.set_rotation(<font color = "blue">0</font>)     v.yaxis.label.set_ha(<font color = "green">'right'</font>)
     v.set_yticks(())
     h = axs[n-<font color = "blue">1</font>, i]      h.xaxis.label.set_rotation(<font color = "blue">90</font>)
     h.set_xticks(())
На данных графиках можно увидеть зависимость, к примеру, между возрастом и балансом на карте. Не будем учитывать эти корреляции при построении наших моделей, однако избавимся от дня и месяца рождения, так как эти параметры не влияют на желание клиента оформить быстрый кредит.
 df = df.select(<font color = "green">'age'</font>, <font color = "green">'job'</font>, <font color = "green">'marital'</font>, <font color = "green">'education'</font>, <font color = "green">'default'</font>, <font color = "green">'balance'</font>,     <font color = "green">'housing'</font>, <font color = "green">'loan'</font>, <font color = "green">'contact'</font>, <font color = "green">'duration'</font>, <font color = "green">'campaign'</font>, <font color = "green">'pdays'</font>, <font color = "green">'previous'</font>,   <font color = "green">'poutcome'</font>, <font color = "green">'deposit'</font>)
 cols = df.columns
 categoricalColumns = [<font color = "green">'job'</font>, <font color = "green">'marital'</font>, <font color = "green">'education'</font>, <font color = "green">'default'</font>, <font color = "green">'housing'</font>, <font color = "green">'loan'</font>, <font color = "green">'contact'</font>, <font color = "green">'poutcome'</font>]
 stages = []
 <font color = "orange">'''for '''</font> categoricalCol <font color = "orange">'''in '''</font> categoricalColumns:     stringIndexer = StringIndexer(inputCol = categoricalCol, outputCol =   categoricalCol + <font color = "green">'Index'</font>)     encoder = OneHotEncoder(inputCols=[stringIndexer.getOutputCol()], outputCols=[categoricalCol + <font color = "green">"classVec"</font>])
     stages += [stringIndexer, encoder]
 label_stringIdx = StringIndexer(inputCol = <font color = "green">'deposit'</font>, outputCol = <font color = "green">'label'</font>)
 stages += [label_stringIdx]
 numericCols = [<font color = "green">'age'</font>, <font color = "green">'balance'</font>, <font color = "green">'duration'</font>, <font color = "green">'campaign'</font>, <font color = "green">'pdays'</font>, <font color = "green">'previous'</font>] assemblerInputs = [c + <font color = "green">"classVec" </font> <font color = "orange">'''for '''</font> c <font color = "orange">'''in '''</font> categoricalColumns] + numericCols assembler = VectorAssembler(inputCols=assemblerInputs, outputCol=<font color = "green">"features"</font>)
 stages += [assembler]
 <font color = "orange">'''from '''</font> pyspark.ml <font color = "orange">'''import '''</font> Pipeline
 pipeline = Pipeline(stages = stages)
 pipelineModel = pipeline.fit(df)
 df = pipelineModel.transform(df)
 selectedCols = [<font color = "green">'label'</font>, <font color = "green">'features'</font>] + cols
 df = df.select(selectedCols)
 df.printSchema()
Наконец, поделим нашу выборку на обучающую и тестирующую
 train, test = df.randomSplit([<font color = "blue">0.7</font>, <font color = "blue">0.3</font>], seed = 2018) print(<font color = "Training Dataset Count: blue" + str(train.count())) print("Test Dataset Count: " + str(test.count())>2018</font>)Построим модели и выведем точность(площадь под ROC-кривой) для: 
Logistic Regression
 <font color = "orange">'''from '''</font> pyspark.ml.classification <font color = "orange">'''import '''</font> LogisticRegression lr = LogisticRegression(featuresCol = <font color = "green">'features'</font>, labelCol = <font color = "green">'label'</font>,    maxIter=<font color = "blue">10</font>)
 lrModel = lr.fit(train)
 trainingSummary = lrModel.summary
 Точность: 0.8865478305561797
Binary Classification
 <font color = "orange">'''from '''</font> pyspark.ml.evaluation <font color = "orange">'''import '''</font> BinaryClassificationEvaluator
 evaluator = BinaryClassificationEvaluator()
 print('<font color = "green">"Точность: '"</font>, evaluator.evaluate(predictions))
Decision Tree
 <font color = "orange">'''from '''</font> pyspark.ml.classification <font color = "orange">'''import '''</font> DecisionTreeClassifier dt = DecisionTreeClassifier(featuresCol = <font color = "green">'features'</font>, labelCol = <font color = "green">'label'</font>,    maxDepth = <font color = "blue">3</font>)
 dtModel = dt.fit(train)
 predictions = dtModel.transform(test)
 evaluator = BinaryClassificationEvaluator()
 print(<font color = "green">"Точность: " </font> + str(evaluator.evaluate(predictions, {evaluator.metricName: <font color = "green">"areaUnderROC"</font>})))
Random Forest
 <font color = "orange">'''from '''</font> pyspark.ml.classification <font color = "orange">'''import '''</font> RandomForestClassifier rf = RandomForestClassifier(featuresCol = <font color = "green">'features'</font>, labelCol = "green">'label'</font>)
 rfModel = rf.fit(train)
 predictions = rfModel.transform(test)
 evaluator = BinaryClassificationEvaluator()
 print(<font color = "green">"Точность: " </font> + str(evaluator.evaluate(predictions, {evaluator.metricName: <font color = "green">"areaUnderROC"</font>})))
Gradient-Boosted Tree 
 <font color = "orange">'''from '''</font> pyspark.ml.classification <font color = "orange">'''import '''</font> GBTClassifier gbt = GBTClassifier(maxIter=<font color = "blue">10</font>)
 gbtModel = gbt.fit(train)
 predictions = gbtModel.transform(test)
 evaluator = BinaryClassificationEvaluator()
 print(<font color = "green">"Точность: " </font> + str(evaluator.evaluate(predictions, {evaluator.metricName: <font color = "green">"areaUnderROC"</font>})))
== Практическое применение Big Data ==