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 |
|---|---|---|---|---|---|
2.1.1) Writing To Disk | # Save as a simple Numpy array (.npy)
# Run time: <1s
np.save("points.npy", points)
# Save as compressed NumPy archive (.npz)
# Run time: ~5s
np.savez_compressed("points.npz", points) | _____no_output_____ | BSD-3-Clause | benchmarks/annotation_store.ipynb | adamshephard/tiatoolbox |
Note that the above numpy format is missing the keys (UUIDs) of each point.This may not be required in all cases. However, for the sake of comparisonwe also generate a NumPy archive with keys included. We store the UUIDsas integers to save space and for a fair comparison where the optimalstorage method is used in each ... | # Generate UUIDs
# Run time: ~10s
keys = np.array([uuid.uuid4().int for _ in range(len(points))])
# Generate some UUIDs as keys
# Save in NumPy format (.npz)
# Run time: <1s
np.savez("uuid_points.npz", keys=keys, coords=points)
# Save in compressed (zip) NumPy format (.npz)
# Run time: ~10s
np.savez_compressed("uuid_po... | _____no_output_____ | BSD-3-Clause | benchmarks/annotation_store.ipynb | adamshephard/tiatoolbox |
2.1.2) Points Dataset Statistics Summary| Format | Write Time | Size ||-------------------------------:|-----------:|-------:|| SQLiteStore (.db) | 6m 20s | 893MB || ndjson | 1m 23s | 667 MB || GeoJSON | 1m 42s | 500 MB ... | box = Polygon.from_bounds(128, 128, 256, 256)
# Time numpy
numpy_runs = timeit.repeat(
(
"where = np.all(["
"points[:, 0] > 128,"
"points[:, 0] < 256,"
"points[:, 1] > 128,"
"points[:, 1] < 256"
"], 0)\n"
"uuids = keys[where]\n"
"result = points[where... | _____no_output_____ | BSD-3-Clause | benchmarks/annotation_store.ipynb | adamshephard/tiatoolbox |
Although the NumPy array is very space efficient on disk, it is not asfast to query as the `SQLiteStore`. The `SQLiteStore` is likely fasterdue to the use of the R tree index. Furthermore, the method used tostore the points in a NumPy array is limited in that it does not useUUIDs, which makes merging two datasets more ... | big_triangle = Polygon(
shell=[
(1024, 1024),
(1024, 4096),
(4096, 4096),
(1024, 1024),
]
)
# Time SQLiteStore
sqlite_runs = timeit.repeat(
"store.query(polygon)",
globals={"store": points_sqlite_store, "polygon": big_triangle},
number=1,
repeat=10,
)
# Time Dic... | _____no_output_____ | BSD-3-Clause | benchmarks/annotation_store.ipynb | adamshephard/tiatoolbox |
2.2) Cell Boundary Polygons DatasetHere we generate a much larger and more complex polygon dataset. Thisconsistes of a grid of over 5 million generated cell boundary likepolygons. | # Generate a grid of 5 million cell boundary polygons (2237 x 2237)
# Run time: ~10m
import random
random.seed(42)
cell_polygons = [
Annotation(geometry=polygon, properties={"class": random.randint(0, 4)})
for polygon
in tqdm(cell_grid(size=(2237, 2237), spacing=35), total=2237**2)
] | 100%|██████████| 5004169/5004169 [10:04<00:00, 8277.35it/s]
| BSD-3-Clause | benchmarks/annotation_store.ipynb | adamshephard/tiatoolbox |
2.2.1) Write To Formats For Comparison | # Write to an SQLiteStore on disk (SSD for recorded times here)
# Run time: ~30m
cell_sqlite_store = SQLiteStore("cells.db")
_ = cell_sqlite_store.append_many(annotations=cell_polygons)
# Create a copy as an in memory DictionaryStore
# Run time: ~5m
cell_dict_store = DictionaryStore()
for key, value in tqdm( # Show a ... | _____no_output_____ | BSD-3-Clause | benchmarks/annotation_store.ipynb | adamshephard/tiatoolbox |
2.2.2) Time To Write Summary StatisticsThe following is a summary of the time required to write each format todisk and the total disk space occupied by the final output.Note that some of these formats, such as GeoJSON compress well withschemes such as gzip and zstd, reducing the disk space by approximatelyhalf. Statis... | # Run time: ~5m
# Setup
xmin, ymin, xmax, ymax = 128, 12, 256, 256
box = Polygon.from_bounds(xmin, ymin, xmax, ymax)
# Time DictionaryStore
dict_runs = timeit.repeat(
"store.query(box)",
globals={"store": cell_dict_store, "box": box},
number=1,
repeat=3,
)
# Time SQLite store
sqlite_runs = timeit.re... | _____no_output_____ | BSD-3-Clause | benchmarks/annotation_store.ipynb | adamshephard/tiatoolbox |
2.2.4) Polygon Query | # Run Time: 35s
# Setup
big_triangle = Polygon(
shell=[
(1024, 1024),
(1024, 4096),
(4096, 4096),
(1024, 1024),
]
)
# Time DictionaryStore
dict_runs = timeit.repeat(
"store.query(polygon)",
globals={"store": cell_dict_store, "polygon": big_triangle},
number=1,
... | _____no_output_____ | BSD-3-Clause | benchmarks/annotation_store.ipynb | adamshephard/tiatoolbox |
2.2.5) Predicate Query | # Run Time: ~10m
# Setup
xmin, ymin, xmax, ymax = 128, 12, 256, 256
box = Polygon.from_bounds(xmin, ymin, xmax, ymax)
predicate = "props['class'] == 0"
# Time DictionaryStore
dict_runs = timeit.repeat(
"store.query(box, predicate)",
globals={"store": cell_dict_store, "box": box, "predicate": predicate},
n... | _____no_output_____ | BSD-3-Clause | benchmarks/annotation_store.ipynb | adamshephard/tiatoolbox |
2.3) Size vs Approximate Lower BoundHere we calculate an estimated lower bound on file size by finding thethe Shannon entropy of each file. This tells us the theoretical minimumnumber of bits per byte. The lowest lower bound is then used as anestimate of the minimum file size possible to store the annotation data. | # Run Time: ~5m
# Files to consider containing keys, geometry, and properties.
# Files which are missing keys e.g. cells.pickle are excluded
# for a fair comparison.
file_names = [
"cells-dicionary-store.pickle",
"cells-dict.pickle",
"cells.db",
"cells.db.zstd",
"cells.geojson",
"cells.ndjson"... | BSD-3-Clause | benchmarks/annotation_store.ipynb | adamshephard/tiatoolbox | |
Plot Results | # Get file sizes
file_sizes = {path: path.stat().st_size for path in [Path(".") / name for name in file_names]}
# Sort by size
file_sizes = {k: v for k, v in sorted(file_sizes.items(), key=lambda x: x[1])}
# Plot
plt.bar(
x=range(len(file_sizes)),
height=file_sizes.values(),
tick_label=[p.name for p in fi... | _____no_output_____ | BSD-3-Clause | benchmarks/annotation_store.ipynb | adamshephard/tiatoolbox |
The SQLite representation (4.9GB) appears to be quite compact comparedwith GeoJSON and ndjson. Although not as compact as a dictionary pickleor Zstandard compressed ndjson, it offers a good compromise betweencompactness and read performance. 3: Extra Bits 3.1) Space SavingA lot of space can be saved by rounding the co... | # Run Time: ~50m
! rm integer-cells.db
int_cell_sqlite_store = SQLiteStore("integer-cells.db")
# We use batches of 1000 to speed up appending
batch = {}
for key, annotation in tqdm(cell_sqlite_store.items(), total=len(cell_sqlite_store)):
geometry = Polygon(np.array(annotation.geometry.exterior.coords).round())
... | 100%|██████████| 10008338/10008338 [51:00<00:00, 3270.16it/s]
| BSD-3-Clause | benchmarks/annotation_store.ipynb | adamshephard/tiatoolbox |
Here the database size is reduced to 2.9GB, down from 4.9GB.Additionally, when using integer coordinates, the database compressesmuch better. Zstandard can compress to approximately 60% of theoriginal size (and 35% of the floating point coordinatedatabase size). This may be done for archival purposes. | # Run time: ~15s
! zstd -f -k integer-cells.db -o integer-cells.db.zstd | integer-cells.db : 60.58% ( 2.86 GiB => 1.73 GiB, integer-cells.db.zstd)
| BSD-3-Clause | benchmarks/annotation_store.ipynb | adamshephard/tiatoolbox |
With higher (slower) compression settings the space can be furtherreduced for long term storage. | # Run time: ~20m
! zstd -f -k -19 --long integer-cells.db -o integer-cells.db.19.zstd | integer-cells.db : 51.22% ( 2.86 GiB => 1.47 GiB, integer-cells.db.19.zstd)
| BSD-3-Clause | benchmarks/annotation_store.ipynb | adamshephard/tiatoolbox |
Copyright 2017 Google LLC. | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the L... | _____no_output_____ | Apache-2.0 | exercises/.ipynb_checkpoints/synthetic_features_and_outliers-checkpoint.ipynb | Kabongosalomon/Crash-Course-Machine-Learning- |
Synthetic Features and Outliers **Learning Objectives:** * Create a synthetic feature that is the ratio of two other features * Use this new feature as an input to a linear regression model * Improve the effectiveness of the model by identifying and clipping (removing) outliers out of the input data Let's revisit o... | from __future__ import print_function
import math
from IPython import display
from matplotlib import cm
from matplotlib import gridspec
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sklearn.metrics as metrics
import tensorflow as tf
from tensorflow.python.data import Dataset
tf.loggin... | _____no_output_____ | Apache-2.0 | exercises/.ipynb_checkpoints/synthetic_features_and_outliers-checkpoint.ipynb | Kabongosalomon/Crash-Course-Machine-Learning- |
Next, we'll set up our input function, and define the function for model training: | def my_input_fn(features, targets, batch_size=1, shuffle=True, num_epochs=None):
"""Trains a linear regression model of one feature.
Args:
features: pandas DataFrame of features
targets: pandas DataFrame of targets
batch_size: Size of batches to be passed to the model
shuffle: True or... | _____no_output_____ | Apache-2.0 | exercises/.ipynb_checkpoints/synthetic_features_and_outliers-checkpoint.ipynb | Kabongosalomon/Crash-Course-Machine-Learning- |
Task 1: Try a Synthetic FeatureBoth the `total_rooms` and `population` features count totals for a given city block.But what if one city block were more densely populated than another? We can explore how block density relates to median house value by creating a synthetic feature that's a ratio of `total_rooms` and `po... | #
# YOUR CODE HERE
#
california_housing_dataframe["rooms_per_person"] =
calibration_data = train_model(
learning_rate=0.00005,
steps=500,
batch_size=5,
input_feature="rooms_per_person"
) | _____no_output_____ | Apache-2.0 | exercises/.ipynb_checkpoints/synthetic_features_and_outliers-checkpoint.ipynb | Kabongosalomon/Crash-Course-Machine-Learning- |
SolutionClick below for a solution. | california_housing_dataframe["rooms_per_person"] = (
california_housing_dataframe["total_rooms"] / california_housing_dataframe["population"])
calibration_data = train_model(
learning_rate=0.05,
steps=500,
batch_size=5,
input_feature="rooms_per_person") | _____no_output_____ | Apache-2.0 | exercises/.ipynb_checkpoints/synthetic_features_and_outliers-checkpoint.ipynb | Kabongosalomon/Crash-Course-Machine-Learning- |
Task 2: Identify OutliersWe can visualize the performance of our model by creating a scatter plot of predictions vs. target values. Ideally, these would lie on a perfectly correlated diagonal line.Use Pyplot's [`scatter()`](https://matplotlib.org/gallery/shapes_and_collections/scatter.html) to create a scatter plot o... | # YOUR CODE HERE | _____no_output_____ | Apache-2.0 | exercises/.ipynb_checkpoints/synthetic_features_and_outliers-checkpoint.ipynb | Kabongosalomon/Crash-Course-Machine-Learning- |
SolutionClick below for the solution. | plt.figure(figsize=(15, 6))
plt.subplot(1, 2, 1)
plt.scatter(calibration_data["predictions"], calibration_data["targets"]) | _____no_output_____ | Apache-2.0 | exercises/.ipynb_checkpoints/synthetic_features_and_outliers-checkpoint.ipynb | Kabongosalomon/Crash-Course-Machine-Learning- |
The calibration data shows most scatter points aligned to a line. The line is almost vertical, but we'll come back to that later. Right now let's focus on the ones that deviate from the line. We notice that they are relatively few in number.If we plot a histogram of `rooms_per_person`, we find that we have a few outlie... | plt.subplot(1, 2, 2)
_ = california_housing_dataframe["rooms_per_person"].hist() | _____no_output_____ | Apache-2.0 | exercises/.ipynb_checkpoints/synthetic_features_and_outliers-checkpoint.ipynb | Kabongosalomon/Crash-Course-Machine-Learning- |
Task 3: Clip OutliersSee if you can further improve the model fit by setting the outlier values of `rooms_per_person` to some reasonable minimum or maximum.For reference, here's a quick example of how to apply a function to a Pandas `Series`: clipped_feature = my_dataframe["my_feature_name"].apply(lambda x: max(x, ... | # YOUR CODE HERE | _____no_output_____ | Apache-2.0 | exercises/.ipynb_checkpoints/synthetic_features_and_outliers-checkpoint.ipynb | Kabongosalomon/Crash-Course-Machine-Learning- |
SolutionClick below for the solution. The histogram we created in Task 2 shows that the majority of values are less than `5`. Let's clip `rooms_per_person` to 5, and plot a histogram to double-check the results. | california_housing_dataframe["rooms_per_person"] = (
california_housing_dataframe["rooms_per_person"]).apply(lambda x: min(x, 5))
_ = california_housing_dataframe["rooms_per_person"].hist() | _____no_output_____ | Apache-2.0 | exercises/.ipynb_checkpoints/synthetic_features_and_outliers-checkpoint.ipynb | Kabongosalomon/Crash-Course-Machine-Learning- |
To verify that clipping worked, let's train again and print the calibration data once more: | calibration_data = train_model(
learning_rate=0.05,
steps=500,
batch_size=5,
input_feature="rooms_per_person")
_ = plt.scatter(calibration_data["predictions"], calibration_data["targets"]) | _____no_output_____ | Apache-2.0 | exercises/.ipynb_checkpoints/synthetic_features_and_outliers-checkpoint.ipynb | Kabongosalomon/Crash-Course-Machine-Learning- |
GAN Workflow Engine with the MedNIST DatasetThe MONAI framework can be used to easily design, train, and evaluate generative adversarial networks.This notebook exemplifies using MONAI components to design and train a simple GAN model to reconstruct images of Hand CT scans.Read the [MONAI Mednist GAN Tutorial](https://... | %pip install -qU "monai[ignite]"
# temporarily need this, FIXME remove when d93c0a6 released
%pip install -qU git+https://github.com/Project-MONAI/MONAI#egg=MONAI
%pip install -qU matplotlib
%matplotlib inline | Note: you may need to restart the kernel to use updated packages.
| Apache-2.0 | examples/notebooks/mednist_GAN_workflow.ipynb | BRAINSia/MONAI |
Setup imports | import logging
import os
import shutil
import sys
import tempfile
import IPython
import matplotlib.pyplot as plt
import torch
from monai.apps import download_and_extract
from monai.config import print_config
from monai.data import CacheDataset, DataLoader
from monai.engines import GanKeys, GanTrainer, default_make_la... | MONAI version: 0.2.0+74.g8e5a53e
Python version: 3.7.5 (default, Nov 7 2019, 10:50:52) [GCC 8.3.0]
Numpy version: 1.19.1
Pytorch version: 1.6.0
Optional dependencies:
Pytorch Ignite version: 0.3.0
Nibabel version: NOT INSTALLED or UNKNOWN VERSION.
scikit-image version: NOT INSTALLED or UNKNOWN VERSION.
Pillow versio... | Apache-2.0 | examples/notebooks/mednist_GAN_workflow.ipynb | BRAINSia/MONAI |
Setup data directoryYou can specify a directory with the `MONAI_DATA_DIRECTORY` environment variable. This allows you to save results and reuse downloads. If not specified a temporary directory will be used. | directory = os.environ.get("MONAI_DATA_DIRECTORY")
root_dir = tempfile.mkdtemp() if directory is None else directory
print(root_dir) | /home/bengorman/notebooks/
| Apache-2.0 | examples/notebooks/mednist_GAN_workflow.ipynb | BRAINSia/MONAI |
Download datasetDownloads and extracts the dataset.The MedNIST dataset was gathered from several sets from [TCIA](https://wiki.cancerimagingarchive.net/display/Public/Data+Usage+Policies+and+Restrictions),[the RSNA Bone Age Challenge](http://rsnachallenges.cloudapp.net/competitions/4),and [the NIH Chest X-ray dataset]... | resource = "https://www.dropbox.com/s/5wwskxctvcxiuea/MedNIST.tar.gz?dl=1"
md5 = "0bc7306e7427e00ad1c5526a6677552d"
compressed_file = os.path.join(root_dir, "MedNIST.tar.gz")
data_dir = os.path.join(root_dir, "MedNIST")
download_and_extract(resource, compressed_file, root_dir, md5)
hand_dir = os.path.join(data_dir, "... | [{'hand': '/home/bengorman/notebooks/MedNIST/Hand/003676.jpeg'}, {'hand': '/home/bengorman/notebooks/MedNIST/Hand/006548.jpeg'}, {'hand': '/home/bengorman/notebooks/MedNIST/Hand/002169.jpeg'}, {'hand': '/home/bengorman/notebooks/MedNIST/Hand/004081.jpeg'}, {'hand': '/home/bengorman/notebooks/MedNIST/Hand/004815.jpeg'}]... | Apache-2.0 | examples/notebooks/mednist_GAN_workflow.ipynb | BRAINSia/MONAI |
Step 2: Initialize MONAI components | logging.basicConfig(stream=sys.stdout, level=logging.INFO)
set_determinism(0)
device = torch.device("cuda:0") | _____no_output_____ | Apache-2.0 | examples/notebooks/mednist_GAN_workflow.ipynb | BRAINSia/MONAI |
Create image transform chainDefine the processing pipeline to convert saved disk images into usable Tensors. | train_transforms = Compose(
[
LoadPNGD(keys=["hand"]),
AddChannelD(keys=["hand"]),
ScaleIntensityD(keys=["hand"]),
RandRotateD(keys=["hand"], range_x=15, prob=0.5, keep_size=True),
RandFlipD(keys=["hand"], spatial_axis=0, prob=0.5),
RandZoomD(keys=["hand"], min_zoom=0... | _____no_output_____ | Apache-2.0 | examples/notebooks/mednist_GAN_workflow.ipynb | BRAINSia/MONAI |
Create dataset and dataloaderHold data and present batches during training. | real_dataset = CacheDataset(training_datadict, train_transforms)
batch_size = 300
real_dataloader = DataLoader(real_dataset, batch_size=batch_size, shuffle=True, num_workers=10)
def prepare_batch(batchdata):
return batchdata["hand"] | _____no_output_____ | Apache-2.0 | examples/notebooks/mednist_GAN_workflow.ipynb | BRAINSia/MONAI |
Define generator and discriminatorLoad basic computer vision GAN networks from libraries. | # define networks
disc_net = Discriminator(
in_shape=(1, 64, 64),
channels=(8, 16, 32, 64, 1),
strides=(2, 2, 2, 2, 1),
num_res_units=1,
kernel_size=5,
).to(device)
latent_size = 64
gen_net = Generator(
latent_shape=latent_size,
start_shape=(latent_size, 8, 8),
channels=[32, 16, 8, 1],
... | _____no_output_____ | Apache-2.0 | examples/notebooks/mednist_GAN_workflow.ipynb | BRAINSia/MONAI |
Create training handlersPerform operations during model training. | metric_logger = MetricLogger(
loss_transform=lambda x: {GanKeys.GLOSS: x[GanKeys.GLOSS], GanKeys.DLOSS: x[GanKeys.DLOSS]},
metric_transform=lambda x: x,
)
handlers = [
StatsHandler(
name="batch_training_loss",
output_transform=lambda x: {
GanKeys.GLOSS: x[GanKeys.GLOSS],
... | _____no_output_____ | Apache-2.0 | examples/notebooks/mednist_GAN_workflow.ipynb | BRAINSia/MONAI |
Create GanTrainerMONAI Workflow engine for adversarial learning. The components come together here with the GanTrainer.Uses a training loop based on Goodfellow et al. 2014 https://arxiv.org/abs/1406.266. ```Training Loop: for each batch of data size m 1. Generate m fakes from random latent codes. 2. Upda... | disc_train_steps = 5
num_epochs = 50
trainer = GanTrainer(
device,
num_epochs,
real_dataloader,
gen_net,
gen_opt,
generator_loss,
disc_net,
disc_opt,
discriminator_loss,
d_prepare_batch=prepare_batch,
d_train_steps=disc_train_steps,
g_update_latents=True,
latent_shap... | _____no_output_____ | Apache-2.0 | examples/notebooks/mednist_GAN_workflow.ipynb | BRAINSia/MONAI |
Step 3: Start Training | trainer.run()
IPython.display.clear_output() | _____no_output_____ | Apache-2.0 | examples/notebooks/mednist_GAN_workflow.ipynb | BRAINSia/MONAI |
Evaluate ResultsExamine G and D loss curves for collapse. | g_loss = [loss[GanKeys.GLOSS] for loss in metric_logger.loss]
d_loss = [loss[GanKeys.DLOSS] for loss in metric_logger.loss]
plt.figure(figsize=(12, 5))
plt.semilogy(g_loss, label="Generator Loss")
plt.semilogy(d_loss, label="Discriminator Loss")
plt.grid(True, "both", "both")
plt.legend()
plt.show() | _____no_output_____ | Apache-2.0 | examples/notebooks/mednist_GAN_workflow.ipynb | BRAINSia/MONAI |
View image reconstructionsWith random latent codes view trained generator output. | test_img_count = 10
test_latents = default_make_latent(test_img_count, latent_size).to(device)
fakes = gen_net(test_latents)
fig, axs = plt.subplots(2, (test_img_count // 2), figsize=(20, 8))
axs = axs.flatten()
for i, ax in enumerate(axs):
ax.axis("off")
ax.imshow(fakes[i, 0].cpu().data.numpy(), cmap="gray") | _____no_output_____ | Apache-2.0 | examples/notebooks/mednist_GAN_workflow.ipynb | BRAINSia/MONAI |
Cleanup data directoryRemove directory if a temporary was used. | if directory is None:
shutil.rmtree(root_dir) | _____no_output_____ | Apache-2.0 | examples/notebooks/mednist_GAN_workflow.ipynb | BRAINSia/MONAI |
We show how to translate from syntax trees, to pregroup parsing diagrams, to equivalent diagrams where all cups and caps are removed. | from discopy import Ty, Id, Box, Diagram, Word
# POS TAGS:
s, n, adj, v, vp = Ty('S'), Ty('N'), Ty('ADJ'), Ty('V'), Ty('VP')
# WORDS:
Jane = Word('Jane', n)
loves = Word('loves', v)
funny = Word('funny', adj)
boys = Word('boys', n)
vocab = [Jane, loves, funny, boys] | _____no_output_____ | BSD-3-Clause | notebooks/rewriting-grammar.ipynb | dimkart/discopy |
Syntax trees | # The CFG's production rules are boxes.
R0 = Box('R0', vp @ n, s)
R1 = Box('R1', n @ vp, s)
R2 = Box('R2', n @ v , vp)
R3 = Box('R3', v @ n , vp)
R4 = Box('R4', adj @ n, n)
# A syntax tree is a diagram!
tree0 = R2 @ R4 >> R0
tree1 = Id(n @ v) @ R4 >> Id(n) @ R3 >> R1
sentence0 = Jane @ loves @ funny @ boys >> tree0
... | Two syntax trees for sentence 'Jane loves funny boys':
| BSD-3-Clause | notebooks/rewriting-grammar.ipynb | dimkart/discopy |
Pregroup parsing | from discopy.rigid import Cup, Cap, Functor
# Dict from POS tags to Pregroup types:
ob = {n : n, s: s, adj: n @ n.l, v: n.r @ s @ n.l, vp: s @ n.l}
_Jane = Word('Jane', n)
_loves = Word('loves', n.r @ s @ n.l)
_funny = Word('funny', n @ n.l)
_boys = Word('boys', n)
# Dict from CFG rules to Pregroup reductions:
ar ... | _____no_output_____ | BSD-3-Clause | notebooks/rewriting-grammar.ipynb | dimkart/discopy |
Snake removal | # Define the Wiring functor that decomposes a word into monoidal boxes with inputs transposed:
love_box = Box('loves', n @ n, s)
funny_box = Box('funny', n, n)
ob = {n: n, s: s}
ar = {_Jane: _Jane, _boys: _boys,
_loves: Cap(n.r, n) @ Cap(n, n.l) >> Diagram.id(n.r) @ love_box @ Diagram.id(n.l),
_funny: Ca... | Equivalent diagram for 'Jane loves funny boys', after snake removal:
| BSD-3-Clause | notebooks/rewriting-grammar.ipynb | dimkart/discopy |
# Download and unpack archive with CIFAR10 dataset to disk from official site: https://www.cs.toronto.edu/~kriz/cifar.html
!wget https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz
!tar -xzf cifar-10-python.tar.gz
!ls -l
# Loading CIFAR10 data using code from official site: https://www.cs.toronto.edu/~kriz/cifar.... | Accuracy 0.380
Accuracy 0.410
Accuracy 0.373
Accuracy 0.375
Accuracy 0.380
Accuracy 0.383
| MIT | extra/KNN_demo.ipynb | Gan4x4/hse-cv2019 | |
**LetsGrowMore**------ ***Data Science Internship***------ `Author: UMER FAROOQ` `Task Level: Beginner Level` `Task Number: 1` `Task Title: Iris Flower Classification` `Language: Python` `IDE: Google Colab` **Steps**: **Step:1*****Importing Libraries*** | import numpy as np
import pandas as pd
import seaborn as sns
sns.set_palette('husl')
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics impor... | _____no_output_____ | MIT | TASK#1.ipynb | Umer86/IRIS_FLOWER_Classfication_ML_Project |
**Step:2*****Loading the Dataset:*** I have pick the dataset from the following link. You can download the dataset as well as you can use by URL. | url = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/iris.csv'
# Creating the list of column name:
column_name = ['sepal-lenght','sepal-width','petal-lenght','petal-width','class']
# Pandas read_csv() is used for reading the csv file:
dataset = pd.read_csv(url, names = column_name) | _____no_output_____ | MIT | TASK#1.ipynb | Umer86/IRIS_FLOWER_Classfication_ML_Project |
**Step:3*****Dataset Summarizing:*** Check the structure/shape of data on which we have to work on. | dataset.shape | _____no_output_____ | MIT | TASK#1.ipynb | Umer86/IRIS_FLOWER_Classfication_ML_Project |
This shows that we have: 1. 150 rows,2. 5 columns.Thats enough for our Beginner Project.*Displaying the First 5 records:* | dataset.head() | _____no_output_____ | MIT | TASK#1.ipynb | Umer86/IRIS_FLOWER_Classfication_ML_Project |
Pandas info() method prints information about a DataFrame such as datatypes, cols, NAN values and usage of memory: | dataset.info()
dataset.isnull()
# Returns no. of missing records/values
dataset.isnull().sum()
""" Pandas describe() is used to view some basic statistical details like percentile, mean, std etc. of a data frame or a series of numeric values: """
dataset.describe() | _____no_output_____ | MIT | TASK#1.ipynb | Umer86/IRIS_FLOWER_Classfication_ML_Project |
**Now let’s check the number of rows that belongs to each class:** | dataset['class'].value_counts() # No of records/samples in each class | _____no_output_____ | MIT | TASK#1.ipynb | Umer86/IRIS_FLOWER_Classfication_ML_Project |
The above outputs shows that each class of flowers has 50 rows. **Step: 4 Data Visualization**------Data visualization is the process of translating large data sets and metrics into charts, graphs and other visuals.------**Violin Plot:** Plotting the violin plot to check the comparison of a variable distribution: | sns.violinplot(y='class', x='sepal-lenght', data=dataset, inner='quartile')
plt.show()
print('\n')
sns.violinplot(y='class', x='sepal-width', data=dataset, inner='quartile')
plt.show()
print('\n')
sns.violinplot(y='class', x='petal-lenght', data=dataset, inner='quartile')
plt.show()
print('\n')
sns.violinplot(y='cla... | _____no_output_____ | MIT | TASK#1.ipynb | Umer86/IRIS_FLOWER_Classfication_ML_Project |
Above-plotted violin plot says that Iris-Setosa class is having a smaller petal length and petal width as compared to other class. **Pair Plot:** Plotting multiple pairwise bivariate distributions in a dataset using pairplot: | sns.pairplot(dataset, hue='class', markers='+')
plt.show() | _____no_output_____ | MIT | TASK#1.ipynb | Umer86/IRIS_FLOWER_Classfication_ML_Project |
From the above, we can see that Iris-Setosa is separated from both other species in all the features. **Heatmap:** Plotting the heatmap to check the correlation.**dataset.corr()** is used to find the pairwise correlation of all columns in the dataframe. | plt.figure(figsize=(8,5))
sns.heatmap(dataset.corr(), annot=True, cmap= 'PuOr')
plt.show() | _____no_output_____ | MIT | TASK#1.ipynb | Umer86/IRIS_FLOWER_Classfication_ML_Project |
**Step: 5 Model Construction (Splitting, Training and Model Creation)**------**SPLITTING THE DATASET:**X have dependent variables.Y have an independent variables. | x= dataset.drop(['class'], axis=1)
y= dataset['class'] # Class is an independent variable
print('X shape: {}\nY Shape: {}'.format(x.shape, y.shape)) | X shape: (150, 4)
Y Shape: (150,)
| MIT | TASK#1.ipynb | Umer86/IRIS_FLOWER_Classfication_ML_Project |
The output shows that X has 150 records/rows and 4 cols, whereas, Y has 150 records and only 1 col. **TRAINING THE TEST SPLIT:**Splitting our dataset into train and test using train_test_split(), what we are doing here is taking 80% of data to train our model, and 20% that we will hold back as a validation dataset: | x_train, x_test, y_train, y_test = train_test_split (x, y, test_size=0.20, random_state=1) | _____no_output_____ | MIT | TASK#1.ipynb | Umer86/IRIS_FLOWER_Classfication_ML_Project |
**MODEL CONSTRUCTION PART:1:**We have no idea which algorithms might work best in this situation.Let's run each algorithm in a loop and print its accuracy so we can choose the best one. Following are the algorithms:1. Logistic Regression (LR)2. Linear Discriminant Analysis (LDA)1. K-Nearest Neighbors (KNN).2. C... | models = []
models.append(('LR', LogisticRegression()))
models.append(('LDA', LinearDiscriminantAnalysis()))
models.append(('KNN', KNeighborsClassifier()))
models.append(('CART', DecisionTreeClassifier()))
models.append(('NB', GaussianNB()))
models.append(('SVC', SVC(gamma='auto')))
# evaluate each model in turn
result... | /usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_logistic.py:940: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
... | MIT | TASK#1.ipynb | Umer86/IRIS_FLOWER_Classfication_ML_Project |
***Support Vector Classifier (SVC) is performing better than other algorithms.Let’s train SVC model on our training set and predict on test set in the next step.*** **MODEL CONSTRUCTION PART:2**We are defining our SVC model and passing gamma as auto.After that fitting/training the model on X_train and Y_train using .fi... | model = SVC(gamma='auto')
model.fit(x_train, y_train)
prediction = model.predict(x_test) | _____no_output_____ | MIT | TASK#1.ipynb | Umer86/IRIS_FLOWER_Classfication_ML_Project |
**Now checking the accuracy of the model using accuracy_score(y_test, prediction).**y_test is actually values of x_testprediction: it predicts values of x_test as mentioned earlier (*then we are predicting on X_test using .predict() method*).**Printing out the classfication report using:** classification_report(y_test,... | print(f"Test Accuracy: {accuracy_score(y_test, prediction)} \n")
print(f'Classification Report:\n \n {classification_report(y_test, prediction)}') | Test Accuracy: 0.9666666666666667
Classification Report:
precision recall f1-score support
Iris-setosa 1.00 1.00 1.00 11
Iris-versicolor 1.00 0.92 0.96 13
Iris-virginica 0.86 1.00 0.92 6
accuracy ... | MIT | TASK#1.ipynb | Umer86/IRIS_FLOWER_Classfication_ML_Project |
Estadística Es la rama de las matemáticas que estudia la variabilidad, así como el proceso aleatorio que la genera siguiendo leyes de probabilidad.La estadística es útil para una amplia variedad de ciencias empíricas (la que entiende los hechos creando representaciones de la realidad), desde la física hasta las cienci... | import random
population = range(100)
sample = random.sample(population, 10) #sample crea una muestra aleatorio dentro del rango
print(sample) | [2, 78, 40, 59, 13, 31, 24, 43, 29, 68]
| Apache-2.0 | week3/day3/theory/statistics.ipynb | Marvxeles/mxrodvi |
--> Tarea Crear población a partir de lista de alturas de alumnos y con clases Conceptos básicos de la estadística descriptivaEn *[estadística descriptiva](https://es.wikipedia.org/wiki/Estad%C3%ADstica_descriptiva)* se utilizan distintas medidas para intentar describir las propiedades de nuestros datos, algunos de lo... | import numpy as np #np y pd es un alias. son librerias de estadistica y tratamientos de datos
import pandas as pd
import matplotlib.pyplot as pyplot
#se instalan en terminal
#pip3 install numpy
from numpy import *
#importo las funciones de numpy a jupiter y se puede usar sin np.
#no se recomienda
lista = [2, 4, 6, 8]
... | _____no_output_____ | Apache-2.0 | week3/day3/theory/statistics.ipynb | Marvxeles/mxrodvi |
Histogramas y DistribucionesMuchas veces los indicadores de la *[estadística descriptiva](https://es.wikipedia.org/wiki/Estad%C3%ADstica_descriptiva)* no nos proporcionan una imagen clara de nuestros *[datos](https://es.wikipedia.org/wiki/Dato)*. Por esta razón, siempre es útil complementarlos con gráficos de las dis... | # Histogram
df.hist() | _____no_output_____ | Apache-2.0 | week3/day3/theory/statistics.ipynb | Marvxeles/mxrodvi |
Distribución normalLa [distribución normal](https://es.wikipedia.org/wiki/Distribuci%C3%B3n_normal) es una de las principales distribuciones, ya que es la que con más frecuencia aparece aproximada en los fenómenos reales. Tiene una forma acampanada y es simétrica respecto de un determinado parámetro estadístico. Con l... | # Graficos embebidos.
%matplotlib inline
import matplotlib.pyplot as plt # importando matplotlib
import seaborn as sns # importando seaborn
# parametros esteticos de seaborn
sns.set_palette("deep", desat=.6)
sns.set_context(rc={"figure.figsize": (8, 4)})
mu, sigma = 0, 0.1 # media y desvio estandar
s = np.random.norm... | _____no_output_____ | Apache-2.0 | week3/day3/theory/statistics.ipynb | Marvxeles/mxrodvi |
Distribuciones simétricas y asimétricasUna distribución es simétrica cuando moda, mediana y media coinciden aproximadamente en sus valores. Si una distribución es simétrica, existe el mismo número de valores a la derecha que a la izquierda de la media, por tanto, el mismo número de desviaciones con signo positivo que ... | # Dibujando la distribucion Gamma
x = stats.gamma(3).rvs(5000)
gamma = plt.hist(x, 70, histtype="stepfilled", alpha=.7) | _____no_output_____ | Apache-2.0 | week3/day3/theory/statistics.ipynb | Marvxeles/mxrodvi |
En este ejemplo podemos ver que la [distribución gamma](https://es.wikipedia.org/wiki/Distribuci%C3%B3n_gamma) que dibujamos tiene una [asimetria](https://es.wikipedia.org/wiki/Asimetr%C3%ADa_estad%C3%ADstica) positiva. | # Calculando la simetria con scipy
stats.skew(x) | _____no_output_____ | Apache-2.0 | week3/day3/theory/statistics.ipynb | Marvxeles/mxrodvi |
Cuartiles y diagramas de cajasLos **[cuartiles](https://es.wikipedia.org/wiki/Cuartil)** son los tres valores de la variable estadística que dividen a un [conjunto de datos](https://es.wikipedia.org/wiki/Conjunto_de_datos) ordenados en cuatro partes iguales. Q1, Q2 y Q3 determinan los valores correspondientes al 25%, ... | lista = [2, 3, 4, 5,6,7,9,10,11, 1000]
import matplotlib.pyplot as plt
# Ejemplo de grafico de cajas en python
datos_1 = np.random.normal(100, 10, 200)
#datos_2 = np.random.normal(80, 30, 200)
datos_3 = np.random.normal(90, 20, 200)
datos_4 = np.random.normal(70, 25, 200)
datos_graf = [datos_1, datos_2, datos_3, dat... | _____no_output_____ | Apache-2.0 | week3/day3/theory/statistics.ipynb | Marvxeles/mxrodvi |
Data Aggregation and Group Operations | import numpy as np
import pandas as pd
PREVIOUS_MAX_ROWS = pd.options.display.max_rows
pd.options.display.max_rows = 20
np.random.seed(12345)
import matplotlib.pyplot as plt
plt.rc('figure', figsize=(10, 6))
np.set_printoptions(precision=4, suppress=True) | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
10.1. GroupBy Mechanics 10.1.0 To get started, here is a small tabular dataset as a DataFrame: | df = pd.DataFrame({'key1' : ['a', 'a', 'b', 'b', 'a'],
'key2' : ['one', 'two', 'one', 'two', 'one'],
'data1' : np.random.randn(5),
'data2' : np.random.randn(5)})
df | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
Suppose you wanted to *compute the mean of the data1 column* using the *labels from key1*.
There are a number of ways to do this.
* One is to access data1 and call groupby with the column (a Series) at key1: | grouped = df['data1'].groupby(df['key1'])
grouped | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
This grouped variable is now a GroupBy object. It has not actually computed anything yet except for some intermediate data about the group key df['key1']. The idea is that this object has all of the information needed to then apply some operation to each of the groups.
For example, to compute group means we can call t... | grouped.mean() | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
Later, I’ll explain more about what happens when you call .mean(). The important thing here is that `the data (a Series) has been aggregated according to the group key`, producing a new Series that is now indexed by the unique values in the key1 column. The result index has the name 'key1' because the DataFrame column ... | means = df['data1'].groupby([df['key1'], df['key2']]).mean()
means | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
Here we grouped the data using two keys (@P:key 1 + key 2 above), and the resulting Series now has a hierarchical index consisting of the unique pairs of keys observed: | means.unstack() | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
In this example, the group keys are all Series, though they could be any arrays of the right length: | states = np.array(['Ohio', 'California', 'California', 'Ohio', 'Ohio'])
years = np.array([2005, 2005, 2006, 2005, 2006])
df['data1'].groupby([states, years]).mean() | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
Frequently the grouping information is found in the same DataFrame as the data you want to work on. In that case, you can pass column names (whether those are strings, numbers, or other Python objects) as the group keys: | df.groupby('key1').mean()
df.groupby(['key1', 'key2']).mean() | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
You may have noticed in the first case df.groupby('key1').mean() that there is no key2 column in the result. *Because df['key2'] is not numeric data*, it is said to be a `nuisance column`, which is therefore excluded from the result. `By default, all of the numeric columns are aggregated`, though it is possible to filt... | df.groupby(['key1', 'key2']).size() | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
Take note that any missing values in a group key will be excluded from the result. 10.1.1. Iterating Over Groups The `GroupBy object supports iteration`, generating a sequence of 2-tuples containing the group name along with the chunk of data. Consider the following: | for name, group in df.groupby('key1'):
print(name)
print(group) | a
key1 key2 data1 data2
0 a one -0.204708 1.393406
1 a two 0.478943 0.092908
4 a one 1.965781 1.246435
b
key1 key2 data1 data2
2 b one -0.519439 0.281746
3 b two -0.555730 0.769023
| MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
In the case of multiple keys, the first element in the tuple will be a tuple of key values: | for (k1, k2), group in df.groupby(['key1', 'key2']):
print((k1, k2))
print(group) | ('a', 'one')
key1 key2 data1 data2
0 a one -0.204708 1.393406
4 a one 1.965781 1.246435
('a', 'two')
key1 key2 data1 data2
1 a two 0.478943 0.092908
('b', 'one')
key1 key2 data1 data2
2 b one -0.519439 0.281746
('b', 'two')
key1 key2 data1 data2
3 b two -... | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
Of course, you can choose to do whatever you want with the pieces of data. *A recipe you may find useful* is `computing a dict of the data pieces as a one-liner`: | pieces = dict(list(df.groupby('key1')))
pieces
# pieces['b'] | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
By default groupby groups on `axis=0`, but you `can group on any of the other axes`. For example, we could group the columns of our example df here by dtype like so: | df.dtypes
grouped = df.groupby(df.dtypes, axis=1)
grouped
#We can print out the groups like so:
for dtype, group in grouped:
print(dtype)
print(group) | float64
data1 data2
0 -0.204708 1.393406
1 0.478943 0.092908
2 -0.519439 0.281746
3 -0.555730 0.769023
4 1.965781 1.246435
object
key1 key2
0 a one
1 a two
2 b one
3 b two
4 a one
| MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
10.1.2. Selecting a Column or Subset of Columns Indexing a GroupBy object created from a DataFrame with a column name or array of column names has the effect of column subsetting for aggregation. This means that: | df.groupby('key1')['data1']
df.groupby('key1')[['data2']] | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
are `syntactic sugar` for: | df['data1'].groupby(df['key1'])
df[['data2']].groupby(df['key1']) | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
Especially for large datasets, it may be desirable to aggregate only a few columns.
For example, in the preceding dataset, to *compute means for just the data2 column* and get the result as a DataFrame, we could write: | df.groupby(['key1', 'key2'])[['data2']].mean() | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
`The object returned by this indexing operation is a grouped DataFrame` if a *list or array* is passed or` a grouped Series` if only a *single column name is passed* as a scalar: | s_grouped = df.groupby(['key1', 'key2'])['data2']
s_grouped
s_grouped.mean() | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
10.1.3. Grouping with Dicts and Series Grouping information may exist in a form other than an array. Let’s consider another example DataFrame: | people = pd.DataFrame(np.random.randn(5, 5),
columns=['a', 'b', 'c', 'd', 'e'],
index=['Joe', 'Steve', 'Wes', 'Jim', 'Travis'])
people.iloc[2:3, [1, 2]] = np.nan # Add a few NA values
people | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
Now, suppose I have a group correspondence for the columns and want to sum together the columns by group: | mapping = {'a': 'red', 'b': 'red', 'c': 'blue',
'd': 'blue', 'e': 'red', 'f' : 'orange'}
mapping | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
Now, you could construct an array from this dict to pass to groupby, but instead we can just pass the dict (I included the key 'f' to highlight that unused grouping keys are OK): | by_column = people.groupby(mapping, axis=1)
by_column.sum() | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
`The same functionality holds for Series`, which can be viewed as a *fixedsize mapping*: | map_series = pd.Series(mapping)
map_series
people.groupby(map_series, axis=1).count() | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
10.1.4. Grouping with Functions Using Python functions is a more generic way of defining a group mapping compared with a dict or Series. `Any function passed as a group key will be called once per index value, with the return values being used as the group names`.
More concretely, consider the example DataFrame from t... | people.groupby(len).sum() | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
Mixing functions with arrays, dicts, or Series is not a problem as everything gets converted to arrays internally: | key_list = ['one', 'one', 'one', 'two', 'two']
people.groupby([len, key_list]).min()
#@P 20210901: not understand how key_list function in this syntax | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
10.1.5. Grouping by Index Levels A final convenience for hierarchically indexed datasets is the ability to aggregate using one of the levels of an axis index.
Let’s look at an example: | columns = pd.MultiIndex.from_arrays([['US', 'US', 'US', 'JP', 'JP'],
[1, 3, 5, 1, 3]],
names=['cty', 'tenor'])
hier_df = pd.DataFrame(np.random.randn(4, 5), columns=columns)
hier_df | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
* *To group by level*, pass the level number or name using the level keyword: | hier_df.groupby(level='cty', axis=1).count() | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
10.2. Data Aggregation `Aggregations` refer to *any data transformation that produces scalar values from arrays*. The preceding examples have used several of them, including *mean, count, min, and sum*. While `quantile` is not explicitly implemented for GroupBy, it is a Series method and thus available for use. Intern... | df
grouped = df.groupby('key1')
grouped['data1'].quantile(0.9) | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
To use your own aggregation functions, pass any function that aggregates an array to the `aggregate` or `agg method`: | def peak_to_peak(arr):
return arr.max() - arr.min()
grouped.agg(peak_to_peak)
def peak_to_peak(arr):
return arr.max() - arr.min()
grouped.aggregate(peak_to_peak)
#@P 20210902: due to the warning that SeriesGroupBy.agg is deprecated -> change to this method but it seems to me that the results are not the sa... | D:\Users\phu.le2\Anaconda3\lib\site-packages\pandas\core\groupby\generic.py:303: FutureWarning: Dropping invalid columns in SeriesGroupBy.agg is deprecated. In a future version, a TypeError will be raised. Before calling .agg, select only columns which should be valid for the aggregating function.
results[key] = self... | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
You may notice that some methods like `describe` also work, even though they are not aggregations, strictly speaking: | grouped.describe() | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
**NOTE**
*Custom aggregation functions are generally much slower than the optimized functions found in Table 10-1* *(count, sum, mean, meadiam, std, var, min, max, prod, first, last)*. This is because there is some extra overhead (function calls, data rearrangement) in constructing the intermediate group data chunks. ... | tips = pd.read_csv('examples/tips.csv')
tips.head()
# Add tip percentage of total bill
tips['tip_pct'] = tips['tip'] / tips['total_bill']
tips[:6] | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
As you’ve already seen, aggregating a Series or all of the columns of a DataFrame is a matter of using `aggregate` with the desired function or calling a method like mean or std. However, you may want to aggregate using a different function depending on the column, or multiple functions at once. Fortunately, this is po... | rouped = tips.groupby(['day', 'smoker'])
grouped | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
Note that for descriptive statistics like those in Table 10-1, you can pass the name of the function as a string: | grouped_pct = grouped['tip_pct']
grouped_pct
grouped_pct.agg('mean') | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
If you p*ass a list of functions or function names* instead, you get back a DataFrame with column names taken from the functions: | grouped_pct.agg(['mean', 'std', peak_to_peak]) | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
Here we passed a list of aggregation functions to `agg` to evaluate indepedently on the data groups. `You don’t need to accept the names that GroupBy gives to the columns`; notably, lambda functions have the name '', which makes them hard to identify (you can see for yourself by looking at a function’s __name__ attribu... | grouped_pct.agg([('foo', 'mean'), ('bar', np.std)])
#@P: mean and std but are named as foo and bar | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
With a DataFrame you have more options, as you can specify a list of functions to apply to all of the columns or different functions per column. To start, suppose we wanted to compute the same three statistics for the *tip_pct* and *total_bill* columns: | functions = ['count', 'mean', 'max']
result = grouped['tip_pct', 'total_bill'].agg(functions)
result
grouped
#to deal with FutureWarning: Indexing with multiple keys (implicitly converted to a tuple of keys) will be deprecated, use a list instead.
#https://stackoverflow.com/questions/61634759/python-futurewarning-in... | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
As you can see, the resulting DataFrame has hierarchical columns, the same as you would get aggregating each column separately and using `concat` to glue the results together using the column names as the keys argument: | result['tip_pct'] | _____no_output_____ | MIT | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.