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
--- Question 2 Write the training loop* Create the loss function. This should be a loss function suitable for multi-class classification.* Create the metric accumulator. This should the compute and store the accuracy of the model during training* Create the trainer with the `adam` optimizer and learning rate of `0.002`...
def train(network, training_dataloader, batch_size, epochs): """ Should take an initialized network and train that network using data from the data loader. :param network: initialized gluon network to be trained :type network: gluon.Block :param training_dataloader: the training DataLoader...
_____no_output_____
MIT
Module_5_LeNet_on_MNIST (1).ipynb
vigneshb-it19/AWS-Computer-Vision-GluonCV
Let's define and initialize a network to test the train function.
net = gluon.nn.Sequential() net.add(gluon.nn.Conv2D(channels=6, kernel_size=5, activation='relu'), gluon.nn.MaxPool2D(pool_size=2, strides=2), gluon.nn.Conv2D(channels=16, kernel_size=3, activation='relu'), gluon.nn.MaxPool2D(pool_size=2, strides=2), gluon.nn.Flatten(), gluon.nn....
0 0.93415 1 0.9572583333333333 2 0.9668111111111111 3 0.972375 4 0.97606
MIT
Module_5_LeNet_on_MNIST (1).ipynb
vigneshb-it19/AWS-Computer-Vision-GluonCV
--- Question 3 Write the validation loop* Create the metric accumulator. This should the compute and store the accuracy of the model on the validation set* Write the validation loop
def validate(network, validation_dataloader): """ Should compute the accuracy of the network on the validation set. :param network: initialized gluon network to be trained :type network: gluon.Block :param validation_dataloader: the training DataLoader provides batches for data for every i...
_____no_output_____
MIT
Module_5_LeNet_on_MNIST (1).ipynb
vigneshb-it19/AWS-Computer-Vision-GluonCV
Callbacks and Multiple inputs
import pandas as pd import numpy as np %matplotlib inline import matplotlib.pyplot as plt from sklearn.preprocessing import scale from keras.optimizers import SGD from keras.layers import Dense, Input, concatenate, BatchNormalization from keras.callbacks import EarlyStopping, TensorBoard, ModelCheckpoint from keras.m...
_____no_output_____
MIT
solutions_do_not_open/Lab_05_DL Callbacks and Multiple Inputs_solution.ipynb
Dataweekends/global_AI_conference_Jan_2018
HypothesisI believe that random forest will have a better score since the data frame has a lot of catergorical data and a lot of columns in general.
# Train the Logistic Regression model on the unscaled data and print the model score classifier = LogisticRegression() classifier.fit(X_dummies_train, y_label_1) print(f"Training Data Score: {classifier.score(X_dummies_train, y_label_1)}") print(f"Testing Data Score: {classifier.score(X_dummies_test, y_label_2)}") # Tr...
Training Score: 1.0 Testing Score: 0.646958740961293
MIT
Credit Risk Evaluator.ipynb
J-Schea29/Supervised-Machine-Learning-Challenge
Hypothesis 2I think that by scaling my scores are going to get better and that the testing and training will be less spread out.
# Scale the data scaler = StandardScaler().fit(X_dummies_train) X_train_scaled = scaler.transform(X_dummies_train) X_test_scaled = scaler.transform(X_dummies_test) X_test_scaled # Train the Logistic Regression model on the scaled data and print the model score classifier = LogisticRegression() classifier.fit(X_train_sc...
Training Score: 1.0 Testing Score: 0.6480221182475542
MIT
Credit Risk Evaluator.ipynb
J-Schea29/Supervised-Machine-Learning-Challenge
IntroHere's a simple example where we produce a set of plots, called a tear sheet, for a single stock. Imports and Settings
# silence warnings import warnings warnings.filterwarnings('ignore') import yfinance as yf import pyfolio as pf %matplotlib inline
_____no_output_____
Apache-2.0
pyfolio/examples/single_stock_example.ipynb
MBounouar/pyfolio-reloaded
Download daily stock prices using yfinance Pyfolio expects tz-aware input set to UTC timezone. You may have to import `yfinance` first by running:```bashpip install yfinance```
fb = yf.Ticker('FB') history = fb.history('max') history.index = history.index.tz_localize('utc') history.info() returns = history.Close.pct_change()
_____no_output_____
Apache-2.0
pyfolio/examples/single_stock_example.ipynb
MBounouar/pyfolio-reloaded
Create returns tear sheetThis will show charts and analysis about returns of the single stock.
pf.create_returns_tear_sheet(returns, live_start_date='2020-1-1')
_____no_output_____
Apache-2.0
pyfolio/examples/single_stock_example.ipynb
MBounouar/pyfolio-reloaded
Import Data
import numpy as np from sklearn.model_selection import GridSearchCV import matplotlib.pyplot as plt # load data import os from google.colab import drive drive.mount('/content/drive') filedir = './drive/My Drive/Final/CNN_data' with open(filedir + '/' + 'feature_extracted', 'rb') as f: X = np.load(f) with open(filedir...
_____no_output_____
MIT
cnn_classifier.ipynb
Poxls88/triggerword
CLF1 Ridge Classifier
''' from sklearn.linear_model import RidgeClassifier parameters = {'alpha':[1]} rc = RidgeClassifier(alpha = 1) clf = GridSearchCV(rc, parameters, cv=3) clf.fit(X[:30], Y[:30]) clf.best_estimator_.fit(X[:30], Y[:30]).score(X, Y) clf.best_index_ ''' from sklearn.linear_model import RidgeClassifier def clf_RidgeClassifi...
_____no_output_____
MIT
cnn_classifier.ipynb
Poxls88/triggerword
CLF2 SVM
from sklearn.svm import SVC def clf_SVM(X_train, Y_train, X_test, Y_test): parameters = {'C':[10, 1, 1e-1, 1e-2, 1e-3]} svc = SVC(kernel='linear') clf = GridSearchCV(svc, parameters, cv=3, return_train_score=True, iid=False) clf.fit(X_train, Y_train) results = clf.cv_results_ opt_index = clf.best_index_ t...
_____no_output_____
MIT
cnn_classifier.ipynb
Poxls88/triggerword
CLF3 LDA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis def clf_lda(Xtrain, Ytrain, Xtest, Ytest): """ Input: training data, labels, testing data, labels Output: training set mean prediciton accuracy, validation accuracy = None, testing set mean prediction accuracy Note: LDA has no hyperparamete...
_____no_output_____
MIT
cnn_classifier.ipynb
Poxls88/triggerword
CLF4 KNN
from sklearn.neighbors import KNeighborsClassifier def clf_KNN(X_train, Y_train, X_test, Y_test): parameters = {'n_neighbors':[1,5,20]} knn = KNeighborsClassifier(algorithm='auto', weights='uniform') clf = GridSearchCV(knn, parameters, cv=3, return_train_score=True, iid=False) clf.fit(X_train, Y_train) result...
_____no_output_____
MIT
cnn_classifier.ipynb
Poxls88/triggerword
CLF5 Decision Tree
from sklearn.tree import DecisionTreeClassifier def clf_DecisionTree(X_train, Y_train, X_test, Y_test): parameters = {'max_depth':[5,10,15,20,25], 'criterion':['entropy', 'gini']} dtc = DecisionTreeClassifier() clf = GridSearchCV(dtc, parameters, cv=3, return_train_score=True, iid=False) clf.fit(X_train, Y_trai...
_____no_output_____
MIT
cnn_classifier.ipynb
Poxls88/triggerword
Testing On Data
clf_list = [clf_RidgeClassifier, clf_SVM, clf_lda, clf_KNN, clf_DecisionTree] def test_trial(X_shuffled, Y_shuffled): global clf_list error = np.zeros((3,5,3)) # partition(3) * clf(5) * error(3) # (8/2,5/5,2/8) * (clf_list) * (trn,val,tst) opt_param = np.empty((3,5), dtype=dict) # part...
_____no_output_____
MIT
cnn_classifier.ipynb
Poxls88/triggerword
View source on GitHub Notebook Viewer Run in binder Run in Google Colab Install Earth Engine API and geemapInstall the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geemap](https://github.com/giswqs/geemap). The **geemap** Python package is built upon the [ipy...
# Installs geemap package import subprocess try: import geemap except ImportError: print('geemap package not installed. Installing ...') subprocess.check_call(["python", '-m', 'pip', 'install', 'geemap']) # Checks whether this notebook is running on Google Colab try: import google.colab import gee...
_____no_output_____
MIT
Image/extract_value_to_points.ipynb
YuePanEdward/earthengine-py-notebooks
Create an interactive map The default basemap is `Google Satellite`. [Additional basemaps](https://github.com/giswqs/geemap/blob/master/geemap/geemap.pyL13) can be added using the `Map.add_basemap()` function.
Map = emap.Map(center=[40,-100], zoom=4) Map.add_basemap('ROADMAP') # Add Google Map Map
_____no_output_____
MIT
Image/extract_value_to_points.ipynb
YuePanEdward/earthengine-py-notebooks
Add Earth Engine Python script
# Add Earth Engine dataset # Input imagery is a cloud-free Landsat 8 composite. l8 = ee.ImageCollection('LANDSAT/LC08/C01/T1') image = ee.Algorithms.Landsat.simpleComposite(**{ 'collection': l8.filterDate('2018-01-01', '2018-12-31'), 'asFloat': True }) # Use these bands for prediction. bands = ['B2', 'B3', 'B...
_____no_output_____
MIT
Image/extract_value_to_points.ipynb
YuePanEdward/earthengine-py-notebooks
Display Earth Engine data layers
Map.addLayerControl() # This line is not needed for ipyleaflet-based Map. Map
_____no_output_____
MIT
Image/extract_value_to_points.ipynb
YuePanEdward/earthengine-py-notebooks
FmriprepToday, many excellent general-purpose, open-source neuroimaging software packages exist: [SPM](https://www.fil.ion.ucl.ac.uk/spm/) (Matlab-based), [FSL](https://fsl.fmrib.ox.ac.uk/fsl/fslwiki), [AFNI](https://afni.nimh.nih.gov/), and [Freesurfer](https://surfer.nmr.mgh.harvard.edu/) (with a shell interface). W...
import os print(os.listdir('bids/derivatives/fmriprep'))
_____no_output_____
MIT
NI-edu/fMRI-introduction/week_4/fmriprep.ipynb
lukassnoek/NI-edu
As said, Fmriprep outputs a directory with results (`sub-03`) and an associated HTML-file with a summary of the (intermediate and final) results. Let's check the directory with results first:
from pprint import pprint # pprint stands for "pretty print", sub_path = os.path.join('bids/derivatives/fmriprep', 'sub-03') pprint(sorted(os.listdir(sub_path)))
_____no_output_____
MIT
NI-edu/fMRI-introduction/week_4/fmriprep.ipynb
lukassnoek/NI-edu
The `figures` directory contains several figures with the result of different preprocessing stages (like functional → high-res anatomical registration), but these figures are also included in the HTML-file, so we'll leave that for now. The other two directories, `anat` and `func`, contain the preprocessed anatomic...
anat_path = os.path.join(sub_path, 'anat') pprint(os.listdir(anat_path))
_____no_output_____
MIT
NI-edu/fMRI-introduction/week_4/fmriprep.ipynb
lukassnoek/NI-edu
Here, we see a couple of different files. There are both (preprocessed) nifti images (`*.nii.gz`) and associated meta-data (plain-text files in JSON format: `*.json`).Importantly, the nifti outputs are in two different spaces: one set of files are in the original "T1 space", so without any resampling to another space (...
func_path = os.path.join(sub_path, 'func') pprint(os.listdir(func_path))
_____no_output_____
MIT
NI-edu/fMRI-introduction/week_4/fmriprep.ipynb
lukassnoek/NI-edu
Again, like the files in the `anat` folder, the functional outputs are available in two spaces: `T1w` and `MNI152NLin2009cAsym`. In terms of actual images, there are preprocessed BOLD files (ending in `preproc_bold.nii.gz`), the functional volume used for "functional → anatomical" registration (ending in `boldref....
import pandas as pd conf_path = os.path.join(func_path, 'sub-03_task-flocBLOCKED_desc-confounds_regressors.tsv') conf = pd.read_csv(conf_path, sep='\t') conf.head()
_____no_output_____
MIT
NI-edu/fMRI-introduction/week_4/fmriprep.ipynb
lukassnoek/NI-edu
Confound files from Fmriprep contain a large set of confounds, ranging from motion parameters (`rot_x`, `rot_y`, `rot_z`, `trans_x`, `trans_y`, and `trans_z`) and their derivatives (`*derivative1`) and squares (`*_power2`) to the average signal from the brain's white matter and cerebrospinal fluid (CSF), which should c...
from IPython.display import IFrame IFrame(src='./bids/derivatives/fmriprep/sub-03.html', width=700, height=600)
_____no_output_____
MIT
NI-edu/fMRI-introduction/week_4/fmriprep.ipynb
lukassnoek/NI-edu
Desafio 1 do [Paulo Silveira](https://twitter.com/paulo_caelum) Encontrar quantos filmes não possuem avaliações e quais são esses filmes
count_rating_by_movieId = movies_rating.pivot_table(index=['movieId'], aggfunc='size').rename('votes') count_rating_by_movieId movies_with_votes = movies.join(count_rating_by_movieId, on="movieId") movies_with_votes[movies_with_votes['votes'].isnull()]
_____no_output_____
MIT
desafios_aula01.ipynb
justapixel/QuarentenaDados
Desafio 2 do [Guilherme Silveira](https://twitter.com/guilhermecaelum) Alterar o nome da coluna nota do dataframe filmes_com_media para nota_média após o join.
rating = movies_rating.groupby("movieId")['rating'].mean() rating filmes_com_media = movies.join(rating, on="movieId").rename(columns={'rating': 'nota_média'}) filmes_com_media
_____no_output_____
MIT
desafios_aula01.ipynb
justapixel/QuarentenaDados
Desafio 3 do [Guilherme Silveira](https://twitter.com/guilhermecaelum) Adicionar ao filmes_com_media o total de votos de cada filme
movies_with_rating_and_votes = filmes_com_media.join(count_rating_by_movieId, on="movieId") movies_with_rating_and_votes
_____no_output_____
MIT
desafios_aula01.ipynb
justapixel/QuarentenaDados
Desafio 4 do [Thiago Gonçalves](https://twitter.com/tgcsantos) Arredondar as médias (coluna de nota média) para duas casas decimais.
movies_with_rating_and_votes = movies_with_rating_and_votes.round({'nota_média':2}) movies_with_rating_and_votes
_____no_output_____
MIT
desafios_aula01.ipynb
justapixel/QuarentenaDados
Desafio 5 do [Allan Spadini](https://twitter.com/allanspadini) Descobrir os generos dos filmes (quais são eles, únicos). (esse aqui o bicho pega)
genres_split = movies.genres.str.split("|") genres_split genres = pd.DataFrame({'genre':np.concatenate(genres_split.values)}) list_genres = genres.groupby('genre').size().reset_index(name='count') list_genres['genre']
_____no_output_____
MIT
desafios_aula01.ipynb
justapixel/QuarentenaDados
Desafio 6 da [Thais André](https://twitter.com/thais_tandre) Contar o número de aparições de cada genero.
list_genres
_____no_output_____
MIT
desafios_aula01.ipynb
justapixel/QuarentenaDados
Desafio 7 do [Guilherme Silveira](https://twitter.com/guilhermecaelum) Plotar o gráfico de aparições de cada genero. Pode ser um gráfico de tipo igual a barra.
list_genres[['genre', 'count']].sort_values(by=['genre'], ascending=True).plot(x='genre', kind='barh', title="Generos")
_____no_output_____
MIT
desafios_aula01.ipynb
justapixel/QuarentenaDados
Write a program to remove characters from a string starting from zero up to n and return a new string.__Example:__remove_char("Untitled", 4) so output must be tled. Here we need to remove first four characters from a string
def remove_char(a, b): # Write your code here print("started") a="Untitled" b=4 remove_char(a,b)
started
MIT
test.ipynb
sharaththota/Test
Write a program to find how many times substring appears in the given string.__Example:__"You can use Markdown to format documentation you add to Markdown cells" sub_string: MarkdownIn the above the substring Markdown is appeared two times.So the count is two
def sub_string(m_string,s_string): # Write your code here print("started") m_string="You can use Markdown to format documentation you add to Markdown cells" s_string="Markdown" sub_string(m_string,s_string)
started
MIT
test.ipynb
sharaththota/Test
Write a program to check if the given number is a palindrome number.__Exapmle:__A palindrome number is a number that is same after reverse. For example 242, is the palindrome number
def palindrom_check(a): # Write your code here print("started") palindrom_check(242)
started
MIT
test.ipynb
sharaththota/Test
Write a program to Extract Unique values from dictionary values__Example:__test= {"gfg': [5, 6, 7, 8], 'is': [10, 11, 7, 5], 'best' : [6, 12, 10, 8], 'for': [1, 2, 5]}out_put: [1, 2, 5, 6, 7, 8, 10, 11, 12]
def extract_unique(a): # Write your code here print("started") test= {'gfg': [5, 6, 7, 8], 'is': [10, 11, 7, 5], 'best' : [6, 12, 10, 8], 'for': [1, 2, 5]} extract_unique(test)
started
MIT
test.ipynb
sharaththota/Test
Write a program to find the dictionary with maximum count of pairs__Example:__Input: test_list = [{"gfg": 2, "best":4}, {"gfg": 2, "is" : 3, "best": 4, "CS":9}, {"gfg":2}] Output: 4
def max_count(a): # Write your code here print("started") test_list = [{"gfg": 2, "best":4}, {"gfg": 2, "is" : 3, "best": 4, "CS":9}, {"gfg":2}] max_count(test_list)
started
MIT
test.ipynb
sharaththota/Test
Access the value of key 'history' from the below dict
def key_access(a): # Write your code here print("started") sampleDict = { "class":{ "student":{ "name": "Mike", "marks" : { "physics":70, "history":80 } } } } key_access(sampleDict)
started
MIT
test.ipynb
sharaththota/Test
Print the value of key hair Print the third element of the key interested in
def third_ele(a): # Write your code here print("started") info={ "personal data":{ "name":"Lauren", "age":20, "major":"Information Science", "physical_features":{ "color":{ "eye":"blue", "hair":"brown" }, "hei...
_____no_output_____
MIT
test.ipynb
sharaththota/Test
Print the Unique values from attempts column
def un_values(df): # Write your code here print("started") un_values(df)
started
MIT
test.ipynb
sharaththota/Test
Print the top five rows from the data frame
def top_five(df): # Write your code here print("started") top_five(df)
started
MIT
test.ipynb
sharaththota/Test
Print the max and min values of the coulmn attempts
def min_max(df): # Write your code here print("started") min_max(df)
started
MIT
test.ipynb
sharaththota/Test
Import data
df = pd.read_hdf('data/car.h5') df.shape df.columns
_____no_output_____
MIT
matrix_two/day3.ipynb
kmwolowiec/data_workshop
Dummy Model
df.select_dtypes(np.number).columns X = df['car_id'] y = df['price_value'] model = DummyRegressor() model.fit(X, y) y_pred = model.predict(X) mae(y, y_pred) [x for x in df.columns if 'price' in x] df['price_currency'].value_counts() df = df[ df.price_currency == 'PLN'] df.shape
_____no_output_____
MIT
matrix_two/day3.ipynb
kmwolowiec/data_workshop
Features
df.sample(5) suffix_cat = '__cat' for feat in df.columns: if isinstance(df[feat][0], list):continue factorized_values = df[feat].factorize()[0] if suffix_cat in feat: df[feat] = factorized_values else: df[feat+suffix_cat] = factorized_values cat_feats = [x for x in df.columns i...
Counting objects: 1 Counting objects: 4, done. Delta compression using up to 2 threads. Compressing objects: 25% (1/4) Compressing objects: 50% (2/4) Compressing objects: 75% (3/4) Compressing objects: 100% (4/4) Compressing objects: 100% (4/4), done. Writing objects: 25% (1/4) Writing objects: 5...
MIT
matrix_two/day3.ipynb
kmwolowiec/data_workshop
Pattern Mining Library
source("https://raw.githubusercontent.com/eogasawara/mylibrary/master/myPreprocessing.R") loadlibrary("arules") loadlibrary("arulesViz") loadlibrary("arulesSequences") data(AdultUCI) dim(AdultUCI) head(AdultUCI)
_____no_output_____
MIT
todo/Pattern.ipynb
lucasgiutavares/mylibrary
Removing attributes
AdultUCI$fnlwgt <- NULL AdultUCI$"education-num" <- NULL
_____no_output_____
MIT
todo/Pattern.ipynb
lucasgiutavares/mylibrary
Conceptual Hierarchy and Binning
AdultUCI$age <- ordered(cut(AdultUCI$age, c(15,25,45,65,100)), labels = c("Young", "Middle-aged", "Senior", "Old")) AdultUCI$"hours-per-week" <- ordered(cut(AdultUCI$"hours-per-week", c(0,25,40,60,168)), ...
_____no_output_____
MIT
todo/Pattern.ipynb
lucasgiutavares/mylibrary
Convert to transactions
AdultTrans <- as(AdultUCI, "transactions")
_____no_output_____
MIT
todo/Pattern.ipynb
lucasgiutavares/mylibrary
A Priori
rules <- apriori(AdultTrans, parameter=list(supp = 0.5, conf = 0.9, minlen=2, maxlen= 10, target = "rules"), appearance=list(rhs = c("capital-gain=None"), default="lhs"), control=NULL) inspect(rules) rules_a <- as(rules, "data.frame") head(rules_a)
_____no_output_____
MIT
todo/Pattern.ipynb
lucasgiutavares/mylibrary
Analysis of Rules
imrules <- interestMeasure(rules, transactions = AdultTrans) head(imrules)
_____no_output_____
MIT
todo/Pattern.ipynb
lucasgiutavares/mylibrary
Removing redundant rules
nrules <- rules[!is.redundant(rules)] arules::inspect(nrules)
lhs rhs support confidence [1] {hours-per-week=Full-time} => {capital-gain=None} 0.5435895 0.9290688 [2] {sex=Male} => {capital-gain=None} 0.6050735 0.9051455 [3] {workclass=Private} => {capital-gain=None} 0.6413742 0.9239073 [4] ...
MIT
todo/Pattern.ipynb
lucasgiutavares/mylibrary
Showing the transactions that support the rulesIn this example, we can see the transactions (trans) that support rules 1.
st <- supportingTransactions(nrules[1], AdultTrans) trans <- unique(st@data@i) length(trans) print(c(length(trans)/length(AdultTrans), nrules[1]@quality$support))
_____no_output_____
MIT
todo/Pattern.ipynb
lucasgiutavares/mylibrary
Now we can see the transactions (trans) that support rules 1 and 2. As can be observed, the support for both rules is not the sum of the support of each rule.
st <- supportingTransactions(nrules[1:2], AdultTrans) trans <- unique(st@data@i) length(trans) print(c(length(trans)/length(AdultTrans), nrules[1:2]@quality$support))
_____no_output_____
MIT
todo/Pattern.ipynb
lucasgiutavares/mylibrary
Rules visualization
options(repr.plot.width=7, repr.plot.height=4) plot(rules) options(repr.plot.width=7, repr.plot.height=4) plot(rules, method="paracoord", control=list(reorder=TRUE))
_____no_output_____
MIT
todo/Pattern.ipynb
lucasgiutavares/mylibrary
Sequence Mining
x <- read_baskets(con = system.file("misc", "zaki.txt", package = "arulesSequences"), info = c("sequenceID","eventID","SIZE")) as(x, "data.frame") s1 <- cspade(x, parameter = list(support = 0.4), control = list(verbose = TRUE)) as(s1, "data.frame")
parameter specification: support : 0.4 maxsize : 10 maxlen : 10 algorithmic control: bfstype : FALSE verbose : TRUE summary : FALSE tidLists : FALSE preprocessing ... 1 partition(s), 0 MB [0.046s] mining transactions ... 0 MB [0.032s] reading sequences ... [0.027s] total elapsed time: 0.105s
MIT
todo/Pattern.ipynb
lucasgiutavares/mylibrary
Load data
df = pd.DataFrame({ 'x': [4.5, 4.9, 5.0, 4.8, 5.8, 5.6, 5.7, 5.8], 'y': [35, 38, 45, 49, 59, 65, 73, 82], 'z': [0, 0, 0, 0, 1, 1, 1, 1] }) df plt.scatter(df['x'], df['y'], c=df['z'])
_____no_output_____
MIT
docs/!ml/notebooks/Perceptron.ipynb
a-mt/dev-roadmap
Train model
def fit(X, y, max_epochs=500): """ X : numpy 2D array. Each row corresponds to one training example. y : numpy 1D array. Label (0 or 1) of each example. """ n = X.shape[1] # Initialize weights weights = np.zeros((n, )) bias = 0.0 for _ in range(max_epochs): errors = 0 ...
_____no_output_____
MIT
docs/!ml/notebooks/Perceptron.ipynb
a-mt/dev-roadmap
Plot predictions
def plot_decision_boundary(): # Draw points plt.scatter(X[:,0], X[:,1], c=y) a = -weights[0]/weights[1] b = -bias/weights[1] # Draw hyperplane with margin _X = np.arange(X[:,0].min(), X[:,0].max()+1, .1) _Y = _X * a + b plt.plot(_X, _Y) plot_decision_boundary() def plot_contour(): ...
_____no_output_____
MIT
docs/!ml/notebooks/Perceptron.ipynb
a-mt/dev-roadmap
Compare with logistic regression
from sklearn.linear_model import LogisticRegression model = LogisticRegression(C=1e20, solver='liblinear', random_state=0) model.fit(X, y) weights = model.coef_[0] bias = model.intercept_[0] plot_decision_boundary()
_____no_output_____
MIT
docs/!ml/notebooks/Perceptron.ipynb
a-mt/dev-roadmap
Compare with SVM
from sklearn import svm model = svm.SVC(kernel='linear', C=1.0) model.fit(X, y) weights = model.coef_[0] bias = model.intercept_[0] plot_decision_boundary()
_____no_output_____
MIT
docs/!ml/notebooks/Perceptron.ipynb
a-mt/dev-roadmap
Gradient Boosting
from sklearn.ensemble import GradientBoostingClassifier from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split cancer = load_breast_cancer() X_train, X_test, y_train, y_test = train_test_split( cancer.data, cancer.target, random_state=0) gbrt = GradientBoostingClassif...
_____no_output_____
MIT
notebooks/extra - Gradient Boosting.ipynb
lampsonnguyen/ml-training-advance
import numpy as np import matplotlib.pyplot as plt
_____no_output_____
MIT
delft course dr weijermars/stress_tensor.ipynb
rksin8/reservoir-geomechanics
Introduction to vectors Plot vector that has notation (2,4,4). Another vector has notation (1,2,3). Find the direction cosines of each vector, the angles of each vector to the three axes, and the angle between the two vectors!
from mpl_toolkits.mplot3d import axes3d X = np.array((0, 0)) Y= np.array((0, 0)) Z = np.array((0, 0)) U = np.array((2, 1)) V = np.array((4, 2)) W = np.array((4, 3)) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.quiver(X, Y, Z, U, V, W) ax.set_xlim([-4, 4]) ax.set_ylim([-4, 4]) ax.set_zlim([-4, 4]) ...
Angle between vector A and B: 11.490459903731518 degrees
MIT
delft course dr weijermars/stress_tensor.ipynb
rksin8/reservoir-geomechanics
Exercise 10-3. Effective, Normal, and Shear Stress on a Plane Consider a plane that makes an angle 60 degrees with $\sigma_1$ and 60 degrees with $\sigma_3$. The principal stresses are: -600, -400, -200 MPa. Calculate:* Total effective stress* Normal stress* Shear stress
# principle stresses sigma_1 = -600; sigma_2 = -400; sigma_3 = -200 # calculate the angle of plane to second principal stress sigma 2 # using pythagorean alpha = 60; gamma = 60 l = np.cos(np.deg2rad(alpha)) n = np.cos(np.deg2rad(gamma)) m = np.sqrt(1 - l**2 - n**2) beta = np.rad2deg(np.arccos(m)) print("The second pr...
The second principal stress sigma 2 makes angle: 45.000000000000014 degrees to the plane The effective stress is: -424.26406871192853 MPa (minus because it's compressive) The normal stress is: -400.0 MPa The shear stress is: 141.4213562373095 MPa
MIT
delft course dr weijermars/stress_tensor.ipynb
rksin8/reservoir-geomechanics
Stress Tensor Components
stress_tensor = [[sigma_xx, sigma_xy, sigma_xz], [sigma_yx, sigma_yy, sigma_yz], [sigma_zx, sigma_zy, sigma_zz]] import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt # point of cube points = np.array([[-5, -5, -5], [5, -5, -5...
_____no_output_____
MIT
delft course dr weijermars/stress_tensor.ipynb
rksin8/reservoir-geomechanics
Exercise 10-7 Total Stress, Deviatoric Stress, Effective Stress, Cauchy Summation$$\sigma_{ij}=\tau_{ij}+P_{ij}$$$$P_{ij}=P \cdot \delta_{ij}$$Pressure is: $P=|\sigma_{mean}|=|\frac{\sigma_{xx}+\sigma_{yy}+\sigma_{zz}}{3}|$Knorecker Delta is: $\delta_{ij}=\begin{bmatrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1 \end{bmatri...
# known l, m, n = 0.7, 0.5, 0.5 # direction cosines alpha, beta, gamma = 45, 60, 60 # angles stress_ij = np.array([[-40, -40, -35], [-40, 45, -50], [-35, -50, -20]]) # total stress tensor # calculate pressure P = np.abs(np.mean(np.array([(stress_ij[0][0]), (stress_ij[1][1]),...
The total effective stress is: -93.59887819840577 MPa X component of principal stress: -93.57142857142858 MPa Y component of principal stress: -61.0 MPa Z component of principal stress: -119.0 MPa The normal stress is: -90.85 MPa Because normal stress -90.85 MPa nearly equals to sigma 1 -93.57142857142858 MPa, the plan...
MIT
delft course dr weijermars/stress_tensor.ipynb
rksin8/reservoir-geomechanics
Exercise 10-8 Transforming Stress Tensor (Containing all the 9 tensors of shear and normal) to Principal Stress Tensor using Cubic Equation
sigma_ij = np.array([[0, 0, 100], [0, 0, 0], [-100, 0, 0]]) # stress tensor # cubic equation coeff3 = 1 coeff2 = -((sigma_ij[0][0] + sigma_ij[1][1] + sigma_ij[2][2])) coeff1 = (sigma_ij[0][0] * sigma_ij[1][1]) + (sigma_ij[1][1] * sigma_ij[2][2]) + (sigma_ij[2][2] * sigma_ij[0][...
_____no_output_____
MIT
delft course dr weijermars/stress_tensor.ipynb
rksin8/reservoir-geomechanics
***
from mpl_toolkits.mplot3d import axes3d X = np.array((0)) Y= np.array((0)) U = np.array((0)) V = np.array((4)) fig, ax = plt.subplots() q = ax.quiver(X, Y, U, V,units='xy' ,scale=1) plt.grid() ax.set_aspect('equal') plt.xlim(-5,5) plt.ylim(-5,5) from mpl_toolkits.mplot3d import axes3d X = np.array((0)) Y= np.arra...
_____no_output_____
MIT
delft course dr weijermars/stress_tensor.ipynb
rksin8/reservoir-geomechanics
AutoGluon Tabular with SageMaker[AutoGluon](https://github.com/awslabs/autogluon) automates machine learning tasks enabling you to easily achieve strong predictive performance in your applications. With just a few lines of code, you can train and deploy high-accuracy deep learning models on tabular, image, and text da...
# Make sure docker compose is set up properly for local mode !./setup.sh # Imports import os import boto3 import sagemaker from time import sleep from collections import Counter import numpy as np import pandas as pd from sagemaker import get_execution_role, local, Model, utils, fw_utils, s3 from sagemaker.estimator im...
_____no_output_____
Apache-2.0
advanced_functionality/autogluon-tabular/AutoGluon_Tabular_SageMaker.ipynb
phiamazon/amazon-sagemaker-examples
Build docker images First, build autogluon package to copy into docker image.
if not os.path.exists('package'): !pip install PrettyTable -t package !pip install --upgrade boto3 -t package !pip install bokeh -t package !pip install --upgrade matplotlib -t package !pip install autogluon -t package
_____no_output_____
Apache-2.0
advanced_functionality/autogluon-tabular/AutoGluon_Tabular_SageMaker.ipynb
phiamazon/amazon-sagemaker-examples
Now build the training/inference image and push to ECR
training_algorithm_name = 'autogluon-sagemaker-training' inference_algorithm_name = 'autogluon-sagemaker-inference' !./container-training/build_push_training.sh {account} {region} {training_algorithm_name} {ecr_uri_prefix} {registry_id} {registry_uri} !./container-inference/build_push_inference.sh {account} {region} {i...
_____no_output_____
Apache-2.0
advanced_functionality/autogluon-tabular/AutoGluon_Tabular_SageMaker.ipynb
phiamazon/amazon-sagemaker-examples
Get the data In this example we'll use the direct-marketing dataset to build a binary classification model that predicts whether customers will accept or decline a marketing offer. First we'll download the data and split it into train and test sets. AutoGluon does not require a separate validation set (it uses bagged...
# Download and unzip the data !aws s3 cp --region {region} s3://sagemaker-sample-data-{region}/autopilot/direct_marketing/bank-additional.zip . !unzip -qq -o bank-additional.zip !rm bank-additional.zip local_data_path = './bank-additional/bank-additional-full.csv' data = pd.read_csv(local_data_path) # Split train/tes...
_____no_output_____
Apache-2.0
advanced_functionality/autogluon-tabular/AutoGluon_Tabular_SageMaker.ipynb
phiamazon/amazon-sagemaker-examples
Check the data
train.head(3) train.shape test.head(3) test.shape X_test.head(3) X_test.shape
_____no_output_____
Apache-2.0
advanced_functionality/autogluon-tabular/AutoGluon_Tabular_SageMaker.ipynb
phiamazon/amazon-sagemaker-examples
Upload the data to s3
train_file = 'train.csv' train.to_csv(train_file,index=False) train_s3_path = session.upload_data(train_file, key_prefix='{}/data'.format(prefix)) test_file = 'test.csv' test.to_csv(test_file,index=False) test_s3_path = session.upload_data(test_file, key_prefix='{}/data'.format(prefix)) X_test_file = 'X_test.csv' X_t...
_____no_output_____
Apache-2.0
advanced_functionality/autogluon-tabular/AutoGluon_Tabular_SageMaker.ipynb
phiamazon/amazon-sagemaker-examples
Hyperparameter SelectionThe minimum required settings for training is just a target label, `fit_args['label']`.Additional optional hyperparameters can be passed to the `autogluon.task.TabularPrediction.fit` function via `fit_args`.Below shows a more in depth example of AutoGluon-Tabular hyperparameters from the exampl...
# Define required label and optional additional parameters fit_args = { 'label': 'y', # Adding 'best_quality' to presets list will result in better performance (but longer runtime) 'presets': ['optimize_for_deployment'], } # Pass fit_args to SageMaker estimator hyperparameters hyperparameters = { 'fit_args': f...
_____no_output_____
Apache-2.0
advanced_functionality/autogluon-tabular/AutoGluon_Tabular_SageMaker.ipynb
phiamazon/amazon-sagemaker-examples
TrainFor local training set `train_instance_type` to `local` . For non-local training the recommended instance type is `ml.m5.2xlarge`. **Note:** Depending on how many underlying models are trained, `train_volume_size` may need to be increased so that they all fit on disk.
%%time instance_type = 'ml.m5.2xlarge' #instance_type = 'local' ecr_image = f'{ecr_uri_prefix}/{training_algorithm_name}:latest' estimator = Estimator(image_name=ecr_image, role=role, train_instance_count=1, train_instance_type=instance_type, ...
_____no_output_____
Apache-2.0
advanced_functionality/autogluon-tabular/AutoGluon_Tabular_SageMaker.ipynb
phiamazon/amazon-sagemaker-examples
Create Model
# Create predictor object class AutoGluonTabularPredictor(RealTimePredictor): def __init__(self, *args, **kwargs): super().__init__(*args, content_type='text/csv', serializer=csv_serializer, deserializer=StringDeserializer(), **kwargs) ecr_image = f'{ecr_u...
_____no_output_____
Apache-2.0
advanced_functionality/autogluon-tabular/AutoGluon_Tabular_SageMaker.ipynb
phiamazon/amazon-sagemaker-examples
Batch Transform For local mode, either `s3:////output/` or `file:///` can be used as outputs.By including the label column in the test data, you can also evaluate prediction performance (In this case, passing `test_s3_path` instead of `X_test_s3_path`).
output_path = f's3://{bucket}/{prefix}/output/' # output_path = f'file://{os.getcwd()}' transformer = model.transformer(instance_count=1, instance_type=instance_type, strategy='MultiRecord', max_payload=6, ...
_____no_output_____
Apache-2.0
advanced_functionality/autogluon-tabular/AutoGluon_Tabular_SageMaker.ipynb
phiamazon/amazon-sagemaker-examples
Endpoint Deploy remote or local endpoint
instance_type = 'ml.m5.2xlarge' #instance_type = 'local' predictor = model.deploy(initial_instance_count=1, instance_type=instance_type)
_____no_output_____
Apache-2.0
advanced_functionality/autogluon-tabular/AutoGluon_Tabular_SageMaker.ipynb
phiamazon/amazon-sagemaker-examples
Attach to endpoint (or reattach if kernel was restarted)
# Select standard or local session based on instance_type if instance_type == 'local': sess = local_session else: sess = session # Attach to endpoint predictor = AutoGluonTabularPredictor(predictor.endpoint, sagemaker_session=sess)
_____no_output_____
Apache-2.0
advanced_functionality/autogluon-tabular/AutoGluon_Tabular_SageMaker.ipynb
phiamazon/amazon-sagemaker-examples
Predict on unlabeled test data
results = predictor.predict(X_test.to_csv(index=False)).splitlines() # Check output print(Counter(results))
_____no_output_____
Apache-2.0
advanced_functionality/autogluon-tabular/AutoGluon_Tabular_SageMaker.ipynb
phiamazon/amazon-sagemaker-examples
Predict on data that includes label column Prediction performance metrics will be printed to endpoint logs.
results = predictor.predict(test.to_csv(index=False)).splitlines() # Check output print(Counter(results))
_____no_output_____
Apache-2.0
advanced_functionality/autogluon-tabular/AutoGluon_Tabular_SageMaker.ipynb
phiamazon/amazon-sagemaker-examples
Check that classification performance metrics match evaluation printed to endpoint logs as expected
y_results = np.array(results) print("accuracy: {}".format(accuracy_score(y_true=y_test, y_pred=y_results))) print(classification_report(y_true=y_test, y_pred=y_results, digits=6))
_____no_output_____
Apache-2.0
advanced_functionality/autogluon-tabular/AutoGluon_Tabular_SageMaker.ipynb
phiamazon/amazon-sagemaker-examples
Clean up endpoint
predictor.delete_endpoint()
_____no_output_____
Apache-2.0
advanced_functionality/autogluon-tabular/AutoGluon_Tabular_SageMaker.ipynb
phiamazon/amazon-sagemaker-examples
Berdasarkan isu [73](https://github.com/taruma/hidrokit/issues/73): **request: mengolah berkas dari data bmkg**Deskripsi:- mengolah berkas excel yang diperoleh dari data online bmkg untuk siap dipakai- memeriksa kondisi dataFungsi yang diharapkan:__Umum / General__- Memeriksa apakah data lengkap atau tidak? Jika tidak...
# AKSES GOOGLE DRIVE from google.colab import drive drive.mount('/content/gdrive') # DRIVE PATH DRIVE_DROP_PATH = '/content/gdrive/My Drive/Colab Notebooks/_dropbox' DRIVE_DATASET_PATH = '/content/gdrive/My Drive/Colab Notebooks/_dataset/uma_pamarayan' DATASET_PATH = DRIVE_DATASET_PATH + '/klimatologi_geofisika_tanger...
_____no_output_____
MIT
hidrokit/contrib_taruma/ipynb/taruma_hk73_bmkg.ipynb
hidrokit/manual
FUNGSI
import pandas as pd import numpy as np from operator import itemgetter from itertools import groupby def _read_bmkg(io): return pd.read_excel( io, skiprows=8, skipfooter=16, header=0, index_col=0, parse_dates=True, date_parser=lambda x: pd.to_datetime(x, format='%d-%m-%Y') ) def _have_nan(data...
_____no_output_____
MIT
hidrokit/contrib_taruma/ipynb/taruma_hk73_bmkg.ipynb
hidrokit/manual
PENGGUNAAN Fungsi `_read_bmkg`Tujuan: Impor berkas excel bmkg ke dataframe
dataset = _read_bmkg(DATASET_PATH) dataset.head() dataset.tail()
_____no_output_____
MIT
hidrokit/contrib_taruma/ipynb/taruma_hk73_bmkg.ipynb
hidrokit/manual
Fungsi `_have_nan()`Tujuan: Memeriksa apakah di dalam tabel memiliki nilai yang hilang (np.nan)
_have_nan(dataset)
_____no_output_____
MIT
hidrokit/contrib_taruma/ipynb/taruma_hk73_bmkg.ipynb
hidrokit/manual
Fungsi `_get_index1D()`Tujuan: Memperoleh index data yang hilang untuk setiap array
_get_index1D(dataset['RH_avg'].isna().values)
_____no_output_____
MIT
hidrokit/contrib_taruma/ipynb/taruma_hk73_bmkg.ipynb
hidrokit/manual
Fungsi `_get_nan()`Tujuan: Memperoleh index data yang hilang untuk setiap kolom dalam bentuk `dictionary`
_get_nan(dataset).keys() print(_get_nan(dataset)['RH_avg'])
[852, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1220, 1221, 1222, 1223, 1224, 1628, 1629, 1697, 2657]
MIT
hidrokit/contrib_taruma/ipynb/taruma_hk73_bmkg.ipynb
hidrokit/manual
Fungsi `_get_nan_columns()`Tujuan: Memperoleh nama kolom yang memiliki nilai yang hilang `NaN`.
_get_nan_columns(dataset)
_____no_output_____
MIT
hidrokit/contrib_taruma/ipynb/taruma_hk73_bmkg.ipynb
hidrokit/manual
Fungsi `_check_nan()`Tujuan: Gabungan dari `_have_nan()` dan `_get_nan()`. Memeriksa apakah dataset memiliki `NaN`, jika iya, memberikan nilai hasil `_get_nan()`, jika tidak memberikan nilai `None`.
_check_nan(dataset).items() # Jika tidak memiliki nilai nan print(_check_nan(dataset.drop(_get_nan_columns(dataset), axis=1)))
None
MIT
hidrokit/contrib_taruma/ipynb/taruma_hk73_bmkg.ipynb
hidrokit/manual
Fungsi `_group_as_list()`Tujuan: Mengelompokkan kelompok array yang bersifat kontinu (nilainya berurutan) dalam masing-masing list.Referensi: https://stackoverflow.com/a/15276206 (dimodifikasi untuk Python 3.x dan kemudahan membaca)
missing_dict = _get_nan(dataset) missing_RH_avg = missing_dict['RH_avg'] print(missing_RH_avg) print(_group_as_list(missing_RH_avg))
[[852], [1037, 1038, 1039, 1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067], [1220, 1221, 1222, 1223, 1224], [1628, 1629], [1697], [2657]]
MIT
hidrokit/contrib_taruma/ipynb/taruma_hk73_bmkg.ipynb
hidrokit/manual
Fungsi `_group_as_index()`Tujuan: Mengubah hasil pengelompokkan menjadi jenis index dataset (dalam kasus ini dalam bentuk tanggal dibandingkan dalam bentuk angka-index dataset).
_group_as_index(_group_as_list(missing_RH_avg), index=dataset.index, date_format='%d %b %Y')
_____no_output_____
MIT
hidrokit/contrib_taruma/ipynb/taruma_hk73_bmkg.ipynb
hidrokit/manual
Fungsi `_get_missing()`Tujuan: Memperoleh index yang memiliki nilai tidak terukur (bernilai `8888` atau `9999`) untuk setiap kolomnya
_get_missing(dataset)
_____no_output_____
MIT
hidrokit/contrib_taruma/ipynb/taruma_hk73_bmkg.ipynb
hidrokit/manual
Penerapan Menampilkan index yang bermasalahTujuan: Setelah memperoleh index dari hasil `_get_missing()` atau `_get_nan()`, bisa menampilkan potongan index tersebut dalam dataframe.
dataset.iloc[_get_missing(dataset)['RR']] _group_as_list(_get_missing(dataset)['RR']) _group_as_index(_, index=dataset.index, date_format='%d %b %Y', format_date='{} sampai {}')
_____no_output_____
MIT
hidrokit/contrib_taruma/ipynb/taruma_hk73_bmkg.ipynb
hidrokit/manual
Homework - Random Walks (18 pts) Continuous random walk in three dimensionsWrite a program simulating a three-dimensional random walk in a continuous space. Let 1000 independent particles all start at random positions within a cube with corners at (0,0,0) and (1,1,1). At each time step each particle will move in a ra...
import numpy as np numTimeSteps = 2000 numParticles = 1000 positions = np.zeros( (numParticles, 3, numTimeSteps) ) # initialize starting positions on first time step positions[:,:,0] = np.random.random( (numParticles, 3) )
_____no_output_____
Unlicense
homework/key-random_walks.ipynb
nishadalal120/NEU-365P-385L-Spring-2021
2. (3 pts) Write code to run your simulation for 2000 time steps.
for t in range(numTimeSteps-1): # 2 * [0 to 1] - 1 --> [-1 to 1] jumpsForAllParticles = 2 * np.random.random((numParticles, 3)) - 1 positions[:,:,t+1] = positions[:,:,t] + jumpsForAllParticles # just for fun, here's another way to run the simulation above without a loop jumpsForAllParticlesAndAllTimeSteps =...
_____no_output_____
Unlicense
homework/key-random_walks.ipynb
nishadalal120/NEU-365P-385L-Spring-2021