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
Step 7: Fit a curve to the data (**For undergraduates, this section is optional.**)Based on macroscopic arguments, the energy of a cluster could scale with both surface area (via a surface tension) and volume (via an energy density for bulk) of the cluster. So we could model the minimum energy as depending on the clus...
#Your code here
_____no_output_____
CC-BY-4.0
uci-pharmsci/assignments/energy_minimization/energy_minimization_assignment.ipynb
matthagy/drug-computing
Machine Learning Engineer Nanodegree Unsupervised Learning Project: Creating Customer Segments Welcome to the third project of the Machine Learning Engineer Nanodegree! In this notebook, some template code has already been provided for you, and it will be your job to implement the additional functionality necessary to...
# Import libraries necessary for this project import numpy as np import pandas as pd from IPython.display import display # Allows the use of display() for DataFrames # Import supplementary visualizations code visuals.py import visuals as vs # Pretty display for notebooks %matplotlib inline # Load the wholesale custo...
Wholesale customers dataset has 440 samples with 6 features each.
MIT
Udacity/MachineLearning/customer_segments_project/customer_segments_nabin_proj.ipynb
nacharya/notebooks
Data ExplorationIn this section, you will begin exploring the data through visualizations and code to understand how each feature is related to the others. You will observe a statistical description of the dataset, consider the relevance of each feature, and select a few sample data points from the dataset which you w...
# Display a description of the dataset display(data.describe())
_____no_output_____
MIT
Udacity/MachineLearning/customer_segments_project/customer_segments_nabin_proj.ipynb
nacharya/notebooks
Implementation: Selecting SamplesTo get a better understanding of the customers and how their data will transform through the analysis, it would be best to select a few sample data points and explore them in more detail. In the code block below, add **three** indices of your choice to the `indices` list which will rep...
# Select three indices of your choice you wish to sample from the dataset indices = [25, 186, 220] # Create a DataFrame of the chosen samples samples = pd.DataFrame(data.loc[indices], columns = data.keys()).reset_index(drop = True) print "Chosen samples of wholesale customers dataset:" display(samples)
Chosen samples of wholesale customers dataset:
MIT
Udacity/MachineLearning/customer_segments_project/customer_segments_nabin_proj.ipynb
nacharya/notebooks
Question 1Consider the total purchase cost of each product category and the statistical description of the dataset above for your sample customers. *What kind of establishment (customer) could each of the three samples you've chosen represent?* **Hint:** Examples of establishments include places like markets, cafes,...
samples_value_mean = data.describe().loc['mean'] samples_mean = samples.append(samples_value_mean) foo = samples_mean.plot(kind='bar', figsize=(12,6))
_____no_output_____
MIT
Udacity/MachineLearning/customer_segments_project/customer_segments_nabin_proj.ipynb
nacharya/notebooks
1st one: Grocery Store as Fresh is above mean, grocery is in the mean, and detergent purchase costs are above the mean 2nd one: Possibly a restaurant cafe because Frozen, Fresh are the highest followed by a decent amount of Deli as well. Only the Frozen item is higher than the mean3rd one: A retailer or a store that se...
# Make a copy of the DataFrame, using the 'drop' function to drop the given feature #feature_name = 'Grocery' def do_feat(feature_name, data): new_data = data.drop(feature_name, 1) from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(new_data, data[featu...
prediction score for Grocery is: 0.681884008544 prediction score for Detergents_Paper is: 0.271666980627 prediction score for Delicatessen is: -2.2547115372 prediction score for Frozen is: -0.210135890125 prediction score for Milk is: 0.156275395017 prediction score for Fresh is: -0.385749710204
MIT
Udacity/MachineLearning/customer_segments_project/customer_segments_nabin_proj.ipynb
nacharya/notebooks
Question 2*Which feature did you attempt to predict? What was the reported prediction score? Is this feature is necessary for identifying customers' spending habits?* **Hint:** The coefficient of determination, `R^2`, is scored between 0 and 1, with 1 being a perfect fit. A negative `R^2` implies the model fails to f...
# Produce a scatter matrix for each pair of features in the data pd.scatter_matrix(data, alpha = 0.3, figsize = (14,8), diagonal = 'kde'); import seaborn as sns sns.heatmap(data.corr(), annot=True)
_____no_output_____
MIT
Udacity/MachineLearning/customer_segments_project/customer_segments_nabin_proj.ipynb
nacharya/notebooks
Question 3*Are there any pairs of features which exhibit some degree of correlation? Does this confirm or deny your suspicions about the relevance of the feature you attempted to predict? How is the data for those features distributed?* **Hint:** Is the data normally distributed? Where do most of the data points lie?...
# Scale the data using the natural logarithm log_data = np.log(data) # TODO: Scale the sample data using the natural logarithm log_samples = np.log(samples) # Produce a scatter matrix for each pair of newly-transformed features pd.scatter_matrix(log_data, alpha = 0.3, figsize = (14,8), diagonal = 'kde');
_____no_output_____
MIT
Udacity/MachineLearning/customer_segments_project/customer_segments_nabin_proj.ipynb
nacharya/notebooks
ObservationAfter applying a natural logarithm scaling to the data, the distribution of each feature should appear much more normal. For any pairs of features you may have identified earlier as being correlated, observe here whether that correlation is still present (and whether it is now stronger or weaker than before...
# Display the log-transformed sample data display(log_samples) import matplotlib.pyplot as plt fig, axes = plt.subplots(2, 3) axes = axes.flatten() fig.set_size_inches(18, 6) fig.suptitle('Distribution of Features') for i, col in enumerate(data.columns): feature = data[col] sns.distplot(feature, label=col, ax=...
_____no_output_____
MIT
Udacity/MachineLearning/customer_segments_project/customer_segments_nabin_proj.ipynb
nacharya/notebooks
Implementation: Outlier DetectionDetecting outliers in the data is extremely important in the data preprocessing step of any analysis. The presence of outliers can often skew results which take into consideration these data points. There are many "rules of thumb" for what constitutes an outlier in a dataset. Here, we ...
outliers_list = np.array([], dtype='int64') #cnt = Counter() # For each feature find the data points with extreme high or low values for feature in log_data.keys(): # Calculate Q1 (25th percentile of the data) for the given feature Q1 = np.percentile(log_data[feature],25) # Calculate Q3 (75th per...
Data points considered outliers for the feature 'Fresh':
MIT
Udacity/MachineLearning/customer_segments_project/customer_segments_nabin_proj.ipynb
nacharya/notebooks
Question 4*Are there any data points considered outliers for more than one feature based on the definition above? Should these data points be removed from the dataset? If any data points were added to the `outliers` list to be removed, explain why.* Data Points considered for more than one feature (Observation in out...
# Apply PCA by fitting the good data with the same number of dimensions as features from sklearn.decomposition import PCA pca = PCA(n_components=6).fit(good_data) # Transform log_samples using the PCA fit above pca_samples = pca.transform(log_samples) # Generate PCA results plot pca_results = vs.pca_results(good_data...
_____no_output_____
MIT
Udacity/MachineLearning/customer_segments_project/customer_segments_nabin_proj.ipynb
nacharya/notebooks
Question 5*How much variance in the data is explained* ***in total*** *by the first and second principal component? What about the first four principal components? Using the visualization provided above, discuss what the first four dimensions best represent in terms of customer spending.* **Hint:** A positive increas...
# Display sample log-data after having a PCA transformation applied display(pd.DataFrame(np.round(pca_samples, 4), columns = pca_results.index.values))
_____no_output_____
MIT
Udacity/MachineLearning/customer_segments_project/customer_segments_nabin_proj.ipynb
nacharya/notebooks
Implementation: Dimensionality ReductionWhen using principal component analysis, one of the main goals is to reduce the dimensionality of the data — in effect, reducing the complexity of the problem. Dimensionality reduction comes at a cost: Fewer dimensions used implies less of the total variance in the data is being...
# Apply PCA by fitting the good data with only two dimensions pca = PCA(n_components=2).fit(good_data) # Transform the good data using the PCA fit above reduced_data = pca.transform(good_data) # Transform log_samples using the PCA fit above pca_samples = pca.transform(log_samples) # Create a DataFrame for the reduce...
[ 0.44302505 0.70681723]
MIT
Udacity/MachineLearning/customer_segments_project/customer_segments_nabin_proj.ipynb
nacharya/notebooks
ObservationRun the code below to see how the log-transformed sample data has changed after having a PCA transformation applied to it using only two dimensions. Observe how the values for the first two dimensions remains unchanged when compared to a PCA transformation in six dimensions.
# Display sample log-data after applying PCA transformation in two dimensions display(pd.DataFrame(np.round(pca_samples, 4), columns = ['Dimension 1', 'Dimension 2']))
_____no_output_____
MIT
Udacity/MachineLearning/customer_segments_project/customer_segments_nabin_proj.ipynb
nacharya/notebooks
Visualizing a BiplotA biplot is a scatterplot where each data point is represented by its scores along the principal components. The axes are the principal components (in this case `Dimension 1` and `Dimension 2`). In addition, the biplot shows the projection of the original features along the components. A biplot can...
# Create a biplot vs.biplot(good_data, reduced_data, pca)
_____no_output_____
MIT
Udacity/MachineLearning/customer_segments_project/customer_segments_nabin_proj.ipynb
nacharya/notebooks
ObservationOnce we have the original feature projections (in red), it is easier to interpret the relative position of each data point in the scatterplot. For instance, a point the lower right corner of the figure will likely correspond to a customer that spends a lot on `'Milk'`, `'Grocery'` and `'Detergents_Paper'`, ...
# TODO: Apply your clustering algorithm of choice to the reduced data from sklearn.cluster import KMeans from sklearn.metrics import silhouette_score reduced_samples = pd.DataFrame(pca_samples, columns = ['Dimension 1', 'Dimension 2']) clusterer = KMeans(n_clusters=2, random_state=42).fit(reduced_data) # Predict the...
('K-Means silhouette score: ', 0.42628101546910835)
MIT
Udacity/MachineLearning/customer_segments_project/customer_segments_nabin_proj.ipynb
nacharya/notebooks
Question 7*Report the silhouette score for several cluster numbers you tried. Of these, which number of clusters has the best silhouette score?* Cluster of 2: 0.4219Cluster of 4: 0.3326Cluster of 6: 0.3654Cluster of 8: 0.3644Cluster of 10: 0.3505Best silhouette score was obtained for a cluster of 2 Cluster Visualiza...
# Display the results of the clustering from implementation vs.cluster_results(reduced_data, preds, centers, pca_samples)
_____no_output_____
MIT
Udacity/MachineLearning/customer_segments_project/customer_segments_nabin_proj.ipynb
nacharya/notebooks
Implementation: Data RecoveryEach cluster present in the visualization above has a central point. These centers (or means) are not specifically data points from the data, but rather the *averages* of all the data points predicted in the respective clusters. For the problem of creating customer segments, a cluster's ce...
def ndprint(a, format_string ='{0:.2f}'): print [format_string.format(v,i) for i,v in enumerate(a)] # Inverse transform the centers log_centers = pca.inverse_transform(centers) # Exponentiate the centers true_centers = np.exp(log_centers) print "centers:" #display(true_centers) for i,v in enumerate(true_centers):...
centers: [ 8866.53752613 1896.60679852 2476.59086525 2088.23564999 293.89989089 681.28963817] [ 4005.0815051 7899.91306923 12103.82742157 952.34560465 4561.39226009 1035.53326638]
MIT
Udacity/MachineLearning/customer_segments_project/customer_segments_nabin_proj.ipynb
nacharya/notebooks
Question 8Consider the total purchase cost of each product category for the representative data points above, and reference the statistical description of the dataset at the beginning of this project. *What set of establishments could each of the customer segments represent?* **Hint:** A customer who is assigned to `...
# Display the predictions for i, pred in enumerate(sample_preds): print "Sample point", i, "predicted to be in Cluster", pred print 'The distance between sample point {} and center of cluster {}:'.format(i, pred) print (samples.iloc[i] - true_centers.iloc[pred])
Sample point 0 predicted to be in Cluster 1 The distance between sample point 0 and center of cluster 1: Fresh 12160.0 Milk -3670.0 Grocery -4509.0 Frozen -751.0 Detergents_Paper -558.0 Delicatessen -979.0 dtype: float64 Sample point 1 predicted to be i...
MIT
Udacity/MachineLearning/customer_segments_project/customer_segments_nabin_proj.ipynb
nacharya/notebooks
Segment 0 is very high on Detergent and Grocery and Segment 1 is very high on Fresh and fairly low on detergent. If we look at the sample points, the predictions of points 0 and 1 should be swapped. Conclusion In this final section, you will investigate ways that you can make use of the clustered data. First, you wil...
# Display the clustering results based on 'Channel' data vs.channel_results(reduced_data, outliers, pca_samples)
_____no_output_____
MIT
Udacity/MachineLearning/customer_segments_project/customer_segments_nabin_proj.ipynb
nacharya/notebooks
Paraphrase This tutorial is available as an IPython notebook at [Malaya/example/paraphrase](https://github.com/huseinzol05/Malaya/tree/master/example/paraphrase). This module only trained on standard language structure, so it is not save to use it for local language structure.
%%time import malaya from pprint import pprint malaya.paraphrase.available_transformer()
INFO:root:tested on 1k paraphrase texts.
MIT
example/paraphrase/load-paraphrase.ipynb
zulkiflizaki/malaya
Load T5 models ```pythondef transformer(model: str = 't2t', quantized: bool = False, **kwargs): """ Load Malaya transformer encoder-decoder model to generate a paraphrase given a string. Parameters ---------- model : str, optional (default='t2t') Model architecture supported. Allowed values: ...
t5 = malaya.paraphrase.transformer(model = 't5', quantized = True)
WARNING:root:Load quantized model will cause accuracy drop.
MIT
example/paraphrase/load-paraphrase.ipynb
zulkiflizaki/malaya
Paraphrase simple stringWe only provide `greedy_decoder` method for T5 models,```python@check_typedef greedy_decoder(self, string: str, split_fullstop: bool = True): """ paraphrase a string. Decoder is greedy decoder with beam width size 1, alpha 0.5 . Parameters ---------- string: str split_fullstop...
string = "Beliau yang juga saksi pendakwaan kesembilan berkata, ia bagi mengelak daripada wujud isu digunakan terhadap Najib." pprint(string) pprint(t5.greedy_decoder([string])) string = """ PELETAKAN jawatan Tun Dr Mahathir Mohamad sebagai Pengerusi Parti Pribumi Bersatu Malaysia (Bersatu) ditolak di dalam mesyuarat k...
_____no_output_____
MIT
example/paraphrase/load-paraphrase.ipynb
zulkiflizaki/malaya
Load TransformerTo load 8-bit quantized model, simply pass `quantized = True`, default is `False`.We can expect slightly accuracy drop from quantized model, and not necessary faster than normal 32-bit float model, totally depends on machine.
model = malaya.paraphrase.transformer(model = 'small-t2t') quantized_model = malaya.paraphrase.transformer(model = 'small-t2t', quantized = True)
WARNING:tensorflow:From /Users/huseinzolkepli/Documents/Malaya/malaya/function/__init__.py:112: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.
MIT
example/paraphrase/load-paraphrase.ipynb
zulkiflizaki/malaya
Predict using greedy decoder```pythondef greedy_decoder(self, strings: List[str], **kwargs): """ Paraphrase strings using greedy decoder. Parameters ---------- strings: List[str] Returns ------- result: List[str] """```
' '.join(splitted[:2]) model.greedy_decoder([' '.join(splitted[:2])]) quantized_model.greedy_decoder([' '.join(splitted[:2])])
_____no_output_____
MIT
example/paraphrase/load-paraphrase.ipynb
zulkiflizaki/malaya
Predict using beam decoder```pythondef beam_decoder(self, strings: List[str], **kwargs): """ Paraphrase strings using beam decoder, beam width size 3, alpha 0.5 . Parameters ---------- strings: List[str] Returns ------- result: List[str] """```
model.beam_decoder([' '.join(splitted[:2])]) quantized_model.beam_decoder([' '.join(splitted[:2])])
_____no_output_____
MIT
example/paraphrase/load-paraphrase.ipynb
zulkiflizaki/malaya
Predict using nucleus decoder```pythondef nucleus_decoder(self, strings: List[str], top_p: float = 0.7, **kwargs): """ Paraphrase strings using nucleus sampling. Parameters ---------- strings: List[str] top_p: float, (default=0.7) cumulative distribution and cut off as soon as the CDF exceeds ...
model.nucleus_decoder([' '.join(splitted[:2])]) quantized_model.nucleus_decoder([' '.join(splitted[:2])], top_p = 0.5)
_____no_output_____
MIT
example/paraphrase/load-paraphrase.ipynb
zulkiflizaki/malaya
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1-mKbU9Yz9vaaQz6cr13SrvvMy_4hXkk7?usp=sharing) Investment Management 1--- Assignment 1**You have to use this Colab notebook to complete the assignment. To get started, create a copy of the notebook and ...
# step 1: install required libraries using "!pip install" # YOUR CODE HERE # step 2: import required libraries using "import" # YOUR CODE HERE # step 3: fetch historical asset prices # YOUR CODE HERE
_____no_output_____
MIT
2_assignment_1/1_PM_assignment_1.ipynb
MathildeBreton/TBS_portfolio_management_2022
Part 1.2. Obtaining data on risk-free asset (4pt)Using a financial data library (e.g. `yfinance`) of your choice, obtain daily data on the U.S. risk-free (1-month Treasury Bill) rate for the last 5 years and store them in a `pandas` DataFrame object named `rf`.If you are unable to obtain the risk-free data using your c...
# step 4: fetch historical risk-free rate # YOUR CODE HERE
_____no_output_____
MIT
2_assignment_1/1_PM_assignment_1.ipynb
MathildeBreton/TBS_portfolio_management_2022
**Part 2: Visualising historical asset prices [10pt]**In this part of the assignment, you will be manipulating dataframes containing historical asset prices using Pandas, and visualising them using a Python plotting library of your choice. The purpose of these visualisations is to help you explore the data and identify...
# step 5: import required data visualisation library # YOUR CODE HERE
_____no_output_____
MIT
2_assignment_1/1_PM_assignment_1.ipynb
MathildeBreton/TBS_portfolio_management_2022
Part 2.1. Rebased stock prices (6pt)To make comparing and plotting different asset price series together easier, we often "rebase" all prices to a given initial value - e.g. 100. In this section, you need to rebase the adjusted close prices for your stocks and plot them on the same diagram using a visualisation library...
# step 6: import required data visualisation library # YOUR CODE HERE
_____no_output_____
MIT
2_assignment_1/1_PM_assignment_1.ipynb
MathildeBreton/TBS_portfolio_management_2022
**Part 3: Absolute return and risk measures [40pt]**In this part of the assignment, you will work with basic financial calculations and functions, such as computing and compounding investment returns, calculating averages, and computing measures of investment risk.I suggest you use `pandas` dataframes to store all nece...
# step 7: import required data visualisation library # YOUR CODE HERE
_____no_output_____
MIT
2_assignment_1/1_PM_assignment_1.ipynb
MathildeBreton/TBS_portfolio_management_2022
3.2. Distribution of returns (5pt)Check what the return distributions look like by plotting a histogram of daily returns calculated in the previous section. You can use any Python visualisation library of your choice.Plot returns distributions for both, arithmetic and logarithmic returns. Discuss whether there are sig...
# step 8: import required data visualisation library # YOUR CODE HERE
_____no_output_____
MIT
2_assignment_1/1_PM_assignment_1.ipynb
MathildeBreton/TBS_portfolio_management_2022
**Your response/ short explanation:** ________HERE_________ 3.3. Correlation matrix (5pt)Using daily arithmetic stock returns, compute pairwise correlations between your 5 assets and plot a correlation matrix. (optional) You may want to have a look at the `heatmap()` method in the `Seaborn` visualisation library. It a...
# step 9: import required data visualisation library # YOUR CODE HERE
_____no_output_____
MIT
2_assignment_1/1_PM_assignment_1.ipynb
MathildeBreton/TBS_portfolio_management_2022
3.4. Cumulative returns (8pt)Using the arithmetic daily returns, compute cumulative returns for each stock over the last 1–, 3-, and 5- year periods and display them as values. Once done, annualise the resulting cumulative daily returns for each stock and display them as well.
# step 10: import required data visualisation library # YOUR CODE HERE
_____no_output_____
MIT
2_assignment_1/1_PM_assignment_1.ipynb
MathildeBreton/TBS_portfolio_management_2022
3.5. Arithmetic average returns (8pt)Compute arithmetic average daily returns for each stock, annualise them, and display the resulting values. As there are typically 252 trading days in a year, to annualise a daily return $r_d$ we use:$$ (1+r_d)^{252} - 1$$
# step 11: import required data visualisation library # YOUR CODE HERE
_____no_output_____
MIT
2_assignment_1/1_PM_assignment_1.ipynb
MathildeBreton/TBS_portfolio_management_2022
3.6. Standard deviation (8pt)Using the stock returns calculated earlier, compute standard deviations of daily returns for each stock over the last 1–, 3-, and 5- year periods and display them.Once done, repeat the calculation of standard deviations but using monthly returns instead. Display the resulting values.Explai...
# step 12: import required data visualisation library # YOUR CODE HERE
_____no_output_____
MIT
2_assignment_1/1_PM_assignment_1.ipynb
MathildeBreton/TBS_portfolio_management_2022
**Your response/ short explanation:** ________HERE_________ **Part 4: Risk-adjusted performance evaluation [40pt]**As part of the course we considered several risk-adjusted performance evaluation measures. In this section of the assignment you are asked to compute one of them - the Sharpe ratio: $$Sharpe\ ratio = \frac...
# step 13: import required data visualisation library # YOUR CODE HERE
_____no_output_____
MIT
2_assignment_1/1_PM_assignment_1.ipynb
MathildeBreton/TBS_portfolio_management_2022
Part 4.2. Sharpe measure function [30pt]Define a new Python function `sharpe(ticker_1, ticker_2, ticker_3)` which:* accepts 3 stock tickers as the only arguments;* fetches historical daily prices for the 3 selected tickers over the last 3 years;* fetches U.S. treasury bill (1-month T-Bill rates) rates over the corr...
# step 14: install required libraries and import as needed def sharpe(ticker_1, ticker_2, ticker_3): """This function returns annualised Sharpe ratios for the entered tickers using last 3 years of stock data from Yahoo finance""" # YOUR CODE HERE # YOUR CODE HERE return # YOUR CODE HERE # execute you...
_____no_output_____
MIT
2_assignment_1/1_PM_assignment_1.ipynb
MathildeBreton/TBS_portfolio_management_2022
Preprocessing captions
# Turn a Unicode string to plain ASCII, thanks to # https://stackoverflow.com/a/518232/2809427 def unicodeToAscii(s): return ''.join( c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn' ) # Lowercase, trim, and remove non-letter characters def normalizeString(...
_____no_output_____
MIT
12_case_study_of_evaluating_attention_in_COCO_dataset/codes/EDA_COCO_Dataset.ipynb
lnpandey/DL_explore_synth_data
Exploratory Data Analysis on COCO datasets
import json import pandas as pd import matplotlib.pyplot as plt import matplotlib import numpy as np import pdb import os from pycocotools.coco import COCO from skimage import io font = {'family' : 'Arial', 'weight' : 'normal', 'size' : 12} matplotlib.rc('font', **font)
_____no_output_____
MIT
12_case_study_of_evaluating_attention_in_COCO_dataset/codes/EDA_COCO_Dataset.ipynb
lnpandey/DL_explore_synth_data
Setting the root directory and annotation json file
# src_root = '../../../../datasets/voc2012/' # src_subset = 'images/' # src_file = src_root+'annotations/instances_train2012.json' # src_desc = 'train2017_voc12' src_root = '../../../../datasets/coco/' src_subset = '/content/opt/cocoapi/images/train2014' src_file = '/content/opt/cocoapi/annotations/instances_train20...
_____no_output_____
MIT
12_case_study_of_evaluating_attention_in_COCO_dataset/codes/EDA_COCO_Dataset.ipynb
lnpandey/DL_explore_synth_data
Basic High Level Information
# Basic High Level Information n_images = len(root['images']) n_boxes = len(root['annotations']) n_categ = len(root['categories']) # height, width heights = [x['height'] for x in root['images']] widths = [x['width'] for x in root['images']] print('Dataset Name: ',src_desc) print('Number of images: ',n_images) pri...
Dataset Name: train2014_coco Number of images: 82783 Number of bounding boxes: 604907 Number of classes: 80 Max min avg height: 640 51 483 Max min avg width: 640 59 578
MIT
12_case_study_of_evaluating_attention_in_COCO_dataset/codes/EDA_COCO_Dataset.ipynb
lnpandey/DL_explore_synth_data
Distribution of objects across images
# Objects per image distribution img2nboxes = {} # mapping "image id" to "number of boxes" for ann in root['annotations']: img_id = ann['image_id'] if img_id in img2nboxes.keys(): img2nboxes[img_id] += 1 else: img2nboxes[img_id] = 1 nboxes_list = list(img2nboxes.values()) min_nboxes...
_____no_output_____
MIT
12_case_study_of_evaluating_attention_in_COCO_dataset/codes/EDA_COCO_Dataset.ipynb
lnpandey/DL_explore_synth_data
Class wise distribution of objects
# Class distribution class2nboxes = {} for ann in root['annotations']: cat_id = ann['category_id'] if cat_id in class2nboxes.keys(): class2nboxes[cat_id] += 1 else: class2nboxes[cat_id] = 1 sorted_c2nb = [(k,v)for k, v in sorted(class2nboxes.items(), reverse=True, key=lambda item: it...
_____no_output_____
MIT
12_case_study_of_evaluating_attention_in_COCO_dataset/codes/EDA_COCO_Dataset.ipynb
lnpandey/DL_explore_synth_data
Class wise bounding box area distribution
# Class wise bounding box area distribution bbox_areas = {} # key: class index, value -> a list of bounding box areas for ann in root['annotations']: area = ann['area'] cat_id = ann['category_id'] if area <= 0.0: continue if cat_id in bbox_areas.keys(): bbox_areas[cat_id].app...
_____no_output_____
MIT
12_case_study_of_evaluating_attention_in_COCO_dataset/codes/EDA_COCO_Dataset.ipynb
lnpandey/DL_explore_synth_data
Class wise 'occurance' in Captions
# caption['annotations'] caption_list=[] for x in caption['annotations']: caption_list.append(x['caption']) caption_list[1:8] len(caption_list) caption_list[9] if 'toilet' in caption_list[9]: print("bro") class_list=[] for x in root['categories']: class_list.append(x['name']) # class_list cnt_frequency=[] f...
_____no_output_____
MIT
12_case_study_of_evaluating_attention_in_COCO_dataset/codes/EDA_COCO_Dataset.ipynb
lnpandey/DL_explore_synth_data
Scala RepresentationsScala objects are integrated with HoTT by using wrappers, combinators and implicit based convenience methods. In this note we look at the basic representations. The main power of this is to provide automatically (through implicits) types and scala bindings for functions from the basic ones.A more ...
load.jar("/home/gadgil/code/ProvingGround/core/.jvm/target/scala-2.11/ProvingGround-Core-assembly-0.8.jar") import provingground._ import HoTT._ import ScalaRep._
_____no_output_____
MIT
notes/.ipynb_checkpoints/ScalaRep-checkpoint.ipynb
alf239/ProvingGround
We consider the type of Natural numbers formed from Integers. This is defined in ScalaRep as:```scalacase object NatInt extends ScalaTyp[Int]```**Warning:** This is an unsafe type, as Integers can overflow, and there is no checking for positivity.
NatInt
_____no_output_____
MIT
notes/.ipynb_checkpoints/ScalaRep-checkpoint.ipynb
alf239/ProvingGround
Conversion using the term methodThe term method converts a scala object, with scala type T say, into a Term, provided there is an implicit representation with scala type T.
import NatInt.rep 1.term
_____no_output_____
MIT
notes/.ipynb_checkpoints/ScalaRep-checkpoint.ipynb
alf239/ProvingGround
Functions to FuncTermsGiven the representation of Int, there are combinators that give representations of, for instance Int => Int => Int. Note also that the type of the resulting term is a type parameter of the scala representations, so we get a refined compile time type
val sum = ((n: Int) => (m: Int) => n + m).term sum(1.term)(2.term) val n = "n" :: NatInt sum(n)(2.term) val s = lmbda(n)(sum(n)(2.term)) s(3.term)
_____no_output_____
MIT
notes/.ipynb_checkpoints/ScalaRep-checkpoint.ipynb
alf239/ProvingGround
We will also define the product
val prod = ((n : Int) => (m: Int) => n * m).term prod(2.term)(4.term)
_____no_output_____
MIT
notes/.ipynb_checkpoints/ScalaRep-checkpoint.ipynb
alf239/ProvingGround
Options
# parse options problem = 'twelve_pieces_process.json' # 'pavilion_process.json' # 'twelve_pieces_process.json' problem_subdir = 'results' recompute_action_states = False load_external_movements = False from collections import namedtuple PlanningArguments = namedtuple('PlanningArguments', ['problem', 'viewer', 'debug'...
_____no_output_____
MIT
examples/notebooks/SCF_diagram.ipynb
gramaziokohler/integral_timber_joints
Parse process from json
import os from termcolor import cprint import pybullet_planning as pp from integral_timber_joints.planning.parsing import parse_process, save_process_and_movements, get_process_path, save_process process = parse_process(problem, subdir=problem_subdir) result_path = get_process_path(problem, subdir='results') if len(pro...
45/72
MIT
examples/notebooks/SCF_diagram.ipynb
gramaziokohler/integral_timber_joints
read jsons
# from collections import defaultdict import json # file_name = 'b4_runtime_data_w_TC_final_nonlinear.json' notc_file_name = 'b4_runtime_data_No_TC_final_all.json' tc_file_name = 'b4_runtime_data_w_TC_nonlinear_40_trials.json' tc_file_name2 = 'b4_runtime_data_w_TC_final_linear.json' # b4_runtime_data_No_TC_21-07-06_1...
dict_keys(['nonlinear', 'linear_forward', 'linear_backward']) dict_keys(['nonlinear', 'linear_forward', 'linear_backward'])
MIT
examples/notebooks/SCF_diagram.ipynb
gramaziokohler/integral_timber_joints
B4-Histogram
from collections import defaultdict # aggregate all success/failure trials agg_data = {'notc':{}, 'tc':{}} for tc_flag in runtime_data: for solve_mode_ in runtime_data[tc_flag]: agg_data[tc_flag][solve_mode_] = defaultdict(list) cnt = 0 for outer_trial_i, tdata in runtime_data[tc_flag][sol...
_____no_output_____
MIT
examples/notebooks/SCF_diagram.ipynb
gramaziokohler/integral_timber_joints
All beam scatter plot
# from collections import defaultdict import json file_names = {'b{}'.format(bid) : 'b{}_runtime_data_w_TC_{}.json'.format(bid, '21-07-06_23-04-03') \ for bid in list(range(0,25)) + list(range(26,32))} file_names.update( {'b{}'.format(bid) : 'b{}_runtime_data_w_TC_{}.json'.format(bid, '21-07-07_07-55...
_____no_output_____
MIT
examples/notebooks/SCF_diagram.ipynb
gramaziokohler/integral_timber_joints
All-beam scatter plot
# from collections import defaultdict import json file_names = {bid : 'b{}_runtime_data_w_TC_{}.json'.format(bid, '21-07-06_23-04-03') \ for bid in list(range(0,25)) + list(range(26,32))} file_names.update( {bid : 'b{}_runtime_data_w_TC_{}.json'.format(bid, '21-07-07_07-55-05') for bid in range(3...
_____no_output_____
MIT
examples/notebooks/SCF_diagram.ipynb
gramaziokohler/integral_timber_joints
Single result
fn = 'b6_runtime_data_w_TC_21-07-07_21-58-12.json' single_runtime_data = {} with open('figs/{}'.format(fn), 'r') as f: single_runtime_data = json.load(f) # ['nonlinear', 'linear_forward', 'linear_backward'] for bid in [25]: # [4, 13, 32, 37, 38, 39]: #[6,25,29,34,36]: # fn = 'b{}_runtime_data_w_TC_21-07-08_19...
==================== b25 | #nonlinear-T#0: True - BT 9 | time 542.60 ---
MIT
examples/notebooks/SCF_diagram.ipynb
gramaziokohler/integral_timber_joints
Detailed diagram
from plotly.subplots import make_subplots import plotly.graph_objects as go from integral_timber_joints.process import RoboticFreeMovement, RoboticLinearMovement, RoboticClampSyncLinearMovement # solve_mode_ = 'linear_forward' # linear_backward | linear_forward | nonlinear beam_id = file_name.split('_runtime_data')[0]...
_____no_output_____
MIT
examples/notebooks/SCF_diagram.ipynb
gramaziokohler/integral_timber_joints
Save runtime data
runtime_data.keys()
_____no_output_____
MIT
examples/notebooks/SCF_diagram.ipynb
gramaziokohler/integral_timber_joints
Start client
from integral_timber_joints.planning.robot_setup import load_RFL_world from integral_timber_joints.planning.run import set_initial_state # * Connect to path planning backend and initialize robot parameters # viewer or diagnosis or view_states or watch or step_sim, client, robot, _ = load_RFL_world(viewer=False, verbos...
_____no_output_____
MIT
examples/notebooks/SCF_diagram.ipynb
gramaziokohler/integral_timber_joints
Visualize traj
from integral_timber_joints.planning.state import set_state from integral_timber_joints.planning.visualization import visualize_movement_trajectory altered_ms = [process.get_movement_by_movement_id('A43_M2')] set_state(client, robot, process, process.initial_state) for altered_m in altered_ms: visualize_movement_t...
=== Viz: No traj found for RoboticLinearMovement(#A43_M2, Linear Approach 2 of 2 to place CL3 ('c2') in storage., traj 0) -- has_start_conf False, has_end_conf True Press enter to continue
MIT
examples/notebooks/SCF_diagram.ipynb
gramaziokohler/integral_timber_joints
Disconnect client
client.disconnect()
_____no_output_____
MIT
examples/notebooks/SCF_diagram.ipynb
gramaziokohler/integral_timber_joints
Plan only one movement
# if id_only: # beam_id = process.get_beam_id_from_movement_id(id_only) # process.get_movement_summary_by_beam_id(beam_id) from integral_timber_joints.planning.stream import compute_free_movement, compute_linear_movement from integral_timber_joints.planning.solve import compute_movement chosen_m = process.get_...
=== Viz: RoboticLinearMovement(#A2_M1, Linear Advance to Final Frame of Beam ('b0'), traj 1)
MIT
examples/notebooks/SCF_diagram.ipynb
gramaziokohler/integral_timber_joints
Debug
prev_m = process.get_movement_by_movement_id('A40_M6') start_state = process.get_movement_start_state(prev_m) end_state = process.get_movement_end_state(prev_m) # v = end_state['robot'].current_frame.point - start_state['robot'].current_frame.point # list(v) set_state(client, robot, process, end_state) print(end_state...
State: current frame: { "point": [ 16365.989685058594, 5373.808860778809, 1185.4075193405151 ], "xaxis": [ -0.25802939931448104, 0.6277901217809272, 0.7343707456616834 ], "yaxis": [ -0.9661370648091927, -0.16763997964096333, -0....
MIT
examples/notebooks/SCF_diagram.ipynb
gramaziokohler/integral_timber_joints
Ungraded Lab: GradCAMThis lab will walk you through generating gradient-weighted class activation maps (GradCAMs) for model predictions. - This is similar to the CAMs you generated before except: - GradCAMs uses gradients instead of the global average pooling weights to weight the activations. Imports
%tensorflow_version 2.x import warnings warnings.filterwarnings("ignore") import os import glob import cv2 from pathlib import Path import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from skimage.io import imread, imsave from skimage.transform import resize from sklearn.m...
_____no_output_____
Apache-2.0
Copy_of_C3_W4_Lab_4_GradCam.ipynb
nafiul-araf/TensorFlow-Advanced-Techniques-Specialization
Download and Prepare the DatasetYou will use the Cats vs Dogs dataset again for this exercise. The following will prepare the train, test, and eval sets.
tfds.disable_progress_bar() splits = ['train[:80%]', 'train[80%:90%]', 'train[90%:]'] # load the dataset given the splits defined above splits, info = tfds.load('cats_vs_dogs', with_info=True, as_supervised=True, split = splits) (train_examples, validation_examples, test_examples) = splits num_examples = info.split...
_____no_output_____
Apache-2.0
Copy_of_C3_W4_Lab_4_GradCam.ipynb
nafiul-araf/TensorFlow-Advanced-Techniques-Specialization
ModellingYou will use a pre-trained VGG16 network as your base model for the classifier. This will be followed by a global average pooling (GAP) and a 2-neuron Dense layer with softmax activation for the output. The earlier VGG blocks will be frozen and we will just fine-tune the final layers during training. These st...
def build_model(): # load the base VGG16 model base_model = vgg16.VGG16(input_shape=IMAGE_SIZE + (3,), weights='imagenet', include_top=False) # add a GAP layer output = layers.GlobalAveragePooling2D()(base_model.output) # output has two neurons for the 2 class...
_____no_output_____
Apache-2.0
Copy_of_C3_W4_Lab_4_GradCam.ipynb
nafiul-araf/TensorFlow-Advanced-Techniques-Specialization
You can now train the model. This will take around 10 minutes to run.
EPOCHS = 3 model.fit(train_batches, epochs=EPOCHS, validation_data=validation_batches)
_____no_output_____
Apache-2.0
Copy_of_C3_W4_Lab_4_GradCam.ipynb
nafiul-araf/TensorFlow-Advanced-Techniques-Specialization
Model InterpretabilityLet's now go through the steps to generate the class activation maps. You will start by specifying the layers you want to visualize.
# select all the layers for which you want to visualize the outputs and store it in a list outputs = [layer.output for layer in model.layers[1:18]] # Define a new model that generates the above output vis_model = Model(model.input, outputs) # store the layer names we are interested in layer_names = [] for layer in ou...
_____no_output_____
Apache-2.0
Copy_of_C3_W4_Lab_4_GradCam.ipynb
nafiul-araf/TensorFlow-Advanced-Techniques-Specialization
Class activation maps (GradCAM)We'll define a few more functions to output the maps. `get_CAM()` is the function highlighted in the lectures and takes care of generating the heatmap of gradient weighted features. `show_random_sample()` takes care of plotting the results.
def get_CAM(processed_image, actual_label, layer_name='block5_conv3'): model_grad = Model([model.inputs], [model.get_layer(layer_name).output, model.output]) with tf.GradientTape() as tape: conv_output_values, predictions = model_grad(processed_image) # watch the co...
_____no_output_____
Apache-2.0
Copy_of_C3_W4_Lab_4_GradCam.ipynb
nafiul-araf/TensorFlow-Advanced-Techniques-Specialization
Time to visualize the results
# Choose an image index to show, or leave it as None to get a random image activations = show_sample(idx=None)
_____no_output_____
Apache-2.0
Copy_of_C3_W4_Lab_4_GradCam.ipynb
nafiul-araf/TensorFlow-Advanced-Techniques-Specialization
Intermediate activations of layersYou can use the utility function below to visualize the activations in the intermediate layers you defined earlier. This plots the feature side by side for each convolution layer starting from the earliest layer all the way to the final convolution layer.
def visualize_intermediate_activations(layer_names, activations): assert len(layer_names)==len(activations), "Make sure layers and activation values match" images_per_row=16 for layer_name, layer_activation in zip(layer_names, activations): nb_features = layer_activation.shape[-1] size=...
_____no_output_____
Apache-2.0
Copy_of_C3_W4_Lab_4_GradCam.ipynb
nafiul-araf/TensorFlow-Advanced-Techniques-Specialization
Ensembling several predictionsEnsembling is about combining the forecasts produced by several models, in order to obtain a final – and hopefully better forecast.
models = [NaiveSeasonal(12), NaiveSeasonal(24), NaiveDrift()] model_predictions = [m.historical_forecasts(series, start=pd.Timestamp('20170101'), forecast_horizon=12, stride=12, ...
_____no_output_____
Apache-2.0
emsembling_predictions.ipynb
siyue-zhang/time-series-forecast-Darts
RegressionEnsembleModel approach
ensemble_model = RegressionEnsembleModel( forecasting_models=[NaiveSeasonal(12), NaiveSeasonal(24), NaiveDrift()], regression_train_n_points=12) ensemble_model.fit(train) ensemble_pred = ensemble_model.predict(48) series.plot(label='actual') ensemble_pred.plot(label='Ensemble forecast') plt.title('MAPE = {:.2...
_____no_output_____
Apache-2.0
emsembling_predictions.ipynb
siyue-zhang/time-series-forecast-Darts
Only Naive model
naive_model = NaiveSeasonal(K=24) naive_model.fit(train) naive_forecast = naive_model.predict(48) val[:48].plot(label='actual') naive_forecast.plot(label='Navie forecast') plt.title('MAPE = {:.2f}%'.format(mape(naive_forecast, series))) plt.legend();
_____no_output_____
Apache-2.0
emsembling_predictions.ipynb
siyue-zhang/time-series-forecast-Darts
Ex1 - Getting and knowing your DataCheck out [World Food Facts Exercises Video Tutorial](https://youtu.be/_jCSK4cMcVw) to watch a data scientist go through the exercises Step 1. Go to https://www.kaggle.com/openfoodfacts/world-food-facts/data Step 2. Download the dataset to your computer and unzip it.
import pandas as pd import numpy as np
_____no_output_____
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/World Food Facts/Exercises_with_solutions.ipynb
iamoespana92/pandas_exercises
Step 3. Use the tsv file and assign it to a dataframe called food
food = pd.read_csv('~/Desktop/en.openfoodfacts.org.products.tsv', sep='\t')
//anaconda/lib/python2.7/site-packages/IPython/core/interactiveshell.py:2717: DtypeWarning: Columns (0,3,5,19,20,24,25,26,27,28,36,37,38,39,48) have mixed types. Specify dtype option on import or set low_memory=False. interactivity=interactivity, compiler=compiler, result=result)
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/World Food Facts/Exercises_with_solutions.ipynb
iamoespana92/pandas_exercises
Step 4. See the first 5 entries
food.head()
_____no_output_____
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/World Food Facts/Exercises_with_solutions.ipynb
iamoespana92/pandas_exercises
Step 5. What is the number of observations in the dataset?
food.shape #will give you both (observations/rows, columns) food.shape[0] #will give you only the observations/rows number
_____no_output_____
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/World Food Facts/Exercises_with_solutions.ipynb
iamoespana92/pandas_exercises
Step 6. What is the number of columns in the dataset?
print(food.shape) #will give you both (observations/rows, columns) print(food.shape[1]) #will give you only the columns number #OR food.info() #Columns: 163 entries
(356027, 163) 163 <class 'pandas.core.frame.DataFrame'> RangeIndex: 356027 entries, 0 to 356026 Columns: 163 entries, code to water-hardness_100g dtypes: float64(107), object(56) memory usage: 442.8+ MB
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/World Food Facts/Exercises_with_solutions.ipynb
iamoespana92/pandas_exercises
Step 7. Print the name of all the columns.
food.columns
_____no_output_____
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/World Food Facts/Exercises_with_solutions.ipynb
iamoespana92/pandas_exercises
Step 8. What is the name of 105th column?
food.columns[104]
_____no_output_____
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/World Food Facts/Exercises_with_solutions.ipynb
iamoespana92/pandas_exercises
Step 9. What is the type of the observations of the 105th column?
food.dtypes['-glucose_100g']
_____no_output_____
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/World Food Facts/Exercises_with_solutions.ipynb
iamoespana92/pandas_exercises
Step 10. How is the dataset indexed?
food.index
_____no_output_____
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/World Food Facts/Exercises_with_solutions.ipynb
iamoespana92/pandas_exercises
Step 11. What is the product name of the 19th observation?
food.values[18][7]
_____no_output_____
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/World Food Facts/Exercises_with_solutions.ipynb
iamoespana92/pandas_exercises
Testing is goodTesting is one of the most important things we can do in our infrastructure to make sure that things are configured the way we expect them to be and that the system as a whole is operating the way we want it to.In a world of dynamic protocols that are **designed** to continue to operate in the face of m...
from pyhpeimc.auth import * from pyhpeimc.plat.icc import * from pyhpeimc.plat.device import * import jtextfsm as textfsm import yaml #import githubuser import mygithub #file not in github repo auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
_____no_output_____
Apache-2.0
Events/ETSS June 2016/DevOps Networking Model/Testing Your Changes.ipynb
manpowertw/leafspine-ops
First we've got to grab the devID of the switch we wish to test
devid = get_dev_details('10.101.0.221', auth.creds, auth.url)['id'] devid
_____no_output_____
Apache-2.0
Events/ETSS June 2016/DevOps Networking Model/Testing Your Changes.ipynb
manpowertw/leafspine-ops
Now we need to create the list of commands that we want to gather their output. For this example, we want to make sure that OSPF, as a system, is still working. So we want to gather the **display ospf peer** output so that we can tkae a look at the peers and make sure that all expected peers are still present and in a ...
cmd_list = ['display ospf peer']
_____no_output_____
Apache-2.0
Events/ETSS June 2016/DevOps Networking Model/Testing Your Changes.ipynb
manpowertw/leafspine-ops
Now that we've got the command list, we're going to use the **run_dev_cmd** function from the **pyhpeimc** library to gather this for the devid of the switch we specified above.We'll also take a quick look at the contents of the **contents** key of the object that is returned by the run_dev_cmd function.
raw_text_data = run_dev_cmd(devid, cmd_list, auth.creds, auth.url) raw_text_data['content']
_____no_output_____
Apache-2.0
Events/ETSS June 2016/DevOps Networking Model/Testing Your Changes.ipynb
manpowertw/leafspine-ops
Just to be sure, we'll print this out to make sure that this is the response we would actually expect for this command from that specific device OS.
print (raw_text_data['content'])
OSPF Process 1 with Router ID 10.101.0.221 Neighbor Brief Information Area: 0.0.0.0 Router ID Address Pri Dead-Time Interface State 10.101.16.1 10.101.0.1 1 36 Vlan1 Full/BDR 10.101.16.1 10.101.15.1 1 32 ...
Apache-2.0
Events/ETSS June 2016/DevOps Networking Model/Testing Your Changes.ipynb
manpowertw/leafspine-ops
We will now run this through a TextFSM template to transform this string into some structured text which will make it much easier to deal with.
template = open("./Textfsm/Templates/displayospf.textfsm") re_table = textfsm.TextFSM(template) fsm_results = re_table.ParseText(raw_text_data['content']) ospf_peer = [ { 'area': i[0], 'router_id' :i[1], 'address':i[2], 'pri' :i[3], 'deadtime': i[4], 'interface': i[5], 'state': i[6]} for i in fsm_results] print ( "Ther...
There are currently 4 OSPF peers on this device
Apache-2.0
Events/ETSS June 2016/DevOps Networking Model/Testing Your Changes.ipynb
manpowertw/leafspine-ops
Now that we've got an object with all the OSPF Peers in them, let's write some quick code to see if the one specific peer, 10.20.1.1, is present in the OSPF peer table and if it's current state is Full/BDR. This will let us know that the OSPF peer we expect to be in the table is, in fact, still in the table and in the...
for peer in ospf_peer: if (peer['address']) == '10.20.1.1' and peer['state'] == "Full/BDR": print ( peer['address'] + " was the peer I was looking for and it's Full") else: print (peer['address'] + ' was not the peer I was looking for')
10.101.0.1 was not the peer I was looking for 10.101.15.1 was not the peer I was looking for 10.20.1.1 was the peer I was looking for and it's Full was not the peer I was looking for
Apache-2.0
Events/ETSS June 2016/DevOps Networking Model/Testing Your Changes.ipynb
manpowertw/leafspine-ops
Checking IP RoutesWhat about checking the routing table of a remote peer?
cmd_list = ['display ip routing-table'] raw_text_data = run_dev_cmd(devid, cmd_list, auth.creds, auth.url) raw_text_data['content'] print (raw_text_data['content']) template = open("./Textfsm/Templates/displayiproutingtable.textfsm") re_table = textfsm.TextFSM(template) fsm_results = re_table.ParseText(raw_text_data['c...
{ "Proto": "Direct", "Interface": "GE1/0/22", "NextHop": "10.20.10.1 ", "Pre": "0", "DestinationMask": "10.20.10.0/24", "Cost": "0" }
Apache-2.0
Events/ETSS June 2016/DevOps Networking Model/Testing Your Changes.ipynb
manpowertw/leafspine-ops
Checking VLANs
devid = get_dev_details('10.20.10.10', auth.creds, auth.url)['id'] devid cmd_list = ['display vlan brief'] raw_text_data = run_dev_cmd(devid, cmd_list, auth.creds, auth.url) raw_text_data['content'] print (raw_text_data['content']) template = open("./TextFSM/Templates/displayvlanbrief.textfsm") re_table = textfsm.TextF...
_____no_output_____
Apache-2.0
Events/ETSS June 2016/DevOps Networking Model/Testing Your Changes.ipynb
manpowertw/leafspine-ops
Checking our workNow that we've captured the VLANs present on the device, we can easily compare this back to the GITHUB YAML file where we originally defined what VLANs should be on the device.First we'll create the git_vlans object from the file vlans.yaml directly from GITHUB.
gitauth = mygithub.gitcreds() #you didn't think I was going to give you my password did you? git_vlans = yaml.load(requests.get('https://raw.githubusercontent.com/netmanchris/Jinja2-Network-Configurations-Scripts/master/vlans.yaml', auth=gitauth).text)
_____no_output_____
Apache-2.0
Events/ETSS June 2016/DevOps Networking Model/Testing Your Changes.ipynb
manpowertw/leafspine-ops
Cleaning up a bitIf we take a look at the gitvlans variable, we can see it's a little too deep for what we want to do. We're going to perform two transformations on the data here to get it to where we want it to be- grab the contents of the git_vlans['vlans'] key which is just the list of vlans.- use the .pop() metho...
git_vlans = git_vlans['vlans'] for vlan in git_vlans: vlan.pop('vlanStatus') git_vlans
_____no_output_____
Apache-2.0
Events/ETSS June 2016/DevOps Networking Model/Testing Your Changes.ipynb
manpowertw/leafspine-ops
Comparing git_vlans and dev_vlansNow that we've got two different list which contain a vlan dictionary for each VLAN with the exact same keys, we can do a boolean magic to see if each of the VLANs are present in the other objects. We'll first do this by comparing to see if all of the VLANs from the **git_vlans** objec...
for vlan in git_vlans: if vlan in dev_vlans: print (vlan['vlanId'] + " is there") elif vlan not in dev_vlans: print (devv['vlanId'] + " is not there")
1 is there 2 is there 3 is there 10 is there
Apache-2.0
Events/ETSS June 2016/DevOps Networking Model/Testing Your Changes.ipynb
manpowertw/leafspine-ops
Comparing dev_vlans to git_vlansYou didn't think we were done did you?For the last step here, we'll do the exact opposite to see if all of the vlans that are actually present on the device are also defined in the vlans.yaml file on github. We want to make sure that no body snuck in and configured a VLAN in our product...
for vlan in dev_vlans: if vlan in git_vlans: print ( "VLAN " + vlan['vlanId'] + " should be there") elif vlan not in git_vlans: print ( "\nSomebody added VLAN " + vlan['vlanId'] + " when we weren't looking. \n \nGo slap them please.\n\n")
VLAN 1 should be there VLAN 2 should be there VLAN 3 should be there Somebody added VLAN 5 when we weren't looking. Go slap them please. VLAN 10 should be there
Apache-2.0
Events/ETSS June 2016/DevOps Networking Model/Testing Your Changes.ipynb
manpowertw/leafspine-ops