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
pick some samples to test
model.eval() with torch.no_grad(): text = 'premise: I am supposed to take food to a party tomorrow. initial: I had bought all the ingredients for it last week. counterfactual: I need to buy all the ingredients for it after work today. original_ending: I spent all day yesterday cooking the food. Unfortunately, I bur...
edited_ending: I spent all day yesterday cooking the food. Unfortunately, I burnt the food. I won't be able to get new ingredients in time for tomorrow's party.
MIT
huggingface_t5_6_3.ipynb
skywalker00001/Conterfactual-Reasoning-Project
8. Evalutation 7.1 Blue score
# predicitions: y', actuals: y from torchtext.data.metrics import bleu_score pre_corpus = [i.split(" ") for i in predictions] act_corpus = [i.split(" ") for i in actuals] print(act_corpus) print(pre_corpus) #bs = bleu_score([pre_corpus[0]], [act_corpus[0]], max_n=1, weights=[1]) #bs = bleu_score([pre_corpus[0]], [act_...
bleus_1: 0.02605
MIT
huggingface_t5_6_3.ipynb
skywalker00001/Conterfactual-Reasoning-Project
7.2 ROUGE
!pip install rouge from rouge import Rouge def compute_rouge(predictions, targets): predictions = [" ".join(prediction).lower() for prediction in predictions] predictions = [prediction if prediction else "EMPTY" for prediction in predictions] targets = [" ".join(target).lower() for target in targets] t...
rouge_1: 0.96353
MIT
huggingface_t5_6_3.ipynb
skywalker00001/Conterfactual-Reasoning-Project
7.3 T5 loss (cross entropy), discussed before
print(final_loss / len(part_large_cleaned_df)) # source = tokenizer.encode_plus(predictions, max_length= config.SOURCE_LEN, padding='max_length', return_tensors='pt') # target = tokenizer.encode_plus(actuals, max_length= config.TARGET_LEN, padding='max_length', return_tensors='pt') # source_ids = source['input_ids']....
{'input_ids': [27, 1866, 8, 1723, 972, 11, 1868, 120, 3, 13106, 3, 9, 509, 32, 13119, 53, 12, 21, 82, 3281, 5, 1], 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
MIT
huggingface_t5_6_3.ipynb
skywalker00001/Conterfactual-Reasoning-Project
Global Alignment: The Needleman Wunsch AlgorithmThe objective of this notebook is to help you familiarize yourself with the Needleman Wunsch algorithm for pairwise alignment of sequences.
import numpy as np # to print colored arrows you will need the termcolor module # if you don't have it, traceback arrows will be printed # without color color = True try : from termcolor import colored except : color = False # the three directions you can go in the traceback: DIAG = 0 UP = 1 LEFT = 2 # UTF-...
~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~` DP matrix A T G T C G C T T A 0.0 -0.1 -0.2 -0.3 -0.4 -0.5 -0.6 -0.7 -0.8 -0.9 -1.0 A -0.1 1.0 0.9 0.8 0.7 0.6 0.5 0.4 0.3 0.2 0.1 T -0.2 0.9 2.0 1.9 1.8 1.7 1.6 1.5 1.4 1.3 1.2 A -0.3 0.8 1.9 1.8 1.7 ...
MIT
notebooks/04_global_alignment.ipynb
asabenhur/CS425
Summary
import numpy as np from scipy.linalg import sqrtm import matplotlib.pyplot as plt N = 1000
_____no_output_____
MIT
HW5/notebook/HW5.ipynb
okuchap/SML
Facet WrappingFacets divide a plot into subplots based on the values of one or morediscrete variable.
import pandas as pd from lets_plot import * LetsPlot.setup_html() df = pd.read_csv('https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg.csv') p = ggplot(df, aes('cty', 'hwy')) + geom_point() p p + facet_wrap(facets='fl', ncol=3)
_____no_output_____
MIT
docs/_downloads/29369f7678f70a010207df843f9d0358/plot__facet_wrapping.ipynb
IKupriyanov-HORIS/lets-plot-docs
Now put heading according to the description mentioned in the dataset
data.columns = ["sepal length", "sepal width", "petal length", "petal width", "Class"] data.head()
_____no_output_____
MIT
Naive_Bayes/Naive_bayes_classifier.ipynb
Ajith013/Machine_learning
Make sure that all the datatypes are correct and consistent
data.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 149 entries, 0 to 148 Data columns (total 5 columns): sepal length 149 non-null float64 sepal width 149 non-null float64 petal length 149 non-null float64 petal width 149 non-null float64 Class 149 non-null object dtypes: float64(4), object(1) me...
MIT
Naive_Bayes/Naive_bayes_classifier.ipynb
Ajith013/Machine_learning
Dividing the dataset in X and Y (Attributes and Classes)
X = data.drop(['Class'], axis = 1) Y = data['Class'] X.head() Y.head()
_____no_output_____
MIT
Naive_Bayes/Naive_bayes_classifier.ipynb
Ajith013/Machine_learning
Now split the data into training and test data
X_train, X_test, y_train, y_test = train_test_split(X, Y, random_state = 0, test_size = 0.30) classifier = GaussianNB() classifier.fit(X_train, y_train)
_____no_output_____
MIT
Naive_Bayes/Naive_bayes_classifier.ipynb
Ajith013/Machine_learning
__The class prior shows the probability of each class. This can be set before building the model manually. If not then it is handled by the function.In the above cas the priors are not set. So it is adjusted according to the data.__ __The priors adjusted according to the data are as follows__
classifier.class_prior_
_____no_output_____
MIT
Naive_Bayes/Naive_bayes_classifier.ipynb
Ajith013/Machine_learning
__Var_smoothing is the portion of the largest variance of all features that is added to variances for calculation stability.In this case the parameter has been set to default.__
classifier.get_params() y_pred = classifier.predict(X_test) cm = confusion_matrix(y_test, y_pred) print("Confusion matrix: ", cm) print("Accuracy of the model: " ,accuracy_score(y_test, y_pred))
Accuracy of the model: 0.8888888888888888
MIT
Naive_Bayes/Naive_bayes_classifier.ipynb
Ajith013/Machine_learning
Using Cache (available since v21.06.00) Need for CacheIn many deep learning use cases, small image patches need to be extracted from the large image and they are fed into the neural network. If the patch size doesn't align with the underlying tile layout of TIFF image (e.g., AI model such as ResNet may accept a partic...
from cucim import CuImage cache = CuImage.cache() print(f' type: {cache.type}({int(cache.type)})') print(f'memory_size: {cache.memory_size}/{cache.memory_capacity}') print(f'free_memory: {cache.free_memory}') print(f' size: {cache.size}/{cache.capacity}') print(f' hit_count: {cache.hit_count}') print(f' ...
type: CacheType.NoCache(0) memory_size: 0/0 free_memory: 0 size: 0/0 hit_count: 0 miss_count: 0 config: {'type': 'nocache', 'memory_capacity': 1024, 'capacity': 5461, 'mutex_pool_capacity': 11117, 'list_padding': 10000, 'extra_shared_memory_size': 100, 'record_stat': False}
Apache-2.0
notebooks/Using_Cache.ipynb
madsbk/cucim
Changing Cache SettingCache configuration can be changed by adding parameters to `cache()` method.The following parameters are available:- `type`: The type (strategy) name. Default to 'no_cache'.- `memory_capacity`: The maximum number of mebibytes (`MiB`, 2^20) that can be allocated (used) in the cache memory. Default...
from cucim import CuImage cache = CuImage.cache('per_process', memory_capacity=2048) print(f' type: {cache.type}({int(cache.type)})') print(f'memory_size: {cache.memory_size}/{cache.memory_capacity}') print(f'free_memory: {cache.free_memory}') print(f' size: {cache.size}/{cache.capacity}') print(f' hit_co...
type: CacheType.PerProcess(1) memory_size: 0/2147483648 free_memory: 2147483648 size: 0/10922 hit_count: 0 miss_count: 0 config: {'type': 'per_process', 'memory_capacity': 2048, 'capacity': 10922, 'mutex_pool_capacity': 11117, 'list_padding': 10000, 'extra_shared_memory_size': 100, 'record_stat': ...
Apache-2.0
notebooks/Using_Cache.ipynb
madsbk/cucim
Choosing Proper Cache Memory SizeIt is important to select the appropriate cache memory size (capacity). Small cache memory size results in low cache hit rates. Conversely, if the cache memory size is too large, memory is wasted.For example, if the default tile size is 256x256 and the patch size to load is 224x224, th...
from cucim import CuImage from cucim.clara.cache import preferred_memory_capacity img = CuImage('input/image.tif') image_size = img.size('XY') # same with `img.resolutions["level_dimensions"][0]` tile_size = img.resolutions['level_tile_sizes'][0] # default: (256, 256) patch_size = (1024, 1024) ...
image size: [19920, 26420] tile size: (256, 256) memory_capacity : 74 MiB memory_capacity2: 74 MiB memory_capacity3: 74 MiB = Cache Info = type: CacheType.PerProcess(1) memory_size: 0/77594624 size: 0/394
Apache-2.0
notebooks/Using_Cache.ipynb
madsbk/cucim
Reserve More Cache MemoryIf more cache memory capacity is needed in runtime, you can use `reserve()` method.
from cucim import CuImage from cucim.clara.cache import preferred_memory_capacity img = CuImage('input/image.tif') memory_capacity = preferred_memory_capacity(img, patch_size=(256, 256)) new_memory_capacity = preferred_memory_capacity(img, patch_size=(512, 512)) print(f'memory_capacity : {memory_capacity} MiB') prin...
memory_capacity : 30 MiB new_memory_capacity: 44 MiB = Cache Info = type: CacheType.PerProcess(1) memory_size: 0/31457280 size: 0/160 = Cache Info (update memory capacity) = type: CacheType.PerProcess(1) memory_size: 0/46137344 size: 0/234 = Cache Info (update memory capacity & capacity) ...
Apache-2.0
notebooks/Using_Cache.ipynb
madsbk/cucim
Profiling Cache Hit/MissIf you add an argument `record_stat=True` to `CuImage.cache()` method, cache statistics is recorded.Cache hit/miss count is accessible through `hit_count`/`miss_count` property of the cache object.You can get/set/unset the recording through `record()` method.
from cucim import CuImage from cucim.clara.cache import preferred_memory_capacity img = CuImage('input/image.tif') memory_capacity = preferred_memory_capacity(img, patch_size=(256, 256)) cache = CuImage.cache('per_process', memory_capacity=memory_capacity, record_stat=True) img.read_region((0,0), (100,100)) print(f'c...
cache hit: 0, cache miss: 1 cache hit: 1, cache miss: 1 cache hit: 2, cache miss: 1 Is recorded: True Is recorded: False cache hit: 0, cache miss: 0 type: CacheType.PerProcess(1) memory_size: 196608/31457280 free_memory: 31260672 size: 1/160 type: CacheType.NoCache(0) memory_size: 0/0 free_memory...
Apache-2.0
notebooks/Using_Cache.ipynb
madsbk/cucim
Considerations in Multi-threading/processing Environment `per_process` strategy Cache memoryIf used in the multi-threading environment and each thread is reading the different part of the image sequentially, please consider increasing cache memory size than the size suggested by `cucim.clara.cache.preferred_memory_cap...
import json from cucim import CuImage cache = CuImage.cache() config_data = {'cache': cache.config} json_text = json.dumps(config_data, indent=4) print(json_text) # Save into the configuration file. with open('.cucim.json', 'w') as fp: fp.write(json_text)
{ "cache": { "type": "nocache", "memory_capacity": 1024, "capacity": 5461, "mutex_pool_capacity": 11117, "list_padding": 10000, "extra_shared_memory_size": 100, "record_stat": false } }
Apache-2.0
notebooks/Using_Cache.ipynb
madsbk/cucim
!mkdir epic3752
from IPython.display import HTML HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide(); } else { $('div.input').show(); } code_show = !code_show } $( document ).ready(code_toggle); </script> <form action="javascript:code_toggle()"><input type="submit" value="Click here...
_____no_output_____
MIT
allesfitter/epic3752_ini.ipynb
jpdeleon/kesprint2
![allesfitter](logo_circ.png)
#::: globals global INPUT global VBOXES global BUTTONS global DROPDOWNS INPUT = {} VBOXES = {} BUTTONS = {} DROPDOWNS = {} layout = {'width': '180px'} layout_wide = {'width': '360px'} layout_textbox = {'width': '120px'} layout_checkbox = {} #:::: clean up csv file def clean_up_csv(fname, N_last_rows=0): with o...
_____no_output_____
MIT
allesfitter/epic3752_ini.ipynb
jpdeleon/kesprint2
1. working directory Select the working directory for this fit, for example `/Users/me/TESS-1b/`. Then you can run a fit using `allesfitter.ns_fit('/Users/me/TESS-1b/')`.
BUTTONS['datadir'] = widgets.Button(description='Select directory', button_style='') text_af_directory = widgets.Text(value='', placeholder='for example: /Users/me/TESS-1b/', disable=True) hbox = widgets.HBox([BUTTONS['datadir'], text_af_directory]) display(hbox) def select_datadir(change): root = Tk() root.wi...
_____no_output_____
MIT
allesfitter/epic3752_ini.ipynb
jpdeleon/kesprint2
2. settings
if 'show_step_2a' in INPUT and INPUT['show_step_2a'] == True: display(Markdown('### General settings')) DROPDOWNS['planet_or_EB'] = widgets.Dropdown(options=['Planets', 'EBs']) display( widgets.HBox([widgets.Label(value='Fitting planets or EBs?', layout=layout), DROPDOWNS['planet_or_EB']]) ) ...
_____no_output_____
MIT
allesfitter/epic3752_ini.ipynb
jpdeleon/kesprint2
3. parameters
import chronos as cr all_campaigns = cr.get_all_campaigns(epic) camps = "c".join([str(c).zfill(2) for c in all_campaigns]) camps import pandas as pd from glob import glob fp = f"{loc}/everest_w_limbdark_prior2_new_ini/EPIC{epic}_c{camps}" csvs = glob(f"{fp}/*mcmc-results.csv") assert len(csvs)>0 ds = {} for i,csv i...
Saved: ./epic3752/k2.csv
MIT
allesfitter/epic3752_ini.ipynb
jpdeleon/kesprint2
4. data filesPlease put all data files into the selected directory, and click the button to confirm.
if 'show_step_4' in INPUT and INPUT['show_step_4']==True: BUTTONS['confirm_data_files'] = widgets.Button(description='Confirm', button_style='') display(BUTTONS['confirm_data_files']) def check_data_files(change): clear_output() display(BUTTONS['confirm_data_files']) a...
_____no_output_____
MIT
allesfitter/epic3752_ini.ipynb
jpdeleon/kesprint2
5. check
if 'show_step_5' in INPUT and INPUT['show_step_5']==True: from allesfitter.general_output import show_initial_guess import matplotlib.pyplot as plt fig_list = show_initial_guess(INPUT['datadir'], do_logprint=False, return_figs=True) for fig in fig_list: plt.show(fig) if 'show_step_5' ...
_____no_output_____
MIT
allesfitter/epic3752_ini.ipynb
jpdeleon/kesprint2
6. tighter priors on errors and baselinesThis will take a couple of minutes. Make sure your initial guess above is very good. This will subtract the model from the data and evaluate the remaining noise patterns to estimate errors, jitter and GP baselines.
if 'show_step_6' in INPUT and INPUT['show_step_6']==True: def estimate_tighter_priors(change): print('\nEstimating errors and baselines... this will take a couple of minutes. Please be patient, you will get notified once everything is completed.\n') #::: run MCMC fit to estimate errors and ba...
_____no_output_____
MIT
allesfitter/epic3752_ini.ipynb
jpdeleon/kesprint2
7. run the fit
if 'show_step_7' in INPUT and INPUT['show_step_7']==True: try: from importlib import reload except: pass try: from imp import reload except: pass import allesfitter reload(allesfitter) button_run_ns_fit = widgets.Button(description='Run...
_____no_output_____
MIT
allesfitter/epic3752_ini.ipynb
jpdeleon/kesprint2
Deploying a trained model to Cloud Machine Learning EngineA Kubeflow Pipeline component to deploy a trained model from a Cloud Storage path to a Cloud Machine Learning Engine service. Intended useUse the component to deploy a trained model to Cloud Machine Learning Engine service. The deployed model can serve online o...
%%capture --no-stderr KFP_PACKAGE = 'https://storage.googleapis.com/ml-pipeline/release/0.1.14/kfp.tar.gz' !pip3 install $KFP_PACKAGE --upgrade
_____no_output_____
Apache-2.0
components/gcp/ml_engine/deploy/sample.ipynb
JohnPaton/pipelines
2. Load the component using KFP SDK
import kfp.components as comp mlengine_deploy_op = comp.load_component_from_url( 'https://raw.githubusercontent.com/kubeflow/pipelines/d2f5cc92a46012b9927209e2aaccab70961582dc/components/gcp/ml_engine/deploy/component.yaml') help(mlengine_deploy_op)
_____no_output_____
Apache-2.0
components/gcp/ml_engine/deploy/sample.ipynb
JohnPaton/pipelines
For more information about the component, please checkout:* [Component python code](https://github.com/kubeflow/pipelines/blob/master/component_sdk/python/kfp_component/google/ml_engine/_deploy.py)* [Component docker file](https://github.com/kubeflow/pipelines/blob/master/components/gcp/container/Dockerfile)* [Sample n...
# Required Parameters PROJECT_ID = '<Please put your project ID here>' # Optional Parameters EXPERIMENT_NAME = 'CLOUDML - Deploy' TRAINED_MODEL_PATH = 'gs://ml-pipeline-playground/samples/ml_engine/census/trained_model/'
_____no_output_____
Apache-2.0
components/gcp/ml_engine/deploy/sample.ipynb
JohnPaton/pipelines
Example pipeline that uses the component
import kfp.dsl as dsl import kfp.gcp as gcp import json @dsl.pipeline( name='CloudML deploy pipeline', description='CloudML deploy pipeline' ) def pipeline( model_uri = 'gs://ml-pipeline-playground/samples/ml_engine/census/trained_model/', project_id = PROJECT_ID, model_id = 'kfp_sample_model', ...
_____no_output_____
Apache-2.0
components/gcp/ml_engine/deploy/sample.ipynb
JohnPaton/pipelines
Compile the pipeline
pipeline_func = pipeline pipeline_filename = pipeline_func.__name__ + '.zip' import kfp.compiler as compiler compiler.Compiler().compile(pipeline_func, pipeline_filename)
_____no_output_____
Apache-2.0
components/gcp/ml_engine/deploy/sample.ipynb
JohnPaton/pipelines
Submit the pipeline for execution
#Specify pipeline argument values arguments = {} #Get or create an experiment and submit a pipeline run import kfp client = kfp.Client() experiment = client.create_experiment(EXPERIMENT_NAME) #Submit a pipeline run run_name = pipeline_func.__name__ + ' run' run_result = client.run_pipeline(experiment.id, run_name, pi...
_____no_output_____
Apache-2.0
components/gcp/ml_engine/deploy/sample.ipynb
JohnPaton/pipelines
Asking salient questions Now that we can generate the concept map, and calculate the cognitive load per sentence, let's display text blurbs in order of increasing cognitive load as we traverse the created learning path. Based on the blurbs, we will ask questions of the student that are multiple choice. The answers wil...
import itertools from itertools import chain import nltk #stop_words = set(stopwords.words('english')) #filename = 'A Mind For Numbers_ How to Excel at Math and Science (Even If You Flunked Algebra)' filename = 'physics_iitjee_vol1' concepts = {} import pickle # Loading extracted concepts from file (see concept_extra...
_____no_output_____
MIT
asking_questions_inferencing/graph_opening.ipynb
rts1988/IntelligentTutoringSystem_Experiments
Functions to get blurbs for two concepts
import pandas as pd def calc_clt_blurb_order(tuplist): tup_to_clt = {} for tup in tuplist: blurb_clt = 0 for i in range(tup[0],tup[1]+1): blurb_clt = blurb_clt + sent_to_clt[i] tup_to_clt[tup] = blurb_clt tup_to_clt = pd.Series(tup_to_clt) tup_to_clt.sort_values(ascen...
_____no_output_____
MIT
asking_questions_inferencing/graph_opening.ipynb
rts1988/IntelligentTutoringSystem_Experiments
Deep learning - hw1- 0756708 ε­«θŒ‚ε‹›
import numpy as np import random import pandas as pd from sklearn.model_selection import train_test_split from keras.utils import to_categorical import matplotlib.pyplot as plt import copy
Using TensorFlow backend.
MIT
Assignment1/hw1.ipynb
john850512/Deep_Learning
1. Data processing
df = pd.read_csv('./titanic.csv') df.head() training_set = df[:800] testing_set = df[800:] X_train = training_set[['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare']].values X_test = testing_set[['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare']].values X_train = X_train.reshape(X_train.shape[0], -1, 1) X_test = X_test...
(800, 6, 1) (800, 2, 1) (91, 6, 1) (91, 2, 1)
MIT
Assignment1/hw1.ipynb
john850512/Deep_Learning
2. Model Architecture
def sigmoid(z): return 1.0 / (1.0 + np.exp(-z)) def sigmoid_derivate(z): return sigmoid(z) * (1-sigmoid(z)) def cross_entropy(output, ground_truth): return np.sum( np.nan_to_num( -ground_truth*np.log(output) - (1-ground_truth)*np.log(1-output) ) ) def cross_entropy_derivative(output, ground_truth): r...
_____no_output_____
MIT
Assignment1/hw1.ipynb
john850512/Deep_Learning
3. Training p1
module1 = NN([6, 32, 32, 64, 2]) module1.SGD(training_data, testing_data, 3000, 100, 0.3) new_x_axis = np.arange(0,3000, 50) fig, ax = plt.subplots(1, 1) ax.plot(new_x_axis, module1.training_loss) ax.set_title('training loss') ax.set_xlabel('Epochs') ax.set_ylabel('Average cross entropy') fig, ax = plt.subplots(1, 2) f...
_____no_output_____
MIT
Assignment1/hw1.ipynb
john850512/Deep_Learning
p2
module2 = NN([6, 3, 3, 2]) module2.SGD(training_data, testing_data, 3000, 100, 0.03) fig, ax = plt.subplots(1, 1) ax.plot(new_x_axis, module2.training_loss) ax.set_title('training loss') ax.set_xlabel('Epochs') ax.set_ylabel('Average cross entropy') fig, ax = plt.subplots(1, 2) fig.set_size_inches(12, 4) ax[0].plot(new...
_____no_output_____
MIT
Assignment1/hw1.ipynb
john850512/Deep_Learning
p4
df.head() module2.weights[0]
_____no_output_____
MIT
Assignment1/hw1.ipynb
john850512/Deep_Learning
p3.
df_new = df.copy() df_new.head() from sklearn.preprocessing import StandardScaler fare_scaler = StandardScaler() df_new['Fare'] = pd.DataFrame(fare_scaler.fit_transform(df_new['Fare'].values.reshape(-1,1))) df_new.head() training_set = df_new[:800] testing_set = df_new[800:] X_train = training_set[['Pclass', 'Sex', 'A...
_____no_output_____
MIT
Assignment1/hw1.ipynb
john850512/Deep_Learning
p3-2
df_new_1 = df.copy() fare_scaler = StandardScaler() age_scaler = StandardScaler() df_new_1['Fare'] = pd.DataFrame(fare_scaler.fit_transform(df_new_1['Fare'].values.reshape(-1,1))) df_new_1['Age'] = pd.DataFrame(age_scaler.fit_transform(df_new_1['Age'].values.reshape(-1,1))) training_set = df_new_1[:800] testing_set = d...
_____no_output_____
MIT
Assignment1/hw1.ipynb
john850512/Deep_Learning
p5
df_new_2 = pd.get_dummies(df_new_1, columns=['Pclass']) df_new_2.head() training_set = df_new_2[:800] testing_set = df_new_2[800:] X_train = training_set[['Pclass_1', 'Pclass_2', 'Pclass_3', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare']].values X_test = testing_set[['Pclass_1', 'Pclass_2', 'Pclass_3', 'Sex', 'Age', 'SibSp',...
_____no_output_____
MIT
Assignment1/hw1.ipynb
john850512/Deep_Learning
p6.
# X_train = training_set[['Pclass_1', 'Pclass_2', 'Pclass_3', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare']].values X_train[1] people_John = np.array([[0, 0, 1, 1, age_scaler.transform([[23]]), 2, 2, fare_scaler.transform([[0.87]])]]).reshape(-1, 1) print(people_John) prediction_john = module5.forward(people_John) print('Joh...
Angelaζ­»δΊ‘ηš„ζ©ŸηŽ‡vsε­˜ζ΄»ηš„ζ©ŸηŽ‡: [0.03808093] [0.96191907]
MIT
Assignment1/hw1.ipynb
john850512/Deep_Learning
> This is one of the 100 recipes of the [IPython Cookbook](http://ipython-books.github.io/), the definitive guide to high-performance scientific computing and data science in Python. Links: * http://mrob.com/pub/comp/xmorphia/F260/F260-k550.html * http://mrob.com/pub/comp/xmorphia/ 12.4. Simulating a Partial Different...
import numpy as np import matplotlib.pyplot as plt %matplotlib inline
_____no_output_____
Apache-2.0
BiologicalPatternFormation/WorkingReactionDiffusion.ipynb
topatomer/IntroToBiophysics
2. We will simulate the following system of partial differential equations on the domain $E=[-1,1]^2$: \begin{align*}\frac{\partial u}{\partial t} &= a \Delta u + u - u^3 - v + k\\\tau\frac{\partial v}{\partial t} &= b \Delta v + u - v\\\end{align*} The variable $u$ represents the concentration of a substance favoring ...
#a = 2.8e-4 #b = 5e-3 a=4e-4 b=2e-4 F=0.0180 k=0.0510 #F=0.0260 #k=0.0550
_____no_output_____
Apache-2.0
BiologicalPatternFormation/WorkingReactionDiffusion.ipynb
topatomer/IntroToBiophysics
3. We discretize time and space. The following condition ensures that the discretization scheme we use here is stable:$$dt \leq \frac{dx^2}{2}$$
size = 200 # size of the 2D grid dx = 2./size # space step T = 10.0 # total time dt = .9 * dx**2/2 # time step n = int(T/dt)
_____no_output_____
Apache-2.0
BiologicalPatternFormation/WorkingReactionDiffusion.ipynb
topatomer/IntroToBiophysics
4. We initialize the variables $u$ and $v$. The matrices $U$ and $V$ contain the values of these variables on the vertices of the 2D grid. These variables are initialized with a uniform noise between $0$ and $1$.
U = np.random.rand(size, size) V = np.random.rand(size, size)
_____no_output_____
Apache-2.0
BiologicalPatternFormation/WorkingReactionDiffusion.ipynb
topatomer/IntroToBiophysics
5. Now, we define a function that computes the discrete Laplace operator of a 2D variable on the grid, using a five-point stencil finite difference method. This operator is defined by:$$\Delta u(x,y) \simeq \frac{u(x+h,y)+u(x-h,y)+u(x,y+h)+u(x,y-h)-4u(x,y)}{dx^2}$$We can compute the values of this operator on the grid ...
def laplacian(Z): Ztop = Z[0:-2,1:-1] Zleft = Z[1:-1,0:-2] Zbottom = Z[2:,1:-1] Zright = Z[1:-1,2:] Zcenter = Z[1:-1,1:-1] return (Ztop + Zleft + Zbottom + Zright - 4 * Zcenter) / dx**2
_____no_output_____
Apache-2.0
BiologicalPatternFormation/WorkingReactionDiffusion.ipynb
topatomer/IntroToBiophysics
6. Now, we simulate the system of equations using the finite difference method. At each time step, we compute the right-hand sides of the two equations on the grid using discrete spatial derivatives (Laplacians). Then, we update the variables using a discrete time derivative.
plt.imshow(U,cmap=plt.cm.copper,interpolation='none') # We simulate the PDE with the finite difference method. for i in range(n): # We compute the Laplacian of u and v. deltaU = laplacian(U) deltaV = laplacian(V) # We take the values of u and v inside the grid. Uc = U[1:-1,1:-1] Vc = V[1:-1,1:-1...
_____no_output_____
Apache-2.0
BiologicalPatternFormation/WorkingReactionDiffusion.ipynb
topatomer/IntroToBiophysics
7. Finally, we display the variable $u$ after a time $T$ of simulation.
plt.imshow(U, cmap=plt.cm.jet, extent=[-1,1,-1,1],interpolation='none');
_____no_output_____
Apache-2.0
BiologicalPatternFormation/WorkingReactionDiffusion.ipynb
topatomer/IntroToBiophysics
Statistics
import numpy as np
_____no_output_____
MIT
Statistics.ipynb
Data-science-vidhya/Numpy
Order statistics Return the minimum value of x along the second axis.
x = np.arange(4).reshape((2, 2)) print("x=\n", x) print("ans=\n", np.amin(x, 1))
x= [[0 1] [2 3]] ans= [0 2]
MIT
Statistics.ipynb
Data-science-vidhya/Numpy
Return the maximum value of x along the second axis. Reduce the second axis to the dimension with size one.
x = np.arange(4).reshape((2, 2)) print("x=\n", x) print("ans=\n", np.amax(x, 1, keepdims=True))
x= [[0 1] [2 3]] ans= [[1] [3]]
MIT
Statistics.ipynb
Data-science-vidhya/Numpy
Calcuate the difference between the maximum and the minimum of x along the second axis.
x = np.arange(10).reshape((2, 5)) print("x=\n", x) out1 = np.ptp(x, 1) out2 = np.amax(x, 1) - np.amin(x, 1) assert np.allclose(out1, out2) print("ans=\n", out1)
x= [[0 1 2 3 4] [5 6 7 8 9]] ans= [4 4]
MIT
Statistics.ipynb
Data-science-vidhya/Numpy
Compute the 75th percentile of x along the second axis.
x = np.arange(1, 11).reshape((2, 5)) print("x=\n", x) print("ans=\n", np.percentile(x, 75, 1))
x= [[ 1 2 3 4 5] [ 6 7 8 9 10]] ans= [4. 9.]
MIT
Statistics.ipynb
Data-science-vidhya/Numpy
Averages and variances Compute the median of flattened x.
x = np.arange(1, 10).reshape((3, 3)) print("x=\n", x) print("ans=\n", np.median(x))
x= [[1 2 3] [4 5 6] [7 8 9]] ans= 5.0
MIT
Statistics.ipynb
Data-science-vidhya/Numpy
Compute the weighted average of x.
x = np.arange(5) weights = np.arange(1, 6) out1 = np.average(x, weights=weights) out2 = (x*(weights/weights.sum())).sum() assert np.allclose(out1, out2) print(out1)
2.6666666666666665
MIT
Statistics.ipynb
Data-science-vidhya/Numpy
Compute the mean, standard deviation, and variance of x along the second axis.
x = np.arange(5) print("x=\n",x) out1 = np.mean(x) out2 = np.average(x) assert np.allclose(out1, out2) print("mean=\n", out1) out3 = np.std(x) out4 = np.sqrt(np.mean((x - np.mean(x)) ** 2 )) assert np.allclose(out3, out4) print("std=\n", out3) out5 = np.var(x) out6 = np.mean((x - np.mean(x)) ** 2 ) assert np.allclos...
x= [0 1 2 3 4] mean= 2.0 std= 1.4142135623730951 variance= 2.0
MIT
Statistics.ipynb
Data-science-vidhya/Numpy
Correlating Compute the covariance matrix of x and y.
x = np.array([0, 1, 2]) y = np.array([2, 1, 0]) print("ans=\n", np.cov(x, y))
ans= [[ 1. -1.] [-1. 1.]]
MIT
Statistics.ipynb
Data-science-vidhya/Numpy
In the above covariance matrix, what does the -1 mean? It means `x` and `y` correlate perfectly in opposite directions. Compute Pearson product-moment correlation coefficients of x and y.
x = np.array([0, 1, 3]) y = np.array([2, 4, 5]) print("ans=\n", np.corrcoef(x, y))
ans= [[1. 0.92857143] [0.92857143 1. ]]
MIT
Statistics.ipynb
Data-science-vidhya/Numpy
Compute cross-correlation of x and y.
x = np.array([0, 1, 3]) y = np.array([2, 4, 5]) print("ans=\n", np.correlate(x, y))
ans= [19]
MIT
Statistics.ipynb
Data-science-vidhya/Numpy
Histograms Compute the histogram of x against the bins.
x = np.array([0.5, 0.7, 1.0, 1.2, 1.3, 2.1]) bins = np.array([0, 1, 2, 3]) print("ans=\n", np.histogram(x, bins)) import matplotlib.pyplot as plt %matplotlib inline plt.hist(x, bins=bins) plt.show()
ans= (array([2, 3, 1], dtype=int64), array([0, 1, 2, 3]))
MIT
Statistics.ipynb
Data-science-vidhya/Numpy
Compute the 2d histogram of x and y.
xedges = [0, 1, 2, 3] yedges = [0, 1, 2, 3, 4] x = np.array([0, 0.1, 0.2, 1., 1.1, 2., 2.1]) y = np.array([0, 0.1, 0.2, 1., 1.1, 2., 3.3]) H, xedges, yedges = np.histogram2d(x, y, bins=(xedges, yedges)) print("ans=\n", H) plt.scatter(x, y) plt.grid()
ans= [[3. 0. 0. 0.] [0. 2. 0. 0.] [0. 0. 1. 1.]]
MIT
Statistics.ipynb
Data-science-vidhya/Numpy
Count number of occurrences of 0 through 7 in x.
x = np.array([0, 1, 1, 3, 2, 1, 7]) print("ans=\n", np.bincount(x))
ans= [1 3 1 1 0 0 0 1]
MIT
Statistics.ipynb
Data-science-vidhya/Numpy
Return the indices of the bins to which each value in x belongs.
x = np.array([0.2, 6.4, 3.0, 1.6]) bins = np.array([0.0, 1.0, 2.5, 4.0, 10.0]) print("ans=\n", np.digitize(x, bins))
ans= [1 4 3 2]
MIT
Statistics.ipynb
Data-science-vidhya/Numpy
Saving and Loading ModelsIn this notebook, I'll show you how to save and load models with PyTorch. This is important because you'll often want to load previously trained models to use in making predictions or to continue training on new data.
%matplotlib inline %config InlineBackend.figure_format = 'retina' import matplotlib.pyplot as plt import torch from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms import helper import fc_model # Define a transform to normalize the data transform =...
Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gz Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-labels-idx1-ubyte.gz Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-images-idx3-ubyte.gz Downloading http://fashion-...
MIT
1. Introduction/.ipynb_checkpoints/Part 6 - Saving and Loading Models-checkpoint.ipynb
Not-A-Builder/DL-PyTorch
Here we can see one of the images.
image, label = next(iter(trainloader)) helper.imshow(image[0,:]);
_____no_output_____
MIT
1. Introduction/.ipynb_checkpoints/Part 6 - Saving and Loading Models-checkpoint.ipynb
Not-A-Builder/DL-PyTorch
Train a networkTo make things more concise here, I moved the model architecture and training code from the last part to a file called `fc_model`. Importing this, we can easily create a fully-connected network with `fc_model.Network`, and train the network using `fc_model.train`. I'll use this model (once it's trained)...
# Create the network, define the criterion and optimizer model = fc_model.Network(784, 10, [512, 256, 128]) criterion = nn.NLLLoss() optimizer = optim.Adam(model.parameters(), lr=0.001) fc_model.train(model, trainloader, testloader, criterion, optimizer, epochs=2)
Epoch: 1/2.. Training Loss: 1.684.. Test Loss: 1.004.. Test Accuracy: 0.627 Epoch: 1/2.. Training Loss: 1.023.. Test Loss: 0.752.. Test Accuracy: 0.719 Epoch: 1/2.. Training Loss: 0.897.. Test Loss: 0.672.. Test Accuracy: 0.738 Epoch: 1/2.. Training Loss: 0.773.. Test Loss: 0.655.. Test Accuracy: 0.750 Epoc...
MIT
1. Introduction/.ipynb_checkpoints/Part 6 - Saving and Loading Models-checkpoint.ipynb
Not-A-Builder/DL-PyTorch
Saving and loading networksAs you can imagine, it's impractical to train a network every time you need to use it. Instead, we can save trained networks then load them later to train more or use them for predictions.The parameters for PyTorch networks are stored in a model's `state_dict`. We can see the state dict cont...
print("Our model: \n\n", model, '\n') print("The state dict keys: \n\n", model.state_dict().keys())
Our model: Network( (hidden_layers): ModuleList( (0): Linear(in_features=784, out_features=512, bias=True) (1): Linear(in_features=512, out_features=256, bias=True) (2): Linear(in_features=256, out_features=128, bias=True) ) (output): Linear(in_features=128, out_features=10, bias=True) (dropout):...
MIT
1. Introduction/.ipynb_checkpoints/Part 6 - Saving and Loading Models-checkpoint.ipynb
Not-A-Builder/DL-PyTorch
The simplest thing to do is simply save the state dict with `torch.save`. For example, we can save it to a file `'checkpoint.pth'`.
torch.save(model.state_dict(), 'checkpoint.pth')
_____no_output_____
MIT
1. Introduction/.ipynb_checkpoints/Part 6 - Saving and Loading Models-checkpoint.ipynb
Not-A-Builder/DL-PyTorch
Then we can load the state dict with `torch.load`.
state_dict = torch.load('checkpoint.pth') print(state_dict.keys())
odict_keys(['hidden_layers.0.weight', 'hidden_layers.0.bias', 'hidden_layers.1.weight', 'hidden_layers.1.bias', 'hidden_layers.2.weight', 'hidden_layers.2.bias', 'output.weight', 'output.bias'])
MIT
1. Introduction/.ipynb_checkpoints/Part 6 - Saving and Loading Models-checkpoint.ipynb
Not-A-Builder/DL-PyTorch
And to load the state dict in to the network, you do `model.load_state_dict(state_dict)`.
model.load_state_dict(state_dict)
_____no_output_____
MIT
1. Introduction/.ipynb_checkpoints/Part 6 - Saving and Loading Models-checkpoint.ipynb
Not-A-Builder/DL-PyTorch
Seems pretty straightforward, but as usual it's a bit more complicated. Loading the state dict works only if the model architecture is exactly the same as the checkpoint architecture. If I create a model with a different architecture, this fails.
# Try this model = fc_model.Network(784, 10, [400, 200, 100]) # This will throw an error because the tensor sizes are wrong! model.load_state_dict(state_dict)
_____no_output_____
MIT
1. Introduction/.ipynb_checkpoints/Part 6 - Saving and Loading Models-checkpoint.ipynb
Not-A-Builder/DL-PyTorch
This means we need to rebuild the model exactly as it was when trained. Information about the model architecture needs to be saved in the checkpoint, along with the state dict. To do this, you build a dictionary with all the information you need to compeletely rebuild the model.
checkpoint = {'input_size': 784, 'output_size': 10, 'hidden_layers': [each.out_features for each in model.hidden_layers], 'state_dict': model.state_dict()} torch.save(checkpoint, 'checkpoint.pth')
_____no_output_____
MIT
1. Introduction/.ipynb_checkpoints/Part 6 - Saving and Loading Models-checkpoint.ipynb
Not-A-Builder/DL-PyTorch
Now the checkpoint has all the necessary information to rebuild the trained model. You can easily make that a function if you want. Similarly, we can write a function to load checkpoints.
def load_checkpoint(filepath): checkpoint = torch.load(filepath) model = fc_model.Network(checkpoint['input_size'], checkpoint['output_size'], checkpoint['hidden_layers']) model.load_state_dict(checkpoint['state_dict']) return model model = ...
Network( (hidden_layers): ModuleList( (0): Linear(in_features=784, out_features=400, bias=True) (1): Linear(in_features=400, out_features=200, bias=True) (2): Linear(in_features=200, out_features=100, bias=True) ) (output): Linear(in_features=100, out_features=10, bias=True) (dropout): Dropout(p=0.5...
MIT
1. Introduction/.ipynb_checkpoints/Part 6 - Saving and Loading Models-checkpoint.ipynb
Not-A-Builder/DL-PyTorch
Modules, Packages and Classes When working with Python interactively, as we have thus far been doing, all functions that we define are available only within that notebook. This would similarly be the case if we were to write a simple script within an IDE.Thus, in order to write more complex programs it is important t...
def mysum(x,y): return x+y def mult(x,y): return x*y def divide(x,y): return x/y
_____no_output_____
Apache-2.0
2.3_Modules_and_Packages.ipynb
estherpuyol/BHF_Python_workshop
Now we will call these functions in a separate Python script 'apply_simple_functions.py'. Open these files, in your IDE. Try running 'apply_simple_functions.py'. Note the initial line which loads the module and renames it in shorthand (see also below); it is important that this module file is available in the same fold...
from BHF_Python_workshop import simplemath as sm # load module # define variables x=2 y=5 print('output sum of x and y:', sm.mysum(x,y)) print('output product of x and y:', sm.mult(x,y)) print('output quotient of x and y:', sm.divide(x,y))
output sum of x and y: 7 output product of x and y: 10 output quotient of x and y: 0.4
Apache-2.0
2.3_Modules_and_Packages.ipynb
estherpuyol/BHF_Python_workshop
The functions defined in the module are now available in the script (and this notebook) by simply prefixing with the name given to the module when it is imported. It is also possible to just load selective functions from a module using the call
from BHF_Python_workshop.simplemath import mysum as simplesum # note use of 'as' here, allows the change of names of functions print('output sum of x and y:', simplesum(x,y))
output sum of x and y: 7
Apache-2.0
2.3_Modules_and_Packages.ipynb
estherpuyol/BHF_Python_workshop
Alternatively all functions can be imported using *
from simplemath import * print('output sum of x and y:', mysum(x,y)) print('output product of x and y:', mult(x,y)) print('output quotient of x and y:', divide(x,y))
_____no_output_____
Apache-2.0
2.3_Modules_and_Packages.ipynb
estherpuyol/BHF_Python_workshop
Standard Modules Some modules come packaged with Python as standard. Useful examples include, ```os```:
import os dirname='/some/path/to/directory' filename='myfile.txt' print('my file path is:', os.path.join(dirname,filename)) # intelligent concatenation of path components print('my file path exists:', os.path.exists(os.path.join(dirname,filename))) # checks whether file exists
_____no_output_____
Apache-2.0
2.3_Modules_and_Packages.ipynb
estherpuyol/BHF_Python_workshop
```os``` performs useful operations on filenames; for more examples see https://docs.python.org/3/library/os.path.htmlmodule-os.path. Also, ```sys```: this allows the addition or removal of paths from your python search path (https://docs.python.org/3/library/sys.htmlmodule-sys), and is useful when you want to add the ...
import sys print('system path:', sys.path) # add path to your system sys.path.append('/some/path/') print('after append system path:', sys.path) #remove path from your system sys.path.remove('/some/path/')
_____no_output_____
Apache-2.0
2.3_Modules_and_Packages.ipynb
estherpuyol/BHF_Python_workshop
```random``` is a random number generator
import random mult=25 rand_int = random.randint(1, 10) #Β random int in defined range rand_float = random.random() # random float between 0 and 1 rand_float_gen = random.random()*mult # random float between 0 and 25 print('my random integer is: ', rand_int) print('my random float (between 0 and 1) is: ', rand_float) ...
_____no_output_____
Apache-2.0
2.3_Modules_and_Packages.ipynb
estherpuyol/BHF_Python_workshop
math is Python's standard math module:
import math x=2.2 y=4 print('ceil of {} is {}'. format(x,math.ceil(x))) print('{} to the power {} is {}'.format(x,y,math.pow(x,y))) print('The natural log of {} is {}'.format(x,math.log(x)))
_____no_output_____
Apache-2.0
2.3_Modules_and_Packages.ipynb
estherpuyol/BHF_Python_workshop
For an extensive list of all standard math operations see https://docs.python.org/3/library/math.htmlmodule-math. Finally, copy which was introduced in the previous notebook for generation of hard copies of objects in memory (https://docs.python.org/3/library/copy.html). For more examples of standard modules see https:...
class MyClass: """A simple example class""" def __init__(self): # constructor self.data = [] x=MyClass() #Β creates new instance of class
_____no_output_____
Apache-2.0
2.3_Modules_and_Packages.ipynb
estherpuyol/BHF_Python_workshop
And, in practice, the statements inside a class definition will usually be method (object function) definitions e.g. :
class MyClass: """A simple example class""" def __init__(self): self.data = [] def f(self): # method return 'hello world' x=MyClass() #Β creates new instance of class print(x.f()) # now run the class sub function f
_____no_output_____
Apache-2.0
2.3_Modules_and_Packages.ipynb
estherpuyol/BHF_Python_workshop
Understanding of the formatting of Python classes is essential knoweldge for development of advanced python packages. However, in this course we will stick to relatively simple scripting. We leave investigation of more advanced features to the reader. For more materials on Python Classes see: https://docs.python.org/3/...
_____no_output_____
Apache-2.0
2.3_Modules_and_Packages.ipynb
estherpuyol/BHF_Python_workshop
Examples of the supported features in Autograd Before using Autograd for more complicated calculations, it might be useful to experiment with what kind of functions Autograd is capable of finding the gradient of. The following Python functions are just meant to illustrate what Autograd can do, but please feel free to ...
import autograd.numpy as np from autograd import grad
_____no_output_____
CC0-1.0
doc/src/GradientOptim/autodiff/examples_allowed_functions.ipynb
ndavila/MachineLearningMSU
Supported functions Here are some examples of supported function implementations that Autograd can differentiate. Keep in mind that this list over examples is not comprehensive, but rather explores which basic constructions one might often use. Functions using simple arithmetics
def f1(x): return x**3 + 1 f1_grad = grad(f1) # Remember to send in float as argument to the computed gradient from Autograd! a = 1.0 # See the evaluated gradient at a using autograd: print("The gradient of f1 evaluated at a = %g using autograd is: %g"%(a,f1_grad(a))) # Compare with the analytical derivative, th...
The gradient of f1 evaluated at a = 1 using autograd is: 3 The gradient of f1 evaluated at a = 1 by finding the analytic expression is: 3
CC0-1.0
doc/src/GradientOptim/autodiff/examples_allowed_functions.ipynb
ndavila/MachineLearningMSU
Functions with two (or more) arguments To differentiate with respect to two (or more) arguments of a Python function, Autograd need to know at which variable the function if being differentiated with respect to.
def f2(x1,x2): return 3*x1**3 + x2*(x1 - 5) + 1 # By sending the argument 0, Autograd will compute the derivative w.r.t the first variable, in this case x1 f2_grad_x1 = grad(f2,0) # ... and differentiate w.r.t x2 by sending 1 as an additional arugment to grad f2_grad_x2 = grad(f2,1) x1 = 1.0 x2 = 3.0 print("Eva...
Evaluating at x1 = 1, x2 = 3 ------------------------------ The derivative of f2 w.r.t x1: 12 The analytical derivative of f2 w.r.t x1: 12 The derivative of f2 w.r.t x2: -4 The analytical derivative of f2 w.r.t x2: -4
CC0-1.0
doc/src/GradientOptim/autodiff/examples_allowed_functions.ipynb
ndavila/MachineLearningMSU
Note that the grad function will not produce the true gradient of the function. The true gradient of a function with two or more variables will produce a vector, where each element is the function differentiated w.r.t a variable. Functions using the elements of its argument directly
def f3(x): # Assumes x is an array of length 5 or higher return 2*x[0] + 3*x[1] + 5*x[2] + 7*x[3] + 11*x[4]**2 f3_grad = grad(f3) x = np.linspace(0,4,5) # Print the computed gradient: print("The computed gradient of f3 is: ", f3_grad(x)) # The analytical gradient is: (2, 3, 5, 7, 22*x[4]) f3_grad_analytical = np...
The computed gradient of f3 is: [ 2. 3. 5. 7. 88.] The analytical gradient of f3 is: [ 2. 3. 5. 7. 88.]
CC0-1.0
doc/src/GradientOptim/autodiff/examples_allowed_functions.ipynb
ndavila/MachineLearningMSU
Note that in this case, when sending an array as input argument, the output from Autograd is another array. This is the true gradient of the function, as opposed to the function in the previous example. By using arrays to represent the variables, the output from Autograd might be easier to work with, as the output is c...
def f4(x): return np.sqrt(1+x**2) + np.exp(x) + np.sin(2*np.pi*x) f4_grad = grad(f4) x = 2.7 # Print the computed derivative: print("The computed derivative of f4 at x = %g is: %g"%(x,f4_grad(x))) # The analytical derivative is: x/sqrt(1 + x**2) + exp(x) + cos(2*pi*x)*2*pi f4_grad_analytical = x/np.sqrt(1 + x**2...
The computed derivative of f4 at x = 2.7 is: 13.8759 The analytical gradient of f4 is: 13.87586944687107
CC0-1.0
doc/src/GradientOptim/autodiff/examples_allowed_functions.ipynb
ndavila/MachineLearningMSU
Functions using if-else tests
def f5(x): if x >= 0: return x**2 else: return -3*x + 1 f5_grad = grad(f5) x = 2.7 # Print the computed derivative: print("The computed derivative of f5 at x = %g is: %g"%(x,f5_grad(x))) # The analytical derivative is: # if x >= 0, then 2*x # else -3 if x >= 0: f5_grad_analytical = 2*x ...
The computed derivative of f5 is: 5.4 The analytical derivative of f5 is: 5.4
CC0-1.0
doc/src/GradientOptim/autodiff/examples_allowed_functions.ipynb
ndavila/MachineLearningMSU
Functions using for- and while loops
def f6_for(x): val = 0 for i in range(10): val = val + x**i return val def f6_while(x): val = 0 i = 0 while i < 10: val = val + x**i i = i + 1 return val f6_for_grad = grad(f6_for) f6_while_grad = grad(f6_while) x = 0.5 # Print the computed derivaties of f6_for and...
The computed derivative of f6_for at x = 0.5 is: 3.95703 The computed derivative of f6_while at x = 0.5 is: 3.95703 The analytical derivative of f6 at x = 0.5 is: 3.95703
CC0-1.0
doc/src/GradientOptim/autodiff/examples_allowed_functions.ipynb
ndavila/MachineLearningMSU
Functions using recursion
def f7(n): # Assume that n is an integer if n == 1 or n == 0: return 1 else: return n*f7(n-1) f7_grad = grad(f7) n = 2.0 print("The computed derivative of f7 at n = %d is: %g"%(n,f7_grad(n))) # The function f7 is an implementation of the factorial of n. # By using the product rule, one can fi...
The computed derivative of f7 at n = 2 is: 1 The analytical derivative of f7 at n = 2 is: 1
CC0-1.0
doc/src/GradientOptim/autodiff/examples_allowed_functions.ipynb
ndavila/MachineLearningMSU
Note that if n is equal to zero or one, Autograd will give an error message. This message appears when the output is independent on input. Unsupported functions Autograd supports many features. However, there are some functions that is not supported (yet) by Autograd. Assigning a value to the variable being differen...
def f8(x): # Assume x is an array x[2] = 3 return x*2 f8_grad = grad(f8) x = 8.4 print("The derivative of f8 is:",f8_grad(x))
_____no_output_____
CC0-1.0
doc/src/GradientOptim/autodiff/examples_allowed_functions.ipynb
ndavila/MachineLearningMSU
Here, Autograd tells us that an 'ArrayBox' does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible. The syntax a.dot(b) when finding the dot produc...
def f9(a): # Assume a is an array with 2 elements b = np.array([1.0,2.0]) return a.dot(b) f9_grad = grad(f9) x = np.array([1.0,0.0]) print("The derivative of f9 is:",f9_grad(x))
_____no_output_____
CC0-1.0
doc/src/GradientOptim/autodiff/examples_allowed_functions.ipynb
ndavila/MachineLearningMSU
Here we are told that the 'dot' function does not belong to Autograd's version of a Numpy array. To overcome this, an alternative syntax which also computed the dot product can be used:
def f9_alternative(x): # Assume a is an array with 2 elements b = np.array([1.0,2.0]) return np.dot(x,b) # The same as x_1*b_1 + x_2*b_2 f9_alternative_grad = grad(f9_alternative) x = np.array([3.0,0.0]) print("The gradient of f9 is:",f9_alternative_grad(x)) # The analytical gradient of the dot product of ve...
The gradient of f9 is: [1. 2.]
CC0-1.0
doc/src/GradientOptim/autodiff/examples_allowed_functions.ipynb
ndavila/MachineLearningMSU