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 |
|---|---|---|---|---|---|
When the optimization is done you should receive a message describing if the method converged or if the maximum number of iterations was reached. In one dimensional examples, you can see the result of the optimization as follows. | myBopt.plot_acquisition()
myBopt.plot_convergence() | _____no_output_____ | BSD-3-Clause | manual/GPyOpt_reference_manual.ipynb | komorihi/GPyOpt |
In problems of any dimension two evaluations plots are available.* The distance between the last two observations.* The value of $f$ at the best location previous to each iteration.To see these plots just run the following cell. | myBopt.plot_convergence() | _____no_output_____ | BSD-3-Clause | manual/GPyOpt_reference_manual.ipynb | komorihi/GPyOpt |
Now let's make a video to track what the algorithm is doing in each iteration. Let's use the LCB in this case with parameter equal to 2. 4. Two dimensional exampleNext, we try a 2-dimensional example. In this case we minimize the use the Six-hump camel function $$f(x_1,x_2) = \left(4-2.1x_1^2 = \frac{x_1^4}{3} \right)... | # create the object function
f_true = GPyOpt.objective_examples.experiments2d.sixhumpcamel()
f_sim = GPyOpt.objective_examples.experiments2d.sixhumpcamel(sd = 0.1)
bounds =[{'name': 'var_1', 'type': 'continuous', 'domain': f_true.bounds[0]},
{'name': 'var_2', 'type': 'continuous', 'domain': f_true.bounds[1]}]
... | _____no_output_____ | BSD-3-Clause | manual/GPyOpt_reference_manual.ipynb | komorihi/GPyOpt |
We create the GPyOpt object. In this case we use the Lower Confidence bound acquisition function to solve the problem. | # Creates three identical objects that we will later use to compare the optimization strategies
myBopt2D = GPyOpt.methods.BayesianOptimization(f_sim.f,
domain=bounds,
model_type = 'GP',
... | _____no_output_____ | BSD-3-Clause | manual/GPyOpt_reference_manual.ipynb | komorihi/GPyOpt |
We run the optimization for 40 iterations and show the evaluation plot and the acquisition function. | # runs the optimization for the three methods
max_iter = 40 # maximum time 40 iterations
max_time = 60 # maximum time 60 seconds
myBopt2D.run_optimization(max_iter,max_time,verbosity=False) | _____no_output_____ | BSD-3-Clause | manual/GPyOpt_reference_manual.ipynb | komorihi/GPyOpt |
Finally, we plot the acquisition function and the convergence plot. | myBopt2D.plot_acquisition()
myBopt2D.plot_convergence() | _____no_output_____ | BSD-3-Clause | manual/GPyOpt_reference_manual.ipynb | komorihi/GPyOpt |
!pip install alpaca_trade_api | Collecting alpaca_trade_api
Downloading alpaca_trade_api-1.5.0-py3-none-any.whl (45 kB)
[?25l
[K |ββββββββ | 10 kB 27.1 MB/s eta 0:00:01
[K |βββββββββββββββ | 20 kB 20.0 MB/s eta 0:00:01
[K |ββββββββββββββββββββββ | 30 kB 10.7 MB/s eta 0:00:01
[K |β... | Apache-2.0 | 1D_CNN_Attempts/1D_CNN_asof_111312FEB.ipynb | Cloblak/aipi540_deeplearning | |
Features To Consider - Targets are only predicting sell within market hours, i.e. at 1530, target is prediciting price for 1100 the next day. Data from pre and post market is taken into consideration, and a sell or buy will be indicated if the price will flucuate after close. | # Import Dependencies
import numpy as np
import pandas as pd
import torch
from torch.utils.data import DataLoader, TensorDataset
from torch.autograd import Variable
from torch.nn import Linear, ReLU, CrossEntropyLoss, Sequential, Conv2d, MaxPool2d, Module, Softmax, BatchNorm2d, Dropout
from torch.optim import Adam, SGD... | X Train Length (4220, 1, 5, 24), y Train Label Length (4220,)
X Val Length (1430, 1, 5, 24), y Val Label Length (1430,)
X Test Length (1025, 1, 5, 24), y Test Label Length (1025,)
| Apache-2.0 | 1D_CNN_Attempts/1D_CNN_asof_111312FEB.ipynb | Cloblak/aipi540_deeplearning |
2D CNN Build Model | trainset = TensorDataset(torch.from_numpy(X_train).float(),
torch.from_numpy(y_train).long())
valset = TensorDataset(torch.from_numpy(X_val).float(),
torch.from_numpy(y_val).long())
testset = TensorDataset(torch.from_numpy(X_test).float(),
torc... | _____no_output_____ | Apache-2.0 | 1D_CNN_Attempts/1D_CNN_asof_111312FEB.ipynb | Cloblak/aipi540_deeplearning |
Spark on Kubernetes Preparing the notebook https://towardsdatascience.com/make-kubeflow-into-your-own-data-science-workspace-cc8162969e29 Setup service account permissions https://github.com/kubeflow/kubeflow/issues/4306 issue with launching spark-operator from jupyter notebook Run command in your shell (not in noteb... | import sys
print(sys.version) | _____no_output_____ | MIT-0 | notebooks/spark-on-eks-cluster-mode.ipynb | aws-samples/eks-kubeflow-spot-sample |
Client Mode | import findspark, pyspark,socket
from pyspark import SparkContext, SparkConf
from pyspark.sql import SparkSession
findspark.init()
localIpAddress = socket.gethostbyname(socket.gethostname())
conf = SparkConf().setAppName('sparktest1')
conf.setMaster('k8s://https://kubernetes.default.svc:443')
conf.set("spark.submit.... | _____no_output_____ | MIT-0 | notebooks/spark-on-eks-cluster-mode.ipynb | aws-samples/eks-kubeflow-spot-sample |
Cluster Mode Java | %%bash
/opt/spark-2.4.6/bin/spark-submit --master "k8s://https://kubernetes.default.svc:443" \
--deploy-mode cluster \
--name spark-java-pi \
--class org.apache.spark.examples.SparkPi \
--conf spark.executor.instances=30 \
--conf spark.kubernetes.namespace=yahavb \
--conf spark.kubernetes.driver.annotation.sidecar.is... | _____no_output_____ | MIT-0 | notebooks/spark-on-eks-cluster-mode.ipynb | aws-samples/eks-kubeflow-spot-sample |
Python | %%bash
/opt/spark-2.4.6/bin/spark-submit --master "k8s://https://kubernetes.default.svc:443" \
--deploy-mode cluster \
--name spark-python-pi \
--conf spark.executor.instances=50 \
--conf spark.kubernetes.container.image=seedjeffwan/spark-py:v2.4.6 \
--conf spark.kubernetes.driver.pod.name=spark-python-pi-driver \
--c... | _____no_output_____ | MIT-0 | notebooks/spark-on-eks-cluster-mode.ipynb | aws-samples/eks-kubeflow-spot-sample |
Designing the maze | arr=np.array([[0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,1,0,0,1,0,0,1,1,1,1,1,0,1,1,0,1,1,1,0],
[0,1,0,0,1,0,0,0,0,0,1,0,0,1,0,0,1,0,0,0],
[0,0,0,0,1,0,0,1,1,1,0,0,1,1,0,0,1,0,0,0],
[0,0,0,0,0,0,0,1,0,0,... | _____no_output_____ | MIT | run.ipynb | burhanusman/RL-Maze |
Defining a Agent [Sarsa Agent because it uses Sarsa to solve the maze] | agent=SarsaAgent(maze) | _____no_output_____ | MIT | run.ipynb | burhanusman/RL-Maze |
Making the agent play episodes and learn | agent.learn(episodes=1000) | _____no_output_____ | MIT | run.ipynb | burhanusman/RL-Maze |
Plotting the maze | nrow=maze.nrow
ncol=maze.ncol
fig=plt.figure()
ax=fig.gca()
ax.set_xticks(np.arange(0.5,ncol,1))
ax.set_yticks(np.arange(0.5,nrow,1))
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.grid('on')
img=ax.imshow(maze.maze,cmap="gray",)
a=5 | _____no_output_____ | MIT | run.ipynb | burhanusman/RL-Maze |
Making Animation of the maze solution | def gen_func():
maze=Maze(arr,rat,cheese)
done=False
while not done:
row,col,_=maze.state
cell=(row,col)
action=agent.get_policy(cell)
maze.step(action)
done=maze.get_status()
yield maze.get_canvas()
def update_plot(canvas):
img.set_data(canvas)
anim=... | _____no_output_____ | MIT | run.ipynb | burhanusman/RL-Maze |
VAE MNIST example: BO in a latent space In this tutorial, we use the MNIST dataset and some standard PyTorch examples to show a synthetic problem where the input to the objective function is a `28 x 28` image. The main idea is to train a [variational auto-encoder (VAE)](https://arxiv.org/abs/1312.6114) on the MNIST da... | import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets # transforms
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
dtype = torch.float | _____no_output_____ | MIT | tutorials/vae_mnist.ipynb | Igevorse/botorch |
Problem setupLet's first define our synthetic expensive-to-evaluate objective function. We assume that it takes the following form:$$\text{image} \longrightarrow \text{image classifier} \longrightarrow \text{scoring function} \longrightarrow \text{score}.$$The classifier is a convolutional neural network (CNN) trained... | class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 20, 5, 1)
self.conv2 = nn.Conv2d(20, 50, 5, 1)
self.fc1 = nn.Linear(4 * 4 * 50, 500)
self.fc2 = nn.Linear(500, 10)
def forward(self, x):
x = F.relu(self.conv1(x))
... | _____no_output_____ | MIT | tutorials/vae_mnist.ipynb | Igevorse/botorch |
We next instantiate the CNN for digit recognition and load a pre-trained model.Here, you may have to change `PRETRAINED_LOCATION` to the location of the `pretrained_models` folder on your machine. | PRETRAINED_LOCATION = "./pretrained_models"
cnn_model = Net().to(device)
cnn_state_dict = torch.load(os.path.join(PRETRAINED_LOCATION, "mnist_cnn.pt"), map_location=device)
cnn_model.load_state_dict(cnn_state_dict); | _____no_output_____ | MIT | tutorials/vae_mnist.ipynb | Igevorse/botorch |
Our VAE model follows the [PyTorch VAE example](https://github.com/pytorch/examples/tree/master/vae), except that we use the same data transform from the CNN tutorial for consistency. We then instantiate the model and again load a pre-trained model. To train these models, we refer readers to the PyTorch Github reposito... | class VAE(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(784, 400)
self.fc21 = nn.Linear(400, 20)
self.fc22 = nn.Linear(400, 20)
self.fc3 = nn.Linear(20, 400)
self.fc4 = nn.Linear(400, 784)
def encode(self, x):
h1 = F.relu(self.fc... | _____no_output_____ | MIT | tutorials/vae_mnist.ipynb | Igevorse/botorch |
We now define the scoring function that maps digits to scores. The function below prefers the digit '3'. | def score(y):
"""Returns a 'score' for each digit from 0 to 9. It is modeled as a squared exponential
centered at the digit '3'.
"""
return torch.exp(-2 * (y - 3)**2) | _____no_output_____ | MIT | tutorials/vae_mnist.ipynb | Igevorse/botorch |
Given the scoring function, we can now write our overall objective, which as discussed above, starts with an image and outputs a score. Let's say the objective computes the expected score given the probabilities from the classifier. | def score_image_recognition(x):
"""The input x is an image and an expected score based on the CNN classifier and
the scoring function is returned.
"""
with torch.no_grad():
probs = torch.exp(cnn_model(x)) # b x 10
scores = score(torch.arange(10, device=device, dtype=dtype)).expand(probs... | _____no_output_____ | MIT | tutorials/vae_mnist.ipynb | Igevorse/botorch |
Finally, we define a helper function `decode` that takes as input the parameters `mu` and `logvar` of the variational distribution and performs reparameterization and the decoding. We use batched Bayesian optimization to search over the parameters `mu` and `logvar` | def decode(train_x):
with torch.no_grad():
decoded = vae_model.decode(train_x)
return decoded.view(train_x.shape[0], 1, 28, 28) | _____no_output_____ | MIT | tutorials/vae_mnist.ipynb | Igevorse/botorch |
Model initialization and initial random batchWe use a `SingleTaskGP` to model the score of an image generated by a latent representation. The model is initialized with points drawn from $[-6, 6]^{20}$. | from botorch.models import SingleTaskGP
from gpytorch.mlls.exact_marginal_log_likelihood import ExactMarginalLogLikelihood
bounds = torch.tensor([[-6.0] * 20, [6.0] * 20], device=device, dtype=dtype)
def initialize_model(n=5):
# generate training data
train_x = (bounds[1] - bounds[0]) * torch.rand(n, 20, ... | _____no_output_____ | MIT | tutorials/vae_mnist.ipynb | Igevorse/botorch |
Define a helper function that performs the essential BO stepThe helper function below takes an acquisition function as an argument, optimizes it, and returns the batch $\{x_1, x_2, \ldots x_q\}$ along with the observed function values. For this example, we'll use a small batch of $q=3$. | from botorch.optim import joint_optimize
BATCH_SIZE = 3
def optimize_acqf_and_get_observation(acq_func):
"""Optimizes the acquisition function, and returns a new candidate and a noisy observation"""
# optimize
candidates = joint_optimize(
acq_function=acq_func,
bounds=bounds,
... | _____no_output_____ | MIT | tutorials/vae_mnist.ipynb | Igevorse/botorch |
Perform Bayesian Optimization loop with qEIThe Bayesian optimization "loop" for a batch size of $q$ simply iterates the following steps: (1) given a surrogate model, choose a batch of points $\{x_1, x_2, \ldots x_q\}$, (2) observe $f(x)$ for each $x$ in the batch, and (3) update the surrogate model. We run `N_BATCH=75... | from botorch import fit_gpytorch_model
from botorch.acquisition.monte_carlo import qExpectedImprovement
from botorch.acquisition.sampler import SobolQMCNormalSampler
seed=1
torch.manual_seed(seed)
N_BATCH = 50
MC_SAMPLES = 2000
best_observed = []
# call helper function to initialize model
train_x, train_obj, mll, mo... | _____no_output_____ | MIT | tutorials/vae_mnist.ipynb | Igevorse/botorch |
We are now ready to run the BO loop (this make take a few minutes, depending on your machine). | import warnings
warnings.filterwarnings("ignore")
print(f"\nRunning BO ", end='')
from matplotlib import pyplot as plt
# run N_BATCH rounds of BayesOpt after the initial random batch
for iteration in range(N_BATCH):
# fit the model
fit_gpytorch_model(mll)
# define the qNEI acquisition module using a... |
Running BO .................................................. | MIT | tutorials/vae_mnist.ipynb | Igevorse/botorch |
EI recommends the best point observed so far. We can visualize what the images corresponding to recommended points *would have* been if the BO process ended at various times. Here, we show the progress of the algorithm by examining the images at 0%, 10%, 25%, 50%, 75%, and 100% completion. The first image is the best i... | import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
fig, ax = plt.subplots(1, 6, figsize=(14, 14))
percentages = np.array([0, 10, 25, 50, 75, 100], dtype=np.float32)
inds = (N_BATCH * BATCH_SIZE * percentages / 100 + 4).astype(int)
for i, ax in enumerate(ax.flat):
b = torch.argmax(score_i... | _____no_output_____ | MIT | tutorials/vae_mnist.ipynb | Igevorse/botorch |
Ensemble LearningSometimes aggregrates or ensembles of many different opinions on a question can perform as well or better than askinga single expert on the same question. This is known as the *wisdom of the crowd* when the aggregrate opinion ofpeople on a question performs as well or better as a single isolated expe... | def flip_unfair_coin(num_flips, head_ratio):
"""Simulate flipping an unbalanced coin. We return a numpy array of size num_flips, with 0 to represent
1 to represent a head and 0 a tail flip. We generate a head or tail result using the head_ratio probability
threshold drawn from a standard uniform distribut... | _____no_output_____ | CC-BY-3.0 | lectures/ng/Lecture-09-Ensembles-Random-Forests.ipynb | tgrasty/CSCI574-Machine-Learning |
Scikit-Learn Voting ClassifierThe following code is an example of creating a voting classifier in Scikit-Learn. We are using the moons datasetshown.Here we create 3 separate classifiers by hand, a logistic regressor, a decision tree,and a support vector classifier (SVC). Notice we specify 'hard' voting for the voti... | # helper functions to visualize decision boundaries for 2-feature classification tasks
# create a scatter plot of the artificial multiclass dataset
from matplotlib import cm
# visualize the blobs using matplotlib. An example of a funciton we can reuse, since later
# we want to plot the decision boundaries along with... | _____no_output_____ | CC-BY-3.0 | lectures/ng/Lecture-09-Ensembles-Random-Forests.ipynb | tgrasty/CSCI574-Machine-Learning |
Lets look at each classifier's accuracy on the test set, including for the ensemble voting classifier: | from sklearn.metrics import accuracy_score
for clf in (log_clf, tree_clf, svm_clf, voting_clf):
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print(clf.__class__.__name__, accuracy_score(y_test, y_pred)) | LogisticRegression 0.8576
DecisionTreeClassifier 0.8768
SVC 0.9056
VotingClassifier 0.904
| CC-BY-3.0 | lectures/ng/Lecture-09-Ensembles-Random-Forests.ipynb | tgrasty/CSCI574-Machine-Learning |
The voting classifier will usually outperform all the individual classifier, if the data is sufficientlynonseparable to make it relatively hard (e.g. with less random noise in the moons data set, you can getreal good performance sometimes with random forest and/or svc, which will exceed the voting classifier).If all cl... | log_clf = LogisticRegression(solver='lbfgs', C=5.0)
tree_clf = DecisionTreeClassifier(max_depth=8)
svm_clf = SVC(gamma=1000.0, C=1.0, probability=True) # enable probability estimates for svm classifier
voting_clf = VotingClassifier(
estimators=[('lr', log_clf), ('tree', tree_clf), ('svc', svm_clf)],
voting='so... | LogisticRegression 0.8576
DecisionTreeClassifier 0.8944
SVC 0.8464
VotingClassifier 0.8976
| CC-BY-3.0 | lectures/ng/Lecture-09-Ensembles-Random-Forests.ipynb | tgrasty/CSCI574-Machine-Learning |
Bagging and PastingOne way to get a diverse set of classifiers is to use very different training algorithms. The previous votingclassifier was an example of this, where we used 3 very different kinds of classifiers for the voting ensemble.Another approach is to use the same training for every predictor, but to train ... | from sklearn.ensemble import BaggingClassifier
from sklearn.tree import DecisionTreeClassifier
bag_clf = BaggingClassifier(
DecisionTreeClassifier(max_leaf_nodes=20), n_estimators=500,
max_samples=100, bootstrap=True, n_jobs=-1
)
bag_clf.fit(X_train, y_train)
y_pred = bag_clf.predict(X_test)
print(bag_clf.__c... | _____no_output_____ | CC-BY-3.0 | lectures/ng/Lecture-09-Ensembles-Random-Forests.ipynb | tgrasty/CSCI574-Machine-Learning |
Out-of-Bag EvaluationWith bagging, some instances may be sampled several times for any given predictor, while others may not besampled at all. By default a `BaggingClassifier` samples `m` training instances with replacement, where `m`is the size of the training set. This means that only about 63% of the training ins... | bag_clf = BaggingClassifier(
DecisionTreeClassifier(), n_estimators=500,
bootstrap=True, n_jobs=-1, oob_score=True
)
bag_clf.fit(X_train, y_train)
print(bag_clf.oob_score_)
y_pred = bag_clf.predict(X_test)
print(accuracy_score(y_test, y_pred)) | 0.9056
0.8976
| CC-BY-3.0 | lectures/ng/Lecture-09-Ensembles-Random-Forests.ipynb | tgrasty/CSCI574-Machine-Learning |
The oob decision function for each training instance is also available through the`oob_decision_function_` variable. | bag_clf.oob_decision_function_ | _____no_output_____ | CC-BY-3.0 | lectures/ng/Lecture-09-Ensembles-Random-Forests.ipynb | tgrasty/CSCI574-Machine-Learning |
Random Patches and Random SubspacesThe default behavior of the bagging/patching classifier is to only sample the training target outputs. However,it can also be useful to build classifiers that only use some of the feautres of the input data. We have lookedat methods for adding features, for example by adding polyno... | from sklearn.ensemble import RandomForestClassifier
rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1)
rnd_clf.fit(X_train, y_train)
y_pred = rnd_clf.predict(X_test)
print(accuracy_score(y_test, y_pred)) | 0.8976
| CC-BY-3.0 | lectures/ng/Lecture-09-Ensembles-Random-Forests.ipynb | tgrasty/CSCI574-Machine-Learning |
A random forest classifier has all of the hyperparameters of a `DecisionTreeClassifier` (to controlhow trees are grown), plus all of the hyperparameters of a `BaggingClassifier` to control the ensemble itself.The random forest algorithm introduces extra randomness when growing trees. Instead of searchingfor the very b... | bag_clf = BaggingClassifier(
DecisionTreeClassifier(splitter='random', max_leaf_nodes=16),
n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1
)
bag_clf.fit(X_train, y_train)
y_pred = bag_clf.predict(X_test)
print(accuracy_score(y_test, y_pred)) | 0.8992
| CC-BY-3.0 | lectures/ng/Lecture-09-Ensembles-Random-Forests.ipynb | tgrasty/CSCI574-Machine-Learning |
Extra-TreesWhen growing a tree in a random forest, at each node only a random subset of features is considered for splitting aswe just discussed. It is possible to make trees even more random by also using random thresholds for eachfeature rather than searching for the best possible thresholds.A forest of such extrem... | from sklearn.datasets import load_iris
iris = load_iris()
rnd_clf = RandomForestClassifier(n_estimators=500, n_jobs=-1)
rnd_clf.fit(iris['data'], iris['target'])
for name, score in zip(iris['feature_names'], rnd_clf.feature_importances_):
print(name, score) | sepal length (cm) 0.0945223465095581
sepal width (cm) 0.022011194440888737
petal length (cm) 0.4251170433221595
petal width (cm) 0.4583494157273937
| CC-BY-3.0 | lectures/ng/Lecture-09-Ensembles-Random-Forests.ipynb | tgrasty/CSCI574-Machine-Learning |
It seems the most importan feature is petal length, followed closely by petal width. Sepal length and especiallysepal width are relatively less important. Boosting*Boosting* (originally called *hypothesis boosting* refers to any ensemble method that can combine several weak learnersinto a strong learner. But unlike ... | import sys
sys.path.append("../../src") # add our class modules to the system PYTHON_PATH
from ml_python_class.custom_funcs import version_information
version_information() | Module Versions
-------------------- ------------------------------------------------------------
matplotlib: ['3.3.0']
numpy: ['1.18.5']
pandas: ['1.0.5']
| CC-BY-3.0 | lectures/ng/Lecture-09-Ensembles-Random-Forests.ipynb | tgrasty/CSCI574-Machine-Learning |
class Student:
def __init__ (self, Name, Student_No, Age, School, Course):
self.Name = Name
self.Student_No = Student_No
self.Age = Age
self.School = School
self.Course = Course
def self (self):
print ("Name: ", self.Name)
print ("Student Number: ", self.Student_No)
print ("Age : "... | Name: Gencianeo Sunvick A.
Student Number: 202117757
Age : 18
School: Adamson University
Course: BS in Computer Engineering
| Apache-2.0 | Gencianeo_Sunvick_A_Prelim1.ipynb | Sunvick/OPP-58001 | |
ProblemFind the smallest difference between two arrays.The function should take in two arrays and find the pair of numbers in the array whose absolute difference is closest to zero. | def smallest_difference(array_one, array_two):
"""
Complexity:
Time: O(nlog(n)) + mlog(m))
where n = length of first array, m = length of second array
(the nlog n comes from sorting using an optimal sorting algorithm)
Space: O(1)
"""
# first, we sort the arrays
ar... | _____no_output_____ | MIT | arrays/smallest_difference.ipynb | codacy-badger/algorithms-1 |
Neuromatch Academy: Week1, Day 2, Tutorial 2 Tutorial objectivesWe are investigating a simple phenomena, working through the 10 steps of modeling ([Blohm et al., 2019](https://doi.org/10.1523/ENEURO.0352-19.2019)) in two notebooks: **Framing the question**1. finding a phenomenon and a question to ask about it2. under... | #@title Utilities and setup
# set up the environment for this tutorial
import time # import time
import numpy as np # import numpy
import scipy as sp # import scipy
from scipy.stats import gamma # import gamma distribution
import math ... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | sanchobarriga/course-content |
Micro-tutorial 6 - planning the model | #@title Video: Planning the model
from IPython.display import YouTubeVideo
video = YouTubeVideo(id='daEtkVporBE', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video | Video available at https://youtube.com/watch?v=daEtkVporBE
| CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | sanchobarriga/course-content |
**Goal:** Identify the key components of the model and how they work together.Our goal all along has been to model our perceptual estimates of sensory data.Now that we have some idea of what we want to do, we need to line up the components of the model: what are the input and output? Which computations are done and in ... | def my_train_illusion_model(sensorydata, params):
'''
Generate output predictions of perceived self-motion and perceived world-motion velocity
based on input visual and vestibular signals.
Args (Input variables passed into function):
sensorydata: (dict) dictionary with two named entries:
... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | sanchobarriga/course-content |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D2_ModelingPractice/solutions/W1D2_Tutorial2_Solution_685e0a13.py) **TD 6.2**: Draft perceived motion functionsNow we draft a set of functions, the first of which is used in the main model function (see above) and serve... | # fill in the input arguments the function should have:
# write the help text for the function:
def my_perceived_motion(arg1, arg2, arg3):
'''
Short description of the function
Args:
argument 1: explain the format and content of the first argument
argument 2: explain the format and content ... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | sanchobarriga/course-content |
We've completed the `my_perceived_motion()` function for you below. Follow this example to complete the template for `my_selfmotion()` and `my_worldmotion()`. Write out the inputs and outputs, and the steps required to calculate the outputs from the inputs.**Perceived motion function** | #Full perceived motion function
def my_perceived_motion(vis, ves, params):
'''
Takes sensory data and parameters and returns predicted percepts
Args:
vis (numpy.ndarray): 1xM array of optic flow velocity data
ves (numpy.ndarray): 1xM array of vestibular acceleration data
params: (... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | sanchobarriga/course-content |
**Template calculate self motion**Put notes in the function below that describe the inputs, the outputs, and steps that transform the output from the input using elements from micro-tutorials 3,4,5. | def my_selfmotion(arg1, arg2):
'''
Short description of the function
Args:
argument 1: explain the format and content of the first argument
argument 2: explain the format and content of the second argument
Returns:
what output does the function generate?
Any further descri... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | sanchobarriga/course-content |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D2_ModelingPractice/solutions/W1D2_Tutorial2_Solution_181325a9.py) **Template calculate world motion**Put notes in the function below that describe the inputs, the outputs, and steps that transform the output from the in... | def my_worldmotion(arg1, arg2, arg3):
'''
Short description of the function
Args:
argument 1: explain the format and content of the first argument
argument 2: explain the format and content of the second argument
argument 3: explain the format and content of the third argument
... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | sanchobarriga/course-content |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D2_ModelingPractice/solutions/W1D2_Tutorial2_Solution_8f913582.py) Micro-tutorial 7 - implement model | #@title Video: implement the model
from IPython.display import YouTubeVideo
video = YouTubeVideo(id='gtSOekY8jkw', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video | Video available at https://youtube.com/watch?v=gtSOekY8jkw
| CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | sanchobarriga/course-content |
**Goal:** We write the components of the model in actual code.For the operations we picked, there function ready to use:* integration: `np.cumsum(data, axis=1)` (axis=1: per trial and over samples)* filtering: `my_moving_window(data, window)` (window: int, default 3)* average: `np.mean(data)`* threshold: if (value > th... | def my_selfmotion(ves, params):
'''
Estimates self motion for one vestibular signal
Args:
ves (numpy.ndarray): 1xM array with a vestibular signal
params (dict): dictionary with named entries:
see my_train_illusion_model() for details
Returns:
(float): an estimate of... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | sanchobarriga/course-content |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D2_ModelingPractice/solutions/W1D2_Tutorial2_Solution_3ea16348.py) Estimate world motionWe have completed the `my_worldmotion()` function for you.**World motion function** | # World motion function
def my_worldmotion(vis, selfmotion, params):
'''
Short description of the function
Args:
vis (numpy.ndarray): 1xM array with the optic flow signal
selfmotion (float): estimate of self motion
params (dict): dictionary with named entries:
see my_tra... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | sanchobarriga/course-content |
Micro-tutorial 8 - completing the model | #@title Video: completing the model
from IPython.display import YouTubeVideo
video = YouTubeVideo(id='-NiHSv4xCDs', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video | Video available at https://youtube.com/watch?v=-NiHSv4xCDs
| CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | sanchobarriga/course-content |
**Goal:** Make sure the model can speak to the hypothesis. Eliminate all the parameters that do not speak to the hypothesis.Now that we have a working model, we can keep improving it, but at some point we need to decide that it is finished. Once we have a model that displays the properties of a system we are interested... | #@title Run to plot model predictions of motion estimates
# prepare to run the model again:
data = {'opticflow':opticflow, 'vestibular':vestibular}
params = {'threshold':0.6, 'filterwindows':[100,50], 'FUN':np.mean}
modelpredictions = my_train_illusion_model(sensorydata=data, params=params)
# process the data to allow... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | sanchobarriga/course-content |
**Questions:*** Why is the data distributed this way? How does it compare to the plot in TD 1.2?* Did you expect to see this?* Where do the model's predicted judgments for each of the two conditions fall?* How does this compare to the behavioral data?However, the main observation should be that **there are illusions**:... | #@title Video: Background
from IPython.display import YouTubeVideo
video = YouTubeVideo(id='5vnDOxN3M_k', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video | Video available at https://youtube.com/watch?v=5vnDOxN3M_k
| CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | sanchobarriga/course-content |
**Goal:** Once we have finished the model, we need a description of how good it is. The question and goals we set in micro-tutorial 1 and 4 help here. There are multiple ways to evaluate a model. Aside from the obvious fact that we want to get insight into the phenomenon that is not directly accessible without the mode... | #@title Run to plot predictions over data
my_plot_predictions_data(judgments, predictions) | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | sanchobarriga/course-content |
When model predictions are correct, the red points in the figure above should lie along the identity line (a dotted black line here). Points off the identity line represent model prediction errors. While in each plot we see two clusters of dots that are fairly close to the identity line, there are also two clusters tha... | #@title Run to calculate R^2
conditions = np.concatenate((np.abs(judgments[:,1]),np.abs(judgments[:,2])))
veljudgmnt = np.concatenate((judgments[:,3],judgments[:,4]))
velpredict = np.concatenate((predictions[:,3],predictions[:,4]))
slope, intercept, r_value, p_value, std_err = sp.stats.linregress(conditions,veljudgmnt... | conditions -> judgments R^2: 0.032
predictions -> judgments R^2: 0.256
| CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | sanchobarriga/course-content |
These $R^2$s express how well the experimental conditions explain the participants judgments and how well the models predicted judgments explain the participants judgments.You will learn much more about model fitting, quantitative model evaluation and model comparison tomorrow!Perhaps the $R^2$ values don't seem very i... | # Testing thresholds
def test_threshold(threshold=0.33):
# prepare to run model
data = {'opticflow':opticflow, 'vestibular':vestibular}
params = {'threshold':threshold, 'filterwindows':[100,50], 'FUN':np.mean}
modelpredictions = my_train_illusion_model(sensorydata=data, params=params)
# get pr... | predictions -> judgments R2: 0.267
| CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | sanchobarriga/course-content |
**TD 9.2:** Credit assigmnent of self motionWhen we look at the figure in **TD 8.1**, we can see a cluster does seem very close to (1,0), just like in the actual data. The cluster of points at (1,0) are from the case where we conclude there is no self motion, and then set the self motion to 0. That value of 0 removes ... | # Template binary self-motion estimates
def my_selfmotion(ves, params):
'''
Estimates self motion for one vestibular signal
Args:
ves (numpy.ndarray): 1xM array with a vestibular signal
params (dict): dictionary with named entries:
see my_train_illusion_model() for details
... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | sanchobarriga/course-content |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D2_ModelingPractice/solutions/W1D2_Tutorial2_Solution_90571e21.py) The function you just wrote will be used when we run the model again below. | #@title Run model credit assigment of self motion
# prepare to run the model again:
data = {'opticflow':opticflow, 'vestibular':vestibular}
params = {'threshold':0.33, 'filterwindows':[100,50], 'FUN':np.mean}
modelpredictions = my_train_illusion_model(sensorydata=data, params=params)
# no process the data to allow plo... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | sanchobarriga/course-content |
That looks much better, and closer to the actual data. Let's see if the $R^2$ values have improved: | #@title Run to calculate R^2 for model with self motion credit assignment
conditions = np.concatenate((np.abs(judgments[:,1]),np.abs(judgments[:,2])))
veljudgmnt = np.concatenate((judgments[:,3],judgments[:,4]))
velpredict = np.concatenate((predictions[:,3],predictions[:,4]))
my_plot_predictions_data(judgments, predic... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | sanchobarriga/course-content |
While the model still predicts velocity judgments better than the conditions (i.e. the model predicts illusions in somewhat similar cases), the $R^2$ values are actually worse than those of the simpler model. What's really going on is that the same set of points that were model prediction errors in the previous model a... | #@title Video: Background
from IPython.display import YouTubeVideo
video = YouTubeVideo(id='kf4aauCr5vA', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video | Video available at https://youtube.com/watch?v=kf4aauCr5vA
| CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | sanchobarriga/course-content |
Fix merge conflicts> Fix merge conflicts in jupyter notebooks When working with jupyter notebooks (which are json files behind the scenes) and GitHub, it is very common that a merge conflict (that will add new lines in the notebook source file) will break some notebooks you are working on. This module defines the func... | #hide
tst_nb="""{
"cells": [
{
"cell_type": "code",
<<<<<<< HEAD
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"3"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"z=... | _____no_output_____ | Apache-2.0 | nbs/05_merge.ipynb | aviadr1/nbdev |
This is an example of broken notebook we defined in `tst_nb`. The json format is broken by the lines automatically added by git. Such a file can't be opened again in jupyter notebook, leaving the user with no other choice than to fix the text file manually. | print(tst_nb) | {
"cells": [
{
"cell_type": "code",
<<<<<<< HEAD
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"3"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"z=3
",
"z"
... | Apache-2.0 | nbs/05_merge.ipynb | aviadr1/nbdev |
Note that in this example, the second conflict is easily solved: it just concerns the execution count of the second cell and can be solved by choosing either option without really impacting your notebook. This is the kind of conflicts `fix_conflicts` will (by default) fix automatically. The first conflict is more compl... | #export
def extract_cells(raw_txt):
"Manually extract cells in potential broken json `raw_txt`"
lines = raw_txt.split('\n')
cells = []
i = 0
while not lines[i].startswith(' "cells"'): i+=1
i += 1
start = '\n'.join(lines[:i])
while lines[i] != ' ],':
while lines[i] != ' {': i+=1
... | _____no_output_____ | Apache-2.0 | nbs/05_merge.ipynb | aviadr1/nbdev |
This function returns the beginning of the text (before the cells are defined), the list of cells and the end of the text (after the cells are defined). | start,cells,end = extract_cells(tst_nb)
test_eq(len(cells), 3)
test_eq(cells[0], """ {
"cell_type": "code",
<<<<<<< HEAD
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"3"
]
},
"execution_count": 6,
"metadata": {},
"output_type... | _____no_output_____ | Apache-2.0 | nbs/05_merge.ipynb | aviadr1/nbdev |
When walking the broken cells, we will add conflicts marker before and after the cells with conflicts as markdown cells. To do that we use this function. | #export
def get_md_cell(txt):
"A markdown cell with `txt`"
return ''' {
"cell_type": "markdown",
"metadata": {},
"source": [
"''' + txt + '''"
]
},'''
tst = ''' {
"cell_type": "markdown",
"metadata": {},
"source": [
"A bit of markdown"
]
},'''
assert get_md_cell("A bit of m... | _____no_output_____ | Apache-2.0 | nbs/05_merge.ipynb | aviadr1/nbdev |
This is the main function used to walk through the cells of a notebook. `cell` is the cell we're at, `cf` the conflict state: `0` if we're not in any conflict, `1` if we are inside the first part of a conflict (between `<<<<<<<` and `=======`) and `2` for the second part of a conflict. `names` contains the names of the... | tst = '\n'.join(['a', f'{conflicts[0]} HEAD', 'b', conflicts[1], 'c'])
c,cf,names,prev,added = analyze_cell(tst, 0, [None,None], None, False,fast=False)
test_eq(c, get_md_cell('`<<<<<<< HEAD`')+'\na\nb')
test_eq(cf, 2)
test_eq(names, ['HEAD', None])
test_eq(prev, ['a\nc'])
test_eq(added, True) | _____no_output_____ | Apache-2.0 | nbs/05_merge.ipynb | aviadr1/nbdev |
Here in this example, we were entering cell `tst` with no conflict state. At the end of the cells, we are still in the second part of the conflict, hence `cf=2`. The result returns a marker for the branch head, then the whole cell in version 1 (a + b). We save a (prior to the conflict hence common to the two versions) ... | #export
def fix_conflicts(fname, fast=True, trust_us=True):
"Fix broken notebook in `fname`"
fname=Path(fname)
shutil.copy(fname, fname.with_suffix('.ipynb.bak'))
with open(fname, 'r') as f: raw_text = f.read()
start,cells,end = extract_cells(raw_text)
res = [start]
cf,names,prev,added = 0,[... | _____no_output_____ | Apache-2.0 | nbs/05_merge.ipynb | aviadr1/nbdev |
The function will begin by backing the notebook `fname` to `fname.bak` in case something goes wrong. Then it parses the broken json, solving conflicts in cells. If `fast=True`, every conflict that only involves metadata or outputs of cells will be solved automatically by using the local (`trust_us=True`) or the remote ... | #hide
from nbdev.export import notebook2script
notebook2script() | Converted 00_export.ipynb.
Converted 01_sync.ipynb.
Converted 02_showdoc.ipynb.
Converted 03_export2html.ipynb.
Converted 04_test.ipynb.
Converted 05_merge.ipynb.
Converted 06_cli.ipynb.
Converted 07_clean.ipynb.
Converted 08_flag_tests.ipynb.
Converted 99_search.ipynb.
Converted index.ipynb.
Converted tutorial.ipynb.
| Apache-2.0 | nbs/05_merge.ipynb | aviadr1/nbdev |
Π‘ΠΊΠ°ΡΠΈΠ²Π°Π΅ΠΌ Π΄Π°Π½Π½ΡΠ΅, ΠΏΡΠ΅ΠΎΠ±ΡΠ°Π·ΡΠ΅ΠΌ ΠΈΡ
Π² ΠΎΠ΄Π½Ρ ΡΠ°Π±Π»ΠΈΡΡ | import numpy as np
import pandas as pd
import json
from datetime import datetime
from datetime import date
from math import sqrt
from zipfile import ZipFile
from os import listdir
from os.path import isfile, join
filesDir = "/content/drive/MyDrive/training_data"
csvFiles = [join(filesDir, f) for f in listdir(filesDir... | _____no_output_____ | Apache-2.0 | Processing.ipynb | Ivan-Nebogatikov/HumanActivityRecognitionOutliersDetection |
data['time_diff'] = data['attr_time'].diff()
indMin = int(data[['time_diff']].idxmin())
print(indMin)
t_j = data.iloc[indMin]['attr_time']
print(t_j)
t_j1 = data.iloc[indMin+1]['attr_time']
diff = t_j1 - t_j
print(diff)
# interpolated = []
data['attr_x_i'] = data.apply(lambda row: (t_j1 - row['attr_time']) * row['a... | 0 [nan, nan, nan]
1 [nan, nan, nan]
2 [nan, nan, nan]
3 [nan, nan, nan]
4 [0.5486020271807942, 9.603077026582291, 1.2872...
... | Apache-2.0 | Processing.ipynb | Ivan-Nebogatikov/HumanActivityRecognitionOutliersDetection | |
ΠΡΠΏΠΎΠΌΠΎΠ³Π°ΡΠ΅Π»ΡΠ½Π°Ρ ΡΡΠ½ΠΊΡΠΈΡ Π΄Π»Ρ Π²ΡΠ²ΠΎΠ΄Π° ΡΠ΅Π·ΡΠ»ΡΡΠ°ΡΠΎΠ² | import pandas as pd
import numpy as np
from scipy import interp
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_recall_fscore_support
from sklearn.metrics import roc_curve, auc
from sklearn.preprocessing import LabelBinarizer
def class_report(y_true, y_pred, y_score=None, average='mic... | _____no_output_____ | Apache-2.0 | Processing.ipynb | Ivan-Nebogatikov/HumanActivityRecognitionOutliersDetection |
ΠΠΏΡΠ΅Π΄Π΅Π»ΡΠ΅ΠΌ ΡΡΠ½ΠΊΡΠΈΠΈ Π΄Π»Ρ ΠΏΡΠ΅Π΄ΡΠΊΠ°Π·Π°Π½ΠΈΡ Ρ ΠΈΡΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°Π½ΠΈΠ΅ΠΌ ΠΊΠ»Π°ΡΡΠΈΡΠΈΠΊΠ°ΡΠΎΡΠ° ΠΈ Ρ ΠΈΡΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°Π½ΠΈΠ΅ΠΌ Π½Π΅ΡΠΊΠΎΠ»ΡΠΊΠΈΡ
ΠΊΠ»Π°ΡΡΠΈΡΠΈΠΊΠ°ΡΠΎΡΠΎΠ² | from sklearn.metrics import accuracy_score
from sklearn.metrics import classification_report
from sklearn.metrics import roc_auc_score
from sklearn import metrics
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
f... | _____no_output_____ | Apache-2.0 | Processing.ipynb | Ivan-Nebogatikov/HumanActivityRecognitionOutliersDetection |
ΠΠΏΡΠ΅Π΄Π΅Π»ΡΠ΅ΠΌ Π½Π°Π±ΠΎΡ ΠΈΡΠΏΠΎΠ»ΡΠ·ΡΠ΅ΠΌΡΡ
ΠΊΠ»Π°ΡΡΠΈΡΠΈΠΊΠ°ΡΠΎΡΠΎΠ² | from sklearn import svm
from sklearn.naive_bayes import GaussianNB
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
from sklearn.ensemble import AdaBoostClassifier
methods = {
"MLP" : MLPClassifier(random_state=1, max_iter=300),
"K-neigh" : KNeighb... | x y z
0 0.000000 0.000000 0.000000
1 0.000000 0.000000 0.000000
2 0.000000 0.000000 0.000000
3 0.000000 0.000000 0.000000
4 0.548602 9.603077 1.287286
... ... ... ...
221608 -3.162401 8.992967 1.387654
221609 -3.108340 8.9246... | Apache-2.0 | Processing.ipynb | Ivan-Nebogatikov/HumanActivityRecognitionOutliersDetection |
SF Salaries Exercise - SolutionsWelcome to a quick exercise for you to practice your pandas skills! We will be using the [SF Salaries Dataset](https://www.kaggle.com/kaggle/sf-salaries) from Kaggle! Just follow along and complete the tasks outlined in bold below. The tasks will get harder and harder as you go along. *... | import pandas as pd | _____no_output_____ | MIT | Python/data_science/data_analysis/04-Pandas-Exercises/02-SF Salaries Exercise - Solutions.ipynb | Kenneth-Macharia/Learning |
** Read Salaries.csv as a dataframe called sal.** | sal = pd.read_csv('Salaries.csv') | _____no_output_____ | MIT | Python/data_science/data_analysis/04-Pandas-Exercises/02-SF Salaries Exercise - Solutions.ipynb | Kenneth-Macharia/Learning |
** Check the head of the DataFrame. ** | sal.head() | _____no_output_____ | MIT | Python/data_science/data_analysis/04-Pandas-Exercises/02-SF Salaries Exercise - Solutions.ipynb | Kenneth-Macharia/Learning |
** Use the .info() method to find out how many entries there are.** | sal.info() # 148654 Entries | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 148654 entries, 0 to 148653
Data columns (total 13 columns):
Id 148654 non-null int64
EmployeeName 148654 non-null object
JobTitle 148654 non-null object
BasePay 148045 non-null float64
OvertimePay 148650 non-null f... | MIT | Python/data_science/data_analysis/04-Pandas-Exercises/02-SF Salaries Exercise - Solutions.ipynb | Kenneth-Macharia/Learning |
**What is the average BasePay ?** | sal['BasePay'].mean() | _____no_output_____ | MIT | Python/data_science/data_analysis/04-Pandas-Exercises/02-SF Salaries Exercise - Solutions.ipynb | Kenneth-Macharia/Learning |
** What is the highest amount of OvertimePay in the dataset ? ** | sal['OvertimePay'].max() | _____no_output_____ | MIT | Python/data_science/data_analysis/04-Pandas-Exercises/02-SF Salaries Exercise - Solutions.ipynb | Kenneth-Macharia/Learning |
** What is the job title of JOSEPH DRISCOLL ? Note: Use all caps, otherwise you may get an answer that doesn't match up (there is also a lowercase Joseph Driscoll). ** | sal[sal['EmployeeName']=='JOSEPH DRISCOLL']['JobTitle'] | _____no_output_____ | MIT | Python/data_science/data_analysis/04-Pandas-Exercises/02-SF Salaries Exercise - Solutions.ipynb | Kenneth-Macharia/Learning |
** How much does JOSEPH DRISCOLL make (including benefits)? ** | sal[sal['EmployeeName']=='JOSEPH DRISCOLL']['TotalPayBenefits'] | _____no_output_____ | MIT | Python/data_science/data_analysis/04-Pandas-Exercises/02-SF Salaries Exercise - Solutions.ipynb | Kenneth-Macharia/Learning |
** What is the name of highest paid person (including benefits)?** | sal[sal['TotalPayBenefits']== sal['TotalPayBenefits'].max()] #['EmployeeName']
# or
# sal.loc[sal['TotalPayBenefits'].idxmax()] | _____no_output_____ | MIT | Python/data_science/data_analysis/04-Pandas-Exercises/02-SF Salaries Exercise - Solutions.ipynb | Kenneth-Macharia/Learning |
** What is the name of lowest paid person (including benefits)? Do you notice something strange about how much he or she is paid?** | sal[sal['TotalPayBenefits']== sal['TotalPayBenefits'].min()] #['EmployeeName']
# or
# sal.loc[sal['TotalPayBenefits'].idxmax()]['EmployeeName']
## ITS NEGATIVE!! VERY STRANGE
sal.groupby('Year')['BasePay'].mean() | _____no_output_____ | MIT | Python/data_science/data_analysis/04-Pandas-Exercises/02-SF Salaries Exercise - Solutions.ipynb | Kenneth-Macharia/Learning |
** What was the average (mean) BasePay of all employees per year? (2011-2014) ? ** | sal.groupby('Year').mean()['BasePay'] | _____no_output_____ | MIT | Python/data_science/data_analysis/04-Pandas-Exercises/02-SF Salaries Exercise - Solutions.ipynb | Kenneth-Macharia/Learning |
** How many unique job titles are there? ** | sal['JobTitle'].nunique()
sal.head(0) # Get the col headers only
sal['JobTitle'].value_counts().head() | _____no_output_____ | MIT | Python/data_science/data_analysis/04-Pandas-Exercises/02-SF Salaries Exercise - Solutions.ipynb | Kenneth-Macharia/Learning |
** What are the top 5 most common jobs? ** | sal['JobTitle'].value_counts().head(5)
# sum(sal[sal['Year']==2013]['JobTitle'].value_counts() == 1)
# sal[sal['Year']==2013sal['Year']==2013
yr_cond = sal['Year']==2013 # Return a series of all rows in sal and whether they have 2013 in their 'Year' column
yr_filtered_sal = sal[yr_cond] # Return sal filtered to only ... | _____no_output_____ | MIT | Python/data_science/data_analysis/04-Pandas-Exercises/02-SF Salaries Exercise - Solutions.ipynb | Kenneth-Macharia/Learning |
** How many Job Titles were represented by only one person in 2013? (e.g. Job Titles with only one occurence in 2013?) ** | sum(sal[sal['Year']==2013]['JobTitle'].value_counts() == 1) # pretty tricky way to do this...
sal
def chief_check(title):
if 'chief' in title.lower():
return True
else:
return False
sum(sal['JobTitle'].apply(lambda title: chief_check(title))) | _____no_output_____ | MIT | Python/data_science/data_analysis/04-Pandas-Exercises/02-SF Salaries Exercise - Solutions.ipynb | Kenneth-Macharia/Learning |
** How many people have the word Chief in their job title? (This is pretty tricky) ** | def chief_string(title):
if 'chief' in title.lower():
return True
else:
return False
sal['Title_len'] = sal['JobTitle'].apply(len)
sal[['Title_len','TotalPayBenefits']].corr()
sum(sal['JobTitle'].apply(lambda x: chief_string(x))) | _____no_output_____ | MIT | Python/data_science/data_analysis/04-Pandas-Exercises/02-SF Salaries Exercise - Solutions.ipynb | Kenneth-Macharia/Learning |
** Bonus: Is there a correlation between length of the Job Title string and Salary? ** | sal['title_len'] = sal['JobTitle'].apply(len)
sal[['title_len','TotalPayBenefits']].corr() # No correlation. | _____no_output_____ | MIT | Python/data_science/data_analysis/04-Pandas-Exercises/02-SF Salaries Exercise - Solutions.ipynb | Kenneth-Macharia/Learning |
Sequence Reconstruction [PASSED]Check whether the original sequence org can be uniquely reconstructed from the sequences in seqs. The org sequence is a permutation of the integers from 1 to n, with 1 β€ n β€ 104. Reconstruction means building a shortest common supersequence of the sequences in seqs (i.e., a shortest seq... | def is_unique_first(x: int, seqs: list):
return len([s for s in seqs if x in s[1:]]) == 0
def reconstruct(orgs: list, seqs: list) -> bool:
res = []
while seqs:
first: set = set([lst[0] for lst in seqs if is_unique_first(lst[0], seqs)])
if not first or len(first) > 2:
return Fal... | _____no_output_____ | MIT | python-data-structures/interviews/goog-2021-02-03.ipynb | dimastatz/courses |
$\newcommand{\xv}{\mathbf{x}} \newcommand{\wv}{\mathbf{w}} \newcommand{\yv}{\mathbf{y}} \newcommand{\zv}{\mathbf{z}} \newcommand{\uv}{\mathbf{u}} \newcommand{\vv}{\mathbf{v}} \newcommand{\Chi}{\mathcal{X}} \newcommand{\R}{\rm I\!R} \newcommand{\sign}{\text{sign}} \newcommand{\Tm}{\mathbf{T}} \newcommand{\Xm}{\mathbf{X}... | import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from copy import deepcopy as copy
x = np.arange(3)
t = copy(x)
def plot_data():
plt.plot(x, t, "o", markersize=10)
plot_data() | _____no_output_____ | MIT | reading_assignments/5_Note-ML Methodology.ipynb | biqar/Fall-2020-ITCS-8156-MachineLearning |
I know that it is silly to apply a linear regression on this obvious model, but let us try. :) | ## Least Square solution: Filled codes here to fit and plot as the instructor's output
import numpy as np
# First creast X1 by adding 1's column to X
N = x.shape[0]
X1 = np.c_[np.ones((N, 1)), x]
# Next, using inverse, solve, lstsq function to get w*
w = np.linalg.inv(X1.transpose().dot(X1)).dot(X1.transpose()).dot(... | _____no_output_____ | MIT | reading_assignments/5_Note-ML Methodology.ipynb | biqar/Fall-2020-ITCS-8156-MachineLearning |
Can we try a nonlinear model on this data? Why not? We can make a nonlinear model by simply adding higher degree terms such square, cubic, quartic, and so on. $$ f(\xv; \wv) = w_0 + w_1 \xv + w_2 \xv^2 + w_3 \xv^3 + \cdots $$This is called *polynomial regression* as we transform the input features to nonlinear by exten... | # Polinomial regression
def poly_regress(x, d=3, t=None, **params):
bnorm = params.pop('normalize', False)
X_poly = []
#######################################################################################
# Transform input features: append polynomial terms (from bias when i=0) to degree d
for... | _____no_output_____ | MIT | reading_assignments/5_Note-ML Methodology.ipynb | biqar/Fall-2020-ITCS-8156-MachineLearning |
The poly_regress() function trains with the data when target input is given after transform the input x as the following example. The function also returns the transformed input X_poly. | Xp, wp = poly_regress(x, 3, t)
print(wp.shape)
print(Xp.shape)
yp = Xp @ wp
plot_data()
plt.plot(x, y)
plt.plot(x, yp) | (4,)
(3, 4)
| MIT | reading_assignments/5_Note-ML Methodology.ipynb | biqar/Fall-2020-ITCS-8156-MachineLearning |
Hmm... They both look good on this. Then, what is the difference? Let us take a look at how they change if I add the test data. If I compare the MSE, they are equivalent. Try to expand the data for test and see how different they are. Here, we use another usage of poly_regress() function without passing target, so we t... | xtest = np.arange(11)-5
Xptest = poly_regress(xtest, 3)
yptest = Xptest @ wp
X1test = np.vstack((np.ones(len(xtest)), xtest)).T
ytest = X1test @ w
plot_data()
plt.plot(xtest, ytest)
plt.plot(xtest, yptest)
| _____no_output_____ | MIT | reading_assignments/5_Note-ML Methodology.ipynb | biqar/Fall-2020-ITCS-8156-MachineLearning |
Here the orange is th linear model and the green line is 3rd degree polynomial regression. Which model looks better? What is your pick? Learning CurveFrom the above example, we realized that the model evaluation we discussed so far is not enough. First, let us consider how well a learned model generalizes to new data... | import os
import pandas as pd
import sklearn
def prepare_country_stats(oecd_bli, gdp_per_capita):
oecd_bli = oecd_bli[oecd_bli["INEQUALITY"]=="TOT"]
oecd_bli = oecd_bli.pivot(index="Country", columns="Indicator", values="Value")
gdp_per_capita.rename(columns={"2015": "GDP per capita"}, inplace=True)
gd... | _____no_output_____ | MIT | reading_assignments/5_Note-ML Methodology.ipynb | biqar/Fall-2020-ITCS-8156-MachineLearning |
This looks like the data showing a linear trend. Now, let us extend the x-axis to further to 110K and see how it looks. | # Visualize the full data
# Visualize the data
full_country_stats.plot(kind='scatter', x="GDP per capita", y='Life satisfaction', figsize=(12,4))
plt.axis([0, 110000, 0, 10])
plt.show() | _____no_output_____ | MIT | reading_assignments/5_Note-ML Methodology.ipynb | biqar/Fall-2020-ITCS-8156-MachineLearning |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.