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
The heatmap above shows silhouette scores for various combinations of random state and number of clusters. The highest scores are for 2 and 3 clusters and they are relatively insensitive to seed. Since there is small differences I will chose 3 clusters to get more insight into data.
km=KMeans(n_clusters=3) predict=km.fit_predict(features) predict km.cluster_centers_ features["cluster"]=predict features.head() grouped_km = features.groupby(['cluster']).mean().round() grouped_km #Ploting scatterplot title = 'Income by age ' plt.figure(figsize=(12,9)) sns.scatterplot(features.age,features.income,hue=...
_____no_output_____
MIT
clustering_k_means_bank_loans.ipynb
Filipos27/KMeans_clustering
*Accompanying code examples of the book "Introduction to Artificial Neural Networks and Deep Learning: A Practical Guide with Applications in Python" by [Sebastian Raschka](https://sebastianraschka.com). All code examples are released under the [MIT license](https://github.com/rasbt/deep-learning-book/blob/master/LICEN...
%load_ext watermark %watermark -a 'Sebastian Raschka' -v -p torch
Sebastian Raschka CPython 3.6.8 IPython 7.2.0 torch 1.0.1.post2
MIT
code/model_zoo/pytorch_ipynb/convnet-vgg16-celeba-data-parallel.ipynb
tongni1975/deep-learning-book
Model Zoo -- CNN Gender Classifier (VGG16 Architecture, CelebA) with Data Parallelism There are multiple ways of leveraging multiple GPUs when using PyTorch. One of these approaches is to send a copy of the model to each available GPU and split the minibatches across using `DataParallel`.To break it down into conceptu...
import os import time import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import Dataset from torch.utils.data import DataLoader from torchvision import datasets from torchvision import transforms import matplotlib.pyplot as plt from PIL i...
_____no_output_____
MIT
code/model_zoo/pytorch_ipynb/convnet-vgg16-celeba-data-parallel.ipynb
tongni1975/deep-learning-book
Dataset Downloading the Dataset Note that the ~200,000 CelebA face image dataset is relatively large (~1.3 Gb). The download link provided below was provided by the author on the official CelebA website at http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html. 1) Download and unzip the file `img_align_celeba.zip`, which ...
df1 = pd.read_csv('list_attr_celeba.txt', sep="\s+", skiprows=1, usecols=['Male']) # Make 0 (female) & 1 (male) labels instead of -1 & 1 df1.loc[df1['Male'] == -1, 'Male'] = 0 df1.head() df2 = pd.read_csv('list_eval_partition.txt', sep="\s+", skiprows=0, header=None) df2.columns = ['Filename', 'Partition'] df2 = df2....
(218, 178, 3)
MIT
code/model_zoo/pytorch_ipynb/convnet-vgg16-celeba-data-parallel.ipynb
tongni1975/deep-learning-book
Implementing a Custom DataLoader Class
class CelebaDataset(Dataset): """Custom Dataset for loading CelebA face images""" def __init__(self, csv_path, img_dir, transform=None): df = pd.read_csv(csv_path, index_col=0) self.img_dir = img_dir self.csv_path = csv_path self.img_names = df.index.values self.y =...
_____no_output_____
MIT
code/model_zoo/pytorch_ipynb/convnet-vgg16-celeba-data-parallel.ipynb
tongni1975/deep-learning-book
Running the VGG16 on this dataset with a minibatch size of 64 uses approximately 6.6 Gb of GPU memory. However, since we will split the batch size over for GPUs now, along with the model, we can actually comfortably use 64*4 as the batch size.
# Note that transforms.ToTensor() # already divides pixels by 255. internally custom_transform = transforms.Compose([transforms.CenterCrop((178, 178)), transforms.Resize((128, 128)), #transforms.Grayscale(), ...
_____no_output_____
MIT
code/model_zoo/pytorch_ipynb/convnet-vgg16-celeba-data-parallel.ipynb
tongni1975/deep-learning-book
Note that for DataParallel to work, the data currently needs to be on the first cuda device, "cuda:0". Otherwise, we will get a `RuntimeError: all tensors must be on devices[0]`. Hence, we define `device` below, which we use to transfer the input data to during training.
device = torch.device("cuda:0") torch.manual_seed(0) num_epochs = 2 for epoch in range(num_epochs): for batch_idx, (x, y) in enumerate(train_loader): print('Epoch:', epoch+1, end='') print(' | Batch index:', batch_idx, end='') print(' | Batch size:', y.size()[0]) ...
Epoch: 1 | Batch index: 0 | Batch size: 256 Epoch: 2 | Batch index: 0 | Batch size: 256
MIT
code/model_zoo/pytorch_ipynb/convnet-vgg16-celeba-data-parallel.ipynb
tongni1975/deep-learning-book
Model
########################## ### SETTINGS ########################## # Hyperparameters random_seed = 1 learning_rate = 0.001 num_epochs = 3 # Architecture num_features = 128*128 num_classes = 2 ########################## ### MODEL ########################## class VGG16(torch.nn.Module): def __init__(self, num_fe...
Using 4 GPUs
MIT
code/model_zoo/pytorch_ipynb/convnet-vgg16-celeba-data-parallel.ipynb
tongni1975/deep-learning-book
Training
def compute_accuracy(model, data_loader): correct_pred, num_examples = 0, 0 for i, (features, targets) in enumerate(data_loader): features = features.to(device) targets = targets.to(device) logits, probas = model(features) _, predicted_labels = torch.max(probas, 1) ...
Epoch: 001/003 | Batch 0000/0636 | Cost: 8824.2812 Epoch: 001/003 | Batch 0050/0636 | Cost: 0.7300 Epoch: 001/003 | Batch 0100/0636 | Cost: 0.5690 Epoch: 001/003 | Batch 0150/0636 | Cost: 0.4973 Epoch: 001/003 | Batch 0200/0636 | Cost: 0.4219 Epoch: 001/003 | Batch 0250/0636 | Cost: 0.3375 Epoch: 001/003 | Batch 0300/0...
MIT
code/model_zoo/pytorch_ipynb/convnet-vgg16-celeba-data-parallel.ipynb
tongni1975/deep-learning-book
Evaluation
model.eval() with torch.set_grad_enabled(False): # save memory during inference print('Test accuracy: %.2f%%' % (compute_accuracy(model, test_loader))) for batch_idx, (features, targets) in enumerate(test_loader): features = features targets = targets break plt.imshow(np.transpose(features[0], (1...
numpy 1.15.4 pandas 0.23.4 torch 1.0.1.post2 PIL.Image 5.3.0
MIT
code/model_zoo/pytorch_ipynb/convnet-vgg16-celeba-data-parallel.ipynb
tongni1975/deep-learning-book
Read dataYour task is to find parameters $\beta$ of a linear model that approximates the following observations. Each observation is decribed by only one input feature $x_{1}$.
# Read data for the file data = pd.read_csv("https://raw.githubusercontent.com/lutik-inc/notebooks/master/chunk_4/task_02/data.csv") # Display the first 5 rows of the data data.head() # Get a matrix of the input feature of the observations x1 = data[['x1']].values # Get a vector of target values you need to approxima...
_____no_output_____
Apache-2.0
course_1/2_topic/2_function_approximation/2_task_02.ipynb
HSE-LAMBDA/ML-IDS
Create matrix XNow you have the vector of targets $y = (y_{1}, y_{2}, ..., y_{n})^{T}$. Create a matrix $X$ that is defined as$$X = \left( \begin{array}{ccccc} 1 & x_{11} & x_{12} & \cdots & x_{1d} \\ 1 & x_{21} & x_{22} & \cdots & x_{2d} \\ \vdots & \vdots & \vdots & \cdots & \vdots \\ ...
X = ... # Put your code here (2 lines) print("Output:") X[:2, :]
_____no_output_____
Apache-2.0
course_1/2_topic/2_function_approximation/2_task_02.ipynb
HSE-LAMBDA/ML-IDS
Expected otput : `[[ 1. , -1. ], [ 1. , -0.959]]` Init $\beta$
beta = np.array([0, 0]) print("Output:") beta
_____no_output_____
Apache-2.0
course_1/2_topic/2_function_approximation/2_task_02.ipynb
HSE-LAMBDA/ML-IDS
LossCalculate the loss function defined as:$$L(\beta) = \frac{1}{n} (X\beta - y)^{T}(X\beta - y)$$**Hint:** To multiply two matrices $a$ and $b$ use functions `a.dot(b)` or `np.dot(a, b)`.
def loss_func(beta): loss = ... # Put your code here (1 line) return loss loss = loss_func(beta) print("Output:") loss
_____no_output_____
Apache-2.0
course_1/2_topic/2_function_approximation/2_task_02.ipynb
HSE-LAMBDA/ML-IDS
Expected otput : `2.19695098` Gradient of the loss functionCalculate gradient of the loss function $\nabla L$ defined as: $$\nabla L = \frac{\partial L}{\partial \beta} = \frac{2}{n} X^{T} (X\beta - y)$$**Hint:** To multiply two matrices $a$ and $b$ use functions `a.dot(b)` or `np.dot(a, b)`.
def grad_func(beta): grad = ... # Put your code here (1 line) return grad grad = grad_func(beta) print("Output:") grad
_____no_output_____
Apache-2.0
course_1/2_topic/2_function_approximation/2_task_02.ipynb
HSE-LAMBDA/ML-IDS
Expected otput : `[-1.40972 , -1.52095704]` Gradient descentNow implement gradient descent for the approximation. The update rule for $\beta$ is:$$\beta_{(t+1)} = \beta_{(t)} - \alpha \nabla L(\beta_{(t)})$$Estimate how many iterations $t$ it is needed to satisfy the following stop criterion:$$| L(\beta_{(t)} - L(\...
alpha = 0.1 # learning rate beta = np.array([0, 0]) # init beta, again :) beta_collector = [beta] loss_collector = [loss_func(beta)] for i_iter in range(1000): # for each iteration # Calculate gradient grad = ... # Put your code here (1 line) # Update beta beta = ... # Put your...
_____no_output_____
Apache-2.0
course_1/2_topic/2_function_approximation/2_task_02.ipynb
HSE-LAMBDA/ML-IDS
Content under Creative Commons Attribution license CC-BY 4.0, code under MIT license (c)2014 L.A. Barba, G.F. Forsyth, C.D. Cooper. Spreading out Welcome back! This is the third lesson of the course [Module 4](https://github.com/numerical-mooc/numerical-mooc/tree/master/lessons/04_spreadout), _Spreading out: paraboli...
import numpy from matplotlib import pyplot %matplotlib inline # Set the font family and size to use for Matplotlib figures. pyplot.rcParams['font.family'] = 'serif' pyplot.rcParams['font.size'] = 16 def ftcs(T0, nt, dt, dx, dy, alpha): """ Computes and returns the temperature distribution after a given numb...
_____no_output_____
CC-BY-3.0
lessons/04_spreadout/04_03_Heat_Equation_2D_Explicit.ipynb
eschew-art/numerical-mooc
See the [`break`](https://docs.python.org/3/tutorial/controlflow.html) statement? It exits the `for` loop at the closest time iteration when the plate reaches $70{\rm C}$.In the code cell below, we define our initial conditions according to the problem set up, and choose the discretization parameters. We start with onl...
# Set parameters. Lx = 0.01 # length of the plate in the x direction Ly = 0.01 # height of the plate in the y direction nx = 21 # number of points in the x direction ny = 21 # number of points in the y direction dx = Lx / (nx - 1) # grid spacing in the x direction dy = Ly / (ny - 1) # grid spacing in the y direct...
_____no_output_____
CC-BY-3.0
lessons/04_spreadout/04_03_Heat_Equation_2D_Explicit.ipynb
eschew-art/numerical-mooc
We don't want our solution blowing up, so let's find a time step with $\frac{\alpha \Delta t}{\Delta x^2} = \frac{\alpha \Delta t}{\Delta y^2} = \frac{1}{4}$.
# Set the time-step size based on CFL limit. sigma = 0.25 dt = sigma * min(dx, dy)**2 / alpha # time-step size nt = 500 # number of time steps to compute # Compute the temperature along the rod. T = ftcs(T0, nt, dt, dx, dy, alpha)
[time step 256] Center at T=70.02 at t=0.16 s
CC-BY-3.0
lessons/04_spreadout/04_03_Heat_Equation_2D_Explicit.ipynb
eschew-art/numerical-mooc
Visualize the results By now, you're no doubt *very* familiar with the `pyplot.plot` command. It's great for line plots, scatter plots, etc., but what about when we have two spatial dimensions and another value (temperature) to display? Are you thinking contour plot? We're thinking contour plot. Check out the docu...
# Plot the filled contour of the temperature. pyplot.figure(figsize=(8.0, 5.0)) pyplot.xlabel('x [m]') pyplot.ylabel('y [m]') levels = numpy.linspace(20.0, 100.0, num=51) contf = pyplot.contourf(x, y, T, levels=levels) cbar = pyplot.colorbar(contf) cbar.set_label('Temperature [C]') pyplot.axis('scaled', adjustable='box...
_____no_output_____
CC-BY-3.0
lessons/04_spreadout/04_03_Heat_Equation_2D_Explicit.ipynb
eschew-art/numerical-mooc
That looks pretty cool! Note that in the call to `pyplot.contourf` you can specify the number of contour levels to display (we chose `51`). Look at that visualization: does it make physical sense to you, considering that the upper and right sides of the chip are insulated, in our problem? Dig deeper In the problem we...
from IPython.core.display import HTML css_file = '../../styles/numericalmoocstyle.css' HTML(open(css_file, 'r').read())
_____no_output_____
CC-BY-3.0
lessons/04_spreadout/04_03_Heat_Equation_2D_Explicit.ipynb
eschew-art/numerical-mooc
A Basic ModelIn this example application it is shown how a simple time series model can be developed to simulate groundwater levels. The recharge (calculated as precipitation minus evaporation) is used as the explanatory time series.
import matplotlib.pyplot as plt import pandas as pd import pastas as ps ps.show_versions()
Python version: 3.8.2 (default, Mar 25 2020, 11:22:43) [Clang 4.0.1 (tags/RELEASE_401/final)] Numpy version: 1.20.2 Scipy version: 1.6.2 Pandas version: 1.1.5 Pastas version: 0.18.0b Matplotlib version: 3.3.4
MIT
examples/notebooks/01_basic_model.ipynb
pastas/pastas
1. Importing the dependent time series dataIn this codeblock a time series of groundwater levels is imported using the `read_csv` function of `pandas`. As `pastas` expects a `pandas` `Series` object, the data is squeezed. To check if you have the correct data type (a `pandas Series` object), you can use `type(oseries)...
# Import groundwater time seriesm and squeeze to Series object gwdata = pd.read_csv('../data/head_nb1.csv', parse_dates=['date'], index_col='date', squeeze=True) print('The data type of the oseries is: %s' % type(gwdata)) # Plot the observed groundwater levels gwdata.plot(style='.', figsize=(10, 4...
The data type of the oseries is: <class 'pandas.core.series.Series'>
MIT
examples/notebooks/01_basic_model.ipynb
pastas/pastas
2. Import the independent time seriesTwo explanatory series are used: the precipitation and the potential evaporation. These need to be `pandas Series` objects, as for the observed heads.Important characteristics of these time series are:- All series are stored as `pandas Series` objects.- The series may have irregula...
# Import observed precipitation series precip = pd.read_csv('../data/rain_nb1.csv', parse_dates=['date'], index_col='date', squeeze=True) print('The data type of the precip series is: %s' % type(precip)) # Import observed evaporation series evap = pd.read_csv('../data/evap_nb1.csv', parse_dates=['...
The data type of the precip series is: <class 'pandas.core.series.Series'> The data type of the evap series is: <class 'pandas.core.series.Series'> The data type of the recharge series is: <class 'pandas.core.series.Series'>
MIT
examples/notebooks/01_basic_model.ipynb
pastas/pastas
3. Create the time series modelIn this code block the actual time series model is created. First, an instance of the `Model` class is created (named `ml` here). Second, the different components of the time series model are created and added to the model. The imported time series are automatically checked for missing v...
# Create a model object by passing it the observed series ml = ps.Model(gwdata, name="GWL") # Add the recharge data as explanatory variable sm = ps.StressModel(recharge, ps.Gamma, name='recharge', settings="evap") ml.add_stressmodel(sm)
INFO: Cannot determine frequency of series head: freq=None. The time series is irregular. INFO: Nan-values were removed at the end of the time series None. INFO: Inferred frequency for time series None: freq=D
MIT
examples/notebooks/01_basic_model.ipynb
pastas/pastas
4. Solve the modelThe next step is to compute the optimal model parameters. The default solver uses a non-linear least squares method for the optimization. The python package `scipy` is used (info on `scipy's` least_squares solver can be found [here](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize...
ml.solve()
INFO: Time Series None was extended to 1975-11-17 00:00:00 with the mean value of the time series.
MIT
examples/notebooks/01_basic_model.ipynb
pastas/pastas
5. Plot the resultsThe solution can be plotted after a solution has been obtained.
ml.plot()
_____no_output_____
MIT
examples/notebooks/01_basic_model.ipynb
pastas/pastas
6. Advanced plottingThere are many ways to further explore the time series model. `pastas` has some built-in functionalities that will provide the user with a quick overview of the model. The `plots` subpackage contains all the options. One of these is the method `plots.results` which provides a plot with more informa...
ml.plots.results(figsize=(10, 6))
_____no_output_____
MIT
examples/notebooks/01_basic_model.ipynb
pastas/pastas
7. StatisticsThe `stats` subpackage includes a number of statistical functions that may applied to the model. One of them is the `summary` method, which gives a summary of the main statistics of the model.
ml.stats.summary()
_____no_output_____
MIT
examples/notebooks/01_basic_model.ipynb
pastas/pastas
8. Improvement: estimate evaporation factorIn the previous model, the recharge was estimated as precipitation minus potential evaporation. A better model is to estimate the actual evaporation as a factor (called the evaporation factor here) times the potential evaporation. First, new model is created (called `ml2` her...
# Create a model object by passing it the observed series ml2 = ps.Model(gwdata) # Add the recharge data as explanatory variable ts1 = ps.RechargeModel(precip, evap, ps.Gamma, name='rainevap', recharge=ps.rch.Linear(), settings=("prec", "evap")) ml2.add_stressmodel(ts1) # Solve the model ml2.s...
INFO: Cannot determine frequency of series head: freq=None. The time series is irregular. INFO: Inferred frequency for time series rain: freq=D INFO: Inferred frequency for time series evap: freq=D INFO: Time Series rain was extended to 1975-11-17 00:00:00 with the mean value of the time series. INFO: Time Series evap ...
MIT
examples/notebooks/01_basic_model.ipynb
pastas/pastas
Load Data
def mnist_data(): compose = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((.5,), (.5,)) ]) out_dir = '{}/dataset'.format(DATA_FOLDER) return datasets.MNIST(root=out_dir, train=True, transform=compose, download=True) # Load data data = mnist_data() # Create loader ...
_____no_output_____
MIT
1. Vanilla GAN TensorFlow.ipynb
akiyamasho/gans
Initialize Graph
## Discriminator # Input X = tf.placeholder(tf.float32, shape=(None, IMAGE_PIXELS)) # Layer 1 Variables D_W1 = tf.Variable(xavier_init([784, 1024])) D_B1 = tf.Variable(xavier_init([1024])) # Layer 2 Variables D_W2 = tf.Variable(xavier_init([1024, 512])) D_B2 = tf.Variable(xavier_init([512])) # Layer 3 Variables D_W...
_____no_output_____
MIT
1. Vanilla GAN TensorFlow.ipynb
akiyamasho/gans
Train Testing
num_test_samples = 16 test_noise = noise(num_test_samples, NOISE_SIZE)
_____no_output_____
MIT
1. Vanilla GAN TensorFlow.ipynb
akiyamasho/gans
Inits
num_epochs = 200 # Start interactive session session = tf.InteractiveSession() # Init Variables tf.global_variables_initializer().run() # Init Logger logger = Logger(model_name='DCGAN1', data_name='CIFAR10')
_____no_output_____
MIT
1. Vanilla GAN TensorFlow.ipynb
akiyamasho/gans
Train
# Iterate through epochs for epoch in range(num_epochs): for n_batch, (batch,_) in enumerate(data_loader): # 1. Train Discriminator X_batch = images_to_vectors(batch.permute(0, 2, 3, 1).numpy()) feed_dict = {X: X_batch, Z: noise(BATCH_SIZE, NOISE_SIZE)} _, d_error, d_pred_re...
_____no_output_____
MIT
1. Vanilla GAN TensorFlow.ipynb
akiyamasho/gans
Omega and XiTo implement Graph SLAM, a matrix and a vector (omega and xi, respectively) are introduced. The matrix is square and labelled with all the robot poses (xi) and all the landmarks (Li). Every time you make an observation, for example, as you move between two poses by some distance `dx` and can relate those t...
import numpy as np # define omega and xi as in the example omega = np.array([[1,0,0], [-1,1,0], [0,-1,1]]) xi = np.array([[-3], [5], [3]]) # calculate the inverse of omega omega_inv = np.linalg.inv(np.matrix(omega)) # calculate the solution, mu mu = ...
[[-3.] [ 2.] [ 5.]]
MIT
2. Omega and Xi, Constraints.ipynb
shinyingl/CV_SLAM
Chapter 3-2 Multiple Linear RegressionConcepts and data from "An Introduction to Statistical Learning, with applications in R" (Springer, 2013) with permission from the authors: G. James, D. Witten, T. Hastie and R. Tibshirani " available at [www.StatLearning.com](http://www.StatLearning.com).For Tables reference se...
# HIDDEN # For Tables reference see http://data8.org/datascience/tables.html # This useful nonsense should just go at the top of your notebook. from datascience import * %matplotlib inline import matplotlib.pyplot as plots import numpy as np from sklearn import linear_model plots.style.use('fivethirtyeight') plots.rc('...
_____no_output_____
BSD-2-Clause
Chapter3-2.ipynb
deculler/MachineLearningTables
3.2.1 Estimating the Regression CoefficientsThe multiple linear regression model takes the form$Y = β_0 + β_1X_1 +···+β_{p}X_{p} + ε$,where $X_j$ represents the jth predictor and $β_j$ quantifies the association between that variable and the response. We interpret βj as the average effect on Y of a one unit increase i...
advertising.linear_regression('Sales').params adver_model = advertising.linear_regression('Sales').model adver_model(0,0,0)
_____no_output_____
BSD-2-Clause
Chapter3-2.ipynb
deculler/MachineLearningTables
Visualizing a 2D regression
ad2 = advertising.drop('Newspaper') ad2.linear_regression('Sales').summary() # Linear model with two input variables is a plane ad2.plot_fit('Sales', ad2.linear_regression('Sales').model, width=8)
_____no_output_____
BSD-2-Clause
Chapter3-2.ipynb
deculler/MachineLearningTables
Multiple regression inference and goodness of fitAt this point "ISL" skips over how to compute the standard error of the multiple regression parameters - relying on R to just produce the answer. It requires some matrix notation and a numerical computation of the matrix inverse, but involves a bunch of standard termin...
# response vector Y = advertising['Sales'] labels = [lbl for lbl in advertising.labels if lbl != 'Sales'] p = len(labels) # number of parameter n = len(Y) # number of observations labels # Transform the table into a matrix advertising.select(labels).rows # Design matrix X = np.array([np.append([1], row) for row in adv...
_____no_output_____
BSD-2-Clause
Chapter3-2.ipynb
deculler/MachineLearningTables
3.2.2 Some Important questions1. Is at least one of the predictors X1 , X2 , . . . , Xp useful in predicting the response?2. Do all the predictors help to explain Y, or is only a subset of the predictors useful?3. How well does the model fit the data?4. Given a set of predictor values, what response value should we pr...
advertising.Cor()
_____no_output_____
BSD-2-Clause
Chapter3-2.ipynb
deculler/MachineLearningTables
F-statistic$F = \frac{(TSS - RSS)/p}{RSS/(n - p - 1)}$When there is no relationship between the response and predictors, one would expect the F-statistic to take on a value close to 1. On the other hand, if Ha is true, then E{(TSS − RSS)/p} > σ2, so we expect F to be greater than 1.
advertising.F_model('Sales', adver_model) advertising.lm_fit('Sales', adver_model) # Using this tool for the 1D model within the table advertising.lm_fit('Sales', advertising.regression_1d('Sales', 'TV'), 'TV')
_____no_output_____
BSD-2-Clause
Chapter3-2.ipynb
deculler/MachineLearningTables
Sometimes we want to test that a particular subset of q of the coefficients are zero. This corresponds to a null hypothesisH0 : $β_{p−q+1} =β_{p−q+2} =...=β_{p} =0$where for convenience we have put the variables chosen for omission at the end of the list. In this case we fit a second model that uses all the variables e...
ad2_model = ad2.linear_regression('Sales').model ad2.lm_fit('Sales', ad2_model) RSS0 = ad2.RSS_model('Sales', ad2_model) RSS = advertising.RSS_model('Sales', adver_model) ((RSS0 - RSS)/1)/(advertising.num_rows - 3 - 1)
_____no_output_____
BSD-2-Clause
Chapter3-2.ipynb
deculler/MachineLearningTables
Variable selection* *Forward selection* - start with null model and add predictors one at a time using the variable that result in the lowest RSS* *Backward selection* - start with all variables and iteratively remove the one with the largest P-value (smallest T-statistic)* *Mixed selection* - add like forward but ski...
input_labels = [lbl for lbl in advertising.labels if lbl != 'Sales'] fwd_labels = ['Sales'] for lbl in input_labels: fwd = advertising.select(fwd_labels + [lbl]) model = fwd.linear_regression('Sales').model print(lbl, fwd.RSS_model('Sales', model))
TV 2102.53058313 Radio 3618.47954903 Newspaper 5134.80454411
BSD-2-Clause
Chapter3-2.ipynb
deculler/MachineLearningTables
Uncomment the following line to install [geemap](https://geemap.org) if needed.
# !pip install geemap import geemap geemap.show_youtube('9EUTX8j-YVM') Map = geemap.Map() Map.split_map() Map Map = geemap.Map() Map.split_map(left_layer='HYBRID', right_layer='ROADMAP') Map basemaps = geemap.ee_basemaps.keys() print(basemaps) for basemap in basemaps: print(basemap) Map = geemap.Map() Map.split_map...
_____no_output_____
MIT
examples/notebooks/04_split_panel_map.ipynb
deeplook/geemap
When `for` gets next element from `zip(surnames, ages)`, it gets a `tuple()`. Python easily iterates over the sequence.
surnames = ['Smith', 'Johnson', 'Williams', 'Jones', 'Brown'] ages = [25, 30, 31, 39, 26] for surname, age in zip(surnames, ages): print('Surname: %s | Age: %s' % (surname, age))
Surname: Smith | Age: 25 Surname: Johnson | Age: 30 Surname: Williams | Age: 31 Surname: Jones | Age: 39 Surname: Brown | Age: 26
MIT
python-note/python_notebooks-master/for_zip_surnames.ipynb
ii6uu99/ipynb
Stack - Bootcamp de Data Science Machine Learning.
import pandas as pd import datetime import glob from minio import Minio import numpy as np import matplotlib.pyplot as plt client = Minio( "localhost:9000", access_key="minioadmin", secret_key="minioadmin", secure=False )
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Baixando o Dataset do Data Lake.
client.fget_object( "processing", "employees_dataset.parquet", "temp_.parquet", ) df = pd.read_parquet("temp_.parquet") df.head()
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Organizando o dataset.
df = df[['department', 'salary', 'mean_work_last_3_months', 'number_projects', 'satisfaction_level', 'last_evaluation', 'time_in_company', 'work_accident','left']] df.head()
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Verificando os registros missing.
df.isnull().sum() df[df.notnull()] df = df[:14998]
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Alterando os tipos de dados.
df["number_projects"] = df["number_projects"].astype(int) df["mean_work_last_3_months"] = df["mean_work_last_3_months"].astype(int) df["time_in_company"] = df["time_in_company"].astype(int) df["work_accident"] = df["work_accident"].astype(int) df["left"] = df["left"].astype(int) df.info() df.head() df = df[:14998]
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Renomeando atributos
df = df.rename(columns={'satisfaction_level': 'satisfaction', 'last_evaluation': 'evaluation', 'number_projects': 'projectCount', 'mean_work_last_3_months': 'averageMonthlyHours', 'time_in_company': 'yearsAtCompany', ...
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Importancia de Features Converte os atributos em categoricos.
df["department"] = df["department"].astype('category').cat.codes df["salary"] = df["salary"].astype('category').cat.codes df.head()
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Separando os conjuntos de dados.
target_name = 'turnover' X = df.drop('turnover', axis=1) y = df[target_name]
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Transformando os dados.
#Transforma os valores das features para minimo 0 e maximo 1. from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler() X = scaler.fit_transform(X) X
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Separando os conjuntos.
#Separa os dados em dados para treino e para teste. from sklearn.model_selection import train_test_split #20% para teste do modelo X_train, X_test, y_train, y_test = train_test_split( X ,y ,test_size = 0.2 ,random_state = 123 ,stratify = y #mantém balanceamento entre as classes (tur...
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Treinando o algoritmo de arvore de decisão.
from sklearn.tree import DecisionTreeClassifier dtree = DecisionTreeClassifier() dtree = dtree.fit(X_train,y_train) importances = dtree.feature_importances_ feat_names = df.drop(['turnover'],axis=1).columns indices = np.argsort(importances)[::-1] plt.figure(figsize=(12,4)) plt.title("Feature importances by DecisionTree...
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Filtrando apenas os atributos relevantes.
#Seleciona apenas as features que se mostraram relevantes no gráfico de importâncias. X = df[["satisfaction","evaluation","averageMonthlyHours","yearsAtCompany"]]
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Separando os conjuntos de dados.
#tem que refazer o processo, pois o 'X' foi alterado direto no df. scaler = MinMaxScaler() X = scaler.fit_transform(X) X_train, X_test, y_train, y_test = train_test_split( X ,y ,test_size = 0.2 ,random_state = 123 ,stratify = y ) X_train
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Função do modelo de base.
#'Linha de base' def base_rate_model(X) : y = np.zeros(X.shape[0]) return y
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Importando métodos de métrica de avaliação.
from sklearn.metrics import roc_auc_score from sklearn.metrics import accuracy_score from sklearn.metrics import classification_report def accuracy_result(y_test,y_predict): acc = accuracy_score(y_test, y_predict) print ("Accuracy = %2.2f" % acc) def roc_classification_report_results(model,y_test,y_predict): ...
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Análise do modelo de baseline
y_predict = base_rate_model(X_test) accuracy_result(y_test, y_predict) #Accuracy não é uma boa métrica, visto que a base de dados é desbalanceada. Ela pode nos enganar neste caso. #Como podemos ver abaixo o modelo não acerta o nosso target que é 1. roc_classification_report_results("Base Model", y_test, y_predict)
Base Model AUC = 0.5 precision recall f1-score support 0 0.76 1.00 0.86 2286 1 0.00 0.00 0.00 714 accuracy 0.76 3000 macro avg 0.38 0.50 0.43 3000 weighted avg 0.58 ...
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Modelo de Regressão Logística. Instânciando o algoritmo.
from sklearn.linear_model import LogisticRegression logis = LogisticRegression()
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Realizando o treinamento.
logis.fit(X_train, y_train)
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Calculando as predições.
y_predict = logis.predict(X_test)
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Avaliando o resultado.
#O treino é feito com as features de treino e as classes de treino e no modelo de predição se passa o conjunto de teste para que o modelo retorne a classe accuracy_result(y_test, y_predict) roc_classification_report_results("Logistic Regression", y_test, y_predict)
Logistic Regression AUC = 0.5406235985207731 precision recall f1-score support 0 0.78 0.97 0.86 2286 1 0.55 0.11 0.18 714 accuracy 0.77 3000 macro avg 0.66 0.54 0.52 3000 w...
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Modelo de Arvore de decisão. Instânciando o algoritmo.
from sklearn.tree import DecisionTreeClassifier dtree = DecisionTreeClassifier()
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Realizando o treinamento.
dtree = dtree.fit(X_train,y_train)
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Calculando as predições.
y_predict = dtree.predict(X_test)
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Avaliando o resultado.
accuracy_result(y_test, y_predict) roc_classification_report_results("Decision Tree", y_test, y_predict)
Decision Tree AUC = 0.6698206841791834 precision recall f1-score support 0 0.85 0.82 0.83 2286 1 0.48 0.52 0.50 714 accuracy 0.75 3000 macro avg 0.66 0.67 0.66 3000 weighte...
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Modelo de Arvore Aleatória (Random Forest) Instânciando o algoritmo.
from sklearn.ensemble import RandomForestClassifier rf = RandomForestClassifier()
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Realizando o treinamento.
rf = rf.fit(X_train,y_train)
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Calculando as predições.
y_predict = rf.predict(X_test)
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Avaliando o resultado.
accuracy_result(y_test, y_predict) roc_classification_report_results("Random Forest", y_test, y_predict)
Random Forest AUC = 0.726341192645037 precision recall f1-score support 0 0.86 0.93 0.89 2286 1 0.69 0.53 0.60 714 accuracy 0.83 3000 macro avg 0.78 0.73 0.75 3000 weighted...
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Pycaret
!pip install pycaret
Requirement already satisfied: pycaret in c:\users\rafael\anaconda3\lib\site-packages (2.3.4) Requirement already satisfied: spacy<2.4.0 in c:\users\rafael\appdata\roaming\python\python38\site-packages (from pycaret) (2.3.7) Requirement already satisfied: Boruta in c:\users\rafael\appdata\roaming\python\python38\site-p...
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Importando os métodos.
from pycaret.classification import *
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Definindo o Setup.
#dica: primeiro executa, confere o datatype depois adiciona transformação de type. s = setup( df[["satisfaction","evaluation","averageMonthlyHours","yearsAtCompany","turnover"]] ,target = "turnover" ,numeric_features = ["yearsAtCompany","averageMonthlyHours"] #transformo ele em numerico, pois antes ...
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Comparando diferentes modelos.
best = compare_models(fold = 5,sort = 'AUC',)
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Criando o modelo.
gbc = create_model('gbc', fold = 5)
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Realizando o tunning do modelo.
tuned_gbc = tune_model(gbc ,fold = 5 ,custom_grid = {"learning_rate":[0.1,0.2,0.5] ,"n_estimators":[100,500,1000] ,"min_samples_split":[1,2,5,10] ,"max_depth":[1,3,9...
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Neste caso não fez sentido o tunning, pois piorou o resultado. Finalizando o modelo.
final_model = finalize_model(tuned_gbc) save_model(final_model,'model')
Transformation Pipeline and Model Successfully Saved
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Transferindo os arquivos para o Data Lake. Modelo de Classificação.
client.fput_object( "curated", "model.pkl", "model.pkl" )
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
Exportando o conjunto de dados para o disco.
df.to_csv("dataset.csv",index=False) client.fput_object( "curated", "dataset.csv", "dataset.csv" )
_____no_output_____
MIT
HR App/notebooks/machine_learning_deploy.ipynb
Rafaschreinert/portfolio_rafael
First Administrative Divisions of Countries **[Work in progress]**This notebook creates a .csv file with first administrative divisions (State, Province, Municipality) for ingestion into the Knowledge Graph.Data source: [GeoNames.org](https://download.geonames.org/export/dump/)Author: Peter Rose (pwrose@ucsd.edu)
import os from pathlib import Path import pandas as pd pd.options.display.max_rows = None # display all rows pd.options.display.max_columns = None # display all columsns NEO4J_IMPORT = Path(os.getenv('NEO4J_IMPORT')) print(NEO4J_IMPORT)
/Users/peter/Library/Application Support/Neo4j Desktop/Application/neo4jDatabases/database-19636412-9e74-4bac-8a4c-c6c8b49bb9d3/installation-4.1.0/import
MIT
notebooks/dataprep/00f-GeoNamesAdmin1.ipynb
cjdekker/covid-19-community
Create admin1
admin1_url = 'https://download.geonames.org/export/dump/admin1CodesASCII.txt' names = ['code', 'name', 'name_ascii', 'geonameid'] admin1 = pd.read_csv(admin1_url, sep='\t', dtype='str', names=names) admin1 = admin1[['code', 'name_ascii', 'geonameid']]
_____no_output_____
MIT
notebooks/dataprep/00f-GeoNamesAdmin1.ipynb
cjdekker/covid-19-community
Standardize column names for Knowlege Graph* id: unique identifier for country* name: name of node* parentId: unique identifier for continent* properties: camelCase
admin1.rename(columns={'code': 'id'}, inplace=True) # standard id column to link nodes admin1.rename(columns={'name_ascii': 'name'}, inplace=True) admin1.rename(columns={'geonameid': 'geonameId'}, inplace=True) admin1['code'] = admin1['id'].str.split('.', expand=True)[1] admin1['parentId'] = admin1['id'].str.split('.',...
_____no_output_____
MIT
notebooks/dataprep/00f-GeoNamesAdmin1.ipynb
cjdekker/covid-19-community
Use "District of Columbia" to be consistent with US Census
admin1['name'] = admin1['name'].str.replace('Washington, D.C.', 'District of Columbia')
_____no_output_____
MIT
notebooks/dataprep/00f-GeoNamesAdmin1.ipynb
cjdekker/covid-19-community
Example
admin1.query("id == 'US.DC'") admin1.query("name == 'Missouri'")
_____no_output_____
MIT
notebooks/dataprep/00f-GeoNamesAdmin1.ipynb
cjdekker/covid-19-community
Export a minimum subset for now
admin1 = admin1[['id','name','code','parentId', 'geonameId']] admin1.fillna('', inplace=True) admin1.head() admin1.to_csv(NEO4J_IMPORT / "00f-GeoNamesAdmin1.csv", index=False)
_____no_output_____
MIT
notebooks/dataprep/00f-GeoNamesAdmin1.ipynb
cjdekker/covid-19-community
Set up the dependencies
# for reading and validating data import emeval.input.spec_details as eisd import emeval.input.phone_view as eipv import emeval.input.eval_view as eiev import arrow # Visualization helpers import emeval.viz.phone_view as ezpv import emeval.viz.eval_view as ezev # For plots import matplotlib.pyplot as plt %matplotlib in...
_____no_output_____
BSD-3-Clause
Evaluations_power_boxplots.ipynb
e-mission/e-mission-eval-public-data
The specThe spec defines what experiments were done, and over which time ranges. Once the experiment is complete, most of the structure is read back from the data, but we use the spec to validate that it all worked correctly. The spec also contains the ground truth for the legs. Here, we read the spec for the trip to ...
DATASTORE_LOC = "bin/data/" AUTHOR_EMAIL = "shankari@eecs.berkeley.edu" sd_la = eisd.FileSpecDetails(DATASTORE_LOC, AUTHOR_EMAIL, "unimodal_trip_car_bike_mtv_la") sd_sj = eisd.FileSpecDetails(DATASTORE_LOC, AUTHOR_EMAIL, "car_scooter_brex_san_jose") sd_ucb = eisd.FileSpecDetails(DATASTORE_LOC, AUTHOR_EMAIL, "train_bus_...
_____no_output_____
BSD-3-Clause
Evaluations_power_boxplots.ipynb
e-mission/e-mission-eval-public-data
Loading the data into a dataframe
pv_la = eipv.PhoneView(sd_la) pv_sj = eipv.PhoneView(sd_sj) sd_sj.CURR_SPEC_ID ios_loc_entries = sd_sj.retrieve_data("ucb-sdb-ios-1", ["background/location"], arrow.get("2019-08-07T14:50:57.445000-07:00").timestamp, arrow.get("2019-08-07T15:00:16.787000-07...
_____no_output_____
BSD-3-Clause
Evaluations_power_boxplots.ipynb
e-mission/e-mission-eval-public-data
Displaying various groupings using boxplots
ifig, ax_array = plt.subplots(nrows=2,ncols=3,figsize=(12,6), sharex=False, sharey=True) timeline_list = ["train_bus_ebike_mtv_ucb", "car_scooter_brex_san_jose", "unimodal_trip_car_bike_mtv_la"] for i, tl in enumerate(timeline_list): battery_drain_df.query("timeline == @tl & phone_os == 'android'").boxplot(ax = ax_...
_____no_output_____
BSD-3-Clause
Evaluations_power_boxplots.ipynb
e-mission/e-mission-eval-public-data
Get all tracts within certain citiesGiven a CSV file containing city names, get all the tracts within those cities' boundaries.
import geopandas as gpd import json import os import pandas as pd all_tracts_path = 'data/us_census_tracts_2014' places_path = 'data/us_census_places_2014' states_by_fips_path = 'data/states_by_fips.json' cities_path = 'data/study_sites.csv' output_path = 'data/tracts_in_cities_study_area.geojson' # load the city name...
data/tracts_in_cities_study_area.geojson Wall time: 17 s
MIT
04-select-tracts-by-cities.ipynb
gboeing/representation-listings
By the end of this activity, you will be able to perform the following in Spark:Determine the accuracy of a classifier modelDisplay the confusion matrix for a classifier modelIn this activity, you will be programming in a Jupyter Python Notebook. If you have not already started the Jupyter Notebook server, see the inst...
from pyspark.sql import SQLContext from pyspark.ml.evaluation import MulticlassClassificationEvaluator from pyspark.mllib.evaluation import MulticlassMetrics
_____no_output_____
MIT
model-evaluation.ipynb
rh01/big-data-ml
Execute the next cell to load the predictions CSV file that we created at the end of the Week 3 Hands-On Classification in Spark into a DataFrame:
sqlContext = SQLContext(sc) predictions = sqlContext.read.load('file:///home/cloudera/Downloads/big-data-4/prediction.csv', format='com.databricks.spark.csv', header='true',inferSchema='true')
_____no_output_____
MIT
model-evaluation.ipynb
rh01/big-data-ml
Step 3. Compute accuracy. Let's create an instance of MulticlassClassificationEvaluator to determine the accuracy of the predictions:
evaluator = MulticlassClassificationEvaluator( labelCol="label",predictionCol="prediction",metricName="precision") evaluator
_____no_output_____
MIT
model-evaluation.ipynb
rh01/big-data-ml
The first two arguments specify the names of the label and prediction columns, and the third argument specifies that we want the overall precision.We can compute the accuracy by calling evaluate():
accuracy = evaluator.evaluate(predictions) print ("Accuracy = %.2g" % ( accuracy ))
Accuracy = 0.81
MIT
model-evaluation.ipynb
rh01/big-data-ml
Step 4. Display confusion matrix. The MulticlassMetrics class can be used to generate a confusion matrix of our classifier model. However, unlike MulticlassClassificationEvaluator, MulticlassMetrics works with RDDs of numbers and not DataFrames, so we need to convert our predictions DataFrame into an RDD.If we use the ...
predictions.rdd.take(2)
_____no_output_____
MIT
model-evaluation.ipynb
rh01/big-data-ml
Instead, we can map the RDD to tuple to get an RDD of numbers:
predictions.rdd.map(tuple).take(2)
_____no_output_____
MIT
model-evaluation.ipynb
rh01/big-data-ml