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 |
|---|---|---|---|---|---|
Partie 2 : Code de César Aléatoire Implementation Voici une legere modification des fonctions d'encryptions du debut de l'exercice.La seule difference etant qu'au lieu de mélanger par décalage, la position de chaque lettre est aléatoire | def convertAlphabetsRand(messageCharNumList, numList, numListToConvert, encrypt = True) :
index = 0
newList = []
for val in messageCharNumList:
indexOfLetter = numListToConvert.index(val)
newList.append(numList[indexOfLetter])
index += 1
if encrypt :
return ' '.join(map(chr,newL... | <ipython-input-17-6c852534887f>:14: DeprecationWarning: The *random* parameter to shuffle() has been deprecated
since Python 3.9 and will be removed in a subsequent version.
random.shuffle(alphabetListShuffled, seed)
| BSD-3-Clause | Exercises/Hands_on_Cypher/Hands_on_Cypher.ipynb | AGuyNextDoor/AProfNextDoor |
Cracking a Random Cypher Voici un cypher généré avec l'algorithme d'encryption de cypher encryptMessageRand.Le but est d'arriver a decrypter le message grace a l'analyse de frequence des caracteres du message. Le message code est en anglais, donc un morceau de texte anglais vous est donne pour que vous puissez compare... | random_cypher = 'J \t _ n \t i _ q q z \t u p \t k p j 2 \t x j u i \t z p v \t u p e _ z \t j 2 \t x i _ u \t x j m m \t h p \t e p x 2 \t j 2 \t i j t u p s z \t _ t \t u i f \t h s f _ u f t u \t e f n p 2 t u s _ u j p 2 \t 1 p s \t 1 s f f e p n \t j 2 \t u i f \t i j t u p s z \t p 1 \t p v s \t 2 _ u j p 2 / \t ... | _____no_output_____ | BSD-3-Clause | Exercises/Hands_on_Cypher/Hands_on_Cypher.ipynb | AGuyNextDoor/AProfNextDoor |
Import Packages | import re
import numpy as np
import pandas as pd
from pprint import pprint
# Gensim
import gensim
import gensim.corpora as corpora
from gensim.utils import simple_preprocess
from gensim.models import CoherenceModel
# spacy for lemmatization
import spacy
# Plotting tools
import pyLDAvis
import pyLDAvis.gensim # don'... | _____no_output_____ | MIT | NG_LDA.ipynb | shivamras304/LyricsMatch_DataX1 |
Importing Lyrics data | # Import Dataset
df = pd.read_csv('')
df1.head()
# df = df1.head(10)
print(df.genre.unique())
print(df.artist.unique())
print(df.year.unique()) | [2007 2008 2006 2016 2004]
| MIT | NG_LDA.ipynb | shivamras304/LyricsMatch_DataX1 |
Remove newline characters | # Convert to list
# data = df.lyrics.values.tolist()
# data = [re.sub('[^a-zA-Z ]' ,'', str(sent)) for sent in data]
# pprint(data[:1])
# def sent_to_words(sentences):
# for sentence in sentences:
# yield(gensim.utils.simple_preprocess(str(sentence), deacc=True)) # deacc=True removes punctuations
# data... | [['mother', 'dear', 'motherits', 'cold', 'tonightlike', 'every', 'otherevery', 'other', 'nightbut', 'never', 'feelfeel', 'it', 'anywayim', 'gonna', 'need', 'sooni', 'can', 'feel', 'itfeel', 'it', 'beginbut', 'dont', 'knowhow', 'im', 'gonna', 'payit', 'must', 'be', 'aboutmid', 'december', 'right', 'nowand', 'think', 'im... | MIT | NG_LDA.ipynb | shivamras304/LyricsMatch_DataX1 |
Creating Bigram and Trigram ModelsBigrams are two words frequently occurring together in the document. Trigrams are 3 words frequently occurring.Some examples in our example are: ‘front_bumper’, ‘oil_leak’, ‘maryland_college_park’ etc.Gensim’s Phrases model can build and implement the bigrams, trigrams, quadgrams and ... | # Build the bigram and trigram models
bigram = gensim.models.Phrases(data_words, min_count=5, threshold=100) # higher threshold fewer phrases.
trigram = gensim.models.Phrases(bigram[data_words], threshold=100)
# Faster way to get a sentence clubbed as a trigram/bigram
bigram_mod = gensim.models.phrases.Phraser(bigra... | ['mother', 'dear', 'motherits', 'cold', 'tonightlike', 'every', 'otherevery', 'other', 'nightbut', 'never', 'feelfeel', 'it', 'anywayim', 'gonna', 'need', 'sooni', 'can', 'feel', 'itfeel', 'it', 'beginbut', 'dont', 'knowhow', 'im', 'gonna', 'payit', 'must', 'be', 'aboutmid', 'december', 'right', 'nowand', 'think', 'im'... | MIT | NG_LDA.ipynb | shivamras304/LyricsMatch_DataX1 |
Remove Stopwords, Make Bigrams and LemmatizeThe bigrams model is ready. Let’s define the functions to remove the stopwords, make bigrams and lemmatization and call them sequentially. | # Define functions for stopwords, bigrams, trigrams and lemmatization
def remove_stopwords(texts):
return [[word for word in simple_preprocess(str(doc)) if word not in stop_words] for doc in texts]
def make_bigrams(texts):
return [bigram_mod[doc] for doc in texts]
def make_trigrams(texts):
return [trigram... | _____no_output_____ | MIT | NG_LDA.ipynb | shivamras304/LyricsMatch_DataX1 |
Let’s call the functions in order. | # Remove Stop Words
data_words_nostops = remove_stopwords(data_words)
# Form Bigrams
data_words_bigrams = make_bigrams(data_words_nostops)
# Initialize spacy 'en' model, keeping only tagger component (for efficiency)
# python3 -m spacy download en
nlp = spacy.load('en', disable=['parser', 'ner'])
# Do lemmatization ... | [['mother', 'dear', 'motherit', 'cold', 'tonightlike', 'otherevery', 'nightbut', 'never', 'feelfeel', 'anywayim', 'go', 'need', 'sooni', 'feel', 'itfeel', 'beginbut', 'do', 'not', 'knowhow', 'be', 'go', 'payit', 'must', 'aboutmid', 'december', 'right', 'nowand', 'think', 'be', 'real', 'surehow', 'old', 'feeli', 'lose',... | MIT | NG_LDA.ipynb | shivamras304/LyricsMatch_DataX1 |
Create the Dictionary and Corpus needed for Topic ModelingThe two main inputs to the LDA topic model are the dictionary(id2word) and the corpus. Let’s create them. | # Create Dictionary
id2word = corpora.Dictionary(data_lemmatized)
# Create Corpus
texts = data_lemmatized
# Term Document Frequency
corpus = [id2word.doc2bow(text) for text in texts]
# View
print(corpus[:1]) | [[(0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 3), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 1), (13, 2), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1), (19, 1), (20, 1), (21, 1), (22, 1), (23, 1), (24, 1), (25, 1), (26, 2), (27, 2), (28, 1), (29, 1), (30, 1), (31, 1), (32, 1), (33, 1), (34, 1), (35, 1), (36,... | MIT | NG_LDA.ipynb | shivamras304/LyricsMatch_DataX1 |
Gensim creates a unique id for each word in the document. The produced corpus shown above is a mapping of (word_id, word_frequency).For example, (0, 1) above implies, word id 0 occurs once in the first document. Likewise, word id 1 occurs twice and so on.This is used as the input by the LDA model.If you want to see wha... | id2word[10]
# Human readable format of corpus (term-frequency)
[[(id2word[id], freq) for id, freq in cp] for cp in corpus[:1]] | _____no_output_____ | MIT | NG_LDA.ipynb | shivamras304/LyricsMatch_DataX1 |
Building the Topic ModelWe have everything required to train the LDA model. In addition to the corpus and dictionary, you need to provide the number of topics as well.Apart from that, alpha and eta are hyperparameters that affect sparsity of the topics. According to the Gensim docs, both defaults to 1.0/num_topics pri... | # Build LDA model
lda_model = gensim.models.ldamodel.LdaModel(corpus=corpus,
id2word=id2word,
num_topics=20,
random_state=100,
update_every=1,
... | [(8,
[('stand', 0.14285714285714285),
('betterpull', 0.08571428571428572),
('cry', 0.08571428571428572),
('youbaby', 0.05714285714285714),
('town', 0.02857142857142857),
('magazinewhen', 0.02857142857142857),
('pageantive', 0.02857142857142857),
('saywont', 0.02857142857142857),
('make', 0.028... | MIT | NG_LDA.ipynb | shivamras304/LyricsMatch_DataX1 |
How to find the optimal number of topics for LDA?My approach to finding the optimal number of topics is to build many LDA models with different values of number of topics (k) and pick the one that gives the highest coherence value.Choosing a ‘k’ that marks the end of a rapid growth of topic coherence usually offers mea... | def compute_coherence_values(dictionary, corpus, texts, limit, start=2, step=3):
"""
Compute c_v coherence for various number of topics
Parameters:
----------
dictionary : Gensim dictionary
corpus : Gensim corpus
texts : List of input texts
limit : Max num of topics
Returns:
--... | _____no_output_____ | MIT | NG_LDA.ipynb | shivamras304/LyricsMatch_DataX1 |
Find the most representative document for each topicSometimes just the topic keywords may not be enough to make sense of what a topic is about. So, to help with understanding the topic, you can find the documents a given topic has contributed to the most and infer the topic by reading that document. Whew!! | # Group top 5 sentences under each topic
sent_topics_sorteddf_mallet = pd.DataFrame()
sent_topics_outdf_grpd = df_topic_sents_keywords.groupby('Dominant_Topic')
for i, grp in sent_topics_outdf_grpd:
sent_topics_sorteddf_mallet = pd.concat([sent_topics_sorteddf_mallet,
... | _____no_output_____ | MIT | NG_LDA.ipynb | shivamras304/LyricsMatch_DataX1 |
Evaluate AminoAcids Prediction | %matplotlib inline
import pylab
pylab.rcParams['figure.figsize'] = (15.0, 12.0)
import os
import sys
import numpy as np
from shutil import copyfile
from src.python.aa_predict import *
import src.python.aa_predict as AA
checkpoint_path = "../../data/trained/aapred_cnn_latest.tar"
emb_dim = 5
win_size = 10
mo... | => loading checkpoint '../../data/trained/aapred_cnn_latest.tar'
=> loaded checkpoint '../../data/trained/aapred_cnn_latest.tar' (epoch 8)
| MIT | src/python/aapred-drilldown.ipynb | yotamfr/prot2vec |
Define Evaluation Function(s) |
import torch
import torch.nn as nn
from torch.autograd import Variable
from pymongo import MongoClient
| _____no_output_____ | MIT | src/python/aapred-drilldown.ipynb | yotamfr/prot2vec |
1 2 3 Predict... |
class_names = sorted(dictionary.keys(), key=lambda aa: dictionary[aa])
client = MongoClient("mongodb://127.0.0.1:27017")
db = client['prot2vec']
global collection_test, size_test, verbose
AA.collection_test = db['sprot']
AA.size_test = 100
AA.verbose = True
AA.use_cuda = False
batch_size = 32
loader = WindowB... | 100%
| MIT | src/python/aapred-drilldown.ipynb | yotamfr/prot2vec |
Evaluate | import itertools
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
# http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
... | Confusion matrix, without normalization
| MIT | src/python/aapred-drilldown.ipynb | yotamfr/prot2vec |
Plot Accuracy | ###https://matplotlib.org/examples/api/barchart_demo.html
def plot_accuracy(title, scores):
N = len(scores)
acc = list(scores.values())
ind = np.arange(N) # the x locations for the groups
width = 0.2 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(ind, acc, width, ... | _____no_output_____ | MIT | src/python/aapred-drilldown.ipynb | yotamfr/prot2vec |
Create a Learner for inference | from fastai import *
from fastai.gen_doc.nbdoc import * | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
In this tutorial, we'll see how the same API allows you to create an empty [`DataBunch`](/basic_data.htmlDataBunch) for a [`Learner`](/basic_train.htmlLearner) at inference time (once you have trained your model) and how to call the `predict` method to get the predictions on a single item. | jekyll_note("""As usual, this page is generated from a notebook that you can find in the docs_srs folder of the
[fastai repo](https://github.com/fastai/fastai). We use the saved models from [this tutorial](/tutorial.data.html) to
have this notebook run fast.
""") | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
Vision To quickly get acces to all the vision functions inside fastai, we use the usual import statements. | from fastai import *
from fastai.vision import * | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
A classification problem Let's begin with our sample of the MNIST dataset. | mnist = untar_data(URLs.MNIST_TINY)
tfms = get_transforms(do_flip=False) | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
It's set up with an imagenet structure so we use it to split our training and validation set, then labelling. | data = (ImageItemList.from_folder(mnist)
.split_by_folder()
.label_from_folder()
.transform(tfms, size=32)
.databunch()
.normalize(imagenet_stats)) | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
Now that our data has been properly set up, we can train a model. Once the time comes to deploy it for inference, we'll need to save the information this [`DataBunch`](/basic_data.htmlDataBunch) contains (classes for instance), to do this, we call `data.export()`. This will create an 'export.pkl' file that you'll need ... | data.export() | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
To create the [`DataBunch`](/basic_data.htmlDataBunch) for inference, you'll need to use the `load_empty` method. Note that for now, transforms and normalization aren't saved inside the export file. This is going to be integrated in a future version of the library. For now, we pass the transforms we applied on the vali... | empty_data = ImageDataBunch.load_empty(mnist, tfms=tfms[1],size=32).normalize(imagenet_stats)
learn = create_cnn(empty_data, models.resnet18)
learn.load('mini_train'); | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
You can now get the predictions on any image via `learn.predict`. | img = data.train_ds[0][0]
learn.predict(img) | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
It returns a tuple of three things: the object predicted (with the class in this instance), the underlying data (here the corresponding index) and the raw probabilities. A multilabel problem Now let's try these on the planet dataset, which is a little bit different in the sense that each image can have multiple tags (... | planet = untar_data(URLs.PLANET_TINY)
planet_tfms = get_transforms(flip_vert=True, max_lighting=0.1, max_zoom=1.05, max_warp=0.) | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
Here each images is labelled in a file named 'labels.csv'. We have to add 'train' as a prefix to the filenames, '.jpg' as a suffix and he labels are separated by spaces. | data = (ImageItemList.from_csv(planet, 'labels.csv', folder='train', suffix='.jpg')
.random_split_by_pct()
.label_from_df(sep=' ')
.transform(planet_tfms, size=128)
.databunch()
.normalize(imagenet_stats)) | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
Again, we call `data.export()` to export our data object properties. | data.export() | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
We can then create the [`DataBunch`](/basic_data.htmlDataBunch) for inference, by using the `load_empty` method as before. | empty_data = ImageDataBunch.load_empty(planet, tfms=tfms[1],size=32).normalize(imagenet_stats)
learn = create_cnn(empty_data, models.resnet18)
learn.load('mini_train'); | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
And we get the predictions on any image via `learn.predict`. | img = data.train_ds[0][0]
learn.predict(img) | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
Here we can specify a particular theshold to consider the predictions are a hit or not. The default is 0.5 but we can change it. | learn.predict(img, thresh=0.3) | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
A regression example For the next example, we are going to use the [BIWI head pose](https://data.vision.ee.ethz.ch/cvl/gfanelli/head_pose/head_forest.htmldb) dataset. On pictures of persons, we have to find the center of their face. For the fastai docs, we have built a small subsample of the dataset (200 images) and p... | biwi = untar_data(URLs.BIWI_SAMPLE)
fn2ctr = pickle.load(open(biwi/'centers.pkl', 'rb')) | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
To grab our data, we use this dictionary to label our items. We also use the [`PointsItemList`](/vision.data.htmlPointsItemList) class to have the targets be of type [`ImagePoints`](/vision.image.htmlImagePoints) (which will make sure the data augmentation is properly applied to them). When calling [`transform`](/tabul... | data = (ImageItemList.from_folder(biwi)
.random_split_by_pct()
.label_from_func(lambda o:fn2ctr[o.name], label_cls=PointsItemList)
.transform(get_transforms(), tfm_y=True, size=(120,160))
.databunch()
.normalize(imagenet_stats)) | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
As before, the road to inference is pretty straightforward: export the data, then load an empty [`DataBunch`](/basic_data.htmlDataBunch). | data.export()
empty_data = ImageDataBunch.load_empty(biwi, tfms=get_transforms()[1], tfm_y=True, size=(120,60)).normalize(imagenet_stats)
learn = create_cnn(empty_data, models.resnet18)
learn.load('mini_train'); | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
And now we can a prediction on an image. | img = data.train_ds[0][0]
learn.predict(img) | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
To visualize the predictions, we can use the [`Image.show`](/vision.image.htmlImage.show) method. | img.show(y=learn.predict(img)[0]) | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
A segmentation example Now we are going to look at the [camvid dataset](http://mi.eng.cam.ac.uk/research/projects/VideoRec/CamVid/) (at least a small sample of it), where we have to predict the class of each pixel in an image. Each image in the 'images' subfolder as an equivalent in 'labels' that is its segmentations ... | camvid = untar_data(URLs.CAMVID_TINY)
path_lbl = camvid/'labels'
path_img = camvid/'images' | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
We read the classes in 'codes.txt' and the function maps each image filename with its corresponding mask filename. | codes = np.loadtxt(camvid/'codes.txt', dtype=str)
get_y_fn = lambda x: path_lbl/f'{x.stem}_P{x.suffix}' | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
The data block API allows us to uickly get everything in a [`DataBunch`](/basic_data.htmlDataBunch) and then we can have a look with `show_batch`. | data = (SegmentationItemList.from_folder(path_img)
.random_split_by_pct()
.label_from_func(get_y_fn, classes=codes)
.transform(get_transforms(), tfm_y=True, size=128)
.databunch(bs=16, path=camvid)
.normalize(imagenet_stats)) | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
As before, we export the data then create an empty [`DataBunch`](/basic_data.htmlDataBunch) that we pass to a [`Learner`](/basic_train.htmlLearner). | data.export()
empty_data = ImageDataBunch.load_empty(camvid, tfms=get_transforms()[1], tfm_y=True, size=128).normalize(imagenet_stats)
learn = Learner.create_unet(empty_data, models.resnet18)
learn.load('mini_train'); | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
And now we can a prediction on an image. | img = data.train_ds[0][0]
learn.predict(img) | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
To visualize the predictions, we can use the [`Image.show`](/vision.image.htmlImage.show) method. | img.show(y=learn.predict(img)[0]) | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
Text Next application is text, so let's start by importing everything we'll need. | from fastai import *
from fastai.text import * | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
Language modelling First let's look a how to get a language model ready for inference. Since we'll load the model trained in the [visualize data tutorial](/tutorial.data.html), we load the vocabulary used there. | imdb = untar_data(URLs.IMDB_SAMPLE)
vocab = Vocab(pickle.load(open(imdb/'tmp'/'itos.pkl', 'rb')))
data_lm = (TextList.from_csv(imdb, 'texts.csv', cols='text', vocab=vocab)
.random_split_by_pct()
.label_for_lm()
.databunch()) | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
Like in vision, we just have to type `data_lm.export()` to save all the information inside the [`DataBunch`](/basic_data.htmlDataBunch) we'll need. In this case, this includes all the vocabulary we created. | data_lm.export() | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
Now let's define a language model learner from an empty data object. | empty_data = TextLMDataBunch.load_empty(imdb)
learn = language_model_learner(empty_data)
learn.load('mini_train_lm'); | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
Then we can predict with the usual method, here we can specify how many words we want the model to predict. | learn.predict('This is a simple test of', n_words=20) | Total time: 00:01
| Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
Classification Now let's see a classification example. We have to use the same vocabulary as for the language model if we want to be able to use the encoder we saved. | data_clas = (TextList.from_csv(imdb, 'texts.csv', cols='text', vocab=vocab)
.split_from_df(col='is_valid')
.label_from_df(cols='label')
.databunch(bs=42)) | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
Again we export the data. | data_clas.export() | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
Now let's define a text classifier from an empty data object. | empty_data = TextClasDataBunch.load_empty(imdb)
learn = text_classifier_learner(empty_data)
learn.load('mini_train_clas'); | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
Then we can predict with the usual method. | learn.predict('I really loved that movie!') | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
Tabular Last application brings us to tabular data. First let's import everything we'll need. | from fastai import *
from fastai.tabular import * | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
We'll use a sample of the [adult dataset](https://archive.ics.uci.edu/ml/datasets/adult) here. Once we read the csv file, we'll need to specify the dependant variable, the categorical variables, the continuous variables and the processors we want to use. | adult = untar_data(URLs.ADULT_SAMPLE)
df = pd.read_csv(adult/'adult.csv')
dep_var = '>=50k'
cat_names = ['workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race', 'sex', 'native-country']
cont_names = ['education-num', 'hours-per-week', 'age', 'capital-loss', 'fnlwgt', 'capital-gain']
procs = [F... | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
Then we can use the data block API to grab everything together before using `data.show_batch()` | data = (TabularList.from_df(df, path=adult, cat_names=cat_names, cont_names=cont_names, procs=procs)
.split_by_idx(valid_idx=range(800,1000))
.label_from_df(cols=dep_var)
.databunch()) | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
We define a [`Learner`](/basic_train.htmlLearner) object that we fit and then save the model. | learn = tabular_learner(data, layers=[200,100], metrics=accuracy)
learn.fit(1, 1e-2)
learn.save('mini_train') | Total time: 00:04
epoch train_loss valid_loss accuracy
1 0.328005 0.354749 0.820000 (00:04)
| Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
As in the other applications, we just have to type `data.export()` to save everything we'll need for inference (here the inner state of each processor). | data.export() | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
Then we create an empty data object and a learner from it like before. | data = TabularDataBunch.load_empty(adult)
learn = tabular_learner(data, layers=[200,100])
learn.load('mini_train'); | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
And we can predict on a row of dataframe that has the right `cat_names` and `cont_names`. | learn.predict(df.iloc[0]) | _____no_output_____ | Apache-2.0 | docs_src/tutorial.inference.ipynb | ahmedsharf11/fastai |
Example 2: mouse blood lineage networksA pipeline providing an example of ShareNet's usage on a mouse blood lineage dataset is included in the ```~/sharenet/example2``` subdirectory. Here, we go through the different steps associated with this pipeline. | %matplotlib inline
import os
import numpy as np
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd
def convert_method_name(name):
method_dict = {'genie': 'GENIE3','pidc':'PIDC','corr': 'Pearson','gaussian': 'BVS'}
for m in method_dict.keys():
if m in name:
... | _____no_output_____ | MIT | example2/example2.ipynb | alexw16/sharenet |
Running ShareNet A Bash script, named ```run_example2.sh```, is included in ```~/sharenet/example2``` subdirectory. This script runs the below command, which fits the ShareNet model to the set of networks inferred using PIDC in the mouse blood lineage dataset. The input data required to perform this step (i.e. the ini... | data_dir = '../sharenet/example2/reference'
baseline_df = pd.read_csv(os.path.join(data_dir,'baseline_auprc.csv'))
baseline_df.index = baseline_df['ref_network'].values
from scipy.stats import wilcoxon
results_dir = '../sharenet/example2/accuracy'
method = 'sharenet.nc10'
measure = 'auprc'
base_... | _____no_output_____ | MIT | example2/example2.ipynb | alexw16/sharenet |
Wilcoxon Rank-Sum Test | print(wilcoxon(df['x2'],y=df['x1'],alternative='greater')) | WilcoxonResult(statistic=1829.0, pvalue=8.570746990858083e-12)
| MIT | example2/example2.ipynb | alexw16/sharenet |
Setup | # Set up the location of observatory
palomar = Observer.at_site('Palomar') | _____no_output_____ | MIT | LeonardoZhu_NightSky/LeonardoZhu_Planning Observations.ipynb | pratsingh/NightSky |
We get the dataset from https://www.cosmos.esa.int/web/hipparcos/sample-tables-1 | data = pd.read_csv('data2.csv')
#Pick out the objects having names
mask = list()
for n in range(len(data['Name'])):
if(isinstance(data['Name'][n],str)):
mask.append(True)
else:
mask.append(False)
data[mask].to_csv('hipparcos.csv')
star_table = pd.read_csv('hipparcos.csv')
#Set the observing wind... | _____no_output_____ | MIT | LeonardoZhu_NightSky/LeonardoZhu_Planning Observations.ipynb | pratsingh/NightSky |
Visibility | #Complie a list of all defined objects
stars = list()
for s in range(len(star_table['Name'])):
coords = SkyCoord(star_table['ra (deg)'][s]*u.deg,
star_table['dec (deg)'][s]*u.deg,
frame='icrs')
stars.append(FixedTarget(name=star_table['Name'][s],... | _____no_output_____ | MIT | LeonardoZhu_NightSky/LeonardoZhu_Planning Observations.ipynb | pratsingh/NightSky |
Create an observability table | time = Time(["2019-10-15 00:00", "2019-10-30 23:59"])
#The moon's illumination values are from: https://www.calendar-12.com/moon_calendar/2019/october
#Use the mean value of the moon's illumination during our observing window
constraint = [AltitudeConstraint(30*u.deg, 90*u.deg),AirmassConstraint(2),
AtNi... | _____no_output_____ | MIT | LeonardoZhu_NightSky/LeonardoZhu_Planning Observations.ipynb | pratsingh/NightSky |
Therefore, these ten objects can be observed through the whole observing window. Moon Phase We found the moon phases from: https://www.calendar-12.com/moon_calendar/2019/octoberAnd based on the moon phases calendar, the moon will be waning gibbous on Oct 15th, 2019 (the start of our observing window) and keep waning u... | #The moon's illumination
for i in range(len(obs_dates)):
moon_ratio = moon_illumination(obs_dates[i])
print(obs_dates[i])
print(moon_ratio)
print("\n") | 2019-10-15 00:00:00.000
0.9865561943920241
2019-10-16 00:00:00.000
0.9562520875685778
2019-10-17 00:00:00.000
0.9074664247952995
2019-10-18 00:00:00.000
0.841225405905627
2019-10-19 00:00:00.000
0.759277143961225
2019-10-20 00:00:00.000
0.6641422433892282
2019-10-21 00:00:00.000
0.5591863674409921
2019-10... | MIT | LeonardoZhu_NightSky/LeonardoZhu_Planning Observations.ipynb | pratsingh/NightSky |
Combined with the moon's illumination, the moon will interfere with our observation somewhat at the beginning of our observing window. And with the moon waning later, the interference would be ignored. Visibility one month later | #New time range
time2 = Time(["2019-11-15 00:00", "2019-11-30 23:59"])
obs_dates2 = list()
for i in range(15,31):
date = "2019-11-" + str(i)
time = Time(date)
obs_dates2.append(time)
# The moon's illumination values are from: https://www.calendar-12.com/moon_calendar/2019/november
#Use the mean value of the... | _____no_output_____ | MIT | LeonardoZhu_NightSky/LeonardoZhu_Planning Observations.ipynb | pratsingh/NightSky |
*本文讲解了概率编程的基本模块*- 随机函数是某个数据生成过程的模型- 初等随机函数就是一类可以显式计算样本概率的随机函数 核心问题:- 样本是有名字的,如何获得样本的名字?如何使用样本的名字? An Introduction to Models in PyroThe basic unit of probabilistic programs is the _stochastic function_. This is an arbitrary Python callable that combines two ingredients:- deterministic Python code; and- primitive stocha... | import torch
import pyro
pyro.set_rng_seed(101) | _____no_output_____ | MIT | tutorial/source/01-intro_part_i(blueprint).ipynb | HeyangGong/Pyro4CI |
Primitive Stochastic Functions原始随机函数是构建模型的基础模块,下面给出正态分布的原始随机函数及其使用。 | loc = 0. # mean zero
scale = 1. # unit variance
normal = torch.distributions.Normal(loc, scale) # create a normal distribution object
x = normal.rsample() # draw a sample from N(0,1)
print("sample", x)
print("log prob", normal.log_prob(x)) # score the sample from N(0,1)
[x for x in dir(normal) if not '_' in x] | _____no_output_____ | MIT | tutorial/source/01-intro_part_i(blueprint).ipynb | HeyangGong/Pyro4CI |
随机函数有几个常见的方法,包括抽样,计算概率等。 A Simple Model 所有的 probalistic programs 是通过 primitive functions and deterministic computation 组合得到的。我们最终的目的是要是用 probablistic programming 来模拟真实世界,我们现在从一个具体的例子出发。现在我们有一堆关于每天平均气温和天气情况的数据。我们想到天气情况和气温的关系。如下的简单随机函数描述了数据的生成过程。 | from graphviz import Source
Source('digraph{rankdir=LR; cloudy -> temperature}')
def weather():
cloudy = torch.distributions.Bernoulli(0.3).sample()
cloudy = 'cloudy' if cloudy.item() == 1.0 else 'sunny'
mean_temp = {'cloudy': 55.0, 'sunny': 75.0}[cloudy]
scale_temp = {'cloudy': 10.0, 'sunny': 15.0}[clo... | ('cloudy', 46.847618103027344)
| MIT | tutorial/source/01-intro_part_i(blueprint).ipynb | HeyangGong/Pyro4CI |
However, `weather` is entirely independent of Pyro - it only calls PyTorch. **We need to turn it into a Pyro program if we want to use this model for anything other than sampling fake data.** 这个模型除生成假数据还能干嘛呢?定义观测数据用于变分推断,提取生成过程中间结果? Model with PyroThe `pyro.sample` Primitive | %psource pyro.sample
# 到底该样本的名字用在哪里?怎么获取?
x = pyro.sample("my_sample", pyro.distributions.Normal(loc, scale))
print(x)
torch.distributions.Normal(loc, scale).rsample(), pyro.distributions.Normal(loc, scale).rsample(), \
torch.distributions.Normal(loc, scale), pyro.distributions.Normal(loc, scale) | _____no_output_____ | MIT | tutorial/source/01-intro_part_i(blueprint).ipynb | HeyangGong/Pyro4CI |
Just like a direct call to `torch.distributions.Normal().rsample()`, this returns a sample from the unit normal distribution. **The crucial difference** is that this sample is _named_. Pyro's backend uses these names to uniquely identify sample statements and _change their behavior at runtime_ depending on how the encl... | def weather():
cloudy = pyro.sample('cloudy', pyro.distributions.Bernoulli(0.3))
cloudy = 'cloudy' if cloudy.item() == 1.0 else 'sunny'
mean_temp = {'cloudy': 55.0, 'sunny': 75.0}[cloudy]
scale_temp = {'cloudy': 10.0, 'sunny': 15.0}[cloudy]
temp = pyro.sample('temp', pyro.distributions.Normal(mean_t... | ('cloudy', 64.5440444946289)
('sunny', 94.37557983398438)
('sunny', 72.5186767578125)
| MIT | tutorial/source/01-intro_part_i(blueprint).ipynb | HeyangGong/Pyro4CI |
Procedurally, `weather()` is still a non-deterministic Python callable that returns two random samples. Because the randomness is now invoked with `pyro.sample`, however, it is much more than that. In particular `weather()` specifies a joint probability distribution over two named random variables: `cloudy` and `temp`.... | from graphviz import Source
Source('digraph{rankdir=LR; cloudy -> temperature -> ice_cream; cloudy -> ice_cream}')
def ice_cream_sales():
cloudy, temp = weather()
expected_sales = 200. if cloudy == 'sunny' and temp > 80.0 else 50.
ice_cream = pyro.sample('ice_cream', pyro.distributions.Normal(expected_sales... | _____no_output_____ | MIT | tutorial/source/01-intro_part_i(blueprint).ipynb | HeyangGong/Pyro4CI |
**This kind of modularity, familiar to any programmer, is obviously very powerful.** But is it powerful enough to encompass all the different kinds of models we'd like to express? ---这种模块化是非常强大的. 下面给出一个随机控制得到几何分布的例子. 几何分布:一种方程思维是 $T = \sum_{i=1}^{T-1}I(X_i = 0) + I(X_T = 1)$, 这个似乎没有什么用, 还是从定义出发, 第一次抽样到 1 的次数. 这种 X 与 T ... | def geometric(p, t=None):
if t is None:
t = 0
x = pyro.sample("x_{}".format(t), pyro.distributions.Bernoulli(p)) # 这里体现了样本名字的作用!!!
if x.item() == 1:
return 0
else:
return 1 + geometric(p, t + 1)
print(geometric(0.5)) | 3
| MIT | tutorial/source/01-intro_part_i(blueprint).ipynb | HeyangGong/Pyro4CI |
Note that the names `x_0`, `x_1`, etc., in `geometric()` are generated dynamically and that different executions can have different numbers of named random variables. We are also free to define stochastic functions that accept as input or produce as output other stochastic functions: | from graphviz import Source
Source('digraph{rankdir=LR; scale, mu_latent -> z1, z2 -> y}')
def normal_product(loc, scale):
z1 = pyro.sample("z1", pyro.distributions.Normal(loc, scale))
z2 = pyro.sample("z2", pyro.distributions.Normal(loc, scale))
y = z1 * z2
return y
def make_normal_normal():
mu_la... | tensor(0.7048)
| MIT | tutorial/source/01-intro_part_i(blueprint).ipynb | HeyangGong/Pyro4CI |
Entity Linking Task Description[Entity linking](https://en.wikipedia.org/wiki/Entity_linking) is the process of connecting concepts mentioned in natural language to their canonical forms stored in a knowledge base. For example, say a knowledge base contained the entity 'ID3452 influenza' and we wanted to process some... | # Download data
DATA_DIR = "tiny_example_data"
wget.download('https://github.com/vadam5/NeMo/blob/main/examples/nlp/entity_linking/data/tiny_example_data.zip?raw=true',
os.path.join("tiny_example_data.zip"))
!unzip tiny_example_data.zip | _____no_output_____ | Apache-2.0 | tutorials/nlp/Entity_Linking_Medical.ipynb | vadam5/NeMo |
In this tutorial we will be using a tiny toy dataset to demonstrate how to use NeMo's entity linking model functionality. The dataset includes synonyms for 12 medical concepts. Here's the dataset before preprocessing: | raw_data = pd.read_csv(os.path.join(DATA_DIR, "tiny_example_dev_data.csv"), names=["ID", "CONCEPT"], index_col=False)
print(raw_data) | ID CONCEPT
0 1 Head ache
1 1 Headache
2 1 Migraine
3 1 Pain in the head
4 1 ... | Apache-2.0 | tutorials/nlp/Entity_Linking_Medical.ipynb | vadam5/NeMo |
We've already paired off the concepts for this dataset with the format `ID concept_synonym1 concept_synonym2`. Here are the first ten rows: | training_data = pd.read_table(os.path.join(DATA_DIR, "tiny_example_train_pairs.tsv"), names=["ID", "CONCEPT_SYN1", "CONCEPT_SYN2"], delimiter='\t')
print(training_data.head(10)) | ID CONCEPT_SYN1 CONCEPT_SYN2
0 1 Pain in the head cephalgia
1 1 Pain in the head cephalalgia
2 1 Migraine cephalgia
3 1 Head ache Pain in the head
4 1 Head ache Migraine
5 1 Head ache cephalalgia
6 1 Headache ... | Apache-2.0 | tutorials/nlp/Entity_Linking_Medical.ipynb | vadam5/NeMo |
Use the [Unified Medical Language System (UMLS)](https://www.nlm.nih.gov/research/umls/index.html) dataset for full medical domain entity linking training. The data contains over 9 million entities and is a table of medical concepts with their corresponding concept IDs (CUI). After [requesting a free license and making... | # Download config
wget.download("https://raw.githubusercontent.com/vadam5/NeMo/main/examples/nlp/entity_linking/conf/tiny_example_entity_linking_config.yaml",
os.path.join("tiny_example_entity_linking_config.yaml"))
# Load in config file
cfg = OmegaConf.load(os.path.join("tiny_example_entity_linking_conf... | _____no_output_____ | Apache-2.0 | tutorials/nlp/Entity_Linking_Medical.ipynb | vadam5/NeMo |
You can run the script at `examples/nlp/entity_linking/self_alignment_pretraining.py` to train a model on a larger dataset. Run```python self_alignment_pretraining.py```from the `examples/nlp/entity_linking` directory. Model EvaluationLet's evaluate our freshly trained model and compare its performance with a BERT Bas... | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Restore second stage pretrained model
sap_model_cfg = cfg
sap_model = nemo_nlp.models.EntityLinkingModel.restore_from(sap_model_cfg.model.nemo_path).to(device)
# Load original model
base_model_cfg = OmegaConf.load("tiny_example_entity_linking_con... | _____no_output_____ | Apache-2.0 | tutorials/nlp/Entity_Linking_Medical.ipynb | vadam5/NeMo |
We are going evaluate our model on a nearest neighbors task using top 1 and top 5 accuarcy as our metric. We will be using a tiny example test knowledge base and test queries. For this evaluation we are going to be comparing every test query with every concept vector in our test set knowledge base. We will rank each it... | # Helper function to get data embeddings
def get_embeddings(model, dataloader):
embeddings, cids = [], []
with torch.no_grad():
for batch in tqdm(dataloader):
input_ids, token_type_ids, attention_mask, batch_cids = batch
batch_embeddings = model.forward(input_ids=input_ids.to(de... | _____no_output_____ | Apache-2.0 | tutorials/nlp/Entity_Linking_Medical.ipynb | vadam5/NeMo |
The purpose of this section was to show an example of evaluating your entity linking model. This evaluation set contains very little data, and no serious conclusions should be drawn about model performance. Top 1 accuracy should be between 0.7 and 1.0 for both models and top 5 accuracy should be between 0.9 and 1.0. Wh... | def build_index(cfg, model):
# Setup index dataset loader
index_dataloader = model.setup_dataloader(cfg.index.index_ds, is_index_data=True)
# Get index dataset embeddings
embeddings, _ = get_embeddings(model, index_dataloader)
# Train IVFFlat index using faiss
embeddings = np.array(emb... | _____no_output_____ | Apache-2.0 | tutorials/nlp/Entity_Linking_Medical.ipynb | vadam5/NeMo |
Entity Linking via Nearest Neighbor Search Now its time to query our indices! | def query_index(cfg, model, index, queries, id2string):
query_embs = get_query_embedding(queries, model).cpu().detach().numpy()
# Use query embedding to find closet concept embedding in knowledge base
distances, neighbors = index.search(query_embs, cfg.index.top_n)
neighbor_concepts = [[id2string[c... | BERT Base output before Self Alignment Pretraining:
The most similar concepts to high blood sugar are:
6 diabetes 0.9095035269856453
0 Headache 0.9046077728271484
8 Nesina 0.8512845933437347
The most similar concepts to head pain are:
1 Myocardial infraction 0.7848673164844513
4 chronic kidney disease 0.7667324692010... | Apache-2.0 | tutorials/nlp/Entity_Linking_Medical.ipynb | vadam5/NeMo |
Nearest neighbors This notebook illustrates the classification of the nodes of a graph by the [k-nearest neighbors algorithm](https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm), based on the labels of a few nodes. | from IPython.display import SVG
import numpy as np
from sknetwork.data import karate_club, painters, movie_actor
from sknetwork.classification import KNN
from sknetwork.embedding import GSVD
from sknetwork.visualization import svg_graph, svg_digraph, svg_bigraph | _____no_output_____ | BSD-3-Clause | docs/tutorials/classification/knn.ipynb | pmla/scikit-network |
Graphs | graph = karate_club(metadata=True)
adjacency = graph.adjacency
position = graph.position
labels_true = graph.labels
seeds = {i: labels_true[i] for i in [0, 33]}
knn = KNN(GSVD(3), n_neighbors=1)
labels_pred = knn.fit_transform(adjacency, seeds)
precision = np.round(np.mean(labels_pred == labels_true), 2)
precision
imag... | _____no_output_____ | BSD-3-Clause | docs/tutorials/classification/knn.ipynb | pmla/scikit-network |
Directed graphs | graph = painters(metadata=True)
adjacency = graph.adjacency
position = graph.position
names = graph.names
rembrandt = 5
klimt = 6
cezanne = 11
seeds = {cezanne: 0, rembrandt: 1, klimt: 2}
knn = KNN(GSVD(3), n_neighbors=2)
labels = knn.fit_transform(adjacency, seeds)
image = svg_digraph(adjacency, position, names, label... | _____no_output_____ | BSD-3-Clause | docs/tutorials/classification/knn.ipynb | pmla/scikit-network |
Bipartite graphs | graph = movie_actor(metadata=True)
biadjacency = graph.biadjacency
names_row = graph.names_row
names_col = graph.names_col
inception = 0
drive = 3
budapest = 8
seeds_row = {inception: 0, drive: 1, budapest: 2}
knn = KNN(GSVD(3), n_neighbors=2)
labels_row = knn.fit_transform(biadjacency, seeds_row)
labels_col = knn.labe... | _____no_output_____ | BSD-3-Clause | docs/tutorials/classification/knn.ipynb | pmla/scikit-network |
WorkFlow Classes Load the data Test Modelling Modelling **** Classes | NAME = "change the conv2d"
BATCH_SIZE = 32
import os
import cv2
import torch
import numpy as np
def load_data(img_size=112):
data = []
index = -1
labels = {}
for directory in os.listdir('./data/'):
index += 1
labels[f'./data/{directory}/'] = [index,-1]
print(len(labels))
for labe... | _____no_output_____ | Apache-2.0 | wandb/run-20210518_105803-3lpt85em/tmp/code/main.ipynb | Programmer-RD-AI/Sign-Language-Recognition |
**** Load the data | REBUILD_DATA = True
if REBUILD_DATA:
data = load_data()
np.random.shuffle(data)
X_train,X_test,y_train,y_test = other_loading_data_proccess(data) | 36
2515
| Apache-2.0 | wandb/run-20210518_105803-3lpt85em/tmp/code/main.ipynb | Programmer-RD-AI/Sign-Language-Recognition |
Test Modelling | import torch
import torch.nn as nn
import torch.nn.functional as F
# class Test_Model(nn.Module):
# def __init__(self):
# super().__init__()
# self.conv1 = nn.Conv2d(1, 6, 5)
# self.pool = nn.MaxPool2d(2, 2)
# self.conv2 = nn.Conv2d(6, 16, 5)
# self.fc1 = nn.Linear(16 * 25 * ... | _____no_output_____ | Apache-2.0 | wandb/run-20210518_105803-3lpt85em/tmp/code/main.ipynb | Programmer-RD-AI/Sign-Language-Recognition |
Modelling | # conv2d_output
# conv2d_1_ouput
# conv2d_2_ouput
# output_fc1
# output_fc2
# output_fc4
# max_pool2d_keranl
# max_pool2d
# num_of_linear
# activation
# best num of epochs
# best optimizer
# best loss
## best lr
class Test_Model(nn.Module):
def __init__(self,conv2d_output=128,conv2d_1_ouput=32,conv2d_2_ouput=64,ou... | _____no_output_____ | Apache-2.0 | wandb/run-20210518_105803-3lpt85em/tmp/code/main.ipynb | Programmer-RD-AI/Sign-Language-Recognition |
Modes of a Vibrating BuildingIn this notebook we will find the vibrational modes of a simple model of a building. We will assume that the mass of the floors are much more than the mass of the walls and that the lateral stiffness of the walls can be modeled by a simple linear spring. We will investigate how the buildin... | from IPython.display import YouTubeVideo
YouTubeVideo('g0cz-oDfUg0', width=600)
YouTubeVideo('hSwjkG3nv1c', width=600)
YouTubeVideo('kzVvd4Dk6sw', width=600)
import numpy as np
import matplotlib.pyplot as plt
from resonance.linear_systems import FourStoryBuildingSystem | _____no_output_____ | MIT | notebooks/12/12_vibrating_building.ipynb | gbrault/resonance |
This gives a bit nicer printing of large NumPy arrays. | np.set_printoptions(precision=5, linewidth=100, suppress=True)
%matplotlib notebook | _____no_output_____ | MIT | notebooks/12/12_vibrating_building.ipynb | gbrault/resonance |
Simulate the four story building | sys = FourStoryBuildingSystem()
sys.constants
sys.coordinates
sys.plot_configuration();
traj = sys.free_response(30, sample_rate=10)
traj[list(sys.coordinates.keys())].plot(subplots=True);
sys.animate_configuration(fps=10)
M, C, K = sys.canonical_coefficients()
M
C
K | _____no_output_____ | MIT | notebooks/12/12_vibrating_building.ipynb | gbrault/resonance |
ExerciseThe system can be normalized by the mass matrix and transformed into a symmetric eigenvalue problem by introducing the new coordinate vector:$$\mathbf{q}=\mathbf{L}^T\mathbf{x}$$$\mathbf{L}$ is the Cholesky decomposition of the symmetric mass matrix, i.e. $\mathbf{M}=\mathbf{L}\mathbf{L}^T$.The equation of mot... | L = np.linalg.cholesky(M)
L
M**0.5
import numpy.linalg as la
from numpy.linalg import inv
K_tilde = inv(L) @ K @ inv(L.T)
K_tilde | _____no_output_____ | MIT | notebooks/12/12_vibrating_building.ipynb | gbrault/resonance |
Notice that $\tilde{\mathbf{K}}$ is symmetric, so we are guaranteed to get real eigenvalues and orthogonal eigenvectors when solving this system. ExerciseFind the eigenvalues and eigenvectors. Create the spectral matrix $\mathbf{\Lambda}$ and the matrix $P$ which contains the orthonormal eigenvectors of $\tilde{\mathbf... | evals, evecs = np.linalg.eig(K_tilde)
evals
evecs
Lambda = np.diag(evals)
Lambda
P = evecs | _____no_output_____ | MIT | notebooks/12/12_vibrating_building.ipynb | gbrault/resonance |
ExerciseProve that the eigenvectors in $\mathbf{P}$ are orthonormal. | np.dot(P[:, 0], P[:, 1])
np.linalg.norm(P[:, 0])
P[:, 0].T @ P[:, 1]
P[:, 0].T @ P[:, 0] | _____no_output_____ | MIT | notebooks/12/12_vibrating_building.ipynb | gbrault/resonance |
An orthonormal matrix has the property that its transpose multiplied by itself is the identity matrix. | P.T @ P | _____no_output_____ | MIT | notebooks/12/12_vibrating_building.ipynb | gbrault/resonance |
ExerciseFind the natural freqencies of the system in both radians per second and Hertz, store them in an array in the order of the eigenvalues with names `ws` and `fs`. | ws = np.sqrt(evals)
ws
fs = ws / 2 / np.pi
fs | _____no_output_____ | MIT | notebooks/12/12_vibrating_building.ipynb | gbrault/resonance |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.