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
Well this is not much code any more. Suddenly implementing our own iterative algorithm seems feasible! QUESTIONBEFORE YOU RUN THE NEXT CELL AND LOOK AT THE PLOT:In the next plot the image stored in `aq_model_image_array` will be shown, i.e. $x = E^H y$. Based on the discussion what the AcquisitionModel E does, what do...
aq_model_image_array = norm_array(aq_model_image.as_array()) fig = plt.figure() plt.set_cmap('gray') ax = fig.add_subplot(1,1,1) ax.imshow(abs(aq_model_image_array[0,:,:])) ax.set_title('Result Backward Method of E ') ax.axis('off')
_____no_output_____
Apache-2.0
notebooks/MR/d_undersampled_reconstructions.ipynb
mastergari/SIRF-Exercises
__Well, bummer again, the artifacts are still there!__ Of course, the acquisition model is just a compact version of our above code. We need something smarter to kill them off. But it got a bit more homogeneous, due to the weighted coil combination. Image Reconstruction as an Inverse Problem Iterative Parallel Imagin...
# Write your code here (this is as much space as you need!) # make sure the name of your function is A_operator # Don't look at the solution before you tried! # With this guy we will write our optimization def A_operator( image ): return E.backward( E.forward(i...
_____no_output_____
Apache-2.0
notebooks/MR/d_undersampled_reconstructions.ipynb
mastergari/SIRF-Exercises
Back to Wikipedia!Now we have all the tools we need. Now let's write the code to optimize our cost function iteratively. We don't care too much about maths, but we want the [algorithm](https://en.wikipedia.org/wiki/Conjugate_gradient_methodThe_resulting_algorithm).
# our images should be the same shape as the GRAPPA output recon_img = grappa_images # since we have no knowledge at all of what the image is we start from zero zero_array = recon_img.as_array() zero_array.fill(0) recon_img.fill(zero_array) # now name the variables the same as in the Wikipedia article: x = recon_im...
_____no_output_____
Apache-2.0
notebooks/MR/d_undersampled_reconstructions.ipynb
mastergari/SIRF-Exercises
Programming task: Initialize Iterative ReconstructionPlease write code executing the following task:- Initialize a variable `r` with `r` = $b - Ax$ (`r` stands for residual). __Hint 0:__ Remember: $b=E^H y$. Don't forget we just defined the A operator!- Print the type of `r` using Pythons built-in `type` and `print`...
## WRITE YOUR CODE IN THIS CELL ## Please make sure to name the variables correctly ##### Don't look at the solution before you tried! ############################# ############################################################################ # this is our first residua...
_____no_output_____
Apache-2.0
notebooks/MR/d_undersampled_reconstructions.ipynb
mastergari/SIRF-Exercises
k-Nearest Neighbor (kNN) exercise*Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For more details see the [assignments page](http://vision.stanford.edu/teaching/cs231n/assignments.html) on the course website.*The k...
# Run some setup code for this notebook. import random import numpy as np from cs231n.data_utils import load_CIFAR10 import matplotlib.pyplot as plt # This is a bit of magic to make matplotlib figures appear inline in the notebook # rather than in a new window. %matplotlib inline plt.rcParams['figure.figsize'] = (10....
_____no_output_____
MIT
hw1/knn.ipynb
hexiang-hu/cs231n-practice
We would now like to classify the test data with the kNN classifier. Recall that we can break down this process into two steps: 1. First we must compute the distances between all test examples and all train examples. 2. Given these distances, for each test example we find the k nearest examples and have them vote for t...
# Open cs231n/classifiers/k_nearest_neighbor.py and implement # compute_distances_two_loops. # Test your implementation: dists = classifier.compute_distances_two_loops(X_test) print dists.shape # We can visualize the distance matrix: each row is a single test example and # its distances to training examples plt.imsh...
_____no_output_____
MIT
hw1/knn.ipynb
hexiang-hu/cs231n-practice
**Inline Question 1:** Notice the structured patterns in the distance matrix. - What is the cause behind the distinctly visible rows? - What causes the columns? **Your Answer**: * Each test image will have variant L2 distance to the training images* Each training image have distinct L2 distance to the test images
# Now implement the function predict_labels and run the code below: # We use k = 1 (which is Nearest Neighbor). y_test_pred = classifier.predict_labels(dists, k=1) # Compute and print the fraction of correctly predicted examples num_correct = np.sum(y_test_pred == y_test) accuracy = float(num_correct) / num_test print...
Two loop version took 52.685231 seconds One loop version took 44.575945 seconds No loop version took 0.529489 seconds
MIT
hw1/knn.ipynb
hexiang-hu/cs231n-practice
Cross-validationWe have implemented the k-Nearest Neighbor classifier but we set the value k = 5 arbitrarily. We will now determine the best value of this hyperparameter with cross-validation.
num_folds = 5 k_choices = [1, 3, 5, 8, 10, 12, 15, 20, 50, 100] X_train_folds = [] y_train_folds = [] ################################################################################ # TODO: # # Split up the training data into folds. After splittin...
Got 141 / 500 correct => accuracy: 0.282000
MIT
hw1/knn.ipynb
hexiang-hu/cs231n-practice
Forced Alignment with Wav2Vec2In this notebook we are going to follow [this pytorch tutorial](https://pytorch.org/tutorials/intermediate/forced_alignment_with_torchaudio_tutorial.html) to align script to speech with torchaudio using the CTC segmentation algorithm described in [ CTC-Segmentation of Large Corpora for Ge...
!pip install torchaudio
 |██████████████████████████████▎ | 834.1 MB 1.3 MB/s eta 0:00:37tcmalloc: large alloc 1147494400 bytes == 0x5625b25b6000 @ 0x7f581be12615 0x5625790604cc 0x56257914047a 0x5625790632ed 0x562579154e1d 0x5625790d6e99 0x5625790d19ee 0x562579064bda 0x5625790d6d00 0x5625790d19ee 0x562579064bda 0x5625790d3737 0x562579...
MIT
10_AUDIO/03_FORCED_ALIGNMENT_WAV2VEC2/01_Forced_Alignment_Wav2Vec2.ipynb
CrispenGari/pytorch-python
Imports
import os, requests, torch, torchaudio, IPython from dataclasses import dataclass import matplotlib.pyplot as plt SPEECH_URL = 'https://download.pytorch.org/torchaudio/test-assets/Lab41-SRI-VOiCES-src-sp0307-ch127535-sg0042.flac' SPEECH_FILE = 'speech.flac' if not os.path.exists(SPEECH_FILE): with open(SPEECH_FILE, ...
_____no_output_____
MIT
10_AUDIO/03_FORCED_ALIGNMENT_WAV2VEC2/01_Forced_Alignment_Wav2Vec2.ipynb
CrispenGari/pytorch-python
Generate frame-wise label probabilityThe first step is to generate the label class porbability of each aduio frame. We can use a ``Wav2Vec2`` model that is trained for ASR.``torchaudio`` provides easy access to pretrained models with associated labels.**Note:** In the subsequent sections, we will compute the probabili...
bundle = torchaudio.pipelines.WAV2VEC2_ASR_BASE_960H model = bundle.get_model() labels = bundle.get_labels() with torch.inference_mode(): waveform, _ = torchaudio.load(SPEECH_FILE) emissions, _ = model(waveform) emissions = torch.log_softmax(emissions, dim=-1) emission = emissions[0].cpu().detach()
_____no_output_____
MIT
10_AUDIO/03_FORCED_ALIGNMENT_WAV2VEC2/01_Forced_Alignment_Wav2Vec2.ipynb
CrispenGari/pytorch-python
Visualization
print(labels) plt.imshow(emission.T) plt.colorbar() plt.title("Frame-wise class probability") plt.xlabel("Time") plt.ylabel("Labels") plt.show()
('<s>', '<pad>', '</s>', '<unk>', '|', 'E', 'T', 'A', 'O', 'N', 'I', 'H', 'S', 'R', 'D', 'L', 'U', 'M', 'W', 'C', 'F', 'G', 'Y', 'P', 'B', 'V', 'K', "'", 'X', 'J', 'Q', 'Z')
MIT
10_AUDIO/03_FORCED_ALIGNMENT_WAV2VEC2/01_Forced_Alignment_Wav2Vec2.ipynb
CrispenGari/pytorch-python
Generate alignment probability (trellis)From the emission matrix, next we generate the trellis which representsthe probability of transcript labels occur at each time frame.Trellis is 2D matrix with time axis and label axis. The label axisrepresents the transcript that we are aligning. In the following, we use$t$ to d...
transcript = 'I|HAD|THAT|CURIOSITY|BESIDE|ME|AT|THIS|MOMENT' dictionary = {c: i for i, c in enumerate(labels)} tokens = [dictionary[c] for c in transcript] print(list(zip(transcript, tokens))) def get_trellis(emission, tokens, blank_id=0): num_frame = emission.size(0) num_tokens = len(tokens) # Trellis has extr...
_____no_output_____
MIT
10_AUDIO/03_FORCED_ALIGNMENT_WAV2VEC2/01_Forced_Alignment_Wav2Vec2.ipynb
CrispenGari/pytorch-python
Visualization.
plt.imshow(trellis[1:, 1:].T, origin='lower') plt.annotate("- Inf", (trellis.size(1) / 5, trellis.size(1) / 1.5)) plt.colorbar() plt.show()
_____no_output_____
MIT
10_AUDIO/03_FORCED_ALIGNMENT_WAV2VEC2/01_Forced_Alignment_Wav2Vec2.ipynb
CrispenGari/pytorch-python
>In the above visualization, we can see that there is a trace of high probability crossing the matrix diagonally. Find the most likely path (backtracking)Once the trellis is generated, we will traverse it following theelements with high probability.We will start from the last label index with the time step of highestp...
@dataclass class Point: token_index: int time_index: int score: float def backtrack(trellis, emission, tokens, blank_id=0): # Note: # j and t are indices for trellis, which has extra dimensions # for time and tokens at the beginning. # When refering to time frame index `T` in trellis, # the correspondin...
[Point(token_index=0, time_index=30, score=0.9999842643737793), Point(token_index=0, time_index=31, score=0.9847016334533691), Point(token_index=0, time_index=32, score=0.9999707937240601), Point(token_index=0, time_index=33, score=0.15400736033916473), Point(token_index=1, time_index=34, score=0.9999173879623413), Poi...
MIT
10_AUDIO/03_FORCED_ALIGNMENT_WAV2VEC2/01_Forced_Alignment_Wav2Vec2.ipynb
CrispenGari/pytorch-python
Visualization
def plot_trellis_with_path(trellis, path): # To plot trellis with path, we take advantage of 'nan' value trellis_with_path = trellis.clone() for i, p in enumerate(path): trellis_with_path[p.time_index, p.token_index] = float('nan') plt.imshow(trellis_with_path[1:, 1:].T, origin='lower') plot_trellis_with_p...
_____no_output_____
MIT
10_AUDIO/03_FORCED_ALIGNMENT_WAV2VEC2/01_Forced_Alignment_Wav2Vec2.ipynb
CrispenGari/pytorch-python
Looking good. Now this path contains repetations for the same labels, so let’s merge them to make it close to the original transcript.When merging the multiple path points, we simply take the average probability for the merged segments.
# Merge the labels @dataclass class Segment: label: str start: int end: int score: float def __repr__(self): return f"{self.label}\t({self.score:4.2f}): [{self.start:5d}, {self.end:5d})" @property def length(self): return self.end - self.start def merge_repeats(path): i1, i2 = 0, 0 segments...
I (0.78): [ 30, 34) | (0.80): [ 34, 36) H (1.00): [ 36, 38) A (0.99): [ 38, 40) D (0.62): [ 40, 43) | (1.00): [ 43, 44) T (0.55): [ 44, 46) H (1.00): [ 46, 48) A (0.37): [ 48, 51) T (0.00): [ 51, 52) | (1.00): [ 52, 55) C (0.97): [ 55, 60) U (1.00): [ 60, ...
MIT
10_AUDIO/03_FORCED_ALIGNMENT_WAV2VEC2/01_Forced_Alignment_Wav2Vec2.ipynb
CrispenGari/pytorch-python
Visualization
def plot_trellis_with_segments(trellis, segments, transcript): # To plot trellis with path, we take advantage of 'nan' value trellis_with_path = trellis.clone() for i, seg in enumerate(segments): if seg.label != '|': trellis_with_path[seg.start+1:seg.end+1, i+1] = float('nan') plt.figure() plt.titl...
/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:10: MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the f...
MIT
10_AUDIO/03_FORCED_ALIGNMENT_WAV2VEC2/01_Forced_Alignment_Wav2Vec2.ipynb
CrispenGari/pytorch-python
Looks good. Now let’s merge the words. The Wav2Vec2 model uses ``'|'`` as the word boundary, so we merge the segments before each occurance of ``'|'``.
# Merge words def merge_words(segments, separator='|'): words = [] i1, i2 = 0, 0 while i1 < len(segments): if i2 >= len(segments) or segments[i2].label == separator: if i1 != i2: segs = segments[i1:i2] word = ''.join([seg.label for seg in segs]) score = sum(seg.score * seg.length...
I (0.78): [ 30, 34) HAD (0.84): [ 36, 43) THAT (0.52): [ 44, 52) CURIOSITY (0.89): [ 55, 91) BESIDE (0.94): [ 94, 115) ME (0.67): [ 117, 123) AT (0.66): [ 125, 128) THIS (0.70): [ 130, 138) MOMENT (0.97): [ 142, 154)
MIT
10_AUDIO/03_FORCED_ALIGNMENT_WAV2VEC2/01_Forced_Alignment_Wav2Vec2.ipynb
CrispenGari/pytorch-python
Visualization
trellis_with_path = trellis.clone() for i, seg in enumerate(segments): if seg.label != '|': trellis_with_path[seg.start+1:seg.end+1, i+1] = float('nan') plt.imshow(trellis_with_path[1:, 1:].T, origin='lower') ax1 = plt.gca() ax1.set_yticks([]) ax1.set_xticks([]) for word in word_segments: plt.axvline(word.st...
_____no_output_____
MIT
10_AUDIO/03_FORCED_ALIGNMENT_WAV2VEC2/01_Forced_Alignment_Wav2Vec2.ipynb
CrispenGari/pytorch-python
Read the data
movies_df = pd.read_csv('mymovies.csv') ratings_df = pd.read_csv('myratings.csv')
_____no_output_____
BSD-4-Clause-UC
GRS.ipynb
hoangkimkhai276/recsys
Select the dataThe recommender system should avoid bias, for example, the recommender system should not recommend movie with just 1 rating which is also a 5-star rating. But should recommend movies with more ratings.Therefore, we only take into account movies with at least 200 ratings and users who have at least rated...
user_threshold = 50 movie_threshold = 200 filtered_users = ratings_df['user'].value_counts()>=user_threshold filtered_users = filtered_users[filtered_users].index.tolist() filtered_movies = ratings_df['item'].value_counts()>=movie_threshold filtered_movies = filtered_movies[filtered_movies].index.tolist() filtered_df...
_____no_output_____
BSD-4-Clause-UC
GRS.ipynb
hoangkimkhai276/recsys
Select a group of n random usersHere we let n = 5, we select 5 random users from the filtered dataset
#Select a random group of user user_ids = filtered_df['user'].unique() group_users_ids = random.sample(list(user_ids), 5) group_users_ids
_____no_output_____
BSD-4-Clause-UC
GRS.ipynb
hoangkimkhai276/recsys
Select rated and unrated movies for the given groupWe now can get the rated movies all users in the groups, and from that, we can also get the unrated movies for the whole group of 5
selected_group_rating = ratings_df.loc[ratings_df['user'].isin(group_users_ids)] group_rated_movies_ids = selected_group_rating['item'].unique() group_unrated_movies_ids = set(movies_df['item']) - set(group_rated_movies_ids) group_rated_movies_df = movies_df.loc[movies_df['item'].isin(group_rated_movies_ids)] group_unr...
_____no_output_____
BSD-4-Clause-UC
GRS.ipynb
hoangkimkhai276/recsys
Calculate expected ratings for unrated moviesFor each users, we need to calculate the expected ratings for the user's unrated movies. To calculate unrated ratings, we first need to trainan algorithm, here, the SVD algorithm from Surprise is used
from surprise import Reader, Dataset, SVD from surprise.model_selection.validation import cross_validate
_____no_output_____
BSD-4-Clause-UC
GRS.ipynb
hoangkimkhai276/recsys
We perform 5-fold cross validation on the whole ratings dataset to see how well SVD will perform
reader = Reader() data = Dataset.load_from_df(ratings_df[['user', 'item', 'rating']], reader) svd = SVD() cross_validate(svd, data, measures=['RMSE', 'MAE'], cv=5, verbose=True)
Evaluating RMSE, MAE of algorithm SVD on 5 split(s). Fold 1 Fold 2 Fold 3 Fold 4 Fold 5 Mean Std RMSE (testset) 0.8776 0.8791 0.8701 0.8678 0.8708 0.8731 0.0044 MAE (testset) 0.6764 0.6764 0.6677 0.6680 0.6679 0.6713 0.0042 Fit time 9.63 9.58 9.44 ...
BSD-4-Clause-UC
GRS.ipynb
hoangkimkhai276/recsys
Next, We train the SVD model on the dataset
trainset = data.build_full_trainset() svd = svd.fit(trainset) def predict(user): unrated_movies = list(group_unrated_movies_df['item'].unique()) pred = pd.DataFrame() i = 0 for item in unrated_movies: pred = pred.append({'user':user,'item': item, 'predicted_rating':svd.predict(user, item)[3]}, i...
_____no_output_____
BSD-4-Clause-UC
GRS.ipynb
hoangkimkhai276/recsys
The algorithm will iterate through 5 users, for each user, it will calculate the predicted rating for each unrated movie. Then the algorithm combines the predicted ratings of 5 users into one big dataset, to perform aggregation calculation
final = pd.concat([df for df in users_rating], ignore_index = True) final
_____no_output_____
BSD-4-Clause-UC
GRS.ipynb
hoangkimkhai276/recsys
Additive Strategy
additive = final.copy() additive= additive.groupby(['item','title']).sum() additive = additive.sort_values(by="predicted_rating", ascending=False).reset_index() additive
_____no_output_____
BSD-4-Clause-UC
GRS.ipynb
hoangkimkhai276/recsys
Most Pleasure Strategy
most_pleasure = final.copy() most_pleasure = final.copy() most_pleasure= most_pleasure.groupby(['item','title']).max() most_pleasure = most_pleasure.sort_values(by="predicted_rating", ascending=False).reset_index() most_pleasure
_____no_output_____
BSD-4-Clause-UC
GRS.ipynb
hoangkimkhai276/recsys
Least Misery Strategy
least_misery = final.copy() least_misery = final.copy() least_misery= least_misery.groupby(['item','title']).min() least_misery = least_misery.sort_values(by="predicted_rating", ascending=False).reset_index() least_misery def fairness(): titles = [] for uid in group_users_ids: data = final.loc[final['us...
_____no_output_____
BSD-4-Clause-UC
GRS.ipynb
hoangkimkhai276/recsys
Call stacks and recursionIn this notebook, we'll take a look at *call stacks*, which will provide an opportunity to apply some of the concepts we've learned about both stacks and recursion. What is a *call stack*?When we use functions in our code, the computer makes use of a data structure called a **call stack**. As...
def add(num_one, num_two): output = num_one + num_two return output result = add(5, 7) print(result)
12
MIT
Data Structures/Recursion/Call stack.ipynb
gmendozah/Data-Structures-and-Algorithms
Before understanding what happens when a function is executed, it is important to remind ourselves that whenever an expression such as `product = 5 * 7` is evaluated, the right hand side of the `=` sign is evaluted first. When the right-hand side is completely evaluated, the result is stored in the variable name mentio...
def add(num_one, num_two): output = num_one + num_two custom_print(output, num_one, num_two) return output def custom_print(output, num_one, num_two): print("The sum of {} and {} is: {}".format(num_one, num_two, output)) result = add(5, 7)
The sum of 5 and 7 is: 12
MIT
Data Structures/Recursion/Call stack.ipynb
gmendozah/Data-Structures-and-Algorithms
What happens "behind-the-scenes" when `add()` is called, as in `result = add(5, 7)`?Feel free to play with this on the Python tutor website. Here are a few points which might help aid the understanding.* We know that when add function is called using `result = add(5, 7)`, a frame is created in the memory for the `add()...
def print_integers(n): # TODO: Complete the function so that it uses recursion to print all integers from n to 1 if n <= 0: return print(n) print_integers(n - 1)
_____no_output_____
MIT
Data Structures/Recursion/Call stack.ipynb
gmendozah/Data-Structures-and-Algorithms
Show Solution
print_integers(5)
5 4 3 2 1
MIT
Data Structures/Recursion/Call stack.ipynb
gmendozah/Data-Structures-and-Algorithms
Libraries
from sklearn.preprocessing import StandardScaler,MinMaxScaler import pandas as pd import torchvision import os import numpy as np from skimage import io,transform as ts import torch from torchvision import transforms from torch.utils.data import Dataset import torch import torch.nn as nn import torch.nn.functional as F...
_____no_output_____
MIT
Results_Summary.ipynb
RajArPatra/MIDAS-tassk-2
Mount Drive
from google.colab import drive drive.mount('/content/drive')
Mounted at /content/drive
MIT
Results_Summary.ipynb
RajArPatra/MIDAS-tassk-2
PART 1 Training and evaluation for part1 for whole of 62 classes
run_train(model,criterion,optimizer,scheduler,'/content/drive/MyDrive/Model_files','task2/BMCNN_part1',0,70,10,False) print('====> After epoch {} '.format(con.epoch)) print('====>conv Time: {}'.format(con.time)) #print('====>conv Time: {}'.format(con.time)) print('====>Average train loss: {:.4f} +-{:.4f}'.format( ...
Confusion matrix, without normalization [[35 0 0 ... 0 0 0] [ 0 21 0 ... 0 0 0] [ 0 0 31 ... 0 0 0] ... [ 0 0 0 ... 29 4 0] [ 0 0 0 ... 0 36 0] [ 0 0 0 ... 0 0 39]]
MIT
Results_Summary.ipynb
RajArPatra/MIDAS-tassk-2
Training and evaluation for part1 for (0-9) classes
run(model,criterion,optimizer,scheduler,'/content/drive/MyDrive/Model_files','task2/BMCNN_(0-9)_part1',0,100,10,False) print('====> After epoch {} '.format(con.epoch)) print('====>conv Time: {}'.format(con.time)) #print('====>conv Time: {}'.format(con.time)) print('====>Average train loss: {:.4f} +-{:.4f}'.format( ...
Confusion matrix, without normalization [[26 2 1 2 2 0 7 0 0 0] [ 0 36 1 1 1 0 0 1 0 0] [ 0 0 37 0 1 0 1 1 0 0] [ 0 2 0 30 1 0 3 0 1 3] [ 0 0 0 0 35 0 2 0 0 3] [ 0 0 0 2 1 34 2 0 0 1] [ 0 0 0 0 1 0 38 0 1 0] [ 0 0 0 0 3 0 0 33 0 4] [ 0 0 0 0 1...
MIT
Results_Summary.ipynb
RajArPatra/MIDAS-tassk-2
Part 2 Training and Evaluation Metrics for part2 without pretrained weights
run(model,criterion,optimizer,scheduler,'/content/drive/MyDrive/Model_files','task2/BMCNN_part2_nopre3',0,100,10,False,1) print('====> After epoch {} '.format(con.epoch)) print('====>conv Time: {}'.format(con.time)) #print('====>conv Time: {}'.format(con.time)) print('====>Average train loss: {:.4f} +-{:.4f}'.format( ...
Confusion matrix, without normalization [[5920 0 0 1 0 0 2 0 0 0] [ 0 6731 0 0 0 1 3 6 1 0] [ 0 10 5938 1 0 0 2 6 1 0] [ 1 0 0 6117 0 7 1 2 2 1] [ 0 2 0 0 5830 0 1 3 0 6] [ 0 0 ...
MIT
Results_Summary.ipynb
RajArPatra/MIDAS-tassk-2
Training and Evaluation Metrics for part2 with pretrained weights from part 1
run_pre(model,criterion,optimizer,scheduler,'/content/drive/MyDrive/Model_files','task2/BMCNN_part2_pre3',0,100,10,False,1) print('====> After epoch {} '.format(con.epoch)) print('====>conv Time: {}'.format(con.time)) #print('====>conv Time: {}'.format(con.time)) print('====>Average train loss: {:.4f} +-{:.4f}'.format(...
Confusion matrix, without normalization [[5923 0 0 0 0 0 0 0 0 0] [ 0 6738 0 0 0 0 0 4 0 0] [ 0 1 5955 0 0 0 0 2 0 0] [ 0 0 0 6127 0 3 0 0 0 1] [ 0 2 0 0 5833 0 0 2 0 5] [ 0 0 ...
MIT
Results_Summary.ipynb
RajArPatra/MIDAS-tassk-2
Part 3 Training and Evaluation Metrics for part3 without pretrained weights
run(model,criterion,optimizer,scheduler,'/content/drive/MyDrive/Model_files','task2/BMCNN_part3_nopre',0,100,10,False,1) print('====> After epoch {} '.format(con.epoch)) print('====>conv Time: {}'.format(con.time)) #print('====>conv Time: {}'.format(con.time)) print('====>Average train loss: {:.4f} +-{:.4f}'.format( ...
Confusion matrix, without normalization [[3362 12 19 76 130 78 446 136 1539 182] [3431 38 35 188 127 74 433 187 1040 254] [3193 24 43 209 98 53 467 170 1541 211] [3058 29 36 220 127 87 377 205 1645 253] [3178 17 36 190 123 86 480 152 1399 253] [3117 35 2...
MIT
Results_Summary.ipynb
RajArPatra/MIDAS-tassk-2
Training and Evaluation Metrics for part3 with pretrained weights from part1
run_pre(model,criterion,optimizer,scheduler,'/content/drive/MyDrive/Model_files','task2/BMCNN_part3_pre2',0,100,10,False,1) print('====> After epoch {} '.format(con.epoch)) print('====>conv Time: {}'.format(con.time)) #print('====>conv Time: {}'.format(con.time)) print('====>Average train loss: {:.4f} +-{:.4f}'.format(...
Confusion matrix, without normalization [[2875 94 1825 16 320 22 195 13 171 449] [2918 88 1458 21 377 38 59 41 199 608] [2649 78 2031 20 382 32 175 50 142 450] [2694 63 1870 26 431 34 183 48 188 500] [2715 84 1684 13 452 29 197 39 149 552] [2692 88 199...
MIT
Results_Summary.ipynb
RajArPatra/MIDAS-tassk-2
How many cases of COVID-19 does each U.S. state really have?> Reported U.S. case counts are based on the number of administered tests. Since not everyone is tested, this number is biased. We use Bayesian techniques to estimate the true number of cases.- author: Joseph Richards- image: images/covid-state-case-estimatio...
#hide # Setup and imports %matplotlib inline import warnings warnings.simplefilter('ignore') import matplotlib.pyplot as plt import numpy as np import pandas as pd import pymc3 as pm import requests from IPython.display import display, Markdown #hide # Data utilities: def get_statewise_testing_data(): ''' ...
_____no_output_____
Apache-2.0
_notebooks/2020-03-18-case-count-estimation-us-states.ipynb
maximelefrancois86/covid19-dashboard
COVID-19 Case Estimates, by State Definition Of Fields:- **Reported Cases**: The number of cases reported by each state, which is a function of how many tests are positive.- **Est Cases**: The predicted number of cases, accounting for the fact that not everyone is tested.- **Est Range**: The 95% confidence interval o...
#hide_input df_display.sort_values( by='Est Cases', ascending=False).style.background_gradient( cmap='Oranges').format( {'Ratio': "{:.1f}"}).format( {'Tests per Million': "{:.1f}"}).format( {'Cases per Million': "{:.1f}"}).format( {'Positive Test Rate': "{:.0%}"}) #hide_input df_plot = df_summa...
_____no_output_____
Apache-2.0
_notebooks/2020-03-18-case-count-estimation-us-states.ipynb
maximelefrancois86/covid19-dashboard
Appendix: Model Diagnostics Derived relationship between Test Capacity and Case Under-reportingPlotted is the estimated relationship between test capacity (in terms of people per test -- larger = less testing) and the likelihood a COVID-19 case is reported (lower = more under-reporting of cases).The lines represent t...
#hide_input # Plot pop/test vs. Prob of case detection for all posterior samples: x = np.linspace(0.0, 4.0, 101) logit_pcase = pd.DataFrame([ trace['alpha'][i] + trace['beta'][i] * x for i in range(n)]) pcase = np.exp(logit_pcase) / (np.exp(logit_pcase) + 1) fig, ax = plt.subplots(1, 1, figsize=(14, 9)) for i...
_____no_output_____
Apache-2.0
_notebooks/2020-03-18-case-count-estimation-us-states.ipynb
maximelefrancois86/covid19-dashboard
Dynamic Time Warping\begin{equation}y = \mathop{\arg\,\max}\limits{l \in L} \frac{1}{n_l} \sum_{i = 0}^{n_l} \text{fastdtw\_distance}(x_i^l, x_{\text{test}})\end{equation}
import dtw print(dtw.score())
0.898484415213
MIT
Notebook.ipynb
toogy/pendigits-hmm
Cavity Length DeterminerUse this notebook to find peak positions in a spectrum and use the free spectral range, along with the known or calculated material refractive index, to determine the cavity length in vacuum. The *must* be done at 0-degree incidence.
import ipywidgets as widgets import matplotlib.pyplot as plt import seaborn as sns import pandas as pd from scipy import signal from ruamel_yaml import YAML import data_io import material_properties as mp import pmath yaml = YAML() sns.set_theme(context='notebook', style='whitegrid', palette='dark') %matplotlib widget...
_____no_output_____
MIT
notebooks/Cavity Length Determiner.ipynb
garrekstemo/pistachio
Project Euler: Problem 6 https://projecteuler.net/problem=6The sum of the squares of the first ten natural numbers is,$$1^2 + 2^2 + ... + 10^2 = 385$$The square of the sum of the first ten natural numbers is,$$(1 + 2 + ... + 10)^2 = 552 = 3025$$Hence the difference between the sum of the squares of the first ten natur...
#Pretty simple process. I summed all the y's up and squared the sum and then I subtracted each x^2 (1-100) from that result. x = 0 y = 0 n = 0 while (y < 100): y = y + 1 n = n + y #print (y) #print (n) n = (n ** 2) while (x < 100): x = x + 1 n = n - (x ** 2) #print (x) print (n) #raise NotImplementedEr...
_____no_output_____
MIT
assignments/assignment02/ProjectEuler6.ipynb
edwardd1/phys202-2015-work
GLM: Logistic Regression* This is a reproduction with a few slight alterations of [Bayesian Log Reg](http://jbencook.github.io/portfolio/bayesian_logistic_regression.html) by J. Benjamin Cook* Author: Peadar Coyle and J. Benjamin Cook* How likely am I to make more than $50,000 US Dollars?* Exploration of model selecti...
%matplotlib inline import pandas as pd import numpy as np import pymc3 as pm import matplotlib.pyplot as plt import seaborn import warnings warnings.filterwarnings('ignore') from collections import OrderedDict from time import time import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.opti...
_____no_output_____
Apache-2.0
docs/source/notebooks/GLM-logistic.ipynb
JvParidon/pymc3
The [Adult Data Set](http://archive.ics.uci.edu/ml/datasets/Adult) is commonly used to benchmark machine learning algorithms. The goal is to use demographic features, or variables, to predict whether an individual makes more than \\$50,000 per year. The data set is almost 20 years old, and therefore, not perfect for de...
data = pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data", header=None, names=['age', 'workclass', 'fnlwgt', 'education-categorical', 'educ', 'marital-status', 'occupation', 'relationship', 'race', 'sex', 'captial-g...
_____no_output_____
Apache-2.0
docs/source/notebooks/GLM-logistic.ipynb
JvParidon/pymc3
Scrubbing and cleaningWe need to remove any null entries in Income. And we also want to restrict this study to the United States.
data = data[~pd.isnull(data['income'])] data[data['native-country']==" United-States"] income = 1 * (data['income'] == " >50K") age2 = np.square(data['age']) data = data[['age', 'educ', 'hours']] data['age2'] = age2 data['income'] = income income.value_counts()
_____no_output_____
Apache-2.0
docs/source/notebooks/GLM-logistic.ipynb
JvParidon/pymc3
Exploring the data Let us get a feel for the parameters. * We see that age is a tailed distribution. Certainly not Gaussian!* We don't see much of a correlation between many of the features, with the exception of Age and Age2. * Hours worked has some interesting behaviour. How would one describe this distribution?
g = seaborn.pairplot(data) # Compute the correlation matrix corr = data.corr() # Generate a mask for the upper triangle mask = np.zeros_like(corr, dtype=np.bool) mask[np.triu_indices_from(mask)] = True # Set up the matplotlib figure f, ax = plt.subplots(figsize=(11, 9)) # Generate a custom diverging colormap cmap = ...
_____no_output_____
Apache-2.0
docs/source/notebooks/GLM-logistic.ipynb
JvParidon/pymc3
We see here not many strong correlations. The highest is 0.30 according to this plot. We see a weak-correlation between hours and income (which is logical), we see a slighty stronger correlation between education and income (which is the kind of question we are answering). The modelWe will use a simple model, which as...
with pm.Model() as logistic_model: pm.glm.GLM.from_formula('income ~ age + age2 + educ + hours', data, family=pm.glm.families.Binomial()) trace_logistic_model = pm.sample(2000, chains=1, init=None, tune=1000) plot_traces(trace_logistic_model, retain=1000)
_____no_output_____
Apache-2.0
docs/source/notebooks/GLM-logistic.ipynb
JvParidon/pymc3
Some results One of the major benefits that makes Bayesian data analysis worth the extra computational effort in many circumstances is that we can be explicit about our uncertainty. Maximum likelihood returns a number, but how certain can we be that we found the right number? Instead, Bayesian inference returns a dist...
plt.figure(figsize=(9,7)) trace = trace_logistic_model[1000:] seaborn.jointplot(trace['age'], trace['educ'], kind="hex", color="#4CB391") plt.xlabel("beta_age") plt.ylabel("beta_educ") plt.show()
_____no_output_____
Apache-2.0
docs/source/notebooks/GLM-logistic.ipynb
JvParidon/pymc3
So how do age and education affect the probability of making more than $$50K?$ To answer this question, we can show how the probability of making more than $50K changes with age for a few different education levels. Here, we assume that the number of hours worked per week is fixed at 50. PyMC3 gives us a convenient way...
# Linear model with hours == 50 and educ == 12 lm = lambda x, samples: 1 / (1 + np.exp(-(samples['Intercept'] + samples['age']*x + samples['age2']*np.square(x) + samples['educ']*12 + ...
_____no_output_____
Apache-2.0
docs/source/notebooks/GLM-logistic.ipynb
JvParidon/pymc3
Each curve shows how the probability of earning more than $ 50K$ changes with age. The red curve represents 19 years of education, the green curve represents 16 years of education and the blue curve represents 12 years of education. For all three education levels, the probability of making more than $50K increases with...
# Plot the posterior predictive distributions of P(income > $50K) vs. age pm.plot_posterior_predictive_glm(trace, eval=np.linspace(25, 75, 1000), lm=lm, samples=100, color="blue", alpha=.15) pm.plot_posterior_predictive_glm(trace, eval=np.linspace(25, 75, 1000), lm=lm2, samples=100, color="green", alpha=.15) pm.plot_po...
_____no_output_____
Apache-2.0
docs/source/notebooks/GLM-logistic.ipynb
JvParidon/pymc3
Finally, we can find a credible interval (remember kids - credible intervals are Bayesian and confidence intervals are frequentist) for this quantity. This may be the best part about Bayesian statistics: we get to interpret credibility intervals the way we've always wanted to interpret them. We are 95% confident that t...
lb, ub = np.percentile(b, 2.5), np.percentile(b, 97.5) print("P(%.3f < O.R. < %.3f) = 0.95" % (np.exp(lb),np.exp(ub)))
P(1.378 < O.R. < 1.414) = 0.95
Apache-2.0
docs/source/notebooks/GLM-logistic.ipynb
JvParidon/pymc3
Model selection One question that was immediately asked was what effect does age have on the model, and why should it be $age^2$ versus age? We'll run the model with a few changes to see what effect higher order terms have on this model in terms of WAIC.
models_lin, traces_lin = run_models(data, 4) dfwaic = pd.DataFrame(index=['k1','k2','k3','k4'], columns=['lin']) dfwaic.index.name = 'model' for nm in dfwaic.index: dfwaic.loc[nm, 'lin'] = pm.waic(traces_lin[nm],models_lin[nm])[0] dfwaic = pd.melt(dfwaic.reset_index(), id_vars=['model'], var_name='poly', value_n...
_____no_output_____
Apache-2.0
docs/source/notebooks/GLM-logistic.ipynb
JvParidon/pymc3
Indian food analysisFirstly please read docs.md Table of contents* Data preparation * Load original dataset into dataframes * Data cleansing * Save dataset * Load cleansed dataset* Analysis * Top 30 popular songs of all time * Analyze by a single song * Analyze track duration with frequency distri...
import numpy as np import pandas as pd # read dataset from csv df_data_by_song : pd.DataFrame = pd.read_csv('dataset/original/data.csv', index_col='name') df_data_by_artist : pd.DataFrame = pd.read_csv('dataset/original/data_by_artist.csv', index_col='artists') df_data_by_genres : pd.DataFrame = pd.read_csv('dataset...
data_by_song: PK: name ['valence', 'year', 'acousticness', 'artists', 'danceability', 'duration_ms', 'energy', 'explicit', 'id', 'instrumentalness', 'key', 'liveness', 'loudness', 'mode', 'popularity', 'release_date', 'speechiness', 'tempo'] data_by_artist: PK: artists ['mode', 'count', 'acousticness', 'danceability', ...
MIT
src/notebook.ipynb
LorenzoTinfena/spotify-music-analysis
Data cleansing
# some fixes df_data_by_song = df_data_by_song.drop(columns=['id']) df_data_by_artist.index.name = 'artist' df_data_by_genres.index.name = 'genre' df_data_w_genres.index.name = 'artist' # reorder columns df_data_by_song = df_data_by_song[['popularity', 'danceability', 'valence', 'duration_ms', 'energy', 'acousticness',...
_____no_output_____
MIT
src/notebook.ipynb
LorenzoTinfena/spotify-music-analysis
Savedataset
df_data_by_song.to_csv('dataset/cleansed/data_by_song.csv') df_data_by_artist.to_csv('dataset/cleansed/data_by_artist.csv') df_data_by_genres.to_csv('dataset/cleansed/data_by_genres.csv') df_data_by_year.to_csv('dataset/cleansed/data_by_year.csv') df_data_w_genres.to_csv('dataset/cleansed/data_w_genres.csv')
_____no_output_____
MIT
src/notebook.ipynb
LorenzoTinfena/spotify-music-analysis
Load cleansed dataset
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np df_data_by_song : pd.DataFrame = pd.read_csv('dataset/cleansed/data_by_song.csv', index_col='name') df_data_by_artist : pd.DataFrame = pd.read_csv('dataset/cleansed/data_by_artist.csv', index_col='artist') df_data_by_genres ...
_____no_output_____
MIT
src/notebook.ipynb
LorenzoTinfena/spotify-music-analysis
Analysis Top 30 popular songs of all timeyou can choose by and ascending or dicending
by = 'loudness' # choices: popularity duration_ms key loudness tempo year ascending = False import matplotlib.pyplot as plt df_data_by_song_tops = df_data_by_song.sort_values(by=by, ascending=ascending).head(30) fig, ax = plt.subplots(figsize=(10, 10)) ax.barh(list(df_data_by_song_tops.index.values), df_data_by_song...
_____no_output_____
MIT
src/notebook.ipynb
LorenzoTinfena/spotify-music-analysis
Analyze by a single songyou can choose song_name
song_name = 'Stasera... Che Sera! - 1991 - Remaster;' import matplotlib.pyplot as plt from lib.complexRadar import ComplexRadar if song_name not in df_data_by_song.index: raise IndexError('Song doesn\'t exist') song = df_data_by_song.loc[song_name] if isinstance(song, pd.DataFrame): #if multiple song with same ...
Release date: 1976 Artists: name: Matia Bazar popularity 43.000000 danceability 0.644500 valence 0.642000 duration_ms 229809.000000 energy 0.576000 acousticness 0.186500 instrumentalness 0.002713 liveness 0.161600...
MIT
src/notebook.ipynb
LorenzoTinfena/spotify-music-analysis
Analyze track duration with frequency distribution chart
X = df_data_by_song.rename(columns={'duration_ms' : 'duration_s'}) X=X['duration_s'].loc[X['duration_s'] < 800000] / 10**3 # plotting plt.figure(figsize=(20, 5)) sns.distplot(X) plt.show()
_____no_output_____
MIT
src/notebook.ipynb
LorenzoTinfena/spotify-music-analysis
Analyze average track details by yearyou can choose by which detail
by = 'duration_ms' #choices: popularity, duration_ms, key, loudness, tempo df_data_by_song : pd.DataFrame = df_data_by_song data = df_data_by_song[[by, 'year']].groupby(by='year').mean() X = data.index Y = data[by].values # plotting fig, ax = plt.subplots() ax.plot(X, Y) ax.grid() ax.set_xlabel('year') ax.set_ylabel...
_____no_output_____
MIT
src/notebook.ipynb
LorenzoTinfena/spotify-music-analysis
Setting up the MAD-X environment
madx = Madx() madx.command.beam('PARTICLE=PROTON, PC = 2.14;') madx.input('BRHO := BEAM->PC * 3.3356;') # call sequence of main units madx.call('/eos/home-a/ahuschau/www/test-acc-models/repository/PS/2019/PS_MU.seq') # call sequence of straight section elements madx.call('/eos/home-a/ahuschau/www/test-acc-models/reposi...
++++++++++++++++++++++++++++++++++++++++++++ + MAD-X 5.04.02 (64 bit, Linux) + + Support: mad@cern.ch, http://cern.ch/mad + + Release date: 2018.10.03 + + Execution date: 2019.08.19 09:29:57 + ++++++++++++++++++++++++++++++++++++++++++++ /************************************...
MIT
acc-models-ps-master/scenarios/lhc_proton/0_injection/MADX_example_ps_inj_lhc.ipynb
HaroonRafique/PS_Lattice_SC_Optimisation
Performing a PTC Twiss
madx.command.use(sequence = 'PS') madx.command.ptc_create_universe() madx.command.ptc_create_layout('time=false, model=2, exact=true, method=6, nst=5') madx.command.ptc_twiss('closed_orbit, icase=56, no=4, slice_magnets') madx.command.ptc_end
Determined SECTOR NMUL MAX : 2 MAD-X Beam Parameters Energy : 0.233665E+01 Kinetic Energy : 0.139838E+01 Particle Rest Mass : 0.938272E+00 Momentum : 0.214000E+01 Setting MADx with energy 2.3366545526771887 method 6 Nu...
MIT
acc-models-ps-master/scenarios/lhc_proton/0_injection/MADX_example_ps_inj_lhc.ipynb
HaroonRafique/PS_Lattice_SC_Optimisation
Print non-zero entries of the PTC Twiss summary table
twiss = madx.table['ptc_twiss_summary'] for k in twiss.keys(): if twiss[k][0] > 0: print(k + ' = ' + str(twiss[k][0]))
length = 628.3185000000026 alpha_c = 0.02673251283033799 alpha_c_p = 0.07111328054643197 gamma_tr = 6.1161778841446335 q1 = 0.24546728367615464 q2 = 0.28366007619895556 beta_x_min = 11.712692822201694 beta_x_max = 22.595657062401727 beta_y_min = 11.641966474678512 beta_y_max = 22.443946960176095 beta11min = 11.71269282...
MIT
acc-models-ps-master/scenarios/lhc_proton/0_injection/MADX_example_ps_inj_lhc.ipynb
HaroonRafique/PS_Lattice_SC_Optimisation
Plot the optics functions
twiss = madx.table['ptc_twiss'] f, ax = plt.subplots(1,figsize = (12,7)) ax.plot(twiss.S, twiss.BETA11, color = 'darkblue', label = r'$\beta_x$', linewidth = 1) ax.plot(twiss.S, twiss.BETA22, color = 'firebrick', label = r'$\beta_y$', linewidth = 1) ax.plot(twiss.S, twiss.DISP1*0-100, 'k', label = r'$D_x$') ax2 = ax...
_____no_output_____
MIT
acc-models-ps-master/scenarios/lhc_proton/0_injection/MADX_example_ps_inj_lhc.ipynb
HaroonRafique/PS_Lattice_SC_Optimisation
Caso de uso 2: Estudio de los accidentes a altas horas de la madrugada Filtramos los datos para quedarnos con accidentes que ocurren a altas horas de la madrugada.
data2=dataTot[dataTot.HORA<=6] data=data2[atributos] # En data2 quedan el resto de variables data for a in atributos: print(a) print(Counter(data[a])) # Box Plot n_var = len(atributos) fig, axes = plt.subplots(1, n_var, sharey=True, figsize=(15,5)) fig.subplots_adjust(wspace=0, hspace=0) colors = sns.color_pa...
_____no_output_____
MIT
practica2/accidentes2-1.ipynb
dcabezas98/IN
K-Means
# Elección de un número adecuado de Clústers atendiendo a las métricas K=list(range(2,10)) silhouette=[] calinski=[] for k in K: results = KMeans(n_clusters=k, random_state=0).fit(data_norm) sil, cal = measures_silhoutte_calinski(data_norm, results.labels_) silhouette.append(sil) calinski.append(cal) pr...
_____no_output_____
MIT
practica2/accidentes2-1.ipynb
dcabezas98/IN
Nos quedaremos con K=3. Introducir más clústers no gana tanto score y hace la segmentación muy difícil de interpretar.
K=3 results = KMeans(n_clusters=K, random_state=0).fit(data_norm) labels=results.labels_ centroids=results.cluster_centers_
_____no_output_____
MIT
practica2/accidentes2-1.ipynb
dcabezas98/IN
Análisis.
Counter(labels) visualize_centroids(centroids, np.array(data), atributos, denormCentroids=True) pairplot(data,atributos,labels) dataC=data.copy() dataC['cluster']=labels dataC # Box Plot n_var = len(atributos) fig, axes = plt.subplots(K, n_var, sharey=True, figsize=(15, 15)) fig.subplots_adjust(wspace=0, hspace=0) col...
_____no_output_____
MIT
practica2/accidentes2-1.ipynb
dcabezas98/IN
Con K=6 también obtenemos una ganancia considerable en las métricas, pero el análisis es más complejo debido al mayor número de clústers.
K=6 results = KMeans(n_clusters=K, random_state=0).fit(data_norm) labels=results.labels_ centroids=results.cluster_centers_ data2['cluster']=labels # Para después observar el resto de variables print(Counter(labels)) # Introduce un clúster con muertos, antes los despreciaba visualize_centroids(centroids, np.array(da...
_____no_output_____
MIT
practica2/accidentes2-1.ipynb
dcabezas98/IN
DBSCANAhora utilizaremos el algoritmo DBSCAN para formar los clústers
# Elección de un umbral de distancia por encima del cual no se mezclarán más clústers #E=[0.1,0.15,0.2,0.25,0.3,0.35] E=[0.1,0.11,0.12,0.13,0.14,0.15] # Con 0.35 en adelante ya hace un sólo clúster K=[] silhouette=[] calinski=[] for e in E: results = DBSCAN(eps=e, min_samples=50, n_jobs=4).fit(data_norm) sil, c...
_____no_output_____
MIT
practica2/accidentes2-1.ipynb
dcabezas98/IN
Elegimos epsilon=0.15
E=0.15 #0.12 produce 8 clústers y considera demasiados elementos (266) como ruidosos results = DBSCAN(eps=E, min_samples=50, n_jobs=4).fit(data_norm) labels=results.labels_ Counter(labels)
_____no_output_____
MIT
practica2/accidentes2-1.ipynb
dcabezas98/IN
Calculamos los centroides a mano
dataC=data.copy() dataC['cluster']=labels dataC # Eliminamos los 183 ejemplos que el algoritmo considera ruidosos dataC.drop(dataC[dataC['cluster']==-1].index,inplace=True) dataC centroids = dataC.groupby('cluster').mean() centroids centroids=centroids.values centroids visualize_centroids(centroids, np.array(data), atr...
180 882
MIT
practica2/accidentes2-1.ipynb
dcabezas98/IN
Estudio de variables circunstanciales y de tipo dentro en los clusters
Counter(data2.TIPO_ACCIDENTE) cluster_3=data2[data2.cluster==3] cluster_4=data2[data2.cluster==4] data2.shape[0], cluster_3.shape[0], cluster_4.shape[0] conjuntos=[data2,cluster_3,cluster_4] def prop(condicion,data): n=0 for i, row in data.iterrows(): if condicion(row): n+=1 return n/dat...
0.05913888423521528 0.17419354838709677 0.09593023255813954
MIT
practica2/accidentes2-1.ipynb
dcabezas98/IN
Load error measurements using `CurveMeasurements`. See `notebooks/measurements.ipynb` for more about reading error measurements.
curvems = CurveMeasurements() curvems.load_from_json('../data/no_pretr_ft.json') print(curvems)
-- num_train_samples: 25 test_errors: [74.04, 74.48, 74.07, 74.4, 75.95, 74.97, 74.02, 75.8, 74.6, 74.27] num_ms: 10 -- num_train_samples: 50 test_errors: [57.59, 58.45, 58.13, 58.44, 59.46, 58.14, 58.71, 58.22] num_ms: 8 -- num_train_samples: 100 test_errors: [45.01, 43.64, 45.06, 44.63] num_ms: 4 -- num_train_samples...
Apache-2.0
notebooks/curve.ipynb
allenai/learning-curve
Load default config. Modify `config.yaml` directly or update parameters once loaded.
cfg = OmegaConf.load('../lc/config.yaml') print('-'*20) print('Default config') print('-'*20) print(OmegaConf.to_yaml(cfg)) cfg.gamma_search = False print('-'*20) print('Modified config') print('-'*20) print(OmegaConf.to_yaml(cfg)) curve_estimator = LearningCurveEstimator(cfg) curve, objective = curve_estimator.estima...
Quality of the fit: 16.561 ------------------------------ Learning curve summary ------------------------------ error_400: 28.2575 beta_400: 16.0257 gamma: -0.5 alpha: 12.2318 eta: 320.5148
Apache-2.0
notebooks/curve.ipynb
allenai/learning-curve
Searching for gamma leads to better fit. To enable gamma search set `gamma_search` to `True` (default). When gamma search is disabled, `curve_estimator.estimate()` uses `cfg.gamma` to estimate the curve.
cfg.gamma_search = True curve, objective = curve_estimator.estimate(curvems) print('Quality of the fit:',objective) curve.print_summary(cfg.N)
Quality of the fit: 6.2808 ------------------------------ Learning curve summary ------------------------------ error_400: 27.9133 beta_400: 18.2284 gamma: -0.41 alpha: 5.6835 eta: 259.2864
Apache-2.0
notebooks/curve.ipynb
allenai/learning-curve
Use `curve_estimator.plot()` to visualizes the learning curve and the error measurements.
curve_estimator.plot(curve,curvems,label='No Pretr; Ft')
_____no_output_____
Apache-2.0
notebooks/curve.ipynb
allenai/learning-curve
You may also want to visualize the variance estimates. We recommend using the smoothed variance estimate but you can switch to using sample variance for curve estimation by setting `cfg.variance_type='sample'`. See `notebooks/variance.ipynb` for details on smooth variance estimation.
curve_estimator.err_mean_var_estimator.visualize(curvems)
_____no_output_____
Apache-2.0
notebooks/curve.ipynb
allenai/learning-curve
Plot multiple curves for easy comparison.
plot_metadata = [ ['../data/no_pretr_linear.json','No Pretr; Lin','r','--'], ['../data/no_pretr_ft.json','No Pretr; Ft','g','-'], ['../data/pretr_linear.json','Pretr; Lin','b','--'], ['../data/pretr_ft.json','Pretr; Ft','m','-'] ] for (json_path,label,color,linestyle) in plot_metadata: curvems.load_...
_____no_output_____
Apache-2.0
notebooks/curve.ipynb
allenai/learning-curve
What if you don't have all recommended error measurements?Technically, it is possible to use just 2 training set sizes to estimate the learning curve but the results may be susceptible to high variance. For instance, here we estimate the learning curve using only measurements on training set sizes of 400 and 200. Note...
import copy for (json_path,label,color,linestyle) in plot_metadata: curvems.load_from_json(json_path) curvems_filtered = copy.deepcopy(curvems) curvems_filtered.curvems = [errms for errms in curvems if errms.num_train_samples in [400,200]] curve, _ = curve_estimator.estimate(curvems_filtered) curve_...
_____no_output_____
Apache-2.0
notebooks/curve.ipynb
allenai/learning-curve
However, results improve considerably when using 3 training set sizes. Below, we estimate learning curve using measurements on training sets of sizes 400, 200, and 100.
for (json_path,label,color,linestyle) in plot_metadata: curvems.load_from_json(json_path) curvems_filtered = copy.deepcopy(curvems) curvems_filtered.curvems = [errms for errms in curvems if errms.num_train_samples in [400,200,100]] curve, _ = curve_estimator.estimate(curvems_filtered) curve_estimato...
_____no_output_____
Apache-2.0
notebooks/curve.ipynb
allenai/learning-curve
It may be possible to use much smaller training set sizes to compute learning curves as shown below. Note that the errors predicted by the curve at 200 and 400 training set sizes, which were not used to estimate the curve, are reasonably accurate.
for (json_path,label,color,linestyle) in plot_metadata: curvems.load_from_json(json_path) curvems_filtered = copy.deepcopy(curvems) curvems_filtered.curvems = [errms for errms in curvems if errms.num_train_samples in [100,50,25]] curve, _ = curve_estimator.estimate(curvems_filtered) curve_estimator....
_____no_output_____
Apache-2.0
notebooks/curve.ipynb
allenai/learning-curve
Quick and Lazy ApproachIt is possible to compute a decent learning curve with only 3 error measurments - 1 for each of full, half, and quarter dataset sizes. In this case, simply set `cfg.v_1` to a reasonable value and proceed as before. This is our recommended approach if you are in a rush. See `notebooks/basic_lazy_...
cfg.v_1 = 10 for (json_path,label,color,linestyle) in plot_metadata: curvems.load_from_json(json_path) curvems_filtered = copy.deepcopy(curvems) curvems_filtered.curvems = [errms for errms in curvems if errms.num_train_samples in [400,200,100]] for errms in curvems_filtered: # Through away all b...
_____no_output_____
Apache-2.0
notebooks/curve.ipynb
allenai/learning-curve
Exercise: GPU performance for fashion mnist dataset This notebook is derived from a tensorflow tutorial here: https://www.tensorflow.org/tutorials/keras/classificationSo please refer to it before starting work on this exercise You need to write code wherever you see `your code goes here` comment. You are going to do im...
# TensorFlow and tf.keras import tensorflow as tf from tensorflow import keras # Helper libraries import numpy as np import matplotlib.pyplot as plt print(tf.__version__) fashion_mnist = keras.datasets.fashion_mnist (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data() class_names = ['...
_____no_output_____
MIT
Program's_Contributed_By_Contributors/AI-Summer-Course/py-master/DeepLearningML/10_gpu_benchmarking/Exercise/exercise_fashion_mnist_gpu_benchmarking.ipynb
siddharthdeo99/Hacktoberfest2k21
5 Epochs performance comparison for 1 hidden layer
%%timeit -n1 -r1 with tf.device('/CPU:0'): # your code goes here %%timeit -n1 -r1 with tf.device('/GPU:0'): # your code goes here
_____no_output_____
MIT
Program's_Contributed_By_Contributors/AI-Summer-Course/py-master/DeepLearningML/10_gpu_benchmarking/Exercise/exercise_fashion_mnist_gpu_benchmarking.ipynb
siddharthdeo99/Hacktoberfest2k21
5 Epocs performance comparison with 5 hidden layers
%%timeit -n1 -r1 with tf.device('/CPU:0'): # your code here %%timeit -n1 -r1 with tf.device('/GPU:0'): # your code here
_____no_output_____
MIT
Program's_Contributed_By_Contributors/AI-Summer-Course/py-master/DeepLearningML/10_gpu_benchmarking/Exercise/exercise_fashion_mnist_gpu_benchmarking.ipynb
siddharthdeo99/Hacktoberfest2k21
Chapter 7This is the seventh in a series of notebooks related to astronomy data.As a continuing example, we will replicate part of the analysis in a recent paper, "[Off the beaten path: Gaia reveals GD-1 stars outside of the main stream](https://arxiv.org/abs/1805.00425)" by Adrian M. Price-Whelan and Ana Bonaca.In th...
# If we're running on Colab, install libraries import sys IN_COLAB = 'google.colab' in sys.modules if IN_COLAB: !pip install astroquery astro-gala pyia python-wget
_____no_output_____
MIT
07_plot.ipynb
abostroem/AstronomicalData
Making Figures That Tell a StorySo far the figure we've made have been "quick and dirty". Mostly we have used Matplotlib's default style, although we have adjusted a few parameters, like `markersize` and `alpha`, to improve legibility.Now that the analysis is done, it's time to think more about:1. Making professional...
import os from wget import download filename = 'gd1_merged.hdf5' path = 'https://github.com/AllenDowney/AstronomicalData/raw/main/data/' if not os.path.exists(filename): print(download(path+filename)) import pandas as pd selected = pd.read_hdf(filename, 'selected') import matplotlib.pyplot as plt def plot_secon...
_____no_output_____
MIT
07_plot.ipynb
abostroem/AstronomicalData
And here's what it looks like.
plt.figure(figsize=(10,2.5)) plot_second_selection(selected)
_____no_output_____
MIT
07_plot.ipynb
abostroem/AstronomicalData
AnnotationsThe figure in the paper uses three other features to present the results more clearly and compellingly:* A vertical dashed line to distinguish the previously undetected region of GD-1,* A label that identifies the new region, and* Several annotations that combine text and arrows to identify features of GD-1...
# Solution # plt.axvline(-55, ls='--', color='gray', # alpha=0.4, dashes=(6,4), lw=2) # plt.text(-60, 5.5, 'Previously\nundetected', # fontsize='small', ha='right', va='top'); # arrowprops=dict(color='gray', shrink=0.05, width=1.5, # headwidth=6, headlength=8, alpha=0.4) # plt...
_____no_output_____
MIT
07_plot.ipynb
abostroem/AstronomicalData
CustomizationMatplotlib provides a default style that determines things like the colors of lines, the placement of labels and ticks on the axes, and many other properties.There are several ways to override these defaults and customize your figures:* To customize only the current figure, you can call functions like `ti...
# Solution # plt.gca().tick_params(top=True, right=True)
_____no_output_____
MIT
07_plot.ipynb
abostroem/AstronomicalData
rcParamsIf you want to make a customization that applies to all figures in a notebook, you can use `rcParams`.Here's an example that reads the current font size from `rcParams`:
plt.rcParams['font.size']
_____no_output_____
MIT
07_plot.ipynb
abostroem/AstronomicalData
And sets it to a new value:
plt.rcParams['font.size'] = 14
_____no_output_____
MIT
07_plot.ipynb
abostroem/AstronomicalData