Il connettore BigQuery per Apache Spark consente ai data scientist di combinare la potenza del motore SQL scalabile e senza problemi di BigQuery con le funzionalità di machine learning di Apache Spark. In questo tutorial, mostriamo come utilizzare Dataproc, BigQuery e Apache Spark ML per eseguire il machine learning su un set di dati.
Crea un sottoinsieme di dati sulla natalità di BigQuery
In questa sezione crei un set di dati nel tuo progetto, quindi crei una tabella nel set di dati in cui copi un sottoinsieme di dati sul tasso di natalità dal set di dati BigQuery natality disponibile pubblicamente. Più avanti in questo tutorial utilizzerai i dati del sottoinsieme in questa tabella per prevedere il peso alla nascita in funzione dell'età materna, dell'età paterna e delle settimane di gestazione.
Puoi creare il sottoinsieme di dati utilizzando la console Google Cloud o eseguendo uno script Python sulla tua macchina locale.
Console
Crea un set di dati nel tuo progetto.
- Vai all'UI web di BigQuery.
- Nel pannello di navigazione a sinistra, fai clic sul nome del progetto, quindi fai clic su CREA SET DI DATI.
- Nella finestra di dialogo Crea set di dati:
- In ID set di dati, inserisci "natality_regression".
- Per Località dei dati, puoi scegliere una
località
per il set di dati. La posizione del valore predefinito è
US multi-region. Una volta creato un set di dati, la posizione non può essere modificata. - Per Scadenza tabella predefinita, scegli una delle seguenti opzioni:
- Mai (impostazione predefinita): devi eliminare la tabella manualmente.
- Numero di giorni: la tabella verrà eliminata dopo il numero di giorni specificato dalla data di creazione.
- Per Crittografia, scegli una delle seguenti opzioni:
- Google-owned and Google-managed encryption key (valore predefinito).
- Chiave gestita dal cliente: consulta Protezione dei dati con le chiavi Cloud KMS.
- Fai clic su Crea set di dati.
Esegui una query sul set di dati pubblico sulla natalità, quindi salva i risultati della query in una nuova tabella del tuo set di dati.
- Copia e incolla la seguente query nell'Editor query, quindi fai clic su Esegui.
CREATE OR REPLACE TABLE natality_regression.regression_input as SELECT weight_pounds, mother_age, father_age, gestation_weeks, weight_gain_pounds, apgar_5min FROM `bigquery-public-data.samples.natality` WHERE weight_pounds IS NOT NULL AND mother_age IS NOT NULL AND father_age IS NOT NULL AND gestation_weeks IS NOT NULL AND weight_gain_pounds IS NOT NULL AND apgar_5min IS NOT NULL
- Al termine della query (in circa un minuto), i risultati vengono salvati come tabella BigQuery "regression_input" nel set di dati
natality_regressiondel progetto.
- Copia e incolla la seguente query nell'Editor query, quindi fai clic su Esegui.
Python
Prima di provare questo esempio, segui le istruzioni di configurazione di Python nella guida rapida di Dataproc per l'utilizzo delle librerie client. Per saperne di più, consulta la documentazione di riferimento dell'API Dataproc Python.
Per eseguire l'autenticazione in Dataproc, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.
Consulta Configurazione di un ambiente di sviluppo Python per istruzioni sull'installazione di Python e della libreria client Google Cloud per Python (necessaria per eseguire il codice). È consigliabile installare e utilizzare un ambiente virtuale Python.
virtualenvCopia e incolla il codice
natality_tutorial.pyriportato di seguito in una shellpythonsulla tua macchina locale. Premi il tasto<return>nella shell per eseguire il codice per creare un set di dati BigQuery "natality_regression" nel tuo progettoGoogle Cloud predefinito con una tabella "regression_input" compilata con un sottoinsieme dei dati pubblicinatality.Conferma la creazione del set di dati
natality_regressione della tabellaregression_input.
Eseguire una regressione lineare
In questa sezione eseguirai una regressione lineare PySpark inviando
il job al servizio Dataproc utilizzando la console Google Cloud
o eseguendo il comando gcloud da un terminale locale.
Console
Copia e incolla il seguente codice in un nuovo file
natality_sparkml.pysul computer locale."""Run a linear regression using Apache Spark ML. In the following PySpark (Spark Python API) code, we take the following actions: * Load a previously created linear regression (BigQuery) input table into our Cloud Dataproc Spark cluster as an RDD (Resilient Distributed Dataset) * Transform the RDD into a Spark Dataframe * Vectorize the features on which the model will be trained * Compute a linear regression using Spark ML """ from pyspark.context import SparkContext from pyspark.ml.linalg import Vectors from pyspark.ml.regression import LinearRegression from pyspark.sql.session import SparkSession # The imports, above, allow us to access SparkML features specific to linear # regression as well as the Vectors types. # Define a function that collects the features of interest # (mother_age, father_age, and gestation_weeks) into a vector. # Package the vector in a tuple containing the label (`weight_pounds`) for that # row. def vector_from_inputs(r): return (r["weight_pounds"], Vectors.dense(float(r["mother_age"]), float(r["father_age"]), float(r["gestation_weeks"]), float(r["weight_gain_pounds"]), float(r["apgar_5min"]))) sc = SparkContext() spark = SparkSession(sc) # Read the data from BigQuery as a Spark Dataframe. natality_data = spark.read.format("bigquery").option( "table", "natality_regression.regression_input").load() # Create a view so that Spark SQL queries can be run against the data. natality_data.createOrReplaceTempView("natality") # As a precaution, run a query in Spark SQL to ensure no NULL values exist. sql_query = """ SELECT * from natality where weight_pounds is not null and mother_age is not null and father_age is not null and gestation_weeks is not null """ clean_data = spark.sql(sql_query) # Create an input DataFrame for Spark ML using the above function. training_data = clean_data.rdd.map(vector_from_inputs).toDF(["label", "features"]) training_data.cache() # Construct a new LinearRegression object and fit the training data. lr = LinearRegression(maxIter=5, regParam=0.2, solver="normal") model = lr.fit(training_data) # Print the model summary. print("Coefficients:" + str(model.coefficients)) print("Intercept:" + str(model.intercept)) print("R^2:" + str(model.summary.r2)) model.summary.residuals.show()
Copia il file
natality_sparkml.pylocale in un bucket Cloud Storage nel tuo progetto.gcloud storage cp natality_sparkml.py gs://bucket-name
Esegui la regressione dalla pagina Invia un job di Dataproc.
Nel campo File Python principale, inserisci l'URI
gs://del bucket Cloud Storage in cui si trova la tua copia del filenatality_sparkml.py.Seleziona
PySparkcome tipo di job.Inserisci
gs://spark-lib/bigquery/spark-bigquery-latest_2.12.jarnel campo File jar. In questo modo, spark-bigquery-connector è disponibile per l'applicazione PySpark in fase di runtime, consentendole di leggere i dati BigQuery in un DataFrame Spark.Compila i campi ID job, Regione e Cluster.
Fai clic su Invia per eseguire il job sul cluster.
Al termine del job, il riepilogo del modello di output della regressione lineare viene visualizzato nella finestra Dettagli job Dataproc.
gcloud
Copia e incolla il seguente codice in un nuovo file
natality_sparkml.pysul computer locale."""Run a linear regression using Apache Spark ML. In the following PySpark (Spark Python API) code, we take the following actions: * Load a previously created linear regression (BigQuery) input table into our Cloud Dataproc Spark cluster as an RDD (Resilient Distributed Dataset) * Transform the RDD into a Spark Dataframe * Vectorize the features on which the model will be trained * Compute a linear regression using Spark ML """ from pyspark.context import SparkContext from pyspark.ml.linalg import Vectors from pyspark.ml.regression import LinearRegression from pyspark.sql.session import SparkSession # The imports, above, allow us to access SparkML features specific to linear # regression as well as the Vectors types. # Define a function that collects the features of interest # (mother_age, father_age, and gestation_weeks) into a vector. # Package the vector in a tuple containing the label (`weight_pounds`) for that # row. def vector_from_inputs(r): return (r["weight_pounds"], Vectors.dense(float(r["mother_age"]), float(r["father_age"]), float(r["gestation_weeks"]), float(r["weight_gain_pounds"]), float(r["apgar_5min"]))) sc = SparkContext() spark = SparkSession(sc) # Read the data from BigQuery as a Spark Dataframe. natality_data = spark.read.format("bigquery").option( "table", "natality_regression.regression_input").load() # Create a view so that Spark SQL queries can be run against the data. natality_data.createOrReplaceTempView("natality") # As a precaution, run a query in Spark SQL to ensure no NULL values exist. sql_query = """ SELECT * from natality where weight_pounds is not null and mother_age is not null and father_age is not null and gestation_weeks is not null """ clean_data = spark.sql(sql_query) # Create an input DataFrame for Spark ML using the above function. training_data = clean_data.rdd.map(vector_from_inputs).toDF(["label", "features"]) training_data.cache() # Construct a new LinearRegression object and fit the training data. lr = LinearRegression(maxIter=5, regParam=0.2, solver="normal") model = lr.fit(training_data) # Print the model summary. print("Coefficients:" + str(model.coefficients)) print("Intercept:" + str(model.intercept)) print("R^2:" + str(model.summary.r2)) model.summary.residuals.show()
Copia il file
natality_sparkml.pylocale in un bucket Cloud Storage nel tuo progetto.gcloud storage cp natality_sparkml.py gs://bucket-name
Invia il job Pyspark al servizio Dataproc eseguendo il comando
gcloud, mostrato di seguito, da una finestra del terminale sulla tua macchina locale.- Il valore del flag --jars rende disponibile spark-bigquery-connector
al job PySpark in fase di runtime per consentirgli di leggere
i dati BigQuery in un DataFrame Spark.
gcloud dataproc jobs submit pyspark \ gs://your-bucket/natality_sparkml.py \ --cluster=cluster-name \ --region=region \ --jars=gs://spark-lib/bigquery/spark-bigquery-with-dependencies_SCALA_VERSION-CONNECTOR_VERSION.jar
- Il valore del flag --jars rende disponibile spark-bigquery-connector
al job PySpark in fase di runtime per consentirgli di leggere
i dati BigQuery in un DataFrame Spark.
L'output della regressione lineare (riepilogo del modello) viene visualizzato nella finestra del terminale al termine del job.
<<< # Print the model summary. ... print "Coefficients:" + str(model.coefficients) Coefficients:[0.0166657454602,-0.00296751984046,0.235714392936,0.00213002070133,-0.00048577251587] <<< print "Intercept:" + str(model.intercept) Intercept:-2.26130330748 <<< print "R^2:" + str(model.summary.r2) R^2:0.295200579035 <<< model.summary.residuals.show() +--------------------+ | residuals| +--------------------+ | -0.7234737533344147| | -0.985466980630501| | -0.6669710598385468| | 1.4162434829714794| |-0.09373154375186754| |-0.15461747949235072| | 0.32659061654192545| | 1.5053877697929803| | -0.640142797263989| | 1.229530260294963| |-0.03776160295256...| | -0.5160734239126814| | -1.5165972740062887| | 1.3269085258245008| | 1.7604670124710626| | 1.2348130901905972| | 2.318660276655887| | 1.0936947030883175| | 1.0169768511417363| | -1.7744915698181583| +--------------------+ only showing top 20 rows.