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
Below I'm running images through the VGG network in batches.> **Exercise:** Below, build the VGG network. Also get the codes from the first fully connected layer (make sure you get the ReLUd values).
# Set the batch size higher if you can fit in in your GPU memory batch_size = 10 codes_list = [] labels = [] batch = [] codes = None with tf.Session() as sess: # TODO: Build the vgg network here vgg = vgg16.Vgg16() input_ = tf.placeholder(tf.float32, [None,224,224,3]) with tf.name_scope("content...
_____no_output_____
MIT
transfer-learning/Transfer_Learning.ipynb
skagrawal/Deep-Learning-Udacity-ND
Building the ClassifierNow that we have codes for all the images, we can build a simple classifier on top of them. The codes behave just like normal input into a simple neural network. Below I'm going to have you do most of the work.
# read codes and labels from file import csv with open('labels') as f: reader = csv.reader(f, delimiter='\n') labels = np.array([each for each in reader if len(each) > 0]).squeeze() with open('codes') as f: codes = np.fromfile(f, dtype=np.float32) codes = codes.reshape((len(labels), -1))
_____no_output_____
MIT
transfer-learning/Transfer_Learning.ipynb
skagrawal/Deep-Learning-Udacity-ND
Data prepAs usual, now we need to one-hot encode our labels and create validation/test sets. First up, creating our labels!> **Exercise:** From scikit-learn, use [LabelBinarizer](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelBinarizer.html) to create one-hot encoded vectors from the label...
from sklearn.preprocessing import LabelBinarizer lb = LabelBinarizer() lb.fit(labels) labels_vecs = lb.transform(labels)
_____no_output_____
MIT
transfer-learning/Transfer_Learning.ipynb
skagrawal/Deep-Learning-Udacity-ND
Now you'll want to create your training, validation, and test sets. An important thing to note here is that our labels and data aren't randomized yet. We'll want to shuffle our data so the validation and test sets contain data from all classes. Otherwise, you could end up with testing sets that are all one class. Typic...
from sklearn.model_selection import StratifiedShuffleSplit ss = StratifiedShuffleSplit(n_splits=1, test_size=0.2) X = codes y = labels_vecs for train_index, test_index in ss.split(X, y): train_x, train_y = X[train_index], y[train_index] test_x, test_y = X[test_index], y[test_index] ss = StratifiedShuffleSpli...
Train shapes (x, y): (2936, 4096) (2936, 5) Validation shapes (x, y): (367, 4096) (367, 5) Test shapes (x, y): (367, 4096) (367, 5)
MIT
transfer-learning/Transfer_Learning.ipynb
skagrawal/Deep-Learning-Udacity-ND
If you did it right, you should see these sizes for the training sets:```Train shapes (x, y): (2936, 4096) (2936, 5)Validation shapes (x, y): (367, 4096) (367, 5)Test shapes (x, y): (367, 4096) (367, 5)``` Classifier layersOnce you have the convolutional codes, you just need to build a classfier from some fully connec...
inputs_ = tf.placeholder(tf.float32, shape=[None, codes.shape[1]]) labels_ = tf.placeholder(tf.int64, shape=[None, labels_vecs.shape[1]]) print(labels_vecs.shape) # TODO: Classifier layers and operations fc = tf.contrib.layers.fully_connected(inputs_, 256) logits = tf.contrib.layers.fully_connected(fc, labels_vecs.sha...
(3670, 5)
MIT
transfer-learning/Transfer_Learning.ipynb
skagrawal/Deep-Learning-Udacity-ND
Batches!Here is just a simple way to do batches. I've written it so that it includes all the data. Sometimes you'll throw out some data at the end to make sure you have full batches. Here I just extend the last batch to include the remaining data.
def get_batches(x, y, n_batches=10): """ Return a generator that yields batches from arrays x and y. """ batch_size = len(x)//n_batches for ii in range(0, n_batches*batch_size, batch_size): # If we're not on the last batch, grab data with size batch_size if ii != (n_batches-1)*batch_siz...
_____no_output_____
MIT
transfer-learning/Transfer_Learning.ipynb
skagrawal/Deep-Learning-Udacity-ND
TrainingHere, we'll train the network.> **Exercise:** So far we've been providing the training code for you. Here, I'm going to give you a bit more of a challenge and have you write the code to train the network. Of course, you'll be able to see my solution if you need help. Use the `get_batches` function I wrote befo...
saver = tf.train.Saver() epochs = 10 iteration = 0 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for e in range(epochs): for x, y in get_batches(train_x, train_y): feed = {inputs_: x, labels_: y} loss, _ = sess.run([cost, opti...
Epoch: 1/10 Iteration: 0 Training loss: 6.09479 Epoch: 1/10 Iteration: 1 Training loss: 19.38938 Epoch: 1/10 Iteration: 2 Training loss: 14.50047 Epoch: 1/10 Iteration: 3 Training loss: 13.24159 Epoch: 1/10 Iteration: 4 Training loss: 7.22328 Epoch: 0/10 Iteration: 5 Validation Acc: 0.6866 Epoch: 1/10 Iteration: 5 Trai...
MIT
transfer-learning/Transfer_Learning.ipynb
skagrawal/Deep-Learning-Udacity-ND
TestingBelow you see the test accuracy. You can also see the predictions returned for images.
with tf.Session() as sess: saver.restore(sess, tf.train.latest_checkpoint('checkpoints')) feed = {inputs_: test_x, labels_: test_y} test_acc = sess.run(accuracy, feed_dict=feed) print("Test accuracy: {:.4f}".format(test_acc)) %matplotlib inline import matplotlib.pyplot as plt from scip...
_____no_output_____
MIT
transfer-learning/Transfer_Learning.ipynb
skagrawal/Deep-Learning-Udacity-ND
Below, feel free to choose images and see how the trained classifier predicts the flowers in them.
test_img_path = 'flower_photos/roses/10894627425_ec76bbc757_n.jpg' test_img = imread(test_img_path) plt.imshow(test_img) # Run this cell if you don't have a vgg graph built if 'vgg' in globals(): print('"vgg" object already exists. Will not create again.') else: #create vgg with tf.Session() as sess: ...
_____no_output_____
MIT
transfer-learning/Transfer_Learning.ipynb
skagrawal/Deep-Learning-Udacity-ND
Introduction to ProgrammingTopics for today will include:- Mozilla Developer Network [(MDN)](https://developer.mozilla.org/en-US/)- Python Documentation [(Official Documentation)](https://docs.python.org/3/)- Importance of Design- Functions- Built in Functions Mozilla Developer Network [(MDN)](https://developer.mozil...
def char_finder(character, string): total = 0 for char in string: if char == character: total += 1 return total if __name__ == "__main__": output = char_finder('z', 'Quick brown fox jumped over the lazy dog') print(output)
1
MIT
JupyterNotebooks/Lessons/Lesson 4.ipynb
emilekhoury/CMPT-120L-910-20F
Functions---This is a intergral piece of how we do things in any programming language. This allows us to repeat instances of code that we've seen and use them at our preferance.We'll often be using functions similar to how we use variables and our data types. Making Our Own Functions---So to make a functions we'll be ...
def exampleName(exampleParameter1: any, exampleParameter2: any) -> any: print(exampleParameter1, exampleParameter2) exampleName("Hello", 5)
Hello 5
MIT
JupyterNotebooks/Lessons/Lesson 4.ipynb
emilekhoury/CMPT-120L-910-20F
Using functions---Using functions is fairly simple. To use a function all we have to do is give the function name followed by parenthesis. This should seem familiar. Functions In Classes---Now we've mentioned classes before, classes can have functions but they're used a little differently. Functions that stem from cl...
class Person: def __init__(self, weight: int, height: int, name: str): self.weight = weight self.height = height self.name = name def who_is_this(self): print("This person's name is " + self.name) print("This person's weight is " + str(self.weight) + " pounds") p...
This person's name is Aaron Kippins This person's weight is 225 pounds This person's height is 70 inches
MIT
JupyterNotebooks/Lessons/Lesson 4.ipynb
emilekhoury/CMPT-120L-910-20F
Built in Functions and Modules---With the talk of dot notation those are often used with built in functions. Built in function are functions that come along with the language. These tend to be very useful because as we start to visit more complex issues they allow us to do complexs thing with ease in some cases.We hav...
string = "I want to go home!" print(string[0:12], "to Cancun!") # print(string[0:1])
I want to go to Cancun!
MIT
JupyterNotebooks/Lessons/Lesson 4.ipynb
emilekhoury/CMPT-120L-910-20F
toUpper toLower---
alpha_sentence = 'Quick brown fox jumped over the lazy dog' print(alpha_sentence.title()) print(alpha_sentence.upper()) print(alpha_sentence.lower()) if alpha_sentence.lower().islower(): print("sentence is all lowercase")
Quick Brown Fox Jumped Over The Lazy Dog QUICK BROWN FOX JUMPED OVER THE LAZY DOG quick brown fox jumped over the lazy dog sentence is all lowercase
MIT
JupyterNotebooks/Lessons/Lesson 4.ipynb
emilekhoury/CMPT-120L-910-20F
Exponents---
print(2 ** 3)
8
MIT
JupyterNotebooks/Lessons/Lesson 4.ipynb
emilekhoury/CMPT-120L-910-20F
math.sqrt()---
import math math.sqrt(4)
_____no_output_____
MIT
JupyterNotebooks/Lessons/Lesson 4.ipynb
emilekhoury/CMPT-120L-910-20F
Integer Division vs Float Division---
print(4//2) print(4/2)
2 2.0
MIT
JupyterNotebooks/Lessons/Lesson 4.ipynb
emilekhoury/CMPT-120L-910-20F
Abs()---
abs(-10)
_____no_output_____
MIT
JupyterNotebooks/Lessons/Lesson 4.ipynb
emilekhoury/CMPT-120L-910-20F
String Manipulation---
dummy_string = "Hey there I'm just a string for the example about to happen." print(dummy_string.center(70, "-")) print(dummy_string.partition(" ")) print(dummy_string.swapcase()) print(dummy_string.split(" "))
-----Hey there I'm just a string for the example about to happen.----- ('Hey', ' ', "there I'm just a string for the example about to happen.") hEY THERE i'M JUST A STRING FOR THE EXAMPLE ABOUT TO HAPPEN. ['Hey', 'there', "I'm", 'just', 'a&...
MIT
JupyterNotebooks/Lessons/Lesson 4.ipynb
emilekhoury/CMPT-120L-910-20F
Array Manipulation---
arr = [2, 5, 6, 1, 4, 3] arr.sort() print(arr) print(arr[3]) # sorted(arr) print(arr[1:3])
[1, 2, 3, 4, 5, 6] 4
MIT
JupyterNotebooks/Lessons/Lesson 4.ipynb
emilekhoury/CMPT-120L-910-20F
Insert and Pop, Append and Remove---
arr.append(7) print(arr) arr.pop() print(arr)
[1, 2, 3, 4, 5, 6, 7, 7] [1, 2, 3, 4, 5, 6, 7]
MIT
JupyterNotebooks/Lessons/Lesson 4.ipynb
emilekhoury/CMPT-120L-910-20F
Add MollWeide Plotting to gwylm class(L. London 2017) Related: positive_dev/examples/plotting_spherical_harmonics.ipynb Setup Environment
# Setup ipython environment %load_ext autoreload %autoreload 2 %matplotlib inline # Import usefuls from nrutils import scsearch,gwylm from matplotlib.pyplot import * from numpy import array
The autoreload extension is already loaded. To reload it, use: %reload_ext autoreload
MIT
issues/closed/issue2_add_mollweide_plotting_to_gwylm.ipynb
llondon6/nrutils_dev
Find a simulation and load data
# Find sim A = scsearch(q=[10,20],keyword='hr',verbose=True,institute='gt') # Load data y = gwylm(A[0],lmax=4,verbose=False,clean=True)
(validate!)>> Multiple catalog directories found. We will scan through the related list, and then store first the catalog_dir that the OS can find. (validate!)>> Selecting "/Volumes/athena/bradwr/"
MIT
issues/closed/issue2_add_mollweide_plotting_to_gwylm.ipynb
llondon6/nrutils_dev
Plot Mollweide
# kind = 'strain' # Make mollweide plot -- NOTE that the time input is relative to the peak in h22 ax0,real_time = y.mollweide_plot(time=0,form='abs',kind=kind) ax0.set_title('$l_{max} = %i$'%max([l for l,m in y.lm]),size=20) # Make time domain plot for reference axarr,fig = y.lm[2,2][kind].plot() for ax in axarr: ...
_____no_output_____
MIT
issues/closed/issue2_add_mollweide_plotting_to_gwylm.ipynb
llondon6/nrutils_dev
Try to put everything in the same figure
# R,C = 6,3 # fig = figure( figsize=3*array([C,1.0*R]) ) # ax4 = subplot2grid( (R,C), (0, 0), colspan=C, rowspan=3, projection='mollweide' ) ax1 = subplot2grid( (R,C), (3, 0), colspan=C) ax2 = subplot2grid( (R,C), (4, 0), colspan=C, sharex=ax1) ax3 = subplot2grid( (R,C), (5, 0), colspan=C, sharex=ax1) # kind = 'st...
_____no_output_____
MIT
issues/closed/issue2_add_mollweide_plotting_to_gwylm.ipynb
llondon6/nrutils_dev
Now perhaps write an external script that animates frames for select time samples?
from os.path import join range(0,100,10)
_____no_output_____
MIT
issues/closed/issue2_add_mollweide_plotting_to_gwylm.ipynb
llondon6/nrutils_dev
Variables
x = 2 y = '3' print(x+int(y)) z = [1, 2, 3] #List w = (2, 3, 4) #Tuple import numpy as np q = np.array([1, 2, 3]) #numpy.ndarray type(q)
5
MIT
Numeric and scientific python.ipynb
Pytoddler/Data-analysis-and-visualization
Console input and output
MyName = input('My name is: ') print('Hello, '+MyName)
My name is: david Hello, david
MIT
Numeric and scientific python.ipynb
Pytoddler/Data-analysis-and-visualization
File input and output
fid = open('msg.txt','w') fid.write('demo of writing.\n') fid.write('Second line') fid.close() fid = open('msg.txt','r') msg = fid.readline() print(msg) msg = fid.readline() print(msg) fid.close() fid = open('msg.txt','r') msg = fid.readlines() print(msg) fid = open('msg.txt','r') msg = fid.read() print(msg) import n...
_____no_output_____
MIT
Numeric and scientific python.ipynb
Pytoddler/Data-analysis-and-visualization
Functions, Conditions, Loop
import numpy as np def f(x): return x**2 x = np.linspace(0,5,10) y = f(x) print(y) import numpy as np def f(x): #這是個奇怪的練習用函數 res = x if res < 3: res = np.nan #<3就傳 Not a Number elif res < 15: res = x**3 else: res = x**4 return res x = np.linspace(0,10,20) y = np.emp...
[ nan nan nan nan nan nan 31.49147106 50.00728969 74.64644992 106.28371483 145.7938475 194.05161102 251.93176848 320.30908296 400.05831754 492.05423531 597.17159936 716.28517277 850.26971862 1000. ]
MIT
Numeric and scientific python.ipynb
Pytoddler/Data-analysis-and-visualization
Matrices, linear equations
A = np.array([[1,2],[3,2]]) B = np.array([1,0]) # x = A^-1 * b sol1 = np.dot(np.linalg.inv(A),B) print(sol1) sol2 = np.linalg.solve(A,B) print(sol2) import sympy as sym sym.init_printing() #This will automatically enable the best printer available in your environment. x,y = sym.symbols('x y') z = sym.linsolve([3*x...
[-0.5 0.75] [-0.5 0.75]
MIT
Numeric and scientific python.ipynb
Pytoddler/Data-analysis-and-visualization
Non-linear equation
from scipy.optimize import fsolve def f(z): #用z參數來表示x和y,做函數運算 x = z[0] y = z[1] return [x+2*y, x**2+y**2-1] z0 = [0,1] z = fsolve(f,z0) print(z) print(f(z))
[-0.89442719 0.4472136 ] [0.0, -1.1102230246251565e-16]
MIT
Numeric and scientific python.ipynb
Pytoddler/Data-analysis-and-visualization
Integration
from scipy.integrate import quad def f(x): return x**2 quad(f,0,2) #計算積分值 import sympy as sym sym.init_printing() x = sym.Symbol('x') f = sym.integrate(x**2,x) f.subs(x,2) #將值帶入函數中 f
_____no_output_____
MIT
Numeric and scientific python.ipynb
Pytoddler/Data-analysis-and-visualization
Derivative
from scipy.misc import derivative def f(x): return x**2 print(derivative(f,2,dx=0.01)) #dx表示精確程度 import sympy as sym sym.init_printing() x = sym.Symbol('x') f = sym.diff(x**3,x) f.subs(x,2) #將值帶入函數中,得解 f
4.0
MIT
Numeric and scientific python.ipynb
Pytoddler/Data-analysis-and-visualization
Interpolation
from scipy.interpolate import interp1d #中間的字是1不是L喔!!! x = np.arange(0,6,1) y = np.array([0.2,0.3,0.5,1.0,0.9,1.1]) %matplotlib inline import matplotlib.pyplot as plt plt.plot(x,y,'bo') xp = np.linspace(0,5,100) #為了顯示差別把點增加 y1 = interp1d(x,y,kind='linear') #一階 plt.plot(xp,y1(xp),'r-') y2 = interp1d(x,y,kind='quadr...
_____no_output_____
MIT
Numeric and scientific python.ipynb
Pytoddler/Data-analysis-and-visualization
Linear regression
import numpy as np x = np.array([0,1,2,3,4,5]) y = np.array([0.1,0.2,0.3,0.5,0.8,2.0 ]) #多項式逼近法,選擇階層 p1 = np.polyfit(x,y,1) print(p1) p2 = np.polyfit(x,y,2) print(p2) p3 = np.polyfit(x,y,3) print(p3) %matplotlib inline import matplotlib.pyplot as plt plt.plot(x,y,'ro') # np.polyval表示多項式的值,把係數p_帶入多項式x求出來的值 xp = np.li...
[ 0.32857143 -0.17142857] [ 0.1125 -0.23392857 0.20357143] [ 0.04166667 -0.2 0.33690476 0.07857143]
MIT
Numeric and scientific python.ipynb
Pytoddler/Data-analysis-and-visualization
Nonlinear regression
import numpy as np from scipy.optimize import curve_fit x = np.array([0,1,2,3,4,5]) y = np.array([0.1,0.2,0.3,0.5,0.8,2.0 ]) #多項式逼近法,選擇階層 p1 = np.polyfit(x,y,1) print(p1) p2 = np.polyfit(x,y,2) print(p2) p3 = np.polyfit(x,y,3) print(p3) #使用指數對數 def f(x,a): return 0.1 * np.exp(a*x) a = curve_fit(f,x,y)[0] #非線性回歸,...
[ 0.32857143 -0.17142857] [ 0.1125 -0.23392857 0.20357143] [ 0.04166667 -0.2 0.33690476 0.07857143] a=[ 0.58628748]
MIT
Numeric and scientific python.ipynb
Pytoddler/Data-analysis-and-visualization
Differential equation
from scipy.integrate import odeint def dydt(y,t,a): return -a * y a = 0.5 t = np.linspace(0,20) y0 = 5.0 y = odeint(dydt,y0,t,args=(a,)) %matplotlib inline import matplotlib.pyplot as plt plt.plot(t,y) plt.xlabel('time') plt.ylabel('y')
_____no_output_____
MIT
Numeric and scientific python.ipynb
Pytoddler/Data-analysis-and-visualization
Nonlinear optimization
#概念:要有Objective、Constraint,然後初始猜想值 import numpy as np from scipy.optimize import minimize def objective(x): #此函數求最小值 x1 = x[0] x2 = x[1] x3 = x[2] x4 = x[3] return x1*x4*(x1+x2+x3)+x3 #用減法做比較 def constraint1(x): return x[0]*x[1]*x[2]*x[3] - 25.0 #用減法做比較 def constraint2(x): sum_sq = 40.0 ...
[ 1. 4.7429961 3.82115462 1.37940765]
MIT
Numeric and scientific python.ipynb
Pytoddler/Data-analysis-and-visualization
PyFunc Model + Transformer ExampleThis notebook demonstrates how to deploy a Python function based model and a custom transformer. This type of model is useful as user would be able to define their own logic inside the model as long as it satisfy contract given in `merlin.PyFuncModel`. If the pre/post-processing steps...
!pip install --upgrade -r requirements.txt > /dev/null import warnings warnings.filterwarnings('ignore')
_____no_output_____
Apache-2.0
examples/transformer/custom-transformer/PyFunc-Transformer.ipynb
Omrisnyk/merlin
1. Initialize Merlin 1.1 Set Merlin Server
import merlin MERLIN_URL = "<MERLIN_HOST>/api/merlin" merlin.set_url(MERLIN_URL)
_____no_output_____
Apache-2.0
examples/transformer/custom-transformer/PyFunc-Transformer.ipynb
Omrisnyk/merlin
1.2 Set Active Project`project` represent a project in real life. You may have multiple model within a project.`merlin.set_project()` will set the active project into the name matched by argument. You can only set it to an existing project. If you would like to create a new project, please do so from the MLP UI.
PROJECT_NAME = "sample" merlin.set_project(PROJECT_NAME)
/Users/ariefrahmansyah/.pyenv/versions/3.7.3/lib/python3.7/site-packages/ipykernel/ipkernel.py:287: DeprecationWarning: `should_run_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing...
Apache-2.0
examples/transformer/custom-transformer/PyFunc-Transformer.ipynb
Omrisnyk/merlin
1.3 Set Active Model`model` represents an abstract ML model. Conceptually, `model` in Merlin is similar to a class in programming language. To instantiate a `model` you'll have to create a `model_version`.Each `model` has a type, currently model type supported by Merlin are: sklearn, xgboost, tensorflow, pytorch, and ...
from merlin.model import ModelType MODEL_NAME = "transformer-pyfunc" merlin.set_model(MODEL_NAME, ModelType.PYFUNC)
_____no_output_____
Apache-2.0
examples/transformer/custom-transformer/PyFunc-Transformer.ipynb
Omrisnyk/merlin
2. Train ModelIn this step, we are going to train a cifar10 model using PyToch and create PyFunc model class that does the prediction using trained PyTorch model. 2.1 Prepare Training Data
import torch import torchvision import torchvision.transforms as transforms transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True,...
/Users/ariefrahmansyah/.pyenv/versions/3.7.3/lib/python3.7/site-packages/torchvision/datasets/lsun.py:8: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable 0it [00:00, ?it/s]
Apache-2.0
examples/transformer/custom-transformer/PyFunc-Transformer.ipynb
Omrisnyk/merlin
2.2 Create PyTorch Model
import torch.nn as nn import torch.nn.functional as F class PyTorchModel(nn.Module): def __init__(self): super(PyTorchModel, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16 * 5 * 5, 120)...
/Users/ariefrahmansyah/.pyenv/versions/3.7.3/lib/python3.7/site-packages/ipykernel/ipkernel.py:287: DeprecationWarning: `should_run_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing...
Apache-2.0
examples/transformer/custom-transformer/PyFunc-Transformer.ipynb
Omrisnyk/merlin
2.3 Train Model
import torch.optim as optim net = PyTorchModel() criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9) for epoch in range(2): # loop over the dataset multiple times running_loss = 0.0 for i, data in enumerate(trainloader, 0): # get the inputs; data is a li...
170500096it [03:10, 1240089.84it/s]
Apache-2.0
examples/transformer/custom-transformer/PyFunc-Transformer.ipynb
Omrisnyk/merlin
2.4 Check Prediction
dataiter = iter(trainloader) inputs, labels = dataiter.next() predict_out = net(inputs[0:1]) predict_out
_____no_output_____
Apache-2.0
examples/transformer/custom-transformer/PyFunc-Transformer.ipynb
Omrisnyk/merlin
2.5 Serialize Model
import os model_dir = "pytorch-model" model_path = os.path.join(model_dir, "model.pt") model_class_path = os.path.join(model_dir, "model.py") torch.save(net.state_dict(), model_path)
_____no_output_____
Apache-2.0
examples/transformer/custom-transformer/PyFunc-Transformer.ipynb
Omrisnyk/merlin
2.6 Save PyTorchModel ClassWe also need to save the PyTorchModel class and upload it to Merlin alongside the serialized trained model. The next cell will write the PyTorchModel we defined above to `pytorch-model/model.py` file.
%%file pytorch-model/model.py import torch.nn as nn import torch.nn.functional as F class PyTorchModel(nn.Module): def __init__(self): super(PyTorchModel, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc...
Overwriting pytorch-model/model.py
Apache-2.0
examples/transformer/custom-transformer/PyFunc-Transformer.ipynb
Omrisnyk/merlin
3. Create PyFunc ModelTo create a PyFunc model you'll have to extend `merlin.PyFuncModel` class and implement its `initialize` and `infer` method.`initialize` will be called once during model initialization. The argument to `initialize` is a dictionary containing a key value pair of artifact name and its URL. The arti...
import importlib import sys from merlin.model import PyFuncModel MODEL_CLASS_NAME="PyTorchModel" class CifarModel(PyFuncModel): def initialize(self, artifacts): model_path = artifacts["model_path"] model_class_path = artifacts["model_class_path"] # Load the python class into memo...
_____no_output_____
Apache-2.0
examples/transformer/custom-transformer/PyFunc-Transformer.ipynb
Omrisnyk/merlin
Now, let's test it locally.
import json with open(os.path.join("input-tensor.json"), "r") as f: tensor_req = json.load(f) m = CifarModel() m.initialize({"model_path": model_path, "model_class_path": model_class_path}) m.infer(tensor_req)
_____no_output_____
Apache-2.0
examples/transformer/custom-transformer/PyFunc-Transformer.ipynb
Omrisnyk/merlin
4. Deploy Model To deploy the model, we will have to create an iteration of the model (by create a `model_version`), upload the serialized model to MLP, and then deploy. 4.1 Create Model Version and Upload `merlin.new_model_version()` is a convenient method to create a model version and start its development process....
with merlin.new_model_version() as v: merlin.log_pyfunc_model(model_instance=CifarModel(), conda_env="env.yaml", artifacts={"model_path": model_path, "model_class_path": model_class_path})
2021/06/23 05:41:28 WARNING mlflow.models.model: Logging model metadata to the tracking server has failed, possibly due older server version. The model artifacts have been logged successfully under gs://<MERLIN_BUCKET>/mlflow/604/7b57180c051842fe815adbacfa282541/artifacts. In addition to exporting model artifacts, MLfl...
Apache-2.0
examples/transformer/custom-transformer/PyFunc-Transformer.ipynb
Omrisnyk/merlin
4.2 Deploy Model and TransformerTo deploy a model and its transformer, you must pass a `transformer` object to `deploy()` function. Each of deployed model version will have its own generated url.
from merlin.resource_request import ResourceRequest from merlin.transformer import Transformer # Create a transformer object and its resources requests resource_request = ResourceRequest(min_replica=1, max_replica=1, cpu_request="100m", memory_request="200Mi") transformer = Transfor...
/Users/ariefrahmansyah/.pyenv/versions/3.7.3/lib/python3.7/site-packages/ipykernel/ipkernel.py:287: DeprecationWarning: `should_run_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing...
Apache-2.0
examples/transformer/custom-transformer/PyFunc-Transformer.ipynb
Omrisnyk/merlin
4.3 Send Test Request
import json import requests with open(os.path.join("input-raw-image.json"), "r") as f: req = json.load(f) resp = requests.post(endpoint.url, json=req) resp.text
_____no_output_____
Apache-2.0
examples/transformer/custom-transformer/PyFunc-Transformer.ipynb
Omrisnyk/merlin
4. Clean Up 4.1 Delete Deployment
merlin.undeploy(v)
Deleting deployment of model transformer-pyfunc version 2 from enviroment id-staging
Apache-2.0
examples/transformer/custom-transformer/PyFunc-Transformer.ipynb
Omrisnyk/merlin
CCI501 - Machine Learning Project Name: Samuel Mwamburi Mghendi Admission Number: P52/37621/2020 Email: mghendi@students.uonbi.ac.ke Course: Machine Learning – CCI 501 Applying Logistic Regression to Establish a Good Pricing Model for Mobile Phone Manufacturers in the Current Market Landscape using Technical Specif...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import os from tqdm import trange
_____no_output_____
MIT
CCI_501_ML_Project.ipynb
mghendi/smartphonepriceclassifier
Import Data
df = pd.read_csv("productdata.csv") df from sklearn import preprocessing
_____no_output_____
MIT
CCI_501_ML_Project.ipynb
mghendi/smartphonepriceclassifier
Exploratory Data AnalysisGathering more information about the dataset in order to better understand it.The relationship and distribution between screen size, screen resolution, camera resolution, storage space, memory, rating and likes against the resultant price charged for each phone sold was plotted and analyzed.
df.describe() df.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 1148 entries, 0 to 1147 Data columns (total 13 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 Phone 1148 non-null object 1 Screen (inches) 1148 non-null float64 2 Resoluti...
MIT
CCI_501_ML_Project.ipynb
mghendi/smartphonepriceclassifier
The feature OS has missing values.
# check shape df.shape
_____no_output_____
MIT
CCI_501_ML_Project.ipynb
mghendi/smartphonepriceclassifier
The dataset has 1,148 records and 12 features.
# remove duplicates, if any df.drop_duplicates(inplace = True) df.shape
_____no_output_____
MIT
CCI_501_ML_Project.ipynb
mghendi/smartphonepriceclassifier
No duplicate records available in the dataset. Mobile Phones by Screen Size Contrasted by User Rating
# previewing distribution of screen size by rating df['Round Rating'] = df['Rating'].round(decimals=0) plt.figure(figsize = (20, 6)) ax = sns.histplot(df, x="Screen (inches)", stat="count", hue="Round Rating", multiple="dodge", shrink=0.8) for p in ax.patches:# histogram bar label h = p.get_height() if (h != 0): a...
_____no_output_____
MIT
CCI_501_ML_Project.ipynb
mghendi/smartphonepriceclassifier
The chart can be used to deduce a high-level inference on the phone industry consumer purchase preference. Phones with a larger screen size, which are inherently larger in size, between 5 to 7 inches are seen to be rated higher.
# changing the datatype of the 'OS' variable df['OS'] = df['OS'].astype('str')
_____no_output_____
MIT
CCI_501_ML_Project.ipynb
mghendi/smartphonepriceclassifier
Mobile Phones by Camera Resolution contrasted by User Rating
# previewing distribution of camera resolution by rating plt.figure(figsize = (20, 6)) ax = sns.histplot(df, x="Camera (MP)", hue="Round Rating", multiple="dodge", shrink=0.8) for p in ax.patches:# label each bar in histogram h = p.get_height() if (h != 0): ax.text(x = p.get_x()+(p.get_width()/2), y = h+1, s = "{:....
_____no_output_____
MIT
CCI_501_ML_Project.ipynb
mghendi/smartphonepriceclassifier
Mobile phones with cameras sporting high resolutions,15 and 32 Megapixels , based on the current offering in the market have significantly better relative ratings than mid-tier models between 20 to 30 Megapixels and low-tier models less than 5 megapixels.
# previewing distribution of Storage Capacity by rating plt.figure(figsize = (20, 6)) ax = sns.histplot(df, x="Storage (GB)", hue="Round Rating", multiple="dodge", shrink=0.8) for p in ax.patches:# label each bar in histogram h = p.get_height() if (h != 0): ax.text(x = p.get_x()+(p.get_width()/2), y = h+1, s = "{:....
_____no_output_____
MIT
CCI_501_ML_Project.ipynb
mghendi/smartphonepriceclassifier
As anticipated, mobile phones with higher internal storage capacities, greater than or equal to 256 Gigabytes, recieve significantly better relative ratings than models with less than 128 gigabytes. Additionally, there are very few purchases of mobile phones equal to or greater than 512 gigabytes of storage. Mobile Ph...
#pairplot to investigate the relationship between all the variables sns.pairplot(df) plt.show()
_____no_output_____
MIT
CCI_501_ML_Project.ipynb
mghendi/smartphonepriceclassifier
In reference to the pair plot above, mid-tier phone models are significantly better rated and well recieved as compared to their much more expensive and budget counterparts in the local current market.Phones with mid-tier features such as an average storage capacity, such as a large display 5 to 7 inches, storage of be...
# creating categorigal variables for the battery type feature df["Battery Type"].replace({"Li-Po": "0", "Li-Ion": "1"}, inplace=True) print(df) # creating categorigal variables for the battery type feature df["Price Category"].replace({"Budget": "0", "Mid-Tier": "1", "Flagship": "2"}, inplace=True) print(df) df["Price ...
_____no_output_____
MIT
CCI_501_ML_Project.ipynb
mghendi/smartphonepriceclassifier
Creating Bag of Words models
df["OS"] = vectorizer.transform(df["OS"]).toarray() print(df) df["Resolution (pixels)"] = vectorizer.transform(df["Resolution (pixels)"]).toarray() print (df)
Phone Screen (inches) Resolution (pixels) \ 0 Gionee M7 Power 6.00 0 1 Gionee M7 6.01 0 2 Samsung Galaxy M21 6GB/128GB 6.40 0 3 Samsung G...
MIT
CCI_501_ML_Project.ipynb
mghendi/smartphonepriceclassifier
4. Data Modelling Data Modelling for Logistic Regression Feature Selection For this experiment, the mobile phone's technical specifications will be used as the independent variables. The ratings and likes which are subjective assessments will be dropped.Variables such as the Phone Name are not important in price po...
X = df.drop(columns = ['Phone','Price(Kshs)', 'Rating', 'Likes', 'OS', 'Battery Type', 'Resolution (pixels)', 'Round Rating']).values y = df['Price Category'].values
_____no_output_____
MIT
CCI_501_ML_Project.ipynb
mghendi/smartphonepriceclassifier
Splitting Data
# splitting into 75% training and 25% test sets from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=1000)
_____no_output_____
MIT
CCI_501_ML_Project.ipynb
mghendi/smartphonepriceclassifier
Feature Scaling
scaler = preprocessing.StandardScaler().fit(X_train) scaler scaler.mean_ scaler.scale_ X_scaled = scaler.transform(X_train) X_scaled X_scaled.mean(axis=0) X_scaled.std(axis=0)
_____no_output_____
MIT
CCI_501_ML_Project.ipynb
mghendi/smartphonepriceclassifier
Logistic Regression
from sklearn.linear_model import LogisticRegression from sklearn.datasets import make_classification from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler X, y = make_classifica...
_____no_output_____
MIT
CCI_501_ML_Project.ipynb
mghendi/smartphonepriceclassifier
5. Performance Evaluation
print("Accuracy:", (score)*100, "%")
Accuracy: 100.0 %
MIT
CCI_501_ML_Project.ipynb
mghendi/smartphonepriceclassifier
PROYECTO CIFAR-10 CARLOS CABAÑÓ 1. Librerias Descargamos la librería para los arrays en preprocesamiento de Keras
from tensorflow import keras as ks from matplotlib import pyplot as plt import numpy as np import time import datetime import random from sklearn.preprocessing import LabelEncoder from tensorflow.keras.regularizers import l2 from tensorflow.keras.callbacks import EarlyStopping from tensorflow.keras.preprocessing.imag...
_____no_output_____
MIT
Project Portfolio/cnn-cifar10-tf2-v12_Notebook_CarlosCabano.ipynb
CarlosCabano/carloscabano.github.io
2. Arquitectura de red del modelo Adoptamos la arquitectura del modelo 11 con los ajustes en Batch Normalization, Kernel Regularizer y Kernel Initializer. Añadimos Batch normalization a las capas de convolución.
model = ks.Sequential() model.add(ks.layers.Conv2D(64, (3, 3), strides=1, activation='relu', kernel_regularizer=l2(0.0005), kernel_initializer="he_uniform", padding='same', input_shape=(32,32,3))) model.add(ks.layers.BatchNormalization()) model.add(ks.layers.Conv2D(64, (3, 3), strides=1, activation='relu', kernel_regu...
Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d (Conv2D) (None, 32, 32, 64) 1792 ____________________________________...
MIT
Project Portfolio/cnn-cifar10-tf2-v12_Notebook_CarlosCabano.ipynb
CarlosCabano/carloscabano.github.io
3. Optimizador, función error Añadimos el learning rate al optimizador
from keras.optimizers import SGD model.compile(optimizer=SGD(lr=0.001, momentum=0.9), loss='sparse_categorical_crossentropy', metrics=['accuracy'])
_____no_output_____
MIT
Project Portfolio/cnn-cifar10-tf2-v12_Notebook_CarlosCabano.ipynb
CarlosCabano/carloscabano.github.io
4. Preparamos los datos
cifar10 = ks.datasets.cifar10 (x_train, y_train), (x_test, y_test) = cifar10.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 cifar10_labels = [ 'airplane', # id 0 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck', ] print('Number of labels: %s' % len(cifar10_labels))
Number of labels: 10
MIT
Project Portfolio/cnn-cifar10-tf2-v12_Notebook_CarlosCabano.ipynb
CarlosCabano/carloscabano.github.io
Pintemos una muestra de las imagenes del dataset CIFAR10:
# Pintemos una muestra de las las imagenes del dataset MNIST print('Train: X=%s, y=%s' % (x_train.shape, y_train.shape)) print('Test: X=%s, y=%s' % (x_test.shape, y_test.shape)) for i in range(9): plt.subplot(330 + 1 + i) plt.imshow(x_train[i], cmap=plt.get_cmap('gray')) plt.title(cifar10_labels[y_train[...
Train: X=(50000, 32, 32, 3), y=(50000, 1) Test: X=(10000, 32, 32, 3), y=(10000, 1)
MIT
Project Portfolio/cnn-cifar10-tf2-v12_Notebook_CarlosCabano.ipynb
CarlosCabano/carloscabano.github.io
Hacemos la validación al mismo tiempo que el entrenamiento:
x_val = x_train[-10000:] y_val = y_train[-10000:] x_train = x_train[:-10000] y_train = y_train[:-10000]
_____no_output_____
MIT
Project Portfolio/cnn-cifar10-tf2-v12_Notebook_CarlosCabano.ipynb
CarlosCabano/carloscabano.github.io
Hacemos el OHE para la clasificación
le = LabelEncoder() le.fit(y_train.ravel()) y_train_encoded = le.transform(y_train.ravel()) y_val_encoded = le.transform(y_val.ravel()) y_test_encoded = le.transform(y_test.ravel())
_____no_output_____
MIT
Project Portfolio/cnn-cifar10-tf2-v12_Notebook_CarlosCabano.ipynb
CarlosCabano/carloscabano.github.io
5. Ajustes: Early Stopping Definimos un early stopping con base en el loss de validación y con el parámetro de "patience" a 10, para tener algo de margen. Con el Early Stopping lograremos parar el entrenamiento en el momento óptimo para evitar que siga entrenando a partir del overfitting.
callback_val_loss = EarlyStopping(monitor="val_loss", patience=5) callback_val_accuracy = EarlyStopping(monitor="val_accuracy", patience=10)
_____no_output_____
MIT
Project Portfolio/cnn-cifar10-tf2-v12_Notebook_CarlosCabano.ipynb
CarlosCabano/carloscabano.github.io
6. Transformador de imágenes 6.1 Imágenes de entrenamiento
train_datagen = ImageDataGenerator( horizontal_flip=True, width_shift_range=0.2, height_shift_range=0.2, ) train_generator = train_datagen.flow( x_train, y_train_encoded, batch_size=64 )
_____no_output_____
MIT
Project Portfolio/cnn-cifar10-tf2-v12_Notebook_CarlosCabano.ipynb
CarlosCabano/carloscabano.github.io
6.2 Imágenes de validación y testeo
validation_datagen = ImageDataGenerator( horizontal_flip=True, width_shift_range=0.2, height_shift_range=0.2, ) validation_generator = validation_datagen.flow( x_val, y_val_encoded, batch_size=64 ) test_datagen = ImageDataGenerator( horizontal_flip=True, width_shift...
_____no_output_____
MIT
Project Portfolio/cnn-cifar10-tf2-v12_Notebook_CarlosCabano.ipynb
CarlosCabano/carloscabano.github.io
6.3 Generador de datos
sample = random.choice(range(0,1457)) image = x_train[sample] plt.imshow(image, cmap=plt.cm.binary) sample = random.choice(range(0,1457)) example_generator = train_datagen.flow( x_train[sample:sample+1], y_train_encoded[sample:sample+1], batch_size=64 ) plt.figure(figsize=(12, 12)) for i in ra...
_____no_output_____
MIT
Project Portfolio/cnn-cifar10-tf2-v12_Notebook_CarlosCabano.ipynb
CarlosCabano/carloscabano.github.io
7. Entrenamiento
t = time.perf_counter() steps=int(x_train.shape[0]/64) history = model.fit(train_generator, epochs=100, use_multiprocessing=False, batch_size= 64, validation_data=validation_generator, steps_per_epoch=steps, callbacks=[callback_val_loss, callback_val_accuracy]) elapsed_time = datetime.timedelta(seconds=(time.perf_coun...
Tiempo de entrenamiento: 0:52:12.653343
MIT
Project Portfolio/cnn-cifar10-tf2-v12_Notebook_CarlosCabano.ipynb
CarlosCabano/carloscabano.github.io
8. Evaluamos los resultados
_, acc = model.evaluate(x_test, y_test_encoded, verbose=0) print('> %.3f' % (acc * 100.0)) plt.title('Cross Entropy Loss') plt.plot(history.history['loss'], color='blue', label='train') plt.plot(history.history['val_loss'], color='orange', label='test') plt.show() plt.title('Classification Accuracy') plt.plot(history....
_____no_output_____
MIT
Project Portfolio/cnn-cifar10-tf2-v12_Notebook_CarlosCabano.ipynb
CarlosCabano/carloscabano.github.io
Dibujamos las primeras imágenes:
i = 0 for l in cifar10_labels: print(i, l) i += 1 num_rows = 5 num_cols = 4 start = 650 num_images = num_rows*num_cols plt.figure(figsize=(2*2*num_cols, 2*num_rows)) for i in range(num_images): plt.subplot(num_rows, 2*num_cols, 2*i+1) plot_image(i+start, predictions[i+start], y_test, x_test) plt.subplot(...
0 airplane 1 automobile 2 bird 3 cat 4 deer 5 dog 6 frog 7 horse 8 ship 9 truck
MIT
Project Portfolio/cnn-cifar10-tf2-v12_Notebook_CarlosCabano.ipynb
CarlosCabano/carloscabano.github.io
Summary About the DatasetThe data files train.csv and test.csv contain gray-scale images of hand-drawn digits, from zero through nine.Each image is 28 pixels in height and 28 pixels in width, for a total of 784 pixels in total. Each pixel has a single pixel-value associated with it, indicating the lightness or darkne...
import numpy as np import pandas as pd import tensorflow as tf import keras.preprocessing.image import sklearn.preprocessing import sklearn.model_selection import sklearn.metrics import sklearn.linear_model import sklearn.naive_bayes import sklearn.tree import sklearn.ensemble import os; import datetime import cv2 i...
Platform deatils Windows-10-10.0.15063-SP0 Python version 3.6.2
BSD-3-Clause
MNIST-image-classification-using-TF.ipynb
jpnevrones/Digit-Recognizer
Additional info: I am going to use the Kaggle csv based data set but MNIST Data set can also be downloaded and extracted using the below functions. Function to downlaod and Extract MNIST Dataset
url = 'http://commondatastorage.googleapis.com/books1000/' last_percent_reported = None def download_progress_hook(count, blockSize, totalSize): """A hook to report the progress of a download. This is mostly intended for users with slow internet connections. Reports every 1% change in download progress. """ gl...
train.csv loaded: data_df(42000,785) test.csv loaded: test_df(28000, 784) x_test.shape = (28000, 28, 28, 1)
BSD-3-Clause
MNIST-image-classification-using-TF.ipynb
jpnevrones/Digit-Recognizer
Preprocessing Normalize data and split into training and validation sets- In order to scale feature that robust to outlier you can use sklearn.preprocessing.RobustScaler() - rtoo = sklearn.preprocessing.RobustScaler() - rtoo.fit(data) - data = rtoo.transform(data) - or you can do standraization by...
# function to normalize data def normalize_data(data): data = data / data.max() # convert from [0:255] to [0.:1.] return data # class labels to one-hot vectors e.g. 1 => [0 1 0 0 0 0 0 0 0 0] def dense_to_one_hot(labels_dense, num_classes): num_labels = labels_dense.shape[0] index_offset = np.aran...
x_train_valid.shape = (42000, 28, 28, 1) y_train_valid_labels.shape = (42000,) image_size = 784 image_width = 28 image_height = 28 labels_count = 10
BSD-3-Clause
MNIST-image-classification-using-TF.ipynb
jpnevrones/Digit-Recognizer
Data augmenttaionlets stick to basics like rotations, translations, zoom using keras
def generate_images(imgs): # rotations, translations, zoom image_generator = keras.preprocessing.image.ImageDataGenerator( rotation_range = 10, width_shift_range = 0.1 , height_shift_range = 0.1, zoom_range = 0.1) # get transformed images imgs = image_generator.flow(imgs.copy(), np....
_____no_output_____
BSD-3-Clause
MNIST-image-classification-using-TF.ipynb
jpnevrones/Digit-Recognizer
Benchmarking on some basic ML modelsAs we have our training data ready lets run couple of basic machine elarning model, I would consider these models to kind of create a baseline which would help me later own to generlize the performance of my model. In simple word these would give me datapoints to compare the perfor...
logistic_regression = sklearn.linear_model.LogisticRegression(verbose=0, solver='lbfgs',multi_class='multinomial') extra_trees = sklearn.ensemble.ExtraTreesClassifier(verbose=0) random_forest = sklearn.ensemble.RandomForestClassifier(verbose=0) bench_markingDict = {'logistic_regression': logistic_regression, ...
1 : logistic_regression train/valid accuracy = 0.940/0.920 1 : extra_trees train/valid accuracy = 1.000/0.947 1 : random_forest train/valid accuracy = 0.999/0.941 2 : logistic_regression train/valid accuracy = 0.940/0.922 2 : extra_trees train/valid accuracy = 1.000/0.949 2 : random_forest train/valid accuracy = 0.999/...
BSD-3-Clause
MNIST-image-classification-using-TF.ipynb
jpnevrones/Digit-Recognizer
Neural network -Lets get to the fun part Neural network
class nn_class: # class that implements the neural network # constructor def __init__(self, nn_name = 'nn_1'): # hyperparameters self.s_f_conv1 = 3; # filter size of first convolution layer (default = 3) self.n_f_conv1 = 36; # number of features of first convolution layer (default = ...
_____no_output_____
BSD-3-Clause
MNIST-image-classification-using-TF.ipynb
jpnevrones/Digit-Recognizer
plan_pole_transectVisualize pole locations on Pea Island beach transect.Profiles were extracted from SfM maps by Jenna on 31 August 2021 - Provisional Data. Read in profilesUse pandas to read profiles; pull out arrays of x, y (UTM meters, same for all profiles) and z (m NAVD88). Calculate distance along profile fro...
import pandas as pd import numpy as np import matplotlib.pyplot as plt fnames = ['crossShore_profile_2019_preDorian.xyz', 'crossShore_profile_2019_postDorian.xyz', 'crossShore_profile_2020_Sep.xyz', 'crossShore_profile_2021_Apr.xyz'] df0 = pd.read_csv(fnames[0],skiprows=1,sep=',',header=None,names=['x'...
_____no_output_____
CC0-1.0
plan_pole_transect.ipynb
csherwood-usgs/DUNEX
Use Stockdon equation to calculate runup for slope on upper beach and offshore waves
def calcR2(H,T,slope,igflag=0): """ % % [R2,S,setup, Sinc, SIG, ir] = calcR2(H,T,slope,igflag); % % Calculated 2% runup (R2), swash (S), setup (setup), incident swash (Sinc) % and infragravity swash (SIG) elevations based on parameterizations from runup paper % also Iribarren (ir) % Augu...
R2: 1.75, max HW: 2.75
CC0-1.0
plan_pole_transect.ipynb
csherwood-usgs/DUNEX
Plot profiles and pole locationsApply arbitrary vertical offset to profiles to collapse them. The range of these offsets suggests fairly big uncertainty in the elevation data. Define a function to plot pole at ground level with 2 m embedded and 3 m above ground. Make plot with vertical exaggeration of 2.1 bazillion.`...
# eyeball offsets to make plot easier to interpret (note this elevates May profile) ioff1 = -.25 ioff2 = +.3 ioff3 = +.25 mhw = 0.77 # estimated from VDatum edist = -5 # distance to offset eroded profile #pole_locations = [96, 89, 82, 75, 68, 55, 42] # Chris's original pole_locations = [104, 95, 84, 76, 68, 55, 42] #...
dist, z: 104.0, 0.9 utmx, utmy: 456574.3, 3948281.3 dist, z: 95.0, 1.4 utmx, utmy: 456565.4, 3948279.8 dist, z: 84.0, 2.2 utmx, utmy: 456554.6, 3948278.0 dist, z: 76.0, 3.5 utmx, utmy: 456546.7, 3948276.7 dist, z: 68.0, 4.5 utmx, utmy: 456538.8, 3948275.4 dist, z: 55.0, 4.9 utmx, utmy: 456526.0, 3948273.2 d...
CC0-1.0
plan_pole_transect.ipynb
csherwood-usgs/DUNEX
**Comments from Katherine here:** How much overlap do we really need? Why is this important? Are there severe edge effects? It seems to me that we should either 1) try to cover as much of the profile as we can with the LiDARs since you're interested in runup (i.e., minimal to no overlap) or 2) cluster poles in areas wh...
# plot beach slope slope = np.diff(z3)/np.diff(dist) plt.plot(dist,0.1*(z3+ioff3),'-k',linewidth=2,label='May 2021') plt.plot(dist[1:],slope) plt.ylim((-.5,.5)) # plot smoothed slope v. index def running_mean(x, N): return np.convolve(x, np.ones((N,))/N)[(N-1):] N = int(2/.12478) print(N) sslope = running_mean(slop...
-0.05149328538733515 0.0008375655872101676
CC0-1.0
plan_pole_transect.ipynb
csherwood-usgs/DUNEX
We are trying to predict weather the classification is normal or abnormal.
dataset.info() dataset.describe() import seaborn as sns sns.set_style("whitegrid"); sns.FacetGrid(dataset, hue="class", size=5.5) \ .map(plt.scatter, "pelvic_incidence", "pelvic_tilt numeric") \ .add_legend(); plt.show(); sns.set_style("whitegrid"); sns.pairplot(dataset, hue="class", size=3); plt.show() for name...
_____no_output_____
Unlicense
Project/KNN AND NB Project.ipynb
foday1989/FODAY-DS.Portfolio.io
Analysis of how mentions of a stock on WSB relates to stock pricesWallStreetBets is a popular forum on reddit known for going to the moon, apes and stonks. Jokes aside, despite all of the ridiculous bad trades, undecipherable jargon and love for memes, it's effect on the stock market is undeniable. Therefore in this p...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import warnings import os import tensorflow as tf from datetime import datetime warnings.filterwarnings('ignore') from google.colab import drive drive.mount('/content/drive')
Mounted at /content/drive
MIT
wsb_sentiment.ipynb
kenzeng24/wsb-analysis
Reddit Post DataSource: https://huggingface.co/datasets/SocialGrep/reddit-wallstreetbets-aug-2021
# TODO: add shortcut from shared drive for: # wsb-aug-2021-comments.csv def load_data(filename, path="/content/drive/MyDrive/"): # read csv file and drop indices df = pd.read_csv(os.path.join(path, filename)) df = df.dropna(axis=0) # convert utc to datetime format df["date"] = pd.to_datetime(df...
_____no_output_____
MIT
wsb_sentiment.ipynb
kenzeng24/wsb-analysis
Overal Sentiment on the Subreddit
def sentiment_bins(df): # extract sentiment sent_df = df[["date","sentiment"]] bins = {} bins["positive"] = sent_df.loc[sent_df["sentiment"] > 0.25,:] bins["negative"] = sent_df.loc[sent_df["sentiment"] < -0.25,:] bins["neutral"] = sent_df.loc[sent_df["sentiment"].between(-0.25,0.25),:] ...
_____no_output_____
MIT
wsb_sentiment.ipynb
kenzeng24/wsb-analysis