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
How To Break Into the FieldNow you have had a closer look at the data, and you saw how I approached looking at how the survey respondents think you should break into the field. Let's recreate those results, as well as take a look at another question.
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import HowToBreakIntoTheField as t %matplotlib inline df = pd.read_csv('./survey_results_public.csv') schema = pd.read_csv('./survey_results_schema.csv') df.head()
_____no_output_____
CC0-1.0
Chapter01__Introduction_to_Data_Science/How To Break Into the Field - Solution .ipynb
marceloestevam/Nanodegree_DataScientist
Question 1**1.** In order to understand how to break into the field, we will look at the **CousinEducation** field. Use the **schema** dataset to answer this question. Write a function called **get_description** that takes the **schema dataframe** and the **column** as a string, and returns a string of the descripti...
def get_description(column_name, schema=schema): ''' INPUT - schema - pandas dataframe with the schema of the developers survey column_name - string - the name of the column you would like to know about OUTPUT - desc - string - the description of the column ''' desc = list(s...
_____no_output_____
CC0-1.0
Chapter01__Introduction_to_Data_Science/How To Break Into the Field - Solution .ipynb
marceloestevam/Nanodegree_DataScientist
The question we have been focused on has been around how to break into the field. Use your **get_description** function below to take a closer look at the **CousinEducation** column.
get_description('CousinEducation')
_____no_output_____
CC0-1.0
Chapter01__Introduction_to_Data_Science/How To Break Into the Field - Solution .ipynb
marceloestevam/Nanodegree_DataScientist
Question 2**2.** Provide a pandas series of the different **CousinEducation** status values in the dataset. Store this pandas series in **cous_ed_vals**. If you are correct, you should see a bar chart of the proportion of individuals in each status. If it looks terrible, and you get no information from it, then you...
cous_ed_vals = df.CousinEducation.value_counts()#Provide a pandas series of the counts for each CousinEducation status cous_ed_vals # assure this looks right # The below should be a bar chart of the proportion of individuals in your ed_vals # if it is set up correctly. (cous_ed_vals/df.shape[0]).plot(kind="bar"); plt...
_____no_output_____
CC0-1.0
Chapter01__Introduction_to_Data_Science/How To Break Into the Field - Solution .ipynb
marceloestevam/Nanodegree_DataScientist
We definitely need to clean this. Above is an example of what happens when you do not clean your data. Below I am using the same code you saw in the earlier video to take a look at the data after it has been cleaned.
possible_vals = ["Take online courses", "Buy books and work through the exercises", "None of these", "Part-time/evening courses", "Return to college", "Contribute to open source", "Conferences/meet-ups", "Bootcamp", "Get a job as a QA tester", "Participate in online c...
_____no_output_____
CC0-1.0
Chapter01__Introduction_to_Data_Science/How To Break Into the Field - Solution .ipynb
marceloestevam/Nanodegree_DataScientist
Question 4**4.** I wonder if some of the individuals might have bias towards their own degrees. Complete the function below that will apply to the elements of the **FormalEducation** column in **df**.
def higher_ed(formal_ed_str): ''' INPUT formal_ed_str - a string of one of the values from the Formal Education column OUTPUT return 1 if the string is in ("Master's degree", "Professional degree") return 0 otherwise ''' if formal_ed_str in ("Master's degree", "Pro...
_____no_output_____
CC0-1.0
Chapter01__Introduction_to_Data_Science/How To Break Into the Field - Solution .ipynb
marceloestevam/Nanodegree_DataScientist
Question 5**5.** Now we would like to find out if the proportion of individuals who completed one of these three programs feel differently than those that did not. Store a dataframe of only the individual's who had **HigherEd** equal to 1 in **ed_1**. Similarly, store a dataframe of only the **HigherEd** equal to 0 v...
ed_1 = df[df['HigherEd'] == 1] # Subset df to only those with HigherEd of 1 ed_0 = df[df['HigherEd'] == 0] # Subset df to only those with HigherEd of 0 print(ed_1['HigherEd'][:5]) #Assure it looks like what you would expect print(ed_0['HigherEd'][:5]) #Assure it looks like what you would expect #Check your subset is ...
_____no_output_____
CC0-1.0
Chapter01__Introduction_to_Data_Science/How To Break Into the Field - Solution .ipynb
marceloestevam/Nanodegree_DataScientist
Question 6**6.** What can you conclude from the above plot? Change the dictionary to mark **True** for the keys of any statements you can conclude, and **False** for any of the statements you cannot conclude.
sol = {'Everyone should get a higher level of formal education': False, 'Regardless of formal education, online courses are the top suggested form of education': True, 'There is less than a 1% difference between suggestions of the two groups for all forms of education': False, 'Those with higher f...
_____no_output_____
CC0-1.0
Chapter01__Introduction_to_Data_Science/How To Break Into the Field - Solution .ipynb
marceloestevam/Nanodegree_DataScientist
Label encoding
# Applying encoding to the PRODUCT column df_product_and_complaint['S_ID'] = df_product_and_complaint['SERVICE_TYPE'].factorize()[0] #factorize[0] arranges the index of each encoded number accordingly to the # index of your categorical variables in the service_type column # Creates a dataframe of the PRODUCT to their...
<class 'pandas.core.frame.DataFrame'> Int64Index: 7307 entries, 0 to 7311 Data columns (total 3 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 SERVICE_TYPE 7307 non-null object 1 MAIN_DESCRIPTION 7307 non-null object 2 S_ID 7307 no...
MIT
.ipynb_checkpoints/ASAR-checkpoint.ipynb
siddharthshenoy/Keywordandsum
Text Pre-Processing
# Looking at a sample text sample_complaint = list(df_product_and_complaint.MAIN_DESCRIPTION[:5])[4] # Converting to a list for TfidfVectorizer to use list_sample_complaint = [] list_sample_complaint.append(sample_complaint) list_sample_complaint # Observing what words are extracted from a TfidfVectorizer from sklearn...
['b15', 'rabbit', 'sofa', 'trapped']
MIT
.ipynb_checkpoints/ASAR-checkpoint.ipynb
siddharthshenoy/Keywordandsum
Model/classifier selection train/startified/test splits
# Split the data into X and y data sets X, y = df_product_and_complaint.MAIN_DESCRIPTION, df_product_and_complaint.SERVICE_TYPE print('X shape:', X.shape, 'y shape:', y.shape) # Split the data into X and y data sets X, y = df_product_and_complaint.MAIN_DESCRIPTION, df_product_and_complaint.SERVICE_TYPE print('X shape:...
_____no_output_____
MIT
.ipynb_checkpoints/ASAR-checkpoint.ipynb
siddharthshenoy/Keywordandsum
Baseline Model - Train/Stratified CV with MultinomialNB()
print('1-gram number of (rows, features):', X_train_val_tfidf1.shape) def metric_cv_stratified(model, X_train_val, y_train_val, n_splits, name): """ Accepts a Model Object, converted X_train_val and y_train_val, n_splits, name and returns a dataframe with various cross-validated metric scores over a st...
_____no_output_____
MIT
.ipynb_checkpoints/ASAR-checkpoint.ipynb
siddharthshenoy/Keywordandsum
1-gram
# ## Testing on all Models using 1-gram # # Initialize Model Object # gnb = GaussianNB() # mnb = MultinomialNB() # logit = LogisticRegression(random_state=seed) # randomforest = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=0) # linearsvc = LinearSVC() # ## We do NOT want these two. They take FO...
_____no_output_____
MIT
.ipynb_checkpoints/ASAR-checkpoint.ipynb
siddharthshenoy/Keywordandsum
Using GloVe50d
#Each complaint is mapped to a feature vector by averaging the word embeddings of all words in the review. #These features are then fed into the defined function above for train/cross validation. # ## Using pre-trained GloVe # #download from https://nlp.stanford.edu/projects/glove/ # glove_file = glove_dir = 'glove....
_____no_output_____
MIT
.ipynb_checkpoints/ASAR-checkpoint.ipynb
siddharthshenoy/Keywordandsum
Using GloVe100d
del glove_model_50d, results_cv_straitified_glove50d # ## Using pre-trained GloVe # # download from https://nlp.stanford.edu/projects/glove/ # num_features = 100 # depends on the pre-trained model you are loading # glove_file = glove_dir = 'glove.6B.' + str(num_features) + 'd.txt' # w2v_output_file = 'glove.6B.' + st...
_____no_output_____
MIT
.ipynb_checkpoints/ASAR-checkpoint.ipynb
siddharthshenoy/Keywordandsum
Using GloVe200d
del glove_model_100d, results_cv_straitified_glove100d # ## Using pre-trained GloVe # # download from https://nlp.stanford.edu/projects/glove/ # num_features = 200 # depends on the pre-trained model you are loading # glove_file = glove_dir = 'glove.6B.' + str(num_features) + 'd.txt' # w2v_output_file = 'glove.6B.' + ...
_____no_output_____
MIT
.ipynb_checkpoints/ASAR-checkpoint.ipynb
siddharthshenoy/Keywordandsum
Using GloVe300d
del glove_model_200d, results_cv_straitified_glove200d # ## Using pre-trained GloVe # # download from https://nlp.stanford.edu/projects/glove/ # num_features = 300 # depends on the pre-trained model you are loading # glove_file = glove_dir = 'glove.6B.' + str(num_features) + 'd.txt' # w2v_output_file = 'glove.6B.' + ...
_____no_output_____
MIT
.ipynb_checkpoints/ASAR-checkpoint.ipynb
siddharthshenoy/Keywordandsum
GoogleNews Word2Vec300d
del glove_model_300d, results_cv_straitified_glove300d # ## Using pre-trained GoogleNews Word2Vec # # download from https://drive.google.com/file/d/0B7XkCwpI5KDYNlNUTTlSS21pQmM/edit # num_features = 300 # depends on the pre-trained model you are loading # # Path to where the word2vec file lives # google_vec_file = 'G...
_____no_output_____
MIT
.ipynb_checkpoints/ASAR-checkpoint.ipynb
siddharthshenoy/Keywordandsum
For full documentation on this project, see [here](https://new-languages-for-nlp.github.io/course-materials/w2/projects.html) This notebook: - Loads project file from GitHub- Loads assets from GitHub repo- installs the custom language object - converts the training data to spaCy binary- configure the project.yml file ...
# @title Colab comes with spaCy v2, needs upgrade to v3 GPU = True # @param {type:"boolean"} # Install spaCy v3 and libraries for GPUs and transformers !pip install spacy --upgrade if GPU: !pip install 'spacy[transformers,cuda111]' !pip install wandb spacy-huggingface-hub
_____no_output_____
MIT
New_Language_Training_(Colab).ipynb
New-Languages-for-NLP/kanbun
The notebook will pull project files from your GitHub repository. Note that you need to set the langugage (lang), treebank (same as the repo name), test_size and package name in the project.yml file in your repository.
private_repo = False # @param {type:"boolean"} repo_name = "kanbun" # @param {type:"string"} !rm -rf /content/newlang_project !rm -rf $repo_name if private_repo: git_access_token = "" # @param {type:"string"} git_url = ( f"https://{git_access_token}@github.com/New-Languages-for-NLP/{repo_name}/" ...
_____no_output_____
MIT
New_Language_Training_(Colab).ipynb
New-Languages-for-NLP/kanbun
2 Prepare the Data for Training
# @title (optional) cell to corrects a problem when your tokens have no pos value %%writefile /usr/local/lib/python3.7/dist-packages/spacy/training/converters/conllu_to_docs.py import re from .conll_ner_to_docs import n_sents_info from ...training import iob_to_biluo, biluo_tags_to_spans from ...tokens import Doc, Tok...
_____no_output_____
MIT
New_Language_Training_(Colab).ipynb
New-Languages-for-NLP/kanbun
3 Model Training
# train the model !python -m spacy project run train /content/newlang_project
_____no_output_____
MIT
New_Language_Training_(Colab).ipynb
New-Languages-for-NLP/kanbun
If you get `ValueError: Could not find gold transition - see logs above.` You may not have sufficent data to train on: https://github.com/explosion/spaCy/discussions/7282
# Evaluate the model using the test data !python -m spacy project run evaluate /content/newlang_project # Find the path for your meta.json file # You'll need to add newlang_project/ + the path from the training step just after "✔ Saved pipeline to output directory" !ls newlang_project/training/urban-giggle/model-last ...
_____no_output_____
MIT
New_Language_Training_(Colab).ipynb
New-Languages-for-NLP/kanbun
Download the trained model to your computer.
# Save the model to disk in a format that can be easily downloaded and re-used. !python -m spacy package ./newlang_project/training/urban-giggle/model-last newlang_project/export from google.colab import files # replace with the path in the previous cell under "✔ Successfully created zipped Python package" files.down...
_____no_output_____
MIT
New_Language_Training_(Colab).ipynb
New-Languages-for-NLP/kanbun
This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/system-design-primer-primer). Design an LRU cache Constraints and assumptions* What are we caching? * We are cahing the results of web queries* Can we assume inputs ar...
%%writefile lru_cache.py class Node(object): def __init__(self, results): self.results = results self.next = next class LinkedList(object): def __init__(self): self.head = None self.tail = None def move_to_front(self, node): # ... def append_to_front(self, node): #...
Overwriting lru_cache.py
CC-BY-4.0
something-learned/Interview/system-design-primer/solutions/object_oriented_design/lru_cache/lru_cache.ipynb
gopala-kr/Code-Rush-101
[Table of Contents](./table_of_contents.ipynb) H Infinity filter
%matplotlib inline #format the book import book_format book_format.set_style()
_____no_output_____
CC-BY-4.0
Appendix-D-HInfinity-Filters.ipynb
wjdghksdl26/Kalman-and-Bayesian-Filters-in-Python
I am still mulling over how to write this chapter. In the meantime, Professor Dan Simon at Cleveland State University has an accessible introduction here:http://academic.csuohio.edu/simond/courses/eec641/hinfinity.pdfIn one sentence the $H_\infty$ (H infinity) filter is like a Kalman filter, but it is robust in the fac...
import numpy as np import matplotlib.pyplot as plt from filterpy.hinfinity import HInfinityFilter dt = 0.1 f = HInfinityFilter(2, 1, dim_u=1, gamma=.01) f.F = np.array([[1., dt], [0., 1.]]) f.H = np.array([[0., 1.]]) f.G = np.array([[dt**2 / 2, dt]]).T f.P = 0.01 f.W = np.array([[0.0003, 0.005], ...
_____no_output_____
CC-BY-4.0
Appendix-D-HInfinity-Filters.ipynb
wjdghksdl26/Kalman-and-Bayesian-Filters-in-Python
Generative Adversarial Networks:label:`sec_basic_gan`Throughout most of this book, we have talked about how to make predictions. In some form or another, we used deep neural networks learned mappings from data examples to labels. This kind of learning is called discriminative learning, as in, we'd like to be able to d...
%matplotlib inline from mxnet import autograd, gluon, init, np, npx from mxnet.gluon import nn from d2l import mxnet as d2l npx.set_np()
_____no_output_____
MIT
python/d2l-en/mxnet/chapter_generative-adversarial-networks/gan.ipynb
rtp-aws/devpost_aws_disaster_recovery
Generate Some "Real" DataSince this is going to be the world's lamest example, we simply generate data drawn from a Gaussian.
X = np.random.normal(0.0, 1, (1000, 2)) A = np.array([[1, 2], [-0.1, 0.5]]) b = np.array([1, 2]) data = np.dot(X, A) + b
_____no_output_____
MIT
python/d2l-en/mxnet/chapter_generative-adversarial-networks/gan.ipynb
rtp-aws/devpost_aws_disaster_recovery
Let us see what we got. This should be a Gaussian shifted in some rather arbitrary way with mean $b$ and covariance matrix $A^TA$.
d2l.set_figsize() d2l.plt.scatter(data[:100, (0)].asnumpy(), data[:100, (1)].asnumpy()); print(f'The covariance matrix is\n{np.dot(A.T, A)}') batch_size = 8 data_iter = d2l.load_array((data,), batch_size)
_____no_output_____
MIT
python/d2l-en/mxnet/chapter_generative-adversarial-networks/gan.ipynb
rtp-aws/devpost_aws_disaster_recovery
GeneratorOur generator network will be the simplest network possible - a single layer linear model. This is since we will be driving that linear network with a Gaussian data generator. Hence, it literally only needs to learn the parameters to fake things perfectly.
net_G = nn.Sequential() net_G.add(nn.Dense(2))
_____no_output_____
MIT
python/d2l-en/mxnet/chapter_generative-adversarial-networks/gan.ipynb
rtp-aws/devpost_aws_disaster_recovery
DiscriminatorFor the discriminator we will be a bit more discriminating: we will use an MLP with 3 layers to make things a bit more interesting.
net_D = nn.Sequential() net_D.add(nn.Dense(5, activation='tanh'), nn.Dense(3, activation='tanh'), nn.Dense(1))
_____no_output_____
MIT
python/d2l-en/mxnet/chapter_generative-adversarial-networks/gan.ipynb
rtp-aws/devpost_aws_disaster_recovery
TrainingFirst we define a function to update the discriminator.
#@save def update_D(X, Z, net_D, net_G, loss, trainer_D): """Update discriminator.""" batch_size = X.shape[0] ones = np.ones((batch_size,), ctx=X.ctx) zeros = np.zeros((batch_size,), ctx=X.ctx) with autograd.record(): real_Y = net_D(X) fake_X = net_G(Z) # Do not need to compu...
_____no_output_____
MIT
python/d2l-en/mxnet/chapter_generative-adversarial-networks/gan.ipynb
rtp-aws/devpost_aws_disaster_recovery
The generator is updated similarly. Here we reuse the cross-entropy loss but change the label of the fake data from $0$ to $1$.
#@save def update_G(Z, net_D, net_G, loss, trainer_G): """Update generator.""" batch_size = Z.shape[0] ones = np.ones((batch_size,), ctx=Z.ctx) with autograd.record(): # We could reuse `fake_X` from `update_D` to save computation fake_X = net_G(Z) # Recomputing `fake_Y` is needed...
_____no_output_____
MIT
python/d2l-en/mxnet/chapter_generative-adversarial-networks/gan.ipynb
rtp-aws/devpost_aws_disaster_recovery
Both the discriminator and the generator performs a binary logistic regression with the cross-entropy loss. We use Adam to smooth the training process. In each iteration, we first update the discriminator and then the generator. We visualize both losses and generated examples.
def train(net_D, net_G, data_iter, num_epochs, lr_D, lr_G, latent_dim, data): loss = gluon.loss.SigmoidBCELoss() net_D.initialize(init=init.Normal(0.02), force_reinit=True) net_G.initialize(init=init.Normal(0.02), force_reinit=True) trainer_D = gluon.Trainer(net_D.collect_params(), ...
_____no_output_____
MIT
python/d2l-en/mxnet/chapter_generative-adversarial-networks/gan.ipynb
rtp-aws/devpost_aws_disaster_recovery
Now we specify the hyperparameters to fit the Gaussian distribution.
lr_D, lr_G, latent_dim, num_epochs = 0.05, 0.005, 2, 20 train(net_D, net_G, data_iter, num_epochs, lr_D, lr_G, latent_dim, data[:100].asnumpy())
loss_D 0.693, loss_G 0.693, 549.8 examples/sec
MIT
python/d2l-en/mxnet/chapter_generative-adversarial-networks/gan.ipynb
rtp-aws/devpost_aws_disaster_recovery
Unstructured Profilers **Data profiling** - *is the process of examining a dataset and collecting statistical or informational summaries about said dataset.*The Profiler class inside the DataProfiler is designed to generate *data profiles* via the Profiler class, which ingests either a Data class or a Pandas DataFrame...
import os import sys import json try: sys.path.insert(0, '..') import dataprofiler as dp except ImportError: import dataprofiler as dp data_path = "../dataprofiler/tests/data" # remove extra tf loggin import tensorflow as tf tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) data = dp.Data(os...
_____no_output_____
Apache-2.0
examples/unstructured_profilers.ipynb
taylorfturner/DataProfiler
Profiler Type It should be noted, in addition to reading the input data from text files, DataProfiler allows the input data as a pandas dataframe, a pandas series, a list, and Data objects (when an unstructured format is selected) if the Profiler is explicitly chosen as unstructured.
# run data profiler and get the report import pandas as pd data = dp.Data(os.path.join(data_path, "csv/SchoolDataSmall.csv"), options={"data_format": "records"}) profile = dp.Profiler(data, profiler_type='unstructured') report = profile.report(report_options={"output_format":"pretty"}) print(json.dumps(report, indent...
_____no_output_____
Apache-2.0
examples/unstructured_profilers.ipynb
taylorfturner/DataProfiler
Profiler options The DataProfiler has the ability to turn on and off components as needed. This is accomplished via the `ProfilerOptions` class.For example, if a user doesn't require vocab count information they may desire to turn off the word count functionality.Below, let's remove the vocab count and set the stop wo...
data = dp.Data(os.path.join(data_path, "txt/discussion_reddit.txt")) profile_options = dp.ProfilerOptions() # Setting multiple options via set profile_options.set({ "*.vocab.is_enabled": False, "*.is_case_sensitive": True }) # Set options via directly setting them profile_options.unstructured_options.text.stop_words...
_____no_output_____
Apache-2.0
examples/unstructured_profilers.ipynb
taylorfturner/DataProfiler
Updating Profiles Beyond just profiling, one of the unique aspects of the DataProfiler is the ability to update the profiles. To update appropriately, the schema (columns / keys) must match appropriately.
# Load and profile a CSV file data = dp.Data(os.path.join(data_path, "txt/sentence-3x.txt")) profile = dp.Profiler(data) # Update the profile with new data: new_data = dp.Data(os.path.join(data_path, "txt/sentence-3x.txt")) profile.update_profile(new_data) # Take a peek at the data print(data.data) print(new_data.dat...
_____no_output_____
Apache-2.0
examples/unstructured_profilers.ipynb
taylorfturner/DataProfiler
Merging Profiles Merging profiles are an alternative method for updating profiles. Particularly, multiple profiles can be generated seperately, then added together with a simple `+` command: `profile3 = profile1 + profile2`
# Load a CSV file with a schema data1 = dp.Data(os.path.join(data_path, "txt/sentence-3x.txt")) profile1 = dp.Profiler(data1) # Load another CSV file with the same schema data2 = dp.Data(os.path.join(data_path, "txt/sentence-3x.txt")) profile2 = dp.Profiler(data2) # Merge the profiles profile3 = profile1 + profile2 ...
_____no_output_____
Apache-2.0
examples/unstructured_profilers.ipynb
taylorfturner/DataProfiler
As you can see, the `update_profile` function and the `+` operator function similarly. The reason the `+` operator is important is that it's possible to *save and load profiles*, which we cover next. Saving and Loading a Profile Not only can the Profiler create and update profiles, it's also possible to save, load the...
# Load data data = dp.Data(os.path.join(data_path, "txt/sentence-3x.txt")) # Generate a profile profile = dp.Profiler(data) # Save a profile to disk for later (saves as pickle file) profile.save(filepath="my_profile.pkl") # Load a profile from disk loaded_profile = dp.Profiler.load("my_profile.pkl") # Report the co...
_____no_output_____
Apache-2.0
examples/unstructured_profilers.ipynb
taylorfturner/DataProfiler
With the ability to save and load profiles, profiles can be generated via multiple machines then merged. Further, profiles can be stored and later used in applications such as change point detection, synthetic data generation, and more.
# Load a multiple files via the Data class filenames = ["txt/sentence-3x.txt", "txt/sentence.txt"] data_objects = [] for filename in filenames: data_objects.append(dp.Data(os.path.join(data_path, filename))) print(data_objects) # Generate and save profiles for i in range(len(data_objects)): profil...
_____no_output_____
Apache-2.0
examples/unstructured_profilers.ipynb
taylorfturner/DataProfiler
Functions
def adf_test(time_series): """ param time_series: takes a time series list as an input return: True/False as a results of KPSS alongside the output in dataframe """ dftest = adfuller(time_series, autolag='AIC') dfoutput = pd.Series(dftest[0:4], index=[ ...
_____no_output_____
MIT
.ipynb_checkpoints/Stationarity-Decomposition-Periodicity-checkpoint.ipynb
ahtshamzafar1/Time-Series-Data-Analysis
Timeseries Analysis
df_weather=pd.read_csv(r'C:\Users\ahtis\OneDrive\Desktop\ARIMA\data\data.csv') df_weather = df_weather[1:60] df_weather = df_weather.dropna() feature_name = "glucose" df_weather["Timestamp"] = pd.to_datetime(df_weather["Timestamp"], format='%Y-%m-%d %H:%M:%S', utc=True) df_weather["Timestamp"] = pd.DatetimeIndex(df...
_____no_output_____
MIT
.ipynb_checkpoints/Stationarity-Decomposition-Periodicity-checkpoint.ipynb
ahtshamzafar1/Time-Series-Data-Analysis
This notebook can be used to generate fake structural variant test data for testing the genome finishing module.Given a source fasta, bam, and paired-end fastqs and insertion parameters, it creates a directory with the following files: ref.fa reads.1.fq reads.2.fq
import sys from django.core.management import setup_environ import settings setup_environ(settings) import random import re import os from Bio import SeqIO import pysam from genome_finish.millstone_de_novo_fns import get_avg_genome_coverage # def _make_fake_insertion(ref_endpoints, ins_endpoints): ref_endpoints ...
_____no_output_____
MIT
genome_designer/debug/make_new_refs_clean.ipynb
churchlab/millstone
Think Bayes: Chapter 5This notebook presents code and exercises from Think Bayes, second edition.Copyright 2016 Allen B. DowneyMIT License: https://opensource.org/licenses/MIT
from __future__ import print_function, division % matplotlib inline import warnings warnings.filterwarnings('ignore') import numpy as np from thinkbayes2 import Pmf, Cdf, Suite, Beta import thinkplot
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
OddsThe following function converts from probabilities to odds.
def Odds(p): return p / (1-p)
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
And this function converts from odds to probabilities.
def Probability(o): return o / (o+1)
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
If 20% of bettors think my horse will win, that corresponds to odds of 1:4, or 0.25.
p = 0.2 Odds(p)
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
If the odds against my horse are 1:5, that corresponds to a probability of 1/6.
o = 1/5 Probability(o)
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
We can use the odds form of Bayes's theorem to solve the cookie problem:
prior_odds = 1 likelihood_ratio = 0.75 / 0.5 post_odds = prior_odds * likelihood_ratio post_odds
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
And then we can compute the posterior probability, if desired.
post_prob = Probability(post_odds) post_prob
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
If we draw another cookie and it's chocolate, we can do another update:
likelihood_ratio = 0.25 / 0.5 post_odds *= likelihood_ratio post_odds
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
And convert back to probability.
post_prob = Probability(post_odds) post_prob
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
Oliver's bloodThe likelihood ratio is also useful for talking about the strength of evidence without getting bogged down talking about priors.As an example, we'll solve this problem from MacKay's {\it Information Theory, Inference, and Learning Algorithms}:> Two people have left traces of their own blood at the scene ...
like1 = 0.01 like2 = 2 * 0.6 * 0.01 likelihood_ratio = like1 / like2 likelihood_ratio
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
Since the ratio is less than 1, it is evidence *against* the hypothesis that Oliver left blood at the scence.But it is weak evidence. For example, if the prior odds were 1 (that is, 50% probability), the posterior odds would be 0.83, which corresponds to a probability of:
post_odds = 1 * like1 / like2 Probability(post_odds)
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
So this evidence doesn't "move the needle" very much. **Exercise:** Suppose other evidence had made you 90% confident of Oliver's guilt. How much would this exculpatory evince change your beliefs? What if you initially thought there was only a 10% chance of his guilt?Notice that evidence with the same strength has a ...
# Solution post_odds = Odds(0.9) * like1 / like2 Probability(post_odds) # Solution post_odds = Odds(0.1) * like1 / like2 Probability(post_odds)
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
Comparing distributionsLet's get back to the Kim Rhode problem from Chapter 4:> At the 2016 Summer Olympics in the Women's Skeet event, Kim Rhode faced Wei Meng in the bronze medal match. They each hit 15 of 25 targets, sending the match into sudden death. In the first round, both hit 1 of 2 targets. In the next two r...
rhode = Beta(1, 1, label='Rhode') rhode.Update((22, 11)) wei = Beta(1, 1, label='Wei') wei.Update((21, 12))
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
Based on the data, the distribution for Rhode is slightly farther right than the distribution for Wei, but there is a lot of overlap.
thinkplot.Pdf(rhode.MakePmf()) thinkplot.Pdf(wei.MakePmf()) thinkplot.Config(xlabel='x', ylabel='Probability')
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
To compute the probability that Rhode actually has a higher value of `p`, there are two options:1. Sampling: we could draw random samples from the posterior distributions and compare them.2. Enumeration: we could enumerate all possible pairs of values and add up the "probability of superiority".I'll start with sampling...
iters = 1000 count = 0 for _ in range(iters): x1 = rhode.Random() x2 = wei.Random() if x1 > x2: count += 1 count / iters
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
`Beta` also provides `Sample`, which returns a NumPy array, so we an perform the comparisons using array operations:
rhode_sample = rhode.Sample(iters) wei_sample = wei.Sample(iters) np.mean(rhode_sample > wei_sample)
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
The other option is to make `Pmf` objects that approximate the Beta distributions, and enumerate pairs of values:
def ProbGreater(pmf1, pmf2): total = 0 for x1, prob1 in pmf1.Items(): for x2, prob2 in pmf2.Items(): if x1 > x2: total += prob1 * prob2 return total pmf1 = rhode.MakePmf(1001) pmf2 = wei.MakePmf(1001) ProbGreater(pmf1, pmf2) pmf1.ProbGreater(pmf2) pmf1.ProbLess(pmf2)
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
**Exercise:** Run this analysis again with a different prior and see how much effect it has on the results. SimulationTo make predictions about a rematch, we have two options again:1. Sampling. For each simulated match, we draw a random value of `x` for each contestant, then simulate 25 shots and count hits.2. Comput...
import random def flip(p): return random.random() < p
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
`flip` returns True with probability `p` and False with probability `1-p`Now we can simulate 1000 rematches and count wins and losses.
iters = 1000 wins = 0 losses = 0 for _ in range(iters): x1 = rhode.Random() x2 = wei.Random() count1 = count2 = 0 for _ in range(25): if flip(x1): count1 += 1 if flip(x2): count2 += 1 if count1 > count2: wins += 1 if count1 < cou...
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
Or, realizing that the distribution of `k` is binomial, we can simplify the code using NumPy:
rhode_rematch = np.random.binomial(25, rhode_sample) thinkplot.Hist(Pmf(rhode_rematch)) wei_rematch = np.random.binomial(25, wei_sample) np.mean(rhode_rematch > wei_rematch) np.mean(rhode_rematch < wei_rematch)
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
Alternatively, we can make a mixture that represents the distribution of `k`, taking into account our uncertainty about `x`:
from thinkbayes2 import MakeBinomialPmf def MakeBinomialMix(pmf, label=''): mix = Pmf(label=label) for x, prob in pmf.Items(): binom = MakeBinomialPmf(n=25, p=x) for k, p in binom.Items(): mix[k] += prob * p return mix rhode_rematch = MakeBinomialMix(rhode.MakePmf(), label='Rhod...
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
Alternatively, we could use MakeMixture:
from thinkbayes2 import MakeMixture def MakeBinomialMix2(pmf): binomials = Pmf() for x, prob in pmf.Items(): binom = MakeBinomialPmf(n=25, p=x) binomials[binom] = prob return MakeMixture(binomials)
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
Here's how we use it.
rhode_rematch = MakeBinomialMix2(rhode.MakePmf()) wei_rematch = MakeBinomialMix2(wei.MakePmf()) rhode_rematch.ProbGreater(wei_rematch), rhode_rematch.ProbLess(wei_rematch)
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
**Exercise:** Run this analysis again with a different prior and see how much effect it has on the results. Distributions of sums and differencesSuppose we want to know the total number of targets the two contestants will hit in a rematch. There are two ways we might compute the distribution of this sum:1. Sampling: ...
iters = 1000 pmf = Pmf() for _ in range(iters): k = rhode_rematch.Random() + wei_rematch.Random() pmf[k] += 1 pmf.Normalize() thinkplot.Hist(pmf)
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
Or we could use `Sample` and NumPy:
ks = rhode_rematch.Sample(iters) + wei_rematch.Sample(iters) pmf = Pmf(ks) thinkplot.Hist(pmf)
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
Alternatively, we could compute the distribution of the sum by enumeration:
def AddPmfs(pmf1, pmf2): pmf = Pmf() for v1, p1 in pmf1.Items(): for v2, p2 in pmf2.Items(): pmf[v1 + v2] += p1 * p2 return pmf
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
Here's how it's used:
pmf = AddPmfs(rhode_rematch, wei_rematch) thinkplot.Pdf(pmf)
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
The `Pmf` class provides a `+` operator that does the same thing.
pmf = rhode_rematch + wei_rematch thinkplot.Pdf(pmf)
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
**Exercise:** The Pmf class also provides the `-` operator, which computes the distribution of the difference in values from two distributions. Use the distributions from the previous section to compute the distribution of the differential between Rhode and Wei in a rematch. On average, how many clays should we expe...
# Solution pmf = rhode_rematch - wei_rematch thinkplot.Pdf(pmf) # Solution # On average, we expect Rhode to win by about 1 clay. pmf.Mean(), pmf.Median(), pmf.Mode() # Solution # But there is, according to this model, a 2% chance that she could win by 10. sum([p for (x, p) in pmf.Items() if x >= 10])
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
Distribution of maximumSuppose Kim Rhode continues to compete in six more Olympics. What should we expect her best result to be?Once again, there are two ways we can compute the distribution of the maximum:1. Sampling.2. Analysis of the CDF.Here's a simple version by sampling:
iters = 1000 pmf = Pmf() for _ in range(iters): ks = rhode_rematch.Sample(6) pmf[max(ks)] += 1 pmf.Normalize() thinkplot.Hist(pmf)
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
And here's a version using NumPy. I'll generate an array with 6 rows and 10 columns:
iters = 1000 ks = rhode_rematch.Sample((6, iters)) ks
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
Compute the maximum in each column:
maxes = np.max(ks, axis=0) maxes[:10]
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
And then plot the distribution of maximums:
pmf = Pmf(maxes) thinkplot.Hist(pmf)
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
Or we can figure it out analytically. If the maximum is less-than-or-equal-to some value `k`, all 6 random selections must be less-than-or-equal-to `k`, so: $ CDF_{max}(x) = CDF(x)^6 $`Pmf` provides a method that computes and returns this `Cdf`, so we can compute the distribution of the maximum like this:
pmf = rhode_rematch.Max(6).MakePmf() thinkplot.Hist(pmf)
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
**Exercise:** Here's how Pmf.Max works: def Max(self, k): """Computes the CDF of the maximum of k selections from this dist. k: int returns: new Cdf """ cdf = self.MakeCdf() cdf.ps **= k return cdfWrite a function that takes a Pmf and an integer `n` and returns a Pmf...
def Min(pmf, k): cdf = pmf.MakeCdf() cdf.ps = 1 - (1-cdf.ps)**k return cdf pmf = Min(rhode_rematch, 6).MakePmf() thinkplot.Hist(pmf)
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
Exercises **Exercise:** Suppose you are having a dinner party with 10 guests and 4 of them are allergic to cats. Because you have cats, you expect 50% of the allergic guests to sneeze during dinner. At the same time, you expect 10% of the non-allergic guests to sneeze. What is the distribution of the total number ...
# Solution n_allergic = 4 n_non = 6 p_allergic = 0.5 p_non = 0.1 pmf = MakeBinomialPmf(n_allergic, p_allergic) + MakeBinomialPmf(n_non, p_non) thinkplot.Hist(pmf) # Solution pmf.Mean()
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
**Exercise** [This study from 2015](http://onlinelibrary.wiley.com/doi/10.1111/apt.13372/full) showed that many subjects diagnosed with non-celiac gluten sensitivity (NCGS) were not able to distinguish gluten flour from non-gluten flour in a blind challenge.Here is a description of the study:>"We studied 35 non-CD subj...
# Solution # Here's a class that models the study class Gluten(Suite): def Likelihood(self, data, hypo): """Computes the probability of the data under the hypothesis. data: tuple of (number who identified, number who did not) hypothesis: number of participants who are gluten ...
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
**Exercise** Coming soon: the space invaders problem.
# Solution # Solution # Solution # Solution # Solution # Solution # Solution # Solution
_____no_output_____
MIT
code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb
proTao/LearningBayes
'The 80/20 Pandas Tutorial: 5 Key Methods for the Majority of Your Data Transformation Needs'> An opinionated pandas tutorial on my preferred methods to accomplish the most essential data transformation tasks in a way that will make veteran R and tidyverse users smile.- toc: false- badges: true- comments: true- catego...
import pandas as pd import numpy as np
_____no_output_____
Apache-2.0
_notebooks/2020-11-25-8020-pandas.ipynb
mcb00/blog_bak
We'll use the [nycflights13](https://github.com/hadley/nycflights13) dataset which contains data on the 336,776 flights that departed from New York City in 2013.
# pull some data into a pandas dataframe flights = pd.read_csv('https://www.openintro.org/book/statdata/nycflights.csv') flights.head()
_____no_output_____
Apache-2.0
_notebooks/2020-11-25-8020-pandas.ipynb
mcb00/blog_bak
Select rows based on their values with `query()` `query()` lets you retain a subset of rows based on the values of the data; it's like `dplyr::filter()` in R or `WHERE` in SQL.Its argument is a string specifying the condition to be met for rows to be included in the result.You specify the condition as an expression i...
#hide_output # compare one column to a value flights.query('month == 6') # compare two column values flights.query('arr_delay > dep_delay') # using arithmetic flights.query('arr_delay > 0.5 * air_time') # using "and" flights.query('month == 6 and day == 1') # using "or" flights.query('origin == "JFK" or dest == "JF...
_____no_output_____
Apache-2.0
_notebooks/2020-11-25-8020-pandas.ipynb
mcb00/blog_bak
You may have noticed that it seems to be much more popular to filter pandas data frames using boolean indexing.Indeed when I ask my favorite search engine how to filter a pandas dataframe on its values, I find[this tutorial](https://cmdlinetips.com/2018/02/how-to-subset-pandas-dataframe-based-on-values-of-a-column/),[t...
#hide_output # canonical boolean indexing flights[(flights['carrier'] == "AA") & (flights['origin'] == "JFK")] # the equivalent use of query() flights.query('carrier == "AA" and origin == "JFK"')
_____no_output_____
Apache-2.0
_notebooks/2020-11-25-8020-pandas.ipynb
mcb00/blog_bak
There are a few reasons I prefer `query()` over boolean indexing.1. `query()` does not require me to type the dataframe name again, whereas boolean indexing requires me to type it every time I wish to refer to a column.1. `query()` makes the code easier to read and understand, especially when expressions get complex.1....
#hide_output # select a list of columns flights.filter(['origin', 'dest']) # select columns containing a particular substring flights.filter(like='time') # select columns matching a regular expression flights.filter(regex='e$')
_____no_output_____
Apache-2.0
_notebooks/2020-11-25-8020-pandas.ipynb
mcb00/blog_bak
Sort rows with `sort_values()` `sort_values()` changes the order of the rows based on the data values; it's like`dplyr::arrange()` in R or `ORDER BY` in SQL.You can specify one or more columns on which to sort, where their order denotes the sorting priority. You can also specify whether to sort in ascending or descen...
#hide_output # sort by a single column flights.sort_values('air_time') # sort by a single column in descending order flights.sort_values('air_time', ascending=False) # sort by carrier, then within carrier, sort by descending distance flights.sort_values(['carrier', 'distance'], ascending=[True, False])
_____no_output_____
Apache-2.0
_notebooks/2020-11-25-8020-pandas.ipynb
mcb00/blog_bak
Add new columns with `assign()` `assign()` adds new columns which can be functions of the existing columns; it's like `dplyr::mutate()` from R.
#hide_output # add a new column based on other columns flights.assign(speed = lambda x: x.distance / x.air_time) # another new column based on existing columns flights.assign(gain = lambda x: x.dep_delay - x.arr_delay)
_____no_output_____
Apache-2.0
_notebooks/2020-11-25-8020-pandas.ipynb
mcb00/blog_bak
If you're like me, this way of using `assign()` might seem a little strange at first.Let's break it down.In the call to `assign()` the keyword argument `speed` tells pandas the name of our new column.The business to the right of the `=` is a inline lambda function that takes the dataframe we passed to `assign()` and re...
#hide_output # neatly chain method calls together ( flights .query('origin == "JFK"') .query('dest == "HNL"') .assign(speed = lambda x: x.distance / x.air_time) .sort_values(by='speed', ascending=False) .query('speed > 8.0') )
_____no_output_____
Apache-2.0
_notebooks/2020-11-25-8020-pandas.ipynb
mcb00/blog_bak
We compose the dot chain by wrapping the entire expression in parentheses and indenting each line within.The first line is the name of the dataframe on which we are operating.Each subsequent line has a single method call.There are a few great things about writing the code this way:1. Readability. It's easy to scan down...
#hide_output # sotre the output of the dot chain in a new dataframe flights_high_speed = ( flights .assign(speed = lambda x: x.distance / x.air_time) .query('speed > 8.0') )
_____no_output_____
Apache-2.0
_notebooks/2020-11-25-8020-pandas.ipynb
mcb00/blog_bak
Collapsing rows into grouped summaries with `groupby()` `groupby()` combined with `apply()` gives us flexibility and control over our grouped summaries; it's like `dplyr::group_by()` and `dplyr::summarise()` in R.This is the primary pattern I use for SQL-style groupby operations in pandas. Specifically it unlocks the ...
# grouped summary with groupby and apply ( flights .groupby(['carrier']) .apply(lambda d: pd.Series({ 'n_flights': len(d), 'med_delay': d.dep_delay.median(), 'avg_delay': d.dep_delay.mean(), })) .head() )
_____no_output_____
Apache-2.0
_notebooks/2020-11-25-8020-pandas.ipynb
mcb00/blog_bak
While you might be used to `apply()` acting over the rows or columns of a dataframe, here we're calling apply on a grouped dataframe object, so it's acting over the _groups_.According to the [pandas documentation](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html):> The function p...
# more complex grouped summary ( flights .groupby(['carrier']) .apply(lambda d: pd.Series({ 'avg_gain': np.mean(d.dep_delay - d.arr_delay), 'pct_delay_gt_30': np.mean(d.dep_delay > 30), 'pct_late_dep_early_arr': np.mean((d.dep_delay > 0) & (d.arr_delay < 0)), 'avg_arr_give...
_____no_output_____
Apache-2.0
_notebooks/2020-11-25-8020-pandas.ipynb
mcb00/blog_bak
Data Transfer This notebook has information regarding the data transfer per latitude in 12 day chunks run for 60 days
from lusee.observation import LObservation from lusee.lunar_satellite import LSatellite, ObservedSatellite import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import interp1d from scipy.optimize import curve_fit import time
_____no_output_____
MIT
LatitudeTable.ipynb
kssumanth27/notebooks
The demodulation function below follows the formula from the excel sheet. Each variable closely matches the varibles from excel sheet
def demodulation(dis_range, rate_pw2, extra_ant_gain): R = np.array([430,1499.99,1500,1999.99,2000,2999.99,3000,4499.99,4500,7499.99,7500,10000]) Pt_error = np.array([11.00,11.00,8.50,8.50,6.00,6.00,4.00,4.00,3.00,3.00,2.50,2.50]) Antenna_gain = np.arange(11) SANT = np.array([21.8,21.8,21.6,21.2,20.6,19...
_____no_output_____
MIT
LatitudeTable.ipynb
kssumanth27/notebooks
The below function and the curve_fit is written to calculate the antenna gain that is added to EIRP from above function
def ext_gain(x,a,b,c): return a*x**2 + b*x + c gain_data = [6.5,4.5,0] ang_gain = [90,60,30] popt,pcov = curve_fit(ext_gain,ang_gain,gain_data) popt
_____no_output_____
MIT
LatitudeTable.ipynb
kssumanth27/notebooks
The below cell plots the histograms of altitude(deg) and Distance(Km) for 13 different latitudes from 30 to -90
maxi = np.zeros(shape = 13) mini = np.zeros(shape = 13) avg = np.zeros(shape = 13) for i in range(13): num = 30+i*(-10) obs = LObservation(lunar_day = "FY2024", lun_lat_deg = num, deltaT_sec=10*60) S = LSatellite() obsat = ObservedSatellite(obs,S) transits = obsat.get_transit_indices() ...
_____no_output_____
MIT
LatitudeTable.ipynb
kssumanth27/notebooks
The cell below calculates the data transfer transfer in kbs. The variable that are commented out will be removed in next revision of this file. Disclaimer: This cell takes around 90 mins to run, which includes, calculating the variables from the lusee.lunar_satellite which takes most time followed by the repetitive u...
t0 = time.time() #main_max = np.zeros(shape = 13) #main_min = np.zeros(shape = 13) #main_mean = np.zeros(shape = 13) #counti_list = [] #counti_list_max = [] #counti_list_min = [] #counti_list_mean = [] datai_list = [] datai_list_max = [] datai_list_min = [] datai_list_mean = [] for i in range(13): # This loop itera...
loop number 0 loop number 1 loop number 2 loop number 3 loop number 4 loop number 5 loop number 6 loop number 7 loop number 8 loop number 9 loop number 10 loop number 11 loop number 12 [ 82. 124. 194. 317. 394. 427. 443. 452. 455. 454. 448. 437. 416.] [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 290. 377. 415.] [...
MIT
LatitudeTable.ipynb
kssumanth27/notebooks