-
Notifications
You must be signed in to change notification settings - Fork 6.7k
Added sample for geospatial classification #7291
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
leahecole
merged 34 commits into
GoogleCloudPlatform:main
from
nikitamaia:geospatial-sandbox
Jan 27, 2022
Merged
Changes from 2 commits
Commits
Show all changes
34 commits
Select commit
Hold shift + click to select a range
8f6f07e
Added sample for geospatial classification
nikitamaia 8ab2d19
Added noxfile
nikitamaia 2279435
added emojis to notebook
nikitamaia 37a7898
Small updates to geospatial sample
nikitamaia 387b7b8
updates to requirements txt
nikitamaia 78638a1
fix minor bugs in notebook
nikitamaia 0d344cf
added requirmenets file
nikitamaia ffbd00d
simplify prediction and data extraction logic
nikitamaia 3e94ff6
update tests
nikitamaia b2b939c
fix linter fail
nikitamaia 964453c
fix linter and header fails
nikitamaia bfbcb6d
auth fix for tests
nikitamaia 0d2696c
add noxfile to serving app
nikitamaia c06e0e4
minor updates based on comments
nikitamaia 105d587
small updates
nikitamaia e1b6061
Merge branch 'main' into geospatial-sandbox
e8a2618
update credentials
nikitamaia 3a9082b
added staging bucket to deploy
nikitamaia 117bbe9
update staging bucket
nikitamaia e0cb2ed
removed serving app noxfile
nikitamaia afcbf5a
clarify use of timestamp in sample
nikitamaia 74b9788
fix permissions error
nikitamaia 9f4dabd
Added project to gcloud build
nikitamaia b0136c1
add GPU support
nikitamaia c4d6f6e
deploy from source code
nikitamaia bd937e5
update READMEs
nikitamaia d487f9a
Merge branch 'main' into geospatial-sandbox
fd947dc
Merge branch 'main' into geospatial-sandbox
3a166e4
added constrants file
nikitamaia 5857fe7
added type hints
nikitamaia b032a5b
fix type hint errors
nikitamaia b0e795d
final updates to notebook
nikitamaia b0dacee
update notebook
nikitamaia e9a8eb9
Merge branch 'main' into geospatial-sandbox
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
1,384 changes: 1,384 additions & 0 deletions
1,384
people-and-planet-ai/geospatial-classification/README.ipynb
Large diffs are not rendered by default.
Oops, something went wrong.
376 changes: 376 additions & 0 deletions
376
people-and-planet-ai/geospatial-classification/e2e_test.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,376 @@ | ||
| # Copyright 2021 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| import logging | ||
| import os | ||
| import platform | ||
| import subprocess | ||
| import time | ||
| import uuid | ||
| import json | ||
| import pandas as pd | ||
| import numpy as np | ||
|
|
||
| from google.cloud import aiplatform | ||
| from google.cloud import storage | ||
| import pytest | ||
| import requests | ||
|
|
||
| import ee | ||
| import google.auth | ||
|
|
||
| credentials, project = google.auth.default() | ||
| ee.Initialize(credentials, project=project) | ||
|
|
||
| PYTHON_VERSION = "".join(platform.python_version_tuple()[0:2]) | ||
|
|
||
| NAME = f"ppai/geospatial-classification-py{PYTHON_VERSION}" | ||
|
|
||
| UUID = uuid.uuid4().hex[0:6] | ||
| PROJECT = os.environ["GOOGLE_CLOUD_PROJECT"] | ||
| REGION = "us-central1" | ||
|
|
||
| TIMEOUT_SEC = 30 * 60 # 30 minutes in seconds | ||
| POLL_INTERVAL_SEC = 60 # 1 minute in seconds | ||
|
|
||
| VERTEX_AI_SUCCESS_STATE = "PIPELINE_STATE_SUCCEEDED" | ||
| VERTEX_AI_FINISHED_STATE = { | ||
| "PIPELINE_STATE_SUCCEEDED", | ||
| "PIPELINE_STATE_FAILED", | ||
| "PIPELINE_STATE_CANCELLED", | ||
| } | ||
|
|
||
| EARTH_ENGINE_SUCCESS_STATE = "SUCCEEDED" | ||
| EARTH_ENGINE_FINISHED_STATE = {"SUCCEEDED"} | ||
|
|
||
| BANDS = [ | ||
|
nikitamaia marked this conversation as resolved.
|
||
| "B1", | ||
| "B2", | ||
| "B3", | ||
| "B4", | ||
| "B5", | ||
| "B6", | ||
| "B7", | ||
| "B8", | ||
| "B8A", | ||
| "B9", | ||
| "B10", | ||
| "B11", | ||
| "B12", | ||
| ] | ||
| LABEL = "label" | ||
|
nikitamaia marked this conversation as resolved.
Outdated
|
||
|
|
||
| logging.getLogger().setLevel(logging.INFO) | ||
|
|
||
|
|
||
| @pytest.fixture(scope="session") | ||
| def bucket_name(): | ||
| storage_client = storage.Client() | ||
|
|
||
| bucket_name = f"{NAME.replace('/', '-')}-{UUID}" | ||
| bucket = storage_client.create_bucket(bucket_name, location=REGION) | ||
|
|
||
| logging.info(f"bucket_name: {bucket_name}") | ||
| yield bucket_name | ||
|
|
||
| bucket.delete(force=True) | ||
|
|
||
|
|
||
| @pytest.fixture(scope="session") | ||
| def test_data(bucket_name): | ||
| label_fc = create_label_fc("labeled_geospatial_data.csv") | ||
|
nikitamaia marked this conversation as resolved.
Outdated
|
||
| label_fc = label_fc.map(format_date) | ||
| data = label_fc.map(get_neighboring_patch).flatten() | ||
| data = data.randomColumn() | ||
| data = data.filter(ee.Filter.gte("random", 0.03)) | ||
|
|
||
| training_task = ee.batch.Export.table.toCloudStorage( | ||
| collection=data, | ||
| description="Training image export: test", | ||
| bucket=bucket_name, | ||
| fileNamePrefix="geospatial_training", | ||
| selectors=BANDS + [LABEL], | ||
| fileFormat="TFRecord", | ||
| ) | ||
|
|
||
| training_task.start() | ||
|
|
||
| validation_task = ee.batch.Export.table.toCloudStorage( | ||
| collection=data, | ||
| description="Validation image export: test", | ||
| bucket=bucket_name, | ||
| fileNamePrefix="geospatial_validation", | ||
| selectors=BANDS + [LABEL], | ||
| fileFormat="TFRecord", | ||
| ) | ||
|
|
||
| validation_task.start() | ||
|
|
||
| train_status = None | ||
| val_status = None | ||
|
|
||
| logging.info("Waiting for data export to complete.") | ||
| for _ in range(0, TIMEOUT_SEC, POLL_INTERVAL_SEC): | ||
| train_status = ee.data.getOperation(training_task.name)["metadata"]["state"] | ||
|
nikitamaia marked this conversation as resolved.
|
||
| val_status = ee.data.getOperation(validation_task.name)["metadata"]["state"] | ||
| if train_status and val_status in EARTH_ENGINE_FINISHED_STATE: | ||
| break | ||
| time.sleep(POLL_INTERVAL_SEC) | ||
|
|
||
| assert train_status == EARTH_ENGINE_SUCCESS_STATE | ||
| assert val_status == EARTH_ENGINE_SUCCESS_STATE | ||
| logging.info(f"Export finished with status {train_status}") | ||
|
|
||
| yield training_task.name | ||
|
|
||
|
|
||
| def create_label_fc(path): | ||
| """Creates a FeatureCollection from the label dataframe.""" | ||
|
|
||
| dataframe = pd.read_csv(path) | ||
| num_examples = dataframe.shape[0] | ||
|
nikitamaia marked this conversation as resolved.
Outdated
|
||
| data_dict = dataframe.to_dict() | ||
| feats = [] | ||
| properties = ["timestamp", "label"] | ||
| for idx in np.arange(num_examples): | ||
| feat_dict = {} | ||
| geometry = ee.Geometry.Point([data_dict["lon"][idx], data_dict["lat"][idx]]) | ||
| for feature in properties: | ||
| feat_dict[feature] = data_dict[feature][idx] | ||
| feat = ee.Feature(geometry, feat_dict) | ||
| feats.append(feat) | ||
|
nikitamaia marked this conversation as resolved.
Outdated
|
||
| return ee.FeatureCollection(feats) | ||
|
|
||
|
|
||
| def format_date(feature): | ||
|
nikitamaia marked this conversation as resolved.
Outdated
|
||
| """Creates start date and end date properties.""" | ||
|
|
||
| # Extract start and end dates | ||
| timestamp = ee.String(feature.get("timestamp")).split(" ").get(0) | ||
| year = ee.Number.parse(ee.String(timestamp).split("-").get(0)) | ||
| month = ee.Number.parse(ee.String(timestamp).split("-").get(1)) | ||
| day = ee.Number.parse(ee.String(timestamp).split("-").get(2)) | ||
| start = ee.Date.fromYMD(year, month, day) | ||
| end = start.advance(1, "day") | ||
|
|
||
| # Create new feature | ||
| feature = feature.set({"start": start, "end": end}) | ||
|
|
||
| return feature | ||
|
|
||
|
|
||
| def get_neighboring_patch(feature): | ||
| """Gets image pixel values for patch.""" | ||
|
|
||
| # filter ImageCollection at start/end dates. | ||
| image = ( | ||
| ee.ImageCollection("COPERNICUS/S2") | ||
| .filterDate(feature.get("start"), feature.get("end")) | ||
| .select(BANDS) | ||
| .median() | ||
|
nikitamaia marked this conversation as resolved.
Outdated
|
||
| ) | ||
|
|
||
| # extract pixel values at the lat/lon with a 16x16 padding | ||
| return ee.FeatureCollection( | ||
|
nikitamaia marked this conversation as resolved.
Outdated
|
||
| [ | ||
| image.neighborhoodToArray(ee.Kernel.square(16)) | ||
| .sampleRegions(collection=ee.FeatureCollection([feature]), scale=10) | ||
| .first() | ||
| ] | ||
| ) | ||
|
|
||
|
|
||
| @pytest.fixture(scope="session") | ||
| def container_image(): | ||
|
nikitamaia marked this conversation as resolved.
Outdated
|
||
| # https://cloud.google.com/sdk/gcloud/reference/builds/submit | ||
| container_image = f"gcr.io/{PROJECT}/{NAME}:{UUID}" | ||
| subprocess.check_call( | ||
| [ | ||
| "gcloud", | ||
| "builds", | ||
| "submit", | ||
| "serving_app", | ||
| f"--tag={container_image}", | ||
| f"--project={PROJECT}", | ||
| "--machine-type=e2-highcpu-8", | ||
| "--timeout=15m", | ||
| "--quiet", | ||
| ] | ||
| ) | ||
|
|
||
| logging.info(f"container_image: {container_image}") | ||
| yield container_image | ||
|
|
||
| # https://cloud.google.com/sdk/gcloud/reference/container/images/delete | ||
| subprocess.check_call( | ||
| [ | ||
| "gcloud", | ||
| "container", | ||
| "images", | ||
| "delete", | ||
| container_image, | ||
| f"--project={PROJECT}", | ||
| "--force-delete-tags", | ||
| "--quiet", | ||
| ] | ||
| ) | ||
|
|
||
|
|
||
| @pytest.fixture(scope="session") | ||
| def service_url(bucket_name, container_image): | ||
| # https://cloud.google.com/sdk/gcloud/reference/run/deploy | ||
| service_name = f"{NAME.replace('/', '-')}-{UUID}" | ||
| subprocess.check_call( | ||
| [ | ||
| "gcloud", | ||
| "run", | ||
| "deploy", | ||
| service_name, | ||
| f"--image={container_image}", | ||
| "--command=gunicorn", | ||
| "--args=--threads=8,--timeout=0,main:app", | ||
| "--platform=managed", | ||
| f"--project={PROJECT}", | ||
| f"--region={REGION}", | ||
| "--memory=1G", | ||
|
nikitamaia marked this conversation as resolved.
|
||
| f"--set-env-vars=PROJECT={PROJECT}", | ||
| f"--set-env-vars=STORAGE_PATH=gs://{bucket_name}", | ||
| f"--set-env-vars=REGION={REGION}", | ||
| f"--set-env-vars=CONTAINER_IMAGE={container_image}", | ||
|
nikitamaia marked this conversation as resolved.
Outdated
|
||
| "--no-allow-unauthenticated", | ||
| ] | ||
| ) | ||
|
|
||
| # https://cloud.google.com/sdk/gcloud/reference/run/services/describe | ||
| service_url = ( | ||
| subprocess.run( | ||
| [ | ||
| "gcloud", | ||
| "run", | ||
| "services", | ||
| "describe", | ||
| service_name, | ||
| "--platform=managed", | ||
| f"--project={PROJECT}", | ||
| f"--region={REGION}", | ||
| "--format=get(status.url)", | ||
| ], | ||
| capture_output=True, | ||
| ) | ||
| .stdout.decode("utf-8") | ||
| .strip() | ||
| ) | ||
|
|
||
| logging.info(f"service_url: {service_url}") | ||
| yield service_url | ||
|
|
||
| # https://cloud.google.com/sdk/gcloud/reference/run/services/delete | ||
| subprocess.check_call( | ||
| [ | ||
| "gcloud", | ||
| "run", | ||
| "services", | ||
| "delete", | ||
| service_name, | ||
| "--platform=managed", | ||
| f"--project={PROJECT}", | ||
| f"--region={REGION}", | ||
| "--quiet", | ||
| ] | ||
| ) | ||
|
|
||
|
|
||
| @pytest.fixture(scope="session") | ||
| def identity_token(): | ||
| yield ( | ||
| subprocess.run( | ||
| ["gcloud", "auth", "print-identity-token", f"--project={PROJECT}"], | ||
| capture_output=True, | ||
| ) | ||
| .stdout.decode("utf-8") | ||
| .strip() | ||
| ) | ||
|
|
||
|
|
||
| @pytest.fixture(scope="session") | ||
| def train_model(bucket_name): | ||
| aiplatform.init(project=PROJECT, staging_bucket=bucket_name) | ||
| job = aiplatform.CustomTrainingJob( | ||
| display_name="climate_script_colab", | ||
| script_path="task.py", | ||
| container_uri="us-docker.pkg.dev/vertex-ai/training/tf-cpu.2-5:latest", | ||
|
nikitamaia marked this conversation as resolved.
Outdated
|
||
| ) | ||
|
|
||
| model = job.run(args=[f"--bucket={bucket_name}"]) | ||
| resource_name = job.resource_name | ||
| logging.info(f"train_model resource_name: {resource_name}") | ||
|
nikitamaia marked this conversation as resolved.
Outdated
|
||
|
|
||
| # Wait until the model training job finishes. | ||
| status = None | ||
| logging.info("Waiting for model to train.") | ||
| for _ in range(0, TIMEOUT_SEC, POLL_INTERVAL_SEC): | ||
| # https://googleapis.dev/python/aiplatform/latest/aiplatform_v1/job_service.html | ||
| status = job.state.name | ||
| if status in VERTEX_AI_FINISHED_STATE: | ||
| break | ||
| time.sleep(POLL_INTERVAL_SEC) | ||
|
|
||
| logging.info(f"Model job finished with status {status}") | ||
| assert status == VERTEX_AI_SUCCESS_STATE | ||
| yield resource_name | ||
|
|
||
|
|
||
| def get_prediction_data(feature, start, end): | ||
| """Extracts Sentinel image as json at specific lat/lon and timestamp.""" | ||
|
|
||
| image = ( | ||
| ee.ImageCollection("COPERNICUS/S2") | ||
| .filterDate(start, end) | ||
| .select(BANDS) | ||
| .mosaic() | ||
| ) | ||
|
|
||
| fc = ee.FeatureCollection( | ||
|
nikitamaia marked this conversation as resolved.
Outdated
|
||
| [ | ||
| image.neighborhoodToArray(ee.Kernel.square(16)) | ||
| .sampleRegions(collection=ee.FeatureCollection([feature]), scale=10) | ||
| .first() | ||
| ] | ||
| ) | ||
|
|
||
| # download FeatureCollection as JSON | ||
| url = fc.getDownloadURL("geojson") | ||
| bytes = requests.get(url).content | ||
| values = bytes.decode("utf-8") | ||
| json_values = json.loads(values) | ||
| return json_values["features"][0]["properties"] | ||
|
nikitamaia marked this conversation as resolved.
Outdated
|
||
|
|
||
|
|
||
| def test_predict(bucket_name, test_data, train_model, service_url, identity_token): | ||
|
|
||
| # Test point | ||
| plant_location = ee.Feature(ee.Geometry.Point([-84.80529, 39.11613])) | ||
| prediction_data = get_prediction_data(plant_location, "2021-10-01", "2021-10-31") | ||
|
nikitamaia marked this conversation as resolved.
Outdated
|
||
| logging.info(f"plant location: {plant_location})") | ||
|
|
||
| # Make prediction | ||
| response = requests.post( | ||
| url=f"{service_url}/predict", | ||
| headers={"Authorization": f"Bearer {identity_token}"}, | ||
| json={"data": prediction_data, "bucket": bucket_name}, | ||
| ).json() | ||
|
|
||
| # Check that we get non-empty predictions. | ||
| assert "predictions" in response["predictions"] | ||
| assert len(response["predictions"]) > 0 | ||
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.