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
node features seem very sensitive perturb topology
# keep backup backup = data.edge_index.clone() backup perturb_data_list = [] for i in range(1000): # clone original data pData = data.clone() # noise parameters noEdgeSwap = 3 # create edges edges = pData.edge_index.T.tolist() edges = np.array(edges) edges = [(x[0][0], x[0][1], {"...
_____no_output_____
MIT
examples/lsc/pcqm4m/.ipynb_checkpoints/triplet-loss-checkpoint.ipynb
edwardelson/ogb
Copyright Netherlands eScience Center and Centrum Wiskunde & Informatica ** Function : Emotion recognition and forecast with BBConvLSTM** ** Author : Yang Liu** ** Contributor : Tianyi Zhang (Centrum Wiskunde & Informatica)** Last Update : 2021.02.08 ** ** Last Update : 2021.02.12 ** ** Library : Pyt...
%matplotlib inline import sys import numbers import pickle # for data loading import os # for pre-processing and machine learning import numpy as np import csv #import sklearn from scipy.signal import resample # for visualization import matplotlib import matplotlib.pyplot as plt from matplotlib.pyplot import cm
_____no_output_____
Apache-2.0
tests/data_preview.ipynb
geek-yang/NEmo
The testing device is Dell Inspirion 5680 with Intel Core i7-8700 x64 CPU and Nvidia GTX 1060 6GB GPU.Here is a benchmark about cpu v.s. gtx 1060 https://www.analyticsindiamag.com/deep-learning-tensorflow-benchmark-intel-i5-4210u-vs-geforce-nvidia-1060-6gb/
################################################################################# ######### datapath ######## ################################################################################# # please specify data path datapath = 'H:\\Creator_Zone\\Script_craft\\NE...
_____no_output_____
Apache-2.0
tests/data_preview.ipynb
geek-yang/NEmo
Recurrent PPO landing using raw altimeter readings
import numpy as np import os,sys sys.path.append('../../../RL_lib/Agents/PPO') sys.path.append('../../../RL_lib/Utils') sys.path.append('../../../Mars3dof_env') sys.path.append('../../../Mars_DTM') %load_ext autoreload %load_ext autoreload %autoreload 2 %matplotlib nbagg import os print(os.getcwd()) %%html <style> ....
_____no_output_____
MIT
Experiments/Mars3DOF/Mars_landing_DTM/altimeter_v_mm3-120step.ipynb
CHEN-yongquan/RL-Meta-Learning-ACTA
Optimize Policy
from env import Env import env_utils as envu from dynamics_model import Dynamics_model from lander_model import Lander_model from ic_gen2 import Landing_icgen import rl_utils from arch_policy_vf import Arch from model import Model from policy import Policy from value_function import Value_function import pcm_model_n...
_____no_output_____
MIT
Experiments/Mars3DOF/Mars_landing_DTM/altimeter_v_mm3-120step.ipynb
CHEN-yongquan/RL-Meta-Learning-ACTA
Test Policy with Realistic Noise
policy.test_mode=True env.test_policy_batch(agent,1000,print_every=100) len(lander_model.trajectory_list) traj_list = lander_model.trajectory_list[0:100] len(traj_list) np.save(fname + '_100traj',traj_list) envu.plot_rf_vf(env.rl_stats.history)
_____no_output_____
MIT
Experiments/Mars3DOF/Mars_landing_DTM/altimeter_v_mm3-120step.ipynb
CHEN-yongquan/RL-Meta-Learning-ACTA
Flowers classifier using Transfer Learning and tf.dataAccuracy : 0.9090909090909091Classification Report precision recall f1-score support 0 0.96429 0.90000 0.93103 60 1 0.88750 0.98611 0.93421 72 2 0.81538 0.89831 0.85484 59 ...
#""" # Google Collab specific stuff.... from google.colab import drive drive.mount('/content/drive') import os !ls "/content/drive/My Drive" USING_COLLAB = True %tensorflow_version 2.x #""" # Setup sys.path to find MachineLearning lib directory try: USING_COLLAB except NameError: USING_COLLAB = False %load_ext auto...
_____no_output_____
MIT
1-Flowers/FlowersTransfer-TF-Data-V1.ipynb
bo9zbo9z/MachineLearning
Examine and understand data
# GLOBALS/CONFIG ITEMS # Set root directory path to data if USING_COLLAB: ROOT_PATH = "/content/drive/My Drive/ImageData/Flowers" ###### CHANGE FOR SPECIFIC ENVIRONMENT else: ROOT_PATH = "/Users/john/Documents/ImageData/Flowers" ###### CHANGE FOR SPECIFIC ENVIRONMENT # Establish global dictionary pa...
_____no_output_____
MIT
1-Flowers/FlowersTransfer-TF-Data-V1.ipynb
bo9zbo9z/MachineLearning
Build an input pipeline
def get_label(file_path): # convert the path to a list of path components parts = tf.strings.split(file_path, os.path.sep) # The second to last is the class-directory return parts[-2] == parms.CLASS_NAMES def decode_image(image): # convert the compressed string to a 3D uint8 tensor image = tf....
_____no_output_____
MIT
1-Flowers/FlowersTransfer-TF-Data-V1.ipynb
bo9zbo9z/MachineLearning
Build model- add and validate pretrained model as a baseline
# Create any call backs for training...These are the most common. from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau, CSVLogger reduce_lr = ReduceLROnPlateau(monitor='loss', patience=2, verbose=1, min_lr=1e-6) earlystopper = EarlyStopping(patience=8, verbose=1) checkpointer = Mod...
_____no_output_____
MIT
1-Flowers/FlowersTransfer-TF-Data-V1.ipynb
bo9zbo9z/MachineLearning
Train model
# Train model steps_per_epoch = np.ceil(train_len // parms.BATCH_SIZE) # set step sizes based on train & batch validation_steps = np.ceil(val_len // parms.BATCH_SIZE) # set step sizes based on val & batch model = build_model(parms) model = compile_model(parms, model) history = model.fit(train_dataset, ...
_____no_output_____
MIT
1-Flowers/FlowersTransfer-TF-Data-V1.ipynb
bo9zbo9z/MachineLearning
Validate model's predictions- Create actual_lables and predict_labels- Calculate Confusion Matrix & Accuracy- Display results
#Load saved model from tensorflow.keras.models import load_model def load_saved_model(model_path): model = load_model(model_path) print("loaded: ", model_path) return model model = load_saved_model(parms.MODEL_PATH) # Use model to generate predicted labels and probabilities #labels, predict_labels, predic...
_____no_output_____
MIT
1-Flowers/FlowersTransfer-TF-Data-V1.ipynb
bo9zbo9z/MachineLearning
Copyright 2021 The TensorFlow Authors.
#@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
site/en-snapshot/lite/tutorials/pose_classification.ipynb
Icecoffee2500/docs-l10n
Human Pose Classification with MoveNet and TensorFlow LiteThis notebook teaches you how to train a pose classification model using MoveNet and TensorFlow Lite. The result is a new TensorFlow Lite model that accepts the output from the MoveNet model as its input, and outputs a pose classification, such as the name of a...
!pip install -q opencv-python import csv import cv2 import itertools import numpy as np import pandas as pd import os import sys import tempfile import tqdm from matplotlib import pyplot as plt from matplotlib.collections import LineCollection import tensorflow as tf import tensorflow_hub as hub from tensorflow impor...
_____no_output_____
Apache-2.0
site/en-snapshot/lite/tutorials/pose_classification.ipynb
Icecoffee2500/docs-l10n
Code to run pose estimation using MoveNet
#@title Functions to run pose estimation with MoveNet #@markdown You'll download the MoveNet Thunder model from [TensorFlow Hub](https://www.google.com/url?sa=D&q=https%3A%2F%2Ftfhub.dev%2Fs%3Fq%3Dmovenet), and reuse some inference and visualization logic from the [MoveNet Raspberry Pi (Python)](https://github.com/ten...
_____no_output_____
Apache-2.0
site/en-snapshot/lite/tutorials/pose_classification.ipynb
Icecoffee2500/docs-l10n
Part 1: Preprocess the input imagesBecause the input for our pose classifier is the *output* landmarks from the MoveNet model, we need to generate our training dataset by running labeled images through MoveNet and then capturing all the landmark data and ground truth labels into a CSV file.The dataset we've provided f...
is_skip_step_1 = False #@param ["False", "True"] {type:"raw"}
_____no_output_____
Apache-2.0
site/en-snapshot/lite/tutorials/pose_classification.ipynb
Icecoffee2500/docs-l10n
(Optional) Upload your own pose dataset
use_custom_dataset = False #@param ["False", "True"] {type:"raw"} dataset_is_split = False #@param ["False", "True"] {type:"raw"}
_____no_output_____
Apache-2.0
site/en-snapshot/lite/tutorials/pose_classification.ipynb
Icecoffee2500/docs-l10n
If you want to train the pose classifier with your own labeled poses (they can be any poses, not just yoga poses), follow these steps:1. Set the above `use_custom_dataset` option to **True**.2. Prepare an archive file (ZIP, TAR, or other) that includes a folder with your images dataset. The folder must include sorted i...
#@markdown Be sure you run this cell. It's hiding the `split_into_train_test()` function that's called in the next code block. import os import random import shutil def split_into_train_test(images_origin, images_dest, test_split): """Splits a directory of sorted images into training and test sets. Args: ima...
_____no_output_____
Apache-2.0
site/en-snapshot/lite/tutorials/pose_classification.ipynb
Icecoffee2500/docs-l10n
**Note:** If you're using `split_into_train_test()` to split the dataset, it expects all images to be PNG, JPEG, or BMP—it ignores other file types. Download the yoga dataset
if not is_skip_step_1 and not use_custom_dataset: !wget -O yoga_poses.zip http://download.tensorflow.org/data/pose_classification/yoga_poses.zip !unzip -q yoga_poses.zip -d yoga_cg IMAGES_ROOT = "yoga_cg"
_____no_output_____
Apache-2.0
site/en-snapshot/lite/tutorials/pose_classification.ipynb
Icecoffee2500/docs-l10n
Preprocess the `TRAIN` dataset
if not is_skip_step_1: images_in_train_folder = os.path.join(IMAGES_ROOT, 'train') images_out_train_folder = 'poses_images_out_train' csvs_out_train_path = 'train_data.csv' preprocessor = MoveNetPreprocessor( images_in_folder=images_in_train_folder, images_out_folder=images_out_train_folder, ...
_____no_output_____
Apache-2.0
site/en-snapshot/lite/tutorials/pose_classification.ipynb
Icecoffee2500/docs-l10n
Preprocess the `TEST` dataset
if not is_skip_step_1: images_in_test_folder = os.path.join(IMAGES_ROOT, 'test') images_out_test_folder = 'poses_images_out_test' csvs_out_test_path = 'test_data.csv' preprocessor = MoveNetPreprocessor( images_in_folder=images_in_test_folder, images_out_folder=images_out_test_folder, csvs_out...
_____no_output_____
Apache-2.0
site/en-snapshot/lite/tutorials/pose_classification.ipynb
Icecoffee2500/docs-l10n
Part 2: Train a pose classification model that takes the landmark coordinates as input, and output the predicted labels.You'll build a TensorFlow model that takes the landmark coordinates and predicts the pose class that the person in the input image performs. The model consists of two submodels:* Submodel 1 calculate...
# Download the preprocessed CSV files which are the same as the output of step 1 if is_skip_step_1: !wget -O train_data.csv http://download.tensorflow.org/data/pose_classification/yoga_train_data.csv !wget -O test_data.csv http://download.tensorflow.org/data/pose_classification/yoga_test_data.csv csvs_out_train_...
_____no_output_____
Apache-2.0
site/en-snapshot/lite/tutorials/pose_classification.ipynb
Icecoffee2500/docs-l10n
Load the preprocessed CSVs into `TRAIN` and `TEST` datasets.
def load_pose_landmarks(csv_path): """Loads a CSV created by MoveNetPreprocessor. Returns: X: Detected landmark coordinates and scores of shape (N, 17 * 3) y: Ground truth labels of shape (N, label_count) classes: The list of all class names found in the dataset dataframe: The CSV loaded as a Pan...
_____no_output_____
Apache-2.0
site/en-snapshot/lite/tutorials/pose_classification.ipynb
Icecoffee2500/docs-l10n
Load and split the original `TRAIN` dataset into `TRAIN` (85% of the data) and `VALIDATE` (the remaining 15%).
# Load the train data X, y, class_names, _ = load_pose_landmarks(csvs_out_train_path) # Split training data (X, y) into (X_train, y_train) and (X_val, y_val) X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.15) # Load the test data X_test, y_test, _,...
_____no_output_____
Apache-2.0
site/en-snapshot/lite/tutorials/pose_classification.ipynb
Icecoffee2500/docs-l10n
Define functions to convert the pose landmarks to a pose embedding (a.k.a. feature vector) for pose classificationNext, convert the landmark coordinates to a feature vector by:1. Moving the pose center to the origin.2. Scaling the pose so that the pose size becomes 13. Flattening these coordinates into a feature vecto...
def get_center_point(landmarks, left_bodypart, right_bodypart): """Calculates the center point of the two given landmarks.""" left = tf.gather(landmarks, left_bodypart.value, axis=1) right = tf.gather(landmarks, right_bodypart.value, axis=1) center = left * 0.5 + right * 0.5 return center def get_pose_size...
_____no_output_____
Apache-2.0
site/en-snapshot/lite/tutorials/pose_classification.ipynb
Icecoffee2500/docs-l10n
Define a Keras model for pose classificationOur Keras model takes the detected pose landmarks, then calculates the pose embedding and predicts the pose class.
# Define the model inputs = tf.keras.Input(shape=(51)) embedding = landmarks_to_embedding(inputs) layer = keras.layers.Dense(128, activation=tf.nn.relu6)(embedding) layer = keras.layers.Dropout(0.5)(layer) layer = keras.layers.Dense(64, activation=tf.nn.relu6)(layer) layer = keras.layers.Dropout(0.5)(layer) outputs = ...
_____no_output_____
Apache-2.0
site/en-snapshot/lite/tutorials/pose_classification.ipynb
Icecoffee2500/docs-l10n
Draw the confusion matrix to better understand the model performance
def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """Plots the confusion matrix.""" if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confus...
_____no_output_____
Apache-2.0
site/en-snapshot/lite/tutorials/pose_classification.ipynb
Icecoffee2500/docs-l10n
(Optional) Investigate incorrect predictionsYou can look at the poses from the `TEST` dataset that were incorrectly predicted to see whether the model accuracy can be improved.Note: This only works if you have run step 1 because you need the pose image files on your local machine to display them.
if is_skip_step_1: raise RuntimeError('You must have run step 1 to run this cell.') # If step 1 was skipped, skip this step. IMAGE_PER_ROW = 3 MAX_NO_OF_IMAGE_TO_PLOT = 30 # Extract the list of incorrectly predicted poses false_predict = [id_in_df for id_in_df in range(len(y_test)) \ if y_pred_label...
_____no_output_____
Apache-2.0
site/en-snapshot/lite/tutorials/pose_classification.ipynb
Icecoffee2500/docs-l10n
Part 3: Convert the pose classification model to TensorFlow LiteYou'll convert the Keras pose classification model to the TensorFlow Lite format so that you can deploy it to mobile apps, web browsers and IoT devices. When converting the model, you'll apply [dynamic range quantization](https://www.tensorflow.org/lite/p...
converter = tf.lite.TFLiteConverter.from_keras_model(model) converter.optimizations = [tf.lite.Optimize.DEFAULT] tflite_model = converter.convert() print('Model size: %dKB' % (len(tflite_model) / 1024)) with open('pose_classifier.tflite', 'wb') as f: f.write(tflite_model)
_____no_output_____
Apache-2.0
site/en-snapshot/lite/tutorials/pose_classification.ipynb
Icecoffee2500/docs-l10n
Then you'll write the label file which contains mapping from the class indexes to the human readable class names.
with open('pose_labels.txt', 'w') as f: f.write('\n'.join(class_names))
_____no_output_____
Apache-2.0
site/en-snapshot/lite/tutorials/pose_classification.ipynb
Icecoffee2500/docs-l10n
As you've applied quantization to reduce the model size, let's evaluate the quantized TFLite model to check whether the accuracy drop is acceptable.
def evaluate_model(interpreter, X, y_true): """Evaluates the given TFLite model and return its accuracy.""" input_index = interpreter.get_input_details()[0]["index"] output_index = interpreter.get_output_details()[0]["index"] # Run predictions on all given poses. y_pred = [] for i in range(len(y_true)): ...
_____no_output_____
Apache-2.0
site/en-snapshot/lite/tutorials/pose_classification.ipynb
Icecoffee2500/docs-l10n
Now you can download the TFLite model (`pose_classifier.tflite`) and the label file (`pose_labels.txt`) to classify custom poses. See the [Android](https://github.com/tensorflow/examples/tree/master/lite/examples/pose_estimation/android) and [Python/Raspberry Pi](https://github.com/tensorflow/examples/tree/master/lite/...
!zip pose_classifier.zip pose_labels.txt pose_classifier.tflite # Download the zip archive if running on Colab. try: from google.colab import files files.download('pose_classifier.zip') except: pass
_____no_output_____
Apache-2.0
site/en-snapshot/lite/tutorials/pose_classification.ipynb
Icecoffee2500/docs-l10n
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns train = pd.read_csv('/content/sample_data/california_housing_test.csv') test = pd.read_csv('/content/sample_data/california_housing_train.csv') train.head() test.head() train.describe() train.hist(figsize=(15,13), grid=False, b...
_____no_output_____
MIT
california_housing.ipynb
crazrycoin/Open-source
In this tutorial, we will learn how to plot a variable "Boundary layer height" for a particular output of WRF model.Referrence: https://wrf-python.readthedocs.io/en/latest/index.html 1. Import libraries
# Loading necessary libraries import numpy as np from netCDF4 import Dataset import matplotlib.pyplot as plt from matplotlib.cm import get_cmap import cartopy.crs as crs from cartopy.feature import NaturalEarthFeature from wrf import (to_np, getvar, smooth2d, get_cartopy, cartopy_xlim, cartopy_ylim, l...
_____no_output_____
MIT
notebook/06 WRF Python - Boundary layer height plot.ipynb
sonnymetvn/Basic-Python-for-Meteorology
2. Download data
# specify where is the location of the data path_in = "data/" path_out = "./" # Open the NetCDF file ncfile = Dataset(path_in + 'wrfout_d01_2016-05-09_00^%00^%00')
_____no_output_____
MIT
notebook/06 WRF Python - Boundary layer height plot.ipynb
sonnymetvn/Basic-Python-for-Meteorology
3. Take out the variables
# Get the boundary layer height PBLH = getvar(ncfile, "PBLH") print(PBLH.dims)
('south_north', 'west_east')
MIT
notebook/06 WRF Python - Boundary layer height plot.ipynb
sonnymetvn/Basic-Python-for-Meteorology
4. Plotting
PBLH.plot()
_____no_output_____
MIT
notebook/06 WRF Python - Boundary layer height plot.ipynb
sonnymetvn/Basic-Python-for-Meteorology
This notebook shows you how to create and query a table or DataFrame loaded from data stored in Azure Blob storage.
from pyspark.sql.functions import lit from pyspark.sql.types import BinaryType,StringType from pyspark.sql import SparkSession
_____no_output_____
Apache-2.0
notebooks/ch04-05_Caltech256 - Loading and process Images Data.ipynb
adipolak/ml-with-apache-spark
Step 1: Set the data location and typeThere are two ways to access Azure Blob storage: account keys and shared access signatures (SAS).To get started, we need to set the location and type of the file.
file_location = "256_sampledata/"
_____no_output_____
Apache-2.0
notebooks/ch04-05_Caltech256 - Loading and process Images Data.ipynb
adipolak/ml-with-apache-spark
Step 2: Read the dataNow that we have specified our file metadata, we can create a DataFrame. Notice that we use an *option* to specify that we want to infer the schema from the file. We can also explicitly set this to a particular schema if we have one already.First, let's create a DataFrame in Python.
! ls -l "256_sampledata" # start Spark session: spark = SparkSession \ .builder \ .appName("Marhselling Image data") \ .config("spark.memory.offHeap.enabled",True) \ .config("spark.memory.offHeap.size","30g")\ .getOrCreate() spark.sql("set spark.sql.files.ignoreCorruptFiles=true") df = spark.read...
_____no_output_____
Apache-2.0
notebooks/ch04-05_Caltech256 - Loading and process Images Data.ipynb
adipolak/ml-with-apache-spark
preprocess 1. Extract labels 2. Extract size 3. transform labels to index Regex expressionNotice that every path file can be different, you will need to tweak the actual regex experssion to fit your file path. for that, take a look at an example of the file path and experiement with a [regex calculator](https://regex...
df.select("path").show(5, truncate=False) import io import numpy as np import pandas as pd import uuid from pyspark.sql.functions import col, pandas_udf, regexp_extract from PIL import Image def extract_label(path_col): """Extract label category number from file path using built-in sql function""" #([^/]+) retu...
+--------------------+-------------+------------+--------------------+ | path| label| size| content| +--------------------+-------------+------------+--------------------+ |file:/home/jovyan...| 249.yo-yo|{1500, 1500}|[FF D8 FF E0 00 1...| |file:/home/jovyan...|196.spaghetti|...
Apache-2.0
notebooks/ch04-05_Caltech256 - Loading and process Images Data.ipynb
adipolak/ml-with-apache-spark
Transform label to index 1st way - the python way
labels = images_w_label_size.select(col("label")).distinct().collect() label_to_idx = {label: index for index,(label,) in enumerate(sorted(labels))} num_classes = len(label_to_idx) @pandas_udf("long") def get_label_idx(labels): return labels.map(lambda label: label_to_idx[label]) labels_idx = images_w_label_size.s...
+-------------+-----------+--------------------+--------------------+------------+ | label|label_index| content| path| size| +-------------+-----------+--------------------+--------------------+------------+ | 249.yo-yo| 3|[FF D8 FF E0 00 1...|file:/home/jovyan...|{1...
Apache-2.0
notebooks/ch04-05_Caltech256 - Loading and process Images Data.ipynb
adipolak/ml-with-apache-spark
2nd way - the mllib way
from pyspark.ml.feature import StringIndexer indexer = StringIndexer(inputCol="label", outputCol="label_index") indexed = indexer.fit(images_w_label_size).transform(images_w_label_size) indexed.show(10) indexed.select("label_index").distinct().collect()
_____no_output_____
Apache-2.0
notebooks/ch04-05_Caltech256 - Loading and process Images Data.ipynb
adipolak/ml-with-apache-spark
3rd way - from the label itself
def extract_index_from_label(label): """Extract index from label""" return regexp_extract(label,"^([^.]+)",1) labels_idx = images_w_label_size.select( col("label"), extract_index_from_label(col("label")).alias("label_index"), col("content"), col("path"), col("size")) labels_idx.show(5,trunca...
_____no_output_____
Apache-2.0
notebooks/ch04-05_Caltech256 - Loading and process Images Data.ipynb
adipolak/ml-with-apache-spark
Step 3: Feature EngineeringExtracting greyscale images.Greyscale is used as an example of feature we might want to extract.
df.printSchema()
root |-- path: string (nullable = true) |-- label: string (nullable = true) |-- size: struct (nullable = true) | |-- width: integer (nullable = true) | |-- height: integer (nullable = true) |-- content: binary (nullable = true) |-- label_index: double (nullable = false)
Apache-2.0
notebooks/ch04-05_Caltech256 - Loading and process Images Data.ipynb
adipolak/ml-with-apache-spark
calculate average image size for each category1. flat the column into two columns2. calculate average size for category3. resize according to average.
# 1st step - flatten the struact flattened = df.withColumn('width', col('size')['width']) flattened = flattened.withColumn('height', col('size')['height']) flattened.select('width','height').show(3, truncate = False) # 2 - calculate average size for category import pandas as pd from pyspark.sql.functions import pandas...
+------------------+ |pandas_mean(width)| +------------------+ | 165992| +------------------+ +-------------+------------------+ | label|pandas_mean(width)| +-------------+------------------+ |196.spaghetti| 39019| | 249.yo-yo| 40944| | 234.tweezer| 34513| | ...
Apache-2.0
notebooks/ch04-05_Caltech256 - Loading and process Images Data.ipynb
adipolak/ml-with-apache-spark
Extract greyscale
# Sample python native function that can do additional processing - expects pandas df as input and returns pandas df as output. def add_grayscale_img(input_df): # Set up return frame. In this case I'll have a row per passed in row. You could be aggregating down to a single image, slicing # out columns,or just abo...
_____no_output_____
Apache-2.0
notebooks/ch04-05_Caltech256 - Loading and process Images Data.ipynb
adipolak/ml-with-apache-spark
Test on small data
pd_df = limited_df.limit(5).toPandas() print(pd_df.columns) limited_df = None
_____no_output_____
Apache-2.0
notebooks/ch04-05_Caltech256 - Loading and process Images Data.ipynb
adipolak/ml-with-apache-spark
Make sure function works correctly
# Some testing code test_df = pd_df.copy() add_grayscale_img(test_df) print(test_df['grayscale_image']) from PIL import ImageFilter # Sample python native function that can do additional processing - expects pandas df as input and returns pandas df as output. def add_laplas(input_df): # Set up return frame. In th...
_____no_output_____
Apache-2.0
notebooks/ch04-05_Caltech256 - Loading and process Images Data.ipynb
adipolak/ml-with-apache-spark
Full Dataset
output_df.show(2, truncate=True) output_df.printSchema()
root |-- path: string (nullable = true) |-- label: string (nullable = true) |-- size: struct (nullable = true) | |-- width: integer (nullable = true) | |-- height: integer (nullable = true) |-- content: binary (nullable = true) |-- label_index: double (nullable = false) |-- grayscale_image: binary (nullab...
Apache-2.0
notebooks/ch04-05_Caltech256 - Loading and process Images Data.ipynb
adipolak/ml-with-apache-spark
Step 5: scale the imageFrom the size column, we notice that caltech_256 image size highly varay. To proced with the process, we need to scale the images to have a unannimous size. For tha we will use Spark UDFs with PIL.This is a must do part of normalizing and preprocessing image data.
from pyspark.sql.types import BinaryType, IntegerType from pyspark.sql.functions import udf img_size = 224 def scale_image(image_bytes): try: image = Image.open(io.BytesIO(image_bytes)).resize([img_size, img_size]) return image.tobytes() except: return None array = output_df.select("conten...
root |-- label_index: double (nullable = false) |-- content: binary (nullable = true)
Apache-2.0
notebooks/ch04-05_Caltech256 - Loading and process Images Data.ipynb
adipolak/ml-with-apache-spark
Step 4: Save and Avoid small files problemSave the image data into a file format where you can query and process at scaleSaving the dataset with the greyscale. Repartition and save to **parquet**
# incase you are running on a distributed environment, with a large dataset, it's a good idea to partition t # save the data: save_path_augmented = "images_data/silver/augmented" # Images data is already compressed so we turn off parquet compression compression = spark.conf.get("spark.sql.parquet.compression.codec") ...
_____no_output_____
Apache-2.0
notebooks/ch04-05_Caltech256 - Loading and process Images Data.ipynb
adipolak/ml-with-apache-spark
Histogram* Create a histogram to visualize the most common salary ranges for employees.
# x_axis = sal_title_group_clean['salary'] # y_axis = plt.hist(emp_title_merged['salary'], color="red" ) plt.title('Salary Ranges for Employees') plt.xlabel('Salary Range ($)') plt.ylabel('Employee Count') plt.grid(alpha=0.5) plt.show() plt.tight_layout()
_____no_output_____
ADSL
EmployeeSQL/Working files/SQL BONUS.ipynb
key12pat34/SQL-challenge-hw7
Bar Chart* Create a bar chart of average salary by title.
x_axis = sal_title_group_clean['title'] y_axis = sal_title_group_clean['salary'] plt.bar(x_axis, y_axis, align = 'center', alpha=0.75, color = ['red','green','blue', 'black', 'orange', 'grey', 'purple']) plt.xticks(rotation = 'vertical') plt.title("Average Salary by Title") plt.xlabel("Employee Titles") plt.ylabel("S...
_____no_output_____
ADSL
EmployeeSQL/Working files/SQL BONUS.ipynb
key12pat34/SQL-challenge-hw7
Exercícios
data = [[1,2,3],[4,5,6],[7,8,9]] list('CBA') list('ZYX') df = pd.DataFrame(data, list('zyx'), list('cba')) df df.sort_index() df.sort_index(axis = 1) df
_____no_output_____
MIT
Pandas/Dados/extras/extras/Organizando DataFrames (Sort).ipynb
lingsv/alura_ds
JWST Pipeline Validation Testing Notebook: Calwebb_detector1, reset step for MIRI **Instruments Affected**: MIRI Table of Contents [Imports](imports_ID) [Introduction](intro_ID) [Get Documentaion String for Markdown Blocks](markdown_from_docs) [Loading Data](data_ID) [Run JWST Pipeline](pipeline_ID) [Create Figu...
from ci_watson.artifactory_helpers import get_bigdata import inspect from IPython.display import Markdown from jwst.dq_init import DQInitStep from jwst.reset import ResetStep from jwst.datamodels import RampModel import matplotlib.pyplot as plt import numpy as np
_____no_output_____
BSD-3-Clause
jwst_validation_notebooks/reset/jwst_reset_miri_test/jwst_reset_miri_testing.ipynb
jbhagan/jwst_validation_notebooks
IntroductionFor this test we are using the reset step in the calwebb_detector1 pipeline. For MIRI exposures, the initial groups in each integration suffer from two effects related to the resetting of the detectors. The first effect is that the first few groups after a reset do not fall on the expected linear accumulat...
# Get raw python docstring raw = inspect.getdoc(ResetStep) # To convert to markdown, you need convert line breaks from \n to <br /> markdown_text = "<br />".join(raw.split("\n")) # Here you can format markdown as an output using the Markdown method. Markdown(""" # ResetStep --- {} """.format(markdown_text))
_____no_output_____
BSD-3-Clause
jwst_validation_notebooks/reset/jwst_reset_miri_test/jwst_reset_miri_testing.ipynb
jbhagan/jwst_validation_notebooks
Loading DataThe data used to test this step is a dark data file taken as part of pre-launch ground testing. The original file name is MIRV00330001001P0000000002101_1_493_SE_2017-09-07T15h14m25.fits that was renamed to jw02201001001_01101_00001_MIRIMAGE_uncal.fits with a script that updates the file to put it in pipeli...
filename = get_bigdata('jwst_validation_notebooks', 'validation_data', 'reset', 'reset_miri_test', 'jw02201001001_01101_00001_MIRIMAGE_uncal.fits')
_____no_output_____
BSD-3-Clause
jwst_validation_notebooks/reset/jwst_reset_miri_test/jwst_reset_miri_testing.ipynb
jbhagan/jwst_validation_notebooks
Run JWST PipelineTake the initial input file and run it through both dq_init and reset to get the before and after correction versions of the data to run.[Top of Page](title_ID)
preim = DQInitStep.call(filename) postim = ResetStep.call(preim)
_____no_output_____
BSD-3-Clause
jwst_validation_notebooks/reset/jwst_reset_miri_test/jwst_reset_miri_testing.ipynb
jbhagan/jwst_validation_notebooks
Show plots and take statistics before and after correctionFor a specific pixel in the dark data:1. Plot the ramps before and after the correction to see if the initial frame values are more in line with the rest of the ramp.2. Fit a line to the ramps and calculate the slope and residuals. The slope should be closer to...
# set input variables print('Shape of data cube: integrations, groups, ysize, xsize ',preim.shape) xval = 650 yval = 550 framenum = 20 # number of frames to plot (reset only corrects first few frames in cube) intsnum = 3 # number of integrations to plot (3 should show reset and not crowd) # put data into prope...
_____no_output_____
BSD-3-Clause
jwst_validation_notebooks/reset/jwst_reset_miri_test/jwst_reset_miri_testing.ipynb
jbhagan/jwst_validation_notebooks
First plot should show that after the correction, the drop at the early part of the ramp has evened out to resemble the data in the rest of the ramp.
# Plot frames vs. counts for a dark pixel before and after correction # loop through integrations for i in range(0, intsnum): # get locations of flagged pixels within the ramps ramp1 = impre.data[i, 0:framenum, yval, xval] ramp2 = impost.data[i, 0:framenum, yval, xval] # plot ramps of selected pixels...
_____no_output_____
BSD-3-Clause
jwst_validation_notebooks/reset/jwst_reset_miri_test/jwst_reset_miri_testing.ipynb
jbhagan/jwst_validation_notebooks
Take a single pixel in the file, before and after the correction, and fit a line to them. After the correction, for a dark, the slope should be closer to zero and the residuals should be much lower.
# get array of frame numbers and choose ramps for selected pixel frames = np.arange(0, framenum) preramp = impre.data[0, 0:framenum, yval, xval] postramp = impost.data[0, 0:framenum, yval, xval] # get slopes of selected pixel before and after correction and see if it is more linear fit = np.polyfit(frames, preramp, ...
_____no_output_____
BSD-3-Clause
jwst_validation_notebooks/reset/jwst_reset_miri_test/jwst_reset_miri_testing.ipynb
jbhagan/jwst_validation_notebooks
Plot the residuals for the linear fit before and after correction for the specified pixel to see if the plotted ramp is flatter after the correction.
# show line plus residual for 1st int yfit = np.polyval(fit[0], frames) yfitcorr = np.polyval(fitpost[0], frames) plt.title('Residuals for ramp (single pixel) before and after reset') plt.xlabel('Frames') plt.ylabel('Residual: linear fit - data') plt.plot(frames, yfit - preramp, label='raw variance') plt.plot(frames, ...
_____no_output_____
BSD-3-Clause
jwst_validation_notebooks/reset/jwst_reset_miri_test/jwst_reset_miri_testing.ipynb
jbhagan/jwst_validation_notebooks
Basic Optimization
def f(x): return (x-3)**2 sp.optimize.minimize(f,2) sp.optimize.minimize(f,2).x sp.optimize.minimize(f,2).fun sp.optimize.minimize?
_____no_output_____
MIT
python/matplotlib/vector/basic/scipy.ipynb
karng87/nasm_game
$$ f(x,y) = (x-1)^2 + (y-2.5)^2 $$$$ x - 2y + 2 \geq 0 \\ -x - 2y + 6 \geq 0 \\ -x + 2y + 2 \geq 0 \\ x \geq 0 \\ y \geq 0$$
def f(x,y): return (x-1)**2 + (y-2.5)**2 def g(x,y): return x - 2*y + 2 def h(x,y): return -x - 2*y + 6 def k(x,y): return -x + 2*y +2 x = np.linspace(0,5,100) x,y = np.meshgrid(x,x) z = f(x,y) g = g(x,y) h = h(x,y) k = k(x,y) fig = plt.figure() ax = fig.add_subplot(projection='3d') ax.plot_surface(x...
_____no_output_____
MIT
python/matplotlib/vector/basic/scipy.ipynb
karng87/nasm_game
interpolate
x = np.linspace(0,10,10) y = x**2 * np.sin(x) fig = plt.figure() ax = fig.add_subplot() plt.scatter(x,y) f = sp.interpolate.interp1d(x,y,kind='linear') f = sp.interpolate.interp1d(x,y,kind='cubic') x_dense = np.linspace(0,10,100) y_dense = f(x_dense) ax.plot(x_dense,y_dense) def f(x): return x**2 +5 sp.integrate.q...
_____no_output_____
MIT
python/matplotlib/vector/basic/scipy.ipynb
karng87/nasm_game
{glue:text}`nteract_github_org`**Activity from {glue:}`nteract_start` to {glue:}`nteract_stop`**
from datetime import date from dateutil.relativedelta import relativedelta from myst_nb import glue import seaborn as sns import pandas as pd import numpy as np import altair as alt from markdown import markdown from IPython.display import Markdown from ipywidgets.widgets import HTML, Tab from ipywidgets import widgets...
_____no_output_____
BSD-3-Clause
monthly_update/generated/book/nteract.ipynb
choldgraf/jupyter-activity-snapshot
Load dataLoad and clean up the data
from pathlib import Path path_data = Path("../data") comments = pd.read_csv(path_data.joinpath('comments.csv'), index_col=None).drop_duplicates() issues = pd.read_csv(path_data.joinpath('issues.csv'), index_col=None).drop_duplicates() prs = pd.read_csv(path_data.joinpath('prs.csv'), index_col=None).drop_duplicates() f...
_____no_output_____
BSD-3-Clause
monthly_update/generated/book/nteract.ipynb
choldgraf/jupyter-activity-snapshot
Merged Pull requestsHere's an analysis of **merged pull requests** across each of the repositories in the Jupyterecosystem.
merged = prs.query('state == "MERGED" and closedAt > @start_date and closedAt < @stop_date') prs_by_repo = merged.groupby(['org', 'repo']).count()['author'].reset_index().sort_values(['org', 'author'], ascending=False) alt.Chart(data=prs_by_repo, title=f"Merged PRs in the last {n_days} days").mark_bar().encode( x=a...
_____no_output_____
BSD-3-Clause
monthly_update/generated/book/nteract.ipynb
choldgraf/jupyter-activity-snapshot
Authoring and merging stats by repositoryLet's see who has been doing most of the PR authoring and merging. The PR author is generally theperson that implemented a change in the repository (code, documentation, etc). The PR merger isthe person that "pressed the green button" and got the change into the main codebase.
# Prep our merging DF merged_by_repo = merged.groupby(['repo', 'author'], as_index=False).agg({'id': 'count', 'authorAssociation': 'first'}).rename(columns={'id': "authored", 'author': 'username'}) closed_by_repo = merged.groupby(['repo', 'mergedBy']).count()['id'].reset_index().rename(columns={'id': "closed", "mergedB...
_____no_output_____
BSD-3-Clause
monthly_update/generated/book/nteract.ipynb
choldgraf/jupyter-activity-snapshot
IssuesIssues are **conversations** that happen on our GitHub repositories. Here's ananalysis of issues across the Jupyter organizations.
created = issues.query('state == "OPEN" and createdAt > @start_date and createdAt < @stop_date') closed = issues.query('state == "CLOSED" and closedAt > @start_date and closedAt < @stop_date') created_counts = created.groupby(['org', 'repo']).count()['number'].reset_index() created_counts['org/repo'] = created_counts.a...
_____no_output_____
BSD-3-Clause
monthly_update/generated/book/nteract.ipynb
choldgraf/jupyter-activity-snapshot
Most-upvoted issues
thumbsup = issues.sort_values("thumbsup", ascending=False).head(25) thumbsup = thumbsup[["title", "url", "number", "thumbsup", "repo"]] text = [] for ii, irow in thumbsup.iterrows(): itext = f"- ({irow['thumbsup']}) {irow['title']} - {irow['repo']} - [#{irow['number']}]({irow['url']})" text.append(itext) text ...
_____no_output_____
BSD-3-Clause
monthly_update/generated/book/nteract.ipynb
choldgraf/jupyter-activity-snapshot
Commenters across repositoriesThese are commenters across all issues and pull requests in the last several days.These are colored by the commenter's association with the organization. For informationabout what these associations mean, [see this StackOverflow post](https://stackoverflow.com/a/28866914/1927102).
commentors = ( comments .query("createdAt > @start_date and createdAt < @stop_date") .groupby(['org', 'repo', 'author', 'authorAssociation']) .count().rename(columns={'id': 'count'})['count'] .reset_index() .sort_values(['org', 'count'], ascending=False) ) n_plot = 50 charts = [] for ii, (iorg, ...
_____no_output_____
BSD-3-Clause
monthly_update/generated/book/nteract.ipynb
choldgraf/jupyter-activity-snapshot
First respondersFirst responders are the first people to respond to a new issue in one of the repositories.The following plots show first responders for recently-created issues.
first_comments = [] for (org, repo, issue_id), i_comments in comments.groupby(['org', 'repo', 'id']): ix_min = pd.to_datetime(i_comments['createdAt']).idxmin() first_comment = i_comments.loc[ix_min] if isinstance(first_comment, pd.DataFrame): first_comment = first_comment.iloc[0] first_comments....
_____no_output_____
BSD-3-Clause
monthly_update/generated/book/nteract.ipynb
choldgraf/jupyter-activity-snapshot
Recent activity A list of merged PRs by projectBelow is a tabbed readout of recently-merged PRs. Check out the title to get an idea for what theyimplemented, and be sure to thank the PR author for their hard work!
tabs = widgets.Tab(children=[]) for ii, ((org, repo), imerged) in enumerate(merged.query("repo in @use_repos").groupby(['org', 'repo'])): merged_by = {} pr_by = {} issue_md = [] issue_md.append(f"#### Closed PRs for repo: [{org}/{repo}](https://github.com/{github_org}/{repo})") issue_md.append("") ...
_____no_output_____
BSD-3-Clause
monthly_update/generated/book/nteract.ipynb
choldgraf/jupyter-activity-snapshot
A list of recent issuesBelow is a list of issues with recent activity in each repository. If they seem of interestto you, click on their links and jump in to participate!
# Add comment count data to issues and PRs comment_counts = ( comments .query("createdAt > @start_date and createdAt < @stop_date") .groupby(['org', 'repo', 'id']) .count().iloc[:, 0].to_frame() ) comment_counts.columns = ['n_comments'] comment_counts = comment_counts.reset_index() n_plot = 5 tabs = wid...
_____no_output_____
BSD-3-Clause
monthly_update/generated/book/nteract.ipynb
choldgraf/jupyter-activity-snapshot
Title HeatMap Element Dependencies Matplotlib Backends Matplotlib Bokeh
import numpy as np import holoviews as hv hv.extension('matplotlib')
_____no_output_____
BSD-3-Clause
examples/reference/elements/matplotlib/HeatMap.ipynb
stuarteberg/holoviews
``HeatMap`` visualises tabular data indexed by two key dimensions as a grid of colored values. This allows spotting correlations in multivariate data and provides a high-level overview of how the two variables are plotted.The data for a ``HeatMap`` may be supplied as 2D tabular data with one or more associated value di...
data = [(chr(65+i), chr(97+j), i*j) for i in range(5) for j in range(5) if i!=j] hv.HeatMap(data).sort()
_____no_output_____
BSD-3-Clause
examples/reference/elements/matplotlib/HeatMap.ipynb
stuarteberg/holoviews
It is important to note that the data should be aggregated before plotting as the ``HeatMap`` cannot display multiple values for one coordinate and will simply use the first value it finds for each combination of x- and y-coordinates.
heatmap = hv.HeatMap([(0, 0, 1), (0, 0, 10), (1, 0, 2), (1, 1, 3)]) heatmap + heatmap.aggregate(function=np.max)
_____no_output_____
BSD-3-Clause
examples/reference/elements/matplotlib/HeatMap.ipynb
stuarteberg/holoviews
As the above example shows before aggregating the second value for the (0, 0) is ignored unless we aggregate the data first.To reveal the values of a ``HeatMap`` we can enable a ``colorbar`` and if you wish to have interactive hover information, you can use the hover tool in the [Bokeh backend](../bokeh/HeatMap.ipynb):
heatmap = hv.HeatMap((np.random.randint(0, 10, 100), np.random.randint(0, 10, 100), np.random.randn(100), np.random.randn(100)), vdims=['z', 'z2']).redim.range(z=(-2, 2)) heatmap.opts(colorbar=True, fig_size=250)
_____no_output_____
BSD-3-Clause
examples/reference/elements/matplotlib/HeatMap.ipynb
stuarteberg/holoviews
決策樹學習 - 分類樹 (以RR Lyrae變星資料集為例)* [程式碼來源](http://www.astroml.org/book_figures/chapter9/fig_rrlyrae_decisiontree.htmlbook-fig-chapter9-fig-rrlyrae-decisiontree)
import numpy as np from matplotlib import pyplot as plt from sklearn.tree import DecisionTreeClassifier from astroML.datasets import fetch_rrlyrae_combined from astroML.utils import split_samples from astroML.utils import completeness_contamination #fetch_rrlyrae_combined? X, y = fetch_rrlyrae_combined() # 合併RR Lyrae...
_____no_output_____
MIT
notebooks/notebooks4ML/DecisionTreeClassifier_RRLyraeExample.ipynb
Astrohackers-TW/IANCUPythonMeetup
Generating benchmark data with 2 covariates p=30
import pandas as pd import toytree as tt import numpy as np import anndata as ad import os import toyplot as tp import toyplot.svg import seaborn as sns import benchmarks.scripts.tree_data_generation as tgen # tree depth d = 5 effect_sizes = [0.3, 0.5, 0.7, 0.9] # number of effects num_effects = 3 # baseline paramete...
/Users/johannes.ostner/opt/anaconda3/envs/scCODA_3/lib/python3.8/site-packages/anndata/_core/anndata.py:120: ImplicitModificationWarning: Transforming to str index. warnings.warn("Transforming to str index.", ImplicitModificationWarning)
BSD-3-Clause
benchmarks/2_covariates/generate_data_2_covariates.ipynb
bio-datascience/tascCODA_reproducibility
GANs
%matplotlib inline from fastai.gen_doc.nbdoc import * from fastai import * from fastai.vision import * from fastai.vision.gan import *
_____no_output_____
Apache-2.0
docs_src/vision.gan.ipynb
navjotts/fastai
GAN stands for [Generative Adversarial Nets](https://arxiv.org/pdf/1406.2661.pdf) and were invented by Ian Goodfellow. The concept is that we will train two models at the same time: a generator and a critic. The generator will try to make new images similar to the ones in our dataset, and the critic's job will try to c...
show_doc(GANLearner)
_____no_output_____
Apache-2.0
docs_src/vision.gan.ipynb
navjotts/fastai
This is the general constructor to create a GAN, you might want to use one of the factory methods that are easier to use. Create a GAN from [`data`](/vision.data.htmlvision.data), a `generator` and a `critic`. The [`data`](/vision.data.htmlvision.data) should have the inputs the `generator` will expect and the images w...
show_doc(GANLearner.from_learners)
_____no_output_____
Apache-2.0
docs_src/vision.gan.ipynb
navjotts/fastai
Directly creates a [`GANLearner`](/vision.gan.htmlGANLearner) from two [`Learner`](/basic_train.htmlLearner): one for the `generator` and one for the `critic`. The `switcher` and all `kwargs` will be passed to the initialization of [`GANLearner`](/vision.gan.htmlGANLearner) along with the following loss functions:- `lo...
show_doc(GANLearner.wgan)
_____no_output_____
Apache-2.0
docs_src/vision.gan.ipynb
navjotts/fastai
The Wasserstein GAN is detailed in [this article]. `switcher` and the `kwargs` will be passed to the [`GANLearner`](/vision.gan.htmlGANLearner) init, `clip`is the weight clipping. Switchers In any GAN training, you will need to tell the [`Learner`](/basic_train.htmlLearner) when to switch from generator to critic and ...
show_doc(FixedGANSwitcher, title_level=3) show_doc(FixedGANSwitcher.on_train_begin) show_doc(FixedGANSwitcher.on_batch_end) show_doc(AdaptiveGANSwitcher, title_level=3) show_doc(AdaptiveGANSwitcher.on_batch_end)
_____no_output_____
Apache-2.0
docs_src/vision.gan.ipynb
navjotts/fastai
Discriminative LR If you want to train your critic at a different learning rate than the generator, this will let you do it automatically (even if you have a learning rate schedule).
show_doc(GANDiscriminativeLR, title_level=3) show_doc(GANDiscriminativeLR.on_batch_begin) show_doc(GANDiscriminativeLR.on_step_end)
_____no_output_____
Apache-2.0
docs_src/vision.gan.ipynb
navjotts/fastai
Specific models
show_doc(basic_critic)
_____no_output_____
Apache-2.0
docs_src/vision.gan.ipynb
navjotts/fastai
This model contains a first 4 by 4 convolutional layer of stride 2 from `n_channels` to `n_features` followed by `n_extra_layers` 3 by 3 convolutional layer of stride 1. Then we put as many 4 by 4 convolutional layer of stride 2 with a number of features multiplied by 2 at each stage so that the `in_size` becomes 1. `k...
show_doc(basic_generator)
_____no_output_____
Apache-2.0
docs_src/vision.gan.ipynb
navjotts/fastai
This model contains a first 4 by 4 transposed convolutional layer of stride 1 from `noise_size` to the last numbers of features of the corresponding critic. Then we put as many 4 by 4 transposed convolutional layer of stride 2 with a number of features divided by 2 at each stage so that the image ends up being of heigh...
show_doc(gan_critic) show_doc(GANTrainer)
_____no_output_____
Apache-2.0
docs_src/vision.gan.ipynb
navjotts/fastai
[`LearnerCallback`](/basic_train.htmlLearnerCallback) that will be responsible to handle the two different optimizers (one for the generator and one for the critic), and do all the work behind the scenes so that the generator (or the critic) are in training mode with parameters requirement gradients each time we switch...
show_doc(GANTrainer.switch)
_____no_output_____
Apache-2.0
docs_src/vision.gan.ipynb
navjotts/fastai
If `gen_mode` is left as `None`, just put the model in the other mode (critic if it was in generator mode and vice versa).
show_doc(GANTrainer.on_train_begin) show_doc(GANTrainer.on_epoch_begin) show_doc(GANTrainer.on_batch_begin) show_doc(GANTrainer.on_backward_begin) show_doc(GANTrainer.on_epoch_end) show_doc(GANTrainer.on_train_end)
_____no_output_____
Apache-2.0
docs_src/vision.gan.ipynb
navjotts/fastai
Specific modules
show_doc(GANModule, title_level=3)
_____no_output_____
Apache-2.0
docs_src/vision.gan.ipynb
navjotts/fastai
If `gen_mode` is left as `None`, just put the model in the other mode (critic if it was in generator mode and vice versa).
show_doc(GANModule.switch) show_doc(GANLoss, title_level=3) show_doc(AdaptiveLoss, title_level=3) show_doc(accuracy_thresh_expand)
_____no_output_____
Apache-2.0
docs_src/vision.gan.ipynb
navjotts/fastai
Data Block API
show_doc(NoisyItem, title_level=3) show_doc(GANItemList, title_level=3)
_____no_output_____
Apache-2.0
docs_src/vision.gan.ipynb
navjotts/fastai
Inputs will be [`NoisyItem`](/vision.gan.htmlNoisyItem) of `noise_sz` while the default class for target is [`ImageItemList`](/vision.data.htmlImageItemList).
show_doc(GANItemList.show_xys) show_doc(GANItemList.show_xyzs)
_____no_output_____
Apache-2.0
docs_src/vision.gan.ipynb
navjotts/fastai
Undocumented Methods - Methods moved below this line will intentionally be hidden
show_doc(GANLoss.critic) show_doc(GANModule.forward) show_doc(GANLoss.generator) show_doc(NoisyItem.apply_tfms) show_doc(AdaptiveLoss.forward) show_doc(GANItemList.get) show_doc(GANItemList.reconstruct) show_doc(AdaptiveLoss.forward)
_____no_output_____
Apache-2.0
docs_src/vision.gan.ipynb
navjotts/fastai
解析庫
BeautifulSoup(markup, "html.parser") BeautifulSoup(markup, "lxml") BeautifulSoup(markup, "xml") BeautifulSoup(markup, "html5lib")
_____no_output_____
MIT
BeautifulSoup.ipynb
Pytoddler/Web-scraping
基本使用
#引入requests好爬取html檔案給bs4使用 import requests response = requests.get('http://ntumail.cc.ntu.edu.tw') response.encoding = 'UTF-8' #加入encoding的方法避免中文亂碼 html = response.text from bs4 import BeautifulSoup soup = BeautifulSoup(html,'html.parser') print(soup.prettify()) #會把html漂亮輸出 print(soup.title.string)
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/> <title> NTU Mail-臺灣大學電子郵件系統 </title> <link href="images/style.cs...
MIT
BeautifulSoup.ipynb
Pytoddler/Web-scraping