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
Plot per year, scenario, market
df_plot=(pd.DataFrame(data_plot.groupby(['YYY', 'Scenario', 'Market'])['Val'].agg('sum')/1000000*size_t)) df_plot df_plot.reset_index(inplace=True) df_plot for scenario in Scenarios: df_plot plt.bar(df_plot.YYY, df_plot.Val) for i in years: spp_plot[data.SSS.isin([i])][ccc[:2]].plot(figsize=(16,9), lw=lw) ...
_____no_output_____
ISC
base/auxils/plotting_tool/CurtailmentHourly.ipynb
juanjerezm/Balmorel_code
Stratified Sampling - Example 2- Author: Michael D. Shields- Date: June 05, 2018 In this example, the stratified sampling method is employed to generate samples from an exponential distribution with strata defined by a text file. The method illustrates stratified sampling for cases where the space is not divided equal...
from UQpy.SampleMethods import STS import numpy as np import matplotlib.pyplot as plt import time from scipy.stats import expon
_____no_output_____
MIT
example/STS/STS_Example2/STS_Example2.ipynb
volpatto/UQpy
Run STS for 6 samples. - 2 dimensions - Strata are defined by the file 'strata.txt' - The strata are unequally sized and are not equal in all dimensions. Run stratified sampling
x_sts = STS(dimension=2, dist_name='Exponential', dist_params=np.ones(2), input_file='strata.txt') fig, ax = plt.subplots() plt.title('Stratified Sample - Exponential') plt.scatter(x_sts.samples[:, 0], x_sts.samples[:, 1]) plt.plot(expon.ppf([0.0, 0.5, 0.5, 0.0],1,1),expon.ppf([0.0, 0.0, 0.333, 0.333],1,1),'b') plt.plo...
_____no_output_____
MIT
example/STS/STS_Example2/STS_Example2.ipynb
volpatto/UQpy
Return the sample weights
print(x_sts.strata.weights) print(x_sts.samples)
_____no_output_____
MIT
example/STS/STS_Example2/STS_Example2.ipynb
volpatto/UQpy
Mining the Social Web, 2nd Edition Appendix B: OAuth PrimerThis IPython Notebook provides an interactive way to follow along with and explore the numbered examples from [_Mining the Social Web (3rd Edition)_](http://bit.ly/Mining-the-Social-Web-3E). The intent behind this notebook is to reinforce the concepts from the...
import json from flask import Flask, request from threading import Timer from IPython.display import IFrame from IPython.display import display from IPython.display import Javascript as JS import twitter from twitter.oauth_dance import parse_oauth_tokens from twitter.oauth import read_token_file, write_token_file OAU...
_____no_output_____
BSD-2-Clause
notebooks/_Appendix B - OAuth Primer.ipynb
alexistrator/Mining-the-Social-Web-3rd-Edition
Facebook OAuth 2.0 Flow with IPython NotebookFacebook implements OAuth 2.0 as its standard authentication mechanism, and this example demonstrates how get an access token for making API requests once you've created an app and gotten a "client id" value that can be used to initiate an OAuth flow. Note that you will nee...
import urllib from flask import Flask, request from threading import Timer from IPython.display import display from IPython.display import Javascript as JS # XXX: Get this value from your Facebook application's settings for the OAuth flow # at https://developers.facebook.com/apps APP_ID = '' # This value is where F...
_____no_output_____
BSD-2-Clause
notebooks/_Appendix B - OAuth Primer.ipynb
alexistrator/Mining-the-Social-Web-3rd-Edition
LinkedIn OAuth 2.0 Flow with IPython NotebookLinkedIn implements OAuth 2.0 as one of its standard authentication mechanism, and "Example 3" demonstrates how to use it to get an access token for making API requests once you've created an app and gotten the "API Key" and "Secret Key" values that are part of the OAuth fl...
import os from threading import Timer from flask import Flask, request from linkedin import linkedin # pip install python3-linkedin from IPython.display import display from IPython.display import Javascript as JS # XXX: Get these values from your application's settings for the OAuth flow CONSUMER_KEY = '' CONSUMER_SE...
_____no_output_____
BSD-2-Clause
notebooks/_Appendix B - OAuth Primer.ipynb
alexistrator/Mining-the-Social-Web-3rd-Edition
2 Data AcquisitionIn this chapter we will discuss data acquisition and data formatting for four online Assyriological projects: [ORACC](http://oracc.org) (2.1), [ETCSL](https://etcsl.orinst.ox.ac.uk/), (2.2) [CDLI](http://cdli.ucla.edu) (2.3) and [BDTNS](http://bdtns.filol.csic.es/) (2.4). The data in [CDLI](http://cd...
import json import panel as pn pn.extension() with open('P100001.json', 'r', encoding='utf8') as p: P100001 = json.load(p) json_object = pn.pane.JSON(P100001, name='P100001', depth=1, height=300, width=500, theme = 'light') json_object
_____no_output_____
CC0-1.0
_build/html/_sources/2_Data_Acquisition/2_Data_Acquisition.ipynb
niekveldhuis/compass
Hello World API with Flask
# We'll create the script - we created our folder structure with cookiecutter import os hello_world_script_file = os.path.join(os.path.pardir,'src','models','hello_world_api2.py') %%writefile $hello_world_script_file from flask import Flask, request app = Flask(__name__) @app.route('/api', methods=['POST']) #api wil...
_____no_output_____
MIT
notebooks/4.0-gr-Build_Machine_Learning_API.ipynb
graemerenfrew/titanic
API for Machine Learning with Flask
# We'll create the script - we created our folder structure with cookiecutter import os machine_learning_api_script_file = os.path.join(os.path.pardir,'src','models','machine_learning_api.py') %%writefile $machine_learning_api_script_file # Now this is the code we used from all the previous steps we performed. from ...
_____no_output_____
MIT
notebooks/4.0-gr-Build_Machine_Learning_API.ipynb
graemerenfrew/titanic
Invoke API using the Requests feature
import os import numpy as np import pandas as pd processed_data_path = os.path.join(os.path.pardir,'data','processed') train_file_path = os.path.join(processed_data_path, 'train.csv') train_df = pd.read_csv(train_file_path) # the processed training data will be used to check the API is working # let's use 5 passengers ...
_____no_output_____
MIT
notebooks/4.0-gr-Build_Machine_Learning_API.ipynb
graemerenfrew/titanic
This is not at all what I expected, but it makes sense as the absolute magnitude increases with both hole size and distance from edge, so to see the feature matching in a colorbar one would need to normalize the peaks to each other or something similar.
for i,hr in enumerate(hrs): plt.plot(separations, harms_rad[:,i,:], 'o-') plt.legend(['newtonian', '$\lambda=1\mu m$', '$\lambda=10\mu m$']) plt.xlabel('modulation separation [$\mu m$]', fontsize=18) plt.ylabel('harmonic strength [N/$\sqrt{Hz}$]', fontsize=18) # plt.axvline(hr, ls='--', alpha=0.7) ...
_____no_output_____
MIT
notebooks/modulated.ipynb
emmetthough/gravity_sim
Transforms Helpers
#exports def type_hints(f): "Same as `typing.get_type_hints` but returns `{}` if not allowed type" return typing.get_type_hints(f) if isinstance(f, typing._allowed_types) else {} #export def anno_ret(func): "Get the return annotation of `func`" if not func: return None ann = type_hints(func) if ...
_____no_output_____
Apache-2.0
dev/02_data_transforms.ipynb
tianjianjiang/fastai_dev
Types
#export @delegates(plt.subplots, keep=True) def subplots(nrows=1, ncols=1, **kwargs): fig,ax = plt.subplots(nrows,ncols,**kwargs) if nrows*ncols==1: ax = array([ax]) return fig,ax #export class TensorImageBase(TensorBase): _show_args = {'cmap':'viridis'} def show(self, ctx=None, **kwargs): r...
_____no_output_____
Apache-2.0
dev/02_data_transforms.ipynb
tianjianjiang/fastai_dev
TypeDispatch -
#export class TypeDispatch: "Dictionary-like object; `__getitem__` matches keys of types using `issubclass`" def __init__(self, *funcs): self.funcs,self.cache = {},{} for f in funcs: self.add(f) self.inst = None def _reset(self): self.funcs = {k:self.funcs[k] for k in sorted...
_____no_output_____
Apache-2.0
dev/02_data_transforms.ipynb
tianjianjiang/fastai_dev
Transform -
#export class _TfmDict(dict): def __setitem__(self,k,v): if k=='_': k='encodes' if k not in ('encodes','decodes') or not isinstance(v,Callable): return super().__setitem__(k,v) if k not in self: super().__setitem__(k,TypeDispatch()) res = self[k] res.add(v) #export class _Tfm...
_____no_output_____
Apache-2.0
dev/02_data_transforms.ipynb
tianjianjiang/fastai_dev
Base class that delegates `__call__` and `decode` to `encodes` and `decodes`, doing nothing if param annotation doesn't match type. If called with listy `x` then it calls function with each item (unless `whole_typle`, in which case it's passed directly as a whole). The function (if matching 1st param type) will cast th...
class A(Transform): pass @A def encodes(self, x): return x+1 f1 = A() test_eq(f1(1), 2) class B(A): pass f2 = B() test_eq(f2(1), 2) class A(Transform): pass f3 = A() test_eq_type(f3(2), 2) test_eq_type(f3.decode(2.0), 2.0)
_____no_output_____
Apache-2.0
dev/02_data_transforms.ipynb
tianjianjiang/fastai_dev
`Transform` can be used as a decorator, to turn a function into a `Transform`.
@Transform def f(x): return x//2 test_eq_type(f(2), 1) test_eq_type(f.decode(2.0), 2.0)
_____no_output_____
Apache-2.0
dev/02_data_transforms.ipynb
tianjianjiang/fastai_dev
You can derive from `Transform` and use either `_` or `encodes` for your encoding function.
class A(Transform): def _(self, x:TensorImage): return -x f = A() t = f(im_t) test_eq(t, -im_t) test_eq(f(1), 1) test_eq(type(t), TensorImage) f
_____no_output_____
Apache-2.0
dev/02_data_transforms.ipynb
tianjianjiang/fastai_dev
Without return annotation we get an `Int` back since that's what was passed.
class A(Transform): pass @A def _(self, x:Int): return x//2 # `_` is an abbreviation for `encodes` @A def encodes(self, x:float): return x+1 f = A() test_eq_type(f(Int(2)), Int(1)) test_eq_type(f(2), 2) test_eq_type(f(2.), 3.)
_____no_output_____
Apache-2.0
dev/02_data_transforms.ipynb
tianjianjiang/fastai_dev
Without return annotation we don't cast if we're not a subclass of the input type.
class A(Transform): def encodes(self, x:Int): return x/2 def _(self, x:float): return x+1 f = A() test_eq_type(f(Int(2)), 1.) test_eq_type(f(2), 2) test_eq_type(f(Float(2.)), Float(3.))
_____no_output_____
Apache-2.0
dev/02_data_transforms.ipynb
tianjianjiang/fastai_dev
With return annotation `None` we get back whatever Python creates usually.
def func(x)->None: return x/2 f = Transform(func) test_eq_type(f(2), 1.) test_eq_type(f(2.), 1.)
_____no_output_____
Apache-2.0
dev/02_data_transforms.ipynb
tianjianjiang/fastai_dev
Since `decodes` has no return annotation, but `encodes` created an `Int` and we pass that result here to `decode`, we end up with an `Int`.
def func(x): return Int(x+1) def dec (x): return x-1 f = Transform(func,dec) t = f(1) test_eq_type(t, Int(2)) test_eq_type(f.decode(t), Int(1))
_____no_output_____
Apache-2.0
dev/02_data_transforms.ipynb
tianjianjiang/fastai_dev
If the transform has `filt` then it's only applied if `filt` param matches.
f.filt = 1 test_eq(f(1, filt=1),2) test_eq_type(f(1, filt=0), 1) class A(Transform): def encodes(self, xy): x,y=xy; return (x+y,y) def decodes(self, xy): x,y=xy; return (x-y,y) f = A(as_item=True) t = f((1,2)) test_eq(t, (3,2)) test_eq(f.decode(t), (1,2)) f.filt = 1 test_eq(f((1,2), filt=1), (3,2)) test_eq(f(...
_____no_output_____
Apache-2.0
dev/02_data_transforms.ipynb
tianjianjiang/fastai_dev
TupleTransform
#export class TupleTransform(Transform): "`Transform` that always treats `as_item` as `False`" as_item_force=False #export class ItemTransform (Transform): "`Transform` that always treats `as_item` as `True`" as_item_force=True def float_to_int(x:(float,int)): return Int(x) f = TupleTransform(float_to_...
_____no_output_____
Apache-2.0
dev/02_data_transforms.ipynb
tianjianjiang/fastai_dev
Non-type-constrained functions are applied to all elements of a tuple.
class A(TupleTransform): pass @A def _(self, x): return x+1 @A def decodes(self, x): return x-1 f = A() t = f((1,2.0)) test_eq_type(t, (2,3.0)) test_eq_type(f.decode(t), (1,2.0))
_____no_output_____
Apache-2.0
dev/02_data_transforms.ipynb
tianjianjiang/fastai_dev
Type-constrained functions are applied to only matching elements of a tuple, and return annotations are only applied where matching.
class B(TupleTransform): def encodes(self, x:int): return Int(x+1) def encodes(self, x:str): return x+'1' def decodes(self, x:Int): return x//2 f = B() start = (1.,2,'3') t = f(start) test_eq_type(t, (1.,Int(3),'31')) test_eq(f.decode(t), (1.,Int(1),'31'))
_____no_output_____
Apache-2.0
dev/02_data_transforms.ipynb
tianjianjiang/fastai_dev
The same behavior also works with `typing` module type classes.
class A(Transform): pass @A def _(self, x:numbers.Integral): return x+1 @A def _(self, x:float): return x*3 @A def decodes(self, x:int): return x-1 f = A() start = 1.0 t = f(start) test_eq(t, 3.) test_eq(f.decode(t), 3) f = A(as_item=False) start = (1.,2,3.) t = f(start) test_eq(t, (3.,3,9.)) test_eq(f.decode(t), (3....
_____no_output_____
Apache-2.0
dev/02_data_transforms.ipynb
tianjianjiang/fastai_dev
Transform accepts lists
def a(x): return L(x_+1 for x_ in x) def b(x): return L(x_-1 for x_ in x) f = TupleTransform(a,b) t = f((L(1,2),)) test_eq(t, (L(2,3),)) test_eq(f.decode(t), (L(1,2),))
_____no_output_____
Apache-2.0
dev/02_data_transforms.ipynb
tianjianjiang/fastai_dev
Export -
#hide from local.notebook.export import notebook2script notebook2script(all_fs=True)
Converted 00_test.ipynb. Converted 01_core.ipynb. Converted 01a_torch_core.ipynb. Converted 01b_script.ipynb. Converted 01c_dataloader.ipynb. Converted 02_data_transforms.ipynb. Converted 03_data_pipeline.ipynb. Converted 05_data_core.ipynb. Converted 06_data_source.ipynb. Converted 07_vision_core.ipynb. Converted 08_p...
Apache-2.0
dev/02_data_transforms.ipynb
tianjianjiang/fastai_dev
Text Generation with Neural NetworksImport necessary packages for preprocessing, model building, etc. We follow the steps described in the theoretical part of this summer school as follows:0. Define Reseach Goal (already done)2. Retrieve Data3. Prepare Data4. Explore Data5. Model Data6. Present and automate Model
from keras.callbacks import LambdaCallback from keras.models import Sequential from keras.layers import Dense, Activation from keras.layers import LSTM from keras.optimizers import RMSprop from keras.utils.data_utils import get_file from keras.models import load_model from keras import backend as K import numpy as np i...
_____no_output_____
MIT
src/Textgen_Notebook.ipynb
spinfo/LSS_DLwithText
1. Retrieve DataLoad your data! You can pick up data from everywhere, such as plain text, HTML, source code, etc.You can either automatically download with Keras get_file function or download it manually and import it in this notebook. Example Data Set[trump.txt](https://raw.githubusercontent.com/harshilkamdar/trump-t...
#path = get_file('trump.txt', origin='https://raw.githubusercontent.com/harshilkamdar/trump-tweets/master/trump.txt') text = io.open('resources/shakespeare.txt', encoding='utf-8').read().lower() print('corpus length:', len(text))
_____no_output_____
MIT
src/Textgen_Notebook.ipynb
spinfo/LSS_DLwithText
2. Prepare DataAs described in the theoretical part of this workshop we need to convert our text into a word embedding that can be processed by a (later) defined Neural Network. 2.1. Create Classes The goal after this step is to have a variable which contains the distinct characters of the text. Characters can be le...
chars = sorted(list(set(text))) print('total chars:', len(chars))
_____no_output_____
MIT
src/Textgen_Notebook.ipynb
spinfo/LSS_DLwithText
2.2. Create Training SetIn the following section we need to create our test set based on our text. The idea is to map a sequence of characters to a class. In this case, a class is one of our distinct characters defined in the previous task. This means that a sequence of characters predicts the next character. This is ...
seqlen = 40 # Sequence length parameter step = 5 # Determines the how many characters the window should be shifted in the text sequences = [] # List of sequences char_class = [] # Corresponding class of each sequence for i in range(0, len(text) - seqlen, step): sequences.append(text[i: i + seqlen]) char_cl...
_____no_output_____
MIT
src/Textgen_Notebook.ipynb
spinfo/LSS_DLwithText
2.3. Check your DataNow that we processed our data, it's time to understand what we have built so far.
for idx in range(len(sequences[:10])): print(sequences[idx], ":" , char_class[idx]) # Print from 1st to 10th character chars[:10] # Print from 150th to 160th character :-) chars[150:160]
_____no_output_____
MIT
src/Textgen_Notebook.ipynb
spinfo/LSS_DLwithText
2.4. Vectorization of Training SequencesThe following section describes the desired form of our final training set. text: "hallo. ".As defined above we have a couple of sequences mapping to the next appearing character in the text (e.g. "ha" mapping to "l"). But first of all, we transform each sequence to the followin...
# Indexed characters as dictionary char_indices = dict((c, i) for i, c in enumerate(chars)) # Both matrices will initialized with zeros training_set = np.zeros((len(sequences), seqlen, len(chars)), dtype=np.bool) target_char = np.zeros((len(sequences), len(chars)), dtype=np.bool) for i, sequence in enumerate(sequences...
_____no_output_____
MIT
src/Textgen_Notebook.ipynb
spinfo/LSS_DLwithText
3. Explore Data
# Let's check the shape of the training_set training_set.shape
_____no_output_____
MIT
src/Textgen_Notebook.ipynb
spinfo/LSS_DLwithText
Output: (x, y, z) x = number of all sequences to test y = window size to predict the next character z = number of all appearing characters in text (for one-hot-enconding)
# Let's check the shape of the target_char (act as our target classes) target_char.shape
_____no_output_____
MIT
src/Textgen_Notebook.ipynb
spinfo/LSS_DLwithText
Output: (x, y) x = number of all sequences to test y = the mapping of each sequence to the next character 4. Model dataLet's get down to business! Create your model.Try different model configuration (see [keras doc](https://keras.io/models/about-keras-models/about-keras-models))
model = Sequential() # build the model: a LSTM model = Sequential() model.add(LSTM(128, input_shape=(seqlen, len(chars)))) model.add(Dense(len(chars))) model.add(Activation('softmax')) optimizer = RMSprop(lr=0.01) model.compile(loss='categorical_crossentropy', optimizer=optimizer) model.summary() def getNextCharIdx(...
_____no_output_____
MIT
src/Textgen_Notebook.ipynb
spinfo/LSS_DLwithText
5. Evaluate ModelWe are not at the sweet part of the model. Let's fit our model and see what it prints!
model.fit(training_set, target_char, batch_size=128, epochs=150, callbacks=[print_callback])
_____no_output_____
MIT
src/Textgen_Notebook.ipynb
spinfo/LSS_DLwithText
Present and AutomateHaving a model trained for hours is a valuable asset! We need now to store the model and use it to solve the problem we wanted to solve with Machine Learning. Keras has a simple function to save a model to the local file system and also a function to load the model again and have it ready for our t...
model.save('shakespeareModel.h5') model = load_model('shakespeareModel.h5')
_____no_output_____
MIT
src/Textgen_Notebook.ipynb
spinfo/LSS_DLwithText
Gold Standard Cosine Similarity
gold_standard = new_labels.columns[1:7] gold_standard cs_annotators = pd.DataFrame(columns=gold_standard) for x in gold_standard: cosine_scores_method_x=[] #average cosine score for each method for y in gold_standard: cosine_score = [] for index,row in new_labels.iterrows(): cosine...
_____no_output_____
MIT
String cosine similarity score-1750newsheadlines.ipynb
zarmeen92/ReadiTopics-Topic-Labeling
Variant of the Blocked Input Model in which the stop process decelerates the go process by a rate that varies across trials
import numpy import random import matplotlib.pyplot as plt import matplotlib import seaborn import pandas import matplotlib.patches as patches from matplotlib.ticker import FormatStrFormatter %matplotlib inline params={'mugo':.2, 'mustop':.8, 'threshold':60, 'nondecisiongo':50, 'nondec...
_____no_output_____
MIT
model_blocked_input.ipynb
levolz/ContextDependence
Creando nuestro propio KNN
import numpy as np import matplotlib.pyplot as plt from matplotlib import style import warnings from math import sqrt from collections import Counter dataset = { 'k' : [[1,2],[2,3], [3,1]], 'r' : [[6,5],[7,7],[8,6]] } new_point = [5,7] [[plt.scatter(ii[0], ii[1], s=50, color=i) for ii in dataset[i]] for i in da...
_____no_output_____
MIT
notebooks/T9 - 2 - K Nearest Neighbors Implementation.ipynb
ledvir26/Machine-Learning-with-Python
Aplicando nueswtro KNN al Dataset del Cancer
import pandas as pd df = pd.read_csv("../datasets/cancer/breast-cancer-wisconsin.data.txt") df.replace("?", -999999, inplace=True) df.columns = ["name", "V1", "V2", "V3", "V4", "V5", "V6", "V7", "V8", "V9", "class"] df.drop(["name"], 1, inplace=True) df.head() full_data = df.astype(float).values.tolist() full_data impo...
_____no_output_____
MIT
notebooks/T9 - 2 - K Nearest Neighbors Implementation.ipynb
ledvir26/Machine-Learning-with-Python
ELEC 400M / EECE 571M Assignment 2: Neural networks(This assignment is a modified version of an assignment used in ECE 421 at the University of Toronto and kindly made available to us by the instructor.)In this assignment, you will implement a neural network model for multi-class classification. The purpose is to demo...
%matplotlib inline import matplotlib.pyplot as plt import numpy as np def loadData(): with np.load('notMNIST.npz') as data: Data, Target = data['images'], data['labels'] np.random.seed(521) randIndx = np.arange(len(Data)) np.random.shuffle(randIndx) Data = Data[randIndx]/255....
_____no_output_____
Apache-2.0
Assignment2/Assignment2B.ipynb
avzero07/machine-learning-course
Data preprocessing [5 points]Input data: The classification should be based on the $d=28\times 28=784$ intensity values in an image (as for Assignment 1).Output data: Since you will be performing multi-class classification, the labels will be converted into a one-hot encoding format. Please first briefly explain the m...
def convertOneHot(trainTarget, validTarget, testTarget): trainTargetOneHot = np.zeros([trainTarget.shape[0],10]) trainTargetOneHot[np.arange(trainTarget.size),trainTarget]=1 validTargetOneHot = np.zeros([validTarget.shape[0],10]) validTargetOneHot[np.arange(validTarget.size),validTarget] = 1 ...
_____no_output_____
Apache-2.0
Assignment2/Assignment2B.ipynb
avzero07/machine-learning-course
Structure of the network [2 points]Sketch the structure of the network to classify the letters from the data set. Identify the dimensions of the network layers, include the activation functions, and do not forget the bias nodes. (You may sketch this by hand and upload a photo of your sketch.) **Solution:***Note: A sca...
def relu(x): return np.maximum(0,x) def softmax(x): maxes = np.amax(x,axis=0) maxes = maxes.reshape(1,maxes.shape[0]) x = x - maxes op = np.exp(x)/sum(np.exp(x)) return op def computeLayer(x,W): return np.matmul(W.T,x) def CE(target, prediction): return (-1/target.shape[1])*(np.sum(np.mu...
_____no_output_____
Apache-2.0
Assignment2/Assignment2B.ipynb
avzero07/machine-learning-course
Backpropagation [2 points]The training of the network will be done via backpropagation. First derive the following gradients:1. $\frac{\partial E_{\mathrm{in}}}{\partial \mathbf{W}^{\mathrm{o}}}$, where $\mathbf{W}^{\mathrm{o}}$ is the weight matrix of the output layer.2. $\frac{\partial E_{\mathrm{in}}}{\partial \mat...
# Utility Functions # A. Easy ForwardProp def forwardProp(inputData,targetLabel,weightHidd,weightOp): # 1. Hidden Layer # Add Bias and Multiply with Weights to get S(1) sToHidd = computeLayer((np.append(np.ones((inputData.shape[0],1)),inputData,axis=1)).T,weightHidd) # Calculate Activation to get X...
_____no_output_____
Apache-2.0
Assignment2/Assignment2B.ipynb
avzero07/machine-learning-course
Network test [4 points]Write a script that constructs the neural network.Initialize your weight matrices by drawing the elements i.i.d. at random from a zero-mean Gaussian distribution with variance equal to $$\sigma_w^2=\frac{2}{\mbox{ of input nodes + of output nodes}}$$ (Xavier normalization http://proceedings.mlr...
# Load Data trainData, validData, testData, trainTarget, validTarget, testTarget = loadData() trainData = trainData.reshape(trainData.shape[0],-1) validData = validData.reshape(validData.shape[0],-1) testData = testData.reshape(testData.shape[0],-1) trainTargetOneHot, validTargetOneHot, testTargetOneHot = convertOneH...
_____no_output_____
Apache-2.0
Assignment2/Assignment2B.ipynb
avzero07/machine-learning-course
**Solution:****Accuracy Curves**![1000acc.png](attachment:1000acc.png)For this network with 1000 hidden nodes, the accuracies at the end of 200 Epochs are,| Dataset | Accuracy ||:----------:|:--------:|| Training | 95.45% || Validation | 92.90% || Testing | 90.89% |**Cross Entropy Loss**![1000ce.png](atta...
print('Number of Hidden Units = 500') wHid500, wOp500, ltrain500, lvalid500, ltest500, atrain500, avalid500, atest500 = constructAndTrainNN(alpha,eta,numIter,500,numInputNodes,numOpNodes,centre,trainData,trainTargetOneHot,validData,validTargetOneHot,testData,testTargetOneHot) print('Number of Hidden Units = 1500') wHi...
Number of Hidden Units = 500
Apache-2.0
Assignment2/Assignment2B.ipynb
avzero07/machine-learning-course
MNIST
root_dir = './' rescale_data = transforms.Lambda(lambda x : x/255) # Compose transformations data_transform = transforms.Compose([ transforms.Resize(32), transforms.RandomHorizontalFlip(), transforms.ToTensor(), rescale_data, #transforms.Normalize((-0.7376), (0.5795)) ]) test_transform = transforms.Compose(...
Num. training samples: 60000 Num. test samples: 10000 54000 samples used as train set 6000 samples used as val set 10000 samples used as test set
MIT
4_VALERIO_PT1_FEDERATED_SHARED_CLASSIFIER_MNIST.ipynb
CasellaJr/Federated-Transfer-Learning-using-Network-Composition
MNIST PERTURBATO
root_dir = './' rescale_data = transforms.Lambda(lambda x : x/255) class AddGaussianNoise(object): def __init__(self, mean=0., std=1.): self.std = std self.mean = mean def __call__(self, tensor): return tensor + torch.randn(tensor.size()) * self.std + self.mean def __r...
/usr/local/lib/python3.7/dist-packages/torch/nn/functional.py:718: UserWarning: Named tensors and all their associated APIs are an experimental feature and subject to change. Please do not use them for anything important until they are released as stable. (Triggered internally at /pytorch/c10/core/TensorImpl.h:1156.) ...
MIT
4_VALERIO_PT1_FEDERATED_SHARED_CLASSIFIER_MNIST.ipynb
CasellaJr/Federated-Transfer-Learning-using-Network-Composition
Quaxis Corporation for Research & Innovation 2020 Written by: JP Aldama MIT License, feel free to do whatever you want with this code. Goal: Object detection using opencv-python and numpy.***Requirements: opencv-python, numpy. It is highly recommended to install Anaconda for python 3.x. Using cv2 we will detect objec...
import cv2 import numpy as np
_____no_output_____
MIT
object_detection.ipynb
sysad-aldama/opencv-object-detection
Step 2: Path to video source and invoke VideoCapture using source video.
SOURCE = 'data/qxdatasets/test_videos/walk_australia_372020.mp4' capture = cv2.VideoCapture(SOURCE)
_____no_output_____
MIT
object_detection.ipynb
sysad-aldama/opencv-object-detection
Step 3: Read first and second frame.
ret, frame1 = capture.read() ret, frame2 = capture.read()
_____no_output_____
MIT
object_detection.ipynb
sysad-aldama/opencv-object-detection
Step 4: The main loop***4a: Calculate the absolute difference between frame1 and frame2. 4b: Convert frames to grayscale. 4c: Apply Gaussian blur to the grayscale frames.4d: Set a threshold.4e: Apply dilation, find contours.4f: For each contour found in frames apply bounding rectangles to each contour found in total c...
# KNOWN BUG: Program freezes if you try to exit the program. # Do not worry, this only applies if you are using Jupyter Notebook. # Just code in your IDE and everything will be fine. while capture.isOpened(): difference = cv2.absdiff(frame1, frame2) grayscale = cv2.cvtColor(difference, cv2.COLOR_BGR2GRAY) ...
_____no_output_____
MIT
object_detection.ipynb
sysad-aldama/opencv-object-detection
Step 5: Close the video and exit the program.
capture.release() cv2.destroyAllWindows()
_____no_output_____
MIT
object_detection.ipynb
sysad-aldama/opencv-object-detection
AG Dynamics of the Earth Jupyter notebooks Georg Kaufmann Dynamic systems: 5. Gravity Spherical harmonics---*Georg Kaufmann,Geophysics Section,Institute of Geological Sciences,Freie Universität Berlin,Germany*In this notebook, we introduce **spherical harmonics** as function space.We discuss:- **Legendre...
import matplotlib.pyplot as plt import numpy as np import math from scipy.special import lpn,lpmn from scipy.special import sph_harm
_____no_output_____
MIT
.ipynb_checkpoints/Dynamics_lab05_Ynm-checkpoint.ipynb
georgkaufmann/Lecture_Dynamics
---- Legendre polynomialsWe refer to the recursive equation for Legendre polynomials, defined on $x \in [-1,1]$:$$ P_n(x) = -\frac{n-1}{n} P_{n-2}(x) +\frac{2n-1}{n} x P_{n-1}(x),$$where we have to know the first two polynomials:$$\begin{array}{rcl}P_0(x) &=& 1 \\P_1(x) &=& x\end{array}$$We start defining the ...
nmax = 5 x = np.linspace(-1,1,51) Pn = np.zeros(len(x)*(nmax+1)).reshape(nmax+1,len(x)) print(Pn.shape) for i in range(len(x)): tmp = lpn(nmax,x[i]) for n in range(nmax+1): Pn[n,i] = tmp[0][n] plt.figure(figsize=(10,6)) plt.xlim([-1.1,1.1]) plt.ylim([-1.1,1.1]) plt.xlabel('x') plt.ylabel('P$_{n}$(x)') ...
_____no_output_____
MIT
.ipynb_checkpoints/Dynamics_lab05_Ynm-checkpoint.ipynb
georgkaufmann/Lecture_Dynamics
---- Associated Legendre polynomialsNext, we refer to the **associated Legendre Polynomials**, $P_n^m(x)$ with therecursive equation:$$(n-m+1) P_{n+1}^{m}(x) = (2n+1) x P_{n}^{m}(x) - (l+m) P_{n-1}^{m}(x)$$We normalize the calculated associated Legendre polynomials:$$P_{nm} = \sqrt{2n+1} \frac{(n-m)!}{(n+m)!} P_n^m$$
nmax = 5 mmax = nmax x = np.linspace(-1,1,101) Pnm = np.zeros(len(x)*(nmax+1)*(mmax+1)).reshape(nmax+1,mmax+1,len(x)) print(Pnm.shape) for i in range(len(x)): tmp = lpmn(mmax,nmax,x[i]) for n in range(nmax+1): for m in range(nmax+1): #print(n,m) if (m == 0): norm...
_____no_output_____
MIT
.ipynb_checkpoints/Dynamics_lab05_Ynm-checkpoint.ipynb
georgkaufmann/Lecture_Dynamics
---- Spherical harmonics$$Y_{nm}(\vartheta,\Phi) = \sqrt{\frac{2n+1}{4\pi} \frac{(n-m)!}{(n+m)!}} P_n^m(\cos\vartheta) e^{im \Phi}$$with- $\Theta \in [90,-90]$ latitude- $\vartheta \in [0,180]$ co-latitude- $\Phi \in [0,360]$ longitudeNote: $x=\cos(\vartheta)$.Note: **Latitude** $\Theta$ and **Co-latitude** $\vartheta$...
# define coordinates d2r = np.pi/180. dlong = 101 #21 dcolat = 51 #11 colat = np.linspace(0, np.pi, dcolat) long = np.linspace(0, 2*np.pi, dlong) colat, long = np.meshgrid(colat, long) print(colat.shape) n=2;m=0 Ynm = sph_harm(m, n, long, colat) fig,axs = plt.subplots(2,1,figsize=(10,10)) axs[0].set_title('P$_{'+st...
_____no_output_____
MIT
.ipynb_checkpoints/Dynamics_lab05_Ynm-checkpoint.ipynb
georgkaufmann/Lecture_Dynamics
![MLU Logo](../../data/MLU_Logo.png) Amazon Access Samples Data Set Let's apply our boosting algorithm to a real dataset! We are going to use the __Amazon Access Samples dataset__. We download this dataset from UCI ML repository from this [link](https://archive.ics.uci.edu/ml/datasets/Amazon+Access+Samples). Dua, D...
! wget https://archive.ics.uci.edu/ml/machine-learning-databases/00216/amzn-anon-access-samples.tgz ! tar -zxvf amzn-anon-access-samples.tgz
_____no_output_____
MIT-0
notebooks/lecture_5/DTE-LECTURE-5-LIGHTGBM.ipynb
dsMOOC/MLA-DTE
We have the following files:* __amzn-anon-access-samples-2.0.csv__: Employee profile data.* __amzn-anon-access-samples-history-2.0.csv__: Resource provision historyBelow, we first read the amzn-anon-access-samples-2.0.csv file (it is a large file) and use some employee fields.
import pandas as pd import random person_fields = ["PERSON_ID", "PERSON_MGR_ID", "PERSON_ROLLUP_1", "PERSON_ROLLUP_2", "PERSON_DEPTNAME", "PERSON_BUSINESS_TITLE", "PERSON_JOB_FAMILY", "PERSON_JOB_CODE"] people = {} for chunk in pd.read_csv('amzn-anon-access-samples-...
_____no_output_____
MIT-0
notebooks/lecture_5/DTE-LECTURE-5-LIGHTGBM.ipynb
dsMOOC/MLA-DTE
Now, let's read the resource provision history file. Here, we will create our dataset. We will read the add access and remove access actions and save them.
add_access_data = [] remove_access_data = [] df = pd.read_csv('amzn-anon-access-samples-history-2.0.csv') # Loop through unique logins (employee ids) for login in df["LOGIN"].unique(): login_df = df[df["LOGIN"]==login].copy() # Save actions for target in login_df["TARGET_NAME"].unique(): login_tar...
_____no_output_____
MIT-0
notebooks/lecture_5/DTE-LECTURE-5-LIGHTGBM.ipynb
dsMOOC/MLA-DTE
Let's save this data so that we can use it later
df = pd.DataFrame(data, columns=["ACTION", "RESOURCE", "MGR_ID", "ROLLUP_1", "ROLLUP_2", "DEPTNAME", "BUSINESS_TITLE", "JOB_FAMILY", "JOB_CODE"]) df.to_csv("data.csv", index=False)
_____no_output_____
MIT-0
notebooks/lecture_5/DTE-LECTURE-5-LIGHTGBM.ipynb
dsMOOC/MLA-DTE
Here is how our data look like:
df.head() # Delete the downloaded files ! rm amzn-anon-access-samples-2.0.csv amzn-anon-access-samples-history-2.0.csv amzn-anon-access-samples.tgz
_____no_output_____
MIT-0
notebooks/lecture_5/DTE-LECTURE-5-LIGHTGBM.ipynb
dsMOOC/MLA-DTE
2. LightGBMLet's use LightGBM on this dataset.
! pip install -q lightgbm
scikit-learn 0.20.4 has requirement scipy>=0.13.3, but you'll have scipy 0.13.0b1 which is incompatible. Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/scikit_learn-0.20.4.dist-info' Consider using the `--user` option or check the pe...
MIT-0
notebooks/lecture_5/DTE-LECTURE-5-LIGHTGBM.ipynb
dsMOOC/MLA-DTE
Let's read the dataset
import pandas as pd import numpy as np data = pd.read_csv("data.csv") data.head() data.info() data["ACTION"].value_counts()
_____no_output_____
MIT-0
notebooks/lecture_5/DTE-LECTURE-5-LIGHTGBM.ipynb
dsMOOC/MLA-DTE
We will fix the column types below to make sure they are handled as categorical variables.
from sklearn.model_selection import train_test_split y = data["ACTION"].values X = data.drop(columns='ACTION') for c in X.columns: X[c] = X[c].astype('category') X_train, X_valid, y_train, y_valid = train_test_split(X, y, ...
_____no_output_____
MIT-0
notebooks/lecture_5/DTE-LECTURE-5-LIGHTGBM.ipynb
dsMOOC/MLA-DTE
Let's fit the lightGBM model below.
import lightgbm as lgb # Create dataset for lightgbm lgb_train = lgb.Dataset(X_train, y_train) lgb_eval = lgb.Dataset(X_valid, y_valid, reference=lgb_train) # Let's see our parameters # boosting_type (string, optional (default='gbdt')) # ‘gbdt’, traditional Gradient Boosting Decision Tree. # ‘dart’, Dropouts meet Mu...
[LightGBM] [Info] Number of positive: 6800, number of negative: 129 [LightGBM] [Warning] Auto-choosing col-wise multi-threading, the overhead of testing was 0.000374 seconds. You can set `force_col_wise=true` to remove the overhead. [LightGBM] [Info] Total Bins 2538 [LightGBM] [Info] Number of data points in the train ...
MIT-0
notebooks/lecture_5/DTE-LECTURE-5-LIGHTGBM.ipynb
dsMOOC/MLA-DTE
Let's see the overall performance on validation set.
from sklearn.metrics import classification_report y_pred = gbm.predict(X_valid, num_iteration=gbm.best_iteration) print(classification_report(y_valid, np.round(y_pred)))
precision recall f1-score support 0 0.26 0.61 0.37 23 1 0.99 0.97 0.98 1200 accuracy 0.96 1223 macro avg 0.63 0.79 0.67 1223 weighted avg 0.98 0.96 0.97 ...
MIT-0
notebooks/lecture_5/DTE-LECTURE-5-LIGHTGBM.ipynb
dsMOOC/MLA-DTE
Preprocessing
# Import our dependencies from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler import pandas as pd import tensorflow as tf # Import and read the charity_data.csv. import pandas as pd application_df = pd.read_csv("/Users/melissa/Downloads/Deep Learning Hw/Resources /ch...
_____no_output_____
ADSL
AlphabetSoupCharity_Optimization.ipynb
melcardenas28/Deep_Learning-
Compile, Train and Evaluate the Model
# Define the model - deep neural net, i.e., the number of input features and hidden nodes for each layer. number_input_features = len(X_train[0]) hidden_nodes_layer1 = 100 hidden_nodes_layer2 = 70 hidden_nodes_layer2 = 40 nn = tf.keras.models.Sequential() # First hidden layer nn.add( tf.keras.layers.Dense(units=...
_____no_output_____
ADSL
AlphabetSoupCharity_Optimization.ipynb
melcardenas28/Deep_Learning-
ML ScriptsSo far, we've done everything inside the Jupyter notebooks but we're going to now move our code into individual python scripts. We will lay out the code that needs to be inside each script but checkout the `API` lesson to see how it all comes together.   data.py Load data
import numpy as np import pandas as pd import random import urllib SEED = 1234 DATA_FILE = 'news.csv' INPUT_FEATURE = 'title' OUTPUT_FEATURE = 'category' # Set seed for reproducibility np.random.seed(SEED) random.seed(SEED) # Load data from GitHub to notebook's local drive url = "https://raw.githubusercontent.com/madew...
_____no_output_____
MIT
notebooks/03_APIs/02_ML_Scripts/02_PT_ML_Scripts.ipynb
AlekseiMikhalev/lessons
Preprocessing
import re LOWER = True FILTERS = r"[!\"'#$%&()*\+,-./:;<=>?@\\\[\]^_`{|}~]" def preprocess_texts(texts, lower, filters): preprocessed_texts = [] for text in texts: if lower: text = ' '.join(word.lower() for word in text.split(" ")) text = re.sub(r"([.,!?])", r" \1 ", text) t...
Wall St. Bears Claw Back Into the Black (Reuters) → wall st bears claw back into the black reuters
MIT
notebooks/03_APIs/02_ML_Scripts/02_PT_ML_Scripts.ipynb
AlekseiMikhalev/lessons
Split data
import collections from sklearn.model_selection import train_test_split TRAIN_SIZE = 0.7 VAL_SIZE = 0.15 TEST_SIZE = 0.15 SHUFFLE = True def train_val_test_split(X, y, val_size, test_size, shuffle): X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=test_size, stratify=y, shuffle=shuffle) ...
X_train: (86700,), y_train: (86700,) X_val: (15300,), y_val: (15300,) X_test: (18000,), y_test: (18000,) pga overhauls system for ryder cup points → Sports Classes: {'Business': 30000, 'Sci/Tech': 30000, 'Sports': 30000, 'World': 30000}
MIT
notebooks/03_APIs/02_ML_Scripts/02_PT_ML_Scripts.ipynb
AlekseiMikhalev/lessons
tokenizers.py Tokenizer
import json import re SEPARATOR = ' ' # word level class Tokenizer(object): def __init__(self, separator, pad_token='<PAD>', oov_token='<UNK>', token_to_index={'<PAD>': 0, '<UNK>': 1}): self.separator = separator self.oov_token = oov_token self.token_to_index = token_to_inde...
<Tokenizer(num_tokens=35635)>
MIT
notebooks/03_APIs/02_ML_Scripts/02_PT_ML_Scripts.ipynb
AlekseiMikhalev/lessons
Label Encoder
class LabelEncoder(object): def __init__(self, class_to_index={}): self.class_to_index = class_to_index self.index_to_class = {v: k for k, v in self.class_to_index.items()} self.classes = list(self.class_to_index.keys()) def __len__(self): return len(self.class_to_index) de...
<LabelEncoder(num_classes=4)>
MIT
notebooks/03_APIs/02_ML_Scripts/02_PT_ML_Scripts.ipynb
AlekseiMikhalev/lessons
datasets.py
import math import torch import torch.nn as nn from torch.utils.data import Dataset from torch.utils.data import DataLoader BATCH_SIZE = 128 FILTER_SIZES = [2, 3, 4] # Set seed for reproducibility torch.manual_seed(SEED) torch.cuda.manual_seed(SEED) torch.cuda.manual_seed_all(SEED) # multi-GPU. torch.backends.cudnn.ben...
cuda
MIT
notebooks/03_APIs/02_ML_Scripts/02_PT_ML_Scripts.ipynb
AlekseiMikhalev/lessons
Pad
def pad_sequences(X, max_seq_len): sequences = np.zeros((len(X), max_seq_len)) for i, sequence in enumerate(X): sequences[i][:len(sequence)] = sequence return sequences # Pad sequences inputs = [[1,2,3], [1,2,3,4], [1,2]] max_seq_len = max(len(x) for x in inputs) padded_inputs = pad_sequences(X=inp...
(3, 4) [[1. 2. 3. 0.] [1. 2. 3. 4.] [1. 2. 0. 0.]]
MIT
notebooks/03_APIs/02_ML_Scripts/02_PT_ML_Scripts.ipynb
AlekseiMikhalev/lessons
Dataset
class TextDataset(Dataset): def __init__(self, X, y, batch_size, max_filter_size): self.X = X self.y = y self.batch_size = batch_size self.max_filter_size = max_filter_size def __len__(self): return len(self.y) def __str__(self): return f"<Dataset(N={len(sel...
torch.Size([128, 13]) torch.Size([128])
MIT
notebooks/03_APIs/02_ML_Scripts/02_PT_ML_Scripts.ipynb
AlekseiMikhalev/lessons
utils.py Embeddings
from io import BytesIO from urllib.request import urlopen from zipfile import ZipFile EMBEDDING_DIM = 100 def load_glove_embeddings(embeddings_file): """Load embeddings from a file.""" embeddings = {} with open(embeddings_file, "r") as fp: for index, line in enumerate(fp): values = line....
(35635, 100)
MIT
notebooks/03_APIs/02_ML_Scripts/02_PT_ML_Scripts.ipynb
AlekseiMikhalev/lessons
model.py Model
import torch.nn.functional as F NUM_FILTERS = 50 HIDDEN_DIM = 128 DROPOUT_P = 0.1 class TextCNN(nn.Module): def __init__(self, embedding_dim, vocab_size, num_filters, filter_sizes, hidden_dim, dropout_p, num_classes, pretrained_embeddings=None, freeze_embeddings=False, padding_id...
<bound method Module.named_parameters of TextCNN( (embeddings): Embedding(35635, 100, padding_idx=0) (conv): ModuleList( (0): Conv1d(100, 50, kernel_size=(2,), stride=(1,)) (1): Conv1d(100, 50, kernel_size=(3,), stride=(1,)) (2): Conv1d(100, 50, kernel_size=(4,), stride=(1,)) ) (dropout): Dropout(p=...
MIT
notebooks/03_APIs/02_ML_Scripts/02_PT_ML_Scripts.ipynb
AlekseiMikhalev/lessons
train.py Training
from pathlib import Path from torch.optim import Adam from torch.optim.lr_scheduler import ReduceLROnPlateau from torch.utils.tensorboard import SummaryWriter %load_ext tensorboard LEARNING_RATE = 1e-4 PATIENCE = 3 NUM_EPOCHS = 100 def train_step(model, device, dataset, optimizer): """Train step.""" # Set model...
_____no_output_____
MIT
notebooks/03_APIs/02_ML_Scripts/02_PT_ML_Scripts.ipynb
AlekseiMikhalev/lessons
Evaluation
import io import itertools import matplotlib.pyplot as plt import seaborn as sns from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.metrics import precision_recall_fscore_support def plot_confusion_matrix(y_pred, y_target, classes, cmap=plt.cm.Blues): """Plot...
_____no_output_____
MIT
notebooks/03_APIs/02_ML_Scripts/02_PT_ML_Scripts.ipynb
AlekseiMikhalev/lessons
inference.py Load model
# Load model model = TextCNN(embedding_dim=EMBEDDING_DIM, vocab_size=vocab_size, num_filters=NUM_FILTERS, filter_sizes=FILTER_SIZES, hidden_dim=HIDDEN_DIM, dropout_p=DROPOUT_P, num_classes=len(classes), pretr...
_____no_output_____
MIT
notebooks/03_APIs/02_ML_Scripts/02_PT_ML_Scripts.ipynb
AlekseiMikhalev/lessons
Inference
import collections def get_probability_distribution(y_prob, classes): results = {} for i, class_ in enumerate(classes): results[class_] = np.float64(y_prob[i]) sorted_results = {k: v for k, v in sorted( results.items(), key=lambda item: item[1], reverse=True)} return sorted_results def g...
[ { "raw_input": "the wimbledon tennis tournament starts next week", "preprocessed_input": "the wimbledon tennis tournament starts next week", "probabilities": { "Sports": 0.9998615980148315, "World": 0.0001376205327687785, "Business": 7.324182433876558e-0...
MIT
notebooks/03_APIs/02_ML_Scripts/02_PT_ML_Scripts.ipynb
AlekseiMikhalev/lessons
ERROR: type should be string, got " https://www.hackerrank.com/challenges/breaking-best-and-worst-records/problem"
import math import os import random import re import sys # Complete the breakingRecords function below. def breakingRecords(scores): min_ = max_ = scores[0] min_change = max_change = 0 for score in scores: if (score<min_): min_ = score min_change += 1 elif (score>max...
_____no_output_____
MIT
Breaking the records.ipynb
ayushsubedi/problem_solving
Model Selection, Underfitting, and Overfitting:label:`sec_model_selection`As machine learning scientists,our goal is to discover *patterns*.But how can we be sure that we havetruly discovered a *general* patternand not simply memorized our data?For example, imagine that we wanted to huntfor patterns among genetic mark...
from d2l import tensorflow as d2l import tensorflow as tf import numpy as np import math
_____no_output_____
MIT
d2l-en/tensorflow/chapter_multilayer-perceptrons/underfit-overfit.ipynb
gr8khan/d2lai
Generating the DatasetFirst we need data. Given $x$, we will use the following cubic polynomial to generate the labels on training and test data:$$y = 5 + 1.2x - 3.4\frac{x^2}{2!} + 5.6 \frac{x^3}{3!} + \epsilon \text{ where }\epsilon \sim \mathcal{N}(0, 0.1^2).$$The noise term $\epsilon$ obeys a normal distributionwi...
max_degree = 20 # Maximum degree of the polynomial n_train, n_test = 100, 100 # Training and test dataset sizes true_w = np.zeros(max_degree) # Allocate lots of empty space true_w[0:4] = np.array([5, 1.2, -3.4, 5.6]) features = np.random.normal(size=(n_train + n_test, 1)) np.random.shuffle(features) poly_features =...
_____no_output_____
MIT
d2l-en/tensorflow/chapter_multilayer-perceptrons/underfit-overfit.ipynb
gr8khan/d2lai
Again, monomials stored in `poly_features`are rescaled by the gamma function,where $\Gamma(n)=(n-1)!$.Take a look at the first 2 samples from the generated dataset.The value 1 is technically a feature,namely the constant feature corresponding to the bias.
# Convert from NumPy ndarrays to tensors true_w, features, poly_features, labels = [tf.constant(x, dtype= tf.float32) for x in [true_w, features, poly_features, labels]] features[:2], poly_features[:2, :], labels[:2]
_____no_output_____
MIT
d2l-en/tensorflow/chapter_multilayer-perceptrons/underfit-overfit.ipynb
gr8khan/d2lai
Training and Testing the ModelLet us first implement a function to evaluate the loss on a given dataset.
def evaluate_loss(net, data_iter, loss): #@save """Evaluate the loss of a model on the given dataset.""" metric = d2l.Accumulator(2) # Sum of losses, no. of examples for X, y in data_iter: l = loss(net(X), y) metric.add(tf.reduce_sum(l), tf.size(l).numpy()) return metric[0] / metric[1]
_____no_output_____
MIT
d2l-en/tensorflow/chapter_multilayer-perceptrons/underfit-overfit.ipynb
gr8khan/d2lai
Now define the training function.
def train(train_features, test_features, train_labels, test_labels, num_epochs=400): loss = tf.losses.MeanSquaredError() input_shape = train_features.shape[-1] # Switch off the bias since we already catered for it in the polynomial # features net = tf.keras.Sequential() net.add(tf.kera...
_____no_output_____
MIT
d2l-en/tensorflow/chapter_multilayer-perceptrons/underfit-overfit.ipynb
gr8khan/d2lai
Third-Order Polynomial Function Fitting (Normal)We will begin by first using a third-order polynomial function, which is the same order as that of the data generation function.The results show that this model's training and test losses can be both effectively reduced.The learned model parameters are also closeto the t...
# Pick the first four dimensions, i.e., 1, x, x^2/2!, x^3/3! from the # polynomial features train(poly_features[:n_train, :4], poly_features[n_train:, :4], labels[:n_train], labels[n_train:])
weight: [[ 4.988523 1.2056429 -3.3774073 5.5973654]]
MIT
d2l-en/tensorflow/chapter_multilayer-perceptrons/underfit-overfit.ipynb
gr8khan/d2lai
Linear Function Fitting (Underfitting)Let us take another look at linear function fitting.After the decline in early epochs,it becomes difficult to further decreasethis model's training loss.After the last epoch iteration has been completed,the training loss is still high.When used to fit nonlinear patterns(like the t...
# Pick the first two dimensions, i.e., 1, x, from the polynomial features train(poly_features[:n_train, :2], poly_features[n_train:, :2], labels[:n_train], labels[n_train:])
weight: [[2.8604352 4.265014 ]]
MIT
d2l-en/tensorflow/chapter_multilayer-perceptrons/underfit-overfit.ipynb
gr8khan/d2lai
Higher-Order Polynomial Function Fitting (Overfitting)Now let us try to train the modelusing a polynomial of too high degree.Here, there are insufficient data to learn thatthe higher-degree coefficients should have values close to zero.As a result, our overly-complex modelis so susceptible that it is being influenced...
# Pick all the dimensions from the polynomial features train(poly_features[:n_train, :], poly_features[n_train:, :], labels[:n_train], labels[n_train:], num_epochs=1500)
weight: [[ 5.022744 1.3021078 -3.496279 5.1624517 0.31825364 1.0755647 -0.12992163 0.2757634 -0.24490005 0.33325827 0.10778137 -0.07051218 -0.47507778 -0.05186964 0.28836033 -0.360715 0.22909148 -0.1936694 0.18136841 0.16792756]]
MIT
d2l-en/tensorflow/chapter_multilayer-perceptrons/underfit-overfit.ipynb
gr8khan/d2lai
Initialize the setting
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"]="1" random.seed(123) class Config(): def __init__(self): self.frame_l = 32 # the length of frames self.joint_n = 15 # the number of joints self.joint_d = 2 # the dimension of joints self.clc_num = 21 ...
_____no_output_____
MIT
DD-Net/jhmdb_1D_lite.ipynb
anhquannguyen21/Skeleton-Action-Recognition
Building the model
def poses_diff(x): H, W = x.get_shape()[1],x.get_shape()[2] x = tf.subtract(x[:,1:,...],x[:,:-1,...]) x = tf.image.resize_nearest_neighbor(x,size=[H.value,W.value],align_corners=False) # should not alignment here return x def pose_motion(P,frame_l): P_diff_slow = Lambda(lambda x: poses_diff(x))(P) ...
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:541: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead. WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:66: The name tf.get_default_grap...
MIT
DD-Net/jhmdb_1D_lite.ipynb
anhquannguyen21/Skeleton-Action-Recognition
Train and test on GT_split 1
from google.colab import drive import pickle drive.mount('/content/drive') DATA_PATH1 = "/content/drive/My Drive/Colab Notebooks/Data" infile = open(DATA_PATH1+'/GT_train_1.pkl','rb') Train = pickle.load(infile) DATA_PATH2 = "/content/drive/My Drive/Colab Notebooks/Data" testfile= open(DATA_PATH2+'/GT_test_1.pkl','rb')...
_____no_output_____
MIT
DD-Net/jhmdb_1D_lite.ipynb
anhquannguyen21/Skeleton-Action-Recognition