markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
Preprocess data | !gdown --id 1-8IU8qyry-yPXwQ7AXz0GHIgn19QKGZP
!gdown --id 1-J0eqf4ig7cP8bMPRgSFUejshnBFTZoq
!gdown --id 1-IIJFl4AGNr7rRax4YSQTTm7j12YJ0ya
import pandas as pd
df = pd.read_csv('thaisum.csv')
val_df = pd.read_csv('validation_set.csv')
test_df = pd.read_csv('test_set.csv')
df = pd.concat([df, val_df, test_df], axis=0)
df ... | _____no_output_____ | MIT | fine_tuning_roBERTsaikwan.ipynb | Sav-eng/roBERTsaikwan-model |
Usually tokenizing takes a lot of time, you can choose to tokenize only some part of data by uncommenting. | # %%time
tokenized_datasets = get_tokenized_dict(df, 358868, 11000, 11000)
# tokenized_datasets = get_tokenized_dict_test_val(df, 358868, 11000, 11000)
# tokenized_datasets = get_tokenized_dict_test(df, 358868, 11000, 11000)
gold_summaries = gold_summary(df, 358868, 11000, 11000) | _____no_output_____ | MIT | fine_tuning_roBERTsaikwan.ipynb | Sav-eng/roBERTsaikwan-model |
You can choose to save the data after preprocessing and load it. | # tokenized_datasets['train'].to_json('train.json', orient='records', lines=True)
# tokenized_datasets['validation'].to_json('/content/drive/MyDrive/validation_true_set.json', orient='records', lines=True)
# tokenized_datasets['test'].to_json('/content/drive/MyDrive/test_true_lower.json', orient='records', lines=True)
... | _____no_output_____ | MIT | fine_tuning_roBERTsaikwan.ipynb | Sav-eng/roBERTsaikwan-model |
Fine-tuning model | model = AutoModelForQuestionAnswering.from_pretrained(
f'airesearch/{model_name}' if model_name not in public_models else f'{model_name}',
revision='main',)
batch_size = 16
learning_rate = 4e-5
args = TrainingArguments(
f"finetune_thaiSum",
evaluation_strategy = "epoch",
learning_ra... | _____no_output_____ | MIT | fine_tuning_roBERTsaikwan.ipynb | Sav-eng/roBERTsaikwan-model |
Postprocess and metrics(BERTscore since rouge we already import at the beginning) | def post_process_index(data, raw_predictions, tokenizer, n_best_size = 20, max_answer_length=50):
all_start_logits, all_end_logits = raw_predictions
predictions = []
for start_logits, end_logits, example in zip(all_start_logits, all_end_logits, data):
start_indexes = np.argsort(start_logits)[-1 : -n_best_size... | _____no_output_____ | MIT | fine_tuning_roBERTsaikwan.ipynb | Sav-eng/roBERTsaikwan-model |
BERTScore | !pip install bert_score==0.3.7
from bert_score import score
import numpy as np
import gc
def cal_bert_score(cands, refs, get_average_f1=True):
'''
arguments: cands, refs
return array of presicion, recall, f1, presicion_average, recall_average, f1_average
if get_average == True return mean of BERTScore
'''
p... | _____no_output_____ | MIT | fine_tuning_roBERTsaikwan.ipynb | Sav-eng/roBERTsaikwan-model |
Evaluate | def evaluate_rouge(cands, refs, tokenizer):
cands_tokenized = tokenize_with_space(cands, tokenizer)
refs_tokenized = tokenize_with_space(refs, tokenizer)
r1, r2, rl = cal_rouge_score(refs_tokenized, cands_tokenized)
return r1, r2, rl
raw_predictions = trainer.predict(tokenized_datasets['test'])
predictions = po... | _____no_output_____ | MIT | fine_tuning_roBERTsaikwan.ipynb | Sav-eng/roBERTsaikwan-model |
Copyright 2018 The TensorFlow Authors.Licensed under the Apache License, Version 2.0 (the "License"); | #@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | _____no_output_____ | Apache-2.0 | samples/core/get_started/eager.ipynb | TomLisankie/tensorflow-models |
Get Started with Eager Execution Run in Google Colab View source on Github This guide uses machine learning to *categorize* Iris flowers by species. It uses [TensorFlow](https://www.tensorflow.org)'s eager execution to:1. Build a model,2. Train this model on example data, and3. Use the model to make predictions ab... | !pip install --upgrade tensorflow | _____no_output_____ | Apache-2.0 | samples/core/get_started/eager.ipynb | TomLisankie/tensorflow-models |
Configure imports and eager executionImport the required Python modules—including TensorFlow—and enable eager execution for this program. Eager execution makes TensorFlow evaluate operations immediately, returning concrete values instead of creating a [computational graph](https://www.tensorflow.org/programmers_guide/... | from __future__ import absolute_import, division, print_function
import os
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow.contrib.eager as tfe
tf.enable_eager_execution()
print("TensorFlow version: {}".format(tf.VERSION))
print("Eager execution: {}".format(tf.executing_eagerly())) | _____no_output_____ | Apache-2.0 | samples/core/get_started/eager.ipynb | TomLisankie/tensorflow-models |
The Iris classification problemImagine you are a botanist seeking an automated way to categorize each Iris flower you find. Machine learning provides many algorithms to statistically classify flowers. For instance, a sophisticated machine learning program could classify flowers based on photographs. Our ambitions are ... | train_dataset_url = "http://download.tensorflow.org/data/iris_training.csv"
train_dataset_fp = tf.keras.utils.get_file(fname=os.path.basename(train_dataset_url),
origin=train_dataset_url)
print("Local copy of the dataset file: {}".format(train_dataset_fp)) | _____no_output_____ | Apache-2.0 | samples/core/get_started/eager.ipynb | TomLisankie/tensorflow-models |
Inspect the dataThis dataset, `iris_training.csv`, is a plain text file that stores tabular data formatted as comma-separated values (CSV). Use the `head -n5` command to take a peak at the first five entries: | !head -n5 {train_dataset_fp} | _____no_output_____ | Apache-2.0 | samples/core/get_started/eager.ipynb | TomLisankie/tensorflow-models |
From this view of the dataset, notice the following:1. The first line is a header containing information about the dataset: * There are 120 total examples. Each example has four features and one of three possible label names. 2. Subsequent rows are data records, one *[example](https://developers.google.com/machine-lea... | # column order in CSV file
column_names = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species']
feature_names = column_names[:-1]
label_name = column_names[-1]
print("Features: {}".format(feature_names))
print("Label: {}".format(label_name)) | _____no_output_____ | Apache-2.0 | samples/core/get_started/eager.ipynb | TomLisankie/tensorflow-models |
Each label is associated with string name (for example, "setosa"), but machine learning typically relies on numeric values. The label numbers are mapped to a named representation, such as:* `0`: Iris setosa* `1`: Iris versicolor* `2`: Iris virginicaFor more information about features and labels, see the [ML Terminology... | class_names = ['Iris setosa', 'Iris versicolor', 'Iris virginica'] | _____no_output_____ | Apache-2.0 | samples/core/get_started/eager.ipynb | TomLisankie/tensorflow-models |
Create a `tf.data.Dataset`TensorFlow's [Dataset API](https://www.tensorflow.org/programmers_guide/datasets) handles many common cases for loading data into a model. This is a high-level API for reading data and transforming it into a form used for training. See the [Datasets Quick Start guide](https://www.tensorflow.o... | batch_size = 32
train_dataset = tf.contrib.data.make_csv_dataset(
train_dataset_fp,
batch_size,
column_names=column_names,
label_name=label_name,
num_epochs=1) | _____no_output_____ | Apache-2.0 | samples/core/get_started/eager.ipynb | TomLisankie/tensorflow-models |
The `make_csv_dataset` function returns a `tf.data.Dataset` of `(features, label)` pairs, where `features` is a dictionary: `{'feature_name': value}`With eager execution enabled, these `Dataset` objects are iterable. Let's look at a batch of features: | features, labels = next(iter(train_dataset))
features | _____no_output_____ | Apache-2.0 | samples/core/get_started/eager.ipynb | TomLisankie/tensorflow-models |
Notice that like-features are grouped together, or *batched*. Each example row's fields are appended to the corresponding feature array. Change the `batch_size` to set the number of examples stored in these feature arrays.You can start to see some clusters by plotting a few features from the batch: | plt.scatter(features['petal_length'],
features['sepal_length'],
c=labels,
cmap='viridis')
plt.xlabel("Petal length")
plt.ylabel("Sepal length"); | _____no_output_____ | Apache-2.0 | samples/core/get_started/eager.ipynb | TomLisankie/tensorflow-models |
To simplify the model building step, create a function to repackage the features dictionary into a single array with shape: `(batch_size, num_features)`.This function uses the [tf.stack](https://www.tensorflow.org/api_docs/python/tf/stack) method which takes values from a list of tensors and creates a combined tensor a... | def pack_features_vector(features, labels):
"""Pack the features into a single array."""
features = tf.stack(list(features.values()), axis=1)
return features, labels | _____no_output_____ | Apache-2.0 | samples/core/get_started/eager.ipynb | TomLisankie/tensorflow-models |
Then use the [tf.data.Dataset.map](https://www.tensorflow.org/api_docs/python/tf/data/dataset/map) method to pack the `features` of each `(features,label)` pair into the training dataset: | train_dataset = train_dataset.map(pack_features_vector) | _____no_output_____ | Apache-2.0 | samples/core/get_started/eager.ipynb | TomLisankie/tensorflow-models |
The features element of the `Dataset` are now arrays with shape `(batch_size, num_features)`. Let's look at the first few examples: | features, labels = next(iter(train_dataset))
print(features[:5]) | _____no_output_____ | Apache-2.0 | samples/core/get_started/eager.ipynb | TomLisankie/tensorflow-models |
Select the type of model Why model?A *[model](https://developers.google.com/machine-learning/crash-course/glossarymodel)* is the relationship between features and the label. For the Iris classification problem, the model defines the relationship between the sepal and petal measurements and the predicted Iris species.... | model = tf.keras.Sequential([
tf.keras.layers.Dense(10, activation="relu", input_shape=(4,)), # input shape required
tf.keras.layers.Dense(10, activation="relu"),
tf.keras.layers.Dense(3)
]) | _____no_output_____ | Apache-2.0 | samples/core/get_started/eager.ipynb | TomLisankie/tensorflow-models |
The *[activation function](https://developers.google.com/machine-learning/crash-course/glossaryactivation_function)* determines the output shape of each node in the layer. These non-linearities are important—without them the model would be equivalent to a single layer. There are many [available activations](https://www... | predictions = model(features)
predictions[:5] | _____no_output_____ | Apache-2.0 | samples/core/get_started/eager.ipynb | TomLisankie/tensorflow-models |
Here, each example returns a [logit](https://developers.google.com/machine-learning/crash-course/glossarylogit) for each class. To convert these logits to a probability for each class, use the [softmax](https://developers.google.com/machine-learning/crash-course/glossarysoftmax) function: | tf.nn.softmax(predictions[:5]) | _____no_output_____ | Apache-2.0 | samples/core/get_started/eager.ipynb | TomLisankie/tensorflow-models |
Taking the `tf.argmax` across classes gives us the predicted class index. But, the model hasn't been trained yet, so these aren't good predictions. | print("Prediction: {}".format(tf.argmax(predictions, axis=1)))
print(" Labels: {}".format(labels)) | _____no_output_____ | Apache-2.0 | samples/core/get_started/eager.ipynb | TomLisankie/tensorflow-models |
Train the model*[Training](https://developers.google.com/machine-learning/crash-course/glossarytraining)* is the stage of machine learning when the model is gradually optimized, or the model *learns* the dataset. The goal is to learn enough about the structure of the training dataset to make predictions about unseen d... | def loss(model, x, y):
y_ = model(x)
return tf.losses.sparse_softmax_cross_entropy(labels=y, logits=y_)
l = loss(model, features, labels)
print("Loss test: {}".format(l)) | _____no_output_____ | Apache-2.0 | samples/core/get_started/eager.ipynb | TomLisankie/tensorflow-models |
Use the [tf.GradientTape](https://www.tensorflow.org/api_docs/python/tf/GradientTape) context to calculate the *[gradients](https://developers.google.com/machine-learning/crash-course/glossarygradient)* used to optimize our model. For more examples of this, see the [eager execution guide](https://www.tensorflow.org/pro... | def grad(model, inputs, targets):
with tf.GradientTape() as tape:
loss_value = loss(model, inputs, targets)
return loss_value, tape.gradient(loss_value, model.trainable_variables) | _____no_output_____ | Apache-2.0 | samples/core/get_started/eager.ipynb | TomLisankie/tensorflow-models |
Create an optimizerAn *[optimizer](https://developers.google.com/machine-learning/crash-course/glossaryoptimizer)* applies the computed gradients to the model's variables to minimize the `loss` function. You can think of the loss function as a curved surface (see Figure 3) and we want to find its lowest point by walki... | optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
global_step = tf.train.get_or_create_global_step() | _____no_output_____ | Apache-2.0 | samples/core/get_started/eager.ipynb | TomLisankie/tensorflow-models |
We'll use this to calculate a single optimization step: | loss_value, grads = grad(model, features, labels)
print("Step: {}, Initial Loss: {}".format(global_step.numpy(),
loss_value.numpy()))
optimizer.apply_gradients(zip(grads, model.variables), global_step)
print("Step: {}, Loss: {}".format(global_step.numpy(),
... | _____no_output_____ | Apache-2.0 | samples/core/get_started/eager.ipynb | TomLisankie/tensorflow-models |
Training loopWith all the pieces in place, the model is ready for training! A training loop feeds the dataset examples into the model to help it make better predictions. The following code block sets up these training steps:1. Iterate each *epoch*. An epoch is one pass through the dataset.2. Within an epoch, iterate o... | ## Note: Rerunning this cell uses the same model variables
# keep results for plotting
train_loss_results = []
train_accuracy_results = []
num_epochs = 201
for epoch in range(num_epochs):
epoch_loss_avg = tfe.metrics.Mean()
epoch_accuracy = tfe.metrics.Accuracy()
# Training loop - using batches of 32
for x,... | _____no_output_____ | Apache-2.0 | samples/core/get_started/eager.ipynb | TomLisankie/tensorflow-models |
Visualize the loss function over time While it's helpful to print out the model's training progress, it's often *more* helpful to see this progress. [TensorBoard](https://www.tensorflow.org/programmers_guide/summaries_and_tensorboard) is a nice visualization tool that is packaged with TensorFlow, but we can create bas... | fig, axes = plt.subplots(2, sharex=True, figsize=(12, 8))
fig.suptitle('Training Metrics')
axes[0].set_ylabel("Loss", fontsize=14)
axes[0].plot(train_loss_results)
axes[1].set_ylabel("Accuracy", fontsize=14)
axes[1].set_xlabel("Epoch", fontsize=14)
axes[1].plot(train_accuracy_results); | _____no_output_____ | Apache-2.0 | samples/core/get_started/eager.ipynb | TomLisankie/tensorflow-models |
Evaluate the model's effectivenessNow that the model is trained, we can get some statistics on its performance.*Evaluating* means determining how effectively the model makes predictions. To determine the model's effectiveness at Iris classification, pass some sepal and petal measurements to the model and ask the model... | test_url = "http://download.tensorflow.org/data/iris_test.csv"
test_fp = tf.keras.utils.get_file(fname=os.path.basename(test_url),
origin=test_url)
test_dataset = tf.contrib.data.make_csv_dataset(
train_dataset_fp,
batch_size,
column_names=column_names,
label_name='sp... | _____no_output_____ | Apache-2.0 | samples/core/get_started/eager.ipynb | TomLisankie/tensorflow-models |
Evaluate the model on the test datasetUnlike the training stage, the model only evaluates a single [epoch](https://developers.google.com/machine-learning/glossary/epoch) of the test data. In the following code cell, we iterate over each example in the test set and compare the model's prediction against the actual labe... | test_accuracy = tfe.metrics.Accuracy()
for (x, y) in test_dataset:
logits = model(x)
prediction = tf.argmax(logits, axis=1, output_type=tf.int32)
test_accuracy(prediction, y)
print("Test set accuracy: {:.3%}".format(test_accuracy.result())) | _____no_output_____ | Apache-2.0 | samples/core/get_started/eager.ipynb | TomLisankie/tensorflow-models |
We can see on the last batch, for example, the model is usually correct: | tf.stack([y,prediction],axis=1) | _____no_output_____ | Apache-2.0 | samples/core/get_started/eager.ipynb | TomLisankie/tensorflow-models |
Use the trained model to make predictionsWe've trained a model and "proven" that it's good—but not perfect—at classifying Iris species. Now let's use the trained model to make some predictions on [unlabeled examples](https://developers.google.com/machine-learning/glossary/unlabeled_example); that is, on examples that ... | predict_dataset = tf.convert_to_tensor([
[5.1, 3.3, 1.7, 0.5,],
[5.9, 3.0, 4.2, 1.5,],
[6.9, 3.1, 5.4, 2.1]
])
predictions = model(predict_dataset)
for i, logits in enumerate(predictions):
class_idx = tf.argmax(logits).numpy()
p = tf.nn.softmax(logits)[class_idx]
name = class_names[class_idx]
prin... | _____no_output_____ | Apache-2.0 | samples/core/get_started/eager.ipynb | TomLisankie/tensorflow-models |
How to make the perfect time-lapse of the EarthThis tutorial shows a detail coverage of making time-lapse animations from satellite imagery like a pro. Table of Contents0. Prerequisites1. Removing clouds2. Applying co-registration3. Large Area Example4. Split ImageNote: This notebook requires an installation of additi... | %load_ext autoreload
%autoreload 2
import datetime as dt
import json
import os
import subprocess
from concurrent.futures import ProcessPoolExecutor
from datetime import date, datetime, time, timedelta
from functools import partial
from glob import glob
import ffmpeg
import geopandas as gpd
import imageio
import matpl... | _____no_output_____ | MIT | batch-processing/how_to_timelapse/how_to_timelapse.ipynb | j-desloires/eo-learn-examples |
0. PrerequisitesIn order to set everything up and make the credentials work, please check [this notebook](https://github.com/sentinel-hub/eo-learn/blob/master/examples/io/SentinelHubIO.ipynb). | class AnimateTask(EOTask):
def __init__(self, image_dir, out_dir, out_name, feature=(FeatureType.DATA, 'RGB'), scale_factor=2.5, duration=3, dpi=150, pad_inches=None, shape=None):
self.image_dir = image_dir
self.out_name = out_name
self.out_dir = out_dir
self.feature = feature
... | _____no_output_____ | MIT | batch-processing/how_to_timelapse/how_to_timelapse.ipynb | j-desloires/eo-learn-examples |
1. Removing clouds | # https://twitter.com/Valtzen/status/1270269337061019648
bbox = BBox(bbox=[-73.558102,45.447728,-73.488750,45.491908], crs=CRS.WGS84)
resolution = 10
time_interval = ('2018-01-01', '2020-01-01')
print(f'Image size: {bbox_to_dimensions(bbox, resolution)}')
geom, crs = bbox.geometry, bbox.crs
wgs84_geometry = Geometry(g... | _____no_output_____ | MIT | batch-processing/how_to_timelapse/how_to_timelapse.ipynb | j-desloires/eo-learn-examples |
2. Applying co-registration | bbox = BBox(bbox=[34.716, 30.950, 34.743, 30.975], crs=CRS.WGS84)
resolution = 10
time_interval = ('2020-01-01', '2021-01-01')
print(f'BBox size: {bbox_to_dimensions(bbox, resolution)}')
geom, crs = bbox.geometry, bbox.crs
wgs84_geometry = Geometry(geom, crs).transform(CRS.WGS84)
geometry_center = wgs84_geometry.geome... | _____no_output_____ | MIT | batch-processing/how_to_timelapse/how_to_timelapse.ipynb | j-desloires/eo-learn-examples |
3. Large Area Example | bbox = BBox(bbox=[21.4,-20.0,23.9,-18.0], crs=CRS.WGS84)
time_interval = ('2017-09-01', '2019-04-01')
# time_interval = ('2017-09-01', '2017-10-01')
resolution = 640
print(f'BBox size: {bbox_to_dimensions(bbox, resolution)}')
geom, crs = bbox.geometry, bbox.crs
wgs84_geometry = Geometry(geom, crs).transform(CRS.WGS84)... | _____no_output_____ | MIT | batch-processing/how_to_timelapse/how_to_timelapse.ipynb | j-desloires/eo-learn-examples |
4. Split Image | bbox = BBox(bbox=[21.3,-20.0,24.0,-18.0], crs=CRS.WGS84)
time_interval = ('2018-09-01', '2020-04-01')
resolution = 120
bbox_splitter = BBoxSplitter([bbox.geometry], bbox.crs, (6,5))
bbox_list = np.array(bbox_splitter.get_bbox_list())
info_list = np.array(bbox_splitter.get_info_list())
print(f'{len(bbox_list)} patches ... | _____no_output_____ | MIT | batch-processing/how_to_timelapse/how_to_timelapse.ipynb | j-desloires/eo-learn-examples |
ROC curve | from sklearn.datasets import make_classification
features,target = make_classification(n_samples=10000,
n_features=10,
n_classes=2,
n_informative=3,
random_state=3)
from sk... | _____no_output_____ | MIT | Machine Learning Cookbook/Chapter 11 Model Evaluation.ipynb | sonwanesuresh95/Books-to-notebooks |
Visualizing confusion matrix | iris = sklearn.datasets.load_iris()
X = iris.data
y = iris.target
X_train, X_test, y_train,y_test = train_test_split(X,y,test_size=0.1)
clf = LogisticRegression()
preds = clf.fit(X_train,y_train).predict(X_test)
from sklearn.metrics import confusion_matrix
conf = confusion_matrix(y_test,preds)
import seaborn as sns
sns... | _____no_output_____ | MIT | Machine Learning Cookbook/Chapter 11 Model Evaluation.ipynb | sonwanesuresh95/Books-to-notebooks |
训练PNet | #导入公共文件
import os
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torchvision
import torchvision.transforms as transforms
from torch.autograd import Variable
import sys
sys.path.append('../')
# add other package
import numpy as np
import pandas as pd
import matplo... | train Pnet Process:...
append flipped images to imdb 72129
2020-05-21 23:53:50.921667 : Epoch: 0, Step: 0, accuracy: 0.57535696, det loss: 0.88428044, bbox loss: 0.18741345, all_loss: 0.9779872, lr:0.01
2020-05-21 23:53:59.577856 : Epoch: 0, Step: 10, accuracy: 0.94787234, det loss: 0.18041657, bbox loss: 0.046751834,... | MIT | train_pnet/train_Pnet.ipynb | ysf465639310/PYTORCH_MTCNN |
Example that generates nans | train_X, test_X,_,_ = get_iris_data()
# train_X = train_X[:,1:5]
# test_X = test_X[:,1:5]
inds = np.random.choice(train_X.shape[0], 3, replace=False)
data = train_X[inds,:]
test_in = test_X[10:11,:]
x_size = train_X.shape[1] # Number of input nodes: 4 features and 1 bias
X = tf.placeholder("float", shape=[None, x_siz... | [[1. 5.7 2.9 4.2 1.3]
[1. 7.6 3. 6.6 2.1]
[1. 5.6 3. 4.5 1.5]
[1. 5.1 3.5 1.4 0.2]
[1. 7.7 2.8 6.7 2. ]
[1. 5.8 2.7 4.1 1. ]
[1. 5.2 3.4 1.4 0.2]
[1. 5. 3.5 1.3 0.3]
[1. 5.1 3.8 1.9 0.4]
[1. 5. 2. 3.5 1. ]
[1. 6.3 2.7 4.9 1.8]
[1. 4.8 3.4 1.9 0.2]
[1. 5. 3. 1.6 0.2]
[1. 5.1 3.3 1.7 0.5... | MIT | notebooks/deep_explainer/Explain Multiply and Division Models defined in Tensorflow.ipynb | ekrim/shap |
Multiplication | # yhat = tf.multiply(X[:,0:1],X)
# yhat = tf.multiply(X,X[:,0:1])
yhat = tf.multiply(X,X)
model = (X,yhat)
e = shap.DeepExplainer(model, data)
shap_values = e.shap_values(test_in)
sums = np.array([shap_values[i].sum() for i in range(len(shap_values))])
sess = tf.Session()
diff = sess.run(model[1], feed_dict={model[0]: ... | [ 0. 11.59333391 1.03666701 14.87333215 2.50333347]
[ 0. 11.593332 1.0366669 14.87333 2.5033336]
| MIT | notebooks/deep_explainer/Explain Multiply and Division Models defined in Tensorflow.ipynb | ekrim/shap |
Division | # yhat = tf.div(X,X[:,0:1]) # These examples don't work
# yhat = tf.div(X[:,0:1],X) # These examples don't work
# yhat = tf.div(X[:,0:2],X[:,2:4])
yhat = tf.div(X,X)
model = (X,yhat)
e = shap.DeepExplainer(model, data)
shap_values = e.shap_values(test_in)
sums = np.array([shap_values[i].sum() for i in range(len(shap_va... | [0.00000000e+00 2.98023224e-09 9.93410746e-09 0.00000000e+00
0.00000000e+00]
[0. 0. 0. 0. 0.]
| MIT | notebooks/deep_explainer/Explain Multiply and Division Models defined in Tensorflow.ipynb | ekrim/shap |
Segmenting and Clustering Neighborhoods in Toronto In this project we explore, segment, and cluster the neighborhoods in the city of Toronto. Since the data is not available in the Internet on a simple presentation, we have to scrape a Wikipedia page wrangle the data, clean it, and then read it into a structured for... | import numpy as np # library to handle data in a vectorized manner
import pandas as pd # library for data analsysis
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
import json # library to handle JSON files
#!conda install -c conda-forge geopy --yes # uncomment this line if you hav... | _____no_output_____ | Unlicense | Toronto.ipynb | Claudia-Perez-Ruisanchez/claudia-perez-ruisanchez.github.io |
Scraping the DataUse the Notebook to build the code to scrape the following Wikipedia page, https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M, in order to obtain the data that is in the table of postal codes and to transform the data into a pandas dataframe like the one shown below: | toronto='https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M'
df = pd.read_html(toronto, header=0)[0]
df.head() | _____no_output_____ | Unlicense | Toronto.ipynb | Claudia-Perez-Ruisanchez/claudia-perez-ruisanchez.github.io |
Eliminating cells with a borough that is Not assignedOnly process the cells that have an assigned borough. Ignore cells with a borough that is Not assigned. | df.drop(df[df['Borough']=="Not assigned"].index,axis=0, inplace=True) | _____no_output_____ | Unlicense | Toronto.ipynb | Claudia-Perez-Ruisanchez/claudia-perez-ruisanchez.github.io |
Grouping by Postal CodeMore than one neighborhood can exist in one postal code area. For example, in the table on the Wikipedia page, you will notice that M5A is listed twice and has two neighborhoods: Harbourfront and Regent Park. These two rows will be combined into one row with the neighborhoods separated with a co... | df1=df.groupby('Postcode')['Neighbourhood'].agg(lambda x: ','.join(x))
df3=pd.DataFrame(df1)
df3.reset_index().head()
df2=df.groupby('Postcode')['Borough'].unique()
df4=pd.DataFrame(df2)
df4.reset_index().head()
df4['Borough']=[df4['Borough'][i][0] for i in range(df4.shape[0])]
df4.reset_index().head()
df4['Neighbour... | _____no_output_____ | Unlicense | Toronto.ipynb | Claudia-Perez-Ruisanchez/claudia-perez-ruisanchez.github.io |
Including the Latitude and Longitude to the DataframeNow in order to utilize the Foursquare location data, we need to get the latitude and the longitude coordinates of each neighborhood. | coords=r'http://cocl.us/Geospatial_data'
coord_df=pd.read_csv(coords)
df4['Latitude']=coord_df['Latitude'].values
df4['Longitude']=coord_df['Longitude'].values
df4.reset_index().head() | _____no_output_____ | Unlicense | Toronto.ipynb | Claudia-Perez-Ruisanchez/claudia-perez-ruisanchez.github.io |
Explore and cluster the neighborhoods in Toronto. | import folium
CLIENT_ID = 'IVUX2ATVRIVIAT3MYAOI3BNB0N5X2BCPEGK3W0FCX5RNN1HN' # my Foursquare ID
CLIENT_SECRET = '1UKWCBE54WZK50IHDYJXAK3GJCXPGQELW5QE30LXCGRA4MG2' # my Foursquare Secret
VERSION = '20180605' # Foursquare API version
print('Your credentails:')
print('CLIENT_ID: ' + CLIENT_ID)
print('CLIENT_SECRET:' + C... | There are 272 uniques categories.
| Unlicense | Toronto.ipynb | Claudia-Perez-Ruisanchez/claudia-perez-ruisanchez.github.io |
Encoding the variables | # one hot encoding
toronto_onehot = pd.get_dummies(toronto_venues[['Venue Category']], prefix="", prefix_sep="")
# add neighborhood column back to dataframe
toronto_onehot['Neighbourhood'] = toronto_venues['Neighbourhood']
# move neighborhood column to the first column
fixed_columns = [toronto_onehot.columns[-1]] + ... | _____no_output_____ | Unlicense | Toronto.ipynb | Claudia-Perez-Ruisanchez/claudia-perez-ruisanchez.github.io |
K Clusters | # set number of clusters
kclusters = 7
toronto_grouped_clustering = toronto_grouped.drop('Neighbourhood', 1)
# run k-means clustering
kmeans = KMeans(n_clusters=kclusters, random_state=0).fit(toronto_grouped_clustering)
# check cluster labels generated for each row in the dataframe
kmeans.labels_[0:10]
# add cluste... | _____no_output_____ | Unlicense | Toronto.ipynb | Claudia-Perez-Ruisanchez/claudia-perez-ruisanchez.github.io |
import pandas as pd
import random
import re
import requests
import time
from tqdm.notebook import tqdm
pd.set_option('display.max_rows', None)
%pip install random_user_agent
from random_user_agent.user_agent import UserAgent
user_agent_rotator = UserAgent()
club_id = 23212 # Wake&Run
home_parkrun = 'Kuzminki'
headers... | _____no_output_____ | MIT | clubmates.ipynb | vol1ura/parkrun_analysis | |
Одноклубники, не бегавшие на домашнем паркране: | outer_home_list.shift(1, fill_value='________Фамилия_Имя___') | _____no_output_____ | MIT | clubmates.ipynb | vol1ura/parkrun_analysis |
Полный список одноклубников: | full_list.apply(last_name_first).sort_values().reset_index(drop=True).shift(1, fill_value='________Фамилия_Имя___') | _____no_output_____ | MIT | clubmates.ipynb | vol1ura/parkrun_analysis |
_____no_output_____ | Apache-2.0 | tensorflow_ml_model_example.ipynb | bavincen/notebooks | ||
Stats Scarcity Plot | import holoviews as hv
import hvplot.pandas
from analysis.utils.constants import stats_counts
rating_cols = ["overall"]
summary_data = (
pd.concat([player_stats[stats_counts], player_ratings[rating_cols]], axis=1)
.sort_values(by="overall", ascending=False)
.round(2)
.reset_index()
)
summary_data["rank... | _____no_output_____ | MIT | analysis/notebooks/strategy_analysis.ipynb | kangliu47/espn-api |
Component Scatter | x_cols = ["AST", "FTR"]
y_cols = ["BLK", "FGR"]
salary_threshold = 35
plot_data = player_ratings.copy().reset_index()
plot_data["x_data"] = plot_data[x_cols].sum(axis=1)
plot_data["y_data"] = plot_data[y_cols].sum(axis=1)
plot_data["strategy_focus"] = plot_data[x_cols + y_cols].sum(axis=1)
from analysis.visualization... | _____no_output_____ | MIT | analysis/notebooks/strategy_analysis.ipynb | kangliu47/espn-api |
Target Players Salary Projection Plot | player_ratings.stats_type.value_counts()
plot_data = player_ratings.reset_index().copy()
plot_data["rank"] = plot_data.index + 1
overall_scatter = plot_data.hvplot.scatter(
x="rank", y="overall", c="overall", s=50, hover_cols=["name", "overall"],
)
overall_line = plot_data.hvplot.line(
x="rank", y="overall", h... | _____no_output_____ | MIT | analysis/notebooks/strategy_analysis.ipynb | kangliu47/espn-api |
Installing important modules for proper functioning. | !pip install tld | Collecting tld
Downloading tld-0.12.6-py37-none-any.whl (412 kB)
|████████████████████████████████| 412 kB 601 kB/s
[?25hInstalling collected packages: tld
Successfully installed tld-0.12.6
[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour w... | MIT | Malicious URL identifier/malicious-url-detection.ipynb | aayushkumar20/Kaggle-datasets-based-models |
Importing all required modules | import re
import seaborn as sns
import matplotlib.pyplot as plt
from colorama import Fore
from urllib.parse import urlparse
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, classification_report, accuracy_score
from sklearn.tree import DecisionTreeClassifier
from sklear... | _____no_output_____ | MIT | Malicious URL identifier/malicious-url-detection.ipynb | aayushkumar20/Kaggle-datasets-based-models |
Reading the contents from the imported (csv) file provided by the Kaggle | data = pd.read_csv('/kaggle/input/malicious-urls-dataset/malicious_phish.csv')
data.head()
data.isnull().sum()
count = data.type.value_counts()
count | _____no_output_____ | MIT | Malicious URL identifier/malicious-url-detection.ipynb | aayushkumar20/Kaggle-datasets-based-models |
Checking data types Counting the numbers of phising, malware, etc types of links from the given csv files | sns.barplot(x=count.index, y=count)
plt.xlabel('Types of links')
plt.ylabel('Counts'); | _____no_output_____ | MIT | Malicious URL identifier/malicious-url-detection.ipynb | aayushkumar20/Kaggle-datasets-based-models |
Representing the types of links based on their categories and types removing 'www" from the given dataset | data['url'] = data['url'].replace('www.', '', regex=True)
data | _____no_output_____ | MIT | Malicious URL identifier/malicious-url-detection.ipynb | aayushkumar20/Kaggle-datasets-based-models |
Removing (WWW) from the given list and allowing only http:// | rem = {"Category": {"benign": 0, "defacement": 1, "phishing":2, "malware":3}}
data['Category'] = data['type']
data = data.replace(rem)
data['url_len'] = data['url'].apply(lambda x: len(str(x)))
def process_tld(url):
try:
res = get_tld(url, as_object = True, fail_silently=False,fix_protocol=True)
pri... | _____no_output_____ | MIT | Malicious URL identifier/malicious-url-detection.ipynb | aayushkumar20/Kaggle-datasets-based-models |
👇 extracting number of feature = ['@','?','-','=','.','','%','+','$','!','*',',','//'] from given data set. | feature = ['@','?','-','=','.','#','%','+','$','!','*',',','//']
for a in feature:
data[a] = data['url'].apply(lambda i: i.count(a))
def abnormal_url(url):
hostname = urlparse(url).hostname
hostname = str(hostname)
match = re.search(hostname, url)
if match:
return 1
else:
return ... | _____no_output_____ | MIT | Malicious URL identifier/malicious-url-detection.ipynb | aayushkumar20/Kaggle-datasets-based-models |
Training the model for realtime use | def digit_count(url):
digits = 0
for i in url:
if i.isnumeric():
digits = digits + 1
return digits
data['digits']= data['url'].apply(lambda i: digit_count(i))
def letter_count(url):
letters = 0
for i in url:
if i.isalpha():
letters = letters + 1
return let... | _____no_output_____ | MIT | Malicious URL identifier/malicious-url-detection.ipynb | aayushkumar20/Kaggle-datasets-based-models |
Step 3 - Twitter Data https://twitter.com/marswxreport?lang=en - Visit the Mars Weather twitter account here and scrape the latest Mars weather tweet from the page. Save the tweet text for the weather report as a variable called mars_weather. | url = 'https://twitter.com/marswxreport?lang=en'
browser.visit(url)
twitter_html = browser.html
soup = bs(twitter_html, "html.parser")
mars_weather = soup.find('p', class_="TweetTextSize TweetTextSize--normal js-tweet-text tweet-text").text
print(mars_weather) | Sol 2169 (2018-09-12), high -10C/14F, low -70C/-93F, pressure at 8.82 hPa, daylight 05:41-17:58
| ADSL | .ipynb_checkpoints/mission_to_mars-checkpoint.ipynb | cgrinstead12/Mission-to-Mars |
Mars FactsVisit the Mars Facts webpage here and use Pandas to scrape the table containing facts about the planet including Diameter, Mass, etc.Use Pandas to convert the data to a HTML table string. | url = "https://space-facts.com/mars/"
browser.visit(url)
facts_html = browser.html
soup = bs(facts_html, "html.parser")
mars_dict = {}
results = soup.find('tbody').find_all('tr')
for result in results:
column_description = result.find('td', class_="column-1").text
column_fact = result.find('td', class_="column-... | _____no_output_____ | ADSL | .ipynb_checkpoints/mission_to_mars-checkpoint.ipynb | cgrinstead12/Mission-to-Mars |
Mars Hemispheres Visit the USGS Astrogeology site here to obtain high resolution images for each of Mar's hemispheres. | executable_path = {"executable_path":"C:/Users/cgrinstead12/Desktop/Mission to Mars/chromedriver.exe"}
browser = Browser("chrome", **executable_path, headless = False)
url = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'
hemispheres = ['Cerberus Hemisphere Enhanced',
... | {'Cerberus Hemisphere Enhanced': 'http://astropedia.astrogeology.usgs.gov/download/Mars/Viking/cerberus_enhanced.tif/full.jpg', 'Schiaparelli Hemisphere Enhanced': 'http://astropedia.astrogeology.usgs.gov/download/Mars/Viking/schiaparelli_enhanced.tif/full.jpg', 'Syrtis Major Hemisphere Enhanced': 'http://astropedia.as... | ADSL | .ipynb_checkpoints/mission_to_mars-checkpoint.ipynb | cgrinstead12/Mission-to-Mars |
Lab 4: Functions and Visualizations Welcome to Lab 4! This week, we'll learn about functions, table methods such as `apply`, and how to generate visualizations! Recommended Reading:* [Applying a Function to a Column](https://www.inferentialthinking.com/chapters/08/1/applying-a-function-to-a-column.html)* [Visualizatio... | import numpy as np
from datascience import *
# These lines set up graphing capabilities.
import matplotlib
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
import warnings
warnings.simplefilter('ignore', FutureWarning)
from ipywidgets import interact, interactive, fixed, interact_ma... | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
**Deadline**: If you are not attending lab physically, you have to complete this lab and submit by Wednesday, February 12th before 8:59 A.M. in order to receive lab credit. Otherwise, please attend the lab you are enrolled in, get checked off with your (u)GSI or learning assistant **AND** submit this assignment by the ... | ...
"""" Converts a proportion to a percentage"""
factor = ...
...
twenty_percent = ...
twenty_percent
grader.check("q11") | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
Like you’ve done with built-in functions in previous labs (max, abs, etc.), you can pass in named values as arguments to your function.**Question 1.2.** Use `to_percentage` again to convert the proportion named `a_proportion` (defined below) to a percentage called `a_percentage`.*Note:* You don't need to define `to_per... | a_proportion = 2**(.5) / 2
a_percentage = ...
a_percentage
grader.check("q12") | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
Here's something important about functions: the names assigned *within* a function body are only accessible within the function body. Once the function has returned, those names are gone. So even if you created a variable called `factor` and defined `factor = 100` inside of the body of the `to_percentage` function and... | # You should see an error when you run this. (If you don't, you might
# have defined factor somewhere above.)
factor | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
As we've seen with built-in functions, functions can also take strings (or arrays, or tables) as arguments, and they can return those things, too.**Question 1.3.** Define a function called `disemvowel`. It should take a single string as its argument. (You can call that argument whatever you want.) It should return a... | def disemvowel(a_string):
"""Removes all vowels from a string."""
...
# An example call to your function. (It's often helpful to run
# an example call from time to time while you're writing a function,
# to see how it currently works.)
disemvowel("Can you read this without vowels?")
grader.check("q13") | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
Calls on calls on callsJust as you write a series of lines to build up a complex computation, it's useful to define a series of small functions that build on each other. Since you can write any code inside a function's body, you can call other functions you've written.If a function is a like a recipe, defining a func... | def num_non_vowels(a_string):
"""The number of characters in a string, minus the vowels."""
...
# Try calling your function yourself to make sure the output is what
# you expect. You can also use the interact function in the next cell if you'd like.
grader.check("q14") | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
Functions can also encapsulate code that *displays output* instead of computing a value. For example, if you call `print` inside a function, and then call that function, something will get printed.The `movies_by_year` dataset in the textbook has information about movie sales in recent years. Suppose you'd like to disp... | movies_by_year = Table.read_table("movies_by_year.csv")
rank = 5
fifth_from_top_movie_year = movies_by_year.sort("Total Gross", descending=True).column("Year").item(rank-1)
print("Year number", rank, "for total gross movie sales was:", fifth_from_top_movie_year) | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
After writing this, you realize you also wanted to print out the 2nd and 3rd-highest years. Instead of copying your code, you decide to put it in a function. Since the rank varies, you make that an argument to your function.**Question 1.5.** Write a function called `print_kth_top_movie_year`. It should take a single... | ...
print(...)
...
# Example calls to your function:
print_kth_top_movie_year(2)
print_kth_top_movie_year(3)
grader.check("q15")
# interact also allows you to pass in an array for a function argument. It will
# then present a dropdown menu of options.
_ = interact(print_kth_top_movie_year, k=np.arange(1, 10)) | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
`print` is not the same as `return`The `print_kth_top_movie_year(k)` function prints the total gross movie sales for the year that was provided! However, since we did not return any value in this function, we can not use it after we call it. Let's look at an example of another function that prints a value but does not... | def print_number_five():
print(5)
print_number_five() | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
However, if we try to use the output of `print_number_five()`, we see that the value `5` is printed but we get a TypeError when we try to add the number 2 to it! | print_number_five_output = print_number_five()
print_number_five_output + 2 | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
It may seem that `print_number_five()` is returning a value, 5. In reality, it just displays the number 5 to you without giving you the actual value! If your function prints out a value without returning it and you try to use that value, you will run into errors, so be careful!Explain to your neighbor how you might add... | raw_compensation = Table.read_table('raw_compensation.csv')
raw_compensation | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
We want to compute the average of the CEOs' pay. Try running the cell below. | np.average(raw_compensation.column("Total Pay")) | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
You should see a TypeError. Let's examine why this error occurred by looking at the values in the `Total Pay` column. **Question 2.1.** Use the `type` function and set `total_pay_type` to the type of the first value in the "Total Pay" column.<!--BEGIN QUESTIONname: q21--> | total_pay_type = ...
total_pay_type
grader.check("q21") | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
**Question 2.2.** You should have found that the values in the `Total Pay` column are strings. It doesn't make sense to take the average of string values, so we need to convert them to numbers if we want to do this. Extract the first value in `Total Pay`. It's Mark Hurd's pay in 2015, in *millions* of dollars. Call i... | mark_hurd_pay_string = ...
mark_hurd_pay_string
grader.check("q22") | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
**Question 2.3.** Convert `mark_hurd_pay_string` to a number of *dollars*. Some hints, as this question requires multiple steps:- The string method `strip` will be useful for removing the dollar sign; it removes a specified character from the start or end of a string. For example, the value of `"100%".strip("%")` is t... | mark_hurd_pay = ...
mark_hurd_pay
grader.check("q23") | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
To compute the average pay, we need to do this for every CEO. But that looks like it would involve copying this code 102 times.This is where functions come in. First, we'll define a new function, giving a name to the expression that converts "total pay" strings to numeric values. Later in this lab, we'll see the pay... | def convert_pay_string_to_number(pay_string):
"""Converts a pay string like '$100' (in millions) to a number of
dollars."""
...
grader.check("q24") | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
Running that cell doesn't convert any particular pay string. Instead, it creates a function called `convert_pay_string_to_number` that can convert *any* string with the right format to a number representing millions of dollars.We can call our function just like we call the built-in functions we've seen. It takes one ar... | convert_pay_string_to_number('$42')
convert_pay_string_to_number(mark_hurd_pay_string)
# We can also compute Safra Catz's pay in the same way:
convert_pay_string_to_number(raw_compensation.where("Name", are.containing("Safra")).column("Total Pay").item(0)) | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
So, what have we gained by defining the `convert_pay_string_to_number` function? Well, without it, we'd have to copy the code `10**6 * float(some_pay_string.strip("$"))` each time we wanted to convert a pay string. Now we just call a function whose name says exactly what it's doing. 3. `apply`ing functionsDefining a ... | our_name_for_max = max
our_name_for_max(2, 6) | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
The old name for `max` is still around: | max(2, 6) | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
Try just writing `max` or `our_name_for_max` (or the name of any other function) in a cell, and run that cell. Python will print out a (very brief) description of the function. | max | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
Now try writing `?max` or `?our_name_for_max` (or the name of any other function) in a cell, and run that cell. A information box should show up at the bottom of your screen a longer description of the function*Note: You can also press Shift+Tab after clicking on a name to see similar information!* | ?our_name_for_max | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
Let's look at what happens when we set `max`to a non-function value. You'll notice that a TypeError will occur when you try calling `max`. Things like integers and strings are not callable. Look out for any functions that might have been renamed when you encounter this type of error | max = 6
max(2, 6)
# This cell resets max to the built-in function. Just run this cell, don't change its contents
import builtins
max = builtins.max | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
Why is this useful? Since functions are just values, it's possible to pass them as arguments to other functions. Here's a simple but not-so-practical example: we can make an array of functions. | make_array(max, np.average, are.equal_to) | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
**Question 3.1.** Make an array containing any 3 other functions you've seen. Call it `some_functions`.<!--BEGIN QUESTIONname: q31--> | some_functions = ...
some_functions
grader.check("q31") | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
Working with functions as values can lead to some funny-looking code. For example, see if you can figure out why the following code works. Check your explanation with a neighbor or a staff member. | make_array(max, np.average, are.equal_to).item(0)(4, -2, 7) | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
A more useful example of passing functions to other functions as arguments is the table method `apply`.`apply` calls a function many times, once on *each* element in a column of a table. It produces an *array* of the results. Here we use `apply` to convert every CEO's pay to a number, using the function you defined: | raw_compensation.apply(convert_pay_string_to_number, "Total Pay") | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
Here's an illustration of what that did:Note that we didn’t write `raw_compensation.apply(convert_pay_string_to_number(), “Total Pay”)` or `raw_compensation.apply(convert_pay_string_to_number(“Total Pay”))`. We just passed the name of the function, with no parentheses, to `apply`, because all we want to do is let `appl... | compensation = raw_compensation.with_column(
"Total Pay ($)",
...
)
compensation
grader.check("q32") | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
Now that we have all the pays as numbers, we can learn more about them through computation.**Question 3.3.** Compute the average total pay of the CEOs in the dataset.<!--BEGIN QUESTIONname: q33--> | average_total_pay = ...
average_total_pay
grader.check("q33") | _____no_output_____ | BSD-3-Clause | lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb | ds-modules/Colab-demo |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.