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 |
|---|---|---|---|---|---|
d) Single matrix operations In this section we describe a few operations that can be done over matrices: d.1) TransposeA very common operation is the transpose. If you are used to see matrix notation, you should know what this operation is. Take a matrix with 2 dimensions:$$ X = \begin{bmatrix} a & b \\ c & d \\ \end... | m1 = np.array([[ .1, 1., 2.], [ 3., .24, 4.], [ 6., 2., 5.]])
print('Initial matrix: \n{}'.format(m1))
m1_transposed = m1.transpose()
print('Transposed matrix with `transpose` \n{}'.format(m1_transposed))
m1_transposed = m1.T
print('Transposed matrix with `T` \n{}'.format(m1_transposed)) | Transposed matrix with `T`
[[0.1 3. 6. ]
[1. 0.24 2. ]
[2. 4. 5. ]]
| MIT | S01 - Bootcamp and Binary Classification/SLU07 - Regression with Linear Regression/Example notebook.ipynb | claury/sidecar-academy-batch2 |
A few examples of non-squared matrices. In these, you'll see that the shape (a, b) gets inverted to (b, a): | m1 = np.array([[ .1, 1., 2., 5.], [ 3., .24, 4., .6]])
print('Initial matrix: \n{}'.format(m1))
m1_transposed = m1.T
print('Transposed matrix: \n{}'.format(m1_transposed))
m1 = np.array([[ .1, 1.], [2., 5.], [ 3., .24], [4., .6]])
print('Initial matrix: \n{}'.format(m1))
m1_transposed = m1.T
print('Trans... | Initial matrix:
[[0.1 1. ]
[2. 5. ]
[3. 0.24]
[4. 0.6 ]]
Transposed matrix:
[[0.1 2. 3. 4. ]
[1. 5. 0.24 0.6 ]]
| MIT | S01 - Bootcamp and Binary Classification/SLU07 - Regression with Linear Regression/Example notebook.ipynb | claury/sidecar-academy-batch2 |
For vectors represented as matrices, this means transforming from a row vector (1, N) to a column vector (N, 1) or vice-versa: | v1 = np.array([ .1, 1., 2.])
v1_reshaped = v1.reshape((1, -1))
print('Row vector as 2-d array: {}'.format(v1_reshaped))
print('Shape: {}'.format(v1_reshaped.shape))
v1_transposed = v1_reshaped.T
print('Transposed (column vector as 2-d array): \n{}'.format(v1_transposed))
print('Shape: {}'.f... | Column vector as 2-d array:
[[3. ]
[0.23]
[2. ]
[0.6 ]]
Shape: (4, 1)
Transposed (row vector as 2-d array): [[3. 0.23 2. 0.6 ]]
Shape: (1, 4)
| MIT | S01 - Bootcamp and Binary Classification/SLU07 - Regression with Linear Regression/Example notebook.ipynb | claury/sidecar-academy-batch2 |
d.2) Statistics operatorsNumpy also allows us to perform several operations over the rows and columns of a matrix, such as: * Sum* Mean* Max* Min* ...The most important thing to take into account when using these is to know exactly in which direction we are performing the operations. We can perform, for example, a `m... | m1 = np.array([[ .1, 1.], [2., 5.], [ 3., .24], [4., .6]])
print('Initial matrix: \n{}'.format(m1)) | Initial matrix:
[[0.1 1. ]
[2. 5. ]
[3. 0.24]
[4. 0.6 ]]
| MIT | S01 - Bootcamp and Binary Classification/SLU07 - Regression with Linear Regression/Example notebook.ipynb | claury/sidecar-academy-batch2 |
Operating over all matrix' values: | print('Total sum of matrix elements: {}'.format(m1.sum()))
print('Minimum of all matrix elements: {}'.format(m1.max()))
print('Maximum of all matrix elements: {}'.format(m1.min()))
print('Mean of all matrix elements: {}'.format(m1.mean())) | Total sum of matrix elements: 15.94
Minimum of all matrix elements: 5.0
Maximum of all matrix elements: 0.1
Mean of all matrix elements: 1.9925
| MIT | S01 - Bootcamp and Binary Classification/SLU07 - Regression with Linear Regression/Example notebook.ipynb | claury/sidecar-academy-batch2 |
Operating across rows - produces a row with the sum/max/min/mean for each column: | print('Total sum of matrix elements: {}'.format(m1.sum(axis=0)))
print('Minimum of all matrix elements: {}'.format(m1.max(axis=0)))
print('Maximum of all matrix elements: {}'.format(m1.min(axis=0)))
print('Mean of all matrix elements: {}'.format(m1.mean(axis=0))) | Total sum of matrix elements: [9.1 6.84]
Minimum of all matrix elements: [4. 5.]
Maximum of all matrix elements: [0.1 0.24]
Mean of all matrix elements: [2.275 1.71 ]
| MIT | S01 - Bootcamp and Binary Classification/SLU07 - Regression with Linear Regression/Example notebook.ipynb | claury/sidecar-academy-batch2 |
Operating across columns - produces a column with the sum/max/min/mean for each row: | print('Total sum of matrix elements: {}'.format(m1.sum(axis=1)))
print('Minimum of all matrix elements: {}'.format(m1.max(axis=1)))
print('Maximum of all matrix elements: {}'.format(m1.min(axis=1)))
print('Mean of all matrix elements: {}'.format(m1.mean(axis=1))) | Total sum of matrix elements: [1.1 7. 3.24 4.6 ]
Minimum of all matrix elements: [1. 5. 3. 4.]
Maximum of all matrix elements: [0.1 2. 0.24 0.6 ]
Mean of all matrix elements: [0.55 3.5 1.62 2.3 ]
| MIT | S01 - Bootcamp and Binary Classification/SLU07 - Regression with Linear Regression/Example notebook.ipynb | claury/sidecar-academy-batch2 |
As an example, imagine that you have a matrix of shape (n_samples, n_features), where each row represents all the features for one sample. Then , to average over the samples, we do: | m1 = np.array([[ .1, 1.], [2., 5.], [ 3., .24], [4., .6]])
print('Initial matrix: \n{}'.format(m1))
print('\n')
print('Sample 1: {}'.format(m1[0, :]))
print('Sample 2: {}'.format(m1[1, :]))
print('Sample 3: {}'.format(m1[2, :]))
print('Sample 4: {}'.format(m1[3, :]))
print('\n')
print('Average over samples: \n{}... | Initial matrix:
[[0.1 1. ]
[2. 5. ]
[3. 0.24]
[4. 0.6 ]]
Sample 1: [0.1 1. ]
Sample 2: [2. 5.]
Sample 3: [3. 0.24]
Sample 4: [4. 0.6]
Average over samples:
[2.275 1.71 ]
| MIT | S01 - Bootcamp and Binary Classification/SLU07 - Regression with Linear Regression/Example notebook.ipynb | claury/sidecar-academy-batch2 |
Other statistical functions behave in a similar manner, so it is important to know how to work the axis of these objects. e) Multiple matrix operations e.1) Element wise operationsSeveral operations available work at the element level, this is, if we have two matrices A and B:$$ A = \begin{bmatrix} a & b \\ c & d \... | m1 = np.array([[ .1, 1., 2., 5.], [ 3., .24, 4., .6]])
m2 = np.array([[ .1, 4., .25, .1], [ 2., 1.5, .42, -1.]])
print('Matrix 1: \n{}'.format(m1))
print('Matrix 2: \n{}'.format(m1))
print('\n')
print('Sum: \n{}'.format(m1 + m2))
print('\n')
print('Difference: \n{}'.format(m1 - m2))
print('\n')
print('M... | Matrix 1:
[[0.1 1. 2. 5. ]
[3. 0.24 4. 0.6 ]]
Matrix 2:
[[0.1 1. 2. 5. ]
[3. 0.24 4. 0.6 ]]
Sum:
[[ 0.2 5. 2.25 5.1 ]
[ 5. 1.74 4.42 -0.4 ]]
Difference:
[[ 0. -3. 1.75 4.9 ]
[ 1. -1.26 3.58 1.6 ]]
Multiplication:
[[ 0.01 4. 0.5 0.5 ]
[ 6. 0.36 1.68 -0.6 ... | MIT | S01 - Bootcamp and Binary Classification/SLU07 - Regression with Linear Regression/Example notebook.ipynb | claury/sidecar-academy-batch2 |
For these operations, ideally your matrices should have the same dimensions. An exception to this is when you have one of the elements that can be [broadcasted](https://numpy.org/doc/stable/user/basics.broadcasting.html) over the other. However we won't cover that in these examples. e.2) Matrix multiplicationAlthough ... | m1 = np.array([[ .1, 1., 2., 5.], [ 3., .24, 4., .6]])
m2 = np.array([[ .1, 4.], [.25, .1], [ 2., 1.5], [.42, -1.]])
print('Matrix 1: \n{}'.format(m1))
print('Matrix 2: \n{}'.format(m1))
print('\n')
print('Matrix multiplication: \n{}'.format(np.matmul(m1, m2)))
m1 = np.array([[ .1, 4.], [.25, .1], [ 2., ... | Matrix 1:
[[ 0.1 4. ]
[ 0.25 0.1 ]
[ 2. 1.5 ]
[ 0.42 -1. ]]
Matrix 2:
[[ 0.1 4. ]
[ 0.25 0.1 ]
[ 2. 1.5 ]
[ 0.42 -1. ]]
Matrix multiplication:
[[12.01 1.06 16.2 ]
[ 0.325 0.274 0.9 ]
[ 4.7 2.36 10. ]
[-2.958 0.18 -3.16 ]]
| MIT | S01 - Bootcamp and Binary Classification/SLU07 - Regression with Linear Regression/Example notebook.ipynb | claury/sidecar-academy-batch2 |
Notice that in both operations the matrix multiplication of shapes `(k, l)` and `(m, n)` yields a matrix of dimensions `(k, n)`. Additionally, for this operation to be possible, the inner dimensions need to match, this is `l == m` . See what happens if we try to multiply matrices with incompatible dimensions: | m1 = np.array([[ .1, 4., 3.], [.25, .1, 1.], [ 2., 1.5, .5], [.42, -1., 4.3]])
m2 = np.array([[ .1, 1., 2.], [ 3., .24, 4.]])
print('Matrix 1: \n{}'.format(m1))
print('Shape: {}'.format(m1.shape))
print('Matrix 2: \n{}'.format(m1))
print('Shape: {}'.format(m2.shape))
print('\n')
try:
m3 = np.matmul(m... | Matrix 1:
[[ 0.1 4. 3. ]
[ 0.25 0.1 1. ]
[ 2. 1.5 0.5 ]
[ 0.42 -1. 4.3 ]]
Shape: (4, 3)
Matrix 2:
[[ 0.1 4. 3. ]
[ 0.25 0.1 1. ]
[ 2. 1.5 0.5 ]
[ 0.42 -1. 4.3 ]]
Shape: (2, 3)
Matrix multiplication raised the following error: matmul: Input operand 1 has a mismatch in its co... | MIT | S01 - Bootcamp and Binary Classification/SLU07 - Regression with Linear Regression/Example notebook.ipynb | claury/sidecar-academy-batch2 |
numpy | def add(image, c):
return uint8(np.clip(float64(image) + c, 0, 255)) | _____no_output_____ | MIT | util/imutil.ipynb | shoulderhu/azure-image-ipy |
matplotlib | def matplot(img, title=None, cmap=None, figsize=None):
col = len(img)
if figsize is None:
plt.figure(figsize=(col * 4, col * 4))
else:
plt.figure(figsize=figsize)
for i, j in enumerate(img):
plt.subplot(1, col, i + 1)
plt.axis("off")
if titl... | _____no_output_____ | MIT | util/imutil.ipynb | shoulderhu/azure-image-ipy |
Chapter 2 | def imread(fname):
return io.imread(os.path.join("/home/nbuser/library/", "Image", "read", fname))
def imsave(fname, image):
io.imsave(os.path.join("/home/nbuser/library/", "Image", "save", fname), image) | _____no_output_____ | MIT | util/imutil.ipynb | shoulderhu/azure-image-ipy |
Chapter 3 | def spatial_resolution(image, scale):
return rescale(rescale(image, 1 / scale), scale, order=0)
def grayslice(image, n):
image = img_as_ubyte(image)
v = 256 // n
return image // v * v | _____no_output_____ | MIT | util/imutil.ipynb | shoulderhu/azure-image-ipy |
Chapter 4 | def imhist(image, equal=False):
if equal:
image = img_as_ubyte(equalize_hist(image))
f = plt.figure()
f.show(plt.hist(image.flatten(), bins=256)) | _____no_output_____ | MIT | util/imutil.ipynb | shoulderhu/azure-image-ipy |
Chapter 5 | def unsharp(alpha=0.2):
A1 = array([[-1, 1, -1],
[1, 1, 1],
[-1, 1, -1]], dtype=float64)
A2 = array([[0, -1, 0],
[-1, 5, -1],
[0, -1, 0]], dtype=float64)
return (alpha * A1 + A2) / (alpha + 1) | _____no_output_____ | MIT | util/imutil.ipynb | shoulderhu/azure-image-ipy |
Chapter 6 | ne = array([[1, 1, 0], [1, 1, 0], [0, 0, 0]])
bi = array([[1, 2, 1], [2, 4, 2], [1, 2, 1]]) / 4
bc = array([[1, 4, 6, 4, 1],
[4, 16, 24, 16, 4],
[6, 24, 35, 24, 6],
[4, 16, 24, 16, 4],
[1, 4, 6, 4, 1]]) / 64
def zeroint(img):
r, c = img.shape
res = zeros((r*2,... | _____no_output_____ | MIT | util/imutil.ipynb | shoulderhu/azure-image-ipy |
Chapter 7 | def fftformat(F):
for f in F:
print("%8.4f %+.4fi" % (f.real, f.imag))
def fftshow(f, type="log"):
if type == "log":
return rescale_intensity(np.log(1 + abs(f)), out_range=(0, 1))
elif type == "abs":
return rescale_intensity(abs(f), out_range=(0, 1))
def circle_mask(img, type, lh, D=... | _____no_output_____ | MIT | util/imutil.ipynb | shoulderhu/azure-image-ipy |
Chapter 8 | def periodic_noise(img, s=None):
if "numpy" not in str(type(s)):
r, c = img.shape
x, y = np.mgrid[0:r, 0:c].astype(float64)
s = np.sin(x / 3 + y / 3) + 1
return (2 * img_as_float(img) + s / 2) / 3
def outlier_filter(img, D=0.5):
av = array([[1, 1, 1],
[1, 0, 1],
... | _____no_output_____ | MIT | util/imutil.ipynb | shoulderhu/azure-image-ipy |
Chapter 9 | def threshold_adaptive(img, cut):
r, c = img.shape
w = c // cut
starts = range(0, c - 1, w)
ends = range(w, c + 1, w)
z = zeros((r, c))
for i in range(cut):
tmp = img[:, starts[i]:ends[i]]
z[:, starts[i]:ends[i]] = tmp > threshold_otsu(tmp)
return z
def zerocross(img):
... | _____no_output_____ | MIT | util/imutil.ipynb | shoulderhu/azure-image-ipy |
Chapter 10 | sq = square(3)
cr = array([[0, 1, 0],
[1, 1, 1],
[0, 1, 0]])
sq
cr
def internal_boundary(a, b):
'''
A - (A erosion B)
'''
return a - binary_erosion(a, b)
def external_boundary(a, b):
'''
(A dilation B) - A
'''
return binary_dilation(a, b) - a
def morphological_g... | _____no_output_____ | MIT | util/imutil.ipynb | shoulderhu/azure-image-ipy |
MethodsWe've already seen a few example of methods when learning about Object and Data Structure Types in Python. Methods are essentially functions built into objects. Later on in the course we will learn about how to create our own objects and methods using Object Oriented Programming (OOP) and classes.Methods will pe... | # Create a simple list
l = [1,2,3,4,5] | _____no_output_____ | BSD-3-Clause | notebooks/Complete-Python-Bootcamp-master/Methods.ipynb | sheldon-cheah/cppkernel |
Fortunately, with iPython and the Jupyter Notebook we can quickly see all the possible methods using the tab key. The methods for a list are:* append* count* extend* insert* pop* remove* reverse* sortLet's try out a few of them: append() allows us to add elements to the end of a list: | l.append(6)
l | _____no_output_____ | BSD-3-Clause | notebooks/Complete-Python-Bootcamp-master/Methods.ipynb | sheldon-cheah/cppkernel |
Great! Now how about count()? The count() method will count the number of occurences of an element in a list. | # Check how many times 2 shows up in the list
l.count(2) | _____no_output_____ | BSD-3-Clause | notebooks/Complete-Python-Bootcamp-master/Methods.ipynb | sheldon-cheah/cppkernel |
You can always use Shift+Tab in the Jupyter Notebook to get more help about the method. In general Python you can use the help() function: | help(l.count) | Help on built-in function count:
count(...)
L.count(value) -> integer -- return number of occurrences of value
| BSD-3-Clause | notebooks/Complete-Python-Bootcamp-master/Methods.ipynb | sheldon-cheah/cppkernel |
Exercise 3: Order of ExecutionThis Jupyter notebook has been written to partner with Lesson 1 - Machine Learning Toolkit | print('Hello World!!')
print(hello_world)
hello_world = 'Hello World!!!!!!!!!!!!' | _____no_output_____ | MIT | Chapter 1 - Machine Learning Toolkit/Exercise 3 - Order of Execution.ipynb | doc-E-brown/Applied-Supervised-Learning-with-Python |
Task 4: Support Vector Machines_All credit for the code examples of this notebook goes to the book "Hands-On Machine Learning with Scikit-Learn & TensorFlow" by A. Geron. Modifications were made and text was added by K. Zoch in preparation for the hands-on sessions._ Setup First, import a few common modules, ensure M... | # Common imports
import numpy as np
import os
# to make this notebook's output stable across runs
np.random.seed(42)
# To plot pretty figures
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rc('axes', labelsize=14)
mpl.rc('xtick', labelsize=12)
mpl.rc('ytick', labelsize=12)
# Function... | _____no_output_____ | Apache-2.0 | task_7_SVMs.ipynb | knutzk/handson-ml |
Large margin *vs* margin violations This code example contains two linear support vector machine classifiers ([LinearSVC](https://scikit-learn.org/stable/modules/generated/sklearn.svm.LinearSVC.html), which are initialised with different hyperparameter C. The used dataset is the iris dataset also shown in the lecture ... | import numpy as np
from sklearn import datasets
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import LinearSVC
# Load the dataset and store the necessary features/labels in X/y.
iris = datasets.load_iris()
X = iris["data"][:, (2, 3)] # petal length, petal widt... | _____no_output_____ | Apache-2.0 | task_7_SVMs.ipynb | knutzk/handson-ml |
Polynomial features vs. polynomial kernelsLet's create a non-linear dataset, for which we can compare two approaches: (1) adding polynomial features to the model, (2) using a polynomial kernel (see exercise sheet). First, create some random data. | from sklearn.datasets import make_moons
X, y = make_moons(n_samples=100, noise=0.15, random_state=42)
def plot_dataset(X, y, axes):
plt.plot(X[:, 0][y==0], X[:, 1][y==0], "bs")
plt.plot(X[:, 0][y==1], X[:, 1][y==1], "g^")
plt.axis(axes)
plt.grid(True, which='both')
plt.xlabel(r"$x_1$", fontsize=20)... | _____no_output_____ | Apache-2.0 | task_7_SVMs.ipynb | knutzk/handson-ml |
Now let's first look at a linear SVM classifier that uses polynomial features. We will implement them through a pipeline including scaling of the inputs. What happens if you increase the degrees of polynomial features? Does the model get better? How is the computing time affected? Hint: you might have to increase the `... | from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
polynomial_svm_clf = Pipeline([
("poly_features", PolynomialFeatures(degree=3)),
("scaler", StandardScaler()),
("svm_clf", LinearSVC(C=10, loss="hinge", max_iter=1000, random_state=42))
])
polynomial... | _____no_output_____ | Apache-2.0 | task_7_SVMs.ipynb | knutzk/handson-ml |
Now let's try the same without polynomial features, but a polynomial kernel instead. What is the fundamental difference between these two approaches? How do they scale in terms of computing time: (1) as a function of the number of features, (2) as a function of the number of instances?1. Try out different degrees for t... | from sklearn.svm import SVC
# Let's make one pipeline with polynomial kernel degree 3.
poly_kernel_svm_clf = Pipeline([
("scaler", StandardScaler()),
("svm_clf", SVC(kernel="poly", degree=3, coef0=1, C=5))
])
poly_kernel_svm_clf.fit(X, y)
# And another pipeline with polynomial kernel degree 10.
po... | _____no_output_____ | Apache-2.0 | task_7_SVMs.ipynb | knutzk/handson-ml |
Gaussian kernels Before trying the following piece of code which implements Gaussian RBF (Radial Basis Function) kernels, remember _similarity features_ that were discussed in the lecture:1. What are similarity features? What is the idea of adding a "landmark"?2. If similarity features help to increase the power of th... | from sklearn.svm import SVC
# Set up multiple values for gamma and hyperparameter C
# and create a list of value pairs.
gamma1, gamma2 = 0.1, 5
C1, C2 = 0.001, 1000
hyperparams = (gamma1, C1), (gamma1, C2), (gamma2, C1), (gamma2, C2)
# Store multiple SVM classifiers in a list with these sets of
# hyperparameters. Fo... | _____no_output_____ | Apache-2.0 | task_7_SVMs.ipynb | knutzk/handson-ml |
RegressionThe following code implements the support vector regression class from Scikit-Learn ([SVR](https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVR.html)). Here are a couple of questions (some of which require changes to the code, others are just conceptual:1. Quick recap: whereas the SVC class trie... | # Generate some random data (degree = 2).
np.random.seed(42)
m = 100
X = 2 * np.random.rand(m, 1) - 1
y = (0.2 + 0.1 * X + 0.5 * X**2 + np.random.randn(m, 1)/10).ravel()
# Import the support vector regression class and create two
# instances with different hyperparameters.
from sklearn.svm import SVR
svm_poly_reg1 = ... | _____no_output_____ | Apache-2.0 | task_7_SVMs.ipynb | knutzk/handson-ml |
Create TensorFlow Deep Neural Network Model**Learning Objective**- Create a DNN model using the high-level Estimator API IntroductionWe'll begin by modeling our data using a Deep Neural Network. To achieve this we will use the high-level Estimator API in Tensorflow. Have a look at the various models available through... | PROJECT = "cloud-training-demos" # Replace with your PROJECT
BUCKET = "cloud-training-bucket" # Replace with your BUCKET
REGION = "us-central1" # Choose an available region for Cloud MLE
TFVERSION = "1.14" # TF version for CMLE to use
import os
os.environ["BUCKET"] = BUCKET
os.environ["PROJE... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/05_review/3_tensorflow_dnn.ipynb | Glairly/introduction_to_tensorflow |
Create TensorFlow model using TensorFlow's Estimator API We'll begin by writing an input function to read the data and define the csv column names and label column. We'll also set the default csv column values and set the number of training steps. | import shutil
import numpy as np
import tensorflow as tf
print(tf.__version__)
CSV_COLUMNS = "weight_pounds,is_male,mother_age,plurality,gestation_weeks".split(',')
LABEL_COLUMN = "weight_pounds"
# Set default values for each CSV column
DEFAULTS = [[0.0], ["null"], [0.0], ["null"], [0.0]]
TRAIN_STEPS = 1000 | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/05_review/3_tensorflow_dnn.ipynb | Glairly/introduction_to_tensorflow |
Create the input functionNow we are ready to create an input function using the Dataset API. | def read_dataset(filename_pattern, mode, batch_size = 512):
def _input_fn():
def decode_csv(value_column):
columns = tf.decode_csv(records = value_column, record_defaults = DEFAULTS)
features = dict(zip(CSV_COLUMNS, columns))
label = features.pop(LABEL_COLUMN)
... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/05_review/3_tensorflow_dnn.ipynb | Glairly/introduction_to_tensorflow |
Create the feature columnsNext, we define the feature columns | def get_categorical(name, values):
return tf.feature_column.indicator_column(
categorical_column = tf.feature_column.categorical_column_with_vocabulary_list(key = name, vocabulary_list = values))
def get_cols():
# Define column types
return [\
get_categorical("is_male", ["True", "False", ... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/05_review/3_tensorflow_dnn.ipynb | Glairly/introduction_to_tensorflow |
Create the Serving Input function To predict with the TensorFlow model, we also need a serving input function. This will allow us to serve prediction later using the predetermined inputs. We will want all the inputs from our user. | def serving_input_fn():
feature_placeholders = {
"is_male": tf.placeholder(dtype = tf.string, shape = [None]),
"mother_age": tf.placeholder(dtype = tf.float32, shape = [None]),
"plurality": tf.placeholder(dtype = tf.string, shape = [None]),
"gestation_weeks": tf.placeholder(dtype = t... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/05_review/3_tensorflow_dnn.ipynb | Glairly/introduction_to_tensorflow |
Create the model and run training and evaluationLastly, we'll create the estimator to train and evaluate. In the cell below, we'll set up a `DNNRegressor` estimator and the train and evaluation operations. | def train_and_evaluate(output_dir):
EVAL_INTERVAL = 300
run_config = tf.estimator.RunConfig(
save_checkpoints_secs = EVAL_INTERVAL,
keep_checkpoint_max = 3)
estimator = tf.estimator.DNNRegressor(
model_dir = output_dir,
feature_columns = get_cols(),
hidden_units... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/05_review/3_tensorflow_dnn.ipynb | Glairly/introduction_to_tensorflow |
Finally, we train the model! | # Run the model
shutil.rmtree(path = "babyweight_trained_dnn", ignore_errors = True) # start fresh each time
train_and_evaluate("babyweight_trained_dnn") | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/05_review/3_tensorflow_dnn.ipynb | Glairly/introduction_to_tensorflow |
Compare different DEMs for individual glaciers For most glaciers in the world there are several digital elevation models (DEM) which cover the respective glacier. In OGGM we have currently implemented 10 different open access DEMs to choose from. Some are regional and only available in certain areas (e.g. Greenland or... | # The RGI Id of the glaciers you want to look for
# Use the original shapefiles or the GLIMS viewer to check for the ID: https://www.glims.org/maps/glims
rgi_id = 'RGI60-11.00897'
# The default is to test for all sources available for this glacier
# Set to a list of source names to override this
sources = None
# Where... | _____no_output_____ | BSD-3-Clause | notebooks/dem_comparison.ipynb | pat-schmitt/tutorials |
Check input and set up | # The sources can be given as parameters
if sources is not None and isinstance(sources, str):
sources = sources.split(',')
# Plotting directory as well
if not plot_dir:
plot_dir = './' + rgi_id
import os
plot_dir = os.path.abspath(plot_dir)
import pandas as pd
import numpy as np
from oggm import cfg, utils, wor... | _____no_output_____ | BSD-3-Clause | notebooks/dem_comparison.ipynb | pat-schmitt/tutorials |
Download the data using OGGM utility functions Note that you could reach the same goal by downloading the data manually from https://cluster.klima.uni-bremen.de/~oggm/gdirs/oggm_v1.4/rgitopo/ | # URL of the preprocessed GDirs
gdir_url = 'https://cluster.klima.uni-bremen.de/~oggm/gdirs/oggm_v1.4/rgitopo/'
# We use OGGM to download the data
gdir = init_glacier_directories([rgi_id], from_prepro_level=1, prepro_border=10,
prepro_rgi_version='62', prepro_base_url=gdir_url)[0] | _____no_output_____ | BSD-3-Clause | notebooks/dem_comparison.ipynb | pat-schmitt/tutorials |
Read the DEMs and store them all in a dataset | if sources is None:
sources = [src for src in os.listdir(gdir.dir) if src in utils.DEM_SOURCES]
print('RGI ID:', rgi_id)
print('Available DEM sources:', sources)
print('Plotting directory:', plot_dir)
# We use xarray to store the data
ods = xr.Dataset()
for src in sources:
demfile = os.path.join(gdir.dir, src) ... | _____no_output_____ | BSD-3-Clause | notebooks/dem_comparison.ipynb | pat-schmitt/tutorials |
Raw topography data | smap = salem.graphics.Map(gdir.grid, countries=False)
smap.set_shapefile(gdir.read_shapefile('outlines'))
smap.set_plot_params(cmap='topo')
smap.set_lonlat_contours(add_tick_labels=False)
smap.set_plot_params(vmin=np.nanquantile([ods[s].min() for s in sources], 0.25),
vmax=np.nanquantile([ods[s].ma... | _____no_output_____ | BSD-3-Clause | notebooks/dem_comparison.ipynb | pat-schmitt/tutorials |
Shaded relief | fig = plt.figure(figsize=(x_size, y_size))
grid = AxesGrid(fig, 111,
nrows_ncols=(n_rows, n_cols),
axes_pad=0.7,
cbar_mode='none',
cbar_location='right',
cbar_pad=0.1
)
smap.set_plot_params(cmap='Blues')
smap.set_shapefile()... | _____no_output_____ | BSD-3-Clause | notebooks/dem_comparison.ipynb | pat-schmitt/tutorials |
Slope | fig = plt.figure(figsize=(x_size, y_size))
grid = AxesGrid(fig, 111,
nrows_ncols=(n_rows, n_cols),
axes_pad=0.7,
cbar_mode='each',
cbar_location='right',
cbar_pad=0.1
)
smap.set_topography();
smap.set_plot_params(vmin=0, vm... | _____no_output_____ | BSD-3-Clause | notebooks/dem_comparison.ipynb | pat-schmitt/tutorials |
Some simple statistics about the DEMs | df = pd.DataFrame()
for s in sources:
df[s] = ods[s].data.flatten()[ods.mask.data.flatten() == 1]
dfs = pd.DataFrame()
for s in sources:
dfs[s] = ods[s + '_slope'].data.flatten()[ods.mask.data.flatten() == 1]
df.describe() | _____no_output_____ | BSD-3-Clause | notebooks/dem_comparison.ipynb | pat-schmitt/tutorials |
Comparison matrix plot | # Table of differences between DEMS
df_diff = pd.DataFrame()
done = []
for s1, s2 in itertools.product(sources, sources):
if s1 == s2:
continue
if (s2, s1) in done:
continue
df_diff[s1 + '-' + s2] = df[s1] - df[s2]
done.append((s1, s2))
# Decide on plot levels
max_diff = df_diff.quantile... | _____no_output_____ | BSD-3-Clause | notebooks/dem_comparison.ipynb | pat-schmitt/tutorials |
Comparison scatter plot | import seaborn as sns
sns.set(style="ticks")
l1, l2 = (utils.nicenumber(df.min().min(), binsize=50, lower=True),
utils.nicenumber(df.max().max(), binsize=50, lower=False))
def plot_unity(xdata, ydata, **kwargs):
points = np.linspace(l1, l2, 100)
plt.gca().plot(points, points, color='k', marker=None... | _____no_output_____ | BSD-3-Clause | notebooks/dem_comparison.ipynb | pat-schmitt/tutorials |
Table statistics | df.describe()
df.corr()
df_diff.describe()
df_diff.abs().describe() | _____no_output_____ | BSD-3-Clause | notebooks/dem_comparison.ipynb | pat-schmitt/tutorials |
Created from https://github.com/awslabs/amazon-sagemaker-examples/blob/master/introduction_to_amazon_algorithms/random_cut_forest/random_cut_forest.ipynb | import boto3
import botocore
import sagemaker
import sys
bucket = 'tdk-awsml-sagemaker-data.io-dev' # <--- specify a bucket you have access to
prefix = ''
execution_role = sagemaker.get_execution_role()
# check if the bucket exists
try:
boto3.Session().client('s3').head_bucket(Bucket=bucket)
except botocore.e... | _____no_output_____ | MIT | code/sagemaker_rcf.ipynb | tkeech1/aws_ml |
Predicting employee attrition rate in organizations Using PyCaret Step 1: Importing the data | import numpy as np
import pandas as pd
from pycaret.regression import *
train_csv = '../dataset/Train.csv'
test_csv = '../dataset/Test.csv'
train_data = pd.read_csv(train_csv)
test_data = pd.read_csv(test_csv) | _____no_output_____ | MIT | notebooks/.ipynb_checkpoints/pycaret-final-checkpoint.ipynb | ChandrakanthNethi/predict-the-employee-attrition-rate-in-organizations |
Step 2: Setup | reg = setup(train_data, target='Attrition_rate', ignore_features=['Employee_ID']) |
Setup Succesfully Completed!
| MIT | notebooks/.ipynb_checkpoints/pycaret-final-checkpoint.ipynb | ChandrakanthNethi/predict-the-employee-attrition-rate-in-organizations |
Step 3: Tuning the models | compare_models() | _____no_output_____ | MIT | notebooks/.ipynb_checkpoints/pycaret-final-checkpoint.ipynb | ChandrakanthNethi/predict-the-employee-attrition-rate-in-organizations |
Step 4: Selecting a model | model = create_model('br')
print(model) | BayesianRidge(alpha_1=1e-06, alpha_2=1e-06, alpha_init=None,
compute_score=False, copy_X=True, fit_intercept=True,
lambda_1=1e-06, lambda_2=1e-06, lambda_init=None, n_iter=300,
normalize=False, tol=0.001, verbose=False)
| MIT | notebooks/.ipynb_checkpoints/pycaret-final-checkpoint.ipynb | ChandrakanthNethi/predict-the-employee-attrition-rate-in-organizations |
Step 5: Predicting on test data | predictions = predict_model(model, data = test_data)
predictions
predictions.rename(columns={"Label": "Attrition_rate"}, inplace=True)
predictions[['Employee_ID', 'Attrition_rate']].to_csv('../predictions.csv', index=False) | _____no_output_____ | MIT | notebooks/.ipynb_checkpoints/pycaret-final-checkpoint.ipynb | ChandrakanthNethi/predict-the-employee-attrition-rate-in-organizations |
from google.colab import drive
drive.mount('/content/drive')
pip install nilearn
pip install tables
pip install git+https://www.github.com/farizrahman4u/keras-contrib.git
pip install SimpleITK
#pip install tensorflow==1.4
import tensorflow as tf
from tensorflow.python.framework import ops
import tensorflow.compat.v1 a... | _____no_output_____ | MIT | test.ipynb | sima97/unihobby | |
#Matriz
v = np.array([[1],[2],[3]])# Vector que es de una sola columna
v1=np.array([1,2,3])#Vector fila
print(M)
print(v)
print(v1)
print (M.shape)
print (v.shape)#nos indica que t... | _____no_output_____ | MIT | Repaso_algebra_LinealHeidy.ipynb | 1966hs/MujeresDigitales |
)
print (v.T.dot(v))
v1=np.array([3,-3,1])
v2=np.array([4,9,2])
print (np.cross(v1, v2, axisa=0, axisb=0).T)
print (np.multiply(M, v))
print (np.multiply(v, v))
| [[14]
[32]
[50]]
[[14]]
[-15 -2 39]
[[ 1 2 3]
[ 8 10 12]
[21 24 27]]
[[1]
[4]
[9]]
| MIT | Repaso_algebra_LinealHeidy.ipynb | 1966hs/MujeresDigitales |
Transpuesta$$C_{mxn}=A_{nxm}^T$$$$c_{ij}=a_{ji}$$$$(A+B)^T = A^T + B^T$$$$(AB)^T = B^T A^T$$Si $A=A^T$ entonces A es **simetrica** | M
print(M.T)#transpuestas
print(v.T)
#el determinante es para saber el valor de la matriz | _____no_output_____ | MIT | Repaso_algebra_LinealHeidy.ipynb | 1966hs/MujeresDigitales |

#hacer una matriz que multiplcarse por si misma da la matriz identidad
#que todo lo diagonal es 1 y el resto 0
v1 = np.array([3, 0, 2])
v2 = np.array([2, 0, -2])
v3 = np.array([0, 1, 1])
M = np.vstack([v1, v2, v3])#creamos la matriz apartir de esos valores y luego los unimos
print (np.linalg.inv(M))#pa... | 10.000000000000002
| MIT | Repaso_algebra_LinealHeidy.ipynb | 1966hs/MujeresDigitales |
**Definicion de Variables** | a= np.array([1,1,1])
b= np.array([2,2,2])
#Multiplcacion de los elementos
#(lo hace elemento a elemento )
a*b
#metodo multiplicacion de elementos:
np.multiply(a,b)
#Metodo multiplicacion de matrices
#2*1+2*1+2*1
np.matmul(a,b)
#Metodo producto punto
#similar a la multiplcacion matricial
np.dot(a,b)
#Metodo producto cr... | _____no_output_____ | MIT | Repaso_algebra_LinealHeidy.ipynb | 1966hs/MujeresDigitales |
**Definicion de Matrices** | a = np.array([[1,2], [2,3]])
b = np.array([[3,4],[5,6]])
print(a)
print(b)
#Multiplicacion elemento a elemento
a*b
#mulitplicacion punto a punto
#Metodo multiplicacion elemento
np.multiply(a,b)
#Metodo multiplcacion matricial
#1*3+2*5=13
#1*4+2*4=16
#2*3+3*5=21
#2*4+3*6=26
np.matmul(a,b)
#Metodo producto punto | _____no_output_____ | MIT | Repaso_algebra_LinealHeidy.ipynb | 1966hs/MujeresDigitales |
**Inversion de matrices** | a= np.array([[1,1,1],[0,2,5],[2,5,-1]])#esta es mi matriz
b= np.linalg.inv(a)#aqui la estoy invirtiendo
b
np.matmul(a,b)#cuando la multiplico matricialmente me da una matriz identidad
#cuando iniverto una matriz y luego la multilplico me da una identidad
v1= np.array([3,0,2])
v2=np.array([2,0,-2])
v3=np.array([0,1,1]... | _____no_output_____ | MIT | Repaso_algebra_LinealHeidy.ipynb | 1966hs/MujeresDigitales |
Valores y vectores propiosUn valor propio $\lambda$ y un vector propio $\vec{u}$ satisfacen$$Au = \lambda u$$Donde A es una matriz cuadrada.Reordenando la ecuacion anterior tenemos el sistema:$$Au -\lambda u = (A- \lambda I)u =0$$El cual tiene solucion si y solo si $det(A-\lambda I)=0$1. Los valores propios son las ra... | #TENGO UN ESPACIO DE DOS DIMENSIONES Y LO QUE HAGO
#ES DISTORSIONAR ESE ESPACIO DIMENSIAL
v1 = np.array([0, 1])
v2 = np.array([-2, -3])
M = np.vstack([v1, v2])
eigvals, eigvecs= np.linalg.eig(M)
print(eigvals)#caractericas de las matrices
print(eigvecs)
#valor propio es un valor que podemos crear y hacer la solucion d... | _____no_output_____ | MIT | Repaso_algebra_LinealHeidy.ipynb | 1966hs/MujeresDigitales |
Setup | from day1 import puzzle1
from day1 import puzzle1slow
from day1 import puzzle1maybefaster
from day2 import puzzle2
from day2 import puzzle2slow
from day2 import puzzle2maybefaster
sample_input1 = [1721, 979, 366, 299, 675, 1456]
input1 = open("input1.txt", "r").read()
input1_list = [int(x) for x in input1.split("\n") ... | _____no_output_____ | MIT | AdventofCode2020/timings/Timing Day 1.ipynb | evan-freeman/puzzles |
Puzzle Timings | %%timeit
puzzle1(input1_list)
%%timeit
puzzle1maybefaster(input1_list)
%%timeit
puzzle1slow(input1_list)
%%timeit
puzzle2(input1_list)
%%timeit
puzzle2maybefaster(input1_list)
%%timeit
puzzle2slow(input1_list) | 393 ms ± 60.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
| MIT | AdventofCode2020/timings/Timing Day 1.ipynb | evan-freeman/puzzles |
Sample Input Timings | %%timeit
puzzle1(sample_input1)
%%timeit
puzzle1slow(sample_input1)
%%timeit
puzzle1maybefaster(sample_input1)
%%timeit
puzzle2(sample_input1)
%%timeit
puzzle2maybefaster(sample_input1)
%%timeit
puzzle2slow(sample_input1) | 6.02 µs ± 166 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
| MIT | AdventofCode2020/timings/Timing Day 1.ipynb | evan-freeman/puzzles |
📃 Solution of Exercise M6.01The aim of this notebook is to investigate if we can tune the hyperparametersof a bagging regressor and evaluate the gain obtained.We will load the California housing dataset and split it into a training anda testing set. | from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
data, target = fetch_california_housing(as_frame=True, return_X_y=True)
target *= 100 # rescale the target in k$
data_train, data_test, target_train, target_test = train_test_split(
data, target, random_stat... | _____no_output_____ | CC-BY-4.0 | notebooks/M6-ensemble_sol_01.ipynb | datagistips/scikit-learn-mooc |
NoteIf you want a deeper overview regarding this dataset, you can refer to theAppendix - Datasets description section at the end of this MOOC. Create a `BaggingRegressor` and provide a `DecisionTreeRegressor`to its parameter `base_estimator`. Train the regressor and evaluate itsstatistical performance on the testing se... | from sklearn.metrics import mean_absolute_error
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import BaggingRegressor
tree = DecisionTreeRegressor()
bagging = BaggingRegressor(base_estimator=tree, n_jobs=-1)
bagging.fit(data_train, target_train)
target_predicted = bagging.predict(data_test)
prin... | _____no_output_____ | CC-BY-4.0 | notebooks/M6-ensemble_sol_01.ipynb | datagistips/scikit-learn-mooc |
Now, create a `RandomizedSearchCV` instance using the previous model andtune the important parameters of the bagging regressor. Find the bestparameters and check if you are able to find a set of parameters thatimprove the default regressor still using the mean absolute error as ametric.TipYou can list the bagging regr... | for param in bagging.get_params().keys():
print(param)
from scipy.stats import randint
from sklearn.model_selection import RandomizedSearchCV
param_grid = {
"n_estimators": randint(10, 30),
"max_samples": [0.5, 0.8, 1.0],
"max_features": [0.5, 0.8, 1.0],
"base_estimator__max_depth": randint(3, 10),... | Mean absolute error after tuning of the bagging regressor:
40.29 k$
| CC-BY-4.0 | notebooks/M6-ensemble_sol_01.ipynb | datagistips/scikit-learn-mooc |
Recommendations with MovieTweetings: Collaborative FilteringOne of the most popular methods for making recommendations is **collaborative filtering**. In collaborative filtering, you are using the collaboration of user-item recommendations to assist in making new recommendations. There are two main methods of perfor... | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tests as t
from scipy.sparse import csr_matrix
from IPython.display import HTML
%matplotlib inline
# Read in the datasets
movies = pd.read_csv('movies_clean.csv')
reviews = pd.read_csv('reviews_clean.csv')
del movies['Unnamed: 0']
del revi... | user_id movie_id rating timestamp date month_1 \
0 1 68646 10 1381620027 2013-10-12 23:20:27 0
1 1 113277 10 1379466669 2013-09-18 01:11:09 0
2 2 422720 8 1412178746 2014-10-01 15:52:26 0
3 2 454876 ... | MIT | lessons/Recommendations/1_Intro_to_Recommendations/4_Collaborative Filtering - Solution.ipynb | callezenwaka/DSND_Term2 |
Measures of SimilarityWhen using **neighborhood** based collaborative filtering, it is important to understand how to measure the similarity of users or items to one another. There are a number of ways in which we might measure the similarity between two vectors (which might be two users or two items). In this noteb... | user_items = reviews[['user_id', 'movie_id', 'rating']]
user_items.head() | _____no_output_____ | MIT | lessons/Recommendations/1_Intro_to_Recommendations/4_Collaborative Filtering - Solution.ipynb | callezenwaka/DSND_Term2 |
Creating the User-Item MatrixIn order to create the user-items matrix (like the one above), I personally started by using a [pivot table](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html). However, I quickly ran into a memory error (a common theme throughout this notebook). I will help y... | # Create user-by-item matrix
user_by_movie = user_items.groupby(['user_id', 'movie_id'])['rating'].max().unstack() | _____no_output_____ | MIT | lessons/Recommendations/1_Intro_to_Recommendations/4_Collaborative Filtering - Solution.ipynb | callezenwaka/DSND_Term2 |
Check your results below to make sure your matrix is ready for the upcoming sections. | assert movies.shape[0] == user_by_movie.shape[1], "Oh no! Your matrix should have {} columns, and yours has {}!".format(movies.shape[0], user_by_movie.shape[1])
assert reviews.user_id.nunique() == user_by_movie.shape[0], "Oh no! Your matrix should have {} rows, and yours has {}!".format(reviews.user_id.nunique(), user_... | _____no_output_____ | MIT | lessons/Recommendations/1_Intro_to_Recommendations/4_Collaborative Filtering - Solution.ipynb | callezenwaka/DSND_Term2 |
`2.` Now that you have a matrix of users by movies, use this matrix to create a dictionary where the key is each user and the value is an array of the movies each user has rated. | # Create a dictionary with users and corresponding movies seen
def movies_watched(user_id):
'''
INPUT:
user_id - the user_id of an individual as int
OUTPUT:
movies - an array of movies the user has watched
'''
movies = user_by_movie.loc[user_id][user_by_movie.loc[user_id].isnull() == False]... | _____no_output_____ | MIT | lessons/Recommendations/1_Intro_to_Recommendations/4_Collaborative Filtering - Solution.ipynb | callezenwaka/DSND_Term2 |
`3.` If a user hasn't rated more than 2 movies, we consider these users "too new". Create a new dictionary that only contains users who have rated more than 2 movies. This dictionary will be used for all the final steps of this workbook. | # Remove individuals who have watched 2 or fewer movies - don't have enough data to make recs
def create_movies_to_analyze(movies_seen, lower_bound=2):
'''
INPUT:
movies_seen - a dictionary where each key is a user_id and the value is an array of movie_ids
lower_bound - (an int) a user must have more... | _____no_output_____ | MIT | lessons/Recommendations/1_Intro_to_Recommendations/4_Collaborative Filtering - Solution.ipynb | callezenwaka/DSND_Term2 |
Calculating User SimilaritiesNow that you have set up the **movies_to_analyze** dictionary, it is time to take a closer look at the similarities between users. Below is the pseudocode for how I thought about determining the similarity between users:```for user1 in movies_to_analyze for user2 in movies_to_analyze ... | def compute_correlation(user1, user2):
'''
INPUT
user1 - int user_id
user2 - int user_id
OUTPUT
the correlation between the matching ratings between the two users
'''
# Pull movies for each user
movies1 = movies_to_analyze[user1]
movies2 = movies_to_analyze[user2]
#... | _____no_output_____ | MIT | lessons/Recommendations/1_Intro_to_Recommendations/4_Collaborative Filtering - Solution.ipynb | callezenwaka/DSND_Term2 |
Why the NaN's?If the function you wrote passed all of the tests, then you have correctly set up your function to calculate the correlation between any two users. `5.` But one question is, why are we still obtaining **NaN** values? As you can see in the code cell above, users 2 and 104 have a correlation of **NaN**. ... | # Which movies did both user 2 and user 104 see?
set_2 = set(movies_to_analyze[2])
set_104 = set(movies_to_analyze[104])
set_2.intersection(set_104)
# What were the ratings for each user on those movies?
print(user_by_movie.loc[2, set_2.intersection(set_104)])
print(user_by_movie.loc[104, set_2.intersection(set_104)]) | _____no_output_____ | MIT | lessons/Recommendations/1_Intro_to_Recommendations/4_Collaborative Filtering - Solution.ipynb | callezenwaka/DSND_Term2 |
`6.` Because the correlation coefficient proved to be less than optimal for relating user ratings to one another, we could instead calculate the euclidean distance between the ratings. I found [this post](https://stackoverflow.com/questions/1401712/how-can-the-euclidean-distance-be-calculated-with-numpy) particularly ... | def compute_euclidean_dist(user1, user2):
'''
INPUT
user1 - int user_id
user2 - int user_id
OUTPUT
the euclidean distance between user1 and user2
'''
# Pull movies for each user
movies1 = movies_to_analyze[user1]
movies2 = movies_to_analyze[user2]
# Find Similar Mov... | _____no_output_____ | MIT | lessons/Recommendations/1_Intro_to_Recommendations/4_Collaborative Filtering - Solution.ipynb | callezenwaka/DSND_Term2 |
Using the Nearest Neighbors to Make RecommendationsIn the previous question, you read in **df_dists**. Therefore, you have a measure of distance between each user and every other user. This dataframe holds every possible pairing of users, as well as the corresponding euclidean distance.Because of the **NaN** values th... | def find_closest_neighbors(user):
'''
INPUT:
user - (int) the user_id of the individual you want to find the closest users
OUTPUT:
closest_neighbors - an array of the id's of the users sorted from closest to farthest away
'''
# I treated ties as arbitrary and just kept whichever was ... | _____no_output_____ | MIT | lessons/Recommendations/1_Intro_to_Recommendations/4_Collaborative Filtering - Solution.ipynb | callezenwaka/DSND_Term2 |
Now What?If you made it this far, you have successfully implemented a solution to making recommendations using collaborative filtering. `8.` Let's do a quick recap of the steps taken to obtain recommendations using collaborative filtering. | # Check your understanding of the results by correctly filling in the dictionary below
a = "pearson's correlation and spearman's correlation"
b = 'item based collaborative filtering'
c = "there were too many ratings to get a stable metric"
d = 'user based collaborative filtering'
e = "euclidean distance and pearson's c... | _____no_output_____ | MIT | lessons/Recommendations/1_Intro_to_Recommendations/4_Collaborative Filtering - Solution.ipynb | callezenwaka/DSND_Term2 |
Additionally, let's take a closer look at some of the results. There are two solution files that you read in to check your results, and you created these objects* **df_dists** - a dataframe of user1, user2, euclidean distance between the two users* **all_recs_sol** - a dictionary of all recommendations (key = user, va... | a = 567
b = 1503
c = 1319
d = 1325
e = 2526710
f = 0
g = 'Use another method to make recommendations - content based, knowledge based, or model based collaborative filtering'
sol_dict2 = {
'For how many pairs of users were we not able to obtain a measure of similarity using correlation?': e,
'For how many pair... | _____no_output_____ | MIT | lessons/Recommendations/1_Intro_to_Recommendations/4_Collaborative Filtering - Solution.ipynb | callezenwaka/DSND_Term2 |
Feature Engineering notebook This is a demo notebook to play with feature engineering toolkit. In this notebook we will see some capabilities of the toolkit like filling missing values, PCA, Random Projections, Normalizing values, and etc. | %load_ext autoreload
%autoreload 1
%matplotlib inline
from Pipeline import Pipeline
from Compare import Compare
from StructuredData.LoadCSV import LoadCSV
from StructuredData.MissingValues import MissingValues
from StructuredData.Normalize import Normalize
from StructuredData.Factorize import Factorize
from StructuredD... | _____no_output_____ | MIT | Feature_Engineering_Toolkit_demo_features_v1.ipynb | jassimran/Feature-Engineering-Toolkit |
Filling missing valuesBy default, median of the values of the column is applied for filling out the missing values | pipelineObj = Pipeline([MissingValues()])
new_df = pipelineObj(df, '0')
new_df.head(5) | _____no_output_____ | MIT | Feature_Engineering_Toolkit_demo_features_v1.ipynb | jassimran/Feature-Engineering-Toolkit |
However, the imputation type is a configurable parameter to customize it as per needs. | pipelineObj = Pipeline([MissingValues(imputation_type = 'mean')])
new_df = pipelineObj(df, '0')
new_df.head(5) | _____no_output_____ | MIT | Feature_Engineering_Toolkit_demo_features_v1.ipynb | jassimran/Feature-Engineering-Toolkit |
Normalize dataBy default, Min max normalization is applied. Please note that assertion has been set such that normlization cant be applied if there rae missing values in that column. This is part of validation phase | pipelineObj = Pipeline([MissingValues(), Normalize(['1','2', '3'])])
new_df = pipelineObj(df, '0')
df.head(5) | _____no_output_____ | MIT | Feature_Engineering_Toolkit_demo_features_v1.ipynb | jassimran/Feature-Engineering-Toolkit |
Factorize dataEncode the object as an enumerated type or categorical variable for column 4 and 8, but we must remove missing values before Factorizing | pipelineObj = Pipeline([MissingValues(), Factorize(['4','8'])])
new_df = pipelineObj(df, '0')
new_df.head(5) | _____no_output_____ | MIT | Feature_Engineering_Toolkit_demo_features_v1.ipynb | jassimran/Feature-Engineering-Toolkit |
Principal Component Analysis Use n_components to play around with how many dimensions you want to keep. Please note that assertions will validate if a data frame has any missing values before applying PCA. In the below example, the pipeline first removed missing values before applying PCA. | pipelineObj = Pipeline([MissingValues(imputation_type = 'mean'), PCAFeatures(n_components = 5)])
pca_df = pipelineObj(df, '0')
pca_df.head(5) | _____no_output_____ | MIT | Feature_Engineering_Toolkit_demo_features_v1.ipynb | jassimran/Feature-Engineering-Toolkit |
Random ProjectionsUse n_components to play around with how many dimensions you want to keep. Please note that assertions will validate if a data frame has any missing values before applying Random Projections. Type of projections can be specified as an argument, by default GaussianRandomProjection is applied. In the b... | pipelineObj = Pipeline([MissingValues(imputation_type = 'mean'), RandomProjection(n_components = 6, proj_type = 'Sparse')])
new_df = pipelineObj(df, '0')
new_df.head() | _____no_output_____ | MIT | Feature_Engineering_Toolkit_demo_features_v1.ipynb | jassimran/Feature-Engineering-Toolkit |
Download the modified CSVAt any point, the new tranformed features can be downloaded using below command | csv_path = './DemoData/synthetic_classification_transformed.csv'
new_df.to_csv(csv_path) | _____no_output_____ | MIT | Feature_Engineering_Toolkit_demo_features_v1.ipynb | jassimran/Feature-Engineering-Toolkit |
Figure 4: NIRCam Grism + Filter Sensitivities ($1^{st}$ order) *** Table of Contents1. [Information](Information)2. [Imports](Imports)3. [Data](Data)4. [Generate the First Order Grism + Filter Sensitivity Plot](Generate-the-First-Order-Grism-+-Filter-Sensitivity-Plot)5. [Issues](Issues)6. [About this Notebook](About-t... | import os
import pylab
import numpy as np
from astropy.io import ascii, fits
from astropy.table import Table
from scipy.optimize import fmin
from scipy.interpolate import interp1d
import requests
import matplotlib.pyplot as plt
%matplotlib inline | _____no_output_____ | BSD-3-Clause | nircam_jdox/nircam_grisms/figure4_sensitivity.ipynb | aliciacanipe/nircam_jdox |
Data Data Location: The data is stored in a NIRCam JDox Box folder here:[ST-INS-NIRCAM -> JDox -> nircam_grisms](https://stsci.box.com/s/wu9mo54vi957x50rdirlcg9zkkr3xiaw) | files = [('https://stsci.box.com/shared/static/i0a9dkp02nnuw6w0xcfd7b42ctxfb8es.fits', 'NIRCam.F250M.R.A.1st.sensitivity.fits'),
('https://stsci.box.com/shared/static/vfnyk9veote92dz1edpbu83un5n20rsw.fits', 'NIRCam.F250M.R.A.2nd.sensitivity.fits'),
('https://stsci.box.com/shared/static/ssvltwzt7f4y5lf... | _____no_output_____ | BSD-3-Clause | nircam_jdox/nircam_grisms/figure4_sensitivity.ipynb | aliciacanipe/nircam_jdox |
Load the data(The next cell assumes you downloaded the data into your ```Users/$(logname)/``` home directory) | if os.environ.get('LOGNAME') is None:
raise ValueError("WARNING: LOGNAME environment variable not set!")
box_directory = os.path.join("/Users/", os.environ['LOGNAME'], "box_data")
box_directory
if not os.path.isdir(box_directory):
try:
os.mkdir(box_directory)
except:
raise OSError("Unable... | _____no_output_____ | BSD-3-Clause | nircam_jdox/nircam_grisms/figure4_sensitivity.ipynb | aliciacanipe/nircam_jdox |
Generate the First Order Grism + Filter Sensitivity Plot Define some convenience functions | def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return array[idx]
def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return array[idx]
def find_mid(w,s,w0,thr=0.05):
fct = interp1d(w,s,bounds_error=None,fill_value='extrapolate')
def func(x):
#prin... | _____no_output_____ | BSD-3-Clause | nircam_jdox/nircam_grisms/figure4_sensitivity.ipynb | aliciacanipe/nircam_jdox |
Create the plots | f, ax1 = plt.subplots(1, figsize=(15, 10))
NUM_COLORS = len(filters)
cm = pylab.get_cmap('tab10')
grism = "R"
mod = "A"
for i,fname in zip(range(NUM_COLORS),filenames):
color = cm(1.*i/NUM_COLORS)
d = fits.open(fname)
w = d[1].data["WAVELENGTH"]
s = d[1].data["SENSITIVITY"]/(1e17)
ax1.plot(w,s,la... | _____no_output_____ | BSD-3-Clause | nircam_jdox/nircam_grisms/figure4_sensitivity.ipynb | aliciacanipe/nircam_jdox |
Figure option 2: filter name positions | f, ax1 = plt.subplots(1, figsize=(15, 10))
thr = 0.05 # 5% of peak boundaries
NUM_COLORS = len(filters)
cm = pylab.get_cmap('tab10')
for i,fil,fname in zip(range(NUM_COLORS),filters,filenames):
color = cm(1.*i/NUM_COLORS)
d = fits.open(fname)
w = d[1].data["WAVELENGTH"]
s = d[1].data["SENSITIVITY"]/... | _____no_output_____ | BSD-3-Clause | nircam_jdox/nircam_grisms/figure4_sensitivity.ipynb | aliciacanipe/nircam_jdox |
**Version 2**: disable unfreezing for speed setup for pytorch/xla on TPU | import os
import collections
from datetime import datetime, timedelta
os.environ["XRT_TPU_CONFIG"] = "tpu_worker;0;10.0.0.2:8470"
_VersionConfig = collections.namedtuple('_VersionConfig', 'wheels,server')
VERSION = "torch_xla==nightly"
CONFIG = {
'torch_xla==nightly': _VersionConfig('nightly', 'XRT-dev{}'.format(... |
The following NEW packages will be installed:
libomp5
0 upgraded, 1 newly installed, 0 to remove and 32 not upgraded.
Need to get 228 kB of archives.
After this operation, 750 kB of additional disk space will be used.
Get:1 http://deb.debian.org/debian stretch/main amd64 libomp5 amd64 3.9.1-1 [228 kB]
Fet... | MIT | image/2. Flower Classification with TPUs/kaggle/fast-pytorch-xla-for-tpu-with-multiprocessing.ipynb | nishchalnishant/Completed_Kaggle_competitions |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.