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
XML looks very similar to HTML. XML is formatted with tags with values inside the tags. XML is not as easy to navigate as JSON. Pandas cannot read in XML directly. One reason is that tag names are user defined. Every XML file might have different formatting. You can imagine why XML has fallen out of favor relative to J...
# import the BeautifulSoup library from bs4 import BeautifulSoup # open the population_data.xml file and load into Beautiful Soup with open("population_data.xml") as fp: soup = BeautifulSoup(fp, "lxml") # lxml is the Parser type # output the first 5 records in the xml file # this is an example of how to navigate t...
_____no_output_____
MIT
lessons/ETLPipelines/2_extract_exercise/.ipynb_checkpoints/2_extract_exercise-checkpoint.ipynb
rabadzhiyski/Data_Science_Udacity
XML Exercise (Challenge)Create a data frame from the xml file. This exercise is somewhat tricky. One solution would be to convert the xml data into dictionaries and then use the dictionaries to create a data frame. The dataframe should have the following layout:| Country or Area | Year | Item | Value ||----|----|----|...
# TODO: Create a pandas data frame from the XML data. # HINT: You can use dictionaries to create pandas data frames. # HINT: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_dict.html#pandas.DataFrame.from_dict # HINT: You can make a dictionary for each column or for each row (See the link a...
_____no_output_____
MIT
lessons/ETLPipelines/2_extract_exercise/.ipynb_checkpoints/2_extract_exercise-checkpoint.ipynb
rabadzhiyski/Data_Science_Udacity
Main Code
import os import time import numpy as np import redis from IPython.display import clear_output from PIL import Image from io import BytesIO import base64 import json import matplotlib.pyplot as plt from face_detection import get_face from utils import img_to_txt, decode_img, log_error ########################## # # ...
_____no_output_____
Apache-2.0
face_detection/Debug.ipynb
SohaibAnwaar/Skin-care
Vectorizing The process that we use to convert text to a form that Python and a machine learning model can understand is called vectorizing Vectorization is used to speed up the Python code without using loop ___- Count VectorizationCreates a document-term matrix where the entry of each c...
import nltk import re import string import pandas as pd pd.set_options('.max_')
_____no_output_____
MIT
Linkedin/NLP/CH03/.ipynb_checkpoints/CountVectorizer-checkpoint.ipynb
Dhaneshgupta1027/Python
Glove应用
#余玄相似度 def cos_sim(x, y): return nd.dot(x,y)/(x.norm() * y.norm()) a = nd.array([4,5]) b = nd.array([400,500]) print(cos_sim(a,b)) #求近义词 def norm_vecs_by_row(x): # 分母中添加的 1e-10 是为了数值稳定性。 return x / (nd.sum(x * x, axis=1) + 1e-10).sqrt().reshape((-1, 1)) def get_knn(token_embedding, k, word): word_vec =...
['biggest']
Apache-2.0
word2vec_glove_fasttext/glove-action.ipynb
ZhouJianyao/NLP
Dictionaries Dictionary in Python is an unordered collection of data values. Dictionary holds key:value pair. Each key-value pair in a Dictionary is separated by a colon whereas each key is separated by a ‘comma’. Keys of a Dictionary must be unique.
Dictionary = {1:'Nokia',2:'EDP',3:'Nokia',4:'Nokia', 'Nokia':1} print(Dictionary) Dictionary = {1:'Nokia', 2:'EDP',3:'Nokia', 1:'ML', 2:'Pritish'} print(Dictionary)
{1: 'Nokia', 2: 'EDP', 3: 'Nokia', 4: 'Nokia', 'Nokia': 1} {1: 'ML', 2: 'Pritish', 3: 'Nokia'}
Unlicense
3_Dictionary.ipynb
dheerajjoshim/machinelearningcourse
Dictionary keys can be of different data types:
Dictionary = {'name':'Pritish',1:[2,3,4]} print(Dictionary)
{'name': 'Pritish', 1: [2, 3, 4]}
Unlicense
3_Dictionary.ipynb
dheerajjoshim/machinelearningcourse
Accessing a particular element in a dictionary via the key:
Dictionary = {1:'Nokia',2:'EDP',3:'Machine Learning'} print(Dictionary[1])
Nokia
Unlicense
3_Dictionary.ipynb
dheerajjoshim/machinelearningcourse
Length of a dictionary: len(dictionary_name)
Dictionary = {1:'Nokia',2:'EDP',3:'Machine Learning'} print(len(Dictionary))
3
Unlicense
3_Dictionary.ipynb
dheerajjoshim/machinelearningcourse
Keys of the dictionary: dictionary_name.keys()
Dictionary = {1:'Nokia',2:'EDP',3:'Machine Learning'} print(Dictionary.keys())
dict_keys([1, 2, 3])
Unlicense
3_Dictionary.ipynb
dheerajjoshim/machinelearningcourse
Values corresponding to the keys of a dictionary: dictionary_name.values()
Dictionary = {1:'Nokia',2:'EDP',3:'Machine Learning'} print(Dictionary.values())
dict_values(['Nokia', 'EDP', 'Machine Learning'])
Unlicense
3_Dictionary.ipynb
dheerajjoshim/machinelearningcourse
Check for all the items in the dictionary: dictionary_name.items()
Dictionary = {1:'Nokia',2:'ML'} # item is the combination of the key, value pair print(Dictionary.items())
dict_items([(1, 'Nokia'), (2, 'ML')])
Unlicense
3_Dictionary.ipynb
dheerajjoshim/machinelearningcourse
Getting the value of a particular key element in dictionary dictionary_name.get(element_index_key)
Dictionary = {1:'Nokia',2:'ML'} print(Dictionary.get(1)) print(Dictionary.get(2))
Nokia ML
Unlicense
3_Dictionary.ipynb
dheerajjoshim/machinelearningcourse
Updating a value in the dictionary:
Dictionary = {1:'Nokia',2:'EDP',3:'Project Management'} Dictionary.update( {3:'ML',1:'NOKIA'} ) # Can update multiple keys at a single time print(Dictionary)
{1: 'NOKIA', 2: 'EDP', 3: 'ML'}
Unlicense
3_Dictionary.ipynb
dheerajjoshim/machinelearningcourse
Updating a value in the dictionary without using built-in update:
edp_subjects = {"ML":93, "Project Management":86, "Cloud Ambessador":90} edp_subjects["ML"]=95 print(edp_subjects["ML"]) print(edp_subjects)
95 {'ML': 95, 'Project Management': 86, 'Cloud Ambessador': 90}
Unlicense
3_Dictionary.ipynb
dheerajjoshim/machinelearningcourse
Pop an element from the dictionary: dictionary_name.pop(key)
Dictionary = {1:'Nokia',2:'EDP',3:'ML'} print(Dictionary.pop(2)) # pop mandatorily needs a value as an argument to be passed print(Dictionary)
EDP {1: 'Nokia', 3: 'ML'}
Unlicense
3_Dictionary.ipynb
dheerajjoshim/machinelearningcourse
Clearing the dictionary elements, deleting the dictionary: dictionary_name.clear() del dictionary_name
students = {"Eric":14, "Bob":12, "Alice":26} students.clear() print(students) del students
{}
Unlicense
3_Dictionary.ipynb
dheerajjoshim/machinelearningcourse
Delete an element in the dictionary: del dictionary_name[element_index]
students = {"Eric":14, "Bob":12, "Alice":26} del students["Bob"] print(students) del students
{'Eric': 14, 'Alice': 26}
Unlicense
3_Dictionary.ipynb
dheerajjoshim/machinelearningcourse
Updating a dictionary by adding one more dictionary to an existing dictionary: dictionary_name1.update(dictionary_name2)
students_1 = {"Eric":14, "Bob":12, "Alice":26} students_2 = {1:'John',2:'Bob',3:'James'} students_1.update(students_2) print(students_1)
{'Eric': 14, 'Bob': 12, 'Alice': 26, 1: 'John', 2: 'Bob', 3: 'James'}
Unlicense
3_Dictionary.ipynb
dheerajjoshim/machinelearningcourse
Ordered Dictionary usage of OrderedDict OrderedDict preserves the order in which the keys are inserted. A regular dict doesn’t track the insertion order, and iterating it gives the values in an arbitrary order. By contrast, the order the items are inserted is remembered by OrderedDict.
from collections import OrderedDict print("This is a normal Dictionary: ") d = {} d['a'] = 1 d['b'] = 2 d['c'] = 3 d['d'] = 4 d['e'] = 5 d['f'] = 6 for key, value in d.items(): print(key, value) print("\nThis is an Ordered Dictionary: ") od = OrderedDict() od['a'] = 1 od['b'] = 2 od['c'] = 3 od['d'] = 4 od['e'...
This is a normal Dictionary: a 1 b 2 c 3 d 4 e 5 f 6 This is an Ordered Dictionary: a 1 b 2 c 3 d 4 e 5 f 6
Unlicense
3_Dictionary.ipynb
dheerajjoshim/machinelearningcourse
Dictionary built-in function
Dictionary = {1:'Nokia',2:'EDP',3:'Machine Learning'} print(dir(Dictionary[1]))
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', ...
Unlicense
3_Dictionary.ipynb
dheerajjoshim/machinelearningcourse
Importamos o numpy
import numpy as np
_____no_output_____
CC-BY-4.0
python1.ipynb
mat-esp-2016/python-1-carlosjessicathais2
Usamos o numpy para abrir os dados do .txt
dados= np.loadtxt('dados/brazil-TAVG-Trend.txt', comments='%') print(dados)
[[ 1.83200000e+03 1.00000000e+00 -5.75000000e-01 ..., nan nan nan] [ 1.83200000e+03 2.00000000e+00 -1.00500000e+00 ..., nan nan nan] [ 1.83200000e+03 3.00000000e+00 -7.93000000e-01 ..., nan nan ...
CC-BY-4.0
python1.ipynb
mat-esp-2016/python-1-carlosjessicathais2
Faremos a média das anomalias anuais
ano = dados[:,0] mes = dados[:,1] anomalia_anual = dados[:,4] media=np.nanmean(anomalia_anual) print(media)
-0.229509107894
CC-BY-4.0
python1.ipynb
mat-esp-2016/python-1-carlosjessicathais2
Faremos o desvio padrão das anomalias anuais
desvpad=np.nanstd(anomalia_anual) print(desvpad)
0.496111048439
CC-BY-4.0
python1.ipynb
mat-esp-2016/python-1-carlosjessicathais2
Plotaremos um gráfico a partir dos dados de Anomalia de Temperatura Média Anual X Tempo
ano_dec= ano+(mes -1)/12 media_tem= np.nanmean(dados[:,8]) %matplotlib inline import matplotlib.pyplot as plt plt.plot(ano_dec, anomalia_anual) plt.xlabel('Tempo (em anos)') plt.ylabel('Anomalia de Temperatura') plt.title('Brasil') plt.savefig('Brasil.pdf')
_____no_output_____
CC-BY-4.0
python1.ipynb
mat-esp-2016/python-1-carlosjessicathais2
Open Parking Stockholm https://openstreetgs.stockholm.se/Home/Parking
import urllib3 import geopandas as gpd http = urllib3.PoolManager() urlbase = "https://openparking.stockholm.se/LTF-Tolken/v1/servicedagar/" url = urlbase + "weekday/m%C3%A5ndag?outputFormat=json&apiKey=cb5d9a39-f208-459a-b8d5-ccd6bf712fe2" df = gpd.read_file(url) df.head() df.info() import folium for index, row in d...
ID: LTFR_SERVICEDAG.31030102 Fållnäsgatan , Tallkrogen - 10.0 ID: LTFR_SERVICEDAG.31030270 Lummerstigen , Herrängen - nan ID: LTFR_SERVICEDAG.31030271 Tanneforsvägen , Stureby - nan ID: LTFR_SERVICEDAG.31030272 Östrandsvägen , Stureby - nan ID: LTFR_SERVICEDAG.31030273 Östrandsvägen...
MIT
Open Parking Stockholm.ipynb
salgo60/open-data-examples
Tutorial 01: Running Sumo SimulationsThis tutorial walks through the process of running non-RL traffic simulations in Flow. Simulations of this form act as non-autonomous baselines and depict the behavior of human dynamics on a network. Similar simulations may also be used to evaluate the performance of hand-designed ...
from flow.scenarios.loop import LoopScenario
_____no_output_____
MIT
tutorials/tutorial01_sumo.ipynb
syuntoku14/flow
This scenario, as well as all other scenarios in Flow, is parametrized by the following arguments: * name* vehicles* net_params* initial_config* traffic_lightsThese parameters allow a single scenario to be recycled for a multitude of different network settings. For example, `LoopScenario` may be used to create ring roa...
name = "ring_example"
_____no_output_____
MIT
tutorials/tutorial01_sumo.ipynb
syuntoku14/flow
2.2 VehicleParamsThe `VehicleParams` class stores state information on all vehicles in the network. This class is used to identify the dynamical behavior of a vehicle and whether it is controlled by a reinforcement learning agent. Morover, information pertaining to the observations and reward function can be collected...
from flow.core.params import VehicleParams vehicles = VehicleParams()
_____no_output_____
MIT
tutorials/tutorial01_sumo.ipynb
syuntoku14/flow
Once this object is created, vehicles may be introduced using the `add` method. This method specifies the types and quantities of vehicles at the start of a simulation rollout. For a description of the various arguements associated with the `add` method, we refer the reader to the following documentation (reference rea...
from flow.controllers.car_following_models import IDMController
_____no_output_____
MIT
tutorials/tutorial01_sumo.ipynb
syuntoku14/flow
Another controller we define is for the vehicle's routing behavior. For closed network where the route for any vehicle is repeated, the `ContinuousRouter` controller is used to perpetually reroute all vehicles to the initial set route.
from flow.controllers.routing_controllers import ContinuousRouter
_____no_output_____
MIT
tutorials/tutorial01_sumo.ipynb
syuntoku14/flow
Finally, we add 22 vehicles of type "human" with the above acceleration and routing behavior into the `Vehicles` class.
vehicles.add("human", acceleration_controller=(IDMController, {}), routing_controller=(ContinuousRouter, {}), num_vehicles=22)
_____no_output_____
MIT
tutorials/tutorial01_sumo.ipynb
syuntoku14/flow
2.3 NetParams`NetParams` are network-specific parameters used to define the shape and properties of a network. Unlike most other parameters, `NetParams` may vary drastically depending on the specific network configuration, and accordingly most of its parameters are stored in `additional_params`. In order to determine ...
from flow.scenarios.loop import ADDITIONAL_NET_PARAMS print(ADDITIONAL_NET_PARAMS)
_____no_output_____
MIT
tutorials/tutorial01_sumo.ipynb
syuntoku14/flow
Importing the `ADDITIONAL_NET_PARAMS` dict from the ring road scenario, we see that the required parameters are:* **length**: length of the ring road* **lanes**: number of lanes* **speed**: speed limit for all edges* **resolution**: resolution of the curves on the ring. Setting this value to 1 converts the ring to a di...
from flow.core.params import NetParams net_params = NetParams(additional_params=ADDITIONAL_NET_PARAMS)
_____no_output_____
MIT
tutorials/tutorial01_sumo.ipynb
syuntoku14/flow
2.4 InitialConfig`InitialConfig` specifies parameters that affect the positioning of vehicle in the network at the start of a simulation. These parameters can be used to limit the edges and number of lanes vehicles originally occupy, and provide a means of adding randomness to the starting positions of vehicles. In or...
from flow.core.params import InitialConfig initial_config = InitialConfig(spacing="uniform", perturbation=1)
_____no_output_____
MIT
tutorials/tutorial01_sumo.ipynb
syuntoku14/flow
2.5 TrafficLightParams`TrafficLightParams` are used to desribe the positions and types of traffic lights in the network. These inputs are outside the scope of this tutorial, and instead are covered in `exercise06_traffic_lights.ipynb`. For our example, we create an empty `TrafficLightParams` object, thereby ensuring t...
from flow.core.params import TrafficLightParams traffic_lights = TrafficLightParams()
_____no_output_____
MIT
tutorials/tutorial01_sumo.ipynb
syuntoku14/flow
3. Setting up an EnvironmentSeveral envionrments in Flow exist to train autonomous agents of different forms (e.g. autonomous vehicles, traffic lights) to perform a variety of different tasks. These environments are often scenario or task specific; however, some can be deployed on an ambiguous set of scenarios as well...
from flow.envs.loop.loop_accel import AccelEnv
_____no_output_____
MIT
tutorials/tutorial01_sumo.ipynb
syuntoku14/flow
Although we will not be training any autonomous agents in this exercise, the use of an environment allows us to view the cumulative reward simulation rollouts receive in the absence of autonomy.Envrionments in Flow are parametrized by three components:* `EnvParams`* `SumoParams`* `Scenario` 3.1 SumoParams`SumoParams` s...
from flow.core.params import SumoParams sumo_params = SumoParams(sim_step=0.1, render=True)
_____no_output_____
MIT
tutorials/tutorial01_sumo.ipynb
syuntoku14/flow
3.2 EnvParams`EnvParams` specify environment and experiment-specific parameters that either affect the training process or the dynamics of various components within the scenario. Much like `NetParams`, the attributes associated with this parameter are mostly environment specific, and can be found in the environment's ...
from flow.envs.loop.loop_accel import ADDITIONAL_ENV_PARAMS print(ADDITIONAL_ENV_PARAMS)
_____no_output_____
MIT
tutorials/tutorial01_sumo.ipynb
syuntoku14/flow
Importing the `ADDITIONAL_ENV_PARAMS` variable, we see that it consists of only one entry, "target_velocity", which is used when computing the reward function associated with the environment. We use this default value when generating the `EnvParams` object.
from flow.core.params import EnvParams env_params = EnvParams(additional_params=ADDITIONAL_ENV_PARAMS)
_____no_output_____
MIT
tutorials/tutorial01_sumo.ipynb
syuntoku14/flow
4. Setting up and Running the ExperimentOnce the inputs to the scenario and environment classes are ready, we are ready to set up a `Experiment` object.
from flow.core.experiment import Experiment
_____no_output_____
MIT
tutorials/tutorial01_sumo.ipynb
syuntoku14/flow
These objects may be used to simulate rollouts in the absence of reinforcement learning agents, as well as acquire behaviors and rewards that may be used as a baseline with which to compare the performance of the learning agent. In this case, we choose to run our experiment for one rollout consisting of 3000 steps (300...
# create the scenario object scenario = LoopScenario(name="ring_example", vehicles=vehicles, net_params=net_params, initial_config=initial_config, traffic_lights=traffic_lights) # create the environment object env = AccelEn...
_____no_output_____
MIT
tutorials/tutorial01_sumo.ipynb
syuntoku14/flow
Quick start guide Installation StableFri can be installed via the Python Package Index (PyPI).If you have `pip` installed just execute the command pip install fri to get the newest stable version.The dependencies should be installed and checked automatically.If you have problems installing please open issue at o...
from fri import genClassificationData
_____no_output_____
MIT
docs/Guide.ipynb
timothycrosley/fri
We want to create a small set with a few features.Because we want to showcase the all-relevant feature selection, we generate multiple strongly and weakly relevant features.
n = 100 features = 6 strongly_relevant = 2 weakly_relevant = 2 X,y = genClassificationData(n_samples=n, n_features=features, n_strel=strongly_relevant, n_redundant=weakly_relevant, random_state=123)
_____no_output_____
MIT
docs/Guide.ipynb
timothycrosley/fri
The method also prints out the parameters again.
X.shape
_____no_output_____
MIT
docs/Guide.ipynb
timothycrosley/fri
We created a binary classification set with 6 features of which 2 are strongly relevant and 2 weakly relevant. PreprocessBecause our method expects mean centered data we need to standardize it first.This centers the values around 0 and deviation to the standard deviation
from sklearn.preprocessing import StandardScaler X_scaled = StandardScaler().fit_transform(X)
_____no_output_____
MIT
docs/Guide.ipynb
timothycrosley/fri
ModelNow we need to creata a Model. We use the `FRI` module.
import fri
_____no_output_____
MIT
docs/Guide.ipynb
timothycrosley/fri
`fri` provides a convenience class `fri.FRI` to create a model.`fri.FRI` needs the type of problem as a first argument of type `ProblemName`.Depending on the Problem you want to analyze pick from one of the available models in `ProblemName`.
list(fri.ProblemName)
_____no_output_____
MIT
docs/Guide.ipynb
timothycrosley/fri
Because we have Classification data we use the `ProblemName.CLASSIFICATION` to instantiate our model.
fri_model = fri.FRI(fri.ProblemName.CLASSIFICATION,slack_loss=0.2,slack_regularization=0.2) fri_model
_____no_output_____
MIT
docs/Guide.ipynb
timothycrosley/fri
We used no parameters for creation so the defaults are active. Fitting to dataNow we can just fit the model to the data using `scikit-learn` like commands.
fri_model.fit(X_scaled,y)
_____no_output_____
MIT
docs/Guide.ipynb
timothycrosley/fri
The resulting feature relevance bounds are saved in the `interval_` variable.
fri_model.interval_
_____no_output_____
MIT
docs/Guide.ipynb
timothycrosley/fri
If you want to print out the relevance class use the `print_interval_with_class()` function.
print(fri_model.print_interval_with_class())
############## Relevance bounds ############## feature: [LB -- UB], relevance class 0: [0.3 -- 0.4], Strong relevant 1: [0.3 -- 0.4], Strong relevant 2: [0.0 -- 0.5], Weak relevant 3: [0.0 -- 0.4], Weak relevant 4: [0.0 -- 0.0], Irrelevant 5: [0.0 -- 0.1], Irrelevant
MIT
docs/Guide.ipynb
timothycrosley/fri
The bounds are grouped in 2d sublists for each feature.To acess the relevance bounds for feature 2 we would use
fri_model.interval_[2]
_____no_output_____
MIT
docs/Guide.ipynb
timothycrosley/fri
The relevance classes are saved in the corresponding variable `relevance_classes_`:
fri_model.relevance_classes_
_____no_output_____
MIT
docs/Guide.ipynb
timothycrosley/fri
`2` denotes strongly relevant features, `1` weakly relevant and `0` irrelevant. Plot resultsThe bounds in numerical form are useful for postprocesing.If we want a human to look at it, we recommend the plot function `plot_relevance_bars`.We can also color the bars according to `relevance_classes_`
# Import plot function from fri.plot import plot_relevance_bars import matplotlib.pyplot as plt %matplotlib inline # Create new figure, where we can put an axis on fig, ax = plt.subplots(1, 1,figsize=(6,3)) # plot the bars on the axis, colored according to fri out = plot_relevance_bars(ax,fri_model.interval_,classes=fr...
_____no_output_____
MIT
docs/Guide.ipynb
timothycrosley/fri
Setting constraints manuallyOur model also allows to compute relevance bounds when the user sets a given range for the features.We use a dictionary to encode our constraints.
preset = {}
_____no_output_____
MIT
docs/Guide.ipynb
timothycrosley/fri
ExampleAs an example, let us constrain the third from our example to the minimum relevance bound.
preset[2] = fri_model.interval_[2, 0]
_____no_output_____
MIT
docs/Guide.ipynb
timothycrosley/fri
We use the function `constrained_intervals`.Note: we need to fit the model before we can use this function.We already did that, so we are fine.
const_ints = fri_model.constrained_intervals(preset=preset) const_ints
_____no_output_____
MIT
docs/Guide.ipynb
timothycrosley/fri
Feature 3 is set to its minimum (at 0).How does it look visually?
fig, ax = plt.subplots(1, 1,figsize=(6,3)) out = plot_relevance_bars(ax, const_ints)
_____no_output_____
MIT
docs/Guide.ipynb
timothycrosley/fri
Feature 3 is reduced to its minimum (no contribution).In turn, its correlated partner feature 4 had to take its maximum contribution. Print internal ParametersIf we want to take at internal parameters, we can use the `verbose` flag in the model creation.
fri_model = fri.FRI(fri.ProblemName.CLASSIFICATION, verbose=True) fri_model.fit(X_scaled,y)
Fitting 3 folds for each of 10 candidates, totalling 30 fits
MIT
docs/Guide.ipynb
timothycrosley/fri
This prints out the parameters of the baseline modelOne can also see the best selected hyperparameter according to gridsearch and the training score of the model in `score`. MultiprocessingTo enable multiprocessing simply use the `n_jobs` parameter when init. the model.It expects an integer parameter which defines the...
fri_model = fri.FRI(fri.ProblemName.CLASSIFICATION, n_jobs=-1, verbose=1) fri_model.fit(X_scaled,y)
Fitting 3 folds for each of 10 candidates, totalling 30 fits
MIT
docs/Guide.ipynb
timothycrosley/fri
Amortized Neural Variational Inference for a toy probabilistic modelConsider a certain number of sensors placed at known locations, $\mathbf{s}_1,\mathbf{s}_2,\ldots,\mathbf{s}_L$. There is a target at an unknown position $\mathbf{z}\in\mathbb{R}^2$ that is emitting a certain signal that is received at the $i$-th sen...
import numpy as np import matplotlib.pyplot as plt import tensorflow as tf %matplotlib inline # use seaborn plotting defaults import seaborn as sns; sns.set()
/Users/olmos/anaconda3/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`. from ._conv import register_converters as _register_converters
MIT
Notebooks/Part_7/Vartional Neural Inference Localization/Neural Variational Inference Localization Problem.ipynb
olmosUC3M/Introduction-to-Tensor-Flow-and-Deep-Learning
Probabilistic model definition and generating samples
############## Elements of the true probabilistic model #################### loc_info = {} loc_info['S'] = 3 # Number o sensors loc_info['pos_s'] = np.array([[0.5,1], [3.5,1], [2,3]]) #Position of sensors #loc_info['target'] = np.random.uniform(-3,3,[2,]) #(Unknown target positio...
_____no_output_____
MIT
Notebooks/Part_7/Vartional Neural Inference Localization/Neural Variational Inference Localization Problem.ipynb
olmosUC3M/Introduction-to-Tensor-Flow-and-Deep-Learning
 TensorFlow Computation Graph and Loss Function
z_dim = 2 #Latent Space model_name = 'model1' #In 'model1.py' we define the variational family learning_rate = 1e-2 num_samples_avg = 1 #Number of samples to approximate the expectation in the ELBO num_samples = 10 #Number of samples from the posterior (for testing) num_it = int(1e4) #SGD ite...
[*] Importing model: model1 [*] Defining placeholders [*] Defining the encoder [*] Defining the log_likelyhood
MIT
Notebooks/Part_7/Vartional Neural Inference Localization/Neural Variational Inference Localization Problem.ipynb
olmosUC3M/Introduction-to-Tensor-Flow-and-Deep-Learning
SGD optimization
############ SGD Inference ##################################### mean_list = [] with tf.Session(graph=sess_VAE) as session: # Add ops to save and restore all the variables. saver = tf.train.Saver() tf.global_variables_initializer().run() print('Training the VAE ...') ...
_____no_output_____
MIT
Notebooks/Part_7/Vartional Neural Inference Localization/Neural Variational Inference Localization Problem.ipynb
olmosUC3M/Introduction-to-Tensor-Flow-and-Deep-Learning
Colormap Choices {colormap_example}================Use a Matplotlib, Colorcet, cmocean, or custom colormap when plottingscalar values.
from pyvista import examples import pyvista as pv import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap import numpy as np
_____no_output_____
MIT
locale/examples/02-plot/cmap.ipynb
tkoyama010/pyvista-doc-translations
Any colormap built for `matplotlib`, `colorcet`, or `cmocean` is fullycompatible with PyVista. Colormaps are typically specified by passingthe string name of the colormap to the plotting routine via the `cmap`argument.See [Matplotlib\'s complete list of availablecolormaps](https://matplotlib.org/tutorials/colors/colorm...
mesh = examples.download_st_helens().warp_by_scalar() # Add scalar array with range (0, 100) that correlates with elevation mesh['values'] = pv.plotting.normalize(mesh['Elevation']) * 100
_____no_output_____
MIT
locale/examples/02-plot/cmap.ipynb
tkoyama010/pyvista-doc-translations
Build a custom colormap - here we make a colormap with 5 discrete colorsand we specify the ranges where those colors fall:
# Define the colors we want to use blue = np.array([12/256, 238/256, 246/256, 1]) black = np.array([11/256, 11/256, 11/256, 1]) grey = np.array([189/256, 189/256, 189/256, 1]) yellow = np.array([255/256, 247/256, 0/256, 1]) red = np.array([1, 0, 0, 1]) mapping = np.linspace(mesh['values'].min(), mesh['values'].max(), ...
_____no_output_____
MIT
locale/examples/02-plot/cmap.ipynb
tkoyama010/pyvista-doc-translations
Simply pass the colormap to the plotting routine!
mesh.plot(scalars='values', cmap=my_colormap)
_____no_output_____
MIT
locale/examples/02-plot/cmap.ipynb
tkoyama010/pyvista-doc-translations
Or you could make a simple colormap\... any Matplotlib colormap can bepassed to PyVista!
boring_cmap = plt.cm.get_cmap("viridis", 5) mesh.plot(scalars='values', cmap=boring_cmap)
_____no_output_____
MIT
locale/examples/02-plot/cmap.ipynb
tkoyama010/pyvista-doc-translations
You can also pass a list of color strings to the color map. Thisapproach divides up the colormap into 5 equal parts.
mesh.plot(scalars=mesh['values'], cmap=['black', 'blue', 'yellow', 'grey', 'red'])
_____no_output_____
MIT
locale/examples/02-plot/cmap.ipynb
tkoyama010/pyvista-doc-translations
If you still wish to have control of the separation of values, you cando this by creating a scalar array and passing that to the plotter alongwith the the colormap
scalars = np.empty(mesh.n_points) scalars[mesh['values'] >= 80] = 4 # red scalars[mesh['values'] < 80] = 3 # grey scalars[mesh['values'] < 55] = 2 # yellow scalars[mesh['values'] < 30] = 1 # blue scalars[mesh['values'] < 1] = 0 # black mesh.plot(scalars=scalars, cmap=['black', 'blue', 'yellow', 'grey', 'red'])
_____no_output_____
MIT
locale/examples/02-plot/cmap.ipynb
tkoyama010/pyvista-doc-translations
Matplotlib vs. Colorcet=======================Let\'s compare Colorcet\'s perceptually uniform \"fire\" colormap toMatplotlib\'s \"hot\" colormap much like the example on the [first pageof Colorcet\'s docs](https://colorcet.holoviz.org/index.html).The \"hot\" version washes out detail at the high end, as if the imageis ...
p = pv.Plotter(shape=(2, 2), border=False) p.subplot(0, 0) p.add_mesh(mesh, scalars='Elevation', cmap="fire", lighting=True, scalar_bar_args={'title': "Colorcet Fire"}) p.subplot(0, 1) p.add_mesh(mesh, scalars='Elevation', cmap="fire", lighting=False, scalar_bar_args={'title': "Colorcet Fire (No ...
_____no_output_____
MIT
locale/examples/02-plot/cmap.ipynb
tkoyama010/pyvista-doc-translations
Homework: Multilingual Embedding-based Machine Translation (7 points) **In this homework** **YOU** will make machine translation system without using parallel corpora, alignment, attention, 100500 depth super-cool recurrent neural network and all that kind superstuff.But even without parallel corpora this system can b...
import gensim import numpy as np from gensim.models import KeyedVectors
_____no_output_____
MIT
week01_embeddings/homework.ipynb
movb/nlp_course
Download embeddings here:* [cc.uk.300.vec.zip](https://yadi.sk/d/9CAeNsJiInoyUA)* [cc.ru.300.vec.zip](https://yadi.sk/d/3yG0-M4M8fypeQ) Load embeddings for ukrainian and russian.
uk_emb = KeyedVectors.load_word2vec_format("cc.uk.300.vec") ru_emb = KeyedVectors.load_word2vec_format("cc.ru.300.vec") ru_emb.most_similar([ru_emb["август"]], topn=10) uk_emb.most_similar([uk_emb["серпень"]]) ru_emb.most_similar([uk_emb["серпень"]])
_____no_output_____
MIT
week01_embeddings/homework.ipynb
movb/nlp_course
Load small dictionaries for correspoinding words pairs as trainset and testset.
def load_word_pairs(filename): uk_ru_pairs = [] uk_vectors = [] ru_vectors = [] with open(filename, "r") as inpf: for line in inpf: uk, ru = line.rstrip().split("\t") if uk not in uk_emb or ru not in ru_emb: continue uk_ru_pairs.append((uk, ru)...
_____no_output_____
MIT
week01_embeddings/homework.ipynb
movb/nlp_course
Embedding space mapping Let $x_i \in \mathrm{R}^d$ be the distributed representation of word $i$ in the source language, and $y_i \in \mathrm{R}^d$ is the vector representation of its translation. Our purpose is to learn such linear transform $W$ that minimizes euclidian distance between $Wx_i$ and $y_i$ for some subs...
from sklearn.linear_model import LinearRegression mapping = LinearRegression(fit_intercept=False).fit(X_train, Y_train)
_____no_output_____
MIT
week01_embeddings/homework.ipynb
movb/nlp_course
Let's take a look at neigbours of the vector of word _"серпень"_ (_"август"_ in Russian) after linear transform.
august = mapping.predict(uk_emb["серпень"].reshape(1, -1)) ru_emb.most_similar(august)
_____no_output_____
MIT
week01_embeddings/homework.ipynb
movb/nlp_course
We can see that neighbourhood of this embedding cosists of different months, but right variant is on the ninth place. As quality measure we will use precision top-1, top-5 and top-10 (for each transformed Ukrainian embedding we count how many right target pairs are found in top N nearest neighbours in Russian embedding...
def precision(pairs, mapped_vectors, topn=1): """ :args: pairs = list of right word pairs [(uk_word_0, ru_word_0), ...] mapped_vectors = list of embeddings after mapping from source embedding space to destination embedding space topn = the number of nearest neighbours in destination embe...
_____no_output_____
MIT
week01_embeddings/homework.ipynb
movb/nlp_course
Making it better (orthogonal Procrustean problem) It can be shown (see original paper) that a self-consistent linear mapping between semantic spaces should be orthogonal. We can restrict transform $W$ to be orthogonal. Then we will solve next problem:$$W^*= \arg\min_W ||WX - Y||_F \text{, where: } W^TW = I$$$$I \text{...
def learn_transform(X_train, Y_train): """ :returns: W* : float matrix[emb_dim x emb_dim] as defined in formulae above """ u, s, vh = np.linalg.svd(X_train.T.dot(Y_train)) return u.dot(vh) W = learn_transform(X_train, Y_train) ru_emb.most_similar([np.matmul(uk_emb["серпень"], W)]) assert precision...
_____no_output_____
MIT
week01_embeddings/homework.ipynb
movb/nlp_course
UK-RU Translator Now we are ready to make simple word-based translator: for earch word in source language in shared embedding space we find the nearest in target language.
with open("fairy_tale.txt", "r") as inpf: uk_sentences = [line.rstrip().lower() for line in inpf] def translate(sentence): """ :args: sentence - sentence in Ukrainian (str) :returns: translation - sentence in Russian (str) * find ukrainian embedding for each word in sentence * t...
src: лисичка - сестричка і вовк - панібрат dst: лисичка – сестричка и волк – панібрат src: як була собі лисичка , да й пішла раз до однії баби добувать огню ; ввійшла у хату да й каже : " добрий день тобі , бабусю ! dst: как была себе лисичка , че и пошла раз к однії бабы добувать огня ; вошла во избу че и говорит : "...
MIT
week01_embeddings/homework.ipynb
movb/nlp_course
US - Baby NamesCheck out [Baby Names Exercises Video Tutorial](https://youtu.be/Daf2QNAy-qA) to watch a data scientist go through the exercises Introduction:We are going to use a subset of [US Baby Names](https://www.kaggle.com/kaggle/us-baby-names) from Kaggle. In the file it will be names from 2004 until 2014 Step...
import pandas as pd
_____no_output_____
BSD-3-Clause
06_Stats/US_Baby_Names/Exercises_with_solutions.ipynb
deep0892/pandas_practice
Step 2. Import the dataset from this [address](https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/US_Baby_Names/US_Baby_Names_right.csv). Step 3. Assign it to a variable called baby_names.
baby_names = pd.read_csv('https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/US_Baby_Names/US_Baby_Names_right.csv') baby_names.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 1016395 entries, 0 to 1016394 Data columns (total 7 columns): Unnamed: 0 1016395 non-null int64 Id 1016395 non-null int64 Name 1016395 non-null object Year 1016395 non-null int64 Gender 1016395 non-null object State 1016395...
BSD-3-Clause
06_Stats/US_Baby_Names/Exercises_with_solutions.ipynb
deep0892/pandas_practice
Step 4. See the first 10 entries
baby_names.head(10)
_____no_output_____
BSD-3-Clause
06_Stats/US_Baby_Names/Exercises_with_solutions.ipynb
deep0892/pandas_practice
Step 5. Delete the column 'Unnamed: 0' and 'Id'
# deletes Unnamed: 0 del baby_names['Unnamed: 0'] # deletes Unnamed: 0 del baby_names['Id'] baby_names.head()
_____no_output_____
BSD-3-Clause
06_Stats/US_Baby_Names/Exercises_with_solutions.ipynb
deep0892/pandas_practice
Step 6. Are there more male or female names in the dataset?
baby_names['Gender'].value_counts()
_____no_output_____
BSD-3-Clause
06_Stats/US_Baby_Names/Exercises_with_solutions.ipynb
deep0892/pandas_practice
Step 7. Group the dataset by name and assign to names
# you don't want to sum the Year column, so you delete it del baby_names["Year"] # group the data names = baby_names.groupby("Name").sum() # print the first 5 observations names.head() # print the size of the dataset print(names.shape) # sort it from the biggest value to the smallest one names.sort_values("Count", ...
(17632, 1)
BSD-3-Clause
06_Stats/US_Baby_Names/Exercises_with_solutions.ipynb
deep0892/pandas_practice
Step 8. How many different names exist in the dataset?
# as we have already grouped by the name, all the names are unique already. # get the length of names len(names)
_____no_output_____
BSD-3-Clause
06_Stats/US_Baby_Names/Exercises_with_solutions.ipynb
deep0892/pandas_practice
Step 9. What is the name with most occurrences?
names.Count.idxmax() # OR # names[names.Count == names.Count.max()]
_____no_output_____
BSD-3-Clause
06_Stats/US_Baby_Names/Exercises_with_solutions.ipynb
deep0892/pandas_practice
Step 10. How many different names have the least occurrences?
len(names[names.Count == names.Count.min()])
_____no_output_____
BSD-3-Clause
06_Stats/US_Baby_Names/Exercises_with_solutions.ipynb
deep0892/pandas_practice
Step 11. What is the median name occurrence?
names[names.Count == names.Count.median()]
_____no_output_____
BSD-3-Clause
06_Stats/US_Baby_Names/Exercises_with_solutions.ipynb
deep0892/pandas_practice
Step 12. What is the standard deviation of names?
names.Count.std()
_____no_output_____
BSD-3-Clause
06_Stats/US_Baby_Names/Exercises_with_solutions.ipynb
deep0892/pandas_practice
Step 13. Get a summary with the mean, min, max, std and quartiles.
names.describe()
_____no_output_____
BSD-3-Clause
06_Stats/US_Baby_Names/Exercises_with_solutions.ipynb
deep0892/pandas_practice
Matplotlib and NumPy crash course You may install numpy, matplotlib, sklearn and many other usefull package e.g. via Anaconda distribution.
import numpy as np
_____no_output_____
MIT
lecture1/NumPy_crash_course.ipynb
HSE-LaMBDA/modern-technologies-for-ml-and-big-data
NumPy basics Array creation
np.array(range(10)) np.ndarray(shape=(5, 4)) np.linspace(0, 1, num=20) np.arange(0, 20) np.zeros(shape=(5, 4)) np.ones(shape=(5,4))
_____no_output_____
MIT
lecture1/NumPy_crash_course.ipynb
HSE-LaMBDA/modern-technologies-for-ml-and-big-data
Possible types of array:- bool- various ints- float, double- string
np.ones(shape=(2, 3), dtype="string") np.zeros(shape=(2, 3), dtype=bool) np.savetxt("eye.txt", np.eye(5, 6)) np.loadtxt("eye.txt") %rm eye.txt
_____no_output_____
MIT
lecture1/NumPy_crash_course.ipynb
HSE-LaMBDA/modern-technologies-for-ml-and-big-data
Array operations
a = np.linspace(0, 9, num=10) a + 1 a * a a - a print a.max() print a.min() np.sum(a) a = np.random.standard_normal(size=(25, )) a b = a.reshape((5, 5)) b b.T np.sum(b) print np.sum(b, axis=1) print np.sum(b, axis=0) ### Matrix multiplication np.dot(b, b) np.vstack([b, b])
_____no_output_____
MIT
lecture1/NumPy_crash_course.ipynb
HSE-LaMBDA/modern-technologies-for-ml-and-big-data
Custom functions
def plus(x, y): return x + y plus_v = np.vectorize(plus) plus_v(np.arange(10), np.arange(10, 20)) plus_v(np.arange(10), 10) @np.vectorize def plus(x, y): return x + y plus(np.arange(10), 10)
_____no_output_____
MIT
lecture1/NumPy_crash_course.ipynb
HSE-LaMBDA/modern-technologies-for-ml-and-big-data
Performance
N = 10000000 a = np.random.standard_normal(size=N) b = np.random.standard_normal(size=N) %%time a + b ab = zip(range(N), range(N)) %%time _ = [ a + b for a, b in ab ]
CPU times: user 1.84 s, sys: 75.9 ms, total: 1.92 s Wall time: 1.92 s
MIT
lecture1/NumPy_crash_course.ipynb
HSE-LaMBDA/modern-technologies-for-ml-and-big-data