markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
As we can see the shots in categorized as shots from the "Right Side(R)", while to the viewers right, are actually to the left side of the hoop. This is something we will need to fix when creating our final shot chart. Drawing the Court But first we need to figure out how to draw the court lines onto our plot. By loo...
from matplotlib.patches import Circle, Rectangle, Arc def draw_court(ax=None, color='black', lw=2, outer_lines=False): # If an axes object isn't provided to plot onto, just get current one if ax is None: ax = plt.gca() # Create the various parts of an NBA basketball court # Create the basketball...
NBA_stats_visualization/Shot charts Notebook.ipynb
JuanIgnacioGil/basket-stats
mit
Lets draw our court
plt.figure(figsize=(12,11)) draw_court(outer_lines=True) plt.xlim(-300,300) plt.ylim(-100,500) plt.show()
NBA_stats_visualization/Shot charts Notebook.ipynb
JuanIgnacioGil/basket-stats
mit
Creating some Shot Charts Now plot our properly adjusted shot chart data along with the court. We can adjust the x-values in two ways. We can either pass in the the negative inverse of LOC_X to plt.scatter or we can pass in descending values to plt.xlim . We'll do the latter to plot our shot chart.
plt.figure(figsize=(12,11)) plt.scatter(shot_df.LOC_X, shot_df.LOC_Y) draw_court(outer_lines=True) # Descending values along the axis from left to right plt.xlim(300,-300) plt.show()
NBA_stats_visualization/Shot charts Notebook.ipynb
JuanIgnacioGil/basket-stats
mit
Lets orient our shot chart with the hoop by the top of the chart, which is the same orientation as the shot charts on stats.nba.com. We do this by settting descending y-values from the bottom to the top of the y-axis. When we do this we no longer need to adjust the x-values of our plot.
plt.figure(figsize=(12,11)) plt.scatter(shot_df.LOC_X, shot_df.LOC_Y) draw_court(outer_lines=True) # Adjust plot limits to just fit in half court plt.xlim(-250,250) # Descending values along th y axis from bottom to top # in order to place the hoop by the top of plot plt.ylim(422.5, -47.5) # get rid of axis tick labels...
NBA_stats_visualization/Shot charts Notebook.ipynb
JuanIgnacioGil/basket-stats
mit
Lets create a few shot charts using jointplot from seaborn .
# create our jointplot joint_shot_chart = sns.jointplot(shot_df.LOC_X, shot_df.LOC_Y, stat_func=None,kind='scatter', space=0, alpha=0.5) joint_shot_chart.fig.set_size_inches(12,11) # A joint plot has 3 Axes, the first one called ax_joint # is the one we want to draw our court onto and adjust some ...
NBA_stats_visualization/Shot charts Notebook.ipynb
JuanIgnacioGil/basket-stats
mit
Getting a Player's Image We could also scrape Jame Harden's picture from stats.nba.com and place it on our plot. We can find his image at this url. To retrieve the image for our plot we can use urlretrieve from url.requests as follows:
import urllib.request # we pass in the link to the image as the 1st argument # the 2nd argument tells urlretrieve what we want to scrape pic = urllib.request.urlretrieve("http://stats.nba.com/media/players/230x185/"+playerID+".png", playerID+".png") # urlretrieve returns a tuple with...
NBA_stats_visualization/Shot charts Notebook.ipynb
JuanIgnacioGil/basket-stats
mit
Now to plot Harden's face on a jointplot we will import OffsetImage from matplotlib. Offset, which will allow us to place the image at the top right corner of the plot. So lets create our shot chart like we did above, but this time we will create a KDE jointplot and at the end add on our image.
from matplotlib.offsetbox import OffsetImage # create our jointplot # get our colormap for the main kde plot # Note we can extract a color from cmap to use for # the plots that lie on the side and top axes cmap=plt.cm.YlOrRd_r # n_levels sets the number of contour lines for the main kde plot joint_shot_chart = sns.j...
NBA_stats_visualization/Shot charts Notebook.ipynb
JuanIgnacioGil/basket-stats
mit
And another jointplot but with hexbins.
# create our jointplot cmap=plt.cm.gist_heat_r joint_shot_chart = sns.jointplot(shot_df.LOC_X, shot_df.LOC_Y, stat_func=None, kind='hex', space=0, color=cmap(.2), cmap=cmap) joint_shot_chart.fig.set_size_inches(12,11) # A joint plot has 3 Axes, the first one called ax_joint # is the...
NBA_stats_visualization/Shot charts Notebook.ipynb
JuanIgnacioGil/basket-stats
mit
MNIST
from sklearn.datasets import fetch_mldata mnist = fetch_mldata('MNIST original') mnist X, y = mnist["data"], mnist["target"] X.shape y.shape 28*28 %matplotlib inline import matplotlib import matplotlib.pyplot as plt some_digit = X[36000] some_digit_image = some_digit.reshape(28, 28) plt.imshow(some_digit_image, cm...
HandsOnML/code/03_classification.ipynb
atulsingh0/MachineLearning
gpl-3.0
Binary classifier
y_train_5 = (y_train == 5) y_test_5 = (y_test == 5) from sklearn.linear_model import SGDClassifier sgd_clf = SGDClassifier(random_state=42) sgd_clf.fit(X_train, y_train_5) sgd_clf.predict([some_digit]) from sklearn.model_selection import cross_val_score cross_val_score(sgd_clf, X_train, y_train_5, cv=3, scoring="ac...
HandsOnML/code/03_classification.ipynb
atulsingh0/MachineLearning
gpl-3.0
Note: there is an issue introduced in Scikit-Learn 0.19.0 where the result of cross_val_predict() is incorrect in the binary classification case when using method="decision_function", as in the code above. The resulting array has an extra first dimension full of 0s. We need to add this small hack for now to work around...
y_scores.shape # hack to work around issue #9589 introduced in Scikit-Learn 0.19.0 if y_scores.ndim == 2: y_scores = y_scores[:, 1] from sklearn.metrics import precision_recall_curve precisions, recalls, thresholds = precision_recall_curve(y_train_5, y_scores) def plot_precision_recall_vs_threshold(precisions, ...
HandsOnML/code/03_classification.ipynb
atulsingh0/MachineLearning
gpl-3.0
ROC curves
from sklearn.metrics import roc_curve fpr, tpr, thresholds = roc_curve(y_train_5, y_scores) def plot_roc_curve(fpr, tpr, label=None): plt.plot(fpr, tpr, linewidth=2, label=label) plt.plot([0, 1], [0, 1], 'k--') plt.axis([0, 1, 0, 1]) plt.xlabel('False Positive Rate', fontsize=16) plt.ylabel('True ...
HandsOnML/code/03_classification.ipynb
atulsingh0/MachineLearning
gpl-3.0
Multiclass classification
sgd_clf.fit(X_train, y_train) sgd_clf.predict([some_digit]) some_digit_scores = sgd_clf.decision_function([some_digit]) some_digit_scores np.argmax(some_digit_scores) sgd_clf.classes_ sgd_clf.classes_[5] from sklearn.multiclass import OneVsOneClassifier ovo_clf = OneVsOneClassifier(SGDClassifier(random_state=42)) ...
HandsOnML/code/03_classification.ipynb
atulsingh0/MachineLearning
gpl-3.0
Multilabel classification
from sklearn.neighbors import KNeighborsClassifier y_train_large = (y_train >= 7) y_train_odd = (y_train % 2 == 1) y_multilabel = np.c_[y_train_large, y_train_odd] knn_clf = KNeighborsClassifier() knn_clf.fit(X_train, y_multilabel) knn_clf.predict([some_digit])
HandsOnML/code/03_classification.ipynb
atulsingh0/MachineLearning
gpl-3.0
Warning: the following cell may take a very long time (possibly hours depending on your hardware).
y_train_knn_pred = cross_val_predict(knn_clf, X_train, y_multilabel, cv=3) f1_score(y_multilabel, y_train_knn_pred, average="macro")
HandsOnML/code/03_classification.ipynb
atulsingh0/MachineLearning
gpl-3.0
Multioutput classification
noise = np.random.randint(0, 100, (len(X_train), 784)) X_train_mod = X_train + noise noise = np.random.randint(0, 100, (len(X_test), 784)) X_test_mod = X_test + noise y_train_mod = X_train y_test_mod = X_test some_index = 5500 plt.subplot(121); plot_digit(X_test_mod[some_index]) plt.subplot(122); plot_digit(y_test_mod...
HandsOnML/code/03_classification.ipynb
atulsingh0/MachineLearning
gpl-3.0
Extra material Dummy (ie. random) classifier
from sklearn.dummy import DummyClassifier dmy_clf = DummyClassifier() y_probas_dmy = cross_val_predict(dmy_clf, X_train, y_train_5, cv=3, method="predict_proba") y_scores_dmy = y_probas_dmy[:, 1] fprr, tprr, thresholdsr = roc_curve(y_train_5, y_scores_dmy) plot_roc_curve(fprr, tprr)
HandsOnML/code/03_classification.ipynb
atulsingh0/MachineLearning
gpl-3.0
KNN classifier
from sklearn.neighbors import KNeighborsClassifier knn_clf = KNeighborsClassifier(n_jobs=-1, weights='distance', n_neighbors=4) knn_clf.fit(X_train, y_train) y_knn_pred = knn_clf.predict(X_test) from sklearn.metrics import accuracy_score accuracy_score(y_test, y_knn_pred) from scipy.ndimage.interpolation import shif...
HandsOnML/code/03_classification.ipynb
atulsingh0/MachineLearning
gpl-3.0
<font color='blue'>Exercício 1</font> Monte a simulação de 1000 jogadas de um dado idôneo de 6 faces. Faça o histograma (normalizado) da frequência. a) Olhando o histograma, o que pode se dizer sobre as probabilidade de cada face? b) Discorra sobre o porque da probabilidade não ser exatamente igual à teórica.
lista = [] for i in range (1,1001): numero = randint (1,7) lista.append(numero) plt.hist(lista,6,normed = True) plt.axis([1,6,0,0.25]) plt.xlabel('Número do dado') plt.ylabel('Frequencia') plt.show()
exercicios/ex3.ipynb
renekm/CD-atualizado-
gpl-3.0
B A probabilidade não é exatamente igual a teórica porque como 1000 é um limite de vezes que se lança tecnicamente muito baixo, as probabilidades acabam ficando muito diferentes, com o aumento de vezes lançadas as possibilidades acabam se estabilizando. <font color='blue'>Exercício 2</font> Ampliando o espaço amostral...
#a soma=0 i=0 while i <= 1000: p1 = randint (1,7) p2 = randint(1,7) i +=1 if p1 + p2 == 7: soma+=1 i+=1 print(soma/i)
exercicios/ex3.ipynb
renekm/CD-atualizado-
gpl-3.0
B A probabilidade é a mesma que o item anteior que é 1/6 porque somente 1 face vai conseguir conseguir obter uma soma com 7. <font color='blue'>Exercício 3</font> Simule 10000 vezes o problema de Monty Hall¹ , usar o seguinte algoritmo: Repetir 10000 vezes: Sorteie um número de porta de 1 a 3 para ser a premiada S...
cont = 0 b = 0 for i in range (1,10000): lista = ['g','g','c'] shuffle(lista) if lista [1] == 'c': del lista[2] elif lista[2]=='c': del lista[1] else: x = randint(1,2) del lista[x] if lista[0]=='c': cont+=1 elif lista[0] != 'c': b+=1 ...
exercicios/ex3.ipynb
renekm/CD-atualizado-
gpl-3.0
1. Load the iris dataset and create a holdout set that is 50% of the data (50% in training and 50% in test). Output the results (don't worry about creating the tree visual unless you'd like to) and discuss them briefly (are they good or not?)
iris = datasets.load_iris() iris x = iris.data[:,2:] y = iris.target dt = tree.DecisionTreeClassifier() x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.5,train_size=0.5) dt = dt.fit(x_train,y_train) def measure_performance(x,y,dt, show_accuracy=True, show_classification_report=True, show_confusi...
class7/homework/najmabadi_shannon_7_1.ipynb
ledeprogram/algorithms
gpl-3.0
Nearly 95% accuracy, with 100% precision for the first species (0), and progressively less precision for the latter two species (1, 2) . 30 were classified as species 1, 26 as species 2, and 15 as species 3; though there were two falsely classified samples in both species 2 and species 3. 2. Redo the model with a 75%...
x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.25,train_size=0.75) dt = dt.fit(x_train,y_train) y_pred=dt.predict(x_test) measure_performance(x_test,y_test,dt)
class7/homework/najmabadi_shannon_7_1.ipynb
ledeprogram/algorithms
gpl-3.0
Over 97% accuracy, with again 100% precision for the first species (0), and a similar percent accuracy for the latter two species (1, 2) . 12 were classified as species 1, 14 as species 2, and 11 as species 3; and there was one falsely classified sample in species 3. There are less total samples because the testing s...
bc = datasets.load_breast_cancer() bc
class7/homework/najmabadi_shannon_7_1.ipynb
ledeprogram/algorithms
gpl-3.0
The attributes (x) are listed near the top of the dataset, and include radius, texture, perimeter, etc. The target (y) is what we are trying to predict. Here, that is whether a tumor is malignant or benign.
x = bc.data[:,:] y = bc.target x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.5,train_size=0.5) dt = dt.fit(x_train,y_train) def measure_performance(x,y,dt, show_accuracy=True, show_classification_report=True, show_confusion_matrix=True): y_pred=dt.predict(x) if show_accuracy: pr...
class7/homework/najmabadi_shannon_7_1.ipynb
ledeprogram/algorithms
gpl-3.0
4. Using the breast cancer data, create a classifier to predict the type of seed. Perform the above hold out evaluation (50-50 and 75-25) and discuss the results.
x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.25,train_size=0.75) dt = dt.fit(x_train,y_train) measure_performance(x_test,y_test,dt)
class7/homework/najmabadi_shannon_7_1.ipynb
ledeprogram/algorithms
gpl-3.0
Retrain a speech recognition model with TensorFlow Lite Model Maker <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://www.tensorflow.org/lite/models/modify/model_maker/speech_recognition"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</...
!sudo apt -y install libportaudio2 !pip install tflite-model-maker import os import glob import random import shutil import librosa import soundfile as sf from IPython.display import Audio import numpy as np import matplotlib.pyplot as plt import seaborn as sns import tensorflow as tf import tflite_model_maker as mm...
site/en-snapshot/lite/models/modify/model_maker/speech_recognition.ipynb
tensorflow/docs-l10n
apache-2.0
Prepare the dataset To train with the default speech dataset, just run all the code below as-is. But if you want to train with your own speech dataset, follow these steps: Note: The model you'll retrain expects input data to be roughly one second of audio at 44.1 kHz. Model Maker perfoms automatic resampling for the t...
use_custom_dataset = False #@param ["False", "True"] {type:"raw"}
site/en-snapshot/lite/models/modify/model_maker/speech_recognition.ipynb
tensorflow/docs-l10n
apache-2.0
Generate a background noise dataset Whether you're using the default speech dataset or a custom dataset, you should have a good set of background noises so your model can distinguish speech from other noises (including silence). Because the following background samples are provided in WAV files that are a minute long ...
tf.keras.utils.get_file('speech_commands_v0.01.tar.gz', 'http://download.tensorflow.org/data/speech_commands_v0.01.tar.gz', cache_dir='./', cache_subdir='dataset-speech', extract=True) tf.keras.utils.get_file('background_aud...
site/en-snapshot/lite/models/modify/model_maker/speech_recognition.ipynb
tensorflow/docs-l10n
apache-2.0
Note: Although there is a newer version available, we're using v0.01 of the speech commands dataset because it's a smaller download. v0.01 includes 30 commands, while v0.02 adds five more ("backward", "forward", "follow", "learn", and "visual").
# Create a list of all the background wav files files = glob.glob(os.path.join('./dataset-speech/_background_noise_', '*.wav')) files = files + glob.glob(os.path.join('./dataset-background', '*.wav')) background_dir = './background' os.makedirs(background_dir, exist_ok=True) # Loop through all files and split each in...
site/en-snapshot/lite/models/modify/model_maker/speech_recognition.ipynb
tensorflow/docs-l10n
apache-2.0
Prepare the speech commands dataset We already downloaded the speech commands dataset, so now we just need to prune the number of classes for our model. This dataset includes over 30 speech command classifications, and most of them have over 2,000 samples. But because we're using transfer learning, we don't need that m...
if not use_custom_dataset: commands = [ "up", "down", "left", "right", "go", "stop", "on", "off", "background"] dataset_dir = './dataset-speech' test_dir = './dataset-test' # Move the processed background samples shutil.move(background_dir, os.path.join(dataset_dir, 'background')) # Delete all director...
site/en-snapshot/lite/models/modify/model_maker/speech_recognition.ipynb
tensorflow/docs-l10n
apache-2.0
Prepare a custom dataset If you want to train the model with our own speech dataset, you need to upload your samples as WAV files in a ZIP (as described above) and modify the following variables to specify your dataset:
if use_custom_dataset: # Specify the ZIP file you uploaded: !unzip YOUR-FILENAME.zip # Specify the unzipped path to your custom dataset # (this path contains all the subfolders with classification names): dataset_dir = './YOUR-DIRNAME'
site/en-snapshot/lite/models/modify/model_maker/speech_recognition.ipynb
tensorflow/docs-l10n
apache-2.0
After changing the filename and path name above, you're ready to train the model with your custom dataset. In the Colab toolbar, select Runtime > Run all to run the whole notebook. The following code integrates our new background noise samples into your dataset and then separates a portion of all samples to create a te...
def move_background_dataset(dataset_dir): dest_dir = os.path.join(dataset_dir, 'background') if os.path.exists(dest_dir): files = glob.glob(os.path.join(background_dir, '*.wav')) for file in files: shutil.move(file, dest_dir) else: shutil.move(background_dir, dest_dir) if use_custom_dataset: ...
site/en-snapshot/lite/models/modify/model_maker/speech_recognition.ipynb
tensorflow/docs-l10n
apache-2.0
Play a sample To be sure the dataset looks correct, let's play at a random sample from the test set:
def get_random_audio_file(samples_dir): files = os.path.abspath(os.path.join(samples_dir, '*/*.wav')) files_list = glob.glob(files) random_audio_path = random.choice(files_list) return random_audio_path def show_sample(audio_path): audio_data, sample_rate = sf.read(audio_path) class_name = os.path.basename...
site/en-snapshot/lite/models/modify/model_maker/speech_recognition.ipynb
tensorflow/docs-l10n
apache-2.0
Define the model When using Model Maker to retrain any model, you have to start by defining a model spec. The spec defines the base model from which your new model will extract feature embeddings to begin learning new classes. The spec for this speech recognizer is based on the pre-trained BrowserFft model from TFJS. T...
spec = audio_classifier.BrowserFftSpec()
site/en-snapshot/lite/models/modify/model_maker/speech_recognition.ipynb
tensorflow/docs-l10n
apache-2.0
Load your dataset Now you need to load your dataset according to the model specifications. Model Maker includes the DataLoader API, which will load your dataset from a folder and ensure it's in the expected format for the model spec. We already reserved some test files by moving them to a separate directory, which make...
if not use_custom_dataset: train_data_ratio = 0.8 train_data = audio_classifier.DataLoader.from_folder( spec, dataset_dir, cache=True) train_data, validation_data = train_data.split(train_data_ratio) test_data = audio_classifier.DataLoader.from_folder( spec, test_dir, cache=True)
site/en-snapshot/lite/models/modify/model_maker/speech_recognition.ipynb
tensorflow/docs-l10n
apache-2.0
Load a custom dataset Note: Setting cache=True is important to make training faster (especially when the dataset must be re-sampled) but it will also require more RAM to hold the data. If you use a very large custom dataset, caching might exceed your RAM capacity.
if use_custom_dataset: train_data_ratio = 0.8 train_data = audio_classifier.DataLoader.from_folder( spec, dataset_dir, cache=True) train_data, validation_data = train_data.split(train_data_ratio) test_data = audio_classifier.DataLoader.from_folder( spec, test_dir, cache=True)
site/en-snapshot/lite/models/modify/model_maker/speech_recognition.ipynb
tensorflow/docs-l10n
apache-2.0
Train the model Now we'll use the Model Maker create() function to create a model based on our model spec and training dataset, and begin training. If you're using a custom dataset, you might want to change the batch size as appropriate for the number of samples in your train set. Note: The first epoch takes longer bec...
# If your dataset has fewer than 100 samples per class, # you might want to try a smaller batch size batch_size = 25 epochs = 25 model = audio_classifier.create(train_data, spec, validation_data, batch_size, epochs)
site/en-snapshot/lite/models/modify/model_maker/speech_recognition.ipynb
tensorflow/docs-l10n
apache-2.0
Review the model performance Even if the accuracy/loss looks good from the training output above, it's important to also run the model using test data that the model has not seen yet, which is what the evaluate() method does here:
model.evaluate(test_data)
site/en-snapshot/lite/models/modify/model_maker/speech_recognition.ipynb
tensorflow/docs-l10n
apache-2.0
View the confusion matrix When training a classification model such as this one, it's also useful to inspect the confusion matrix. The confusion matrix gives you detailed visual representation of how well your classifier performs for each classification in your test data.
def show_confusion_matrix(confusion, test_labels): """Compute confusion matrix and normalize.""" confusion_normalized = confusion.astype("float") / confusion.sum(axis=1) sns.set(rc = {'figure.figsize':(6,6)}) sns.heatmap( confusion_normalized, xticklabels=test_labels, yticklabels=test_labels, cmap='...
site/en-snapshot/lite/models/modify/model_maker/speech_recognition.ipynb
tensorflow/docs-l10n
apache-2.0
Export the model The last step is exporting your model into the TensorFlow Lite format for execution on mobile/embedded devices and into the SavedModel format for execution elsewhere. When exporting a .tflite file from Model Maker, it includes model metadata that describes various details that can later help during inf...
TFLITE_FILENAME = 'browserfft-speech.tflite' SAVE_PATH = './models' print(f'Exporing the model to {SAVE_PATH}') model.export(SAVE_PATH, tflite_filename=TFLITE_FILENAME) model.export(SAVE_PATH, export_format=[mm.ExportFormat.SAVED_MODEL, mm.ExportFormat.LABEL])
site/en-snapshot/lite/models/modify/model_maker/speech_recognition.ipynb
tensorflow/docs-l10n
apache-2.0
Run inference with TF Lite model Now your TFLite model can be deployed and run using any of the supported inferencing libraries or with the new TFLite AudioClassifier Task API. The following code shows how you can run inference with the .tflite model in Python.
# This library provides the TFLite metadata API ! pip install -q tflite_support from tflite_support import metadata import json def get_labels(model): """Returns a list of labels, extracted from the model metadata.""" displayer = metadata.MetadataDisplayer.with_model_file(model) labels_file = displayer.get_pack...
site/en-snapshot/lite/models/modify/model_maker/speech_recognition.ipynb
tensorflow/docs-l10n
apache-2.0
To observe how well the model performs with real samples, run the following code block over and over. Each time, it will fetch a new test sample and run inference with it, and you can listen to the audio sample below.
# Get a WAV file for inference and list of labels from the model tflite_file = os.path.join(SAVE_PATH, TFLITE_FILENAME) labels = get_labels(tflite_file) random_audio = get_random_audio_file(test_dir) # Ensure the audio sample fits the model input interpreter = tf.lite.Interpreter(tflite_file) input_details = interpret...
site/en-snapshot/lite/models/modify/model_maker/speech_recognition.ipynb
tensorflow/docs-l10n
apache-2.0
Download the TF Lite model Now you can deploy the TF Lite model to your mobile or embedded device. You don't need to download the labels file because you can instead retrieve the labels from .tflite file metadata, as shown in the previous inferencing example.
try: from google.colab import files except ImportError: pass else: files.download(tflite_file)
site/en-snapshot/lite/models/modify/model_maker/speech_recognition.ipynb
tensorflow/docs-l10n
apache-2.0
<span id="clustering_notebook_plat_prod">Choose Platform and Product &#9652;</span> Examine available products
# Get available products products_info = dc.list_products() # List LANDSAT 7 products print("LANDSAT 7 Products:") products_info[["platform", "name"]][products_info.platform == "LANDSAT_7"] # List LANDSAT 8 products print("LANDSAT 8 Products:") products_info[["platform", "name"]][products_info.platform == "LANDSAT_8"...
notebooks/feature_extraction/Clustering_Notebook.ipynb
ceos-seo/data_cube_notebooks
apache-2.0
Choose product and platform
product = 'ls8_usgs_sr_scene' platform = 'LANDSAT_8' collection = 'c1' level = 'l2'
notebooks/feature_extraction/Clustering_Notebook.ipynb
ceos-seo/data_cube_notebooks
apache-2.0
<span id="clustering_notebook_extents">Get the Maximum Extents of the Cube &#9652;</span>
from utils.data_cube_utilities.dc_load import get_product_extents full_lat, full_lon, min_max_dates = get_product_extents(api, platform, product) print("{}:".format(platform)) print("Lat bounds:", full_lat) print("Lon bounds:", full_lon) print("Time bounds:", min_max_dates) from utils.data_cube_utilities.dc_display...
notebooks/feature_extraction/Clustering_Notebook.ipynb
ceos-seo/data_cube_notebooks
apache-2.0
<span id="clustering_notebook_define_extents">Define the Extents of the Analysis &#9652;</span> Specify start and end dates in the same order as platforms and products
# from datetime import datetime # start_date, end_date = (datetime(2010,1,1), datetime(2011,1,1)) # start_date, end_date = dt.datetime(2014,1,1), dt.datetime(2016,1,1) start_date, end_date = dt.datetime(2014,9,1), dt.datetime(2015,3,1) date_range = (start_date, end_date)
notebooks/feature_extraction/Clustering_Notebook.ipynb
ceos-seo/data_cube_notebooks
apache-2.0
Specify an area to analyze
# Specify latitude and longitude bounds of an interesting area within the full extents # Vietnam # lat_small = (9.8, 9.85) # Area #1 # lon_small = (105.1, 105.15) # Area #1 # Ghana # Weija Reservoir - North lat_small = (5.5974, 5.6270) lon_small = (-0.3900, -0.3371)
notebooks/feature_extraction/Clustering_Notebook.ipynb
ceos-seo/data_cube_notebooks
apache-2.0
Visualize the selected area
display_map(latitude = lat_small,longitude = lon_small)
notebooks/feature_extraction/Clustering_Notebook.ipynb
ceos-seo/data_cube_notebooks
apache-2.0
<span id="clustering_notebook_retrieve_data">Load Data from the Data Cube and Create a Composite &#9652;</span> Create geographic chunks for efficient processing
from utils.data_cube_utilities.dc_chunker import create_geographic_chunks geographic_chunks = create_geographic_chunks( latitude=lat_small, longitude=lon_small, geographic_chunk_size=.05)
notebooks/feature_extraction/Clustering_Notebook.ipynb
ceos-seo/data_cube_notebooks
apache-2.0
Create a geomedian composite
from utils.data_cube_utilities.clean_mask import landsat_clean_mask_full from utils.data_cube_utilities.dc_mosaic import create_hdmedians_multiple_band_mosaic measurements = ['blue', 'green', 'red', 'nir', 'swir1', 'swir2', 'pixel_qa'] product_chunks = [] for index, chunk in enumerate(geographic_chunks): data = d...
notebooks/feature_extraction/Clustering_Notebook.ipynb
ceos-seo/data_cube_notebooks
apache-2.0
Combine the chunks to produce the final mosaic
from utils.data_cube_utilities.dc_chunker import combine_geographic_chunks final_composite = combine_geographic_chunks(product_chunks)
notebooks/feature_extraction/Clustering_Notebook.ipynb
ceos-seo/data_cube_notebooks
apache-2.0
<span id="clustering_notebook_examine_composite">Examine the Composite and Export as a GeoTIFF &#9652;</span> True color
from utils.data_cube_utilities.dc_rgb import rgb fig = plt.figure(figsize=figure_ratio(final_composite, fixed_width=8, fixed_height=8)) rgb(final_composite, bands=['red', 'green', 'blue'], fig=fig) plt.title('True Color Geomedian Composite', fontsize=16) plt.show()
notebooks/feature_extraction/Clustering_Notebook.ipynb
ceos-seo/data_cube_notebooks
apache-2.0
False color
fig = plt.figure(figsize=figure_ratio(final_composite, fixed_width=8, fixed_height=8)) rgb(final_composite, bands=['swir1', 'nir', 'red'], fig=fig) plt.title('False Color Geomedian Composite', fontsize=16) plt.show()
notebooks/feature_extraction/Clustering_Notebook.ipynb
ceos-seo/data_cube_notebooks
apache-2.0
Example of a composited swir1 band
final_composite.swir1.plot(figsize = figure_ratio(final_composite, fixed_width=10, fixed_height=10), cmap = 'magma') plt.title('SWIR1 Composite', fontsize=16) plt.show()
notebooks/feature_extraction/Clustering_Notebook.ipynb
ceos-seo/data_cube_notebooks
apache-2.0
Export to GeoTIFF
from utils.data_cube_utilities.import_export import export_slice_to_geotiff import os geotiff_dir = 'output/geotiffs/Clustering_Notebook' if not os.path.exists(geotiff_dir): os.makedirs(geotiff_dir) export_slice_to_geotiff(final_composite, '{}/final_composite.tif'.format(geotiff_dir))
notebooks/feature_extraction/Clustering_Notebook.ipynb
ceos-seo/data_cube_notebooks
apache-2.0
<span id="clustering_notebook_cluster">Perform Clustering &#9652;</span>
from utils.data_cube_utilities.aggregate import xr_scale_res from utils.data_cube_utilities.dc_clustering import kmeans_cluster_dataset, get_frequency_counts # Bands used for clustering cluster_bands = ['red', 'green', 'blue', 'swir1'] classification_4 = kmeans_cluster_dataset(final_composite, cluster_bands, n_clus...
notebooks/feature_extraction/Clustering_Notebook.ipynb
ceos-seo/data_cube_notebooks
apache-2.0
<span id="clustering_notebook_visualize">Visualize the Clustered Data &#9652;</span>
# Define standard formatting. def get_figsize_geospatial(fixed_width=8, fixed_height=14, num_cols=1, num_rows=1): return figure_ratio(final_composite, fixed_width=fixed_width, fixed_height=fixed_height, num_cols=num_cols, num_rows=num_rows...
notebooks/feature_extraction/Clustering_Notebook.ipynb
ceos-seo/data_cube_notebooks
apache-2.0
<span id="clustering_notebook_export_clustered_data">Export the Clustered Data as a GeoTIFF &#9652;</span>
from utils.data_cube_utilities.import_export import export_slice_to_geotiff if not os.path.exists(geotiff_dir): os.makedirs(geotiff_dir) output_kmeans_cluster4_file_path = os.path.join(geotiff_dir, "cluster4_kmeans.tif") output_kmeans_cluster8_file_path = os.path.join(geotiff_dir, "cluster8_kmeans.tif") outpu...
notebooks/feature_extraction/Clustering_Notebook.ipynb
ceos-seo/data_cube_notebooks
apache-2.0
Detecting Changes in Sentinel-1 Imagery (Part 2) Author: mortcanty Run me first Run the following cell to initialize the API. The output will contain instructions on how to grant this notebook access to Earth Engine using your account.
import ee # Trigger the authentication flow. ee.Authenticate() # Initialize the library. ee.Initialize()
tutorials/detecting-changes-in-sentinel-1-imagery-pt-2/index.ipynb
google/earthengine-community
apache-2.0
Datasets and Python modules One dataset will be used in the tutorial: COPERNICUS/S1_GRD_FLOAT Sentinel-1 ground range detected images The following cell imports some python modules which we will be using as we go along and enables inline graphics.
import matplotlib.pyplot as plt import numpy as np from scipy.stats import norm, gamma, f, chi2 import IPython.display as disp %matplotlib inline
tutorials/detecting-changes-in-sentinel-1-imagery-pt-2/index.ipynb
google/earthengine-community
apache-2.0
And to make use of interactive graphics, we import the folium package:
# Import the Folium library. import folium # Define a method for displaying Earth Engine image tiles to folium map. def add_ee_layer(self, ee_image_object, vis_params, name): map_id_dict = ee.Image(ee_image_object).getMapId(vis_params) folium.raster_layers.TileLayer( tiles = map_id_dict['tile_fetcher'].url_for...
tutorials/detecting-changes-in-sentinel-1-imagery-pt-2/index.ipynb
google/earthengine-community
apache-2.0
Part 2. Hypothesis testing We continue from Part 1 of the Tutorial with the area of interest aoi covering the Frankfurt International Airport and a subset aoi_sub consisting of uniform pixels within a forested region.
geoJSON = { "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": {}, "geometry": { "type": "Polygon", "coordinates": [ [ [ 8.473892211914062, 49.98081240937428 ], [ ...
tutorials/detecting-changes-in-sentinel-1-imagery-pt-2/index.ipynb
google/earthengine-community
apache-2.0
This time we filter the S1 archive to get an image collection consisting of two images acquired in the month of August, 2020. Because we are interested in change detection, it is essential that the local incidence angles be the same in both images. So now we specify both the orbit pass (ASCENDING) as well the relative...
im_coll = (ee.ImageCollection('COPERNICUS/S1_GRD_FLOAT') .filterBounds(aoi) .filterDate(ee.Date('2020-08-01'),ee.Date('2020-08-31')) .filter(ee.Filter.eq('orbitProperties_pass', 'ASCENDING')) .filter(ee.Filter.eq('relativeOrbitNumber_start', 15)) ...
tutorials/detecting-changes-in-sentinel-1-imagery-pt-2/index.ipynb
google/earthengine-community
apache-2.0
Here are the acquisition times in the collection, formatted with Python's time module:
import time acq_times = im_coll.aggregate_array('system:time_start').getInfo() [time.strftime('%x', time.gmtime(acq_time/1000)) for acq_time in acq_times]
tutorials/detecting-changes-in-sentinel-1-imagery-pt-2/index.ipynb
google/earthengine-community
apache-2.0
A ratio image Let's select the first two images and extract the VV bands, clipping them to aoi_sub,
im_list = im_coll.toList(im_coll.size()) im1 = ee.Image(im_list.get(0)).select('VV').clip(aoi_sub) im2 = ee.Image(im_list.get(1)).select('VV').clip(aoi_sub)
tutorials/detecting-changes-in-sentinel-1-imagery-pt-2/index.ipynb
google/earthengine-community
apache-2.0
Now we'll build the ratio of the VV bands and display it
ratio = im1.divide(im2) url = ratio.getThumbURL({'min': 0, 'max': 10}) disp.Image(url=url, width=800)
tutorials/detecting-changes-in-sentinel-1-imagery-pt-2/index.ipynb
google/earthengine-community
apache-2.0
As in the first part of the Tutorial, standard GEE reducers can be used to calculate a histogram, mean and variance of the ratio image:
hist = ratio.reduceRegion(ee.Reducer.fixedHistogram(0, 5, 500), aoi_sub).get('VV').getInfo() mean = ratio.reduceRegion(ee.Reducer.mean(), aoi_sub).get('VV').getInfo() variance = ratio.reduceRegion(ee.Reducer.variance(), aoi_sub).get('VV').getInfo()
tutorials/detecting-changes-in-sentinel-1-imagery-pt-2/index.ipynb
google/earthengine-community
apache-2.0
Here is a plot of the (normalized) histogram using numpy and matplotlib:
a = np.array(hist) x = a[:, 0] y = a[:, 1] / np.sum(a[:, 1]) plt.grid() plt.plot(x, y, '.') plt.show()
tutorials/detecting-changes-in-sentinel-1-imagery-pt-2/index.ipynb
google/earthengine-community
apache-2.0
This looks a bit like the gamma distribution we met in Part 1 but is in fact an F probability distribution. The F distribution is defined as the ratio of two chi square distributions, see Eq. (1.12), with $m_1$ and $m_2$ degrees of freedom. The above histogram is an $F$ distribution with $m_1=2m$ and $m_2=2m$ degrees ...
m = 5 plt.grid() plt.plot(x, y, '.', label='data') plt.plot(x, f.pdf(x, 2*m, 2*m) / 100, '-r', label='F-dist') plt.legend() plt.show()
tutorials/detecting-changes-in-sentinel-1-imagery-pt-2/index.ipynb
google/earthengine-community
apache-2.0
Checking the mean and variance, we get approximate agreement
print(mean, m/(m-1)) print(variance, m*(2*m-1)/(m-1)**2/(m-2))
tutorials/detecting-changes-in-sentinel-1-imagery-pt-2/index.ipynb
google/earthengine-community
apache-2.0
So what is so special about this distribution? When looking for changes between two co-registered Sentinel-1 images acquired at different times, it might seem natural to subtract one from the other and then examine the difference, much as we would do for instance with visual/infrared ground reflectance images. In the c...
im1 = ee.Image(im_list.get(0)).select('VV').clip(aoi) im2 = ee.Image(im_list.get(1)).select('VV').clip(aoi) ratio = im1.divide(im2) location = aoi.centroid().coordinates().getInfo()[::-1] mp = folium.Map(location=location, zoom_start=12) mp.add_ee_layer(ratio, {'min': 0, 'max': 20, 'palette': ['black',...
tutorials/detecting-changes-in-sentinel-1-imagery-pt-2/index.ipynb
google/earthengine-community
apache-2.0
We might guess that the bright pixels here are significant changes, for instance due to aircraft movements on the tarmac or vehicles moving on the highway. Of course ''significant'' doesn't necessarily imply ''interesting''. We already know Frankfurt has a busy airport and that a German Autobahn is always crowded. The ...
# Decision threshold alpha/2: dt = f.ppf(0.0005, 2*m, 2*m) # LRT statistics. q1 = im1.divide(im2) q2 = im2.divide(im1) # Change map with 0 = no change, 1 = decrease, 2 = increase in intensity. c_map = im1.multiply(0).where(q2.lt(dt), 1) c_map = c_map.where(q1.lt(dt), 2) # Mask no-change pixels. c_map = c_map.updateM...
tutorials/detecting-changes-in-sentinel-1-imagery-pt-2/index.ipynb
google/earthengine-community
apache-2.0
Most changes are within the airport or on the Autobahn. Barge movements on the Main River (upper left hand corner) are also signaled as significant changes. Note that the 'red' changes (significant increases in intensity) do not show up in the 'ratio' overlay, which displays $s_1/s_2$. Bivariate change detection Rather...
def det(im): return im.expression('b(0) * b(1)') # Number of looks. m = 5 im1 = ee.Image(im_list.get(0)).select('VV', 'VH').clip(aoi) im2 = ee.Image(im_list.get(1)).select('VV', 'VH').clip(aoi) m2logQ = det(im1).log().add(det(im2).log()).subtract( det(im1.add(im2)).log().multiply(2)).add(4*np.log(2)).multiply(...
tutorials/detecting-changes-in-sentinel-1-imagery-pt-2/index.ipynb
google/earthengine-community
apache-2.0
and then plot its histogram, comparing it with the chi square distribution scipy.stats.chi2.pdf() with two degrees of freedom:
hist = m2logQ.reduceRegion( ee.Reducer.fixedHistogram(0, 20, 200), aoi).get('VV').getInfo() a = np.array(hist) x = a[:, 0] y = a[:, 1] / np.sum(a[:, 1]) plt.plot(x, y, '.', label='data') plt.plot(x, chi2.pdf(x, 2)/10, '-r', label='chi square') plt.legend() plt.grid() plt.show()
tutorials/detecting-changes-in-sentinel-1-imagery-pt-2/index.ipynb
google/earthengine-community
apache-2.0
Looks pretty good. Note now that a small value of the LRT $Q$ in Eq. (2.15) corresponds to a large value of $-2\log{Q}$. Therefore the P value for a measurement $q$ is now the probability of getting the value $-2\log{q}$ or higher, $$ P = {\rm Prob}(-2\log{Q} \ge -2\log{q}) = 1 - {\rm Prob}(-2\log{Q} < -2\log{q}). $$ S...
geoJSON ={ "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": {}, "geometry": { "type": "Polygon", "coordinates": [ [ [ -98.2122802734375, 49.769291532628515 ], [ ...
tutorials/detecting-changes-in-sentinel-1-imagery-pt-2/index.ipynb
google/earthengine-community
apache-2.0
This is a mixed agricultural/forest area in southern Manitoba, Canada. We'll gather two images, one from the beginning of August and one from the beginning of September, 2018. A lot of harvesting takes place in this interval, so we expect some extensive changes.
im1 = ee.Image(ee.ImageCollection('COPERNICUS/S1_GRD_FLOAT') .filterBounds(aoi1) .filterDate(ee.Date('2018-08-01'), ee.Date('2018-08-31')) .filter(ee.Filter.eq('orbitProperties_pass', 'ASCENDING')) .filter(ee.Filter.eq('relativeOrbitNumber_start', 136)) ...
tutorials/detecting-changes-in-sentinel-1-imagery-pt-2/index.ipynb
google/earthengine-community
apache-2.0
Here are the acquisition times:
acq_time = im1.get('system:time_start').getInfo() print( time.strftime('%x', time.gmtime(acq_time/1000)) ) acq_time = im2.get('system:time_start').getInfo() print( time.strftime('%x', time.gmtime(acq_time/1000)) )
tutorials/detecting-changes-in-sentinel-1-imagery-pt-2/index.ipynb
google/earthengine-community
apache-2.0
Fortunately it is possible to map the chi square cumulative distribution function over an ee.Image() so that a P value image can be calculated directly. This wasn't possible in the single band case, as the F cumulative distribution is not available on the GEE. Here are the P values:
def chi2cdf(chi2, df): ''' Chi square cumulative distribution function for df degrees of freedom using the built-in incomplete gamma function gammainc() ''' return ee.Image(chi2.divide(2)).gammainc(ee.Number(df).divide(2)) # The observed test statistic image -2logq. m2logq = det(im1).log().add(det(im2).log()...
tutorials/detecting-changes-in-sentinel-1-imagery-pt-2/index.ipynb
google/earthengine-community
apache-2.0
The uniformly dark areas correspond to small or vanishing P values and signify change. The bright areas correspond to no change. Why they are not uniformly bright will be explained below. Now we set a significance threshold of $\alpha=0.01$ and display the significant changes, whereby 1% of them will be false positives...
c_map = p_value.multiply(0).where(p_value.lt(0.01), 1) crop2018 = (ee.ImageCollection('AAFC/ACI') .filter(ee.Filter.date('2018-01-01', '2018-12-01')) .first() .clip(aoi1)) mp = folium.Map(location=location, zoom_start=12) mp.add_ee_layer(crop2018, {min: 0, max: 255}, 'crop2018')...
tutorials/detecting-changes-in-sentinel-1-imagery-pt-2/index.ipynb
google/earthengine-community
apache-2.0
The major crops in the scene are soybeans (dark brown), oats (light brown), canola (light green), corn (light yellow) and winter wheat (dark gray). The wooded areas exhibit little change, while canola has evidently been extensively harvested in the interval. A note on P values Because small P values are indicative of c...
geoJSON ={ "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": {}, "geometry": { "type": "Polygon", "coordinates": [ [ [ -98.18550109863281, 49.769735012247885 ], [ ...
tutorials/detecting-changes-in-sentinel-1-imagery-pt-2/index.ipynb
google/earthengine-community
apache-2.0
So the P values of no-change measurements are uniformly distributed over $[0, 1]$ (the excess of small P values at the left can be ascribed to genuine changes within the polygon). A large P value is no more indicative of no change than a small one. Of course it has to be this way. When, for example, we set a significan...
c_map = p_value.multiply(0).where(p_value.lt(0.01), 1) diff = im2.subtract(im1) d_map = c_map.multiply(0) # Initialize the direction map to zero. d_map = d_map.where(det(diff).gt(0), 2) # All pos or neg def diffs are now labeled 2. d_map = d_map.where(diff.select(0).gt(0), 3) # Re-label pos def ...
tutorials/detecting-changes-in-sentinel-1-imagery-pt-2/index.ipynb
google/earthengine-community
apache-2.0
Now we display the changes, with positive definite red, negative definite blue, and indefinite yellow:
mp = folium.Map(location=location, zoom_start=12) mp.add_ee_layer(crop2018, {min: 0, max: 255}, 'crop2018') mp.add_ee_layer( c_map.updateMask(c_map.gt(0)), { 'min': 0, 'max': 3, 'palette': ['black', 'yellow', 'blue', 'red'] }, 'c_map') mp.add_child(folium.LayerControl())
tutorials/detecting-changes-in-sentinel-1-imagery-pt-2/index.ipynb
google/earthengine-community
apache-2.0
Activate the Environment
!conda activate asim
activitysim/examples/example_mtc/notebooks/getting_started.ipynb
synthicity/activitysim
agpl-3.0
Creating an Example Setup The example is included in the package and can be copied to a user defined location using the package's command line interface. The example includes all model steps. The command below copies the example_mtc example to a new example folder. It also changes into the new example folder so we c...
!activitysim create -e example_mtc -d example %cd example
activitysim/examples/example_mtc/notebooks/getting_started.ipynb
synthicity/activitysim
agpl-3.0
Run the Example The code below runs the example, which runs in a few minutes. The example consists of 100 synthetic households and the first 25 zones in the example model region. The full example (example_mtc_full) can be created and downloaded from the activitysim resources repository using activitysim's create comm...
!activitysim run -c configs -d data -o output
activitysim/examples/example_mtc/notebooks/getting_started.ipynb
synthicity/activitysim
agpl-3.0
Inputs and Outputs Overview An ActivitySim model requires: Configs: settings, model step expressions files, etc.​ settings.yaml - main settings file for running the model network_los.yaml - network level-of-service (skims) settings file [model].yaml - configuration file for the model step (such as auto ownership) [mod...
import os for root, dirs, files in os.walk(".", topdown=False): for name in files: print(os.path.join(root, name)) for name in dirs: print(os.path.join(root, name))
activitysim/examples/example_mtc/notebooks/getting_started.ipynb
synthicity/activitysim
agpl-3.0
Inputs Run the commands below to: * Load required Python libraries for reading data * Display the settings.yaml, including the list of models to run * Display the land_use, households, and persons tables * Display the skims
print("Load libraries.") import pandas as pd import openmatrix as omx import yaml import glob print("Display the settings file.\n") with open(r'configs/settings.yaml') as file: file_contents = yaml.load(file, Loader=yaml.FullLoader) print(yaml.dump(file_contents)) print("Display the network_los file.\n") wi...
activitysim/examples/example_mtc/notebooks/getting_started.ipynb
synthicity/activitysim
agpl-3.0
Outputs Run the commands below to: * Display the output household and person tables * Display the output tour and trip tables
print("The output pipeline contains the state of each table after each model step.") pipeline = pd.io.pytables.HDFStore('output/pipeline.h5') pipeline.keys() print("Households table after trip mode choice, which contains several calculated fields.") pipeline['/households/joint_tour_frequency'] #watch out for key chang...
activitysim/examples/example_mtc/notebooks/getting_started.ipynb
synthicity/activitysim
agpl-3.0
Other notable outputs
print("Final output accessibility table to written to CSV.") pd.read_csv("output/final_accessibility.csv") print("Joint tour participants table, which contains the person ids of joint tour participants.") pipeline['joint_tour_participants/joint_tour_participation'] print("Destination choice sample logsums table for s...
activitysim/examples/example_mtc/notebooks/getting_started.ipynb
synthicity/activitysim
agpl-3.0
Trip matrices A write_trip_matrices step at the end of the model adds boolean indicator columns to the trip table in order to assign each trip into a trip matrix and then aggregates the trip counts and writes OD matrices to OMX (open matrix) files. The coding of trips into trip matrices is done via annotation expressi...
print("trip matrices by time of day for assignment") output_files = os.listdir("output") for output_file in output_files: if "omx" in output_file: print(output_file)
activitysim/examples/example_mtc/notebooks/getting_started.ipynb
synthicity/activitysim
agpl-3.0
Tracing calculations Tracing calculations is an important part of model setup and debugging. Often times data issues, such as missing values in input data and/or incorrect submodel expression files, do not reveal themselves until a downstream submodels fails. There are two types of tracing in ActivtiySim: household a...
print("All trace files.\n") glob.glob("output/trace/*.csv") print("Trace files for auto ownership.\n") glob.glob("output/trace/auto_ownership*.csv") print("Trace chooser data for auto ownership.\n") pd.read_csv("output\\trace\\auto_ownership_simulate.simple_simulate.eval_mnl.choosers.csv") print("Trace utility expr...
activitysim/examples/example_mtc/notebooks/getting_started.ipynb
synthicity/activitysim
agpl-3.0
Run the Multiprocessor Example The command below runs the multiprocessor example, which runs in a few minutes. It uses settings inheritance to override setings in the configs folder with settings in the configs_mp folder. This allows for re-using expression files and settings files in the single and multiprocessed se...
!activitysim run -c configs_mp -c configs -d data -o output
activitysim/examples/example_mtc/notebooks/getting_started.ipynb
synthicity/activitysim
agpl-3.0
1. Corpus acquisition In this block we will work with collections of text documents. The objectives will be: Find the most important topics in the collection and assign documents to topics Analyze the structure of the collection by means of graph analysis We will work with a collection of research projects funded by ...
xmlfile = '../data/1600057.xml' with open(xmlfile,'r') as fin: print(fin.read())
TM4.DTUCourse/notebook/DTU02901_student.ipynb
ML4DS/ML4all
mit
1.1.2. Parsing XML XML is an inherently hierarchical data format, and the most natural way to represent it is with a tree. The ElementTree module has two classes for this purpose: ElementTree represents the whole XML document as a tree Element represents a single node in this tree We can import XLM data by reading an...
import xml.etree.ElementTree as ET tree = ET.parse(xmlfile) root = tree.getroot
TM4.DTUCourse/notebook/DTU02901_student.ipynb
ML4DS/ML4all
mit
or directly reading a string:
root = ET.fromstring(open(xmlfile,'r').read())
TM4.DTUCourse/notebook/DTU02901_student.ipynb
ML4DS/ML4all
mit
fromstring() parses XML from a string directly into an Element, which is the root element of the parsed tree. Other parsing functions may create an ElementTree, but we will not cover them here. As an Element, root has a tag and a dictionary of attributes:
print(root.tag) print(root.attrib)
TM4.DTUCourse/notebook/DTU02901_student.ipynb
ML4DS/ML4all
mit
It also has children nodes over which we can iterate:
for child in root: print(child.tag, child.attrib)
TM4.DTUCourse/notebook/DTU02901_student.ipynb
ML4DS/ML4all
mit
Children are nested, and we can access specific child nodes by index. We can also access the text of specified elements. For instance:
for child in root[0]: print(child.tag, child.attrib, child.text)
TM4.DTUCourse/notebook/DTU02901_student.ipynb
ML4DS/ML4all
mit