0

我正在尝试使用库中的 ML 模型SparkTrials优化hyperopt。我在具有 16 个内核的单台机器上运行它,但是当我运行以下将内核数设置为 8 的代码时,我收到一条警告,似乎表明只使用了一个内核。

SparkTrials接受作为参数spark_session,理论上是我设置核心数量的地方。

谁能帮我?

谢谢!

import os, shutil, tempfile
from hyperopt import fmin, tpe, hp, SparkTrials, STATUS_OK
import numpy as np
from sklearn import linear_model, datasets, model_selection
import pyspark
from pyspark.sql import SparkSession

spark = SparkSession.builder.master("local").config('spark.local.dir', './').config("spark.executor.cores", 8).getOrCreate()

def gen_data(bytes):
  """
  Generates train/test data with target total bytes for a random regression problem.
  Returns (X_train, X_test, y_train, y_test).
  """
  n_features = 100
  n_samples = int(1.0 * bytes / (n_features + 1) / 8)
  X, y = datasets.make_regression(n_samples=n_samples, n_features=n_features, random_state=0)
  return model_selection.train_test_split(X, y, test_size=0.2, random_state=1)

def train_and_eval(data, alpha):
  """
  Trains a LASSO model using training data with the input alpha and evaluates it using test data.
  """
  X_train, X_test, y_train, y_test = data  
  model = linear_model.Lasso(alpha=alpha)
  model.fit(X_train, y_train)
  loss = model.score(X_test, y_test)
  return {"loss": loss, "status": STATUS_OK}

def tune_alpha(objective):
  """
  Uses Hyperopt's SparkTrials to tune the input objective, which takes alpha as input and returns loss.
  Returns the best alpha found.
  """
  best = fmin(
    fn=objective,
    space=hp.uniform("alpha", 0.0, 10.0),
    algo=tpe.suggest,
    max_evals=8,
    trials=SparkTrials(parallelism=8,spark_session=spark))
  return best["alpha"]

data_small = gen_data(10 * 1024 * 1024)  # ~10MB

def objective_small(alpha):
  # For small data, you might reference it directly.
  return train_and_eval(data_small, alpha)

tune_alpha(objective_small)

并行度 (8) 大于当前 Spark 任务槽总数 (1)。如果启用了动态分配,您可能会看到分配了更多的执行程序。

4

1 回答 1

3

如果您在集群中: Spark 命名法中的核心与您的 CPU 中的物理核心无关,spark.executor.cores您指定了每个执行程序(您在这里有一个)可以运行的最大线程数(=任务)如果您想增加,则为 8您必须在代码--num-executors的命令行或spark.executor.instances配置属性中使用的执行器数量。

如果您在纱线集群中,我建议尝试类似的配置

spark.conf.set("spark.dynamicAllocation.enabled", "true")
spark.conf.set("spark.executor.cores", 4)
spark.conf.set("spark.dynamicAllocation.minExecutors","2")
spark.conf.set("spark.dynamicAllocation.maxExecutors","10")

请考虑以上选项在本地模式下不可用

本地:在本地模式下,您只有一个执行程序,如果您想更改其工作线程的数量(默认为一个),您必须像这样设置您的主线程local[*]local[16]

于 2020-11-02T14:12:06.943 回答