Probar BigQuery DataFrames
Usa esta guía de inicio rápido para realizar las siguientes tareas de análisis y aprendizaje automático (ML) con la API BigQuery DataFrames en un notebook de BigQuery:
- Crea un DataFrame a partir del
bigquery-public-data.ml_datasets.penguins
conjunto de datos público. - Calcula la masa corporal media de un pingüino.
- Crea un modelo de regresión lineal.
- Crea un DataFrame con un subconjunto de los datos de pingüinos para usarlo como datos de entrenamiento.
- Limpiar los datos de entrenamiento.
- Define los parámetros del modelo.
- Ajusta el modelo.
- Puntúa el modelo.
Antes de empezar
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator
(
roles/resourcemanager.projectCreator
), which contains theresourcemanager.projects.create
permission. Learn how to grant roles.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator
(
roles/resourcemanager.projectCreator
), which contains theresourcemanager.projects.create
permission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Compruebe que la API de BigQuery esté habilitada.
Si has creado un proyecto, la API de BigQuery se habilita automáticamente.
- Usuario de BigQuery (
roles/bigquery.user
) - Usuario de tiempo de ejecución de cuaderno (
roles/aiplatform.notebookRuntimeUser
) - Code Creator (
roles/dataform.codeCreator
) - Crea una celda de código en el cuaderno.
Añade el siguiente código a la celda de código:
import bigframes.pandas as bpd # Set BigQuery DataFrames options # Note: The project option is not required in all environments. # On BigQuery Studio, the project ID is automatically detected. bpd.options.bigquery.project = your_gcp_project_id # Use "partial" ordering mode to generate more efficient queries, but the # order of the rows in DataFrames may not be deterministic if you have not # explictly sorted it. Some operations that depend on the order, such as # head() will not function until you explictly order the DataFrame. Set the # ordering mode to "strict" (default) for more pandas compatibility. bpd.options.bigquery.ordering_mode = "partial" # Create a DataFrame from a BigQuery table query_or_table = "bigquery-public-data.ml_datasets.penguins" df = bpd.read_gbq(query_or_table) # Efficiently preview the results using the .peek() method. df.peek()
Modifica la línea
bpd.options.bigquery.project = your_gcp_project_id
para especificar el ID de tu proyecto Google Cloud . Por ejemplo,bpd.options.bigquery.project = "myProjectID"
.Ejecuta la celda de código.
El código devuelve un objeto
DataFrame
con datos sobre pingüinos.Crea una celda de código en el cuaderno y añade el siguiente código:
# Use the DataFrame just as you would a pandas DataFrame, but calculations # happen in the BigQuery query engine instead of the local system. average_body_mass = df["body_mass_g"].mean() print(f"average_body_mass: {average_body_mass}")
Ejecuta la celda de código.
El código calcula la masa corporal media de los pingüinos y la imprime en la consolaGoogle Cloud .
Crea una celda de código en el cuaderno y añade el siguiente código:
# Create the Linear Regression model from bigframes.ml.linear_model import LinearRegression # Filter down to the data we want to analyze adelie_data = df[df.species == "Adelie Penguin (Pygoscelis adeliae)"] # Drop the columns we don't care about adelie_data = adelie_data.drop(columns=["species"]) # Drop rows with nulls to get our training data training_data = adelie_data.dropna() # Pick feature columns and label column X = training_data[ [ "island", "culmen_length_mm", "culmen_depth_mm", "flipper_length_mm", "sex", ] ] y = training_data[["body_mass_g"]] model = LinearRegression(fit_intercept=False) model.fit(X, y) model.score(X, y)
Ejecuta la celda de código.
El código devuelve las métricas de evaluación del modelo.
- In the Google Cloud console, go to the Manage resources page.
- In the project list, select the project that you want to delete, and then click Delete.
- In the dialog, type the project ID, and then click Shut down to delete the project.
- Sigue aprendiendo a usar DataFrames de BigQuery.
- Consulta cómo visualizar gráficos con DataFrames de BigQuery.
- Consulta cómo usar un cuaderno de BigQuery DataFrames.
Permisos obligatorios
Para crear y ejecutar cuadernos, necesitas los siguientes roles de Gestión de Identidades y Accesos (IAM):
Crear un cuaderno
Sigue las instrucciones de Crear un cuaderno desde el editor de BigQuery para crear un cuaderno.
Probar BigQuery DataFrames
Prueba BigQuery DataFrames siguiendo estos pasos:
Limpieza
La forma más fácil de evitar que te cobren es eliminar el proyecto que has creado para el tutorial.
Para ello, sigue las instrucciones que aparecen a continuación: