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
Download File
# def tt(j): # type_ = test['type'][j] # return models[type_].predict(np.expand_dims(X[j], axis=0)) # def get_dataframe(): # with Pool(8) as p: # a = p.map(tt,[i for i in range(sub.shape[0])]) # return pd.DataFrame(np.array(a)) # %%time # sub['scalar_coupling_constant'] = get_dataframe() # s...
_____no_output_____
MIT
Gradient Boosting for molecular properties/pmp-lightgbm-inference.ipynb
dhananjayraut/ML_projects
02 | Decision Tree. A Supervised Classification Model - Subscribe to my [Blog ↗](https://blog.pythonassembly.com/)- Let's keep in touch on [LinkedIn ↗](www.linkedin.com/in/jsulopz) 😄 Discipline to Search Solutions in Google > Apply the following steps when **looking for solutions in Google**:>> 1. **Necesity**: How t...
import seaborn as sns sns.load_dataset(name='titanic').iloc[:, :4]
_____no_output_____
MIT
II Machine Learning & Deep Learning/02_Decision Tree. A Supervised Classification Model/02session_decision-tree.ipynb
Blanes3/resolving-python-data-science
`DecisionTreeClassifier()` Model in Python Build the Model > 1. **Necesity**: Build Model> 2. **Google**: How do you search for the solution?> 3. **Solution**: Find the `function()` that makes it happen Code Thinking> Which function computes the Model?> - `fit()`>> How could can you **import the function in Python**...
explanatory = ? target = ?
_____no_output_____
MIT
II Machine Learning & Deep Learning/02_Decision Tree. A Supervised Classification Model/02session_decision-tree.ipynb
Blanes3/resolving-python-data-science
Finally `fit()` the Model Calculate a Prediction with the Model > - `model.predict_proba()` Model Visualization > - `tree.plot_tree()` Model Interpretation > Why `sex` is the most important column? What has to do with **EDA** (Exploratory Data Analysis)?
%%HTML <iframe width="560" height="315" src="https://www.youtube.com/embed/7VeUPuFGJHk" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
_____no_output_____
MIT
II Machine Learning & Deep Learning/02_Decision Tree. A Supervised Classification Model/02session_decision-tree.ipynb
Blanes3/resolving-python-data-science
Copy paddleocr.py to cp_pdocr.py
!python cp_pdocr.py --image_dir doc/imgs_en/can-ho.jpg --lang=en
Namespace(cls_batch_num=6, cls_image_shape='3, 48, 192', cls_model_dir='/root/.paddleocr/cls', cls_thresh=0.9, det=True, det_algorithm='DB', det_db_box_thresh=0.5, det_db_score_mode='fast', det_db_thresh=0.3, det_db_unclip_ratio=1.6, det_east_cover_thresh=0.1, det_east_nms_thresh=0.2, det_east_score_thresh=0.8, det_lim...
Apache-2.0
use_PaddleOCR_colab.ipynb
hieu28022000/PaddleOCR
CRRT Mortality Prediction Model Construction Christopher V. Cosgriff, David Sasson, Colby Wilkinson, Kanhua YinThe purpose of this notebook is to build a deep learning model that predicts ICU mortality in the CRRT population. The data is extracted in the `extract_cohort_and_features` notebook and stored in the `data` ...
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from IPython.display import SVG import os from keras.optimizers import Adam, SGD, rmsprop from keras.models import Sequential,Model from keras.layers import Dense, Activation, Dropout, Input, Dropout, concatenate from keras.layers.recurrent im...
/home/cosgriffc/env/ML/lib/python3.5/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`. from ._conv import register_converters as _register_converters Usin...
MIT
mortality_model.ipynb
cosgriffc/bst261-crrt
Step 1: Load and Prepare DataHere will we load in the data, and create train, validation, and testing splits.
# set tensors to float 32 as this is what GPUs expect features_sequence = np.load('./features_sequence.npy').astype(np.float32) features_static = np.load('./features_static.npy').astype(np.float32) labels = np.load('./labels.npy').astype(np.float32) x_seq_full_train, x_seq_test, x_static_full_train, x_static_test, y_f...
_____no_output_____
MIT
mortality_model.ipynb
cosgriffc/bst261-crrt
Next we need to remove NANs from the data; we'll impute the trianing population mean, the simplest method suggested by David Sontag.
def impute_mean(source_data, input_data): ''' Takes the source data, and uses it to determine means for all features; it then applies them to the input data. inputs: source_data: a tensor to provide means input_data: the data to fill in NA for output: output_data: data with nan...
_____no_output_____
MIT
mortality_model.ipynb
cosgriffc/bst261-crrt
Step 2: Build Model Model 1Base model, no regularization.
# Define inputs sequence_input = Input(shape = (x_seq_train.shape[1], x_seq_train.shape[2], ), dtype = 'float32', name = 'sequence_input') static_input = Input(shape = (x_static_train.shape[1], ), name = 'static_input') # Network architecture seq_x = GRU(units = 128)(sequence_input) # Seperate output for the GRU late...
_____no_output_____
MIT
mortality_model.ipynb
cosgriffc/bst261-crrt
10% Dropout
# Define inputs sequence_input = Input(shape = (x_seq_train.shape[1], x_seq_train.shape[2], ), dtype = 'float32', name = 'sequence_input') static_input = Input(shape = (x_static_train.shape[1], ), name = 'static_input') # Network architecture seq_x = GRU(units = 128)(sequence_input) # Seperate output for the GRU late...
_____no_output_____
MIT
mortality_model.ipynb
cosgriffc/bst261-crrt
First Deep Learning Model
import numpy as np %matplotlib inline import matplotlib.pyplot as plt from sklearn.datasets.samples_generator import make_circles X, y = make_circles(n_samples=1000, noise=0.1, factor=0.2, random_state=0) X X.shape plt.figure(figsize=(5, 5)) plt.plot(X[y==0, 0...
_____no_output_____
MIT
course/1 First Deep Learning Model.ipynb
Zhenxingzhang/zero_to_deep_learning_video
models.unet Type an introduction of the package here.
from fastai.gen_doc.nbdoc import * from fastai.models.unet import *
_____no_output_____
Apache-2.0
docs_src/models.unet.ipynb
Gokkulnath/fastai_v1
Global Variable Definitions:
show_doc(DynamicUnet)
_____no_output_____
Apache-2.0
docs_src/models.unet.ipynb
Gokkulnath/fastai_v1
[`DynamicUnet`](/models.unet.htmlDynamicUnet)
show_doc(UnetBlock)
_____no_output_____
Apache-2.0
docs_src/models.unet.ipynb
Gokkulnath/fastai_v1
[`UnetBlock`](/models.unet.htmlUnetBlock)
show_doc(UnetBlock.forward)
_____no_output_____
Apache-2.0
docs_src/models.unet.ipynb
Gokkulnath/fastai_v1
$\color{black}{}$ 1. Fitting data--- Input data
import pandas as pd import seaborn as sns data = pd.read_csv('https://milliams.com/courses/applied_data_analysis/linear.csv') data.head()
_____no_output_____
MIT
fitting_data.ipynb
bibliotekue/python-applied-data-analysis
Let's check how many rows we have
data.count()
_____no_output_____
MIT
fitting_data.ipynb
bibliotekue/python-applied-data-analysis
We have 50 rows here. In the input data, each row is often called a sample (though sometimes also called an instance, example or observation). For example, it could be the information about a single person from a census or the measurements at a particular time from a weather station. Let's have a look at what the data ...
sns.scatterplot(data=data, x="x", y="y")
_____no_output_____
MIT
fitting_data.ipynb
bibliotekue/python-applied-data-analysis
We can clearly visually see here that there is a linear relationship between the x and y values but we need to be able to extract the exact parameters programmatically. Setting up our model We import the model and create an instance of it. By default the LinearRegression model will fit the y-intercept, but since we do...
from sklearn.linear_model import LinearRegression model = LinearRegression(fit_intercept=True)
_____no_output_____
MIT
fitting_data.ipynb
bibliotekue/python-applied-data-analysis
Fitting the data Once we have created our model, we can fit it to the data by calling the `fit()` method on it. This takes two arguments:1. The input data as a two-dimensional structure of the size ($N_{samples}$,$N_{features}$)2. The labels or targets of the data as a one-dimensional data structure of size ($N_{sampl...
X = data[['x']] y = data['y'] model.fit(X, y)
_____no_output_____
MIT
fitting_data.ipynb
bibliotekue/python-applied-data-analysis
Making predictions using the model We can use this to plot the fit over the original data to compare the result. By getting the predicted *__y__* values for the minimum and maximum x values, we can plot a straight line between them to visualise the model. The `predict()` function takes an array of the same shape as th...
x_fit = pd.DataFrame({'x': [0, 10]}) y_pred = model.predict(x_fit) import matplotlib.pyplot as plt plt.figure(figsize=(20,20)) fig, ax = plt.subplots() sns.scatterplot(data=data, x='x', y='y', ax=ax) ax.plot(x_fit['x'], y_pred, linestyle=':', color='red') plt.show()
_____no_output_____
MIT
fitting_data.ipynb
bibliotekue/python-applied-data-analysis
As well as plotting the line in a graph, we can also extract the calculated values of the gradient and y-intercept. The gradient is available as a list of values, `model.coef_`, one for each dimension or feature. The intercept is available as `model.intercept_`.
print(f'Model gradient: {model.coef_[0]}') print(f'Model intercept: {model.intercept_}')
Model gradient: 1.9776566003853107 Model intercept: -4.903310725531115
MIT
fitting_data.ipynb
bibliotekue/python-applied-data-analysis
Implement Canny edge detection
# Try Canny using "wide" and "tight" thresholds wide = cv2.Canny(gray, 30, 100) tight = cv2.Canny(gray, 200, 240) # Display the images f, (ax1, ax2) = plt.subplots(1, 2, figsize=(20,10)) ax1.set_title('wide') ax1.imshow(wide, cmap='gray') ax2.set_title('tight') ax2.imshow(tight, cmap='gray')
_____no_output_____
MIT
1_2_Convolutional_Filters_Edge_Detection/5. Canny Edge Detection.ipynb
Echo9k/CVND_Exercises
TODO: Try to find the edges of this flowerSet a small enough threshold to isolate the boundary of the flower.
# Read in the image image = cv2.imread('images/sunflower.jpg') # Change color to RGB (from BGR) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) plt.imshow(image) # Convert the image to grayscale gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) ## TODO: Define lower and upper thresholds for hysteresis # right now the th...
_____no_output_____
MIT
1_2_Convolutional_Filters_Edge_Detection/5. Canny Edge Detection.ipynb
Echo9k/CVND_Exercises
Loading Raw Data
import tensorflow as tf (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() x_train_flatten = x_train.reshape(x_train.shape[0], x_train.shape[1]*x_train.shape[2])/255.0 x_test_flatten = x_test.reshape(x_test.shape[0], x_test.shape[1]*x_test.shape[2])/255.0 print(x_train_flatten.shape, y_train.sh...
(980, 784) (1135, 784) (1032, 784) (1010, 784) (982, 784) (892, 784) (958, 784) (1028, 784) (974, 784) (1009, 784)
MIT
PennyLane/Data Reuploading Classifier/.ipynb_checkpoints/DRC MNIST MultiClass PCA-Copy1-checkpoint.ipynb
Graciaira/quantum_image_classifier
Selecting the datasetOutput: X_train, Y_train, X_test, Y_test
num_sample = 300 n_class = 4 mult_test = 0.25 X_train = x_train_list[0][:num_sample, :] X_test = x_test_list[0][:int(mult_test*num_sample), :] Y_train = np.zeros((n_class*X_train.shape[0],), dtype=int) Y_test = np.zeros((n_class*X_test.shape[0],), dtype=int) for i in range(n_class-1): X_train = np.concatenate((X_t...
(1200, 784) (1200,) (300, 784) (300,)
MIT
PennyLane/Data Reuploading Classifier/.ipynb_checkpoints/DRC MNIST MultiClass PCA-Copy1-checkpoint.ipynb
Graciaira/quantum_image_classifier
Dataset Preprocessing (Standardization + PCA) Standardization
def normalize(X, use_params=False, params=None): """Normalize the given dataset X Args: X: ndarray, dataset Returns: (Xbar, mean, std): tuple of ndarray, Xbar is the normalized dataset with mean 0 and standard deviation 1; mean and std are the mean and standard deviatio...
_____no_output_____
MIT
PennyLane/Data Reuploading Classifier/.ipynb_checkpoints/DRC MNIST MultiClass PCA-Copy1-checkpoint.ipynb
Graciaira/quantum_image_classifier
PCA
from sklearn.decomposition import PCA from matplotlib import pyplot as plt num_component = 9 pca = PCA(n_components=num_component, svd_solver='full') pca.fit(X_train) np.cumsum(pca.explained_variance_ratio_) X_train = pca.transform(X_train) X_test = pca.transform(X_test) print(X_train.shape, Y_train.shape) print(X_test...
(1200, 9) (1200,) (300, 9) (300,)
MIT
PennyLane/Data Reuploading Classifier/.ipynb_checkpoints/DRC MNIST MultiClass PCA-Copy1-checkpoint.ipynb
Graciaira/quantum_image_classifier
Norm
X_train = (X_train.T / np.sqrt(np.sum(X_train ** 2, -1))).T X_test = (X_test.T / np.sqrt(np.sum(X_test ** 2, -1))).T plt.scatter(X_train[:100, 0], X_train[:100, 1]) plt.scatter(X_train[100:200, 0], X_train[100:200, 1]) plt.scatter(X_train[200:300, 0], X_train[200:300, 1])
_____no_output_____
MIT
PennyLane/Data Reuploading Classifier/.ipynb_checkpoints/DRC MNIST MultiClass PCA-Copy1-checkpoint.ipynb
Graciaira/quantum_image_classifier
Quantum
import pennylane as qml from pennylane import numpy as np from pennylane.optimize import AdamOptimizer, GradientDescentOptimizer qml.enable_tape() # Set a random seed np.random.seed(42) def plot_data(x, y, fig=None, ax=None): """ Plot data with red/blue values for a binary classification. Args: ...
_____no_output_____
MIT
PennyLane/Data Reuploading Classifier/.ipynb_checkpoints/DRC MNIST MultiClass PCA-Copy1-checkpoint.ipynb
Graciaira/quantum_image_classifier
Constant definition
np.random.seed(1) random.seed(1) torch.manual_seed(1) torch.cuda.manual_seed_all(1) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") lr = 2e-3 seq_len = 12 beta1 = 0.5 content_dim = 128 pose_dim = 10 channels = 3 normalize = False sd_nf = 100 image_width = 64 batch_size = 100 log_dir = './logs/0522...
_____no_output_____
MIT
train.ipynb
TMYuan/video-interpolation
Data Loader
train_data = MovingMNIST(True, '../data_uni/', seq_len=seq_len) test_data = MovingMNIST(False, '../data_uni/', seq_len=seq_len) train_loader = DataLoader( train_data, batch_size=batch_size, num_workers=16, shuffle=True, drop_last=True, pin_memory=True ) test_loader = DataLoader( test_data, ...
_____no_output_____
MIT
train.ipynb
TMYuan/video-interpolation
Model definition
# # netEC = dcgan_unet_models.content_encoder(content_dim, channels).to(device) # netEC = dcgan_models.content_encoder(content_dim, channels).to(device) # netEP = dcgan_models.pose_encoder(pose_dim, channels).to(device) # # netD = dcgan_unet_models.decoder(content_dim, pose_dim, channels).to(device) # netD = dcgan_mode...
_____no_output_____
MIT
train.ipynb
TMYuan/video-interpolation
Plot function
# --------- plotting funtions ------------------------------------ def plot_rec(x, epoch, dtype): x_c = x[0] x_p = x[np.random.randint(1, len(x))] h_c = netEC(x_c) h_p = netEP(x_p, h_c) rec = netD([h_c, h_p]) x_c, x_p, rec = x_c.data, x_p.data, rec.data fname = '{}-{}.png'.format(dtype, ep...
_____no_output_____
MIT
train.ipynb
TMYuan/video-interpolation
Training function
def train(x): optimizerEC.zero_grad() optimizerEP.zero_grad() optimizerD.zero_grad() # x_c1 = x[0] # x_c2 = x[1] # x_p1 = x[2] # x_p2 = x[3] x_c1 = x[np.random.randint(len(x))] x_c2 = x[np.random.randint(len(x))] x_p1 = x[np.random.randint(len(x))] x_p2 = x[np.random.randint...
_____no_output_____
MIT
train.ipynb
TMYuan/video-interpolation
$H(curl, \Omega)$ Elliptic Problems $\newcommand{\dd}{\,{\rm d}}$$\newcommand{\uu}{\mathbf{u}}$$\newcommand{\vv}{\mathbf{v}}$$\newcommand{\nn}{\mathbf{n}}$$\newcommand{\ff}{\mathbf{f}}$$\newcommand{\Hcurlzero}{\mathbf{H}_0(\mbox{curl}, \Omega)}$$\newcommand{\Curl}{\nabla \times}$Let $\Omega \subset \mathbb{R}^d$ be an...
import numpy as np from sympy import pi, cos, sin, sqrt, Matrix, Tuple, lambdify from scipy.sparse.linalg import spsolve from scipy.sparse.linalg import gmres as sp_gmres from scipy.sparse.linalg import minres as sp_minres from scipy.sparse.linalg import cg as sp_cg from scipy.sparse.linalg import bicg as sp_bicg from ...
0.0029394893438220407
MIT
lessons/Chapter5/03_Hcurl_elliptic_problem.ipynb
pyccel/IGA-Python
Emotion recognition using Emo-DB dataset and scikit-learn Database: Emo-DB database (free) 7 emotionsThe data can be downloaded from http://emodb.bilderbar.info/index-1024.htmlCode of emotionsW->Anger->WutL->Boredom->LangeweileE->Disgust->EkelA->Anxiety/Fear->AngstF->Happiness->FreudeT->Sadness->TrauerN->Neutral![imag...
import requests import zipfile import os import numpy as np import matplotlib.pyplot as plt import scipy.stats as st import itertools import sys sys.path.append("../") from plots_examples import plot_confusion_matrix, plot_ROC, plot_histogram # disvoice imports from phonation.phonation import Phonation from articulat...
Using TensorFlow backend. /home/camilo/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:526: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.i...
MIT
notebooks_examples/emotion classification using SVMs in scikit-learn.ipynb
virtualcharacters/DisVoice
Download and unzip data
def download_url(url, save_path, chunk_size=128): r = requests.get(url, stream=True) with open(save_path, 'wb') as fd: for chunk in r.iter_content(chunk_size=chunk_size): fd.write(chunk) PATH_data="http://emodb.bilderbar.info/download/download.zip" download_url(PATH_data, "./dow...
_____no_output_____
MIT
notebooks_examples/emotion classification using SVMs in scikit-learn.ipynb
virtualcharacters/DisVoice
prepare labels from the datasetwe will get labels for two classification problems: 1. high vs. low arousal emotions2. positive vs. negative emotions
PATH_AUDIO=os.path.abspath("./emo-db/wav")+"/" labelsd='WLEAFTN' labelshl= [0, 1, 0, 0, 0, 1, 1] # 0 high arousal emotion, 1 low arousal emotions labelspn= [0, 0, 0, 0, 1, 0, 1] # 0 negative valence emotion, 1 positive valence emotion hf=os.listdir(PATH_AUDIO) hf.sort() yArousal=np.zeros(len(hf)) yValence=np.zeros(...
_____no_output_____
MIT
notebooks_examples/emotion classification using SVMs in scikit-learn.ipynb
virtualcharacters/DisVoice
compute features using disvoice: phonation, articulation, prosody, phonological
phonationf=Phonation() articulationf=Articulation() prosodyf=Prosody() phonologicalf=Phonological() replearningf=RepLearning('CAE')
WARNING:tensorflow:From /home/camilo/anaconda3/lib/python3.6/site-packages/tensorflow/python/ops/resource_variable_ops.py:435: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version. Instructions for updating: Colocations handled automatically by placer.
MIT
notebooks_examples/emotion classification using SVMs in scikit-learn.ipynb
virtualcharacters/DisVoice
phonation features
Xphonation=phonationf.extract_features_path(PATH_AUDIO, static=True, plots=False, fmt="npy") print(Xphonation.shape)
Processing 14a07Aa.wav: 69%|██████▉ | 368/535 [00:10<00:04, 40.87it/s]../phonation/phonation.py:161: WavFileWarning: Chunk (non-data) not understood, skipping it. fs, data_audio=read(audio) Processing 16b10Wb.wav: 100%|██████████| 535/535 [00:14<00:00, 36.70it/s]
MIT
notebooks_examples/emotion classification using SVMs in scikit-learn.ipynb
virtualcharacters/DisVoice
articulation features
Xarticulation=articulationf.extract_features_path(PATH_AUDIO, static=True, plots=False, fmt="npy") print(Xarticulation.shape)
Processing 03a01Fa.wav: 0%| | 0/535 [00:00<?, ?it/s]/home/camilo/anaconda3/lib/python3.6/site-packages/numpy/core/_asarray.py:136: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecat...
MIT
notebooks_examples/emotion classification using SVMs in scikit-learn.ipynb
virtualcharacters/DisVoice
prosody features
Xprosody=prosodyf.extract_features_path(PATH_AUDIO, static=True, plots=False, fmt="npy") print(Xprosody.shape)
Processing 14a07Aa.wav: 69%|██████▉ | 370/535 [01:12<00:33, 4.96it/s]../prosody/prosody.py:300: WavFileWarning: Chunk (non-data) not understood, skipping it. fs, data_audio=read(audio) Processing 14a07Fd.wav: 70%|██████▉ | 372/535 [01:12<00:29, 5.57it/s]../prosody/prosody.py:300: WavFileWarning: Chunk (non-da...
MIT
notebooks_examples/emotion classification using SVMs in scikit-learn.ipynb
virtualcharacters/DisVoice
phonological features
Xphonological=phonologicalf.extract_features_path(PATH_AUDIO, static=True, plots=False, fmt="npy") print(Xphonological.shape)
Processing 14a07Aa.wav: 69%|██████▉ | 370/535 [02:24<00:57, 2.89it/s]/home/camilo/anaconda3/lib/python3.6/site-packages/phonet/phonet.py:235: WavFileWarning: Chunk (non-data) not understood, skipping it. fs, signal=read(audio_file) Processing 16b10Wb.wav: 100%|██████████| 535/535 [03:28<00:00, 2.57it/s]
MIT
notebooks_examples/emotion classification using SVMs in scikit-learn.ipynb
virtualcharacters/DisVoice
representation learning features
Xrep=replearningf.extract_features_path(PATH_AUDIO, static=True, plots=False, fmt="npy") print(Xrep.shape)
Processing 03a01Fa.wav: 0%| | 0/535 [00:00<?, ?it/s]/home/camilo/anaconda3/lib/python3.6/site-packages/torch/nn/functional.py:1639: UserWarning: nn.functional.sigmoid is deprecated. Use torch.sigmoid instead. warnings.warn("nn.functional.sigmoid is deprecated. Use torch.sigmoid instead.") Processing 08b01W...
MIT
notebooks_examples/emotion classification using SVMs in scikit-learn.ipynb
virtualcharacters/DisVoice
Emotion classification using an SVM classifier
def classify(X, y): # train test split Xtrain, Xtest, ytrain, ytest = train_test_split(X, y, test_size=0.30, random_state=42) # z-score standarization scaler = preprocessing.StandardScaler().fit(Xtrain) Xtrain=scaler.transform(Xtrain) Xtest=scaler.transform(Xtest) Results=[] ...
_____no_output_____
MIT
notebooks_examples/emotion classification using SVMs in scikit-learn.ipynb
virtualcharacters/DisVoice
classify high vs. low arousal with the different feature sets
classify(Xphonation, yArousal) classify(Xarticulation, yArousal) classify(Xprosody, yArousal) classify(Xphonological, yArousal) classify(Xrep, yArousal)
Fitting 10 folds for each of 500 candidates, totalling 5000 fits
MIT
notebooks_examples/emotion classification using SVMs in scikit-learn.ipynb
virtualcharacters/DisVoice
classify positive vs. negative valence with the different feature sets
classify(Xphonation, yValence) classify(Xarticulation, yValence) classify(Xprosody, yValence) classify(Xphonological, yValence) classify(Xrep, yValence)
Fitting 10 folds for each of 500 candidates, totalling 5000 fits
MIT
notebooks_examples/emotion classification using SVMs in scikit-learn.ipynb
virtualcharacters/DisVoice
!pip install keras-tuner import tensorflow as tf from tensorflow import keras import numpy as np from matplotlib import pyplot mnist=keras.datasets.mnist (train_x, train_y), (test_x, test_y) = mnist.load_data() for i in range(9): # define subplot pyplot.subplot(330 + 1 + i) # plot raw pixel data pyplot.imsho...
_____no_output_____
Apache-2.0
Keras_mnist_digit_dataset.ipynb
Nikhitha-S-Pavan/Deep-learning-examples-using-keras
07 - Ensemble Methodsby [Alejandro Correa Bahnsen](http://www.albahnsen.com/) & [Iván Torroledo](http://www.ivantorroledo.com/)version 1.3, June 2018 Part of the class [Applied Deep Learning](https://github.com/albahnsen/AppliedDeepLearningClass)This notebook is licensed under a [Creative Commons Attribution-ShareAlik...
import numpy as np # set a seed for reproducibility np.random.seed(1234) # generate 1000 random numbers (between 0 and 1) for each model, representing 1000 observations mod1 = np.random.rand(1000) mod2 = np.random.rand(1000) mod3 = np.random.rand(1000) mod4 = np.random.rand(1000) mod5 = np.random.rand(1000) # each m...
0.841
MIT
notebooks/07_EnsembleMethods.ipynb
Tionick/AppliedDeepLearningClass
**Note:** As you add more models to the voting process, the probability of error decreases, which is known as [Condorcet's Jury Theorem](http://en.wikipedia.org/wiki/Condorcet%27s_jury_theorem). What is ensembling?**Ensemble learning (or "ensembling")** is the process of combining several predictive models in order to...
# read in and prepare the vehicle training data import zipfile import pandas as pd with zipfile.ZipFile('../datasets/vehicles_train.csv.zip', 'r') as z: f = z.open('vehicles_train.csv') train = pd.io.parsers.read_table(f, index_col=False, sep=',') with zipfile.ZipFile('../datasets/vehicles_test.csv.zip', 'r') a...
_____no_output_____
MIT
notebooks/07_EnsembleMethods.ipynb
Tionick/AppliedDeepLearningClass
Train different models
from sklearn.linear_model import LinearRegression from sklearn.tree import DecisionTreeRegressor from sklearn.naive_bayes import GaussianNB from sklearn.neighbors import KNeighborsRegressor models = {'lr': LinearRegression(), 'dt': DecisionTreeRegressor(), 'nb': GaussianNB(), 'nn': KNeigh...
lr 2138.3579028745116 dt 1414.213562373095 nb 5477.2255750516615 nn 1671.3268182295567
MIT
notebooks/07_EnsembleMethods.ipynb
Tionick/AppliedDeepLearningClass
Evaluate the error of the mean of the predictions
np.sqrt(mean_squared_error(y_pred.mean(axis=1), y_test))
_____no_output_____
MIT
notebooks/07_EnsembleMethods.ipynb
Tionick/AppliedDeepLearningClass
Comparing manual ensembling with a single model approach**Advantages of manual ensembling:**- Increases predictive accuracy- Easy to get started**Disadvantages of manual ensembling:**- Decreases interpretability- Takes longer to train- Takes longer to predict- More complex to automate and maintain- Small gains in accu...
# set a seed for reproducibility np.random.seed(1) # create an array of 1 through 20 nums = np.arange(1, 21) print(nums) # sample that array 20 times with replacement print(np.random.choice(a=nums, size=20, replace=True))
[ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20] [ 6 12 13 9 10 12 6 16 1 17 2 13 8 14 7 19 6 19 12 11]
MIT
notebooks/07_EnsembleMethods.ipynb
Tionick/AppliedDeepLearningClass
**How does bagging work (for decision trees)?**1. Grow B trees using B bootstrap samples from the training data.2. Train each tree on its bootstrap sample and make predictions.3. Combine the predictions: - Average the predictions for **regression trees** - Take a vote for **classification trees**Notes:- **Each bo...
# set a seed for reproducibility np.random.seed(123) n_samples = train.shape[0] n_B = 10 # create ten bootstrap samples (will be used to select rows from the DataFrame) samples = [np.random.choice(a=n_samples, size=n_samples, replace=True) for _ in range(1, n_B +1 )] samples # show the rows for the first decision tre...
_____no_output_____
MIT
notebooks/07_EnsembleMethods.ipynb
Tionick/AppliedDeepLearningClass
Build one tree for each sample
from sklearn.tree import DecisionTreeRegressor # grow each tree deep treereg = DecisionTreeRegressor(max_depth=None, random_state=123) # DataFrame for storing predicted price from each tree y_pred = pd.DataFrame(index=test.index, columns=[list(range(n_B))]) # grow one tree for each bootstrap sample and make predicti...
_____no_output_____
MIT
notebooks/07_EnsembleMethods.ipynb
Tionick/AppliedDeepLearningClass
Results of each tree
for i in range(n_B): print(i, np.sqrt(mean_squared_error(y_pred[i], y_test)))
0 1621.7274740226856 1 2942.7877939124323 2 1825.7418583505537 3 1000.0 4 1276.7145334803704 5 1414.213562373095 6 1414.213562373095 7 1000.0 8 1554.5631755148024 9 1914.854215512676
MIT
notebooks/07_EnsembleMethods.ipynb
Tionick/AppliedDeepLearningClass
Results of the ensemble
y_pred.mean(axis=1) np.sqrt(mean_squared_error(y_test, y_pred.mean(axis=1)))
_____no_output_____
MIT
notebooks/07_EnsembleMethods.ipynb
Tionick/AppliedDeepLearningClass
Bagged decision trees in scikit-learn (with B=500)
# define the training and testing sets X_train = train.iloc[:, 1:] y_train = train.iloc[:, 0] X_test = test.iloc[:, 1:] y_test = test.iloc[:, 0] # instruct BaggingRegressor to use DecisionTreeRegressor as the "base estimator" from sklearn.ensemble import BaggingRegressor bagreg = BaggingRegressor(DecisionTreeRegressor(...
_____no_output_____
MIT
notebooks/07_EnsembleMethods.ipynb
Tionick/AppliedDeepLearningClass
Estimating out-of-sample errorFor bagged models, out-of-sample error can be estimated without using **train/test split** or **cross-validation**!On average, each bagged tree uses about **two-thirds** of the observations. For each tree, the **remaining observations** are called "out-of-bag" observations.
# show the first bootstrap sample samples[0] # show the "in-bag" observations for each sample for sample in samples: print(set(sample)) # show the "out-of-bag" observations for each sample for sample in samples: print(sorted(set(range(n_samples)) - set(sample)))
[4, 5, 7, 8] [5, 6, 8, 10, 11, 12] [1, 5, 10, 11] [4, 7, 9, 13] [0, 1, 5, 7, 8, 9] [2, 3, 8, 12, 13] [6, 7, 10, 11, 13] [0, 4, 8, 10, 12, 13] [0, 2, 4, 5, 10, 13] [2, 7, 9, 12]
MIT
notebooks/07_EnsembleMethods.ipynb
Tionick/AppliedDeepLearningClass
How to calculate **"out-of-bag error":**1. For every observation in the training data, predict its response value using **only** the trees in which that observation was out-of-bag. Average those predictions (for regression) or take a vote (for classification).2. Compare all predictions to the actual response values in ...
# compute the out-of-bag R-squared score (not MSE, unfortunately!) for B=500 bagreg.oob_score_
_____no_output_____
MIT
notebooks/07_EnsembleMethods.ipynb
Tionick/AppliedDeepLearningClass
Estimating feature importanceBagging increases **predictive accuracy**, but decreases **model interpretability** because it's no longer possible to visualize the tree to understand the importance of each feature.However, we can still obtain an overall summary of **feature importance** from bagged models:- **Bagged reg...
# read in the data with zipfile.ZipFile('../datasets/hitters.csv.zip', 'r') as z: f = z.open('hitters.csv') hitters = pd.read_csv(f, sep=',', index_col=False) # remove rows with missing values hitters.dropna(inplace=True) hitters.head() # encode categorical variables as integers hitters['League'] = pd.factoriz...
_____no_output_____
MIT
notebooks/07_EnsembleMethods.ipynb
Tionick/AppliedDeepLearningClass
Predicting salary with a decision treeFind the best **max_depth** for a decision tree using cross-validation:
# list of values to try for max_depth max_depth_range = range(1, 21) # list to store the average RMSE for each value of max_depth RMSE_scores = [] # use 10-fold cross-validation with each value of max_depth from sklearn.model_selection import cross_val_score for depth in max_depth_range: treereg = DecisionTreeReg...
_____no_output_____
MIT
notebooks/07_EnsembleMethods.ipynb
Tionick/AppliedDeepLearningClass
Predicting salary with a Random Forest
from sklearn.ensemble import RandomForestRegressor rfreg = RandomForestRegressor() rfreg
_____no_output_____
MIT
notebooks/07_EnsembleMethods.ipynb
Tionick/AppliedDeepLearningClass
Tuning n_estimatorsOne important tuning parameter is **n_estimators**, which is the number of trees that should be grown. It should be a large enough value that the error seems to have "stabilized".
# list of values to try for n_estimators estimator_range = range(10, 310, 10) # list to store the average RMSE for each value of n_estimators RMSE_scores = [] # use 5-fold cross-validation with each value of n_estimators (WARNING: SLOW!) for estimator in estimator_range: rfreg = RandomForestRegressor(n_estimators...
_____no_output_____
MIT
notebooks/07_EnsembleMethods.ipynb
Tionick/AppliedDeepLearningClass
Tuning max_featuresThe other important tuning parameter is **max_features**, which is the number of features that should be considered at each split.
# list of values to try for max_features feature_range = range(1, len(feature_cols)+1) # list to store the average RMSE for each value of max_features RMSE_scores = [] # use 10-fold cross-validation with each value of max_features (WARNING: SLOW!) for feature in feature_range: rfreg = RandomForestRegressor(n_esti...
_____no_output_____
MIT
notebooks/07_EnsembleMethods.ipynb
Tionick/AppliedDeepLearningClass
Fitting a Random Forest with the best parameters
# max_features=8 is best and n_estimators=150 is sufficiently large rfreg = RandomForestRegressor(n_estimators=150, max_features=8, max_depth=3, oob_score=True, random_state=1) rfreg.fit(X, y) # compute feature importances pd.DataFrame({'feature':feature_cols, 'importance':rfreg.feature_importances_}).sort_values('impo...
_____no_output_____
MIT
notebooks/07_EnsembleMethods.ipynb
Tionick/AppliedDeepLearningClass
Reducing X to its most important features
# check the shape of X X.shape rfreg # set a threshold for which features to include from sklearn.feature_selection import SelectFromModel print(SelectFromModel(rfreg, threshold=0.1, prefit=True).transform(X).shape) print(SelectFromModel(rfreg, threshold='mean', prefit=True).transform(X).shape) print(SelectFromModel(rf...
_____no_output_____
MIT
notebooks/07_EnsembleMethods.ipynb
Tionick/AppliedDeepLearningClass
Examples with the SolarAbund Class (v1.1)
# import from linetools.abund import solar as labsol
_____no_output_____
BSD-3-Clause
docs/examples/SolarAbund.ipynb
jchowk/linetools
Init
sol = labsol.SolarAbund() sol
_____no_output_____
BSD-3-Clause
docs/examples/SolarAbund.ipynb
jchowk/linetools
Usage
# Simple calls print(sol['C']) print(sol[6]) # Ratio print(sol.get_ratio('C/Fe')) # Multiple calls print(sol[6,12,'S'])
[ 8.43 7.53 7.15]
BSD-3-Clause
docs/examples/SolarAbund.ipynb
jchowk/linetools
Bits and pieces
from linetools.abund import ions as laions # Ion name laions.ion_name((6,2)) # Name to ion laions.name_ion('CII') from linetools.abund.elements import ELEMENTS ele = ELEMENTS['C'] ele.eleconfig_dict
_____no_output_____
BSD-3-Clause
docs/examples/SolarAbund.ipynb
jchowk/linetools
Plotting Various Scan Reports **Covid Patient**
plt.imshow(cv2.imread("../input/covid19-image-dataset/Covid19-dataset/train/Covid/022.jpeg"))
_____no_output_____
CC0-1.0
covid-19-prediction-using-cnn.ipynb
AdityaIyer2609/Covid-19-Prediction-Using-CNN
**Pneumomnia Patient**
plt.imshow(cv2.imread("../input/covid19-image-dataset/Covid19-dataset/train/Viral Pneumonia/020.jpeg"))
_____no_output_____
CC0-1.0
covid-19-prediction-using-cnn.ipynb
AdityaIyer2609/Covid-19-Prediction-Using-CNN
**Normal Patient**
plt.imshow(cv2.imread("../input/covid19-image-dataset/Covid19-dataset/train/Normal/018.jpeg"))
_____no_output_____
CC0-1.0
covid-19-prediction-using-cnn.ipynb
AdityaIyer2609/Covid-19-Prediction-Using-CNN
Preprocessing the images
train_datagen=ImageDataGenerator(rescale=1/255, shear_range=0.2, zoom_range=2, horizontal_flip=True) training_set=train_datagen.flow_from_directory('../input/covid19-image-dataset/Covid19-dataset/train', ...
_____no_output_____
CC0-1.0
covid-19-prediction-using-cnn.ipynb
AdityaIyer2609/Covid-19-Prediction-Using-CNN
Building VGG-16 architecture & Neural Network
model = tf.keras.models.Sequential([ tf.keras.layers.Conv2D(32,(3,3),strides=(1, 1),activation='relu',padding='same', input_shape=(224, 224, 3)), tf.keras.layers.MaxPooling2D(pool_size=(2,2)), tf.keras.layers.Conv2D(64,(3,3),strides=(1, 1) ,padding='same',activation='relu'), tf.keras.layers.MaxPoo...
Epoch 1/71 8/8 [==============================] - 16s 2s/step - loss: 1.1425 - accuracy: 0.3302 - val_loss: 1.0993 - val_accuracy: 0.4091 Epoch 2/71 8/8 [==============================] - 14s 2s/step - loss: 1.0259 - accuracy: 0.5257 - val_loss: 1.0013 - val_accuracy: 0.4394 Epoch 3/71 8/8 [============================...
CC0-1.0
covid-19-prediction-using-cnn.ipynb
AdityaIyer2609/Covid-19-Prediction-Using-CNN
Prediction
import numpy as np from keras.preprocessing import image test_image = image.load_img('../input/covid19-image-dataset/Covid19-dataset/test/Viral Pneumonia/0112.jpeg', target_size = (224, 224)) test_image = image.img_to_array(test_image) test_image = np.expand_dims(test_image, axis = 0) result = model.predict(test_image)...
[[0. 0.00101711 0.99898285]]
CC0-1.0
covid-19-prediction-using-cnn.ipynb
AdityaIyer2609/Covid-19-Prediction-Using-CNN
Collaborative filtering on Google Analytics dataThis notebook demonstrates how to implement a WALS matrix refactorization approach to do collaborative filtering.
import os PROJECT = "cloud-training-demos" # REPLACE WITH YOUR PROJECT ID BUCKET = "cloud-training-demos-ml" # REPLACE WITH YOUR BUCKET NAME REGION = "us-central1" # REPLACE WITH YOUR BUCKET REGION e.g. us-central1 # Do not change these os.environ["PROJECT"] = PROJECT os.environ["BUCKET"] = BUCKET os.environ["REGION"]...
1.13.1
Apache-2.0
courses/machine_learning/deepdive/10_recommend/labs/wals.ipynb
KayvanShah1/training-data-analyst
Create raw datasetFor collaborative filtering, we don't need to know anything about either the users or the content. Essentially, all we need to know is userId, itemId, and rating that the particular user gave the particular item.In this case, we are working with newspaper articles. The company doesn't ask their users...
from google.cloud import bigquery bq = bigquery.Client(project = PROJECT) sql = """ WITH CTE_visitor_page_content AS ( SELECT # Schema: https://support.google.com/analytics/answer/3437719?hl=en # For a completely unique visit-session ID, we combine combination of fullVisitorId and visitNumber: ...
7337153711992174438,100074831,0.2321051400452234 5190801220865459604,100170790,1.0 2293633612703952721,100510126,0.2481776360816793 5874973374932455844,100510126,0.16690549004998828 1173698801255170595,100676857,0.05464232805149575 883397426232997550,10083328,0.9487035095774818 1808867070685560283,100906145,1.0 7615995...
Apache-2.0
courses/machine_learning/deepdive/10_recommend/labs/wals.ipynb
KayvanShah1/training-data-analyst
Create dataset for WALSThe raw dataset (above) won't work for WALS: The userId and itemId have to be 0,1,2 ... so we need to create a mapping from visitorId (in the raw data) to userId and contentId (in the raw data) to itemId. We will need to save the above mapping to a file because at prediction time, we'll need to ...
import pandas as pd import numpy as np def create_mapping(values, filename): with open(filename, 'w') as ofp: value_to_id = {value:idx for idx, value in enumerate(values.unique())} for value, idx in value_to_id.items(): ofp.write("{},{}\n".format(value, idx)) return value_to_id df =...
_____no_output_____
Apache-2.0
courses/machine_learning/deepdive/10_recommend/labs/wals.ipynb
KayvanShah1/training-data-analyst
Creating rows and columns datasets
import pandas as pd import numpy as np mapped_df = pd.read_csv(filepath_or_buffer = "data/collab_mapped.csv", header = None, names = ["userId", "itemId", "rating"]) mapped_df.head() NITEMS = np.max(mapped_df["itemId"]) + 1 NUSERS = np.max(mapped_df["userId"]) + 1 mapped_df["rating"] = np.round(mapped_df["rating"].value...
total 31908 -rw-r--r-- 1 jupyter jupyter 13152765 Jul 31 20:41 collab_raw.csv -rw-r--r-- 1 jupyter jupyter 2134511 Jul 31 20:41 users.csv -rw-r--r-- 1 jupyter jupyter 82947 Jul 31 20:41 items.csv -rw-r--r-- 1 jupyter jupyter 7812739 Jul 31 20:41 collab_mapped.csv -rw-r--r-- 1 jupyter jupyter 2252828 Jul 31 20:41 ...
Apache-2.0
courses/machine_learning/deepdive/10_recommend/labs/wals.ipynb
KayvanShah1/training-data-analyst
To summarize, we created the following data files from collab_raw.csv: ```collab_mapped.csv``` is essentially the same data as in ```collab_raw.csv``` except that ```visitorId``` and ```contentId``` which are business-specific have been mapped to ```userId``` and ```itemId``` which are enumerated in 0,1,2,.... The map...
import os import tensorflow as tf from tensorflow.python.lib.io import file_io from tensorflow.contrib.factorization import WALSMatrixFactorization def read_dataset(mode, args): def decode_example(protos, vocab_size): # TODO return def remap_keys(sparse_tensor): # Current indice...
_____no_output_____
Apache-2.0
courses/machine_learning/deepdive/10_recommend/labs/wals.ipynb
KayvanShah1/training-data-analyst
This code is helpful in developing the input function. You don't need it in production.
def try_out(): with tf.Session() as sess: fn = read_dataset( mode = tf.estimator.ModeKeys.EVAL, args = {"input_path": "data", "batch_size": 4, "nitems": NITEMS, "nusers": NUSERS}) feats, _ = fn() print(feats["input_rows"].eval()) print(feats["input_r...
284,5609,36 284,2754,42 284,3168,534 2621,5528,2694 4409,5295,343 5161,3267,3369 5479,1335,55 5479,1335,55 4414,284,5572 284,241,2359
Apache-2.0
courses/machine_learning/deepdive/10_recommend/labs/wals.ipynb
KayvanShah1/training-data-analyst
Run as a Python moduleLet's run it as Python module for just a few steps.
os.environ["NITEMS"] = str(NITEMS) os.environ["NUSERS"] = str(NUSERS) %%bash rm -rf wals.tar.gz wals_trained gcloud ai-platform local train \ --module-name=walsmodel.task \ --package-path=${PWD}/walsmodel \ -- \ --output_dir=${PWD}/wals_trained \ --input_path=${PWD}/data \ --num_epochs=0.01 --ni...
Will train for 2 steps, evaluating once every 162 steps
Apache-2.0
courses/machine_learning/deepdive/10_recommend/labs/wals.ipynb
KayvanShah1/training-data-analyst
Run on Cloud
%%bash gsutil -m cp data/* gs://${BUCKET}/wals/data %%bash OUTDIR=gs://${BUCKET}/wals/model_trained JOBNAME=wals_$(date -u +%y%m%d_%H%M%S) echo $OUTDIR $REGION $JOBNAME gsutil -m rm -rf $OUTDIR gcloud ai-platform jobs submit training $JOBNAME \ --region=$REGION \ --module-name=walsmodel.task \ --package-pat...
_____no_output_____
Apache-2.0
courses/machine_learning/deepdive/10_recommend/labs/wals.ipynb
KayvanShah1/training-data-analyst
This took 10 minutes for me. Get row and column factorsOnce you have a trained WALS model, you can get row and column factors (user and item embeddings) from the checkpoint file. We'll look at how to use these in the section on building a recommendation system using deep neural networks.
def get_factors(args): with tf.Session() as sess: estimator = tf.contrib.factorization.WALSMatrixFactorization( num_rows = args["nusers"], num_cols = args["nitems"], embedding_dimension = args["n_embeds"], model_dir = args["output_dir"]) row_...
INFO:tensorflow:Using default config. INFO:tensorflow:Using config: {'_environment': 'local', '_is_chief': True, '_keep_checkpoint_every_n_hours': 10000, '_num_worker_replicas': 0, '_session_config': None, '_task_type': None, '_eval_distribute': None, '_tf_config': gpu_options { per_process_gpu_memory_fraction: 1.0 }...
Apache-2.0
courses/machine_learning/deepdive/10_recommend/labs/wals.ipynb
KayvanShah1/training-data-analyst
You can visualize the embedding vectors using dimensional reduction techniques such as PCA.
import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn.decomposition import PCA pca = PCA(n_components = 3) pca.fit(user_embeddings) user_embeddings_pca = pca.transform(user_embeddings) fig = plt.figure(figsize = (8,8)) ax = fig.add_subplot(111, projection = "3d") xs, ys, zs = user_embed...
_____no_output_____
Apache-2.0
courses/machine_learning/deepdive/10_recommend/labs/wals.ipynb
KayvanShah1/training-data-analyst
Welcome back to Data Science using Pythonဒီအပါတ်မှာ Python Programming Language ကို အသုံးပြုရပြီး Program တွေ ရေးသားရမှာ ဖြစ်ပါတယ်။
# ဒီ cell ကို run လိုက်ပါ။ !git clone https://github.com/neolaw84/data_science_using_python_labs.git %cd week02
_____no_output_____
Apache-2.0
week02/01_hello_world.ipynb
neolaw84/data_science_using_python_labs
Hello World"Hello World" လို့ print ထုတ်တဲ့ statement တကြောင်းထဲပါတဲ့ Python program ကို ရေးကြည့်ရအောင်။```python beginning of programprint("Hello World") end of program```အပေါ်က program ကို အောက်က cell မှာ ကူးရေးပါ။
# copy the program here and run # you will see the output underneath %%writefile lab_hello_world.py # copy the program here to make the program file called "lab_hello_world.py" # program မှန် မမှန်ကို ဒီ cell ကို run ပြီး စမ်းသပ်ပါ။ !pytest test_hello_world.py # မင်္ဂလာပါ ကမ္ဘာကြီး လို့ output ထုတ်ပေးတဲ့ program ကို ...
_____no_output_____
Apache-2.0
week02/01_hello_world.ipynb
neolaw84/data_science_using_python_labs
Most Frequent ElementWrite a function that finds the most frequent element in an array.`most_frequent([1, 2, 2, 3]) 2`
numbers = [1, 2, 2, 3]
_____no_output_____
ADSL
04-Career-Modules/Interview_Questions/09-Most_Frequent/Unsolved/Most_Frequent.ipynb
anirudhmungre/sneaky-lessons
Building a Stack in Python Before we start let us reiterate they key components of a stack. A stack is a data structure that consists of two main operations: push and pop. A push is when you add an element to the **top of the stack** and a pop is when you remove an element from **the top of the stack**. Python 3.x con...
class Stack: def __init__(self): # TODO: Initialize the Stack def size(self): # TODO: Check the size of the Stack def push(self, item): # TODO: Push item onto Stack def pop(self): # TODO: Pop item off of the Stack
_____no_output_____
MIT
data structure/stack and queues/stack/python_stack_practice.ipynb
salviosage/Data-Structures-Algorithms-Nanodegree-playground-o
Test the Stack
MyStack = Stack() MyStack.push("Web Page 1") MyStack.push("Web Page 2") MyStack.push("Web Page 3") print (MyStack.items) MyStack.pop() MyStack.pop() print ("Pass" if (MyStack.items[0] == 'Web Page 1') else "Fail") MyStack.pop() print ("Pass" if (MyStack.pop() == None) else "Fail")
_____no_output_____
MIT
data structure/stack and queues/stack/python_stack_practice.ipynb
salviosage/Data-Structures-Algorithms-Nanodegree-playground-o
Hide Solution
# Solution class Stack: def __init__(self): self.items = [] def size(self): return len(self.items) def push(self, item): self.items.append(item) def pop(self): if self.size()==0: return None else: return self.items.pop() ...
_____no_output_____
MIT
data structure/stack and queues/stack/python_stack_practice.ipynb
salviosage/Data-Structures-Algorithms-Nanodegree-playground-o
Custom URL prefix with Seldon and AmbassadorThis notebook shows how you can deploy Seldon Deployments with custom Ambassador configuration. Setup Seldon CoreUset the setup notebook to [Setup Cluster](../../../notebooks/seldon_core_setup.ipynbSetup-Cluster) with [Ambassador Ingress](../../../notebooks/seldon_core_setu...
!pygmentize model_custom_ambassador.json !kubectl create -f model_custom_ambassador.json !kubectl rollout status deploy/$(kubectl get deploy -l seldon-deployment-id=example-custom -o jsonpath='{.items[0].metadata.name}')
_____no_output_____
Apache-2.0
examples/ambassador/custom/ambassador_custom.ipynb
pachyderm/seldon-core
Get predictions
from seldon_core.seldon_client import SeldonClient sc = SeldonClient(deployment_name="example-custom",namespace="seldon")
_____no_output_____
Apache-2.0
examples/ambassador/custom/ambassador_custom.ipynb
pachyderm/seldon-core
REST Request
r = sc.predict(gateway="ambassador",transport="rest",gateway_prefix="/mycompany/ml") assert(r.success==True) print(r) !kubectl delete -f model_custom_ambassador.json
_____no_output_____
Apache-2.0
examples/ambassador/custom/ambassador_custom.ipynb
pachyderm/seldon-core
Install the packages
!pip install -Uqq datasets pythainlp==2.2.4 transformers==4.4.0 tensorflow==2.4.0 tensorflow_text emoji seqeval sentencepiece fuzzywuzzy !npx degit --force https://github.com/vistec-AI/thai2transformers#dev %load_ext autoreload %autoreload 2 import pythainlp, transformers pythainlp.__version__, transformers.__version_...
_____no_output_____
MIT
fine_tuning_roBERTsaikwan.ipynb
Sav-eng/roBERTsaikwan-model
Prepare function for calculate metrics
!pip install rouge from rouge import Rouge rouge = Rouge() def cal_rouge_score(hyps, refs, get_average_f1=True): ''' argument: cands, refs [list of string], get_average_f1=True return dict of r1, r2, rl score if get_average_f1 == True return mean of rouge-1, rouge-2, rouge-L ''' r1 = dict(); r1['precision'...
_____no_output_____
MIT
fine_tuning_roBERTsaikwan.ipynb
Sav-eng/roBERTsaikwan-model
Utility functions for calculate label in our use.
def tokenize_with_space(texts, tokenizer): output = [] encoded_texts = tokenizer(texts, max_length=416, truncation=True) for text in encoded_texts['input_ids']: tokenized_text = " ".join(tokenizer.convert_ids_to_tokens(text, skip_special_tokens=True)) if(len(tokenized_text)==0): output.append("") ...
_____no_output_____
MIT
fine_tuning_roBERTsaikwan.ipynb
Sav-eng/roBERTsaikwan-model