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
Task: implement TF-IDF featuresNot all words are equally useful. One can prioritize rare words and downscale words like "and"/"or" by using __tf-idf features__. This abbreviation stands for __text frequency/inverse document frequence__ and means exactly that:$$ feature_i = { Count(word_i \in x) \times { log {N \over C...
def tf_idf(texts_collection, a = 1): global_counts = text_to_bow(' '.join(texts_collection)) return np.stack(list(map(text_to_bow, texts_train))) * np.log(len(texts_collection)/(global_counts + a)) idf = np.log(len(texts_train)/(global_counts + 1)) X_train_tfidf = X_train_bow * idf X_test_tfidf = X_test_bow * i...
_____no_output_____
MIT
week02_classification/homework_part1.ipynb
andnlv/natural-language-processing
```````````````````````````````````````````````` Solving it better: word vectorsLet's try another approach: instead of counting per-word frequencies, we shall map all words to pre-trained word vectors and average over them to get text features.This should give us two key advantages: (1) we now have 10^2 features instea...
import gensim.downloader embeddings = gensim.downloader.load("fasttext-wiki-news-subwords-300") # If you're low on RAM or download speed, use "glove-wiki-gigaword-100" instead. Ignore all further asserts. type(embeddings) embeddings.get_vector('qweqw', ) def vectorize_sum(comment): """ implement a function th...
_____no_output_____
MIT
week02_classification/homework_part1.ipynb
andnlv/natural-language-processing
Assignments of Day 6
# Create a bank account class that has two attributes # arr = [] # arr.append([ownername,balance]) # for i in arr: # if self.name == i[0]: class bank: def __init__(self,ownername,balance): self.ownername = ownername self.balance = balance def deposit(self,amount): self....
you don't have enough cradit in your account, see you have only 5000
Apache-2.0
Day6 Assignment.ipynb
divi2398/Lakshmi.M
For this challenge,create a cone class that has two attributes:*R=Radius*h=HeightAnd two methods:*Volume = Π * r2 = (h/3)*Surface area : base : Π * r2 , side : Π * r * √(r2 + h2)Make only one class with functions,as in where required import Math.
import math class cone: def __init__(self,radius,height): self.radius=radius self.height=height def volume(self): vol = math.pi * (self.radius**2) * (self.height/3) print("Volume of this cone is : ",vol) def surfaceArea(self): area = math.pi* self.ra...
Surface area of this cone is 201.22293136239685
Apache-2.0
Day6 Assignment.ipynb
divi2398/Lakshmi.M
Data analysis with Python, Apache Spark, and PixieDust***In this notebook you will:* analyze customer demographics, such as, age, gender, income, and location* combine that data with sales data to examine trends for product categories, transaction types, and product popularity* load data from GitHub as well as from a...
import pixiedust import pyspark.sql.functions as func import pyspark.sql.types as types import re import json import os import requests
_____no_output_____
Apache-2.0
notebooks/analyze-customer-data.ipynb
aimazin/customer-data-with-spark
**If you get any errors or if a package is out of date:*** uncomment the lines in the next cell (remove the ``)* restart the kernel (from the Kernel menu at the top of the notebook)* reload the browser page* run the cell above, and continue with the notebook
#!pip install jinja2 --user --upgrade #!pip install pixiedust --user --upgrade #!pip install -U --no-deps bokeh
_____no_output_____
Apache-2.0
notebooks/analyze-customer-data.ipynb
aimazin/customer-data-with-spark
Load data into the notebookThe data file contains both the customer demographic data that you'll analyzed in Part 1, and the sales transaction data for Part 2.With `pixiedust.sampleData()` you can load csv data from any url. The below loads the data in a Spark DataFrame. > In case you wondered, this works with Pandas ...
raw_df = pixiedust.sampleData('https://raw.githubusercontent.com/IBM/analyze-customer-data-spark-pixiedust/master/data/customers_orders1_opt.csv') raw_df
_____no_output_____
Apache-2.0
notebooks/analyze-customer-data.ipynb
aimazin/customer-data-with-spark
[Back to Table of Contents](toc) Explore customer demographics In this part of the notebook, you will prepare the customer data and then start learning about your customers by creating multiple charts and maps. Prepare the customer data setCreate a new Spark DataFrame with only the data you need and then cleanse and ...
# Extract the customer information from the data set customer_df = raw_df.select("CUST_ID", "CUSTNAME", "ADDRESS1", "ADDRESS2", "CITY", "POSTAL_CODE", ...
_____no_output_____
Apache-2.0
notebooks/analyze-customer-data.ipynb
aimazin/customer-data-with-spark
Notice that the data type of the AGE column is currently a string. Convert the AGE column to a numeric data type so you can run calculations on customer age.
# --------------------------------------- # Cleanse age (enforce numeric data type) # --------------------------------------- def getNumericVal(col): """ input: pyspark.sql.types.Column output: the numeric value represented by col or None """ try: return int(col) except ValueError: ...
_____no_output_____
Apache-2.0
notebooks/analyze-customer-data.ipynb
aimazin/customer-data-with-spark
The GenderCode column contains salutations instead of gender values. Derive the gender information for each customer based on the salutation and rename the GenderCode column to GENDER.
# ------------------------------ # Derive gender from salutation # ------------------------------ def deriveGender(col): """ input: pyspark.sql.types.Column output: "male", "female" or "unknown" """ if col in ['Mr.', 'Master.']: return 'male' elif col in ['Mrs.', 'Miss.']: re...
_____no_output_____
Apache-2.0
notebooks/analyze-customer-data.ipynb
aimazin/customer-data-with-spark
Explore the customer data setInstead of exploring the data with `.printSchema()` and `.show()` you can quickly explore data sets using PixieDust'. Invoke the `display()` command and click the table icon to review the schema and preview the data. Customize the options to display only a subset of the fields or rows or a...
display(customer_df)
_____no_output_____
Apache-2.0
notebooks/analyze-customer-data.ipynb
aimazin/customer-data-with-spark
[Back to Table of Contents](toc) Visualize customer demographics and locationsNow you are ready to explore the customer base. Using simple charts, you can quickly see these characteristics: * Customer demographics (gender and age) * Customer locations (city, state, and country)You will create charts with the PixieDust ...
display(customer_df)
_____no_output_____
Apache-2.0
notebooks/analyze-customer-data.ipynb
aimazin/customer-data-with-spark
[Back to Table of Contents](toc) View customers by generation in a bar chartLook at how many customers you have per "generation."Run the next cell and configure the graph: 1. Choose **Bar Chart** as the chart type and configure the chart options as instructed below.2. Put `GENERATION` into the **Keys** box.3. Set **agg...
display(customer_df)
_____no_output_____
Apache-2.0
notebooks/analyze-customer-data.ipynb
aimazin/customer-data-with-spark
[Back to Table of Contents](toc) View customers by age in a histogram chartA generation is a broad age range. You can look at a smaller age range with a histogram chart. A histogram is like a bar chart except each bar represents a range of numbers, called a bin. You can customize the size of the age range by adjusting ...
display(customer_df)
_____no_output_____
Apache-2.0
notebooks/analyze-customer-data.ipynb
aimazin/customer-data-with-spark
[Back to Table of Contents](toc) View specific information with a filter functionYou can filter records to restrict analysis by using the [PySpark DataFrame](https://spark.apache.org/docs/latest/api/python/pyspark.sql.htmlpyspark.sql.DataFrame) `filter()` function.If you want to view the age distribution for a specific...
# Data subsetting: display age distribution for a specific generation # (Chart type: histogram, Chart Options > Values: AGE) # to change the filter condition remove the # sign condition = "GENERATION = 'Baby_Boomers'" #condition = "GENERATION = 'Gen_X'" #condition = "GENERATION = 'Gen_Y'" #condition = "GENERATION = 'G...
_____no_output_____
Apache-2.0
notebooks/analyze-customer-data.ipynb
aimazin/customer-data-with-spark
PixieDust supports basic filtering to make it easy to analyse data subsets. For example, to view the age distribution for a specific gender configure the chart as follows: 1. Choose `Histogram` as the chart type. 2. Put `AGE` into the **Values** box and click OK. 3. Click the filter button (looking like a funnel), a...
display(customer_df)
_____no_output_____
Apache-2.0
notebooks/analyze-customer-data.ipynb
aimazin/customer-data-with-spark
You can also filter by location. For example, the following command creates a new DataFrame that filters for customers from the USA:
condition = "COUNTRY_CODE = 'US'" us_customer_df = customer_df.filter(condition)
_____no_output_____
Apache-2.0
notebooks/analyze-customer-data.ipynb
aimazin/customer-data-with-spark
You can pivot your analysis perspective based on aspects that are of interest to you by choosing different keys and clusters.Create a bar chart and cluster the data.Run the next cell and configure the graph:1. Choose **Bar chart** as the chart type.2. Put `COUNTRY_CODE` into the **Keys** box.4. Set Aggregation to **COU...
display(us_customer_df)
_____no_output_____
Apache-2.0
notebooks/analyze-customer-data.ipynb
aimazin/customer-data-with-spark
Now try to cluster the customers by state.A bar chart isn't the best way to show geographic location! [Back to Table of Contents](toc) View customer density by location with a mapMaps are a much better way to view location data than other chart types. Visualize customer density by US state with a map.Run the next cell ...
display(us_customer_df)
_____no_output_____
Apache-2.0
notebooks/analyze-customer-data.ipynb
aimazin/customer-data-with-spark
[Back to Table of Contents](toc) Enrich demographic information with open dataYou can easily combine other sources of data with your existing data. There is a lot of publicly available open data sets that can be very helpful. For example, knowing the approximate income level of your customers might help you target your...
# Load median income information for all US ZIP codes from a public source income_df = pixiedust.sampleData('https://raw.githubusercontent.com/IBM/analyze-customer-data-spark-pixiedust/master/data/x19_income_select.csv') income_df.printSchema()
_____no_output_____
Apache-2.0
notebooks/analyze-customer-data.ipynb
aimazin/customer-data-with-spark
Now cleanse the income data set to remove the data that you don't need. Create a new DataFrame for this data: - The zip code, extracted from the GEOID column. - The column B19049e1, which contains the median household income for 2013.
# ------------------------------ # Helper: Extract ZIP code # ------------------------------ def extractZIPCode(col): """ input: pyspark.sql.types.Column containing a geo code, like '86000US01001' output: ZIP code """ m = re.match('^\d+US(\d\d\d\d\d)$',col) if m: return m.group(1) el...
_____no_output_____
Apache-2.0
notebooks/analyze-customer-data.ipynb
aimazin/customer-data-with-spark
Perform a left outer join on the customer data set with the income data set, using the zip code as the join condition. For the complete syntax of joins, go to the pyspark DataFrame documentation and scroll down to the `join` syntax.
us_customer_df = us_customer_df.join(income_df, us_customer_df.POSTAL_CODE == income_df.ZIP, 'left_outer').drop('GEOID').drop('ZIP') display(us_customer_df)
_____no_output_____
Apache-2.0
notebooks/analyze-customer-data.ipynb
aimazin/customer-data-with-spark
REINFORCE in lasagneJust like we did before for q-learning, this time we'll design a lasagne network to learn `CartPole-v0` via policy gradient (REINFORCE).Most of the code in this notebook is taken from approximate qlearning, so you'll find it more or less familiar and even simpler. __Frameworks__ - we'll accept this...
%env THEANO_FLAGS = 'floatX=float32' import os if type(os.environ.get("DISPLAY")) is not str or len(os.environ.get("DISPLAY")) == 0: !bash ../xvfb start os.environ['DISPLAY'] = ':1' import gym import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline env = gym.make("CartPole-v0"...
[2017-03-14 19:35:59,320] Making new env: CartPole-v0
Unlicense
week06_policy_based/reinforce_lasagne.ipynb
kianya/Practical_RL
Building the network for REINFORCE For REINFORCE algorithm, we'll need a model that predicts action probabilities given states.
import theano import theano.tensor as T # create input variables. We'll support multiple states at once states = T.matrix("states[batch,units]") actions = T.ivector("action_ids[batch]") cumulative_rewards = T.vector("G[batch] = r + gamma*r' + gamma^2*r'' + ...") import lasagne from lasagne.layers import * # input la...
_____no_output_____
Unlicense
week06_policy_based/reinforce_lasagne.ipynb
kianya/Practical_RL
Predict function
# get probabilities of actions predicted_probas = get_output(l_action_probas) # predict action probability given state # if you use float32, set allow_input_downcast=True predict_proba = <compile a function that takes states and returns predicted_probas >
_____no_output_____
Unlicense
week06_policy_based/reinforce_lasagne.ipynb
kianya/Practical_RL
Loss function and updatesWe now need to define objective and update over policy gradient.Our objective function is$$ J \approx { 1 \over N } \sum _{s_i,a_i} \pi_\theta (a_i | s_i) \cdot G(s_i,a_i) $$Following the REINFORCE algorithm, we can define our objective as follows: $$ \hat J \approx { 1 \over N } \sum _{s_i...
# select probabilities for chosen actions, pi(a_i|s_i) predicted_probas_for_actions = predicted_probas[T.arange( actions.shape[0]), actions] # REINFORCE objective function J = # <policy objective as in the last formula. Please use mean, not sum.> # all network weights all_weights = <get all "thetas" aka network we...
_____no_output_____
Unlicense
week06_policy_based/reinforce_lasagne.ipynb
kianya/Practical_RL
Computing cumulative rewards
def get_cumulative_rewards(rewards, # rewards at each step gamma=0.99 # discount for reward ): """ take a list of immediate rewards r(s,a) for the whole session compute cumulative returns (a.k.a. G(s,a) in Sutton '16) G_t = r_t + gamma*r_{t+1} +...
_____no_output_____
Unlicense
week06_policy_based/reinforce_lasagne.ipynb
kianya/Practical_RL
Playing the game
def generate_session(t_max=1000): """play env with REINFORCE agent and train at the session end""" # arrays to record session states, actions, rewards = [], [], [] s = env.reset() for t in range(t_max): # action probabilities array aka pi(a|s) action_probas = predict_proba([s])[0...
mean reward:20.900 mean reward:35.860 mean reward:50.820 mean reward:88.550 mean reward:132.080 mean reward:165.890 mean reward:193.790 mean reward:166.510 mean reward:120.910 mean reward:98.450 mean reward:236.340 mean reward:280.410 mean reward:317.610 You Win!
Unlicense
week06_policy_based/reinforce_lasagne.ipynb
kianya/Practical_RL
Video
# record sessions import gym.wrappers env = gym.wrappers.Monitor(gym.make("CartPole-v0"), directory="videos", force=True) sessions = [generate_session() for _ in range(100)] env.close() # show video from IPython.display import HTML import os video_names = list( filter(lambda s: s.endswit...
_____no_output_____
Unlicense
week06_policy_based/reinforce_lasagne.ipynb
kianya/Practical_RL
Reflect Tables into SQLALchemy ORM
# Python SQL toolkit and Object Relational Mapper import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func, inspect # create engine to hawaii.sqlite engine = create_engine("sqlite:///./Resources/hawaii.sqlite") # reflect an existing ...
_____no_output_____
MIT
.ipynb_checkpoints/temp_analysis_bonus_2_starter - Copy-checkpoint.ipynb
pratixashah/sqlalchemy
Bonus Challenge Assignment: Temperature Analysis II
# This function called `calc_temps` will accept start date and end date in the format '%Y-%m-%d' # and return the minimum, maximum, and average temperatures for that range of dates def calc_temps(start_date, end_date): """TMIN, TAVG, and TMAX for a list of dates. Args: start_date (string): A date ...
_____no_output_____
MIT
.ipynb_checkpoints/temp_analysis_bonus_2_starter - Copy-checkpoint.ipynb
pratixashah/sqlalchemy
Daily Rainfall Average
# Calculate the total amount of rainfall per weather station for your trip dates using the previous year's # matching dates. # Sort this in descending order by precipitation amount and list the station, name, latitude, longitude, and elevation # Use this function to calculate the daily normals # (i.e. the averages f...
_____no_output_____
MIT
.ipynb_checkpoints/temp_analysis_bonus_2_starter - Copy-checkpoint.ipynb
pratixashah/sqlalchemy
📝 Exercise M3.02The goal is to find the best set of hyperparameters which maximize thegeneralization performance on a training set.Here again with limit the size of the training set to make computationrun faster. Feel free to increase the `train_size` value if your computeris powerful enough.
import numpy as np import pandas as pd adult_census = pd.read_csv("../datasets/adult-census.csv") target_name = "class" target = adult_census[target_name] data = adult_census.drop(columns=[target_name, "education-num"]) from sklearn.model_selection import train_test_split data_train, data_test, target_train, target...
_____no_output_____
MIT
sklearn/notes/parameter_tuning_ex_03.ipynb
shamik-biswas-rft/CodeSnippets
In this exercise, we will progressively define the classification pipelineand later tune its hyperparameters.Our pipeline should:* preprocess the categorical columns using a `OneHotEncoder` and use a `StandardScaler` to normalize the numerical data.* use a `LogisticRegression` as a predictive model.Start by defining t...
from sklearn.compose import make_column_selector as selector # Write your code here. categorical_selector = selector(dtype_include=object) numerical_selector = selector(dtype_exclude=object) categorical_columns = categorical_selector(data) numerical_columns = numerical_selector(data) from sklearn.preprocessing import...
_____no_output_____
MIT
sklearn/notes/parameter_tuning_ex_03.ipynb
shamik-biswas-rft/CodeSnippets
Subsequently, create a `ColumnTransformer` to redirect the specific columnsa preprocessing pipeline.
from sklearn.compose import ColumnTransformer # Write your code here. preprocessor = ColumnTransformer( [ ('cat_process', cat_processor, categorical_columns), ('num_process', num_processor, numerical_columns) ])
_____no_output_____
MIT
sklearn/notes/parameter_tuning_ex_03.ipynb
shamik-biswas-rft/CodeSnippets
Assemble the final pipeline by combining the above preprocessorwith a logistic regression classifier. Force the maximum number ofiterations to `10_000` to ensure that the model will converge.
from sklearn.pipeline import make_pipeline from sklearn.linear_model import LogisticRegression # Write your code here. model = make_pipeline(preprocessor, LogisticRegression(max_iter=11_000))
_____no_output_____
MIT
sklearn/notes/parameter_tuning_ex_03.ipynb
shamik-biswas-rft/CodeSnippets
Use `RandomizedSearchCV` with `n_iter=20` to find the best set ofhyperparameters by tuning the following parameters of the `model`:- the parameter `C` of the `LogisticRegression` with values ranging from 0.001 to 10. You can use a log-uniform distribution (i.e. `scipy.stats.loguniform`);- the parameter `with_mean` of...
model.get_params() from sklearn.model_selection import RandomizedSearchCV from scipy.stats import loguniform # Write your code here. params_dict = { 'columntransformer__num_process__with_mean': [True, False], 'columntransformer__num_process__with_std': [True, False], 'logisticregression__C': loguniform(1e-...
Fitting 5 folds for each of 20 candidates, totalling 100 fits
MIT
sklearn/notes/parameter_tuning_ex_03.ipynb
shamik-biswas-rft/CodeSnippets
Stage 3: What do I need to install?Maybe your experience looks like the typical python dependency management (https://xkcd.com/1987/):Furthermore, data science packages can have all sorts of additional non-Python dependencies which makes things even more confusing, and we end up spending more time sorting out our depe...
from sklearn.preprocessing import StandardScaler import matplotlib.pyplot as plt import pandas as pd %matplotlib inline
_____no_output_____
MIT
notebooks/03-Environment-Challenge.ipynb
acwooding/easydata-tutorial
Updating your conda and pip environmentsThe `make` commands, `make create_environment` and `make update_environment` are wrappers that allow you to easily manage your conda and pip environments using a file called `environment.yml` file, which lists the packages you want in your python environment.(If you ever forget ...
%conda info
_____no_output_____
MIT
notebooks/03-Environment-Challenge.ipynb
acwooding/easydata-tutorial
Another useful cell to include is the following.If you want your environment changes to be immediately available in your running notebooks, make sure to run a notebook cell containing:
%load_ext autoreload %autoreload 2
_____no_output_____
MIT
notebooks/03-Environment-Challenge.ipynb
acwooding/easydata-tutorial
If you did your task correctly, the following import will succeed.
import seaborn as sns
_____no_output_____
MIT
notebooks/03-Environment-Challenge.ipynb
acwooding/easydata-tutorial
- First make sure that our notebook can display a simple widget. Some ppl might have trouble with this.
from ipywidgets import interact def f(x): return x interact(f, x=10)
_____no_output_____
MIT
demo.ipynb
w-hc/coco_vis
- If you see a slider that can be dragged, it's good. - Resolve any widget related notebook setup problems before proceeding
vis = Visualizer( coco_eval, matching_threshold=0.5, area='all', img_directory=img_directory )
_____no_output_____
MIT
demo.ipynb
w-hc/coco_vis
- the widget will disappear after each session. Have to re-run
vis.category_PR_curve() vis.image_vis()
_____no_output_____
MIT
demo.ipynb
w-hc/coco_vis
Load Data
key = data.get_output_keys()[2] key output = data.load_output(key) qf = torch.Tensor(output["qf"]) gf = torch.Tensor(output["gf"]) q_pids = np.array(output["q_pids"]) g_pids = np.array(output["g_pids"]) q_camids = np.array(output["q_camids"]) g_camids = np.array(output["g_camids"]) distmat = compute_distmat(qf, gf)
_____no_output_____
MIT
notebooks/Post Rank.ipynb
itsnamgyu/reid-metric
Baseline Results
result = evaluate(distmat, q_pids, g_pids, q_camids, g_camids) result
_____no_output_____
MIT
notebooks/Post Rank.ipynb
itsnamgyu/reid-metric
Re-ranked Results
all_distmat = compute_inner_distmat(torch.cat((qf, gf))) re_distmat = rerank_distmat(all_distmat, qf.shape[0]) re_result = evaluate(re_distmat, q_pids, g_pids, q_camids, g_camids) re_result
_____no_output_____
MIT
notebooks/Post Rank.ipynb
itsnamgyu/reid-metric
One-Shot Evaluation Using Modules Rocchio
ntot = torch.as_tensor rocchio.run(qf, gf, ntot(q_pids), ntot(g_pids), ntot(q_camids), ntot(g_camids), t=3)
_____no_output_____
MIT
notebooks/Post Rank.ipynb
itsnamgyu/reid-metric
Neighborhood Expansion (Min)
ntot = torch.from_numpy ne.run(qf, gf, ntot(q_pids), ntot(g_pids), ntot(q_camids), ntot(g_camids), t=3, method="min")
_____no_output_____
MIT
notebooks/Post Rank.ipynb
itsnamgyu/reid-metric
Neighborhood Expansion (Mean)
ntot = torch.from_numpy ne.run(qf, gf, ntot(q_pids), ntot(g_pids), ntot(q_camids), ntot(g_camids), t=3, method="mean")
_____no_output_____
MIT
notebooks/Post Rank.ipynb
itsnamgyu/reid-metric
Development Feedback Models
q_pids = torch.tensor(output["q_pids"]) g_pids = torch.tensor(output["g_pids"]) q = len(q_pids) g = len(g_pids) m = qf.shape[1] q_camids = np.array(output["q_camids"]) g_camids = np.array(output["g_camids"])
_____no_output_____
MIT
notebooks/Post Rank.ipynb
itsnamgyu/reid-metric
Naive Feedback
if input("reset? ") == "y": positive_indices = torch.zeros((q, g), dtype=bool) negative_indices = torch.zeros((q, g), dtype=bool) for i in tqdm(range(5)): qf_adjusted = qf # no adjust, naive re-rank distmat = compute_distmat(qf_adjusted, gf) distmat[positive_indices] = float("inf") distmat[neg...
_____no_output_____
MIT
notebooks/Post Rank.ipynb
itsnamgyu/reid-metric
Rocchio
if input("reset? ") == "y": positive_indices = torch.zeros((q, g), dtype=bool) negative_indices = torch.zeros((q, g), dtype=bool) alpha = 1 beta = 0.65 gamma = 0.35 qf_adjusted = qf for i in tqdm(range(5)): distmat = compute_distmat(qf_adjusted, gf) distmat[positive_indices] = float("inf") distmat[...
_____no_output_____
MIT
notebooks/Post Rank.ipynb
itsnamgyu/reid-metric
Function Tests (Rocchio)
def adjust_qf(qf, gf, positive_indices, negative_indices, alpha=1, beta=0.65, gamma=0.35): assert(qf.shape[1] == gf.shape[1]) mean_positive_gf = positive_indices.float().mm(gf) / positive_indices.float().sum(dim=1, keepdim=True) mean_negative_gf = negative_indices.float().mm(gf) / negative_indices.float().s...
_____no_output_____
MIT
notebooks/Post Rank.ipynb
itsnamgyu/reid-metric
Module Test (Naive)
positive_indices = None negative_indices = None distmat = None for i in tqdm(range(3)): distmat, positive_indices, negative_indices = feedback.naive_round( qf, gf, q_pids, g_pids, positive_indices, negative_indices, previous_distmat=distmat) naive_result = evaluate(distmat, q_pids, g_pids, q_camids, g_camid...
_____no_output_____
MIT
notebooks/Post Rank.ipynb
itsnamgyu/reid-metric
Module Test (Rocchio)
positive_indices = None negative_indices = None distmat = None for i in tqdm(range(3)): distmat, positive_indices, negative_indices = rocchio.rocchio_round( qf, gf, q_pids, g_pids, positive_indices, negative_indices, previous_distmat=distmat) rocchio_result = evaluate(distmat, q_pids, g_pids, q_camids, g_ca...
_____no_output_____
MIT
notebooks/Post Rank.ipynb
itsnamgyu/reid-metric
Single Feedback Rocchio (Old)Initial implementation test
g_pids = torch.Tensor(output["g_pids"]) q_pids = torch.Tensor(output["q_pids"]) match = g_pids[min_indices] == q_pids selected_gf = gf[min_indices] selected_gf.shape weights = match.float() * (beta + gamma) - gamma weighted_feedback = selected_gf * weights.reshape(-1, 1) weighted_feedback inverse_weights = 1 - weights ...
_____no_output_____
MIT
notebooks/Post Rank.ipynb
itsnamgyu/reid-metric
View source on GitHub Notebook Viewer Run in binder Run in Google Colab Install Earth Engine APIInstall the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geehydro](https://github.com/giswqs/geehydro). The **geehydro** Python package builds on the [folium](http...
# %%capture # !pip install earthengine-api # !pip install geehydro
_____no_output_____
MIT
Image/texture.ipynb
guy1ziv2/earthengine-py-notebooks
Import libraries
import ee import folium import geehydro
_____no_output_____
MIT
Image/texture.ipynb
guy1ziv2/earthengine-py-notebooks
Authenticate and initialize Earth Engine API. You only need to authenticate the Earth Engine API once. Uncomment the line `ee.Authenticate()` if you are running this notebook for this first time or if you are getting an authentication error.
# ee.Authenticate() ee.Initialize()
_____no_output_____
MIT
Image/texture.ipynb
guy1ziv2/earthengine-py-notebooks
Create an interactive map This step creates an interactive map using [folium](https://github.com/python-visualization/folium). The default basemap is the OpenStreetMap. Additional basemaps can be added using the `Map.setOptions()` function. The optional basemaps can be `ROADMAP`, `SATELLITE`, `HYBRID`, `TERRAIN`, or `...
Map = folium.Map(location=[40, -100], zoom_start=4) Map.setOptions('HYBRID')
_____no_output_____
MIT
Image/texture.ipynb
guy1ziv2/earthengine-py-notebooks
Add Earth Engine Python script
import math # Load a high-resolution NAIP image. image = ee.Image('USDA/NAIP/DOQQ/m_3712213_sw_10_1_20140613') # Zoom to San Francisco, display. Map.setCenter(-122.466123, 37.769833, 17) Map.addLayer(image, {'max': 255}, 'image') # Get the NIR band. nir = image.select('N') # Define a neighborhood with a kernel. squ...
_____no_output_____
MIT
Image/texture.ipynb
guy1ziv2/earthengine-py-notebooks
Display Earth Engine data layers
Map.setControlVisibility(layerControl=True, fullscreenControl=True, latLngPopup=True) Map
_____no_output_____
MIT
Image/texture.ipynb
guy1ziv2/earthengine-py-notebooks
TFMA Notebook exampleThis notebook describes how to export your model for TFMA and demonstrates the analysis tooling it offers.Note: Please make sure to follow the instructions in [README.md](https://github.com/tensorflow/tfx/blob/master/tfx/examples/chicago_taxi/README.md) when running this notebook SetupImport neces...
import apache_beam as beam import os import preprocess import shutil import tensorflow as tf import tensorflow_data_validation as tfdv import tensorflow_model_analysis as tfma from google.protobuf import text_format from tensorflow.python.lib.io import file_io from tensorflow_transform.beam.tft_beam_io import transf...
_____no_output_____
Apache-2.0
tfx/examples/chicago_taxi/chicago_taxi_tfma_local_playground.ipynb
yongsheng268/tfx
Helper functions and some constants for running the notebook locally.
BASE_DIR = os.getcwd() DATA_DIR = os.path.join(BASE_DIR, 'data') OUTPUT_DIR = os.path.join(BASE_DIR, 'chicago_taxi_output') # Base dir containing train and eval data TRAIN_DATA_DIR = os.path.join(DATA_DIR, 'train') EVAL_DATA_DIR = os.path.join(DATA_DIR, 'eval') # Base dir where TFT writes training data TFT_TRAIN_OU...
_____no_output_____
Apache-2.0
tfx/examples/chicago_taxi/chicago_taxi_tfma_local_playground.ipynb
yongsheng268/tfx
Clean up output directories.
shutil.rmtree(TFT_TRAIN_OUTPUT_BASE_DIR, ignore_errors=True) shutil.rmtree(TFT_EVAL_OUTPUT_BASE_DIR, ignore_errors=True) shutil.rmtree(TF_OUTPUT_BASE_DIR, ignore_errors=True) shutil.rmtree(get_schema_file(), ignore_errors=True)
_____no_output_____
Apache-2.0
tfx/examples/chicago_taxi/chicago_taxi_tfma_local_playground.ipynb
yongsheng268/tfx
Compute and visualize descriptive data statistics
# Compute stats over training data. train_stats = tfdv.generate_statistics_from_csv(data_location=os.path.join(TRAIN_DATA_DIR, 'data.csv')) # Visualize training data stats. tfdv.visualize_statistics(train_stats)
_____no_output_____
Apache-2.0
tfx/examples/chicago_taxi/chicago_taxi_tfma_local_playground.ipynb
yongsheng268/tfx
Infer a schema
# Infer a schema from the training data stats. schema = tfdv.infer_schema(statistics=train_stats, infer_feature_shape=False) tfdv.display_schema(schema=schema)
_____no_output_____
Apache-2.0
tfx/examples/chicago_taxi/chicago_taxi_tfma_local_playground.ipynb
yongsheng268/tfx
Check evaluation data for errors
# Compute stats over eval data. eval_stats = tfdv.generate_statistics_from_csv(data_location=os.path.join(EVAL_DATA_DIR, 'data.csv')) # Compare stats of eval data with training data. tfdv.visualize_statistics(lhs_statistics=eval_stats, rhs_statistics=train_stats, lhs_name='EVAL_DATASET', rhs_n...
_____no_output_____
Apache-2.0
tfx/examples/chicago_taxi/chicago_taxi_tfma_local_playground.ipynb
yongsheng268/tfx
Freeze the schemaNow that the schema has been reviewed and curated, we will store it in a file to reflect its "frozen" state.
file_io.recursive_create_dir(OUTPUT_DIR) file_io.write_string_to_file(get_schema_file(), text_format.MessageToString(schema))
_____no_output_____
Apache-2.0
tfx/examples/chicago_taxi/chicago_taxi_tfma_local_playground.ipynb
yongsheng268/tfx
Preprocess Inputstransform_data is defined in preprocess.py and uses the tensorflow_transform library to perform preprocessing. The same code is used for both local preprocessing in this notebook and preprocessing in the Cloud (via Dataflow).
# Transform eval data preprocess.transform_data(input_handle=os.path.join(EVAL_DATA_DIR, 'data.csv'), outfile_prefix=TFT_EVAL_FILE_PREFIX, working_dir=get_tft_eval_output_dir(0), schema_file=get_schema_file(), pipel...
_____no_output_____
Apache-2.0
tfx/examples/chicago_taxi/chicago_taxi_tfma_local_playground.ipynb
yongsheng268/tfx
Compute statistics over transformed data
# Compute stats over transformed training data. TRANSFORMED_TRAIN_DATA = os.path.join(get_tft_train_output_dir(0), TFT_TRAIN_FILE_PREFIX + "*") transformed_train_stats = tfdv.generate_statistics_from_tfrecord(data_location=TRANSFORMED_TRAIN_DATA) # Visualize transformed training data stats and compare to raw training ...
_____no_output_____
Apache-2.0
tfx/examples/chicago_taxi/chicago_taxi_tfma_local_playground.ipynb
yongsheng268/tfx
Prepare the ModelTo use TFMA, export the model into an **EvalSavedModel** by calling ``tfma.export.export_eval_savedmodel``.``tfma.export.export_eval_savedmodel`` is analogous to ``estimator.export_savedmodel`` but exports the evaluation graph as opposed to the training or inference graph. Notice that one of the input...
def run_experiment(hparams): """Run the training and evaluate using the high level API""" # Train and evaluate the model as usual. estimator = task.train_and_maybe_evaluate(hparams) # Export TFMA's sepcial EvalSavedModel eval_model_dir = os.path.join(hparams.output_dir, EVAL_MODEL_DIR) receive...
_____no_output_____
Apache-2.0
tfx/examples/chicago_taxi/chicago_taxi_tfma_local_playground.ipynb
yongsheng268/tfx
Train and export the model for TFMA
def run_local_experiment(tft_run_id, tf_run_id, num_layers, first_layer_size, scale_factor): """Helper method to train and export the model for TFMA The caller specifies the input and output directory by providing run ids. The optional parameters allows the user to change the modelfor time series view....
_____no_output_____
Apache-2.0
tfx/examples/chicago_taxi/chicago_taxi_tfma_local_playground.ipynb
yongsheng268/tfx
Run TFMA to compute metricsFor local analysis, TFMA offers a helper method ``tfma.run_model_analysis``
help(tfma.run_model_analysis)
_____no_output_____
Apache-2.0
tfx/examples/chicago_taxi/chicago_taxi_tfma_local_playground.ipynb
yongsheng268/tfx
You can also write your own custom pipeline if you want to perform extra transformations on the data before evaluation.
def run_tfma(slice_spec, tf_run_id, tfma_run_id, input_csv, schema_file, add_metrics_callbacks=None): """A simple wrapper function that runs tfma locally. A function that does extra transformations on the data and then run model analysis. Args: slice_spec: The slicing spec for how to slice...
_____no_output_____
Apache-2.0
tfx/examples/chicago_taxi/chicago_taxi_tfma_local_playground.ipynb
yongsheng268/tfx
You can also compute metrics on slices of your data in TFMA. Slices can be specified using ``tfma.slicer.SingleSliceSpec``.Below are examples of how slices can be specified.
# An empty slice spec means the overall slice, that is, the whole dataset. OVERALL_SLICE_SPEC = tfma.slicer.SingleSliceSpec() # Data can be sliced along a feature column # In this case, data is sliced along feature column trip_start_hour. FEATURE_COLUMN_SLICE_SPEC = tfma.slicer.SingleSliceSpec(columns=['trip_start_hou...
_____no_output_____
Apache-2.0
tfx/examples/chicago_taxi/chicago_taxi_tfma_local_playground.ipynb
yongsheng268/tfx
Let's run TFMA!
tf.logging.set_verbosity(tf.logging.INFO) tfma_result_1 = run_tfma(input_csv=os.path.join(EVAL_DATA_DIR, 'data.csv'), tf_run_id=0, tfma_run_id=1, slice_spec=ALL_SPECS, schema_file=get_schema_file()) print('Done')
_____no_output_____
Apache-2.0
tfx/examples/chicago_taxi/chicago_taxi_tfma_local_playground.ipynb
yongsheng268/tfx
Visualization: Slicing MetricsTo see the slices, either use the name of the column (by setting slicing_column) or provide a tfma.slicer.SingleSliceSpec (by setting slicing_spec). If neither is provided, the overall will be displayed.The default visualization is **slice overview** when the number of slices is small. It...
# Show data sliced along feature column trip_start_hour. tfma.view.render_slicing_metrics( tfma_result_1, slicing_column='trip_start_hour') # Show metrics sliced by COLUMN_CROSS_VALUE_SPEC above. tfma.view.render_slicing_metrics(tfma_result_1, slicing_spec=COLUMN_CROSS_VALUE_SPEC) # Show overall metrics. tfma.view....
_____no_output_____
Apache-2.0
tfx/examples/chicago_taxi/chicago_taxi_tfma_local_playground.ipynb
yongsheng268/tfx
Visualization: PlotsTFMA offers a number of built-in plots. To see them, add them to ``add_metrics_callbacks``
tf.logging.set_verbosity(tf.logging.INFO) tfma_vis = run_tfma(input_csv=os.path.join(EVAL_DATA_DIR, 'data.csv'), tf_run_id=0, tfma_run_id='vis', slice_spec=ALL_SPECS, schema_file=get_schema_file(), add_metrics_callback...
_____no_output_____
Apache-2.0
tfx/examples/chicago_taxi/chicago_taxi_tfma_local_playground.ipynb
yongsheng268/tfx
Plots must be visualized for an individual slice. To specify a slice, use ``tfma.slicer.SingleSliceSpec``.In the example below, we are using ``tfma.slicer.SingleSliceSpec(features=[('trip_start_hour', 1)])`` to specify the slice where trip_start_hour is 1.Plots are interactive:- Drag to pan- Scroll to zoom- Right click...
tfma.view.render_plot(tfma_vis, tfma.slicer.SingleSliceSpec(features=[('trip_start_hour', 1)]))
_____no_output_____
Apache-2.0
tfx/examples/chicago_taxi/chicago_taxi_tfma_local_playground.ipynb
yongsheng268/tfx
Custom metricsIn addition to plots, it is also possible to compute additional metrics not present at export time or custom metrics metrics using ``add_metrics_callbacks``.All metrics in ``tf.metrics`` are supported in the callback and can be used to compose other metrics:https://www.tensorflow.org/api_docs/python/tf/m...
# Defines a callback that adds FNR to the result. def add_fnr_for_threshold(threshold): def _add_fnr_callback(features_dict, predictions_dict, labels_dict): metric_ops = {} prediction_tensor = tf.cast( predictions_dict.get(tf.contrib.learn.PredictionKey.LOGISTIC), tf.float64) fn_...
_____no_output_____
Apache-2.0
tfx/examples/chicago_taxi/chicago_taxi_tfma_local_playground.ipynb
yongsheng268/tfx
Visualization: Time SeriesIt is important to track how your model is doing over time. TFMA offers two modes to show your model performs over time.**Multiple model analysis** shows how model perfoms from one version to another. This is useful early on to see how the addition of new features, change in modeling techniqu...
help(tfma.multiple_model_analysis)
_____no_output_____
Apache-2.0
tfx/examples/chicago_taxi/chicago_taxi_tfma_local_playground.ipynb
yongsheng268/tfx
**Multiple data analysis** shows how a model perfoms under different evaluation data set. This is useful to ensure that model performance does not degrade over time. TFMA offer a conveneient method.
help(tfma.multiple_data_analysis)
_____no_output_____
Apache-2.0
tfx/examples/chicago_taxi/chicago_taxi_tfma_local_playground.ipynb
yongsheng268/tfx
It is also possible to compose a time series manually.
# Create different models. # Run some experiments with different hidden layer configurations. run_local_experiment(tft_run_id=0, tf_run_id=1, num_layers=3, first_layer_size=200, scale_factor=0.7) run_local_experiment(tft_run_id=0, ...
_____no_output_____
Apache-2.0
tfx/examples/chicago_taxi/chicago_taxi_tfma_local_playground.ipynb
yongsheng268/tfx
Like plots, time series view must visualized for a slice too.In the example below, we are showing the overall slice.Select a metric to see its time series graph. Hover over each data point to get more details.
eval_results = tfma.make_eval_results([tfma_result_1, tfma_result_2, tfma_result_3], tfma.constants.MODEL_CENTRIC_MODE) tfma.view.render_time_series(eval_results, OVERALL_SLICE_SPEC)
_____no_output_____
Apache-2.0
tfx/examples/chicago_taxi/chicago_taxi_tfma_local_playground.ipynb
yongsheng268/tfx
Serialized results can also be used to construct a time series. Thus, there is no need to re-run TFMA for models already evaluated for a long running pipeline.
# Visualize the results in a Time Series. In this case, we are showing the slice specified. eval_results_from_disk = tfma.load_eval_results([get_tfma_output_dir(1), get_tfma_output_dir(2), get_tfma_output_dir(3)], ...
_____no_output_____
Apache-2.0
tfx/examples/chicago_taxi/chicago_taxi_tfma_local_playground.ipynb
yongsheng268/tfx
Conservative remapping
import xgcm import xarray as xr import numpy as np import xbasin
_____no_output_____
MIT
docs/remapping.ipynb
BenniSchmiedel/ECO
We open the example data and create 2 grids: 1 for the dataset we have and 1 for the remapped one.Here '_fr' means *from* and '_to' *to* (i.e. remapped data).
ds = xr.open_dataset('data/nemo_output_ex.nc') from xnemogcm import open_nemo_and_domain_cfg ds = open_nemo_and_domain_cfg(datadir='/home/romain/Documents/Education/PhD/Courses/2019-OC6310/Project/Experiments/EXP_eos00/Rawdata') metrics_fr = { ('X',): ['e1t', 'e1u', 'e1v', 'e1f'], ('Y',): ['e2t', 'e2u', 'e2v'...
<xarray.Dataset> Dimensions: (axis_nbounds: 2, t: 5, x_c: 21, x_f: 21, y_c: 40, y_f: 40, z_c: 36, z_f: 36) Coordinates: * z_f (z_f) float64 -0.5 0.5 1.5 2.5 3.5 ... 31.5 32.5 33.5 34.5 * t (t) object 7756-01-01 00:00:00 ... 7796-01-01 00:00:00 * x_c (x_c) int64 0 1 2 3 4 ...
MIT
docs/remapping.ipynb
BenniSchmiedel/ECO
Remap a T point
%timeit xbasin.remap_vertical(ds.thetao, grid_fr, grid_to, axis='Z') theta_to = xbasin.remap_vertical(ds.thetao, grid_fr, grid_to, axis='Z') print(theta_to.coords)
Coordinates: * z_c (z_c) int64 0 1 2 3 4 5 6 7 8 9 ... 26 27 28 29 30 31 32 33 34 35 * t (t) object 7756-01-01 00:00:00 ... 7796-01-01 00:00:00 * x_c (x_c) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 * y_c (y_c) int64 0 1 2 3 4 5 6 7 8 9 ... 30 31 32 33 34 35 36 37 38 39
MIT
docs/remapping.ipynb
BenniSchmiedel/ECO
The total heat content is conserved:
hc_fr = grid_fr.integrate(ds.thetao, axis='Z') hc_to = grid_to.integrate(theta_to, axis='Z') (hc_fr == hc_to).all()
_____no_output_____
MIT
docs/remapping.ipynb
BenniSchmiedel/ECO
Remap a W point
w_to = xbasin.remap_vertical(ds.woce*0+1, grid_fr, grid_to, axis='Z') grid_to.integrate(w_to, axis='Z')[-1].plot() grid_fr.integrate((ds.woce*0+1), axis='Z')[-1].plot()
_____no_output_____
MIT
docs/remapping.ipynb
BenniSchmiedel/ECO
Time comparisonThe heart function of the remapping is computed from python to C++ with pythran, which improves the speed. However if pythran is not installed, the original python function is called instead.As a user, you should not use the 2 following functions, they are only shown here for the time comparison.
fake_dataset = [ np.ascontiguousarray(ds.gdept_0.values.reshape(ds.gdept_0.values.shape+(1,))), np.ascontiguousarray(ds.gdepw_0.values.reshape(ds.gdepw_0.values.shape+(1,))), np.ascontiguousarray(ds.thetao.transpose('z_c', 'y_c', 'x_c', 't').values.flatten().reshape(ds.thetao.transpose('z_c', 'y_c', 'x_c', ...
_____no_output_____
MIT
docs/remapping.ipynb
BenniSchmiedel/ECO
Pure Python
%timeit _interpolation_pure_python(*fake_dataset)
120 ms ± 1.1 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
MIT
docs/remapping.ipynb
BenniSchmiedel/ECO
Pythran
%timeit _interpolation_pythran(*fake_dataset)
2.66 ms ± 16.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
MIT
docs/remapping.ipynb
BenniSchmiedel/ECO
DeepDreaming with TensorFlow >[Loading and displaying the model graph](loading)>[Naive feature visualization](naive)>[Multiscale image generation](multiscale)>[Laplacian Pyramid Gradient Normalization](laplacian)>[Playing with feature visualzations](playing)>[DeepDream](deepdream) This notebook demonstrates a number o...
# boilerplate code from __future__ import print_function import os from io import BytesIO import numpy as np from functools import partial import PIL.Image from IPython.display import clear_output, Image, display, HTML import tensorflow as tf
_____no_output_____
Apache-2.0
tensorflow/examples/tutorials/deepdream/deepdream.ipynb
espuer/tensorflow
Loading and displaying the model graphThe pretrained network can be downloaded [here](https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip). Unpack the `tensorflow_inception_graph.pb` file from the archive and set its path to `model_fn` variable. Alternatively you can uncomment and run the fol...
#!wget https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip && unzip inception5h.zip model_fn = 'tensorflow_inception_graph.pb' # creating TensorFlow session and loading the model graph = tf.Graph() sess = tf.InteractiveSession(graph=graph) with tf.gfile.FastGFile(model_fn, 'rb') as f: gra...
_____no_output_____
Apache-2.0
tensorflow/examples/tutorials/deepdream/deepdream.ipynb
espuer/tensorflow
To take a glimpse into the kinds of patterns that the network learned to recognize, we will try to generate images that maximize the sum of activations of particular channel of a particular convolutional layer of the neural network. The network we explore contains many convolutional layers, each of which outputs tens t...
layers = [op.name for op in graph.get_operations() if op.type=='Conv2D' and 'import/' in op.name] feature_nums = [int(graph.get_tensor_by_name(name+':0').get_shape()[-1]) for name in layers] print('Number of layers', len(layers)) print('Total number of feature channels:', sum(feature_nums)) # Helper functions for TF...
Number of layers 59 Total number of feature channels: 7548
Apache-2.0
tensorflow/examples/tutorials/deepdream/deepdream.ipynb
espuer/tensorflow
Naive feature visualization Let's start with a naive way of visualizing these. Image-space gradient ascent!
# Picking some internal layer. Note that we use outputs before applying the ReLU nonlinearity # to have non-zero gradients for features with negative initial activations. layer = 'mixed4d_3x3_bottleneck_pre_relu' channel = 139 # picking some feature channel to visualize # start with a gray image with a little noise im...
_____no_output_____
Apache-2.0
tensorflow/examples/tutorials/deepdream/deepdream.ipynb
espuer/tensorflow
Multiscale image generationLooks like the network wants to show us something interesting! Let's help it. We are going to apply gradient ascent on multiple scales. Details formed on smaller scale will be upscaled and augmented with additional details on the next scale.With multiscale image generation it may be tempting...
def tffunc(*argtypes): '''Helper that transforms TF-graph generating function into a regular one. See "resize" function below. ''' placeholders = list(map(tf.placeholder, argtypes)) def wrap(f): out = f(*placeholders) def wrapper(*args, **kw): return out.eval(dict(zip(pla...
_____no_output_____
Apache-2.0
tensorflow/examples/tutorials/deepdream/deepdream.ipynb
espuer/tensorflow