markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Let’s visualize the results. The script plotcount.py reads in a data file and plots the 10 most frequently occurring words as a text-based bar plot:
run $code/plotcount.py $repo_path/isles.dat ascii
content/posts/makefile-tutorial/makefile_tutorial_0.ipynb
dm-wyncode/zipped-code
mit
plotcount.py can also show the plot graphically
run $code/plotcount.py $repo_path/isles.dat show
content/posts/makefile-tutorial/makefile_tutorial_0.ipynb
dm-wyncode/zipped-code
mit
plotcount.py can also create the plot as an image file (e.g. a PNG file)
run $code/plotcount.py $repo_path/isles.dat $repo_path/isles.png
content/posts/makefile-tutorial/makefile_tutorial_0.ipynb
dm-wyncode/zipped-code
mit
Import the objects necessary to display the generated png file in this notebook.
from IPython.display import Image Image(filename=os.path.join(repo_path, 'isles.png'))
content/posts/makefile-tutorial/makefile_tutorial_0.ipynb
dm-wyncode/zipped-code
mit
Finally, let’s test Zipf’s law for these books The most frequently-occurring word occurs approximately twice as often as the second most frequent word. This is Zipf’s Law.
run $code/zipf_test.py $repo_path/abyss.dat $repo_path/isles.dat
content/posts/makefile-tutorial/makefile_tutorial_0.ipynb
dm-wyncode/zipped-code
mit
What we really want is an executable description of our pipeline that allows software to do the tricky part for us: figuring out what steps need to be rerun. Create a file, called Makefile, with the following contents. Python's built-in format is used to create the contents of the Makefile.
makefile_contents = """ # Count words. {repo_path}/isles.dat : {data}/books/isles.txt {tab_char}python {code}/wordcount.py {data}/books/isles.txt {repo_path}/isles.dat """.format(code=code, data=data, repo_path=repo_path, tab_char=TAB_CHAR)
content/posts/makefile-tutorial/makefile_tutorial_0.ipynb
dm-wyncode/zipped-code
mit
Write the contents to a file named Makefile.
with open('Makefile', 'w') as fh: fh.write(makefile_contents)
content/posts/makefile-tutorial/makefile_tutorial_0.ipynb
dm-wyncode/zipped-code
mit
Let’s first sure we start from scratch and delete the .dat and .png files we created earlier: Run rm in shell.
!rm $repo_path/*.dat $repo_path/*.png
content/posts/makefile-tutorial/makefile_tutorial_0.ipynb
dm-wyncode/zipped-code
mit
Run make in shell. By default, Make prints out the actions it executes:
!make
content/posts/makefile-tutorial/makefile_tutorial_0.ipynb
dm-wyncode/zipped-code
mit
Let’s see if we got what we expected. Run head in shell.
!head -5 $repo_path/isles.dat
content/posts/makefile-tutorial/makefile_tutorial_0.ipynb
dm-wyncode/zipped-code
mit
Simple function that just add two numbers:
#Define a Python function def add(a: float, b: float) -> float: '''Calculates sum of two arguments''' return a + b
samples/core/lightweight_component/lightweight_component.ipynb
kubeflow/pipelines
apache-2.0
Convert the function to a pipeline operation
add_op = components.create_component_from_func(add)
samples/core/lightweight_component/lightweight_component.ipynb
kubeflow/pipelines
apache-2.0
A bit more advanced function which demonstrates how to use imports, helper functions and produce multiple outputs.
#Advanced function #Demonstrates imports, helper functions and multiple outputs from typing import NamedTuple def my_divmod(dividend: float, divisor:float) -> NamedTuple('MyDivmodOutput', [('quotient', float), ('remainder', float), ('mlpipeline_ui_metadata', 'UI_metadata'), ('mlpipeline_metrics', 'Metrics')]): '''D...
samples/core/lightweight_component/lightweight_component.ipynb
kubeflow/pipelines
apache-2.0
Test running the python function directly
my_divmod(100, 7)
samples/core/lightweight_component/lightweight_component.ipynb
kubeflow/pipelines
apache-2.0
Convert the function to a pipeline operation You can specify an alternative base container image (the image needs to have Python 3.5+ installed).
divmod_op = components.create_component_from_func(my_divmod, base_image='tensorflow/tensorflow:1.11.0-py3')
samples/core/lightweight_component/lightweight_component.ipynb
kubeflow/pipelines
apache-2.0
Define the pipeline Pipeline function has to be decorated with the @dsl.pipeline decorator
import kfp.deprecated.dsl as dsl @dsl.pipeline( name='calculation-pipeline', description='A toy pipeline that performs arithmetic calculations.' ) def calc_pipeline( a=7, b=8, c=17, ): #Passing pipeline parameter and a constant value as operation arguments add_task = add_op(a, 4) #Returns a dsl.C...
samples/core/lightweight_component/lightweight_component.ipynb
kubeflow/pipelines
apache-2.0
Submit the pipeline for execution
#Specify pipeline argument values arguments = {'a': 7, 'b': 8} #Submit a pipeline run kfp.Client().create_run_from_pipeline_func(calc_pipeline, arguments=arguments) # Run the pipeline on a separate Kubeflow Cluster instead # (use if your notebook is not running in Kubeflow - e.x. if using AI Platform Notebooks) # kfp...
samples/core/lightweight_component/lightweight_component.ipynb
kubeflow/pipelines
apache-2.0
Funções
def mapLibSVM(row): return (row[5],Vectors.dense(row[:3])) df = spark.read \ .format("csv") \ .option("header", "true") \ .option("inferSchema", "true") \ .load("datasets/iris.data")
2019/12-spark/14-spark-mllib-classification/mllibClass_OtacilioBezerra.ipynb
InsightLab/data-science-cookbook
mit
Convertendo a saída de categórica para numérica
indexer = StringIndexer(inputCol="label", outputCol="labelIndex") indexer = indexer.fit(df).transform(df) indexer.show() dfLabeled = indexer.rdd.map(mapLibSVM).toDF(["label", "features"]) dfLabeled.show() train, test = dfLabeled.randomSplit([0.9, 0.1], seed=12345)
2019/12-spark/14-spark-mllib-classification/mllibClass_OtacilioBezerra.ipynb
InsightLab/data-science-cookbook
mit
Definição do Modelo Logístico
lr = LogisticRegression(labelCol="label", maxIter=15)
2019/12-spark/14-spark-mllib-classification/mllibClass_OtacilioBezerra.ipynb
InsightLab/data-science-cookbook
mit
Cross-Validation - TrainValidationSplit e CrossValidator
paramGrid = ParamGridBuilder()\ .addGrid(lr.regParam, [0.1, 0.001]) \ .build() tvs = TrainValidationSplit(estimator=lr, estimatorParamMaps=paramGrid, evaluator=MulticlassClassificationEvaluator(), trainRatio=0.8) cval = CrossVali...
2019/12-spark/14-spark-mllib-classification/mllibClass_OtacilioBezerra.ipynb
InsightLab/data-science-cookbook
mit
Treino do Modelo e Predição do Teste
result_tvs = tvs.fit(train).transform(test) result_cval = cval.fit(train).transform(test) preds_tvs = result_tvs.select(["prediction", "label"]) preds_cval = result_cval.select(["prediction", "label"])
2019/12-spark/14-spark-mllib-classification/mllibClass_OtacilioBezerra.ipynb
InsightLab/data-science-cookbook
mit
Avaliação dos Modelos
# Instânciação dos Objetos de Métrics metrics_tvs = MulticlassMetrics(preds_tvs.rdd) metrics_cval = MulticlassMetrics(preds_cval.rdd) # Estatísticas Gerais para o Método TrainValidationSplit print("Summary Stats") print("F1 Score = %s" % metrics_tvs.fMeasure()) print("Accuracy = %s" % metrics_tvs.accuracy) print("Weig...
2019/12-spark/14-spark-mllib-classification/mllibClass_OtacilioBezerra.ipynb
InsightLab/data-science-cookbook
mit
Conclusão: Uma vez que ambos os modelos de CrossValidation usam o mesmo modelo de predição (a Regressão Logística), e contando com o fato de que o dataset é relativamente pequeno, é natural que ambos os métodos de CrossValidation encontrem o mesmo (ou aproximadamente igual) valor ótimo para os hyperparâmetros testados....
from pyspark.ml.classification import RandomForestClassifier
2019/12-spark/14-spark-mllib-classification/mllibClass_OtacilioBezerra.ipynb
InsightLab/data-science-cookbook
mit
Definição do Modelo de Árvores Randômicas
rf = RandomForestClassifier(labelCol="label", featuresCol="features")
2019/12-spark/14-spark-mllib-classification/mllibClass_OtacilioBezerra.ipynb
InsightLab/data-science-cookbook
mit
Cross-Validation - CrossValidator
paramGrid = ParamGridBuilder()\ .addGrid(rf.numTrees, [1, 100]) \ .build() cval = CrossValidator(estimator=rf, estimatorParamMaps=paramGrid, evaluator=MulticlassClassificationEvaluator(), numFolds=10)
2019/12-spark/14-spark-mllib-classification/mllibClass_OtacilioBezerra.ipynb
InsightLab/data-science-cookbook
mit
Treino do Modelo e Predição do Teste
results = cval.fit(train).transform(test) predictions = results.select(["prediction", "label"])
2019/12-spark/14-spark-mllib-classification/mllibClass_OtacilioBezerra.ipynb
InsightLab/data-science-cookbook
mit
Avaliação do Modelo
# Instânciação dos Objetos de Métrics metrics = MulticlassMetrics(predictions.rdd) # Estatísticas Gerais para o Método TrainValidationSplit print("Summary Stats") print("F1 Score = %s" % metrics.fMeasure()) print("Accuracy = %s" % metrics.accuracy) print("Weighted recall = %s" % metrics.weightedRecall) print("Weighted...
2019/12-spark/14-spark-mllib-classification/mllibClass_OtacilioBezerra.ipynb
InsightLab/data-science-cookbook
mit
Learn the model structure using PC
est = PC(data=samples) estimated_model = est.estimate(variant="stable", max_cond_vars=4) get_f1_score(estimated_model, model) est = PC(data=samples) estimated_model = est.estimate(variant="orig", max_cond_vars=4) get_f1_score(estimated_model, model)
examples/Structure Learning in Bayesian Networks.ipynb
pgmpy/pgmpy
mit
Learn the model structure using Hill-Climb Search
scoring_method = K2Score(data=samples) est = HillClimbSearch(data=samples) estimated_model = est.estimate( scoring_method=scoring_method, max_indegree=4, max_iter=int(1e4) ) get_f1_score(estimated_model, model)
examples/Structure Learning in Bayesian Networks.ipynb
pgmpy/pgmpy
mit
The Geobase knowledge base Geobase is a small knowledge base about the geography of the United States. It contains (almost) all the information needed to answer queries in the Geo880 dataset, including facts about: states: capital, area, population, major cities, neighboring states, highest and lowest points and elev...
from geobase import GeobaseReader reader = GeobaseReader() unaries = [str(t) for t in reader.tuples if len(t) == 2] print('\nSome unaries:\n ' + '\n '.join(unaries[:10])) binaries = [str(t) for t in reader.tuples if len(t) == 3] print('\nSome binaries:\n ' + '\n '.join(binaries[:10]))
sippycup-unit-3.ipynb
sloanesturz/cs224u-final-project
gpl-2.0
Some observations here: Unaries are pairs consisting of a unary predicate (a type) and an entity. Binaries are triples consisting of binary predicate (a relation) and two entities (or an entity and a numeric or string value). Entities are named by unique identifiers of the form /type/name. This is a GeobaseReader con...
from graph_kb import GraphKB simpsons_tuples = [ # unaries ('male', 'homer'), ('female', 'marge'), ('male', 'bart'), ('female', 'lisa'), ('female', 'maggie'), ('adult', 'homer'), ('adult', 'marge'), ('child', 'bart'), ('child', 'lisa'), ('child', 'maggie'), # binaries...
sippycup-unit-3.ipynb
sloanesturz/cs224u-final-project
gpl-2.0
The GraphKB object now contains three indexes: unaries[U]: all entities belonging to unary relation U binaries_fwd[B][E]: all entities X such that (E, X) belongs to binary relation B binaries_rev[B][E]: all entities X such that (X, E) belongs to binary relation B For example:
simpsons_kb.unaries['child'] simpsons_kb.binaries_fwd['has_sister']['lisa'] simpsons_kb.binaries_rev['has_sister']['lisa']
sippycup-unit-3.ipynb
sloanesturz/cs224u-final-project
gpl-2.0
The GraphKBExecutor class A GraphKBExecutor executes formal queries against a GraphKB and returns their denotations. Queries are represented by Python tuples, and can be nested. Denotations are also represented by Python tuples, but are conceptually sets (possibly empty). The elements of these tuples are always sorted...
queries = [ 'bart', 'male', ('has_sister', 'lisa'), # who has sister lisa? ('lisa', 'has_sister'), # lisa has sister who, i.e., who is a sister of lisa? ('lisa', 'has_brother'), # lisa has brother who, i.e., who is a brother of lisa? ('.and', 'male', 'child'), ('.or', 'male', 'adult'), ...
sippycup-unit-3.ipynb
sloanesturz/cs224u-final-project
gpl-2.0
Note that the query (R E) denotes entities having relation R to entity E, whereas the query (E R) denotes entities to which entity E has relation R. For a more detailed understanding of the style of semantic representation defined by GraphKBExecutor, take a look at the source code. Using GraphKBExecutor with Geobase
geobase = GraphKB(reader.tuples) executor = geobase.executor() queries = [ ('/state/texas', 'capital'), # capital of texas ('.and', 'river', ('traverses', '/state/utah')), # rivers that traverse utah ('.argmax', 'height', 'mountain'), # tallest mountain ] for query in queries: print() print(query) ...
sippycup-unit-3.ipynb
sloanesturz/cs224u-final-project
gpl-2.0
Grammar engineering It's time to start developing a grammar for the geography domain. As in Unit 2, the performance metric we'll focus on during grammar engineering is oracle accuracy (the proportion of examples for which any parse is correct), not accuracy (the proportion of examples for which the first parse is cor...
from collections import defaultdict from operator import itemgetter from geo880 import geo880_train_examples words = [word for example in geo880_train_examples for word in example.input.split()] counts = defaultdict(int) for word in words: counts[word] += 1 counts = sorted([(count, word) for word, count in counts....
sippycup-unit-3.ipynb
sloanesturz/cs224u-final-project
gpl-2.0
There are at least four major categories of words here: - Words that refer to entities, such as "texas", "mississippi", "usa", and "austin". - Words that refer to types, such as "state", "river", and "cities". - Words that refer to relations, such as "in", "borders", "capital", and "long". - Other function words, such ...
from parsing import Grammar, Rule optional_words = [ 'the', '?', 'what', 'is', 'in', 'of', 'how', 'many', 'are', 'which', 'that', 'with', 'has', 'major', 'does', 'have', 'where', 'me', 'there', 'give', 'name', 'all', 'a', 'by', 'you', 'to', 'tell', 'other', 'it', 'do', 'whose', 'show', 'one', 'on', 'fo...
sippycup-unit-3.ipynb
sloanesturz/cs224u-final-project
gpl-2.0
Because $Query has not yet been defined, we won't be able to parse anything yet. Entities and collections Our grammar will need to be able to recognize names of entities, such as "utah". There are hundreds of entities in Geobase, and we don't want to have to introduce a grammar rule for each entity. Instead, we'll de...
from annotator import Annotator, NumberAnnotator class GeobaseAnnotator(Annotator): def __init__(self, geobase): self.geobase = geobase def annotate(self, tokens): phrase = ' '.join(tokens) places = self.geobase.binaries_rev['name'][phrase] return [('$Entity', place) for place ...
sippycup-unit-3.ipynb
sloanesturz/cs224u-final-project
gpl-2.0
Now a couple of rules that will enable us to parse inputs that simply name locations, such as "utah". (TODO: explain rationale for $Collection and $Query.)
rules_collection_entity = [ Rule('$Query', '$Collection', lambda sems: sems[0]), Rule('$Collection', '$Entity', lambda sems: sems[0]), ] rules = rules_optionals + rules_collection_entity
sippycup-unit-3.ipynb
sloanesturz/cs224u-final-project
gpl-2.0
Now let's make a grammar.
annotators = [NumberAnnotator(), GeobaseAnnotator(geobase)] grammar = Grammar(rules=rules, annotators=annotators)
sippycup-unit-3.ipynb
sloanesturz/cs224u-final-project
gpl-2.0
Let's try to parse some inputs which just name locations.
parses = grammar.parse_input('what is utah') for parse in parses[:1]: print('\n'.join([str(parse.semantics), str(executor.execute(parse.semantics))]))
sippycup-unit-3.ipynb
sloanesturz/cs224u-final-project
gpl-2.0
Great, it worked. Now let's run an evaluation on the Geo880 training examples.
from experiment import sample_wins_and_losses from geoquery import GeoQueryDomain from metrics import DenotationOracleAccuracyMetric from scoring import Model domain = GeoQueryDomain() model = Model(grammar=grammar, executor=executor.execute) metric = DenotationOracleAccuracyMetric() sample_wins_and_losses(domain=dom...
sippycup-unit-3.ipynb
sloanesturz/cs224u-final-project
gpl-2.0
We don't yet have a single win: denotation oracle accuracy remains stuck at zero. However, the average number of parses is slightly greater than zero, meaning that there are a few examples which our grammar can parse (though not correctly). It would be interesting to know which examples. There's a utility function i...
rules_types = [ Rule('$Collection', '$Type', lambda sems: sems[0]), Rule('$Type', 'state', 'state'), Rule('$Type', 'states', 'state'), Rule('$Type', 'city', 'city'), Rule('$Type', 'cities', 'city'), Rule('$Type', 'big cities', 'city'), Rule('$Type', 'towns', 'city'), Rule('$Type', 'rive...
sippycup-unit-3.ipynb
sloanesturz/cs224u-final-project
gpl-2.0
We should now be able to parse inputs denoting types, such as "name the lakes":
rules = rules_optionals + rules_collection_entity + rules_types grammar = Grammar(rules=rules, annotators=annotators) parses = grammar.parse_input('name the lakes') for parse in parses[:1]: print('\n'.join([str(parse.semantics), str(executor.execute(parse.semantics))]))
sippycup-unit-3.ipynb
sloanesturz/cs224u-final-project
gpl-2.0
It worked. Let's evaluate on the Geo880 training data again.
model = Model(grammar=grammar, executor=executor.execute) sample_wins_and_losses(domain=domain, model=model, metric=metric, seed=1)
sippycup-unit-3.ipynb
sloanesturz/cs224u-final-project
gpl-2.0
Liftoff! We have two wins, and denotation oracle accuracy is greater than zero! Just barely. Relations and joins In order to really make this bird fly, we're going to have to handle relations. In particular, we'd like to be able to parse queries which combine a relation with an entity or collection, such as "what is...
rules_relations = [ Rule('$Collection', '$Relation ?$Optionals $Collection', lambda sems: sems[0](sems[2])), Rule('$Relation', '$FwdRelation', lambda sems: (lambda arg: (sems[0], arg))), Rule('$Relation', '$RevRelation', lambda sems: (lambda arg: (arg, sems[0]))), Rule('$FwdRelation', '$FwdBordersRela...
sippycup-unit-3.ipynb
sloanesturz/cs224u-final-project
gpl-2.0
We should now be able to parse "what is the capital of vermont". Let's see:
rules = rules_optionals + rules_collection_entity + rules_types + rules_relations grammar = Grammar(rules=rules, annotators=annotators) parses = grammar.parse_input('what is the capital of vermont ?') for parse in parses[:1]: print('\n'.join([str(parse.semantics), str(executor.execute(parse.semantics))]))
sippycup-unit-3.ipynb
sloanesturz/cs224u-final-project
gpl-2.0
Montpelier! I always forget that one. OK, let's evaluate our progress on the Geo880 training data.
model = Model(grammar=grammar, executor=executor.execute) sample_wins_and_losses(domain=domain, model=model, metric=metric, seed=1)
sippycup-unit-3.ipynb
sloanesturz/cs224u-final-project
gpl-2.0
Hot diggity, it's working. Denotation oracle accuracy is over 12%, double digits. We have 75 wins, and they're what we expect: queries that simply combine a relation and an entity (or collection). Intersections
rules_intersection = [ Rule('$Collection', '$Collection $Collection', lambda sems: ('.and', sems[0], sems[1])), Rule('$Collection', '$Collection $Optional $Collection', lambda sems: ('.and', sems[0], sems[2])), Rule('$Collection', '$Collection $Optional $Optional $Collection', lam...
sippycup-unit-3.ipynb
sloanesturz/cs224u-final-project
gpl-2.0
Let's evaluate the impact on the Geo880 training examples.
model = Model(grammar=grammar, executor=executor.execute) sample_wins_and_losses(domain=domain, model=model, metric=metric, seed=1)
sippycup-unit-3.ipynb
sloanesturz/cs224u-final-project
gpl-2.0
Great, denotation oracle accuracy has more than doubled, from 12% to 28%. And the wins now include intersections like "which states border new york". The losses, however, are clearly dominated by one category of error. Superlatives Many of the losses involve superlatives, such as "biggest" or "shortest". Let's remed...
rules_superlatives = [ Rule('$Collection', '$Superlative ?$Optionals $Collection', lambda sems: sems[0] + (sems[2],)), Rule('$Collection', '$Collection ?$Optionals $Superlative', lambda sems: sems[2] + (sems[0],)), Rule('$Superlative', 'largest', ('.argmax', 'area')), Rule('$Superlative', 'largest', ('...
sippycup-unit-3.ipynb
sloanesturz/cs224u-final-project
gpl-2.0
Now we should be able to parse "tallest mountain":
rules = rules_optionals + rules_collection_entity + rules_types + rules_relations + rules_intersection + rules_superlatives grammar = Grammar(rules=rules, annotators=annotators) parses = grammar.parse_input('tallest mountain') for parse in parses[:1]: print('\n'.join([str(parse.semantics), str(executor.execute(pars...
sippycup-unit-3.ipynb
sloanesturz/cs224u-final-project
gpl-2.0
Wow, superlatives make a big difference. Denotation oracle accuracy has surged from 28% to 42%. Reverse joins
def reverse(relation_sem): """TODO""" # relation_sem is a lambda function which takes an arg and forms a pair, # either (rel, arg) or (arg, rel). We want to swap the order of the pair. def apply_and_swap(arg): pair = relation_sem(arg) return (pair[1], pair[0]) return apply_and_swap ...
sippycup-unit-3.ipynb
sloanesturz/cs224u-final-project
gpl-2.0
This time the gain in denotation oracle accuracy was more modest, from 42% to 47%. Still, we are making good progress. However, note that a substantial gap has opened between accuracy and oracle accuracy. This indicates that we could benefit from adding a scoring model. Feature engineering Through an iterative proce...
from experiment import evaluate_model from metrics import denotation_match_metrics evaluate_model(model=model, examples=geo880_train_examples[:10], metrics=denotation_match_metrics(), print_examples=True)
sippycup-unit-3.ipynb
sloanesturz/cs224u-final-project
gpl-2.0
Take a look through that output. Over the ten examples, we achieved denotation oracle accuracy of 60%, but denotation accuracy of just 40%. In other words, there were two examples where we generated a correct parse, but failed to rank it at the top. Take a closer look at those two cases. The first case is "what stat...
def empty_denotation_feature(parse): features = defaultdict(float) if parse.denotation == (): features['empty_denotation'] += 1.0 return features weights = {'empty_denotation': -1.0} model = Model(grammar=grammar, feature_fn=empty_denotation_feature, weights=weights, ...
sippycup-unit-3.ipynb
sloanesturz/cs224u-final-project
gpl-2.0
Let's evaluate the impact of using our new empty_denotation feature on the Geo880 training examples.
from experiment import evaluate_model from metrics import denotation_match_metrics evaluate_model(model=model, examples=geo880_train_examples, metrics=denotation_match_metrics(), print_examples=False)
sippycup-unit-3.ipynb
sloanesturz/cs224u-final-project
gpl-2.0
Vertex client library: AutoML text entity extraction model for batch prediction <table align="left"> <td> <a href="https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb"> <img src="https:...
import os import sys # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install -U google-cloud-aiplatform $USER_FLAG
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Restart the kernel Once you've installed the Vertex client library and Google cloud-storage, you need to restart the notebook kernel so it can find the packages.
if not os.getenv("IS_TESTING"): # Automatically restart kernel after installs import IPython app = IPython.Application.instance() app.kernel.do_shutdown(True)
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Before you begin GPU runtime Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select Runtime > Change Runtime Type > GPU Set up your Google Cloud project The following steps are required, regardless of your notebook environment. Select or create a Google Cloud project. When y...
PROJECT_ID = "[your-project-id]" # @param {type:"string"} if PROJECT_ID == "" or PROJECT_ID is None or PROJECT_ID == "[your-project-id]": # Get your GCP project id from gcloud shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null PROJECT_ID = shell_output[0] print("Project ID:"...
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Region You can also change the REGION variable, which is used for operations throughout the rest of this notebook. Below are regions supported for Vertex. We recommend that you choose the region closest to you. Americas: us-central1 Europe: europe-west4 Asia Pacific: asia-east1 You may not use a multi-regional bucke...
REGION = "us-central1" # @param {type: "string"}
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Authenticate your Google Cloud account If you are using Google Cloud Notebook, your environment is already authenticated. Skip this step. If you are using Colab, run the cell below and follow the instructions when prompted to authenticate your account via oAuth. Otherwise, follow these steps: In the Cloud Console, go t...
# If you are running this notebook in Colab, run this cell and follow the # instructions to authenticate your GCP account. This provides access to your # Cloud Storage bucket and lets you submit training jobs and prediction # requests. # If on Google Cloud Notebook, then don't execute this code if not os.path.exists("...
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Create a Cloud Storage bucket The following steps are required, regardless of your notebook environment. This tutorial is designed to use training data that is in a public Cloud Storage bucket and a local Cloud Storage bucket for your batch predictions. You may alternatively use your own training data that you have sto...
BUCKET_NAME = "gs://[your-bucket-name]" # @param {type:"string"} if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "gs://[your-bucket-name]": BUCKET_NAME = "gs://" + PROJECT_ID + "aip-" + TIMESTAMP
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Set up variables Next, set up some variables used throughout the tutorial. Import libraries and define constants Import Vertex client library Import the Vertex client library into our Python environment.
import time from google.cloud.aiplatform import gapic as aip from google.protobuf import json_format from google.protobuf.json_format import MessageToJson, ParseDict from google.protobuf.struct_pb2 import Struct, Value
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Vertex constants Setup up the following constants for Vertex: API_ENDPOINT: The Vertex API service endpoint for dataset, model, job, pipeline and endpoint services. PARENT: The Vertex location root path for dataset, model, job, pipeline and endpoint resources.
# API service endpoint API_ENDPOINT = "{}-aiplatform.googleapis.com".format(REGION) # Vertex location root path for your dataset, model and endpoint resources PARENT = "projects/" + PROJECT_ID + "/locations/" + REGION
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
AutoML constants Set constants unique to AutoML datasets and training: Dataset Schemas: Tells the Dataset resource service which type of dataset it is. Data Labeling (Annotations) Schemas: Tells the Dataset resource service how the data is labeled (annotated). Dataset Training Schemas: Tells the Pipeline resource serv...
# Text Dataset type DATA_SCHEMA = "gs://google-cloud-aiplatform/schema/dataset/metadata/text_1.0.0.yaml" # Text Labeling type LABEL_SCHEMA = "gs://google-cloud-aiplatform/schema/dataset/ioformat/text_extraction_io_format_1.0.0.yaml" # Text Training task TRAINING_SCHEMA = "gs://google-cloud-aiplatform/schema/trainingjob...
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Hardware Accelerators Set the hardware accelerators (e.g., GPU), if any, for prediction. Set the variable DEPLOY_GPU/DEPLOY_NGPU to use a container image supporting a GPU and the number of GPUs allocated to the virtual machine (VM) instance. For example, to use a GPU container image with 4 Nvidia Telsa K80 GPUs allocat...
if os.getenv("IS_TESTING_DEPOLY_GPU"): DEPLOY_GPU, DEPLOY_NGPU = ( aip.AcceleratorType.NVIDIA_TESLA_K80, int(os.getenv("IS_TESTING_DEPOLY_GPU")), ) else: DEPLOY_GPU, DEPLOY_NGPU = (aip.AcceleratorType.NVIDIA_TESLA_K80, 1)
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Container (Docker) image For AutoML batch prediction, the container image for the serving binary is pre-determined by the Vertex prediction service. More specifically, the service will pick the appropriate container for the model depending on the hardware accelerator you selected. Machine Type Next, set the machine typ...
if os.getenv("IS_TESTING_DEPLOY_MACHINE"): MACHINE_TYPE = os.getenv("IS_TESTING_DEPLOY_MACHINE") else: MACHINE_TYPE = "n1-standard" VCPU = "4" DEPLOY_COMPUTE = MACHINE_TYPE + "-" + VCPU print("Deploy machine type", DEPLOY_COMPUTE)
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Tutorial Now you are ready to start creating your own AutoML text entity extraction model. Set up clients The Vertex client library works as a client/server model. On your side (the Python script) you will create a client that sends requests and receives responses from the Vertex server. You will use different clients ...
# client options same for all services client_options = {"api_endpoint": API_ENDPOINT} def create_dataset_client(): client = aip.DatasetServiceClient(client_options=client_options) return client def create_model_client(): client = aip.ModelServiceClient(client_options=client_options) return client ...
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Dataset Now that your clients are ready, your first step in training a model is to create a managed dataset instance, and then upload your labeled data to it. Create Dataset resource instance Use the helper function create_dataset to create the instance of a Dataset resource. This function does the following: Uses the...
TIMEOUT = 90 def create_dataset(name, schema, labels=None, timeout=TIMEOUT): start_time = time.time() try: dataset = aip.Dataset( display_name=name, metadata_schema_uri=schema, labels=labels ) operation = clients["dataset"].create_dataset(parent=PARENT, dataset=dataset) ...
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Now save the unique dataset identifier for the Dataset resource instance you created.
# The full unique ID for the dataset dataset_id = result.name # The short numeric ID for the dataset dataset_short_id = dataset_id.split("/")[-1] print(dataset_id)
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Data preparation The Vertex Dataset resource for text has a couple of requirements for your text entity extraction data. Text examples must be stored in a JSONL file. Unlike text classification and sentiment analysis, a CSV index file is not supported. The examples must be either inline text or reference text files th...
IMPORT_FILE = "gs://ucaip-test-us-central1/dataset/ucaip_ten_dataset.jsonl"
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Quick peek at your data You will use a version of the NCBI Biomedical dataset that is stored in a public Cloud Storage bucket, using a JSONL index file. Start by doing a quick peek at the data. You count the number of examples by counting the number of objects in a JSONL index file (wc -l) and then peek at the first f...
if "IMPORT_FILES" in globals(): FILE = IMPORT_FILES[0] else: FILE = IMPORT_FILE count = ! gsutil cat $FILE | wc -l print("Number of Examples", int(count[0])) print("First 10 rows") ! gsutil cat $FILE | head
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Import data Now, import the data into your Vertex Dataset resource. Use this helper function import_data to import the data. The function does the following: Uses the Dataset client. Calls the client method import_data, with the following parameters: name: The human readable name you give to the Dataset resource (e.g....
def import_data(dataset, gcs_sources, schema): config = [{"gcs_source": {"uris": gcs_sources}, "import_schema_uri": schema}] print("dataset:", dataset_id) start_time = time.time() try: operation = clients["dataset"].import_data( name=dataset_id, import_configs=config ) ...
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Train the model Now train an AutoML text entity extraction model using your Vertex Dataset resource. To train the model, do the following steps: Create an Vertex training pipeline for the Dataset resource. Execute the pipeline to start the training. Create a training pipeline You may ask, what do we use a pipeline fo...
def create_pipeline(pipeline_name, model_name, dataset, schema, task): dataset_id = dataset.split("/")[-1] input_config = { "dataset_id": dataset_id, "fraction_split": { "training_fraction": 0.8, "validation_fraction": 0.1, "test_fraction": 0.1, }, ...
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Construct the task requirements Next, construct the task requirements. Unlike other parameters which take a Python (JSON-like) dictionary, the task field takes a Google protobuf Struct, which is very similar to a Python dictionary. Use the json_format.ParseDict method for the conversion. The minimal fields you need to ...
PIPE_NAME = "biomedical_pipe-" + TIMESTAMP MODEL_NAME = "biomedical_model-" + TIMESTAMP task = json_format.ParseDict( { "multi_label": False, "budget_milli_node_hours": 8000, "model_type": "CLOUD", "disable_early_stopping": False, }, Value(), ) response = create_pipeline(PI...
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Now save the unique identifier of the training pipeline you created.
# The full unique ID for the pipeline pipeline_id = response.name # The short numeric ID for the pipeline pipeline_short_id = pipeline_id.split("/")[-1] print(pipeline_id)
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Get information on a training pipeline Now get pipeline information for just this training pipeline instance. The helper function gets the job information for just this job by calling the the job client service's get_training_pipeline method, with the following parameter: name: The Vertex fully qualified pipeline ide...
def get_training_pipeline(name, silent=False): response = clients["pipeline"].get_training_pipeline(name=name) if silent: return response print("pipeline") print(" name:", response.name) print(" display_name:", response.display_name) print(" state:", response.state) print(" training...
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Deployment Training the above model may take upwards of 120 minutes time. Once your model is done training, you can calculate the actual time it took to train the model by subtracting end_time from start_time. For your model, you will need to know the fully qualified Vertex Model resource identifier, which the pipeline...
while True: response = get_training_pipeline(pipeline_id, True) if response.state != aip.PipelineState.PIPELINE_STATE_SUCCEEDED: print("Training job has not completed:", response.state) model_to_deploy_id = None if response.state == aip.PipelineState.PIPELINE_STATE_FAILED: ra...
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Model information Now that your model is trained, you can get some information on your model. Evaluate the Model resource Now find out how good the model service believes your model is. As part of training, some portion of the dataset was set aside as the test (holdout) data, which is used by the pipeline service to ev...
def list_model_evaluations(name): response = clients["model"].list_model_evaluations(parent=name) for evaluation in response: print("model_evaluation") print(" name:", evaluation.name) print(" metrics_schema_uri:", evaluation.metrics_schema_uri) metrics = json_format.MessageToDic...
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Model deployment for batch prediction Now deploy the trained Vertex Model resource you created for batch prediction. This differs from deploying a Model resource for on-demand prediction. For online prediction, you: Create an Endpoint resource for deploying the Model resource to. Deploy the Model resource to the En...
test_item_1 = 'Molecular basis of hexosaminidase A deficiency and pseudodeficiency in the Berks County Pennsylvania Dutch.\tFollowing the birth of two infants with Tay-Sachs disease ( TSD ) , a non-Jewish , Pennsylvania Dutch kindred was screened for TSD carriers using the biochemical assay . A high frequency of indivi...
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Make the batch input file Now make a batch input file, which you will store in your local Cloud Storage bucket. The batch input file can only be in JSONL format. For JSONL file, you make one dictionary entry per line for each data item (instance). The dictionary contains the key/value pairs: content: The Cloud Storage...
import json import tensorflow as tf gcs_test_item_1 = BUCKET_NAME + "/test1.txt" with tf.io.gfile.GFile(gcs_test_item_1, "w") as f: f.write(test_item_1 + "\n") gcs_test_item_2 = BUCKET_NAME + "/test2.txt" with tf.io.gfile.GFile(gcs_test_item_2, "w") as f: f.write(test_item_2 + "\n") gcs_input_uri = BUCKET_NA...
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Compute instance scaling You have several choices on scaling the compute instances for handling your batch prediction requests: Single Instance: The batch prediction requests are processed on a single compute instance. Set the minimum (MIN_NODES) and maximum (MAX_NODES) number of compute instances to one. Manual Sc...
MIN_NODES = 1 MAX_NODES = 1
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Make batch prediction request Now that your batch of two test items is ready, let's do the batch request. Use this helper function create_batch_prediction_job, with the following parameters: display_name: The human readable name for the prediction job. model_name: The Vertex fully qualified identifier for the Model re...
BATCH_MODEL = "biomedical_batch-" + TIMESTAMP def create_batch_prediction_job( display_name, model_name, gcs_source_uri, gcs_destination_output_uri_prefix, parameters=None, ): if DEPLOY_GPU: machine_spec = { "machine_type": DEPLOY_COMPUTE, "accelerator_type": D...
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Now get the unique identifier for the batch prediction job you created.
# The full unique ID for the batch job batch_job_id = response.name # The short numeric ID for the batch job batch_job_short_id = batch_job_id.split("/")[-1] print(batch_job_id)
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Get information on a batch prediction job Use this helper function get_batch_prediction_job, with the following paramter: job_name: The Vertex fully qualified identifier for the batch prediction job. The helper function calls the job client service's get_batch_prediction_job method, with the following paramter: name...
def get_batch_prediction_job(job_name, silent=False): response = clients["job"].get_batch_prediction_job(name=job_name) if silent: return response.output_config.gcs_destination.output_uri_prefix, response.state print("response") print(" name:", response.name) print(" display_name:", respons...
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Get the predictions When the batch prediction is done processing, the job state will be JOB_STATE_SUCCEEDED. Finally you view the predictions stored at the Cloud Storage path you set as output. The predictions will be in a JSONL format, which you indicated at the time you made the batch prediction job, under a subfolde...
def get_latest_predictions(gcs_out_dir): """ Get the latest prediction subfolder using the timestamp in the subfolder name""" folders = !gsutil ls $gcs_out_dir latest = "" for folder in folders: subfolder = folder.split("/")[-2] if subfolder.startswith("prediction-"): if subf...
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Cleaning up To clean up all GCP resources used in this project, you can delete the GCP project you used for the tutorial. Otherwise, you can delete the individual resources you created in this tutorial: Dataset Pipeline Model Endpoint Batch Job Custom Job Hyperparameter Tuning Job Cloud Storage Bucket
delete_dataset = True delete_pipeline = True delete_model = True delete_endpoint = True delete_batchjob = True delete_customjob = True delete_hptjob = True delete_bucket = True # Delete the dataset using the Vertex fully qualified identifier for the dataset try: if delete_dataset and "dataset_id" in globals(): ...
notebooks/community/gapic/automl/showcase_automl_text_entity_extraction_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Create growler application with name NotebookServer
app = growler.App("NotebookServer")
examples/ExampleNotebook_1.ipynb
pyGrowler/Growler
apache-2.0
Add a general purpose method which prints ip address and the USER-AGENT header
@app.use def print_client_info(req, res): ip = req.ip reqpath = req.path print("[{ip}] {path}".format(ip=ip, path=reqpath)) print(" >", req.headers['USER-AGENT']) print(flush=True)
examples/ExampleNotebook_1.ipynb
pyGrowler/Growler
apache-2.0
Next, add a route matching any GET requests for the root (/) of the site. This uses a simple global variable to count the number times this page has been accessed, and return text to the client
i = 0 @app.get("/") def index(req, res): global i res.send_text("It Works! (%d)" % i) i += 1
examples/ExampleNotebook_1.ipynb
pyGrowler/Growler
apache-2.0
We can see the tree of middleware all requests will pass through - Notice the router object that was implicitly created which will match all requests.
app.print_middleware_tree()
examples/ExampleNotebook_1.ipynb
pyGrowler/Growler
apache-2.0
Use the helper method to create the asyncio server listening on port 9000.
app.create_server_and_run_forever(host='127.0.0.1', port=9000)
examples/ExampleNotebook_1.ipynb
pyGrowler/Growler
apache-2.0
First we will establish some general variables for our game, including the 'stake' of the game (how much money each play is worth), as well as a list representing the cards used in the game. To make things easier, we will just use a list of numbers 0-9 for the cards.
gameStake = 50 cards = range(10)
notebooks/week-2/04 - Lab 2 Assignment.ipynb
yuhao0531/dmc
apache-2.0
Next, let's define a new class to represent each player in the game. I have provided a rough framework of the class definition along with comments along the way to help you complete it. Places where you should write code are denoted by comments inside [] brackets and CAPITAL TEXT.
class Player: # create here two local variables to store a unique ID for each player and the player's current 'pot' of money PN=0 Pot=0# [FILL IN YOUR VARIABLES HERE] # in the __init__() function, use the two input variables to initialize the ID and starting pot of each player def __i...
notebooks/week-2/04 - Lab 2 Assignment.ipynb
yuhao0531/dmc
apache-2.0
Next we will create some functions outside the class definition which will control the flow of the game. The first function will play one round. It will take as an input the collection of players, and iterate through each one, calling each player's '.play() function.
def playHand(players): for player in players: dealerCard = random.choice(cards) player.play(dealerCard)#[EXECUTE THE PLAY() FUNCTION FOR EACH PLAYER USING THE DEALER CARD, AND PRINT OUT THE RESULTS]
notebooks/week-2/04 - Lab 2 Assignment.ipynb
yuhao0531/dmc
apache-2.0
Next we will define a function that will check the balances of each player, and print out a message with the player's ID and their balance.
def checkBalances(players): for player in players: print 'player '+str(player.returnID())+ ' has $ '+str(player.returnPot())+ ' left'#[PRINT OUT EACH PLAYER'S BALANCE BY USING EACH PLAYER'S ACCESSOR FUNCTIONS]
notebooks/week-2/04 - Lab 2 Assignment.ipynb
yuhao0531/dmc
apache-2.0
Now we are ready to start the game. First we create an empy list to store the collection of players in the game.
players = []
notebooks/week-2/04 - Lab 2 Assignment.ipynb
yuhao0531/dmc
apache-2.0
Then we create a loop that will run a certain number of times, each time creating a player with a unique ID and a starting balance. Each player should be appended to the empty list, which will store all the players. In this case we pass the 'i' iterator of the loop as the player ID, and set a constant value of 500 for ...
for i in range(5): players.append(Player(i, 500))
notebooks/week-2/04 - Lab 2 Assignment.ipynb
yuhao0531/dmc
apache-2.0
Once the players are created, we will create a loop to run the game a certain amount of times. Each step of the loop should start with a print statement announcing the start of the game, and then call the playHand() function, passing as an input the list of players.
for i in range(10): print '' print 'start game ' + str(i) playHand(players)
notebooks/week-2/04 - Lab 2 Assignment.ipynb
yuhao0531/dmc
apache-2.0
Finally, we will analyze the results of the game by running the 'checkBalances()' function and passing it our list of players.
print '' print 'game results:' checkBalances(players)
notebooks/week-2/04 - Lab 2 Assignment.ipynb
yuhao0531/dmc
apache-2.0