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 |
|---|---|---|---|---|---|
**Note**: Computing the optimal number of topics for LDA will take a pretty long amount of timeThe time complexity of this process : **O( m * x * p)**where:* m = no. of tokens in the corpus* x = summation of no. of topics given in the range* p = no. of passes for LDA model | lda_model.compute_optimal_topics(processed_data,2,4,1,path)
lda = lda_model.Optimal_lda_model('./results/lda_tuning_results1.csv')
lda.print_topics() | _____no_output_____ | MIT | LDA_New.ipynb | parikshitsaikia1619/LDA_modeing_IQVIA |
Step 6: Visualization | import pyLDAvis
import pyLDAvis.gensim_models as gensimvis
pyLDAvis.enable_notebook()
vis = gensimvis.prepare(lda, new_corpus, id_word)
vis | _____no_output_____ | MIT | LDA_New.ipynb | parikshitsaikia1619/LDA_modeing_IQVIA |
Monte Carlo MethodsIn this notebook, you will write your own implementations of many Monte Carlo (MC) algorithms. While we have provided some starter code, you are welcome to erase these hints and write your code from scratch. Part 0: Explore BlackjackEnvWe begin by importing the necessary packages. | import sys
import gym
import numpy as np
from collections import defaultdict
from plot_utils import plot_blackjack_values, plot_policy | _____no_output_____ | MIT | monte-carlo/Monte_Carlo.ipynb | romOlivo/NanodegreeExercises |
Use the code cell below to create an instance of the [Blackjack](https://github.com/openai/gym/blob/master/gym/envs/toy_text/blackjack.py) environment. | env = gym.make('Blackjack-v0') | _____no_output_____ | MIT | monte-carlo/Monte_Carlo.ipynb | romOlivo/NanodegreeExercises |
Each state is a 3-tuple of:- the player's current sum $\in \{0, 1, \ldots, 31\}$,- the dealer's face up card $\in \{1, \ldots, 10\}$, and- whether or not the player has a usable ace (`no` $=0$, `yes` $=1$).The agent has two potential actions:``` STICK = 0 HIT = 1```Verify this by running the code cell below. | print(env.observation_space)
print(env.action_space) | Tuple(Discrete(32), Discrete(11), Discrete(2))
Discrete(2)
| MIT | monte-carlo/Monte_Carlo.ipynb | romOlivo/NanodegreeExercises |
Execute the code cell below to play Blackjack with a random policy. (_The code currently plays Blackjack three times - feel free to change this number, or to run the cell multiple times. The cell is designed for you to get some experience with the output that is returned as the agent interacts with the environment._) | for i_episode in range(10):
state = env.reset()
while True:
print(state)
action = env.action_space.sample()
state, reward, done, info = env.step(action)
if done:
print('End game! Reward: ', reward)
print('You won :)\n') if reward > 0 else print('You lost :... | (12, 10, False)
End game! Reward: -1.0
You lost :(
(15, 9, False)
(20, 9, False)
End game! Reward: 1.0
You won :)
(20, 5, False)
End game! Reward: -1
You lost :(
(8, 4, False)
(19, 4, True)
(14, 4, False)
End game! Reward: 1.0
You won :)
(19, 9, False)
(20, 9, False)
End game! Reward: 1.0
You won :)
(14, 6, F... | MIT | monte-carlo/Monte_Carlo.ipynb | romOlivo/NanodegreeExercises |
Part 1: MC PredictionIn this section, you will write your own implementation of MC prediction (for estimating the action-value function). We will begin by investigating a policy where the player _almost_ always sticks if the sum of her cards exceeds 18. In particular, she selects action `STICK` with 80% probability ... | def generate_episode_from_limit_stochastic(bj_env):
episode = []
state = bj_env.reset()
while True:
probs = [0.8, 0.2] if state[0] > 18 else [0.2, 0.8]
action = np.random.choice(np.arange(2), p=probs)
next_state, reward, done, info = bj_env.step(action)
episode.append((state,... | _____no_output_____ | MIT | monte-carlo/Monte_Carlo.ipynb | romOlivo/NanodegreeExercises |
Execute the code cell below to play Blackjack with the policy. (*The code currently plays Blackjack three times - feel free to change this number, or to run the cell multiple times. The cell is designed for you to gain some familiarity with the output of the `generate_episode_from_limit_stochastic` function.*) | for i in range(10):
print(generate_episode_from_limit_stochastic(env)) | [((15, 3, False), 1, -1)]
[((13, 9, False), 1, -1)]
[((15, 9, False), 1, 0), ((18, 9, False), 1, -1)]
[((18, 5, True), 1, 0), ((12, 5, False), 1, 0), ((21, 5, False), 0, 1.0)]
[((21, 3, True), 0, 1.0)]
[((11, 4, False), 1, 0), ((18, 4, False), 1, 0), ((21, 4, False), 0, 1.0)]
[((9, 3, False), 1, 0), ((12, 3, False), 0,... | MIT | monte-carlo/Monte_Carlo.ipynb | romOlivo/NanodegreeExercises |
Now, you are ready to write your own implementation of MC prediction. Feel free to implement either first-visit or every-visit MC prediction; in the case of the Blackjack environment, the techniques are equivalent.Your algorithm has three arguments:- `env`: This is an instance of an OpenAI Gym environment.- `num_episo... | def mc_prediction_q(env, num_episodes, generate_episode, gamma=1.0):
# initialize empty dictionaries of arrays
returns_sum = defaultdict(lambda: np.zeros(env.action_space.n))
N = defaultdict(lambda: np.zeros(env.action_space.n))
Q = defaultdict(lambda: np.zeros(env.action_space.n))
# loop over episo... | _____no_output_____ | MIT | monte-carlo/Monte_Carlo.ipynb | romOlivo/NanodegreeExercises |
Use the cell below to obtain the action-value function estimate $Q$. We have also plotted the corresponding state-value function.To check the accuracy of your implementation, compare the plot below to the corresponding plot in the solutions notebook **Monte_Carlo_Solution.ipynb**. | # obtain the action-value function
Q = mc_prediction_q(env, 500000, generate_episode_from_limit_stochastic)
# obtain the corresponding state-value function
V_to_plot = dict((k,(k[0]>18)*(np.dot([0.8, 0.2],v)) + (k[0]<=18)*(np.dot([0.2, 0.8],v))) \
for k, v in Q.items())
# plot the state-value function
plot_b... | Episode 500000/500000. | MIT | monte-carlo/Monte_Carlo.ipynb | romOlivo/NanodegreeExercises |
Part 2: MC ControlIn this section, you will write your own implementation of constant-$\alpha$ MC control. Your algorithm has four arguments:- `env`: This is an instance of an OpenAI Gym environment.- `num_episodes`: This is the number of episodes that are generated through agent-environment interaction.- `alpha`: Th... | def generate_policy(q_table):
policy = {}
for state in q_table.keys():
policy[state] = np.argmax(q_table[state])
return policy
def take_action(state, policy, epsilon):
probs = [0.8, 0.2] if state[0] > 18 else [0.2, 0.8]
action = np.random.choice(np.arange(2), p=probs)
if (state in policy... | _____no_output_____ | MIT | monte-carlo/Monte_Carlo.ipynb | romOlivo/NanodegreeExercises |
Use the cell below to obtain the estimated optimal policy and action-value function. Note that you should fill in your own values for the `num_episodes` and `alpha` parameters. | # obtain the estimated optimal policy and action-value function
policy, Q = mc_control(env, 1000000, 0.01) | Episode 1000000/1000000. | MIT | monte-carlo/Monte_Carlo.ipynb | romOlivo/NanodegreeExercises |
Next, we plot the corresponding state-value function. | # obtain the corresponding state-value function
V = dict((k,np.max(v)) for k, v in Q.items())
# plot the state-value function
plot_blackjack_values(V) | _____no_output_____ | MIT | monte-carlo/Monte_Carlo.ipynb | romOlivo/NanodegreeExercises |
Finally, we visualize the policy that is estimated to be optimal. | # plot the policy
plot_policy(policy) | _____no_output_____ | MIT | monte-carlo/Monte_Carlo.ipynb | romOlivo/NanodegreeExercises |
IntroductionIn this notebook, we implement [YOLOv4](https://arxiv.org/pdf/2004.10934.pdf) for training on your own dataset.We also recommend reading our blog post on [Training YOLOv4 on custom data](https://blog.roboflow.ai/training-yolov4-on-a-custom-dataset/) side by side.We will take the following steps to impleme... | # CUDA: Let's check that Nvidia CUDA drivers are already pre-installed and which version is it.
!/usr/local/cuda/bin/nvcc --version
# We need to install the correct cuDNN according to this output
!nvidia-smi
# Change the number depending on what GPU is listed above, under NVIDIA-SMI > Name.
# Tesla K80: 30
# Tesla P100... | env: compute_capability=75
| MIT | YOLOv4_Darknet_Roboflow1.ipynb | qwerlarlgus/Darknet |
STEP 1. Install cuDNN according to the current CUDA versionColab added cuDNN as an inherent install - so you don't have to do a thing - major win Step 2: Installing Darknet for YOLOv4 on Colab | %cd /content/
%rm -rf darknet
#we clone the fork of darknet maintained by roboflow
#small changes have been made to configure darknet for training
!git clone https://github.com/roboflow-ai/darknet.git
%cd /content/darknet/
%rm Makefile
#colab occasionally shifts dependencies around, at the time of authorship, this Make... | CUDNN_VERSION=7.6.5.32
__EGL_VENDOR_LIBRARY_DIRS=/usr/lib64-nvidia:/usr/share/glvnd/egl_vendor.d/
LD_LIBRARY_PATH=/usr/lib64-nvidia
CLOUDSDK_PYTHON=python3
LANG=en_US.UTF-8
HOSTNAME=d41f1c72eaaf
OLDPWD=/
CLOUDSDK_CONFIG=/content/.config
NVIDIA_VISIBLE_DEVICES=all
DATALAB_SETTINGS_OVERRIDES={"kernelManagerProxyPort":600... | MIT | YOLOv4_Darknet_Roboflow1.ipynb | qwerlarlgus/Darknet |
Set up Custom Dataset for YOLOv4 We'll use Roboflow to convert our dataset from any format to the YOLO Darknet format. 1. To do so, create a free [Roboflow account](https://app.roboflow.ai).2. Upload your images and their annotations (in any format: VOC XML, COCO JSON, TensorFlow CSV, etc).3. Apply preprocessing and a... |
from google.colab import drive
drive.mount('/content/drive')
#if you already have YOLO darknet format, you can skip this step
%cd /content/darknet
#!curl -L [YOUR LINK HERE] > roboflow.zip; unzip roboflow.zip; rm roboflow.zip
!cp /content/drive/MyDrive/Aquarium-darknet.zip .
!pwd
!unzip ./Aquarium-darknet.zip
#Set up... | /content/darknet
| MIT | YOLOv4_Darknet_Roboflow1.ipynb | qwerlarlgus/Darknet |
Write Custom Training Config for YOLOv4 | #we build config dynamically based on number of classes
#we build iteratively from base config files. This is the same file shape as cfg/yolo-obj.cfg
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
num_classes = file_len('train/_darknet.labels')
print("writing conf... | [net]
batch=64
subdivisions=24
width=416
height=416
channels=3
momentum=0.949
decay=0.0005
angle=0
saturation = 1.5
exposure = 1.5
hue = .1
learning_rate=0.001
burn_in=1000
max_batches=14000
policy=steps
steps=11200.0,12600.0
scales=.1,.1
#cutmix=1
mosaic=1
#:104x104 54:52x52 85:26x26 104:13x13 for 416
[convolution... | MIT | YOLOv4_Darknet_Roboflow1.ipynb | qwerlarlgus/Darknet |
Train Custom YOLOv4 Detector | !./darknet detector train data/obj.data cfg/custom-yolov4-detector.cfg yolov4.conv.137 -dont_show -map
#If you get CUDA out of memory adjust subdivisions above!
#adjust max batches down for shorter training above |
(next mAP calculation at 2568 iterations)
Last accuracy mAP@0.5 = 59.40 %, best = 59.40 %
2461: 10.640112, 8.513406 avg loss, 0.001000 rate, 8.034781 seconds, 118128 images, 16.766305 hours left
Loaded: 0.000033 seconds
^C
| MIT | YOLOv4_Darknet_Roboflow1.ipynb | qwerlarlgus/Darknet |
Infer Custom Objects with Saved YOLOv4 Weights | #define utility function
def imShow(path):
import cv2
import matplotlib.pyplot as plt
%matplotlib inline
image = cv2.imread(path)
height, width = image.shape[:2]
resized_image = cv2.resize(image,(3*width, 3*height), interpolation = cv2.INTER_CUBIC)
fig = plt.gcf()
fig.set_size_inches(18, 10)
plt.axi... | _____no_output_____ | MIT | YOLOv4_Darknet_Roboflow1.ipynb | qwerlarlgus/Darknet |
Programming Exercise 2: Logistic Regression IntroductionIn this exercise, you will implement logistic regression and apply it to two different datasets. Before starting on the programming exercise, we strongly recommend watching the video lectures and completing the review questions for the associated topics.All the i... | # used for manipulating directory paths
import os
# Scientific and vector computation for python
import numpy as np
# Plotting library
from matplotlib import pyplot
# Optimization module in scipy
from scipy import optimize
# library written for this exercise providing additional functions for assignment submission,... | _____no_output_____ | MIT | learning-phase/machine-learning/week-3/tanmai/.ipynb_checkpoints/exercise2-checkpoint.ipynb | Saharsh007/open-qas |
Submission and GradingAfter completing each part of the assignment, be sure to submit your solutions to the grader. The following is a breakdown of how each part of this exercise is scored.| Section | Part | Submission function | Points | :- |:- ... | # Load data
# The first two columns contains the exam scores and the third column
# contains the label.
data = np.loadtxt(os.path.join('Data', 'ex2data1.txt'), delimiter=',')
X, y = data[:, 0:2], data[:, 2] | _____no_output_____ | MIT | learning-phase/machine-learning/week-3/tanmai/.ipynb_checkpoints/exercise2-checkpoint.ipynb | Saharsh007/open-qas |
1.1 Visualizing the dataBefore starting to implement any learning algorithm, it is always good to visualize the data if possible. We display the data on a 2-dimensional plot by calling the function `plotData`. You will now complete the code in `plotData` so that it displays a figure where the axes are the two exam sc... | def plotData(X, y):
"""
Plots the data points X and y into a new figure. Plots the data
points with * for the positive examples and o for the negative examples.
Parameters
----------
X : array_like
An Mx2 matrix representing the dataset.
y : array_like
Label value... | _____no_output_____ | MIT | learning-phase/machine-learning/week-3/tanmai/.ipynb_checkpoints/exercise2-checkpoint.ipynb | Saharsh007/open-qas |
Now, we call the implemented function to display the loaded data: | plotData(X, y)
# add axes labels
pyplot.xlabel('Exam 1 score')
pyplot.ylabel('Exam 2 score')
pyplot.legend(['Admitted', 'Not admitted'])
pass | _____no_output_____ | MIT | learning-phase/machine-learning/week-3/tanmai/.ipynb_checkpoints/exercise2-checkpoint.ipynb | Saharsh007/open-qas |
1.2 Implementation 1.2.1 Warmup exercise: sigmoid functionBefore you start with the actual cost function, recall that the logistic regression hypothesis is defined as:$$ h_\theta(x) = g(\theta^T x)$$where function $g$ is the sigmoid function. The sigmoid function is defined as: $$g(z) = \frac{1}{1+e^{-z}}$$.Your first... | def sigmoid(z):
"""
Compute sigmoid function given the input z.
Parameters
----------
z : array_like
The input to the sigmoid function. This can be a 1-D vector
or a 2-D matrix.
Returns
-------
g : array_like
The computed sigmoid function. g has the sa... | _____no_output_____ | MIT | learning-phase/machine-learning/week-3/tanmai/.ipynb_checkpoints/exercise2-checkpoint.ipynb | Saharsh007/open-qas |
The following cell evaluates the sigmoid function at `z=0`. You should get a value of 0.5. You can also try different values for `z` to experiment with the sigmoid function. | # Test the implementation of sigmoid function here
z = 0
g = sigmoid(z)
print('g(', z, ') = ', g) | g( 0 ) = 0.5
| MIT | learning-phase/machine-learning/week-3/tanmai/.ipynb_checkpoints/exercise2-checkpoint.ipynb | Saharsh007/open-qas |
After completing a part of the exercise, you can submit your solutions for grading by first adding the function you modified to the submission object, and then sending your function to Coursera for grading. The submission script will prompt you for your login e-mail and submission token. You can obtain a submission tok... | # appends the implemented function in part 1 to the grader object
grader[1] = sigmoid
# send the added functions to coursera grader for getting a grade on this part
grader.grade() |
Submitting Solutions | Programming Exercise logistic-regression
Login (email address): vvijaytanmai@gmail.com
Token: c71I4EgVY0bY6fIL
Part Name | Score | Feedback
--------- | ----- | --------
Sigmoid Function | 5 ... | MIT | learning-phase/machine-learning/week-3/tanmai/.ipynb_checkpoints/exercise2-checkpoint.ipynb | Saharsh007/open-qas |
1.2.2 Cost function and gradientNow you will implement the cost function and gradient for logistic regression. Before proceeding we add the intercept term to X. | # Setup the data matrix appropriately, and add ones for the intercept term
m, n = X.shape
# Add intercept term to X
X = np.concatenate([np.ones((m, 1)), X], axis=1) | _____no_output_____ | MIT | learning-phase/machine-learning/week-3/tanmai/.ipynb_checkpoints/exercise2-checkpoint.ipynb | Saharsh007/open-qas |
Now, complete the code for the function `costFunction` to return the cost and gradient. Recall that the cost function in logistic regression is$$ J(\theta) = \frac{1}{m} \sum_{i=1}^{m} \left[ -y^{(i)} \log\left(h_\theta\left( x^{(i)} \right) \right) - \left( 1 - y^{(i)}\right) \log \left( 1 - h_\theta\left( x^{(i)} \ri... | def costFunction(theta, X, y):
"""
Compute cost and gradient for logistic regression.
Parameters
----------
theta : array_like
The parameters for logistic regression. This a vector
of shape (n+1, ).
X : array_like
The input dataset of shape (m x n+1) where m is... | _____no_output_____ | MIT | learning-phase/machine-learning/week-3/tanmai/.ipynb_checkpoints/exercise2-checkpoint.ipynb | Saharsh007/open-qas |
Once you are done call your `costFunction` using two test cases for $\theta$ by executing the next cell. | # Initialize fitting parameters
initial_theta = np.zeros(n+1)
cost, grad = costFunction(initial_theta, X, y)
print('Cost at initial theta (zeros): {:.3f}'.format(cost))
print('Expected cost (approx): 0.693\n')
print('Gradient at initial theta (zeros):')
print('\t[{:.4f}, {:.4f}, {:.4f}]'.format(*grad))
print('Expect... | Cost at initial theta (zeros): 0.693
Expected cost (approx): 0.693
Gradient at initial theta (zeros):
[-0.1000, -12.0092, -11.2628]
Expected gradients (approx):
[-0.1000, -12.0092, -11.2628]
Cost at test theta: 0.218
Expected cost (approx): 0.218
Gradient at test theta:
[0.043, 2.566, 2.647]
Expected gradients (a... | MIT | learning-phase/machine-learning/week-3/tanmai/.ipynb_checkpoints/exercise2-checkpoint.ipynb | Saharsh007/open-qas |
*You should now submit your solutions.* | grader[2] = costFunction
grader[3] = costFunction
grader.grade() |
Submitting Solutions | Programming Exercise logistic-regression
Use token from last successful submission (vvijaytanmai@gmail.com)? (Y/n): y
Part Name | Score | Feedback
--------- | ----- | --------
Sigmoid Function... | MIT | learning-phase/machine-learning/week-3/tanmai/.ipynb_checkpoints/exercise2-checkpoint.ipynb | Saharsh007/open-qas |
1.2.3 Learning parameters using `scipy.optimize`In the previous assignment, you found the optimal parameters of a linear regression model by implementing gradient descent. You wrote a cost function and calculated its gradient, then took a gradient descent step accordingly. This time, instead of taking gradient descent... | # set options for optimize.minimize
options= {'maxiter': 400}
# see documention for scipy's optimize.minimize for description about
# the different parameters
# The function returns an object `OptimizeResult`
# We use truncated Newton algorithm for optimization which is
# equivalent to MATLAB's fminunc
# See https:/... | Cost at theta found by optimize.minimize: 0.203
Expected cost (approx): 0.203
theta:
[-25.161, 0.206, 0.201]
Expected theta (approx):
[-25.161, 0.206, 0.201]
| MIT | learning-phase/machine-learning/week-3/tanmai/.ipynb_checkpoints/exercise2-checkpoint.ipynb | Saharsh007/open-qas |
Once `optimize.minimize` completes, we want to use the final value for $\theta$ to visualize the decision boundary on the training data as shown in the figure below. To do so, we have written a function `plotDecisionBoundary` for plotting the decision boundary on top of training data.... | # Plot Boundary
utils.plotDecisionBoundary(plotData, theta, X, y) | _____no_output_____ | MIT | learning-phase/machine-learning/week-3/tanmai/.ipynb_checkpoints/exercise2-checkpoint.ipynb | Saharsh007/open-qas |
1.2.4 Evaluating logistic regressionAfter learning the parameters, you can use the model to predict whether a particular student will be admitted. For a student with an Exam 1 score of 45 and an Exam 2 score of 85, you should expect to see an admissionprobability of 0.776. Another way to evaluate the quality of the pa... | def predict(theta, X):
"""
Predict whether the label is 0 or 1 using learned logistic regression.
Computes the predictions for X using a threshold at 0.5
(i.e., if sigmoid(theta.T*x) >= 0.5, predict 1)
Parameters
----------
theta : array_like
Parameters for logistic regression.... | _____no_output_____ | MIT | learning-phase/machine-learning/week-3/tanmai/.ipynb_checkpoints/exercise2-checkpoint.ipynb | Saharsh007/open-qas |
After you have completed the code in `predict`, we proceed to report the training accuracy of your classifier by computing the percentage of examples it got correct. | # Predict probability for a student with score 45 on exam 1
# and score 85 on exam 2
prob = sigmoid(np.dot([1, 45, 85], theta))
print('For a student with scores 45 and 85,'
'we predict an admission probability of {:.3f}'.format(prob))
print('Expected value: 0.775 +/- 0.002\n')
# Compute accuracy on our train... | For a student with scores 45 and 85,we predict an admission probability of 0.776
Expected value: 0.775 +/- 0.002
Train Accuracy: 89.00 %
Expected accuracy (approx): 89.00 %
| MIT | learning-phase/machine-learning/week-3/tanmai/.ipynb_checkpoints/exercise2-checkpoint.ipynb | Saharsh007/open-qas |
*You should now submit your solutions.* | grader[4] = predict
grader.grade() |
Submitting Solutions | Programming Exercise logistic-regression
Use token from last successful submission (vvijaytanmai@gmail.com)? (Y/n): y
Part Name | Score | Feedback
--------- | ----- | --------
Sigmoid Function... | MIT | learning-phase/machine-learning/week-3/tanmai/.ipynb_checkpoints/exercise2-checkpoint.ipynb | Saharsh007/open-qas |
2 Regularized logistic regressionIn this part of the exercise, you will implement regularized logistic regression to predict whether microchips from a fabrication plant passes quality assurance (QA). During QA, each microchip goes through various tests to ensure it is functioning correctly.Suppose you are the product ... | # Load Data
# The first two columns contains the X values and the third column
# contains the label (y).
data = np.loadtxt(os.path.join('Data', 'ex2data2.txt'), delimiter=',')
X = data[:, :2]
y = data[:, 2] | _____no_output_____ | MIT | learning-phase/machine-learning/week-3/tanmai/.ipynb_checkpoints/exercise2-checkpoint.ipynb | Saharsh007/open-qas |
2.1 Visualize the dataSimilar to the previous parts of this exercise, `plotData` is used to generate a figure, where the axes are the two test scores, and the positive (y = 1, accepted) and negative (y = 0, rejected) examples are shown withdifferent markers. | plotData(X, y)
# Labels and Legend
pyplot.xlabel('Microchip Test 1')
pyplot.ylabel('Microchip Test 2')
# Specified in plot order
pyplot.legend(['y = 1', 'y = 0'], loc='upper right')
pass | _____no_output_____ | MIT | learning-phase/machine-learning/week-3/tanmai/.ipynb_checkpoints/exercise2-checkpoint.ipynb | Saharsh007/open-qas |
The above figure shows that our dataset cannot be separated into positive and negative examples by a straight-line through the plot. Therefore, a straight-forward application of logistic regression will not perform well on this dataset since logistic regression will only be able to find a linear decision boundary. 2.2 ... | # Note that mapFeature also adds a column of ones for us, so the intercept
# term is handled
X = utils.mapFeature(X[:, 0], X[:, 1]) | _____no_output_____ | MIT | learning-phase/machine-learning/week-3/tanmai/.ipynb_checkpoints/exercise2-checkpoint.ipynb | Saharsh007/open-qas |
2.3 Cost function and gradientNow you will implement code to compute the cost function and gradient for regularized logistic regression. Complete the code for the function `costFunctionReg` below to return the cost and gradient.Recall that the regularized cost function in logistic regression is$$ J(\theta) = \frac{1}{... | def costFunctionReg(theta, X, y, lambda_):
"""
Compute cost and gradient for logistic regression with regularization.
Parameters
----------
theta : array_like
Logistic regression parameters. A vector with shape (n, ). n is
the number of features including any intercept. If we h... | _____no_output_____ | MIT | learning-phase/machine-learning/week-3/tanmai/.ipynb_checkpoints/exercise2-checkpoint.ipynb | Saharsh007/open-qas |
Once you are done with the `costFunctionReg`, we call it below using the initial value of $\theta$ (initialized to all zeros), and also another test case where $\theta$ is all ones. | # Initialize fitting parameters
initial_theta = np.zeros(X.shape[1])
# Set regularization parameter lambda to 1
# DO NOT use `lambda` as a variable name in python
# because it is a python keyword
lambda_ = 1
# Compute and display initial cost and gradient for regularized logistic
# regression
cost, grad = costFunctio... | Cost at initial theta (zeros): 0.693
Expected cost (approx) : 0.693
Gradient at initial theta (zeros) - first five values only:
[0.0085, 0.0188, 0.0001, 0.0503, 0.0115]
Expected gradients (approx) - first five values only:
[0.0085, 0.0188, 0.0001, 0.0503, 0.0115]
------------------------------
Cost at test t... | MIT | learning-phase/machine-learning/week-3/tanmai/.ipynb_checkpoints/exercise2-checkpoint.ipynb | Saharsh007/open-qas |
*You should now submit your solutions.* | grader[5] = costFunctionReg
grader[6] = costFunctionReg
grader.grade() |
Submitting Solutions | Programming Exercise logistic-regression
Use token from last successful submission (vvijaytanmai@gmail.com)? (Y/n): y
Part Name | Score | Feedback
--------- | ----- | --------
Sigmoid Function... | MIT | learning-phase/machine-learning/week-3/tanmai/.ipynb_checkpoints/exercise2-checkpoint.ipynb | Saharsh007/open-qas |
2.3.1 Learning parameters using `scipy.optimize.minimize`Similar to the previous parts, you will use `optimize.minimize` to learn the optimal parameters $\theta$. If you have completed the cost and gradient for regularized logistic regression (`costFunctionReg`) correctly, you should be able to step through the next p... | # Initialize fitting parameters
initial_theta = np.zeros(X.shape[1])
# Set regularization parameter lambda to 1 (you should vary this)
lambdas = [0,0.5,1,10,100]
# set options for optimize.minimize
options= {'maxiter': 100}
for lambda_ in lambdas:
res = optimize.minimize(costFunctionReg,
... | Train Accuracy: 86.4 %
Expected accuracy (with lambda = 1): 83.1 % (approx)
Train Accuracy: 82.2 %
Expected accuracy (with lambda = 1): 83.1 % (approx)
Train Accuracy: 83.1 %
Expected accuracy (with lambda = 1): 83.1 % (approx)
Train Accuracy: 74.6 %
Expected accuracy (with lambda = 1): 83.1 % (approx)
Train Accura... | MIT | learning-phase/machine-learning/week-3/tanmai/.ipynb_checkpoints/exercise2-checkpoint.ipynb | Saharsh007/open-qas |
Working directoryThe notebooks that you save here persist in the host filesystem. | import os
print(os.getcwd())
for d in os.listdir():
print(f'\t {d}') | /home/jovyan/work
.ipynb_checkpoints
demo.ipynb
| Apache-2.0 | work/demo.ipynb | vladiuz1/py3-jupyter-docker-compose |
requirements.txtThe `requirements.txt` file contains list of modules you want to use in your notebook. The demo `requirements.txt` has flask module, check if below runs without errors: | import flask
print('No problem, flask module installed.') | No problem, flask module installed.
| Apache-2.0 | work/demo.ipynb | vladiuz1/py3-jupyter-docker-compose |
Imports | %load_ext autoreload
%autoreload 2
import ib_insync
print(ib_insync.__all__)
import helpers.hdbg as dbg
import helpers.hprint as pri
import core.explore as exp
import im.ib.data.extract.gateway.utils as ibutils | _____no_output_____ | BSD-3-Clause | im/ib/data/extract/gateway/notebooks/Task114_Download_futures_price_data_from_IB.ipynb | alphamatic/amp |
Connect | ib = ibutils.ib_connect(client_id=100, is_notebook=True) | _____no_output_____ | BSD-3-Clause | im/ib/data/extract/gateway/notebooks/Task114_Download_futures_price_data_from_IB.ipynb | alphamatic/amp |
Historical data | import logging
#dbg.init_logger(verbosity=logging.DEBUG)
dbg.init_logger(verbosity=logging.INFO)
import datetime
# start_ts = pd.to_datetime(pd.Timestamp("2018-02-01 06:00:00").tz_localize(tz="America/New_York"))
# import datetime
# #datetime.datetime.combine(start_ts, datetime.time())
# dt = start_ts.to_pydatetime()
... | _____no_output_____ | BSD-3-Clause | im/ib/data/extract/gateway/notebooks/Task114_Download_futures_price_data_from_IB.ipynb | alphamatic/amp |
%load_ext autoreload
%autoreload 2
import ib_insync
print(ib_insync.__all__)
import helpers.hdbg as dbg
import helpers.hprint as pri
import core.explore as exp
import im.ib.data.extract.gateway.utils as ibutils
import logging
dbg.init_logger(verbosity=logging.DEBUG)
#dbg.init_logger(verbosity=logging.INFO)
import pa... | (datetime.datetime(2021, 2, 18, 23, 59, 59, tzinfo=<DstTzInfo 'America/New_York' EST-1 day, 19:00:00 STD>), Timestamp('2021-02-18 18:00:00-0500', tz='America/New_York'))
(Timestamp('2021-02-18 18:00:00-0500', tz='America/New_York'), Timestamp('2021-02-17 18:00:00-0500', tz='America/New_York'))
(Timestamp('2021-02-17 18... | BSD-3-Clause | im/ib/data/extract/gateway/notebooks/Task114_Download_futures_price_data_from_IB.ipynb | alphamatic/amp | |
As explained in the [Composing Data](Composing_Data.ipynb) and [Containers](Containers.ipynb) tutorials, HoloViews allows you to build up hierarchical containers that express the natural relationships between your data items, in whatever multidimensional space best characterizes your application domain. Once your data... | import numpy as np
import holoviews as hv
hv.notebook_extension()
%opts Layout [fig_size=125] Points [size_index=None] (s=50) Scatter3D [size_index=None]
%opts Bounds (linewidth=2 color='k') {+axiswise} Text (fontsize=16 color='k') Image (cmap='Reds') | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Sampling_Data.ipynb | stuarteberg/holoviews |
1D Elements: Slicing and indexing Certain Chart elements support both single-dimensional indexing and slicing: ``Scatter``, ``Curve``, ``Histogram``, and ``ErrorBars``. Here we'll look at how we can easily slice a ``Histogram`` to select a subregion of it: | np.random.seed(42)
edges, data = np.histogram(np.random.randn(100))
hist = hv.Histogram(edges, data)
subregion = hist[0:1]
hist * subregion | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Sampling_Data.ipynb | stuarteberg/holoviews |
The two bins in a different color show the selected region, overlaid on top of the full histogram. We can also access the value for a specific bin in the ``Histogram``. A continuous-valued index that falls inside a particular bin will return the corresponding value or frequency. | hist[0.25], hist[0.5], hist[0.55] | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Sampling_Data.ipynb | stuarteberg/holoviews |
We can slice a ``Curve`` the same way: | xs = np.linspace(0, np.pi*2, 21)
curve = hv.Curve((xs, np.sin(xs)))
subregion = curve[np.pi/2:np.pi*1.5]
curve * subregion * hv.Scatter(curve) | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Sampling_Data.ipynb | stuarteberg/holoviews |
Here again the region in a different color is the specified subregion, and we've also marked each discrete point with a dot using the ``Scatter`` ``Element``. As before we can also get the value for a specific sample point; whatever x-index is provided will snap to the closest sample point and return the dependent val... | curve[4.05], curve[4.1], curve[4.17], curve[4.3] | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Sampling_Data.ipynb | stuarteberg/holoviews |
It is important to note that an index (or a list of indices, as for the 2D and 3D cases below) will always return the raw indexed (dependent) value, i.e. a number. A slice (indicated with `:`), on the other hand, will retain the Element type even in cases where the plot might not be useful, such as having only a singl... | curve[4:4.5] | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Sampling_Data.ipynb | stuarteberg/holoviews |
2D and 3D Elements: slicing For data defined in a 2D space, there are 2D equivalents of the 1D Curve and Scatter types. A ``Points``, for example, can be thought of as a number of points in a 2D space. | r = np.arange(0, 1, 0.005)
xs, ys = (r * fn(85*np.pi*r) for fn in (np.cos, np.sin))
paths = hv.Points((xs, ys))
paths + paths[0:1, 0:1] | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Sampling_Data.ipynb | stuarteberg/holoviews |
However, indexing is not supported in this space, because there could be many possible points near a given set of coordinates, and finding the nearest one would require a search across potentially incommensurable dimensions, which is poorly defined and difficult to support.Slicing in 3D works much like slicing in 2D, b... | xs = np.linspace(0, np.pi*8, 201)
scatter = hv.Scatter3D((xs, np.sin(xs), np.cos(xs)))
scatter + scatter[5:10, :, 0:] | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Sampling_Data.ipynb | stuarteberg/holoviews |
2D Raster and Image: slicing and indexingRaster and the various other image-like objects (Images, RGB, HSV, etc.) can all sliced and indexed, as can Surface, because they all have an underlying regular grid of key dimension values: | %opts Image (cmap='Blues') Bounds (color='red')
np.random.seed(0)
extents = (0, 0, 10, 10)
img = hv.Image(np.random.rand(10, 10), bounds=extents)
img_slice = img[1:9,4:5]
box = hv.Bounds((1,4,9,5))
img*box + img_slice
img[4.2,4.2], img[4.3,4.2], img[5.0,4.2] | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Sampling_Data.ipynb | stuarteberg/holoviews |
SamplingSampling is essentially a process of indexing an Element at multiple index locations, and collecting the results. Thus any Element that can be indexed can also be sampled. Compared to regular indexing, sampling is different in that multiple indices may be supplied at the same time. Also, indexing will only... | img_coords = hv.Points(img.table(), extents=extents)
labeled_img = img * img_coords * hv.Points([img.closest([(5.1,4.9)])]).opts(style=dict(color='r'))
img + labeled_img + img.sample([(5.1,4.9)])
img[5.1,4.9] | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Sampling_Data.ipynb | stuarteberg/holoviews |
Here, the output of the indexing operation is the value (0.1965823616800535) from the location closest to the specified , whereas ``.sample()`` returns a Table that lists both the coordinates *and* the value, and slicing (in previous section) returns an Element of the same type, not a Table.Next we can try sampling alo... | sampled = img.sample(y=5)
labeled_img = img * img_coords * hv.Points(zip(sampled['x'], [img.closest(y=5)]*10))
img + labeled_img + sampled | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Sampling_Data.ipynb | stuarteberg/holoviews |
Sampling works on any regularly sampled Element type. For example, we can select multiple samples along the x-axis of a Curve. | xs = np.arange(10)
samples = [2, 4, 6, 8]
curve = hv.Curve(zip(xs, np.sin(xs)))
curve_samples = hv.Scatter(zip(xs, [0] * 10)) * hv.Scatter(zip(samples, [0]*len(samples)))
curve + curve_samples + curve.sample(samples) | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Sampling_Data.ipynb | stuarteberg/holoviews |
Sampling HoloMapsSampling is often useful when you have more data than you wish to visualize or analyze at one time. First, let's create a HoloMap containing a number of observations of some noisy data. | obs_hmap = hv.HoloMap({i: hv.Image(np.random.randn(10, 10), bounds=extents)
for i in range(3)}, kdims=['Observation']) | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Sampling_Data.ipynb | stuarteberg/holoviews |
HoloMaps also provide additional functionality to perform regular sampling on your data. In this case we'll take 3x3 subsamples of each of the Images. | sample_style = dict(edgecolors='k', alpha=1)
all_samples = obs_hmap.table().to.scatter3d().opts(style=dict(alpha=0.15))
sampled = obs_hmap.sample((3,3))
subsamples = sampled.to.scatter3d().opts(style=sample_style)
all_samples * subsamples + sampled | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Sampling_Data.ipynb | stuarteberg/holoviews |
By supplying bounds in as a (left, bottom, right, top) tuple we can also sample a subregion of our images: | sampled = obs_hmap.sample((3,3), bounds=(2,5,5,10))
subsamples = sampled.to.scatter3d().opts(style=sample_style)
all_samples * subsamples + sampled | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Sampling_Data.ipynb | stuarteberg/holoviews |
Since this kind of sampling is only well supported for continuous coordinate systems, we can only apply this kind of sampling to Image types for now. Sampling ChartsSampling Chart-type Elements like Curve, Scatter, Histogram is only supported by providing an explicit list of samples, since those Elements have no underl... | xs = np.arange(10)
extents = (0, 0, 2, 10)
curve = hv.HoloMap({(i) : hv.Curve(zip(xs, np.sin(xs)*i))
for i in np.linspace(0.5, 1.5, 3)},
kdims=['Observation'])
all_samples = curve.table().to.points()
sampled = curve.sample([0, 2, 4, 6, 8])
sampling = all_samples * sampled.to.point... | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Sampling_Data.ipynb | stuarteberg/holoviews |
Alternatively, you can always deconstruct your data into a Table (see the [Columnar Data](Columnar_Data.ipynb) tutorial) and perform ``select`` operations instead. This is also the easiest way to sample ``NdElement`` types like Bars. Individual samples should be supplied as a set, while ranges can be specified as a two... | sampled = curve.table().select(Observation=(0, 1.1), x={0, 2, 4, 6, 8})
sampling = all_samples * sampled.to.points(extents=extents).opts(style=dict(color='r'))
sampling + sampled | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Sampling_Data.ipynb | stuarteberg/holoviews |
C6.01: Introduction | from sklearn.datasets.samples_generator import make_blobs
n_clusters = 2
centers = [[-1,-1],[1,1]]
stdevs = [0.4, 0.6]
X, y = make_blobs(n_samples = 20, centers = centers, cluster_std = stdevs, random_state = 1200000)
from sklearn.cluster import KMeans
model = KMeans(n_clusters = n_clusters)
preds = model.fit_predict... | _____no_output_____ | MIT | course/3_unsupervised_learning/01_clustering/UL6_PCA_Storyboard_Assets.ipynb | claudiocmp/udacity-dsnd |
C6.09: Dimensionality Reduction | n_points = [4, 7, 9, 9, 7, 4]
n_rooms = [3, 4, 5, 6, 7, 8]
size_lower = [ 600, 800, 1000, 1300, 1600, 2000]
size_upper = [1000, 1300, 1600, 2000, 2400, 3000]
np.random.seed(147258369)
rooms = []
sizes = []
for i in range(6):
# use beta dist to generate sizes, find bounds with
# lower @ 0.2, upper @ 0.8.
... | _____no_output_____ | MIT | course/3_unsupervised_learning/01_clustering/UL6_PCA_Storyboard_Assets.ipynb | claudiocmp/udacity-dsnd |
C6.10: PCA Properties | alt_slope = np.array([1.3,1.1])
alt_slope = alt_slope / np.sqrt((alt_slope ** 2).sum())
alt_center = np.array([-.35,-.35])
X_alt = np.matmul( np.dot(X - alt_center, alt_slope).reshape(-1,1), alt_slope.reshape(1,-1) ) + alt_center
plt.figure(figsize = [15,15])
plt.scatter(X[:,0], X[:,1], s = 64, c = plot_colors[-1])
p... | _____no_output_____ | MIT | course/3_unsupervised_learning/01_clustering/UL6_PCA_Storyboard_Assets.ipynb | claudiocmp/udacity-dsnd |
Real caseFirst, the real case is relatively simple.The integral that we want to do is:$$k_\Delta(\tau) = \frac{1}{\Delta^2}\int_{t_i-\Delta/2}^{t_i+\Delta/2} \mathrm{d}t \,\int_{t_j-\Delta/2}^{t_j+\Delta/2}\mathrm{d}t^\prime\,k(t - t^\prime)$$For celerite kernels it helps to make the assumtion that $t_j + \Delta/2 < t... | import sympy as sm
cr = sm.symbols("cr", positive=True)
ti, tj, dt, t, tp = sm.symbols("ti, tj, dt, t, tp", real=True)
k = sm.exp(-cr*(t - tp))
k0 = k.subs([(t, ti), (tp, tj)])
kint = sm.simplify(sm.integrate(
sm.integrate(k, (t, ti-dt/2, ti+dt/2)),
(tp, tj-dt/2, tj+dt/2)) / dt**2)
res = sm.simplify(kint / k0)... | (exp(2*cr*dt) - 2*exp(cr*dt) + 1)*exp(-cr*dt)/(cr**2*dt**2)
| MIT | paper/proofs/celerite-integral.ipynb | exowanderer/exoplanet |
This is the factor that we want.Let's make sure that it is identical to what we have in the note. | kD = 2 * (sm.cosh(cr*dt) - 1) / (cr*dt)**2
sm.simplify(res.expand() - kD.expand()) | _____no_output_____ | MIT | paper/proofs/celerite-integral.ipynb | exowanderer/exoplanet |
Excellent.Let's double check that this reduces to the original kernel in the limit $\Delta \to 0$: | sm.limit(kD, dt, 0) | _____no_output_____ | MIT | paper/proofs/celerite-integral.ipynb | exowanderer/exoplanet |
Complex caseThe complex cases proceeds similarly, but it's a bit more involved.In this case,$$k(\tau) = (a + i\,b)\,\exp(-(c+i\,d)\,(t_i-t_j))$$ | a, b, c, d = sm.symbols("a, b, c, d", real=True, positive=True)
k = sm.exp(-(c + sm.I*d) * (t - tp))
k0 = k.subs([(t, ti), (tp, tj)])
kint = sm.simplify(sm.integrate(k, (t, ti-dt/2, ti+dt/2)) / dt)
kint = sm.simplify(sm.integrate(kint.expand(), (tp, tj-dt/2, tj+dt/2)) / dt)
print(sm.simplify(kint / k0)) | (2*cos(I*dt*(c + I*d)) - 2)/(dt**2*(c**2 + 2*I*c*d - d**2))
| MIT | paper/proofs/celerite-integral.ipynb | exowanderer/exoplanet |
That doesn't look so bad!But, I'm going to re-write it by hand and make sure that it's correct: | coeff = (c-sm.I*d)**2 / (dt*(c**2+d**2))**2
coeff *= (sm.exp((c+sm.I*d)*dt) + sm.exp(-(c+sm.I*d)*dt)-2)
sm.simplify(coeff * k0 - kint) | _____no_output_____ | MIT | paper/proofs/celerite-integral.ipynb | exowanderer/exoplanet |
Good.Now we need to work out nice expressions for the real and imaginary parts of this.First, the real part.I found that it was easiest to look at the prefactors for the trig functions directly and simplify those.Here we go: | res = (a+sm.I*b) * coeff
A = sm.simplify((res.expand(complex=True) +
sm.conjugate(res).expand(complex=True)) / 2)
sm.simplify(sm.poly(A, sm.cos(dt*d)).coeff_monomial(sm.cos(dt*d)))
sm.simplify(sm.poly(sm.poly(A, sm.cos(dt*d)).coeff_monomial(1), sm.sin(dt*d)).coeff_monomial(sm.sin(dt*d)))
sm.simplify(sm... | _____no_output_____ | MIT | paper/proofs/celerite-integral.ipynb | exowanderer/exoplanet |
Then, same thing for the imaginary part: | B = sm.simplify(-sm.I * (res.expand(complex=True) -
sm.conjugate(res).expand(complex=True)) / 2)
sm.simplify(sm.poly(B, sm.cos(dt*d)).coeff_monomial(sm.cos(dt*d)))
sm.simplify(sm.poly(sm.poly(B, sm.cos(dt*d)).coeff_monomial(1), sm.sin(dt*d)).coeff_monomial(sm.sin(dt*d)))
sm.simplify(sm.poly(sm.... | _____no_output_____ | MIT | paper/proofs/celerite-integral.ipynb | exowanderer/exoplanet |
Ok.Now let's make sure that the simplified expressions are right. | C1 = (a*c**2 - a*d**2 + 2*b*c*d)
C2 = (b*c**2 - b*d**2 - 2*a*c*d)
cos_term = (sm.exp(c*dt) + sm.exp(-c*dt)) * sm.cos(d*dt) - 2
sin_term = (sm.exp(c*dt) - sm.exp(-c*dt)) * sm.sin(d*dt)
denom = dt**2 * (c**2 + d**2)**2
A0 = (C1 * cos_term - C2 * sin_term) / denom
B0 = (C2 * cos_term + C1 * sin_term) / denom
sm.simplify(... | _____no_output_____ | MIT | paper/proofs/celerite-integral.ipynb | exowanderer/exoplanet |
Finally let's rewrite things in terms of hyperbolic trig functions. | sm.simplify(2*(sm.cosh(c*dt) * sm.cos(d*dt) - 1).expand() - cos_term.expand())
sm.simplify(2*(sm.sinh(c*dt) * sm.sin(d*dt)).expand() - sin_term.expand()) | _____no_output_____ | MIT | paper/proofs/celerite-integral.ipynb | exowanderer/exoplanet |
Looks good!Let's make sure that this actually reproduces the target integral: | sm.simplify(((a+sm.I*b)*kint/k0 - (A+sm.I*B)).expand(complex=True)) | _____no_output_____ | MIT | paper/proofs/celerite-integral.ipynb | exowanderer/exoplanet |
Finally, let's make sure that this reduces to the original kernel when $\Delta \to 0$: | sm.limit(A, dt, 0), sm.limit(B, dt, 0) | _____no_output_____ | MIT | paper/proofs/celerite-integral.ipynb | exowanderer/exoplanet |
Overlapping exposures & the power spectrumIf we directly evaluate the power spectrum of this kernel, we'll have some issues because there will be power from lags where our assumption of non-overlapping exposures will break down.Instead, we can evaluate the correct power spectrum by realizing that the integrals that we... | omega = sm.symbols("omega", real=True)
sm.simplify(sm.integrate(sm.exp(sm.I * t * omega) / dt, (t, -dt / 2, dt / 2))) | _____no_output_____ | MIT | paper/proofs/celerite-integral.ipynb | exowanderer/exoplanet |
Therefore, the integrated power spectrum is$$S_\Delta(\omega) = \frac{\sin^2(\Delta\,\omega/2)}{(\Delta\,\omega/2)^2}\,S(\omega) = \mathrm{sinc}^2(\Delta\,\omega/2)\,S(\omega)$$ For overlapping exposures, some care must be taken when computing the autocorrelation because of the absolute value.This also means that celer... | tau = sm.symbols("tau", real=True, positive=True)
kp = sm.exp(-cr*(t - tp))
km = sm.exp(-cr*(tp - t))
k1 = sm.simplify(sm.integrate(
sm.integrate(kp, (tp, tj-dt/2, tj+dt/2)),
(t, tj+dt/2, ti+dt/2)) / dt**2)
k2 = sm.simplify(sm.integrate(
sm.integrate(kp, (tp, tj-dt/2, t)),
(t, ti-dt/2, tj+dt/2)) / dt**2... | _____no_output_____ | MIT | paper/proofs/celerite-integral.ipynb | exowanderer/exoplanet |
Ok. That's the result for the real case. Now let's work through the result for the complex case. | arg1 = ((a+sm.I*b) * kint.subs([(cr, c+sm.I*d)])).expand(complex=True)
arg2 = ((a-sm.I*b) * kint.subs([(cr, c-sm.I*d)])).expand(complex=True)
res = sm.simplify((arg1 + arg2) / 2)
res
C1 = (a*c**2 - a*d**2 + 2*b*c*d)
C2 = (b*c**2 - b*d**2 - 2*a*c*d)
denom = dt**2 * (c**2 + d**2)**2
dpt = dt + tau
dmt = dt - tau
cos_ter... | _____no_output_____ | MIT | paper/proofs/celerite-integral.ipynb | exowanderer/exoplanet |
Module1> module 1 | #export
def nothing(): pass | _____no_output_____ | Apache-2.0 | module1.ipynb | hamelsmu/nbdev_export_demo |
目标规划**基本上分为两种思路: 加权系数法(转化为单一目标), 优先等级法(按重要程度不同, 转化为单目标模型)**正负偏差变量: $d_i^+=max\{f_i-d_i^0,0\},\ d_i^-=-min\{f_i-d_i^0,0\}$, 显然恒有$d_i^+\times d_i^-=0$ | # 例16.3
# 该题的规划模型如下:
# min z =P[0]*dminus[0] + P[1]*(dplus[1]+dminus[1]) + P[2]*(3 * (dplus[2]+dminus[2]) + dplus[3])
# 2*x[0] + 2*x[1] <= 12
# 200*x[0] + 300*x[1] + dminus[0] - dplus[0] = 1500
# 2*x[0] - x[1] + dminus[1] - dplus[1] = 0
# 4*x[0] + dminus[2] - dplus[2] = 16
# 5*x[1] + dminus[3] - dpl... | _____no_output_____ | MIT | .ipynb_checkpoints/16 目标规划-checkpoint.ipynb | ZDDWLIG/math-model |
Fully-Connected Neural NetsIn this exercise we will implement fully-connected networks using a modular approach. For each layer we will implement a `forward` and a `backward` function. The `forward` function will receive inputs, weights, and other parameters and will return both an output and a `cache` object storing ... | # As usual, a bit of setup
from __future__ import print_function
import time
import numpy as np
import matplotlib.pyplot as plt
from cs231n.classifiers.fc_net import *
from cs231n.data_utils import get_CIFAR10_data
from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array
from cs231n.solv... | ('X_train: ', (49000, 3, 32, 32))
('y_train: ', (49000,))
('X_val: ', (1000, 3, 32, 32))
('y_val: ', (1000,))
('X_test: ', (1000, 3, 32, 32))
('y_test: ', (1000,))
| Apache-2.0 | assignment1/two_layer_net.ipynb | qiaw99/CS231n-Convolutional-Neural-Networks-for-Visual-Recognition |
Affine layer: forwardOpen the file `cs231n/layers.py` and implement the `affine_forward` function.Once you are done you can test your implementaion by running the following: | # Test the affine_forward function
num_inputs = 2
input_shape = (4, 5, 6)
output_dim = 3
input_size = num_inputs * np.prod(input_shape)
weight_size = output_dim * np.prod(input_shape)
x = np.linspace(-0.1, 0.5, num=input_size).reshape(num_inputs, *input_shape)
w = np.linspace(-0.2, 0.3, num=weight_size).reshape(np.p... | Testing affine_forward function:
difference: 9.769849468192957e-10
| Apache-2.0 | assignment1/two_layer_net.ipynb | qiaw99/CS231n-Convolutional-Neural-Networks-for-Visual-Recognition |
Affine layer: backwardNow implement the `affine_backward` function and test your implementation using numeric gradient checking. | # Test the affine_backward function
np.random.seed(231)
x = np.random.randn(10, 2, 3)
w = np.random.randn(6, 5)
b = np.random.randn(5)
dout = np.random.randn(10, 5)
dx_num = eval_numerical_gradient_array(lambda x: affine_forward(x, w, b)[0], x, dout)
dw_num = eval_numerical_gradient_array(lambda w: affine_forward(x, w... | Testing affine_backward function:
dx error: 5.399100368651805e-11
dw error: 9.904211865398145e-11
db error: 2.4122867568119087e-11
| Apache-2.0 | assignment1/two_layer_net.ipynb | qiaw99/CS231n-Convolutional-Neural-Networks-for-Visual-Recognition |
ReLU activation: forwardImplement the forward pass for the ReLU activation function in the `relu_forward` function and test your implementation using the following: | # Test the relu_forward function
x = np.linspace(-0.5, 0.5, num=12).reshape(3, 4)
out, _ = relu_forward(x)
correct_out = np.array([[ 0., 0., 0., 0., ],
[ 0., 0., 0.04545455, 0.13636364,],
[ 0.22727273, 0.31818182, 0... | Testing relu_forward function:
difference: 4.999999798022158e-08
| Apache-2.0 | assignment1/two_layer_net.ipynb | qiaw99/CS231n-Convolutional-Neural-Networks-for-Visual-Recognition |
ReLU activation: backwardNow implement the backward pass for the ReLU activation function in the `relu_backward` function and test your implementation using numeric gradient checking: | np.random.seed(231)
x = np.random.randn(10, 10)
dout = np.random.randn(*x.shape)
dx_num = eval_numerical_gradient_array(lambda x: relu_forward(x)[0], x, dout)
_, cache = relu_forward(x)
dx = relu_backward(dout, cache)
# The error should be on the order of e-12
print('Testing relu_backward function:')
print('dx error... | Testing relu_backward function:
dx error: 3.2756349136310288e-12
| Apache-2.0 | assignment1/two_layer_net.ipynb | qiaw99/CS231n-Convolutional-Neural-Networks-for-Visual-Recognition |
Inline Question 1: We've only asked you to implement ReLU, but there are a number of different activation functions that one could use in neural networks, each with its pros and cons. In particular, an issue commonly seen with activation functions is getting zero (or close to zero) gradient flow during backpropagation... | from cs231n.layer_utils import affine_relu_forward, affine_relu_backward
np.random.seed(231)
x = np.random.randn(2, 3, 4)
w = np.random.randn(12, 10)
b = np.random.randn(10)
dout = np.random.randn(2, 10)
out, cache = affine_relu_forward(x, w, b)
dx, dw, db = affine_relu_backward(dout, cache)
dx_num = eval_numerical_g... | Testing affine_relu_forward and affine_relu_backward:
dx error: 2.299579177309368e-11
dw error: 8.162011105764925e-11
db error: 7.826724021458994e-12
| Apache-2.0 | assignment1/two_layer_net.ipynb | qiaw99/CS231n-Convolutional-Neural-Networks-for-Visual-Recognition |
Loss layers: Softmax and SVMNow implement the loss and gradient for softmax and SVM in the `softmax_loss` and `svm_loss` function in `cs231n/layers.py`. These should be similar to what you implemented in `cs231n/classifiers/softmax.py` and `cs231n/classifiers/linear_svm.py`.You can make sure that the implementations a... | np.random.seed(231)
num_classes, num_inputs = 10, 50
x = 0.001 * np.random.randn(num_inputs, num_classes)
y = np.random.randint(num_classes, size=num_inputs)
dx_num = eval_numerical_gradient(lambda x: svm_loss(x, y)[0], x, verbose=False)
loss, dx = svm_loss(x, y)
# Test svm_loss function. Loss should be around 9 and ... | Testing svm_loss:
loss: 8.999602749096233
dx error: 1.4021566006651672e-09
Testing softmax_loss:
loss: 2.3025458445007376
dx error: 8.234144091578429e-09
| Apache-2.0 | assignment1/two_layer_net.ipynb | qiaw99/CS231n-Convolutional-Neural-Networks-for-Visual-Recognition |
Two-layer networkOpen the file `cs231n/classifiers/fc_net.py` and complete the implementation of the `TwoLayerNet` class. Read through it to make sure you understand the API. You can run the cell below to test your implementation. | np.random.seed(231)
N, D, H, C = 3, 5, 50, 7
X = np.random.randn(N, D)
y = np.random.randint(C, size=N)
std = 1e-3
model = TwoLayerNet(input_dim=D, hidden_dim=H, num_classes=C, weight_scale=std)
print('Testing initialization ... ')
W1_std = abs(model.params['W1'].std() - std)
b1 = model.params['b1']
W2_std = abs(mode... | Testing initialization ...
Testing test-time forward pass ...
Testing training loss (no regularization)
Running numeric gradient check with reg = 0.0
W1 relative error: 1.83e-08
W2 relative error: 3.20e-10
b1 relative error: 9.83e-09
b2 relative error: 4.33e-10
Running numeric gradient check with reg = 0.7
W1 relat... | Apache-2.0 | assignment1/two_layer_net.ipynb | qiaw99/CS231n-Convolutional-Neural-Networks-for-Visual-Recognition |
SolverOpen the file `cs231n/solver.py` and read through it to familiarize yourself with the API. You also need to imeplement the `sgd` function in `cs231n/optim.py`. After doing so, use a `Solver` instance to train a `TwoLayerNet` that achieves about `36%` accuracy on the validation set. | input_size = 32 * 32 * 3
hidden_size = 50
num_classes = 10
model = TwoLayerNet(input_size, hidden_size, num_classes)
solver = None
##############################################################################
# TODO: Use a Solver instance to train a TwoLayerNet that achieves about 36% #
# accuracy on the validation s... | (Iteration 1 / 4900) loss: 2.300089
(Epoch 0 / 10) train acc: 0.171000; val_acc: 0.170000
(Iteration 101 / 4900) loss: 1.782419
(Iteration 201 / 4900) loss: 1.803466
(Iteration 301 / 4900) loss: 1.712676
(Iteration 401 / 4900) loss: 1.693946
(Epoch 1 / 10) train acc: 0.399000; val_acc: 0.428000
(Iteration 501 / 4900) l... | Apache-2.0 | assignment1/two_layer_net.ipynb | qiaw99/CS231n-Convolutional-Neural-Networks-for-Visual-Recognition |
Debug the trainingWith the default parameters we provided above, you should get a validation accuracy of about 0.36 on the validation set. This isn't very good.One strategy for getting insight into what's wrong is to plot the loss function and the accuracies on the training and validation sets during optimization.Anot... | # Run this cell to visualize training loss and train / val accuracy
plt.subplot(2, 1, 1)
plt.title('Training loss')
plt.plot(solver.loss_history, 'o')
plt.xlabel('Iteration')
plt.subplot(2, 1, 2)
plt.title('Accuracy')
plt.plot(solver.train_acc_history, '-o', label='train')
plt.plot(solver.val_acc_history, '-o', label... | _____no_output_____ | Apache-2.0 | assignment1/two_layer_net.ipynb | qiaw99/CS231n-Convolutional-Neural-Networks-for-Visual-Recognition |
Tune your hyperparameters**What's wrong?**. Looking at the visualizations above, we see that the loss is decreasing more or less linearly, which seems to suggest that the learning rate may be too low. Moreover, there is no gap between the training and validation accuracy, suggesting that the model we used has low capa... | best_model = None
best_acc = 0
#################################################################################
# TODO: Tune hyperparameters using the validation set. Store your best trained #
# model in best_model. #
# ... | (Iteration 1 / 4900) loss: 2.306069
(Epoch 0 / 10) train acc: 0.104000; val_acc: 0.114000
(Iteration 101 / 4900) loss: 1.724592
(Iteration 201 / 4900) loss: 1.782996
(Iteration 301 / 4900) loss: 1.663951
(Iteration 401 / 4900) loss: 1.639033
(Epoch 1 / 10) train acc: 0.443000; val_acc: 0.435000
(Iteration 501 / 4900) l... | Apache-2.0 | assignment1/two_layer_net.ipynb | qiaw99/CS231n-Convolutional-Neural-Networks-for-Visual-Recognition |
Test your model!Run your best model on the validation and test sets. You should achieve above 48% accuracy on the validation set and the test set. | y_val_pred = np.argmax(best_model.loss(data['X_val']), axis=1)
print('Validation set accuracy: ', (y_val_pred == data['y_val']).mean())
data = get_CIFAR10_data()
y_test_pred = np.argmax(best_model.loss(data["X_test"]), axis=1)
print('Test set accuracy: ', (y_test_pred == data['y_test']).mean()) | Test set accuracy: 0.495
| Apache-2.0 | assignment1/two_layer_net.ipynb | qiaw99/CS231n-Convolutional-Neural-Networks-for-Visual-Recognition |
Inline Question 2: Now that you have trained a Neural Network classifier, you may find that your testing accuracy is much lower than the training accuracy. In what ways can we decrease this gap? Select all that apply.1. Train on a larger dataset.2. Add more hidden units.3. Increase the regularization strength.4. None ... | _____no_output_____ | Apache-2.0 | assignment1/two_layer_net.ipynb | qiaw99/CS231n-Convolutional-Neural-Networks-for-Visual-Recognition | |
Welcome to 101 Exercises for Python FundamentalsSolving these exercises will help make you a better programmer. Solve them in order, because each solution builds scaffolding, working code, and knowledge you can use on future problems. Read the directions carefully, and have fun!> "Learning to program takes a little b... | # Example problem:
# Uncomment the line below and run this cell.
# The hashtag "#" character in a line of Python code is the comment character.
doing_python_right_now = True
# The lines below will test your answer. If you see an error, then it means that your answer is incorrect or incomplete.
assert doing_python_rig... | Exercise 4 is correct.
| MIT | 101_exercises.ipynb | barbmarques/python-exercises |
List Operations**Hint** Recommend finding and using built-in Python functionality whenever possible. | # Exercise 5
# Given the following assigment of the list of fruits, add "tomato" to the end of the list.
fruits = ["mango", "banana", "guava", "kiwi", "strawberry"]
fruits.append('tomato')
assert fruits == ["mango", "banana", "guava", "kiwi", "strawberry", "tomato"], "Ensure the variable contains all the strings in ... | Exercise 10 is correct
| MIT | 101_exercises.ipynb | barbmarques/python-exercises |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.