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
Endpoint InterfaceUsing the Endpoint interface to request IPA content is fairly straighforward1. Identify the required IPA Endpoint (URL)2. Use the Endpoint Interface to send a request to the Endpoint3. Decode the response and extract the IPA data Identifying the Surfaces EndpointTo ascertain the Endpoint, we can use ...
vs_endpoint = rdp.Endpoint(session, "https://api.refinitiv.com/data/quantitative-analytics-curves-and-surfaces/v1/surfaces")
_____no_output_____
Apache-2.0
Vol Surfaces Webinar.ipynb
Refinitiv-API-Samples/Article.RDPLibrary.Python.VolatilitySurfaces_Curves
Build our JSON RequestUsing the reference documentation or by referring to the example queries shown on the above API playground page, I can build up my Request. Currently there are four Underlying Types of Volatility Surface supported:* Eti : exchange-traded instruments like equities, equity indices, and futures.* F...
eti_request_body={ "universe": [ { "surfaceTag": "RENAULT", "underlyingType": "Eti", "underlyingDefinition": { "instrumentCode": "RENA.PA" }, "surfaceParameters": { "xAxis": "Date", "yAxis": "Moneyness", ...
_____no_output_____
Apache-2.0
Vol Surfaces Webinar.ipynb
Refinitiv-API-Samples/Article.RDPLibrary.Python.VolatilitySurfaces_Curves
I then send the request to the Platform using the instance of Endpoint interface I created:
eti_response = vs_endpoint.send_request( method = rdp.Endpoint.RequestMethod.POST, body_parameters = eti_request_body ) print(json.dumps(eti_response.data.raw, indent=2))
{ "data": [ { "surfaceTag": "RENAULT", "surface": [ [ null, "0.5", "0.6", "0.7", "0.75", "0.8", "0.85", "0.9", "0.95", "0.975", "1", "1.025", "1.05", "1.1...
Apache-2.0
Vol Surfaces Webinar.ipynb
Refinitiv-API-Samples/Article.RDPLibrary.Python.VolatilitySurfaces_Curves
Once I get the response back, I extract the payload and use the Matplotlib library to plot my surface. For example, below I extract and plot the Volatility Surface data for 'VW'.
surfaces = eti_response.data.raw['data'] plot_surface(surfaces, 'VW')
_____no_output_____
Apache-2.0
Vol Surfaces Webinar.ipynb
Refinitiv-API-Samples/Article.RDPLibrary.Python.VolatilitySurfaces_Curves
Smile CurveI can also use the same surfaces response data to plot a Smile Curve.For example, to compare the volatility smiles of the 4 equities at the chosen expiry time (where the maturity value of 1 is the first expiry):
plot_smile(surfaces, 1)
_____no_output_____
Apache-2.0
Vol Surfaces Webinar.ipynb
Refinitiv-API-Samples/Article.RDPLibrary.Python.VolatilitySurfaces_Curves
Volatility TermsWe can also use the same surfaces response data to plot the Term Structure (the full code for all the plots can be found in the plotting_helper file)Let the user to choose the Moneyness index - **integer value** - to use for the chart:
moneyness=1 plot_term_volatility(surfaces, moneyness)
_____no_output_____
Apache-2.0
Vol Surfaces Webinar.ipynb
Refinitiv-API-Samples/Article.RDPLibrary.Python.VolatilitySurfaces_Curves
Equity Volatility Surface - advanced usageLet's dig deeper into some advanced parameters for ETI volaitlity surfaces.The request is highly configurable and the various parameters & options are listed on the API playground. For example, the options are :* Timestamp : Default, Close, Settle* Volatility Model : SVI or SS...
eti_advanced_request_body={ "universe": [ { "surfaceTag": "ANZ", "underlyingType": "Eti", "underlyingDefinition": { "instrumentCode": "ANZ.AX" }, "surfaceParameters": { "timestamp" :"Close", "volatilityModel": "SS...
{ "data": [ { "surfaceTag": "ANZ", "surface": [ [ null, "0.5", "0.6", "0.7", "0.75", "0.8", "0.85", "0.9", "0.95", "0.975", "1", "1.025", "1.05", "1.1", ...
Apache-2.0
Vol Surfaces Webinar.ipynb
Refinitiv-API-Samples/Article.RDPLibrary.Python.VolatilitySurfaces_Curves
Once again, I extract the payload and plot my surface for 'ANZ'.
surfaces = eti_advanced_response.data.raw['data'] plot_surface(surfaces, 'ANZ')
_____no_output_____
Apache-2.0
Vol Surfaces Webinar.ipynb
Refinitiv-API-Samples/Article.RDPLibrary.Python.VolatilitySurfaces_Curves
Equity Volatility Surface - Weights and Goodness of FitIn this section, I will apply my own weights per moneyness range and check the goodness of fit.I will keep the same ANZ request and simply add my weighting assumptions:* Options with moneyness below 50% will have a 0.5 weight* Options with moneyness above 150% wil...
eti_weights_request_body={ "universe": [ { "surfaceTag": "ANZ_withWeights", "underlyingType": "Eti", "underlyingDefinition": { "instrumentCode": "ANZ.AX" }, "surfaceParameters": { "timestamp" :"Close", "volatility...
{ "data": [ { "surfaceTag": "ANZ_withWeights", "surface": [ [ null, "0.5", "0.6", "0.7", "0.75", "0.8", "0.85", "0.9", "0.95", "0.975", "1", "1.025", "1.05", ...
Apache-2.0
Vol Surfaces Webinar.ipynb
Refinitiv-API-Samples/Article.RDPLibrary.Python.VolatilitySurfaces_Curves
Once again, I extract the payload and plot my new surface for 'ANZ'
surfaces = eti_weights_response.data.raw['data'] plot_surface(surfaces, 'ANZ_withWeights')
_____no_output_____
Apache-2.0
Vol Surfaces Webinar.ipynb
Refinitiv-API-Samples/Article.RDPLibrary.Python.VolatilitySurfaces_Curves
Since we changed the weights, I might want to view the Goodness Of Fit for this new generated surface.
pd.DataFrame(data=surfaces[0]["goodnessOfFit"])
_____no_output_____
Apache-2.0
Vol Surfaces Webinar.ipynb
Refinitiv-API-Samples/Article.RDPLibrary.Python.VolatilitySurfaces_Curves
FX Volatility SurfaceI can also use the same IPA Endpoint to request FX Volatility Surfaces For example the request below, will allow me to generate an FX volatility surface:for USDSGD cross rates express the axes in Dates and Delta and return the data in a matrix format As I mentioned earlier, the request is conf...
fx_request_body={ "universe": [ { "underlyingType": "Fx", "surfaceTag": "FxVol-USDSGD", "underlyingDefinition": { "fxCrossCode": "USDSGD" }, "surfaceLayout": { "format": "Matrix", "yValues":...
{ "data": [ { "surfaceTag": "FxVol-USDSGD", "surface": [ [ null, -0.1, -0.15, -0.2, -0.25, -0.3, -0.35, -0.4, -0.45, 0.5, 0.45, 0.4, 0.35, 0.3, ...
Apache-2.0
Vol Surfaces Webinar.ipynb
Refinitiv-API-Samples/Article.RDPLibrary.Python.VolatilitySurfaces_Curves
Once again, I extract the payload and plot my surface - below I extract and plot the Volatility Surface for 'Singapore Dollar / US Dollar'.
fx_surfaces = fx_response.data.raw['data'] plot_surface(fx_surfaces, 'FxVol-USDSGD', True)
_____no_output_____
Apache-2.0
Vol Surfaces Webinar.ipynb
Refinitiv-API-Samples/Article.RDPLibrary.Python.VolatilitySurfaces_Curves
Let's use the Surfaces to price OTC optionsNow that we know how to build a surface, we will see how we can use them to price OTC contracts.
fc_endpoint = rdp.Endpoint(session, "https://api.refinitiv.com/data/quantitative-analytics/v1/financial-contracts")
_____no_output_____
Apache-2.0
Vol Surfaces Webinar.ipynb
Refinitiv-API-Samples/Article.RDPLibrary.Python.VolatilitySurfaces_Curves
In the request below, I will price two OTC 'BNPP' options:
option_request_body = { "fields": ["InstrumentTag","ExerciseType","OptionType","ExerciseStyle","EndDate","StrikePrice",\ "MarketValueInDealCcy","VolatilityPercent","DeltaPercent","ErrorMessage"], "universe":[{ "instrumentType": "Option", "instrumentDefinition": { ...
_____no_output_____
Apache-2.0
Vol Surfaces Webinar.ipynb
Refinitiv-API-Samples/Article.RDPLibrary.Python.VolatilitySurfaces_Curves
Creating a Pipeline using a Corpus ClassWhen working with a corpus of texts it can quickly become confusing to keep track of which step in an NLP pipeline you are on. Say you want to run a Frequency Distribution, did you remember to tokenize the text? To pull out the stopwords? While this is simple enough if you are w...
import os import nltk import string class Corpus(object): # rather than enter the data bit by bit, we create a constructor that takes in the data at one time # all the attributes we want the class to have follow the __init__ syntax def __init__(self, corpus_dir): # all the attributes we want the c...
As mentioned above, this output presents as though it is being run from the command line.
CC-BY-4.0
corpus.ipynb
walshbr/humanists-nlp-cookbook
The payoff of organzing your project within classes is that you can run them as a module from the interpreter or as a Python file from the terminal. For the remainder of this section, we have inserted the above code into a file called file class_practice.py. The following code blocks show how you might go about importi...
# import the script as a module--file name without the extension import class_practice # store the path to the corpus directory corpus_dir = "corpus/sonnets/" # create a new corpus using our class template this_corpus = class_practice.Corpus(corpus_dir) # now we can access elements of our corpus by accessing this_co...
corpus/sonnets/ ['corpus/sonnets/sonnet_two.txt', 'corpus/sonnets/sonnet_five.txt', 'corpus/sonnets/sonnet_four.txt', 'corpus/sonnets/sonnets_three.txt', 'corpus/sonnets/sonnet_one.txt']
CC-BY-4.0
corpus.ipynb
walshbr/humanists-nlp-cookbook
Now that our corpus is in the interpreter, we can confirm that it contains many texts:
this_corpus.texts
_____no_output_____
CC-BY-4.0
corpus.ipynb
walshbr/humanists-nlp-cookbook
That is a little confusing. As a humanist, we might expect to see the titles of the text or something similar. But we haven't told our class anything like that. Instead, our corpus points to particular texts, represented by their locations in our computer's memory. But, since this is just a list, we can pull out indivi...
first_text = this_corpus.texts[0] # from here, any of our text level attributes will be available to us: print(first_text.filename) print(first_text.raw_text)
corpus/sonnets/sonnet_two.txt When forty winters shall besiege thy brow, And dig deep trenches in thy beauty's field, Thy youth's proud livery so gazed on now, Will be a totter'd weed of small worth held: Then being asked, where all thy beauty lies, Where all the treasure of thy lusty days; To say, within thine own dee...
CC-BY-4.0
corpus.ipynb
walshbr/humanists-nlp-cookbook
We could loop over our corpus to pull out information from each text:
for text in this_corpus.texts: print(text.filename) # get the first few characters from each line for text in this_corpus.texts: print(text.raw_text[0:40])
corpus/sonnets/sonnet_two.txt corpus/sonnets/sonnet_five.txt corpus/sonnets/sonnet_four.txt corpus/sonnets/sonnets_three.txt corpus/sonnets/sonnet_one.txt When forty winters shall besiege thy bro Those hours, that with gentle work did f Unthrifty loveliness, why dost thou spen Look in thy glass and tell the face thou F...
CC-BY-4.0
corpus.ipynb
walshbr/humanists-nlp-cookbook
Depending on how complex you've made your Text class, you can get to some interesting analysis right away. Here, we take advantage of the fact that we use NLTK's more robust Text class to look at the top words in each text. Even though both this small example and NLTK both have created classes named "Text", they contai...
for text in this_corpus.texts: print(text.nltk_text.vocab().most_common(10)) print('=======')
[('thy', 7), ('beauty', 4), ("'s", 3), ('thou', 3), ('shall', 2), ('and', 2), ('deep', 2), ("'d", 2), ('thine', 2), ('praise', 2)] ======= [('beauty', 3), ('every', 2), ('doth', 2), ('summer', 2), ('winter', 2), ("'s", 2), ('those', 1), ('hours', 1), ('gentle', 1), ('work', 1)] ======= [('thy', 6), ('thou', 5), ('dost'...
CC-BY-4.0
corpus.ipynb
walshbr/humanists-nlp-cookbook
Theoretically, the process is agnostic of what texts are actually in the corpus folder. So you could use this as a starting point for analysis without having to reinvent the wheel each time. We could, for example, create a new corpus from a different set of texts and quickly grab the most common words from those texts....
corpus_dir = "corpus/woolf/" new_corpus = class_practice.Corpus(corpus_dir) print(new_corpus.texts) for text in new_corpus.texts: print(text.filename) print(text.nltk_text.vocab().most_common(10)) print('======')
[<class_practice.Text object at 0x10d2e0310>, <class_practice.Text object at 0x12a02f910>, <class_practice.Text object at 0x12a2815b0>] corpus/woolf/1922_jacobs_room.txt [('--', 546), ('said', 425), ("'s", 411), ('jacob', 390), ('the', 360), ('one', 291), ('i', 236), ('mrs.', 225), ('like', 165), ('but', 153)] ====== c...
CC-BY-4.0
corpus.ipynb
walshbr/humanists-nlp-cookbook
We don't have to rework all of the basic details of what a corpus looks like. And, looking at these results, we might very quickly notice some changes we want to make to our pipeline! Thanks to how we've organized things, this should not be too challenging. However, this reproducibility is also a potential challenge. E...
import importlib importlib.reload(class_practice) #re-instantiate the corpus or text this_corpus = class_practice.Corpus(corpus_dir)
_____no_output_____
CC-BY-4.0
corpus.ipynb
walshbr/humanists-nlp-cookbook
Outlier DetectionThe goal is to remove outlier cells from the ```hpacellseg``` output.Outliers on the training set:* (Shape) Cells where the minimum bounding rectangle has a (h,w) ratio outside of 95% of the data range.* (Shape) Cells that are very large compared to the image size or the other cells in the image. (?)*...
import os import importlib import numpy import pandas import sklearn import matplotlib.pyplot as plt import cv2 import skimage import pycocotools import json import ast import src.utils importlib.reload(src.utils) from tqdm import tqdm import multiprocessing, logging from joblib import Parallel, delayed train = pa...
_____no_output_____
BSD-3-Clause
notebooks/Outlier-Detection.ipynb
mpff/hpa-single-cell-classification
Functions for parsing precomputed and compressed train and test dataset rles.
def get_rle_from_df(row): string = row.RLEmask h = row.ImageHeight w = row.ImageWidth rle = src.utils.decode_b64_string(string, h, w) return rle def get_mask_from_rle(rle): mask = pycocotools._mask.decode([rle])[:,:,0] return mask rles = train.apply(get_rle_from_df, axis=1) rles.head() ...
_____no_output_____
BSD-3-Clause
notebooks/Outlier-Detection.ipynb
mpff/hpa-single-cell-classification
Generate Outlier MetricsCalculate the **bounding box**.
def get_bbox_from_rle(rle): """x,y = bottom left!""" bbox = pycocotools._mask.toBbox([encoded_mask])[0] x, y, w, h = (int(l) for l in bbox) return x, y, w, h
_____no_output_____
BSD-3-Clause
notebooks/Outlier-Detection.ipynb
mpff/hpa-single-cell-classification
Calculate the **minimum bounding rectangle** (rotated bounding box).
def get_mbr_from_mask(mask): return x, y, l1, l2, phi def get_hw_from_mbr(mbr): return h, w if not n_workers: n_workers=num_cores processed_list = Parallel(n_jobs=int(n_workers))( delayed(segment_image)(i, segmentator, images_frame, test) for i in tqdm(images) ) touch = train.touches.apply(ast.liter...
_____no_output_____
BSD-3-Clause
notebooks/Outlier-Detection.ipynb
mpff/hpa-single-cell-classification
Policy Iteration
#Inplace game = GridWorld(4, (2,1), inplace=True, policy_iteration = True) print(game.play(epochs=50, threshold=0.00000000000001)) game = GridWorld(4, (2,1), inplace=False, policy_iteration = True) print(game.play(epochs=50, threshold=0.00000000000001))
Initial V [0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.] Initial Policy [3 2 1 1] [1 2 2 2] [3 3 3 3] [3 3 1 1] Final Policy: [1 3 0 0] [1 3 0 0] [1 0 0 0] [1 2 0 0] Final Value Function: [-0.25578487 -0.23139462 -0.25578487 -0.25639462] [-0.23139462 0.74421513 -0.23139462 -0.25578487] [ 0.74421513 -0.2313...
Apache-2.0
RL using Dynamic Programming.ipynb
SanketAgrawal/ReinforcementLearning
Value Iteration
#Inplace game = GridWorld(4, (2,1), inplace=True, policy_iteration = False) print(game.play(epochs=50, threshold=0.00000000000001)) game = GridWorld(4, (2,1), inplace=False, policy_iteration = False) print(game.play(epochs=50, threshold=0.00000000000001))
Initial V [0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.] Initial Policy [2 2 2 3] [1 2 3 2] [3 1 2 2] [3 2 2 3] Final Policy: [1 3 0 0] [1 3 0 0] [1 0 0 0] [1 2 0 0] Final Value Function: [-0.25578487 -0.23139462 -0.25578487 -0.25639462] [-0.23139462 0.74421513 -0.23139462 -0.25578487] [ 0.74421513 -0.2313...
Apache-2.0
RL using Dynamic Programming.ipynb
SanketAgrawal/ReinforcementLearning
Yandex geocoding APIThis notebook works with [Yandex Geocoding API](https://tech.yandex.ru/maps/geocoder/doc/desc/concepts/about-docpage/), you have to get an API key to replicate the process.Free limit for HTTP GET request is now only 1000 addresses per day. [Open data about housing](https://www.reformagkh.ru/opendat...
import pandas as pd import requests import geopandas as gpd from pyproj import CRS from shapely import wkt import matplotlib.pyplot as plt import contextily as ctx import warnings warnings.filterwarnings("ignore") # reading api keys api_keys = pd.read_excel('../api_keys.xlsx') api_keys.set_index('key_name', inplace=...
_____no_output_____
MIT
geocoding_yandex_api.ipynb
skaryaeva/urban_studies_notebooks
Setup directory variables
print(os.environ['PIPELINEDIR']) if not os.path.exists(os.environ['PIPELINEDIR']): os.makedirs(os.environ['PIPELINEDIR']) figdir = os.path.join(os.environ['OUTPUTDIR'], 'figs') print(figdir) if not os.path.exists(figdir): os.makedirs(figdir) phenos = ['Overall_Psychopathology','Psychosis_Positive','Psychosis_NegativeDi...
_____no_output_____
MIT
1_code/10_results_model_performance.ipynb
lindenmp/normative_neurodev_cs_t1
Setup plots
if not os.path.exists(figdir): os.makedirs(figdir) os.chdir(figdir) sns.set(style='white', context = 'paper', font_scale = 0.8) cmap = my_get_cmap('psych_phenos')
_____no_output_____
MIT
1_code/10_results_model_performance.ipynb
lindenmp/normative_neurodev_cs_t1
Load data
def load_data(indir, phenos, alg, score, metric): accuracy_mean = np.zeros((100, len(phenos))) accuracy_std = np.zeros((100, len(phenos))) y_pred_var = np.zeros((100, len(phenos))) p_vals = pd.DataFrame(columns = phenos) sig_points = pd.DataFrame(columns = phenos) for p, pheno in enumerate(phe...
/Users/lindenmp/Google-Drive-Penn/work/research_projects/normative_neurodev_cs_t1/2_pipeline/8_prediction_fixedpcs/out/t1Exclude_schaefer_400_ /Users/lindenmp/Google-Drive-Penn/work/research_projects/normative_neurodev_cs_t1/2_pipeline/8_prediction_fixedpcs/out/t1Exclude_schaefer_400_predict_symptoms_rcv_nuis_ageAtScan...
MIT
1_code/10_results_model_performance.ipynb
lindenmp/normative_neurodev_cs_t1
Load whole-brain results
accuracy_mean, accuracy_std, _, p_vals, sig_points = load_data(modeldir, phenos, alg, score, metric) p_vals = get_fdr_p_df(p_vals) p_vals[p_vals < 0.05] accuracy_mean_z, accuracy_std_z, _, p_vals_z, sig_points_z = load_data(modeldir+'_z', phenos, alg, score, metric) p_vals_z = get_fdr_p_df(p_vals_z) p_vals_z[p_vals_z <...
_____no_output_____
MIT
1_code/10_results_model_performance.ipynb
lindenmp/normative_neurodev_cs_t1
Plot
stats = pd.DataFrame(index = phenos, columns = ['meanx', 'meany', 'test_stat', 'pval']) for i, pheno in enumerate(phenos): df = pd.DataFrame(columns = ['model','pheno']) for model in ['wb','wbz']: df_tmp = pd.DataFrame(columns = df.columns) if model == 'wb': df_tmp.loc[:,'score'] =...
_____no_output_____
MIT
1_code/10_results_model_performance.ipynb
lindenmp/normative_neurodev_cs_t1
Code for comparison tests
final_stations[final_stations.ZIP=='10019'] final_stations[final_stations.STATION=='5 AV'] final_stations[final_stations.STATION.str.contains('5 AV')] final_stations.dropna(subset=['NAME'])[final_stations.dropna(subset=['NAME']).NAME.str.contains('2 AV')] station_test[station_test.STATION.str.contains('5 AV')] geo_test...
_____no_output_____
SGI-B-2.0
fuzzywuzzy match geo and turnstile.ipynb
Lwaggaman/EDA_Project
Advanced Lane Finding ProjectThe goals / steps of this project are the following:* Compute the camera calibration matrix and distortion coefficients given a set of chessboard images.* Apply a distortion correction to raw images.* Use color transforms, gradients, etc., to create a thresholded binary image.* Apply a per...
import numpy as np import cv2 import glob import matplotlib.pyplot as plt %matplotlib qt # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0) objp = np.zeros((6*9,3), np.float32) objp[:,:2] = np.mgrid[0:9,0:6].T.reshape(-1,2) # Arrays to store object points and image points from all the images. objpoi...
_____no_output_____
MIT
examples/.ipynb_checkpoints/example-checkpoint.ipynb
sLakshmiprasad/advanced-lane-lines
Calibrate the camera using the objpoints and imgpoints
%matplotlib inline img = cv2.imread('../test_images/test2.jpg') img_size = (img.shape[1], img.shape[0]) ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, img_size,None,None) dst = cv2.undistort(img, mtx, dist, None, mtx) f, (ax1, ax2) = plt.subplots(1, 2, figsize=(20,10)) ax1.imshow(img) ax1.se...
Camera calibration matrix [[1.15777942e+03 0.00000000e+00 6.67111050e+02] [0.00000000e+00 1.15282305e+03 3.86129068e+02] [0.00000000e+00 0.00000000e+00 1.00000000e+00]] Distortion coefficient [[-0.24688832 -0.02372817 -0.00109843 0.00035105 -0.00259133]]
MIT
examples/.ipynb_checkpoints/example-checkpoint.ipynb
sLakshmiprasad/advanced-lane-lines
■ 딥러닝 복습 1장. numpy 2장. 퍼셉트론 3장. 3층 신경망 구현 4장. 2층 신경망 구현(수치미분) 5장. 2층 신경망 구현(오차역전파) tensorflow 1.x -> tensorflow 2.x -------------------------------------------------------------------- 6장. 신경망 학습시키는 기술들 7장. CNN을 이용한 신경망 구현 ----------------------------------------------------------------...
W1 = tf.get_variable(name='W1', shape=[784,50], initializer = tf.contrib.layers.xavier_initializer())
_____no_output_____
MIT
.ipynb_checkpoints/(200818) 2.-checkpoint.ipynb
Adrian123K/tensor
2. He 가중치 초기값 구성$$ \sqrt{{{2} \over {n}}} \cdot \rm{np.random.randn(r,c)} $$
W1 = tf.get_variable(name="W1", shape=[784,50], initializer = tf.contrib.layers.variance_scaling_initializer())
_____no_output_____
MIT
.ipynb_checkpoints/(200818) 2.-checkpoint.ipynb
Adrian123K/tensor
예제1. 어제 마지막 문제로 만들었던 텐서 플로우로 구현한 신경망 코드에 가중치 초기값을 xavier로 해서 구현하시오
import tensorflow as tf import numpy as np import warnings import os from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot = True) os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' warnings.filterwarnings('ignore') tf.reset_default_graph() # 은닉1층 x = tf.placeholder...
WARNING:tensorflow:From <ipython-input-9-a5d4a56c599c>:6: read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version. Instructions for updating: Please use alternatives such as official/mnist/dataset.py from tensorflow/models. WARNING:tensorflow:From...
MIT
.ipynb_checkpoints/(200818) 2.-checkpoint.ipynb
Adrian123K/tensor
※ 문제137. 이번에는 가중치 초기값을 He로 해서 수행하시오
import tensorflow as tf import numpy as np import warnings import os from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot = True) os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' warnings.filterwarnings('ignore') tf.reset_default_graph() # 텐서 그래프 초기화 하는 코드 # 은닉1층...
Extracting MNIST_data/train-images-idx3-ubyte.gz Extracting MNIST_data/train-labels-idx1-ubyte.gz Extracting MNIST_data/t10k-images-idx3-ubyte.gz Extracting MNIST_data/t10k-labels-idx1-ubyte.gz {1} 에폭 훈련데이터 정확도 : 0.99 테스트 데이터 정확도: 0.96 {2} 에폭 훈련데이터 정확도 : 1.0 테스트 데이터 정확도: 1.0 {3} 에폭 훈련데이터 정확도 : 1.0 테스트 데이터 정확도:...
MIT
.ipynb_checkpoints/(200818) 2.-checkpoint.ipynb
Adrian123K/tensor
※ 문제138. 위의 2층 신경망을 3층 신경망으로 변경하시오 기존층 : 입력층 -------> 은닉1층 ------> 출력층 784 100 10 변경후 : 입력층 -------> 은닉1층 ------> 은닉2층 -------> 출력층 784 100 50 10
import tensorflow as tf import numpy as np import warnings import os from tensorflow.examples.tutorials.mnist import input_data os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' warnings.filterwarnings('ignore') mnist = input_data.read_data_sets("MNIST_data/", one_hot = True) tf.reset_default_graph() # 텐서 그래프 초기화 하는 코드 # 은닉1...
Extracting MNIST_data/train-images-idx3-ubyte.gz Extracting MNIST_data/train-labels-idx1-ubyte.gz Extracting MNIST_data/t10k-images-idx3-ubyte.gz Extracting MNIST_data/t10k-labels-idx1-ubyte.gz {1} 에폭 훈련데이터 정확도 : 0.91 테스트 데이터 정확도: 0.95 {2} 에폭 훈련데이터 정확도 : 0.98 테스트 데이터 정확도: 0.97 {3} 에폭 훈련데이터 정확도 : 0.97 테스트 데이터 정...
MIT
.ipynb_checkpoints/(200818) 2.-checkpoint.ipynb
Adrian123K/tensor
■ 텐서 플로우로 배치 정규화 구현하는 방법 배치 정규화 - 신경망 학습시 가중치 값의 데이터가 골고루 분산될 수 있도록 강제화 하는 장치 층이 깊어져도 가중치의 정규분포를 계속 유지할 수 있도록 층마다 강제화 하는 장치 ```pythonbatch_z1 = tf.contrib.layers.batch_norm(z1, True)``` Affine1 ------> 배치 정규화 ------> ReLU (z1) 예제1. 지금까지 완성한 신경망에 배치 정규화를 은닉 1층에 구현하시오
import tensorflow as tf import numpy as np import warnings import os from tensorflow.examples.tutorials.mnist import input_data os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' warnings.filterwarnings('ignore') mnist = input_data.read_data_sets("MNIST_data/", one_hot = True) tf.reset_default_graph() # 텐서 그래프 초기화 하는 코드 # 은닉1...
Extracting MNIST_data/train-images-idx3-ubyte.gz Extracting MNIST_data/train-labels-idx1-ubyte.gz Extracting MNIST_data/t10k-images-idx3-ubyte.gz Extracting MNIST_data/t10k-labels-idx1-ubyte.gz 1 에폭 훈련데이터 정확도 : 0.99 테스트 데이터 정확도: 0.97 2 에폭 훈련데이터 정확도 : 1.0 테스트 데이터 정확도: 0.98 3 에폭 훈련데이터 정확도 : 0.98 테스트 데이터 정확도: 0.9...
MIT
.ipynb_checkpoints/(200818) 2.-checkpoint.ipynb
Adrian123K/tensor
※ 문제139. 은닉 2층에도 배치 정규화를 적용하시오
import tensorflow as tf import numpy as np import warnings import os from tensorflow.examples.tutorials.mnist import input_data os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' warnings.filterwarnings('ignore') mnist = input_data.read_data_sets("MNIST_data/", one_hot = True) tf.reset_default_graph() # 텐서 그래프 초기화 하는 코드 # 은닉1...
_____no_output_____
MIT
.ipynb_checkpoints/(200818) 2.-checkpoint.ipynb
Adrian123K/tensor
■ 텐서 플로우로 dropout 적용하는 방법 드롭아웃(dropout) 사용해야하는 이유 - 오버피팅 방지 구현 예시```python keep_prob = tf.placeholder('float') 0.8 -> 전체 뉴런 중 80%만 남기고 20% 랜덤으로 삭제 1.0 -> 모든 뉴런을 그대로 남겨둔다y3_drop = tf.nn.dropout(y3, keep_prob)``` 훈련할 때는 뉴런을 삭제하고 테스트 할 때는 뉴런을 삭제하지 않으려고 keep_prob로 남겨둠
import tensorflow as tf import numpy as np import warnings import os from tensorflow.examples.tutorials.mnist import input_data os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' warnings.filterwarnings('ignore') mnist = input_data.read_data_sets("MNIST_data/", one_hot = True) tf.reset_default_graph() # 텐서 그래프 초기화 하는 코드 # 입력...
Extracting MNIST_data/train-images-idx3-ubyte.gz Extracting MNIST_data/train-labels-idx1-ubyte.gz Extracting MNIST_data/t10k-images-idx3-ubyte.gz Extracting MNIST_data/t10k-labels-idx1-ubyte.gz WARNING:tensorflow:From <ipython-input-15-159da87ef0a0>:38: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob...
MIT
.ipynb_checkpoints/(200818) 2.-checkpoint.ipynb
Adrian123K/tensor
■ 훈련과 테스트 데이터의 정확도가 시각화 될 수 있도록 코드를 추가
import tensorflow as tf import numpy as np import warnings import os from tensorflow.examples.tutorials.mnist import input_data os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' warnings.filterwarnings('ignore') mnist = input_data.read_data_sets("MNIST_data/", one_hot = True) tf.reset_default_graph() # 텐서 그래프 초기화 하는 코드 # 입력...
Extracting MNIST_data/train-images-idx3-ubyte.gz Extracting MNIST_data/train-labels-idx1-ubyte.gz Extracting MNIST_data/t10k-images-idx3-ubyte.gz Extracting MNIST_data/t10k-labels-idx1-ubyte.gz 훈련 1에폭 정확도 : 0.65 테스트 1에폭 정확도 : 0.42 ----------------------------------------------- 훈련 2에폭 정확도 : 0.99 테스트 2에폭 정확도 : 0.99 ----...
MIT
.ipynb_checkpoints/(200818) 2.-checkpoint.ipynb
Adrian123K/tensor
※ 문제140. 위의 CNN 신경망을 아래와 같이 구현하시오 변경 전 : 입력층 ----> Conv1 ----> pooling ----> FC1층 ----> FC2층 ----> 출력층 784 32 100 50 10 변경 후 : 입력층 ----> Conv1 ----> pooling ----> Conv2 ----> pooling ----> FC1층 ----> FC2층 ----> 출력층 784 32 ...
import tensorflow as tf import numpy as np import warnings import os from tensorflow.examples.tutorials.mnist import input_data os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' warnings.filterwarnings('ignore') mnist = input_data.read_data_sets("MNIST_data/", one_hot = True) tf.reset_default_graph() # 텐서 그래프 초기화 하는 코드 # 입력...
Extracting MNIST_data/train-images-idx3-ubyte.gz Extracting MNIST_data/train-labels-idx1-ubyte.gz Extracting MNIST_data/t10k-images-idx3-ubyte.gz Extracting MNIST_data/t10k-labels-idx1-ubyte.gz 훈련 1에폭 정확도 : 0.5 테스트 1에폭 정확도 : 0.21 ----------------------------------------------- 훈련 2에폭 정확도 : 1.0 테스트 2에폭 정확도 : 0.98 ------...
MIT
.ipynb_checkpoints/(200818) 2.-checkpoint.ipynb
Adrian123K/tensor
■ cifar10 데이터를 이용한 신경망 구성 cifar10은 총 6만 개의 데이터 셋으로 이루어져 있으며 그 중 5만 개가 훈련데이터, 1만 개가 테스트 데이터 class는 비행기부터 트럭까지 총 10개 1. 비행기 2. 자동차 3. 새 4. 고양이 5. 사슴 6. 강아지 7. 개구리 8. 말 9. 배 10. 트럭 ■ 신경망 구현 홈페이지를 만들려면 필요한 코드 1. 사진 데이터를 신경망에 로드하는 코드들 2. 사진 이...
import os def image_load(path): file_list = os.listdir(path) return file_list train_image = 'd:/tensor/cifar10/train100/' print(image_load(train_image))
['1.png', '10.png', '100.png', '11.png', '12.png', '13.png', '14.png', '15.png', '16.png', '17.png', '18.png', '19.png', '2.png', '20.png', '21.png', '22.png', '23.png', '24.png', '25.png', '26.png', '27.png', '28.png', '29.png', '3.png', '30.png', '31.png', '32.png', '33.png', '34.png', '35.png', '36.png', '37.png', '...
MIT
.ipynb_checkpoints/(200818) 2.-checkpoint.ipynb
Adrian123K/tensor
예제2. 위의 결과에서 .png는 빼고 숫자만 출력되게 하시오
import os import re def image_load(path): file_list = os.listdir(path) file_name = [] for i in file_list: name = re.sub('[^0-9]','',i) file_name.append(name) return file_name train_image = 'd:/tensor/cifar10/train100/' print(image_load(train_image))
['1', '10', '100', '11', '12', '13', '14', '15', '16', '17', '18', '19', '2', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '3', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '4', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '5', '50', '51', '52', '53', '54', '55', '56', '57',...
MIT
.ipynb_checkpoints/(200818) 2.-checkpoint.ipynb
Adrian123K/tensor
예제3. 위의 결과를 정렬해서 출력하시오
import os import re def image_load(path): file_list = os.listdir(path) file_name = [] for i in file_list: file_name.append(int(re.sub('[^0-9]', '', i))) file_name.sort() return file_name train_image = 'd:/tensor/cifar10/train100/' print(image_load(train_image))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, ...
MIT
.ipynb_checkpoints/(200818) 2.-checkpoint.ipynb
Adrian123K/tensor
예제4. 위의 출력된 결과에서 다시 .png를 붙여서 아래와 같이 출력되게 하시오
import os import re def image_load(path): file_list = os.listdir(path) file_name = [] for i in file_list: file_name.append(int(re.sub('[^0-9]', '', i))) file_name.sort() file_res = [] for i in file_name: file_res.append(str(i)+'.png') return file_res train_image = 'd:...
['1.png', '2.png', '3.png', '4.png', '5.png', '6.png', '7.png', '8.png', '9.png', '10.png', '11.png', '12.png', '13.png', '14.png', '15.png', '16.png', '17.png', '18.png', '19.png', '20.png', '21.png', '22.png', '23.png', '24.png', '25.png', '26.png', '27.png', '28.png', '29.png', '30.png', '31.png', '32.png', '33.png'...
MIT
.ipynb_checkpoints/(200818) 2.-checkpoint.ipynb
Adrian123K/tensor
예제5. 이미지 이름 앞에 절대 경로가 아래처럼 붙게 하시오 ['d:/tensor/cifar10/train100/1.png','d:/tensor/cifar10/train100/2.png',...,'d:/tensor/cifar10/train100/100.png']
import os import re def image_load(path): file_list = os.listdir(path) file_name = [] for i in file_list: file_name.append(int(re.sub('[^0-9]', '', i))) file_name.sort() file_res = [] for i in file_name: file_res.append(path+str(i)+'.png') return file_res train_image ...
['d:/tensor/cifar10/train100/1.png', 'd:/tensor/cifar10/train100/2.png', 'd:/tensor/cifar10/train100/3.png', 'd:/tensor/cifar10/train100/4.png', 'd:/tensor/cifar10/train100/5.png', 'd:/tensor/cifar10/train100/6.png', 'd:/tensor/cifar10/train100/7.png', 'd:/tensor/cifar10/train100/8.png', 'd:/tensor/cifar10/train100/9.p...
MIT
.ipynb_checkpoints/(200818) 2.-checkpoint.ipynb
Adrian123K/tensor
예제6. cv2.imread 함수를 이용해서 이미지를 숫자로 변경하시오
import os import re import numpy as np import cv2 def image_load(path): file_list = os.listdir(path) file_name = [] for i in file_list: file_name.append(int(re.sub('[^0-9]', '', i))) file_name.sort() file_res = [] for j in file_name: file_res.append(path+str(j)+'.png') ...
[[[[ 63 62 59] [ 45 46 43] [ 43 48 50] ... [108 132 158] [102 125 152] [103 124 148]] [[ 20 20 16] [ 0 0 0] [ 0 8 18] ... [ 55 88 123] [ 50 83 119] [ 57 87 122]] [[ 21 24 25] [ 0 7 16] [ 8 27 49] ... [ 50 84 118] [ 50 84 120] [ 4...
MIT
.ipynb_checkpoints/(200818) 2.-checkpoint.ipynb
Adrian123K/tensor
■ 데이터를 신경망에 로드하기 위해 필요한 총 4개의 함수 1. image_load : 데이터를 숫자로 변환하는 함수 2. label_load : 정답 숫자를 one hot encoding하는 함수 3. next_batch : 배치 단위로 데이터 가져오는 함수 4. shuffle_batch : 이미지 데이터를 shuffle 하는 함수 예제8. train_label.csv의 숫자를 출력하는 함수를 만드시오
train_label = 'd:/tensor/cifar10/train_label.csv' import csv def label_load(path): file = open(path) label_data = csv.reader(file) label_list = [] for i in label_data: label_list.append(i) return label_list print(label_load(train_label))
50000
MIT
.ipynb_checkpoints/(200818) 2.-checkpoint.ipynb
Adrian123K/tensor
예제9. 위의 결과가 문자가 아니라 숫자로 출력되게 하시오
train_label = 'd:/tensor/cifar10/train_label.csv' import csv import numpy as np def label_load(path): file = open(path) label_data = csv.reader(file) label_list = [] for i in label_data: label_list.append(i) label = np.array(label_list).astype(int) return lab...
[[6] [9] [9] ... [9] [1] [1]]
MIT
.ipynb_checkpoints/(200818) 2.-checkpoint.ipynb
Adrian123K/tensor
예제10. 아래의 결과를 출력하시오 [0 0 0 1 0 0 0 0 0 0]
import numpy as np print(np.eye(10)[4])
[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
MIT
.ipynb_checkpoints/(200818) 2.-checkpoint.ipynb
Adrian123K/tensor
예제11. 위의 np.eye를 가지고 예제 9에서 출력하고 있는 숫자들이 아래와 같이 one hot encoding된 숫자로 출력되게 하시오 [0 0 0 1 0 0 0 0 0 0] [0 0 1 0 0 0 0 0 0 0] [1 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 1 0 0] ...
train_label = 'd:/tensor/cifar10/train_label.csv' import csv import numpy as np def label_load(path): file = open(path) label_data = csv.reader(file) label_list = [] for i in label_data: label_list.append(i) label = np.eye(10)[np.array(label_list).astype(int)] re...
[[[0. 0. 0. ... 0. 0. 0.]] [[0. 0. 0. ... 0. 0. 1.]] [[0. 0. 0. ... 0. 0. 1.]] ... [[0. 0. 0. ... 0. 0. 1.]] [[0. 1. 0. ... 0. 0. 0.]] [[0. 1. 0. ... 0. 0. 0.]]]
MIT
.ipynb_checkpoints/(200818) 2.-checkpoint.ipynb
Adrian123K/tensor
예제12. 위의 결과는 3차원인데 신경망에서 라벨을 사용하려면 2차원이어야 하므로 차원을 2차원으로 축소시켜서 출력하시오
train_label = 'd:/tensor/cifar10/train_label.csv' import csv import numpy as np def label_load(path): file = open(path) label_data = csv.reader(file) label_list = [] for i in label_data: label_list.append(i) label = np.eye(10)[np.array(label_list).astype(int)].reshape(-1,...
[[0. 0. 0. ... 0. 0. 0.] [0. 0. 0. ... 0. 0. 1.] [0. 0. 0. ... 0. 0. 1.] ... [0. 0. 0. ... 0. 0. 1.] [0. 1. 0. ... 0. 0. 0.] [0. 1. 0. ... 0. 0. 0.]]
MIT
.ipynb_checkpoints/(200818) 2.-checkpoint.ipynb
Adrian123K/tensor
예제13. 지금까지 만든 두 개의 함수 image_load와 label_load를 loader2.py라는 파이썬 코드에 저장하고 아래와 같이 loader2.py를 import한 후에 cifar10 전체 데이터를 로드하는 코드를 구현하시오
import loader2 train_image='D:/tensor/cifar10/train/' train_label = 'D:/tensor/cifar10/train_label.csv' test_image='D:/tensor/cifar10/test/' test_label = 'D:/tensor/cifar10/test_label.csv' trainX = loader2.image_load(train_image) trainY = loader2.label_load(train_label) testX = loader2.image_load(test_image) testY =...
(50000, 32, 32, 3) (50000, 10) (10000, 32, 32, 3) (10000, 10)
MIT
.ipynb_checkpoints/(200818) 2.-checkpoint.ipynb
Adrian123K/tensor
예제14. 신경망에 100장씩 데이터를 로드할 수 있도록 아래와 같이 next_batch 함수를 생성하시오
import loader2 def next_batch(data1, data2, init, final): return data1[init:final], data2[init:final] test_image = 'D:/tensor/cifar10/test/' test_label = 'D:/tensor/cifar10/test_label.csv' testX = loader2.image_load(test_image) testY = loader2.label_load(test_label) print(next_batch(testX, testY, 0 ,100))
(array([[[[ 49, 112, 158], [ 47, 111, 159], [ 51, 116, 165], ..., [ 36, 95, 137], [ 36, 91, 126], [ 33, 85, 116]], [[ 51, 112, 152], [ 40, 110, 151], [ 45, 114, 159], ..., [ 31, 95, 136], [ 32, 91, 125], ...
MIT
.ipynb_checkpoints/(200818) 2.-checkpoint.ipynb
Adrian123K/tensor
예제15. 아래와 같이 shuffle_batch 함수를 만들고 loader2.py에 추가시키시오
def shuffle_batch(data_list, label): x = np.arange(len(data_list)) np.random.shuffle(x) data_list2 = data_list[x] label2 = label[x] return data_list2, label2 import loader2 test_image = 'D:/tensor/cifar10/test/' test_label = 'D:/tensor/cifar10/test_label.csv' testX = loader2.image_load(t...
_____no_output_____
MIT
.ipynb_checkpoints/(200818) 2.-checkpoint.ipynb
Adrian123K/tensor
※ 문제141. (오늘의 마지막 문제) 4개의 함수를 모두 loader2.py에 넣고 내일 옥스포드에서 설계한 vgg 신경망에 넣기 위해 아래와 같이 실행되게 하시오```pythonimport loader2train_image='D:/tensor/cifar10/train/'train_label = 'D:/tensor/cifar10/train_label.csv'test_image='D:/tensor/cifar10/test/'test_label = 'D:/tensor/cifar10/test_label.csv'trainX = loader2.image_load(train_...
import loader2 train_image='D:/tensor/cifar10/train/' train_label = 'D:/tensor/cifar10/train_label.csv' test_image='D:/tensor/cifar10/test/' test_label = 'D:/tensor/cifar10/test_label.csv' trainX = loader2.image_load(train_image) trainY = loader2.label_load(train_label) testX = loader2.image_load(test_image) testY =...
_____no_output_____
MIT
.ipynb_checkpoints/(200818) 2.-checkpoint.ipynb
Adrian123K/tensor
If you want to average results for multiple seeds, LOG_DIRS must contain subfolders in the following format: ```-0```, ```-1```, ```-0```, ```-1```. Where names correspond to experiments you want to compare separated with random seeds by dash.
LOG_DIRS = 'logs/reacher/' # Uncomment below to see the effect of the timit limits flag # LOG_DIRS = 'time_limit_logs/reacher' results = pu.load_results(LOG_DIRS) fig = pu.plot_results(results, average_group=True, split_fn=lambda _: '', shaded_std=False)
_____no_output_____
MIT
write_and_test/visualize.ipynb
liuandrew/training-rl-algo
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) BUZZ_PIN = 18 GPIO.setup(BUZZ_PIN, GPIO.OUT) GPIO.output(BUZZ_PIN,False) def hold(j): for k in range(1,j): pass def fire(): for j in range(1,1100): GPIO.output(BUZZ_PIN,True) hold(j) GPIO.output(BUZZ_PIN,False) hold(j) try: ...
_____no_output_____
CC0-1.0
notebooks/nl-be/Output - Buzzer (Piezo).ipynb
RaspberryJamBe/IPythonNotebooks
Gaussian Distribution (Normal or Bell Curve) Think of a Jupyter Notebook file as a Python script, but with comments given the seriousness they deserve, meaning inserted Youtubes if necessary. We also adopt a more conversational style with the reader, and with Python, pausing frequently to take stock, because we're te...
import numpy as np import scipy.stats as st import matplotlib.pyplot as plt import math
_____no_output_____
MIT
BellCurve.ipynb
4dsolutions/ONLC_XPYS
You'll be glad to have np.linspace as a friend, as so often you know exactly what the upper and lower bounds, of a domain, might be. You'll be computing a range. Do you remember these terms from high school? A domain is like a pile of cannon balls that we feed to our cannon, which them fires them, testing our knowle...
domain = np.linspace(-5, 5, 100)
_____no_output_____
MIT
BellCurve.ipynb
4dsolutions/ONLC_XPYS
I know mu sounds like "mew", the sound a kitten makes, and that's sometimes insisted upon by sticklers, for when we have a continuous function, versus one that's discrete. Statisticians make a big deal about the difference between digital and analog, where the former is seen as a "sampling" of the latter. Complete da...
mu = 0 # might be x-bar if discrete sigma = 1 # standard deviation, more below
_____no_output_____
MIT
BellCurve.ipynb
4dsolutions/ONLC_XPYS
What we have here (below) is a typical Python numeric function, although it does get its pi from numpy instead of math. That won't matter. The sigma and mu in this function are globals and set above. Some LaTex would be in order here, I realize. Let me scavange the internet for something appropriate...$pdf(x,\mu,\s...
from IPython.display import display, Latex ltx = '$ pdf(x,\\mu,\\sigma) = \\frac{1}{ \\sigma' + \ '\\sqrt{2 \\pi}} e^{\\left(-\\frac{{\\left(\\mu - ' + \ 'x\\right)}^{2}}{2 \\, \\sigma^{2}}\\right)} $' display(Latex(ltx))
_____no_output_____
MIT
BellCurve.ipynb
4dsolutions/ONLC_XPYS
I'm really tempted to try out [PrettyPy](https://github.com/charliekawczynski/prettyPy).
def g(x): return (1/(sigma * math.sqrt(2 * np.pi))) * math.exp(-0.5 * ((mu - x)/sigma)**2)
_____no_output_____
MIT
BellCurve.ipynb
4dsolutions/ONLC_XPYS
What I do below is semi-mysterious, and something I'd like to get to in numpy in more detail. The whole idea behind numpy is every function, or at least the unary ones, are vectorized, meaning the work element-wise through every cell, with no need for any for loops.My Gaussian formula above won't natively understand h...
%timeit vg = np.vectorize(g)
The slowest run took 5.55 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 4.1 µs per loop
MIT
BellCurve.ipynb
4dsolutions/ONLC_XPYS
At any rate, this way, with a list comprehension, is orders of magnitude slower:
%timeit vg2 = np.array([g(x) for x in domain]) vg = np.vectorize(g) %matplotlib inline %timeit plt.plot(domain, vg(domain))
The slowest run took 89.97 times longer than the fastest. This could mean that an intermediate result is being cached. 1 loop, best of 3: 2.49 ms per loop
MIT
BellCurve.ipynb
4dsolutions/ONLC_XPYS
I bravely built my own version of the Gaussian distribution, a continuous function (any real number input is OK, from negative infinity to infinity, but not those (keep it in between). The thing about a Gaussian is you can shrink it and grow it while keeping the curve itself, self similar. Remember "hyperparamters"? ...
%timeit plt.plot(domain, st.norm.pdf(domain)) mu = 0 sigma = math.sqrt(0.2) plt.plot(domain, vg(domain), color = 'blue') sigma = math.sqrt(1) plt.plot(domain, vg(domain), color = 'red') sigma = math.sqrt(5) plt.plot(domain, vg(domain), color = 'orange') mu = -2 sigma = math.sqrt(.5) plt.plot(domain, vg(domain), color =...
_____no_output_____
MIT
BellCurve.ipynb
4dsolutions/ONLC_XPYS
[see Wikipedia figure](https://en.wikipedia.org/wiki/Gaussian_functionProperties)These are Gaussian PDFs or Probability Density Functions.68.26% of values happen within -1 and 1.
from IPython.display import YouTubeVideo YouTubeVideo("xgQhefFOXrM") a = st.norm.cdf(-1) # Cumulative distribution function b = st.norm.cdf(1) b - a a = st.norm.cdf(-2) b = st.norm.cdf(2) b - a # 99.73% is more correct than 99.72% a = st.norm.cdf(-3) b = st.norm.cdf(3) b - a # 95% a = st.norm.cdf(-1.96) b = st.norm....
_____no_output_____
MIT
BellCurve.ipynb
4dsolutions/ONLC_XPYS
What are the chances a value is less than -1.32?
st.norm.cdf(-1.32)
_____no_output_____
MIT
BellCurve.ipynb
4dsolutions/ONLC_XPYS
What are the chances a value is between -0.21 and 0.85?
1 - st.norm.sf(-0.21) # filling in from the right (survival function) a = st.norm.cdf(0.85) # filling in from the left a b = st.norm.cdf(-0.21) # from the left b a-b # getting the difference (per the Youtube)
_____no_output_____
MIT
BellCurve.ipynb
4dsolutions/ONLC_XPYS
Lets plot the integral of the Bell Curve. This curve somewhat describes the temporal pattern whereby a new technology is adopted, first by early adopters, then comes the bandwagon effect, then come the stragglers. Not the every technology gets adopted in this way. Only some do.
plt.plot(domain, st.norm.cdf(domain))
_____no_output_____
MIT
BellCurve.ipynb
4dsolutions/ONLC_XPYS
[Standard Deviation](https://en.wikipedia.org/wiki/Standard_deviation)Above is the Bell Curve integral.Remember the derivative is obtain from small differences: (f(x+h) - f(x))/xGiven x is our entire domain and operations are vectorized, it's easy enough to plot said derivative.
x = st.norm.cdf(domain) diff = st.norm.cdf(domain + 0.01) plt.plot(domain, (diff-x)/0.01) x = st.norm.pdf(domain) diff = st.norm.pdf(domain + 0.01) plt.plot(domain, (diff-x)/0.01) x = st.norm.pdf(domain) plt.plot(domain, x, color = "red") x = st.norm.pdf(domain) diff = st.norm.pdf(domain + 0.01) plt.plot(domain, (diff...
_____no_output_____
MIT
BellCurve.ipynb
4dsolutions/ONLC_XPYS
Integrating the GaussianApparently there's no closed form, however sympy is able to do an integration somehow.
from sympy import var, Lambda, integrate, sqrt, pi, exp, latex fig = plt.gcf() fig.set_size_inches(8,5) var('a b x sigma mu') pdf = Lambda((x,mu,sigma), (1/(sigma * sqrt(2*pi)) * exp(-(mu-x)**2 / (2*sigma**2))) ) cdf = Lambda((a,b,mu,sigma), integrate( pdf(x,mu,sigma),(x,a,b) ) ) display(Latex('$ cdf(a,b,\mu...
_____no_output_____
MIT
BellCurve.ipynb
4dsolutions/ONLC_XPYS
Lets stop right here and note the pdf and cdf have been defined, using sympy's Lambda and integrate, and the cdf will be fed a lot of data, one hundred points, along with mu and sigma. Then it's simply a matter of plotting.What's amazing is our ability to get something from sympy that works to give a cdf, independentl...
x = np.linspace(50,159,100) y = np.array([cdf(-1e99,v,100,15) for v in x],dtype='float') plt.grid(True) plt.title('Cumulative Distribution Function') plt.xlabel('IQ') print(type(plt.xlabel)) plt.ylabel('Y') plt.text(65,.75,'$\mu = 100$',fontsize=16) plt.text(65,.65,'$\sigma = 15$',fontsize=16) plt.plot(x,y,color='gray'...
<class 'function'>
MIT
BellCurve.ipynb
4dsolutions/ONLC_XPYS
The above is truly a testament to Python's power, or the Python ecosystem's power. We've brought in sympy, able to do symbolic integration, and talk LaTeX at the same time. That's impressive. Here's [the high IQ source](https://arachnoid.com/IPython/normal_distribution.html) for the original version of the above cod...
domain = np.linspace(0, 200, 3000) IQ = st.norm.pdf(domain, 100, 15) plt.plot(domain, IQ, color = "red") domain = np.linspace(0, 200, 3000) mu = 100 sigma = 15 IQ = vg(domain) plt.plot(domain, IQ, color = "green")
_____no_output_____
MIT
BellCurve.ipynb
4dsolutions/ONLC_XPYS
Db2 Connection Document This notebook contains the connect statement that will be used for connecting to Db2. The typical way of connecting to Db2 within a notebooks it to run the db2 notebook (`db2.ipynb`) and then issue the `%sql connect` statement:```sql%run db2.ipynb%sql connect to sample user ...```Rather than ha...
%sql CONNECT TO SAMPLE USER DB2INST1 USING db2inst1 HOST localhost PORT 50000
_____no_output_____
Apache-2.0
connection.ipynb
Db2-DTE-POC/db2v11
Check that the EMPLOYEE and DEPARTMENT table existA lot of the examples depend on these two tables existing in the database. These tables will be created for you if they don't already exist. Note that they will not overwrite the existing Db2 samples tables.
if sqlcode == 0: %sql -sampledata
_____no_output_____
Apache-2.0
connection.ipynb
Db2-DTE-POC/db2v11
Code for Refreshing Slideware and Youtube Videos in a Notebook
%%javascript window.findCellIndicesByTag = function findCellIndicesByTag(tagName) { return (Jupyter.notebook.get_cells() .filter( ({metadata: {tags}}) => tags && tags.includes(tagName) ) .map((cell) => Jupyter.notebook.find_cell_index(cell)) ); }; window.refresh = function runPlotCells() { va...
_____no_output_____
Apache-2.0
connection.ipynb
Db2-DTE-POC/db2v11
Run through all of the cells and refresh everything that has a **refresh** tag in it.
from IPython.display import Javascript display(Javascript("window.refresh()"))
_____no_output_____
Apache-2.0
connection.ipynb
Db2-DTE-POC/db2v11
Performance Testing with Computing the Mandlebrot Set This sample was executed on a DSVM on a Standard_D2_v2 in Azure. This code below also uses a few other cluster config files titled: - "10_core_cluster.json" - "20_core_cluster.json"- "40_core_cluster.json"- "80_core_cluster.json"Each of the cluster config files abo...
install.packages(c('httr','rjson','RCurl','digest','foreach','iterators','devtools','curl','jsonlite','mime'))
_____no_output_____
MIT
samples/mandelbrot/mandelbrot_performance_test.ipynb
zerweck/doAzureParallel
Install doAzureParallel and rAzureBatch from github
library(devtools) install_github("Azure/rAzureBatch") install_github("Azure/doAzureParallel")
_____no_output_____
MIT
samples/mandelbrot/mandelbrot_performance_test.ipynb
zerweck/doAzureParallel
Install *microbenchmark* package and other utilities
install.packages("microbenchmark") library(microbenchmark) library(reshape2) library(ggplot2)
_____no_output_____
MIT
samples/mandelbrot/mandelbrot_performance_test.ipynb
zerweck/doAzureParallel
Define function to compute the mandlebrot set.
vmandelbrot <- function(xvec, y0, lim) { mandelbrot <- function(x0,y0,lim) { x <- x0; y <- y0 iter <- 0 while (x^2 + y^2 < 4 && iter < lim) { xtemp <- x^2 - y^2 + x0 y <- 2 * x * y + y0 x <- xtemp iter <- iter + 1 } iter } unlist(lapply(xvec, mandelbrot, y0=y0, ...
_____no_output_____
MIT
samples/mandelbrot/mandelbrot_performance_test.ipynb
zerweck/doAzureParallel
The local execution is performed on a single Standard_D2_V2 DSVM in Azure. We use the doParallel package and use both cores for this performance test
localExecution <- function() { print("doParallel") library(doParallel) cl<-makeCluster(2) registerDoParallel(cl) x.in <- seq(-2, 1.5, length.out=1080) y.in <- seq(-1.5, 1.5, length.out=1080) m <- 1000 mset <- foreach(i=y.in, .combine=rbind, .export = "vmandelbrot") %dopar% vmandelbrot(x.in, i, m) }
_____no_output_____
MIT
samples/mandelbrot/mandelbrot_performance_test.ipynb
zerweck/doAzureParallel
The Azure Execution takes in a pool_config JSON file and will use doAzureParallel.
azureExecution <- function(pool_config) { print("doAzureParallel") library(doAzureParallel) pool <- doAzureParallel::makeCluster(pool_config) registerDoAzureParallel(pool) x.in <- seq(-2, 1.5, length.out=1080) y.in <- seq(-1.5, 1.5, length.out=1080) m <- 1000 mset <- foreach(i=y.in, .combine=rbind, .o...
_____no_output_____
MIT
samples/mandelbrot/mandelbrot_performance_test.ipynb
zerweck/doAzureParallel
Using the *microbenchmark* package, we test the difference in performance when running the same code to calculate the mandlebrot set on a single machine (localExecution), a cluster of 10 cores, a cluster of 20 cores, and finally a cluster of 40 cores.
op <- microbenchmark( doParLocal=localExecution(), doParAzure_10cores=azureExecution("10_core_cluster.json"), doParAzure_20cores=azureExecution("20_core_cluster.json"), doParAzure_40cores=azureExecution("40_core_cluster.json"), times=5L) print(op) plot(op)
_____no_output_____
MIT
samples/mandelbrot/mandelbrot_performance_test.ipynb
zerweck/doAzureParallel
Load the data
iris = load_iris(as_frame=True) pd.concat([iris.data, iris.target], axis=1).plot.scatter( x='petal length (cm)', y='petal width (cm)', c='target', colormap='viridis' ) iris.data X = iris.data[['petal length (cm)','petal width (cm)']] y = iris.target X_train, X_test, y_train, y_test= train_test_split(X, ...
_____no_output_____
MIT
lab9/lab9.ipynb
YgLK/ML
for 0 target value
# for 0 target value per_clf_0 = Perceptron() per_clf_0.fit(X_train, y_train_0) y_pred_train_0 = per_clf_0.predict(X_train) y_pred_test_0 = per_clf_0.predict(X_test) acc_train_0 = accuracy_score(y_train_0, y_pred_train_0) acc_test_0 = accuracy_score(y_test_0, y_pred_test_0) print("acc_train_0", acc_train_0) print("acc_...
acc_train_0 1.0 acc_test_0 1.0
MIT
lab9/lab9.ipynb
YgLK/ML
for 1 target value
y_train_1 = (y_train == 1).astype(int) y_test_1 = (y_test == 1).astype(int) # for 1 target value per_clf_1 = Perceptron() per_clf_1.fit(X_train, y_train_1) y_pred_train_1 = per_clf_1.predict(X_train) y_pred_test_1 = per_clf_1.predict(X_test) acc_train_1 = accuracy_score(y_train_1, y_pred_train_1) acc_test_1 = accuracy_...
acc_train_1 0.6666666666666666 acc_test_1 0.6666666666666666
MIT
lab9/lab9.ipynb
YgLK/ML
for 2 target value
y_train_2 = (y_train == 2).astype(int) y_test_2 = (y_test == 2).astype(int) # for 2 target value per_clf_2 = Perceptron() per_clf_2.fit(X_train, y_train_2) y_pred_train_2 = per_clf_2.predict(X_train) y_pred_test_2 = per_clf_2.predict(X_test) acc_train_2 = accuracy_score(y_train_2, y_pred_train_2) acc_test_2 = accuracy_...
acc_train_2 0.825 acc_test_2 0.8666666666666667
MIT
lab9/lab9.ipynb
YgLK/ML
weights
print("0: bias weight", per_clf_0.intercept_) print("Input weights (w1, w2): ", per_clf_0.coef_) print("1: bias weight", per_clf_1.intercept_) print("Input weights (w1, w2): ", per_clf_1.coef_) print("0: bias weight", per_clf_2.intercept_) print("Input weights (w1, w2): ", per_clf_2.coef_)
0: bias weight [-39.] Input weights (w1, w2): [[ 0.8 27.3]]
MIT
lab9/lab9.ipynb
YgLK/ML
Save accuracy lists and weight tuple in the pickles
# accuracy per_acc = [(acc_train_0, acc_test_0), (acc_train_1, acc_test_1), (acc_train_2, acc_test_2)] filename = "per_acc.pkl" save_object_as_pickle(per_acc, filename) print("per_acc\n", per_acc) # weights per_wght = [(per_clf_0.intercept_[0], per_clf_0.coef_[0][0], per_clf_0.coef_[0][1]), (per_clf_1.intercept_[0], pe...
per_wght [(9.0, -2.0999999999999988, -3.0999999999999996), (-8.0, 4.600000000000016, -22.699999999999974), (-39.0, 0.7999999999999883, 27.30000000000003)]
MIT
lab9/lab9.ipynb
YgLK/ML
Perceptron, XOR
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) y = np.array([0, 1, 1, 0]) per_clf_xor = Perceptron() per_clf_xor.fit(X, y) pred_xor = per_clf_xor.predict(X) xor_acc = accuracy_score(y, pred_xor) print("xor_accuracy:", xor_acc) print("XOR: bias weight", per_clf_xor.intercept_) print("Inpu...
XOR: bias weight [0.] Input weights (w1, w2): [[0. 0.]]
MIT
lab9/lab9.ipynb
YgLK/ML
2nd Perceprton, XOR
import tensorflow as tf from tensorflow import keras while True: model = keras.models.Sequential() model.add(keras.layers.Dense(2, activation="relu", input_dim=2)) model.add(keras.layers.Dense(1, activation="sigmoid")) model.compile(loss=tf.keras.losses.BinaryCrossentropy(), optimiz...
[[0.33351305] [0.999105 ] [0.33351305] [0.33351305]] 0.75 [[0.33357185] [0.9995415 ] [0.33357185] [0.33357185]] 0.75 WARNING:tensorflow:5 out of the last 5 calls to <function Model.make_predict_function.<locals>.predict_function at 0x0000013C7743D430> triggered tf.function retracing. Tracing is expensive and the...
MIT
lab9/lab9.ipynb
YgLK/ML