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 |
|---|---|---|---|---|---|
ロジスティック回帰を適用した結果を表示します。 | w0, w1, w2, err_rate, result = run_logistic(train_set)
fig = plt.figure(figsize=(6, 12))
subplot = fig.add_subplot(2,1,1)
show_result(subplot, train_set, w0, w1, w2, err_rate)
subplot = fig.add_subplot(2,1,2)
draw_roc(subplot, result) | _____no_output_____ | Apache-2.0 | 05-roc_curve.ipynb | RXV06021/test_ml4se_colab |
*Python Machine Learning 2nd Edition* by [Sebastian Raschka](https://sebastianraschka.com), Packt Publishing Ltd. 2017Code Repository: https://github.com/rasbt/python-machine-learning-book-2nd-editionCode License: [MIT License](https://github.com/rasbt/python-machine-learning-book-2nd-edition/blob/master/LICENSE.txt) ... | %load_ext watermark
%watermark -a "Sebastian Raschka" -u -d -v -p numpy,pandas,matplotlib,scipy,sklearn | Sebastian Raschka
last updated: 2017-08-25
CPython 3.6.1
IPython 6.1.0
numpy 1.12.1
pandas 0.20.3
matplotlib 2.0.2
scipy 0.19.1
sklearn 0.19.0
| MIT | python-machine-learning-book-2nd-edition/code/ch11/ch11.ipynb | gopala-kr/ds-notebooks |
*The use of `watermark` is optional. You can install this IPython extension via "`pip install watermark`". For more information, please see: https://github.com/rasbt/watermark.* Overview - [Grouping objects by similarity using k-means](Grouping-objects-by-similarity-using-k-means) - [K-means clustering using scikit-... | from IPython.display import Image
%matplotlib inline | _____no_output_____ | MIT | python-machine-learning-book-2nd-edition/code/ch11/ch11.ipynb | gopala-kr/ds-notebooks |
Grouping objects by similarity using k-means K-means clustering using scikit-learn | from sklearn.datasets import make_blobs
X, y = make_blobs(n_samples=150,
n_features=2,
centers=3,
cluster_std=0.5,
shuffle=True,
random_state=0)
import matplotlib.pyplot as plt
plt.scatter(X[:, 0], X[:, 1],
c='... | _____no_output_____ | MIT | python-machine-learning-book-2nd-edition/code/ch11/ch11.ipynb | gopala-kr/ds-notebooks |
A smarter way of placing the initial cluster centroids using k-means++ ... Hard versus soft clustering ... Using the elbow method to find the optimal number of clusters | print('Distortion: %.2f' % km.inertia_)
distortions = []
for i in range(1, 11):
km = KMeans(n_clusters=i,
init='k-means++',
n_init=10,
max_iter=300,
random_state=0)
km.fit(X)
distortions.append(km.inertia_)
plt.plot(range(1, 11), distortion... | _____no_output_____ | MIT | python-machine-learning-book-2nd-edition/code/ch11/ch11.ipynb | gopala-kr/ds-notebooks |
Quantifying the quality of clustering via silhouette plots | import numpy as np
from matplotlib import cm
from sklearn.metrics import silhouette_samples
km = KMeans(n_clusters=3,
init='k-means++',
n_init=10,
max_iter=300,
tol=1e-04,
random_state=0)
y_km = km.fit_predict(X)
cluster_labels = np.unique(y_km)
n_cluster... | _____no_output_____ | MIT | python-machine-learning-book-2nd-edition/code/ch11/ch11.ipynb | gopala-kr/ds-notebooks |
Comparison to "bad" clustering: | km = KMeans(n_clusters=2,
init='k-means++',
n_init=10,
max_iter=300,
tol=1e-04,
random_state=0)
y_km = km.fit_predict(X)
plt.scatter(X[y_km == 0, 0],
X[y_km == 0, 1],
s=50,
c='lightgreen',
edgecolor='black',
... | _____no_output_____ | MIT | python-machine-learning-book-2nd-edition/code/ch11/ch11.ipynb | gopala-kr/ds-notebooks |
Organizing clusters as a hierarchical tree Grouping clusters in bottom-up fashion | Image(filename='./images/11_05.png', width=400)
import pandas as pd
import numpy as np
np.random.seed(123)
variables = ['X', 'Y', 'Z']
labels = ['ID_0', 'ID_1', 'ID_2', 'ID_3', 'ID_4']
X = np.random.random_sample([5, 3])*10
df = pd.DataFrame(X, columns=variables, index=labels)
df | _____no_output_____ | MIT | python-machine-learning-book-2nd-edition/code/ch11/ch11.ipynb | gopala-kr/ds-notebooks |
Performing hierarchical clustering on a distance matrix | from scipy.spatial.distance import pdist, squareform
row_dist = pd.DataFrame(squareform(pdist(df, metric='euclidean')),
columns=labels,
index=labels)
row_dist | _____no_output_____ | MIT | python-machine-learning-book-2nd-edition/code/ch11/ch11.ipynb | gopala-kr/ds-notebooks |
We can either pass a condensed distance matrix (upper triangular) from the `pdist` function, or we can pass the "original" data array and define the `metric='euclidean'` argument in `linkage`. However, we should not pass the squareform distance matrix, which would yield different distance values although the overall cl... | # 1. incorrect approach: Squareform distance matrix
from scipy.cluster.hierarchy import linkage
row_clusters = linkage(row_dist, method='complete', metric='euclidean')
pd.DataFrame(row_clusters,
columns=['row label 1', 'row label 2',
'distance', 'no. of items in clust.'],
... | _____no_output_____ | MIT | python-machine-learning-book-2nd-edition/code/ch11/ch11.ipynb | gopala-kr/ds-notebooks |
Attaching dendrograms to a heat map | # plot row dendrogram
fig = plt.figure(figsize=(8, 8), facecolor='white')
axd = fig.add_axes([0.09, 0.1, 0.2, 0.6])
# note: for matplotlib < v1.5.1, please use orientation='right'
row_dendr = dendrogram(row_clusters, orientation='left')
# reorder data with respect to clustering
df_rowclust = df.iloc[row_dendr['leaves... | _____no_output_____ | MIT | python-machine-learning-book-2nd-edition/code/ch11/ch11.ipynb | gopala-kr/ds-notebooks |
Applying agglomerative clustering via scikit-learn | from sklearn.cluster import AgglomerativeClustering
ac = AgglomerativeClustering(n_clusters=3,
affinity='euclidean',
linkage='complete')
labels = ac.fit_predict(X)
print('Cluster labels: %s' % labels)
ac = AgglomerativeClustering(n_clusters=2,
... | Cluster labels: [0 1 1 0 0]
| MIT | python-machine-learning-book-2nd-edition/code/ch11/ch11.ipynb | gopala-kr/ds-notebooks |
Locating regions of high density via DBSCAN | Image(filename='images/11_13.png', width=500)
from sklearn.datasets import make_moons
X, y = make_moons(n_samples=200, noise=0.05, random_state=0)
plt.scatter(X[:, 0], X[:, 1])
plt.tight_layout()
#plt.savefig('images/11_14.png', dpi=300)
plt.show() | _____no_output_____ | MIT | python-machine-learning-book-2nd-edition/code/ch11/ch11.ipynb | gopala-kr/ds-notebooks |
K-means and hierarchical clustering: | f, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 3))
km = KMeans(n_clusters=2, random_state=0)
y_km = km.fit_predict(X)
ax1.scatter(X[y_km == 0, 0], X[y_km == 0, 1],
edgecolor='black',
c='lightblue', marker='o', s=40, label='cluster 1')
ax1.scatter(X[y_km == 1, 0], X[y_km == 1, 1],
ed... | _____no_output_____ | MIT | python-machine-learning-book-2nd-edition/code/ch11/ch11.ipynb | gopala-kr/ds-notebooks |
Density-based clustering: | from sklearn.cluster import DBSCAN
db = DBSCAN(eps=0.2, min_samples=5, metric='euclidean')
y_db = db.fit_predict(X)
plt.scatter(X[y_db == 0, 0], X[y_db == 0, 1],
c='lightblue', marker='o', s=40,
edgecolor='black',
label='cluster 1')
plt.scatter(X[y_db == 1, 0], X[y_db == 1, 1],
... | _____no_output_____ | MIT | python-machine-learning-book-2nd-edition/code/ch11/ch11.ipynb | gopala-kr/ds-notebooks |
Summary ... ---Readers may ignore the next cell. | ! python ../.convert_notebook_to_script.py --input ch11.ipynb --output ch11.py | [NbConvertApp] Converting notebook ch11.ipynb to script
[NbConvertApp] Writing 14002 bytes to ch11.py
| MIT | python-machine-learning-book-2nd-edition/code/ch11/ch11.ipynb | gopala-kr/ds-notebooks |
Batch NormalizationOne way to make deep networks easier to train is to use more sophisticated optimization procedures such as SGD+momentum, RMSProp, or Adam. Another strategy is to change the architecture of the network to make it easier to train. One idea along these lines is batch normalization which was proposed by... | # As usual, a bit of setup
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.solver import Solver
%matplotlib inline
p... | 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,)
| MIT | assignment2/BatchNormalization.ipynb | lalithnag/cs231n |
Batch normalization: forwardIn the file `cs231n/layers.py`, implement the batch normalization forward pass in the function `batchnorm_forward`. Once you have done so, run the following to test your implementation.Referencing the paper linked to above would be helpful! | # Check the training-time forward pass by checking means and variances
# of features both before and after batch normalization
# Simulate the forward pass for a two-layer network
np.random.seed(231)
N, D1, D2, D3 = 200, 50, 60, 3
X = np.random.randn(N, D1)
W1 = np.random.randn(D1, D2)
W2 = np.random.randn(D2, D3)
a... | After batch normalization (test-time):
means: [-0.03927353 -0.04349151 -0.10452686]
stds: [1.01531399 1.01238345 0.97819961]
| MIT | assignment2/BatchNormalization.ipynb | lalithnag/cs231n |
Batch normalization: backwardNow implement the backward pass for batch normalization in the function `batchnorm_backward`.To derive the backward pass you should write out the computation graph for batch normalization and backprop through each of the intermediate nodes. Some intermediates may have multiple outgoing bra... | # Gradient check batchnorm backward pass
np.random.seed(231)
N, D = 4, 5
x = 5 * np.random.randn(N, D) + 12
gamma = np.random.randn(D)
beta = np.random.randn(D)
dout = np.random.randn(N, D)
bn_param = {'mode': 'train'}
fx = lambda x: batchnorm_forward(x, gamma, beta, bn_param)[0]
fg = lambda a: batchnorm_forward(x, a,... | dx error: 1.6674604875341426e-09
dgamma error: 7.417225040694815e-13
dbeta error: 2.379446949959628e-12
| MIT | assignment2/BatchNormalization.ipynb | lalithnag/cs231n |
Batch normalization: alternative backwardIn class we talked about two different implementations for the sigmoid backward pass. One strategy is to write out a computation graph composed of simple operations and backprop through all intermediate values. Another strategy is to work out the derivatives on paper. For examp... | np.random.seed(231)
N, D = 100, 500
x = 5 * np.random.randn(N, D) + 12
gamma = np.random.randn(D)
beta = np.random.randn(D)
dout = np.random.randn(N, D)
bn_param = {'mode': 'train'}
out, cache = batchnorm_forward(x, gamma, beta, bn_param)
t1 = time.time()
dx1, dgamma1, dbeta1 = batchnorm_backward(dout, cache)
t2 = ti... | dx difference: 9.890497291190823e-13
dgamma difference: 0.0
dbeta difference: 0.0
speedup: 3.19x
| MIT | assignment2/BatchNormalization.ipynb | lalithnag/cs231n |
Fully Connected Nets with Batch NormalizationNow that you have a working implementation for batch normalization, go back to your `FullyConnectedNet` in the file `cs231n/classifiers/fc_net.py`. Modify your implementation to add batch normalization.Concretely, when the `normalization` flag is set to `"batchnorm"` in the... | np.random.seed(231)
N, D, H1, H2, C = 2, 15, 20, 30, 10
X = np.random.randn(N, D)
y = np.random.randint(C, size=(N,))
# You should expect losses between 1e-4~1e-10 for W,
# losses between 1e-08~1e-10 for b,
# and losses between 1e-08~1e-09 for beta and gammas.
for reg in [0, 3.14]:
print('Running check with reg = '... | Running check with reg = 0
Initial loss: 2.2611955101340957
W1 relative error: 1.10e-04
W2 relative error: 3.11e-06
W3 relative error: 4.05e-10
b1 relative error: 4.44e-08
b2 relative error: 2.22e-08
b3 relative error: 1.01e-10
beta1 relative error: 7.33e-09
beta2 relative error: 1.89e-09
gamma1 relative error: 6.96e... | MIT | assignment2/BatchNormalization.ipynb | lalithnag/cs231n |
Batchnorm for deep networksRun the following to train a six-layer network on a subset of 1000 training examples both with and without batch normalization. | np.random.seed(231)
# Try training a very deep net with batchnorm
hidden_dims = [100, 100, 100, 100, 100]
num_train = 1000
small_data = {
'X_train': data['X_train'][:num_train],
'y_train': data['y_train'][:num_train],
'X_val': data['X_val'],
'y_val': data['y_val'],
}
weight_scale = 2e-2
bn_model = FullyConnec... | (Iteration 1 / 200) loss: 2.340974
(Epoch 0 / 10) train acc: 0.107000; val_acc: 0.107000
(Epoch 1 / 10) train acc: 0.324000; val_acc: 0.264000
(Iteration 21 / 200) loss: 1.996679
(Epoch 2 / 10) train acc: 0.426000; val_acc: 0.303000
(Iteration 41 / 200) loss: 2.038482
(Epoch 3 / 10) train acc: 0.483000; val_acc: 0.3130... | MIT | assignment2/BatchNormalization.ipynb | lalithnag/cs231n |
Run the following to visualize the results from two networks trained above. You should find that using batch normalization helps the network to converge much faster. | def plot_training_history(title, label, baseline, bn_solvers, plot_fn, bl_marker='.', bn_marker='.', labels=None):
"""utility function for plotting training history"""
plt.title(title)
plt.xlabel(label)
bn_plots = [plot_fn(bn_solver) for bn_solver in bn_solvers]
bl_plot = plot_fn(baseline)
num_b... | _____no_output_____ | MIT | assignment2/BatchNormalization.ipynb | lalithnag/cs231n |
Batch normalization and initializationWe will now run a small experiment to study the interaction of batch normalization and weight initialization.The first cell will train 8-layer networks both with and without batch normalization using different scales for weight initialization. The second layer will plot training a... | np.random.seed(231)
# Try training a very deep net with batchnorm
hidden_dims = [50, 50, 50, 50, 50, 50, 50]
num_train = 1000
small_data = {
'X_train': data['X_train'][:num_train],
'y_train': data['y_train'][:num_train],
'X_val': data['X_val'],
'y_val': data['y_val'],
}
bn_solvers_ws = {}
solvers_ws = {}
weigh... | _____no_output_____ | MIT | assignment2/BatchNormalization.ipynb | lalithnag/cs231n |
Inline Question 1:Describe the results of this experiment. How does the scale of weight initialization affect models with/without batch normalization differently, and why? Answer:Bacth norm is robust to weight initialisatio scale upto a point - after which both break. Batch normalization and batch sizeWe will now ru... | def run_batchsize_experiments(normalization_mode):
np.random.seed(231)
# Try training a very deep net with batchnorm
hidden_dims = [100, 100, 100, 100, 100]
num_train = 1000
small_data = {
'X_train': data['X_train'][:num_train],
'y_train': data['y_train'][:num_train],
'X_val': data... | _____no_output_____ | MIT | assignment2/BatchNormalization.ipynb | lalithnag/cs231n |
Inline Question 2:Describe the results of this experiment. What does this imply about the relationship between batch normalization and batch size? Why is this relationship observed? Answer:Batchnorm is sensitive to batch size because mean and variance depend on these minibatches of data. Layer NormalizationBatch norm... | N, D = x.shape
print('X-shape :', x.shape)
mean = np.mean(x, axis = 1, keepdims = True)/D
print('mean-shape :', mean.shape)
#xmu = (x.T - mu.T).T
#print('xmu-shape :', xmu.shape)
temp = np.ones((1,D))
munew = np.matmul(mean, temp)
xmu = x - munew
print('xmu-shape :', xmu.shape)
# Check the training-time forward pass... | dx error: 2.107277492956569e-09
dgamma error: 4.519489546032799e-12
dbeta error: 2.5842537629899423e-12
| MIT | assignment2/BatchNormalization.ipynb | lalithnag/cs231n |
Layer Normalization and batch sizeWe will now run the previous batch size experiment with layer normalization instead of batch normalization. Compared to the previous experiment, you should see a markedly smaller influence of batch size on the training history! | ln_solvers_bsize, solver_bsize, batch_sizes = run_batchsize_experiments('layernorm')
plt.subplot(2, 1, 1)
plot_training_history('Training accuracy (Layer Normalization)','Epoch', solver_bsize, ln_solvers_bsize, \
lambda x: x.train_acc_history, bl_marker='-^', bn_marker='-o', labels=batch_sizes)
p... | No normalization: batch size = 5
Normalization: batch size = 5
Normalization: batch size = 10
Normalization: batch size = 50
| MIT | assignment2/BatchNormalization.ipynb | lalithnag/cs231n |
More Information about Synestias[When Earth and the Moon Were One](https://www.scientificamerican.com/article/when-earth-and-the-moon-were-one/)by Simon J. Lock and Sarah T. StewartScientific American, July 2019. Check your local library for anonline or print subscription.[Where did the Moon come from? A New Theory](h... | from IPython.display import YouTubeVideo
YouTubeVideo('7uRPPaYuu44', width=640, height=360) | _____no_output_____ | MIT | synestia-book/_build/jupyter_execute/docs/MoreInformation.ipynb | ststewart/synestiabook2 |
Introduction to Neural NetworksIn this notebook you will learn how to create and use a neural network to classify articles of clothing. To achieve this, we will use a sub module of TensorFlow called *keras*.*This guide is based on the following TensorFlow documentation.*https://www.tensorflow.org/tutorials/keras/classi... | %tensorflow_version 2.x # this line is not required unless you are in a notebook
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt | _____no_output_____ | Unlicense | AI-ML/Tensorflow fcc/Instructor notebooks/Neural Networks.ipynb | f-dufour/cheat-sheets-and-snippets |
DatasetFor this tutorial we will use the MNIST Fashion Dataset. This is a dataset that is included in keras.This dataset includes 60,000 images for training and 10,000 images for validation/testing. | fashion_mnist = keras.datasets.fashion_mnist # load dataset
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data() # split into tetsing and training | _____no_output_____ | Unlicense | AI-ML/Tensorflow fcc/Instructor notebooks/Neural Networks.ipynb | f-dufour/cheat-sheets-and-snippets |
Let's have a look at this data to see what we are working with. | train_images.shape | _____no_output_____ | Unlicense | AI-ML/Tensorflow fcc/Instructor notebooks/Neural Networks.ipynb | f-dufour/cheat-sheets-and-snippets |
So we've got 60,000 images that are made up of 28x28 pixels (784 in total). | train_images[0,23,23] # let's have a look at one pixel | _____no_output_____ | Unlicense | AI-ML/Tensorflow fcc/Instructor notebooks/Neural Networks.ipynb | f-dufour/cheat-sheets-and-snippets |
Our pixel values are between 0 and 255, 0 being black and 255 being white. This means we have a grayscale image as there are no color channels. | train_labels[:10] # let's have a look at the first 10 training labels | _____no_output_____ | Unlicense | AI-ML/Tensorflow fcc/Instructor notebooks/Neural Networks.ipynb | f-dufour/cheat-sheets-and-snippets |
Our labels are integers ranging from 0 - 9. Each integer represents a specific article of clothing. We'll create an array of label names to indicate which is which. | class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] | _____no_output_____ | Unlicense | AI-ML/Tensorflow fcc/Instructor notebooks/Neural Networks.ipynb | f-dufour/cheat-sheets-and-snippets |
Fianlly let's look at what some of these images look like! | plt.figure()
plt.imshow(train_images[1])
plt.colorbar()
plt.grid(False)
plt.show() | _____no_output_____ | Unlicense | AI-ML/Tensorflow fcc/Instructor notebooks/Neural Networks.ipynb | f-dufour/cheat-sheets-and-snippets |
Data PreprocessingThe last step before creating our model is to *preprocess* our data. This simply means applying some prior transformations to our data before feeding it the model. In this case we will simply scale all our greyscale pixel values (0-255) to be between 0 and 1. We can do this by dividing each value in t... | train_images = train_images / 255.0
test_images = test_images / 255.0 | _____no_output_____ | Unlicense | AI-ML/Tensorflow fcc/Instructor notebooks/Neural Networks.ipynb | f-dufour/cheat-sheets-and-snippets |
Building the ModelNow it's time to build the model! We are going to use a keras *sequential* model with three different layers. This model represents a feed-forward neural network (one that passes values from left to right). We'll break down each layer and its architecture below. | model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)), # input layer (1)
keras.layers.Dense(128, activation='relu'), # hidden layer (2)
keras.layers.Dense(10, activation='softmax') # output layer (3)
]) | _____no_output_____ | Unlicense | AI-ML/Tensorflow fcc/Instructor notebooks/Neural Networks.ipynb | f-dufour/cheat-sheets-and-snippets |
**Layer 1:** This is our input layer and it will conist of 784 neurons. We use the flatten layer with an input shape of (28,28) to denote that our input should come in in that shape. The flatten means that our layer will reshape the shape (28,28) array into a vector of 784 neurons so that each pixel will be associated ... | model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']) | _____no_output_____ | Unlicense | AI-ML/Tensorflow fcc/Instructor notebooks/Neural Networks.ipynb | f-dufour/cheat-sheets-and-snippets |
Training the ModelNow it's finally time to train the model. Since we've already done all the work on our data this step is as easy as calling a single method. | model.fit(train_images, train_labels, epochs=10) # we pass the data, labels and epochs and watch the magic! | _____no_output_____ | Unlicense | AI-ML/Tensorflow fcc/Instructor notebooks/Neural Networks.ipynb | f-dufour/cheat-sheets-and-snippets |
Evaluating the ModelNow it's time to test/evaluate the model. We can do this quite easily using another builtin method from keras.The *verbose* argument is defined from the keras documentation as:"verbose: 0 or 1. Verbosity mode. 0 = silent, 1 = progress bar."(https://keras.io/models/sequential/) | test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=1)
print('Test accuracy:', test_acc) | _____no_output_____ | Unlicense | AI-ML/Tensorflow fcc/Instructor notebooks/Neural Networks.ipynb | f-dufour/cheat-sheets-and-snippets |
You'll likely notice that the accuracy here is lower than when training the model. This difference is reffered to as **overfitting**.And now we have a trained model that's ready to use to predict some values! Making PredictionsTo make predictions we simply need to pass an array of data in the form we've specified in th... | predictions = model.predict(test_images) | _____no_output_____ | Unlicense | AI-ML/Tensorflow fcc/Instructor notebooks/Neural Networks.ipynb | f-dufour/cheat-sheets-and-snippets |
This method returns to us an array of predictions for each image we passed it. Let's have a look at the predictions for image 1. | predictions[0] | _____no_output_____ | Unlicense | AI-ML/Tensorflow fcc/Instructor notebooks/Neural Networks.ipynb | f-dufour/cheat-sheets-and-snippets |
If we wan't to get the value with the highest score we can use a useful function from numpy called ```argmax()```. This simply returns the index of the maximium value from a numpy array. | np.argmax(predictions[0]) | _____no_output_____ | Unlicense | AI-ML/Tensorflow fcc/Instructor notebooks/Neural Networks.ipynb | f-dufour/cheat-sheets-and-snippets |
And we can check if this is correct by looking at the value of the cooresponding test label. | test_labels[0] | _____no_output_____ | Unlicense | AI-ML/Tensorflow fcc/Instructor notebooks/Neural Networks.ipynb | f-dufour/cheat-sheets-and-snippets |
Verifying PredictionsI've written a small function here to help us verify predictions with some simple visuals. | COLOR = 'white'
plt.rcParams['text.color'] = COLOR
plt.rcParams['axes.labelcolor'] = COLOR
def predict(model, image, correct_label):
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
prediction = model.predict(np.array([image]))
... | _____no_output_____ | Unlicense | AI-ML/Tensorflow fcc/Instructor notebooks/Neural Networks.ipynb | f-dufour/cheat-sheets-and-snippets |
MXNet Tutorial and Hand Written Digit RecognitionIn this tutorial we will go through the basic use case of MXNet and also touch on some advanced usages. This example is based on the MNIST dataset, which contains 70,000 images of hand written characters with 28-by-28 pixel size.This tutorial covers the following topics... | %matplotlib inline
import mxnet as mx
import numpy as np
import cv2
import matplotlib.pyplot as plt
import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG) | _____no_output_____ | Apache-2.0 | python/moved-from-mxnet/tutorial.ipynb | marktab/mxnet-notebooks |
Network DefinitionNow we can start constructing our network: | # Variables are place holders for input arrays. We give each variable a unique name.
data = mx.symbol.Variable('data')
# The input is fed to a fully connected layer that computes Y=WX+b.
# This is the main computation module in the network.
# Each layer also needs an unique name. We'll talk more about naming in the ne... | _____no_output_____ | Apache-2.0 | python/moved-from-mxnet/tutorial.ipynb | marktab/mxnet-notebooks |
We can visualize the network we just defined with MXNet's visualization module: | mx.viz.plot_network(mlp) | _____no_output_____ | Apache-2.0 | python/moved-from-mxnet/tutorial.ipynb | marktab/mxnet-notebooks |
Variable NamingMXNet requires variable names to follow certain conventions:- All input arrays have a name. This includes inputs (data & label) and model parameters (weight, bias, etc).- Arrays can be renamed by creating named variable. Otherwise, a default name is given as 'SymbolName_ArrayName'. For example, FullyCon... | mlp.list_arguments() | _____no_output_____ | Apache-2.0 | python/moved-from-mxnet/tutorial.ipynb | marktab/mxnet-notebooks |
Data LoadingWe fetch and load the MNIST dataset and partition it into two sets: 60000 examples for training and 10000 examples for testing. We also visualize a few examples to get an idea of what the dataset looks like. | from sklearn.datasets import fetch_mldata
mnist = fetch_mldata('MNIST original')
np.random.seed(1234) # set seed for deterministic ordering
p = np.random.permutation(mnist.data.shape[0])
X = mnist.data[p]
Y = mnist.target[p]
for i in range(10):
plt.subplot(1,10,i+1)
plt.imshow(X[i].reshape((28,28)), cmap='Grey... | _____no_output_____ | Apache-2.0 | python/moved-from-mxnet/tutorial.ipynb | marktab/mxnet-notebooks |
Now we can create data iterators from our MNIST data. A data iterator returns a batch of data examples each time for the network to process. MXNet provide a suite of basic DataIters for parsing different data format. Here we use NDArrayIter, which wraps around a numpy array and each time slice a chunk from it along the... | batch_size = 100
train_iter = mx.io.NDArrayIter(X_train, Y_train, batch_size=batch_size)
test_iter = mx.io.NDArrayIter(X_test, Y_test, batch_size=batch_size) | _____no_output_____ | Apache-2.0 | python/moved-from-mxnet/tutorial.ipynb | marktab/mxnet-notebooks |
TrainingWith the network and data source defined, we can finally start to train our model. We do this with MXNet's convenience wrapper for feed forward neural networks (it can also be made to handle RNNs with explicit unrolling). | model = mx.model.FeedForward(
ctx = mx.gpu(0), # Run on GPU 0
symbol = mlp, # Use the network we just defined
num_epoch = 10, # Train for 10 epochs
learning_rate = 0.1, # Learning rate
momentum = 0.9, # Momentum for SGD with momentum
wd = 0.00001) # Weight decay... | INFO:root:Start training with [gpu(0)]
INFO:root:Epoch[0] Batch [200] Speed: 70941.64 samples/sec Train-accuracy=0.389050
INFO:root:Epoch[0] Batch [400] Speed: 97857.94 samples/sec Train-accuracy=0.646450
INFO:root:Epoch[0] Batch [600] Speed: 70507.97 samples/sec Train-accuracy=0.743333
INFO:root:Epoch[0] Resetting Dat... | Apache-2.0 | python/moved-from-mxnet/tutorial.ipynb | marktab/mxnet-notebooks |
EvaluationAfter the model is trained, we can evaluate it on a held out test set.First, lets classity a sample image: | plt.imshow((X_test[0].reshape((28,28))*255).astype(np.uint8), cmap='Greys_r')
plt.show()
print 'Result:', model.predict(X_test[0:1])[0].argmax() | _____no_output_____ | Apache-2.0 | python/moved-from-mxnet/tutorial.ipynb | marktab/mxnet-notebooks |
We can also evaluate the model's accuracy on the entire test set: | print 'Accuracy:', model.score(test_iter)*100, '%' | Accuracy: 97.38 %
| Apache-2.0 | python/moved-from-mxnet/tutorial.ipynb | marktab/mxnet-notebooks |
Now, try if your model recognizes your own hand writing.Write a digit from 0 to 9 in the box below. Try to put your digit in the middle of the box. | # run hand drawing test
from IPython.display import HTML
def classify(img):
img = img[len('data:image/png;base64,'):].decode('base64')
img = cv2.imdecode(np.fromstring(img, np.uint8), -1)
img = cv2.resize(img[:,:,3], (28,28))
img = img.astype(np.float32).reshape((1, 784))/255.0
return model.predict... | _____no_output_____ | Apache-2.0 | python/moved-from-mxnet/tutorial.ipynb | marktab/mxnet-notebooks |
DebuggingDNNs can perform poorly for a lot of reasons, like learning rate too big/small, initialization too big/small, network structure not reasonable, etc. When this happens it's often helpful to print out the weights and intermediate outputs to understand what's going on. MXNet provides a monitor utility that does ... | def norm_stat(d):
"""The statistics you want to see.
We compute the L2 norm here but you can change it to anything you like."""
return mx.nd.norm(d)/np.sqrt(d.size)
mon = mx.mon.Monitor(
100, # Print every 100 batches
norm_stat, # The statistics function defined above
p... | INFO:root:Start training with [gpu(0)]
INFO:root:Batch: 1 fc1_backward_weight 0.000519617
INFO:root:Batch: 1 fc1_weight 0.00577777
INFO:root:Batch: 1 fc2_backward_weight 0.00164324
INFO:root:Batch: 1 fc2_weight 0.00577121
INFO:roo... | Apache-2.0 | python/moved-from-mxnet/tutorial.ipynb | marktab/mxnet-notebooks |
Under the hood: Custom Training Loop`mx.model.FeedForward` is a convenience wrapper for training standard feed forward networks. What if the model you are working with is more complicated? With MXNet, you can easily control every aspect of training by writing your own training loop.Neural network training typically ha... | # ==================Binding=====================
# The symbol we created is only a graph description.
# To run it, we first need to allocate memory and create an executor by 'binding' it.
# In order to bind a symbol, we need at least two pieces of information: context and input shapes.
# Context specifies which device ... | input_shapes {'softmax_label': (100,), 'data': (100, 784)}
epoch: 0 iter: 100 metric: ('accuracy', 0.1427)
epoch: 0 iter: 200 metric: ('accuracy', 0.42695)
epoch: 0 iter: 300 metric: ('accuracy', 0.5826333333333333)
epoch: 0 iter: 400 metric: ('accuracy', 0.66875)
epoch: 0 iter: 500 metric: ('accuracy', 0.72238)
epoch:... | Apache-2.0 | python/moved-from-mxnet/tutorial.ipynb | marktab/mxnet-notebooks |
New OperatorsMXNet provides a repository of common operators (or layers). However, new models often require new layers. There are several ways to [create new operators](https://mxnet.readthedocs.org/en/latest/tutorial/new_op_howto.html) with MXNet. Here we talk about the easiest way: pure python. | # Define custom softmax operator
class NumpySoftmax(mx.operator.NumpyOp):
def __init__(self):
# Call the parent class constructor.
# Because NumpySoftmax is a loss layer, it doesn't need gradient input from layers above.
super(NumpySoftmax, self).__init__(need_top_grad=False)
def l... | INFO:root:Start training with [gpu(0)]
INFO:root:Epoch[0] Batch [100] Speed: 53975.81 samples/sec Train-accuracy=0.167800
INFO:root:Epoch[0] Batch [200] Speed: 75720.80 samples/sec Train-accuracy=0.455800
INFO:root:Epoch[0] Batch [300] Speed: 73701.82 samples/sec Train-accuracy=0.602833
INFO:root:Epoch[0] Batch [400] S... | Apache-2.0 | python/moved-from-mxnet/tutorial.ipynb | marktab/mxnet-notebooks |
Challenge 026 - Giant Squid!This challenge is taken from Advent of Code 2021 - Day 4: Giant Squid (https://adventofcode.com/2021/day/4). Problem - Part 1You're already almost 1.5km (almost a mile) below the surface of the ocean, already so deep that you can't see any sunlight. What you can see, however, is a giant squ... | class Board:
def __init__(self):
self.position = {}
self.bingo= {
"column": [0,0,0,0,0],
"row": [0,0,0,0,0]
}
self.playBoard = [
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
... | _____no_output_____ | MIT | challenges/026-Giant_Squid/026-Day04_Giant_Squid.ipynb | jfdaniel77/interview-challenge |
Problem - Part 2On the other hand, it might be wise to try a different strategy: let the giant squid win.You aren't sure how many bingo boards a giant squid could play at once, so rather than waste time counting its arms, the safe thing to do is to figure out which board will win last and choose that one. That way, no... | class Board:
def __init__(self):
self.position = {}
self.bingo= {
"column": [0,0,0,0,0],
"row": [0,0,0,0,0]
}
self.playBoard = [
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
... | _____no_output_____ | MIT | challenges/026-Giant_Squid/026-Day04_Giant_Squid.ipynb | jfdaniel77/interview-challenge |
Parallel Processing with Dask====<img src="http://dask.readthedocs.io/en/latest/_images/dask_horizontal.svg" width="30%" align=right alt="Dask logo"> Learning Objectives* get acquanted with the Python Dask Library* learn how to execute basic operations on large arrays which cannot fit in RAM* learn about... |
from dask.distributed import Client
client = Client(processes=False)
client
| _____no_output_____ | CC-BY-4.0 | notebooks/2_dask_colab.ipynb | oceanhackweek/Oceans19-data-science-tutorial |
The distributed scheduler provides nice diagnostic tools which are useful to gain insight on the computation. They can reveal processing bottlenecks and are useful when running a scalable cluster (like kubernetes) and monitoring nodes. | # If we have set up a Kubernetes cluster we can start it in the following way:
#from dask_kubernetes import KubeCluster
#cluster = KubeCluster()
#cluster.scale(4)
#cluster | _____no_output_____ | CC-BY-4.0 | notebooks/2_dask_colab.ipynb | oceanhackweek/Oceans19-data-science-tutorial |
Dask ArraysA dask array looks and feels a lot like a numpy array.However, a dask array doesn't directly hold any data.Instead, it symbolically represents the computations needed to generate the data.Nothing is actually computed until the actual numerical values are needed.This mode of operation is called "lazy"; it al... | import numpy as np
shape = (1000, 4000)
ones_np = np.ones(shape)
ones_np | _____no_output_____ | CC-BY-4.0 | notebooks/2_dask_colab.ipynb | oceanhackweek/Oceans19-data-science-tutorial |
This size of the array is: | print('%.1f MB' % (ones_np.nbytes / 1e6)) | 32.0 MB
| CC-BY-4.0 | notebooks/2_dask_colab.ipynb | oceanhackweek/Oceans19-data-science-tutorial |
Now let's create the same array using dask's array interface. | import dask.array as da
ones = da.ones(shape)
ones | _____no_output_____ | CC-BY-4.0 | notebooks/2_dask_colab.ipynb | oceanhackweek/Oceans19-data-science-tutorial |
This works, but we didn't tell dask how to split up the array, so it is not optimized for distributed computation.A crucal difference with dask is that we must specify the `chunks` argument. "Chunks" describes how the array is split up over many sub-arrays.
ones = da.ones(shape, chunks=chunk_shape)
ones | _____no_output_____ | CC-BY-4.0 | notebooks/2_dask_colab.ipynb | oceanhackweek/Oceans19-data-science-tutorial |
Notice that we just see a symbolic represetnation of the array, including its shape, dtype, and chunksize.No data has been generated yet.When we call `.compute()` on a dask array, the computation is trigger and the dask array becomes a numpy array. | ones.compute()
| _____no_output_____ | CC-BY-4.0 | notebooks/2_dask_colab.ipynb | oceanhackweek/Oceans19-data-science-tutorial |
Task Graphs In order to understand what happened when we called `.compute()`, we can visualize the dask _graph_, the symbolic operations that make up the array | ones.visualize() | _____no_output_____ | CC-BY-4.0 | notebooks/2_dask_colab.ipynb | oceanhackweek/Oceans19-data-science-tutorial |
Our array has four chunks. To generate it, dask calls `np.ones` four times and then concatenates this together into one array.Rather than immediately loading a dask array (which puts all the data into RAM), it is more common to reduce the data somehow. For example: | sum_of_ones = ones.sum()
sum_of_ones.visualize() | _____no_output_____ | CC-BY-4.0 | notebooks/2_dask_colab.ipynb | oceanhackweek/Oceans19-data-science-tutorial |
Here we see dask's strategy for finding the sum. This simple example illustrates the beauty of dask: it automatically designs an algorithm appropriate for custom operations with big data. If we make our operation more complex, the graph gets more complex. | fancy_calculation = (ones * ones[::-1, ::-1]).mean()
fancy_calculation.visualize() | _____no_output_____ | CC-BY-4.0 | notebooks/2_dask_colab.ipynb | oceanhackweek/Oceans19-data-science-tutorial |
A Bigger CalculationThe examples above were toy examples; the data (32 MB) is nowhere nearly big enough to warrant the use of dask.We can make it a lot bigger! | bigshape = (100000, 4000)
big_ones = da.ones(bigshape, chunks=chunk_shape)
big_ones
print('%.1f MB' % (big_ones.nbytes / 1e6)) | 3200.0 MB
| CC-BY-4.0 | notebooks/2_dask_colab.ipynb | oceanhackweek/Oceans19-data-science-tutorial |
This dataset is 6.4 GB, rather than 32 MB! This is probably close to or greater than the amount of available RAM than you have in your computer. Nevertheless, dask has no problem working on it._Do not try to `.visualize()` this array!_When doing a big calculation, dask also has some tools to help us understand what is ... | pip install bokeh
!jupyter nbextension enable --py widgetsnbextension
big_calc = (big_ones * big_ones[::-1, ::-1]).mean()
from dask.distributed import get_task_stream
with get_task_stream(filename="task-stream.html",plot=True) as ts:
big_calc.compute()
#client.profile(filename="dask-profile.html")
from bokeh.plot... | _____no_output_____ | CC-BY-4.0 | notebooks/2_dask_colab.ipynb | oceanhackweek/Oceans19-data-science-tutorial |
Reduction All the usual numpy methods work on dask arrays.You can also apply numpy function directly to a dask array, and it will stay lazy. | big_ones_reduce = (np.cos(big_ones)**2).mean(axis=1)
big_ones_reduce
from matplotlib import pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (12,8) | _____no_output_____ | CC-BY-4.0 | notebooks/2_dask_colab.ipynb | oceanhackweek/Oceans19-data-science-tutorial |
Plotting also triggers computation, since we need the actual values | plt.plot(big_ones_reduce)
| _____no_output_____ | CC-BY-4.0 | notebooks/2_dask_colab.ipynb | oceanhackweek/Oceans19-data-science-tutorial |
Dask DelayedDask.delayed is a simple and powerful way to parallelize existing code. It allows users to delay function calls into a task graph with dependencies. Dask.delayed doesn't provide any fancy parallel algorithms like Dask.dataframe, but it does give the user complete control over what they want to build.Syst... | import time
def inc(x):
time.sleep(0.1)
return x + 1
def dec(x):
time.sleep(0.1)
return x - 1
def add(x, y):
time.sleep(0.2)
return x + y | _____no_output_____ | CC-BY-4.0 | notebooks/2_dask_colab.ipynb | oceanhackweek/Oceans19-data-science-tutorial |
We can run them like normal Python functions below | %%time
x = inc(1)
y = dec(2)
z = add(x, y)
z | CPU times: user 64.8 ms, sys: 11.4 ms, total: 76.2 ms
Wall time: 401 ms
| CC-BY-4.0 | notebooks/2_dask_colab.ipynb | oceanhackweek/Oceans19-data-science-tutorial |
These ran one after the other, in sequence. Note though that the first two lines `inc(1)` and `dec(2)` don't depend on each other, we *could* have called them in parallel had we been clever. Annotate functions with Dask Delayed to make them lazyWe can call `dask.delayed` on our funtions to make them lazy. Rather than... | import dask
inc = dask.delayed(inc)
dec = dask.delayed(dec)
add = dask.delayed(add) | _____no_output_____ | CC-BY-4.0 | notebooks/2_dask_colab.ipynb | oceanhackweek/Oceans19-data-science-tutorial |
Calling these lazy functions is now almost free. We're just constructing a graph | %%time
x = inc(1)
y = dec(2)
z = add(x, y)
z | CPU times: user 367 µs, sys: 0 ns, total: 367 µs
Wall time: 335 µs
| CC-BY-4.0 | notebooks/2_dask_colab.ipynb | oceanhackweek/Oceans19-data-science-tutorial |
Visualize computation | z.visualize(rankdir='LR') | _____no_output_____ | CC-BY-4.0 | notebooks/2_dask_colab.ipynb | oceanhackweek/Oceans19-data-science-tutorial |
Run in parallelCall `.compute()` when you want your result as a normal Python objectIf you started `Client()` above then you may want to watch the status page during computation. | %%time
z.compute() | CPU times: user 74.6 ms, sys: 7.71 ms, total: 82.3 ms
Wall time: 323 ms
| CC-BY-4.0 | notebooks/2_dask_colab.ipynb | oceanhackweek/Oceans19-data-science-tutorial |
Parallelize Normal Python codeNow we use Dask in normal for-loopy Python code. This generates graphs instead of doing computations directly, but still looks like the code we had before. Dask is a convenient way to add parallelism to existing workflows. | %%time
zs = []
for i in range(256):
x = inc(i)
y = dec(x)
z = add(x, y)
zs.append(z)
zs = dask.persist(*zs) # trigger computation in the background | CPU times: user 147 ms, sys: 16.9 ms, total: 164 ms
Wall time: 167 ms
| CC-BY-4.0 | notebooks/2_dask_colab.ipynb | oceanhackweek/Oceans19-data-science-tutorial |
In general `dask.delayed` is useful when the output of the individual parallel tasks are in a dask format (like dask.array) and are intended to be concatenated in one big dask object. Dask SchedulersThe Dask *Schedulers* orchestrate the tasks in the Task Graphs so that they can be run in parallel. *How* they run in p... | _____no_output_____ | CC-BY-4.0 | notebooks/2_dask_colab.ipynb | oceanhackweek/Oceans19-data-science-tutorial | |
多层感知机 --- 使用Gluon我们只需要稍微改动[多类Logistic回归](../chapter_crashcourse/softmax-regression-gluon.md)来实现多层感知机。 定义模型唯一的区别在这里,我们加了一行进来。 | from mxnet import gluon
net = gluon.nn.Sequential()
with net.name_scope():
net.add(gluon.nn.Flatten())
net.add(gluon.nn.Dense(256, activation="relu"))
net.add(gluon.nn.Dense(10))
net.initialize() | _____no_output_____ | Apache-2.0 | chapter_supervised-learning/mlp-gluon.ipynb | kyoyo/gluon_tutorials_zh_git |
读取数据并训练 | import sys
sys.path.append('..')
from mxnet import ndarray as nd
from mxnet import autograd
import utils
batch_size = 256
train_data, test_data = utils.load_data_fashion_mnist(batch_size)
softmax_cross_entropy = gluon.loss.SoftmaxCrossEntropyLoss()
trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate... | Epoch 0. Loss: 0.694022, Train acc 0.745893, Test acc 0.817508
| Apache-2.0 | chapter_supervised-learning/mlp-gluon.ipynb | kyoyo/gluon_tutorials_zh_git |
Direct Links1. [To get top 10 by genre](best_genre)2. [To get top 10 similar users](top_ten) | # Reading the ratings data
ratings = pd.read_csv('Dataset/ratings.csv')
len(ratings)
#Just taking the required columns
ratings = ratings[['userId', 'movieId','rating']]
# Checking if the user has rated the same movie twice, in that case we just take max of them
ratings_df = ratings.groupby(['userId','movieId']).aggrega... | _____no_output_____ | MIT | MovieLens_Recommendation_Notebook-Copy1.ipynb | nikita9604/Movie-Recommendation-Website-based-on-Genre |
Reading movie_score.csv directly | #movie_score.to_csv('movie_score.csv', index = False)
movie_score = pd.read_csv('movie_score.csv')
movie_score.head()
# Gives the best movies according to genre based on weighted score which is calculated using IMDB formula
def best_movies_by_genre(genre,top_n):
return pd.DataFrame(movie_score.loc[(movie_score[gen... | _____no_output_____ | MIT | MovieLens_Recommendation_Notebook-Copy1.ipynb | nikita9604/Movie-Recommendation-Website-based-on-Genre |
Gets the other top 10 movies which are watched by the people who saw this particular movie | #ratings_movies.to_csv('ratings_movies.csv', index = False)
ratings_movies = pd.read_csv('ratings_movies.csv')
ratings_movies.head()
#Gets the other top 10 movies which are watched by the people who saw this particular movie
def get_other_movies(movie_name):
#get all users who watched a specific movie
df_movie... | _____no_output_____ | MIT | MovieLens_Recommendation_Notebook-Copy1.ipynb | nikita9604/Movie-Recommendation-Website-based-on-Genre |
Directly getting top 10 movies based on content similarity | movie_content_df_temp = pd.read_csv('mv_cnt_tmp.csv')
movie_content_df_temp.head()
a_file = open("indicies.pkl", "rb")
inds = pickle.load(a_file)
a_file.close()
inds['Skyfall (2012)']
from numpy import load
data_dict = load('cosine.npz')
cosine_sim = data_dict['arr_0']
cosine_sim
cosine_sim.shape
#Gets the top 10 sim... | 7120
14026
| MIT | MovieLens_Recommendation_Notebook-Copy1.ipynb | nikita9604/Movie-Recommendation-Website-based-on-Genre |
User_index is row and Movie_index is column and value is rating | #Create two user-item matrices, one for training and another for testing
train_data_matrix = np.zeros((n_users, n_items))
#for every line in the data
for line in df_train.itertuples():
#set the value in the column and row to
#line[1] is userId, line[2] is movieId and line[3] is rating, line[4] is movie_ind... | _____no_output_____ | MIT | MovieLens_Recommendation_Notebook-Copy1.ipynb | nikita9604/Movie-Recommendation-Website-based-on-Genre |
CF Part 1 - Data loading and EDA> Collaborative Filtering on MovieLens Latest-small Part 1 - Downloading movielens latest small dataset and exploratory data analysis- toc: false- badges: true- comments: true- categories: [movie, collaborative]- image: | import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import sys
import os
from scipy.sparse import csr_matrix
from sklearn.preprocessing import LabelEncoder
!wget http://files.grouplens.org/datasets/movielens/ml-latest-small.zip
!unzip ml-latest-small.zip
DOWNLOAD_DESTINATION_DIR = "/content/ml-lates... | _____no_output_____ | Apache-2.0 | _notebooks/2021-06-23-collaborative-filtering-movielens-latest-small-01.ipynb | recohut/notebook |
Ratings range from $0.5$ to $5.0$, with a step of $0.5$. The above histogram presents the repartition of ratings in the dataset. the two most commun ratings are $4.0$ and $3.0$ and the less common ratings are $0.5$ and $1.5$ | # average rating of movies
movie_means = ratings.join(movies['title'], on='itemid').groupby('title').rating.mean()
movie_means[:50].plot(kind='bar', grid=True, figsize=(16,6), title="mean ratings of 50 movies");
# 30 most rated movies vs. 30 less rated movies
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(16,4), shar... | _____no_output_____ | Apache-2.0 | _notebooks/2021-06-23-collaborative-filtering-movielens-latest-small-01.ipynb | recohut/notebook |
multi variable에 대한 linear regression의 코드를 리뷰해보자 | import tensorflow as tf
import numpy as np
tf.set_random_seed(777) # for reproducibility
x1_data = [73., 93., 89., 96., 73.]
x2_data = [80., 88., 91., 98., 66.]
x3_data = [75., 93., 90., 100., 70.]
# Hypothesis / y hat
y_data = [152., 185., 180., 196., 142.]
x1 = tf.placeholder(tf.float32)
x2 = tf.placeholder(tf.floa... | x1 : [87.0] , x2 : [82.0] , x3 : [91.0]
Prediction: [ 177.55586243]
| MIT | code/multi_variable_linear_regression_01_start.ipynb | zeran4/justdoit |
Find the missing targets | ndat = np.load('more_targets.npy', allow_pickle=True)
flare_table = Table.read('new_flares.tab', format='ascii')
lks = []
for tic in np.unique(flare_table['Target_ID']):
s = search_lightcurve('TIC {}'.format(int(tic)), author='SPOC',
exptime=120, mission='TESS')
d = s[s.year<2020][0].... | WARNING: AstropyDeprecationWarning: medlim.csv already exists. Automatically overwriting ASCII files is deprecated. Use the argument 'overwrite=True' in the future. [astropy.io.ascii.ui]
WARNING: AstropyDeprecationWarning: lowlim.csv already exists. Automatically overwriting ASCII files is deprecated. Use the argument ... | MIT | braiding/plotting.ipynb | afeinstein20/flares_soc |
Load Tables | medlim = Table.read('medlim.csv',format='csv')
lowlim = Table.read('lowlim.csv',format='csv')
upplim = Table.read('upplim.csv',format='csv') | _____no_output_____ | MIT | braiding/plotting.ipynb | afeinstein20/flares_soc |
Plot the light curves | outliers = np.unique(medlim[(medlim['amp']>=1) & (medlim['Prot']<3)]['TIC_ID'])
lk = []
tic_tracker=[]
for tic in outliers:
print(tic)
d = search_lightcurve('TIC {}'.format(tic), mission='TESS',
author='SPOC').download_all().stitch()
lk.append(d)
tic_tracker.append(d.meta['TI... | 2
4
10
14
9
| MIT | braiding/plotting.ipynb | afeinstein20/flares_soc |
Rotation period plot | fig = plt.figure(figsize=(8,6))
fig.set_facecolor('w')
plt.scatter(mgun['bp']-mgun['rp'],
mgun['period_days'],
c=mgun['flare_rates'],
vmin=0, vmax=0.5,
cmap=parula_map)
plt.yscale('log')
plt.ylabel('Rotation Period [days]')
plt.xlabel('$B_p - R_p$')
plt.xlim(-1,5)
plt.... | _____no_output_____ | MIT | braiding/plotting.ipynb | afeinstein20/flares_soc |
Fitting the Flare Frequency Distributions | def slope_fit(x, n, i=0, j=1, plot=False, init=[-1.5,-2],
bounds=((-10.0, 10.0), (-1000, 1000))):
logx = np.log10(x)
logn = np.log10(n)
q = ((np.isnan(logn) == False) & (np.isfinite(logn)==True))
if plot:
plt.plot(logx[i:j], np.log10(n[i:j]), '.', c='k')
plt.plot... | _____no_output_____ | MIT | braiding/plotting.ipynb | afeinstein20/flares_soc |
Amplitude Binning | bins = np.logspace(np.log10(1), np.log10(500),20)
cut = 3
outslow = []
outfast = []
for t in [medlim, upplim, lowlim]:
os = plt.hist(t[t['Prot']>=cut]['amp']*100,
bins=bins,
weights=np.full(len(t[t['Prot']>=cut]['amp']),
1.0/np.nansum(t[t['Prot']>=cut]['Total_obs_t... | //anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:94: MatplotlibDeprecationWarning: savefig() got unexpected keyword argument "rasterize" which is no longer supported as of 3.3 and will become an error in 3.6
| MIT | braiding/plotting.ipynb | afeinstein20/flares_soc |
Feature Transformation with Amazon a SageMaker Processing Job and Scikit-LearnIn this notebook, we convert raw text into BERT embeddings. This will allow us to perform natural language processing tasks such as text classification.Typically a machine learning (ML) process consists of few steps. First, gathering data w... | import sagemaker
import boto3
sess = sagemaker.Session()
role = sagemaker.get_execution_role()
bucket = sess.default_bucket()
region = boto3.Session().region_name
sm = boto3.Session().client(service_name="sagemaker", region_name=region)
s3 = boto3.Session().client(service_name="s3", region_name=region) | _____no_output_____ | Apache-2.0 | 06_prepare/02_Prepare_Dataset_BERT_Scikit_ScriptMode_FeatureStore.ipynb | MarcusFra/workshop |
Setup Input Data | %store -r s3_public_path_tsv
try:
s3_public_path_tsv
except NameError:
print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
print("[ERROR] Please run the notebooks in the INGEST section before you continue.")
print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
print(s3_public_... | _____no_output_____ | Apache-2.0 | 06_prepare/02_Prepare_Dataset_BERT_Scikit_ScriptMode_FeatureStore.ipynb | MarcusFra/workshop |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.