Probar BigQuery DataFrames
Usa esta guía de inicio rápido para realizar las siguientes tareas de análisis y aprendizaje automático (AA) mediante la API de BigQuery DataFrames en un notebook de BigQuery:
- Crea un DataFrame sobre el conjunto de datos públicos
bigquery-public-data.ml_datasets.penguins
. - Calcula la masa corporal promedio de un pingüino.
- Crear un modelo de regresión lineal.
- Crea un DataFrame sobre un subconjunto de datos de pingüinos para usarlo como datos de entrenamiento.
- Limpia los datos de entrenamiento.
- Establece los parámetros del modelo.
- Ajusta el modelo.
- Asigna una puntuación al modelo.
Antes de comenzar
- 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.
Verifica que la API de BigQuery esté habilitada.
Si creaste un proyecto nuevo, la API de BigQuery se habilita automáticamente.
- Usuario de BigQuery (
roles/bigquery.user
) - Usuario del entorno de ejecución del notebook (
roles/aiplatform.notebookRuntimeUser
) - Creador de código (
roles/dataform.codeCreator
) - Crea una celda de código nueva en el notebook.
Agrega 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 los pingüinos.Crea una celda de código nueva en el notebook y agrega 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 promedio de los pingüinos y la imprime en laGoogle Cloud consola.
Crea una celda de código nueva en el notebook y agrega 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 BigQuery DataFrames.
- Aprende a visualizar gráficos con BigQuery DataFrames.
- Aprende a usar un notebook de BigQuery DataFrames.
Permisos necesarios
Para crear y ejecutar notebooks, necesitas los siguientes roles de Identity and Access Management (IAM):
Crea un notebook
Sigue las instrucciones en Crea un notebook desde el editor de BigQuery para crear un notebook nuevo.
Probar BigQuery DataFrames
Prueba BigQuery DataFrames mediante estos pasos:
Limpia
La manera más fácil de eliminar la facturación es borrar el proyecto que creaste para el instructivo.
Para borrar el proyecto, sigue estos pasos: