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
There are also a few special keys in the `word2idx` dictionary. You are already familiar with the special start word (`""`) and special end word (`""`). There is one more special token, corresponding to unknown words (`""`). All tokens that don't appear anywhere in the `word2idx` dictionary are considered unknown wo...
unk_word = data_loader.dataset.vocab.unk_word print('Special unknown word:', unk_word) print('All unknown words are mapped to this integer:', data_loader.dataset.vocab(unk_word))
Special unknown word: <unk> All unknown words are mapped to this integer: 2
MIT
1_Preliminaries.ipynb
lanhhv84/Image-Captioning
Check this for yourself below, by pre-processing the provided nonsense words that never appear in the training captions.
print(data_loader.dataset.vocab('jfkafejw')) print(data_loader.dataset.vocab('ieowoqjf'))
2 2
MIT
1_Preliminaries.ipynb
lanhhv84/Image-Captioning
The final thing to mention is the `vocab_from_file` argument that is supplied when creating a data loader. To understand this argument, note that when you create a new data loader, the vocabulary (`data_loader.dataset.vocab`) is saved as a [pickle](https://docs.python.org/3/library/pickle.html) file in the project fol...
# Obtain the data loader (from file). Note that it runs much faster than before! data_loader = get_loader(transform=transform_train, mode='train', batch_size=batch_size, cocoapi_loc=cocoapi_loc, vocab_from_file=True)
Vocabulary successfully loaded from vocab.pkl file! loading annotations into memory...
MIT
1_Preliminaries.ipynb
lanhhv84/Image-Captioning
In the next section, you will learn how to use the data loader to obtain batches of training data. Step 2: Use the Data Loader to Obtain BatchesThe captions in the dataset vary greatly in length. You can see this by examining `data_loader.dataset.caption_lengths`, a Python list with one entry for each training captio...
from collections import Counter # Tally the total number of training captions with each length. counter = Counter(data_loader.dataset.caption_lengths) lengths = sorted(counter.items(), key=lambda pair: pair[1], reverse=True) for value, count in lengths: print('value: %2d --- count: %5d' % (value, count))
value: 10 --- count: 86332 value: 11 --- count: 79945 value: 9 --- count: 71935 value: 12 --- count: 57639 value: 13 --- count: 37648 value: 14 --- count: 22335 value: 8 --- count: 20769 value: 15 --- count: 12842 value: 16 --- count: 7729 value: 17 --- count: 4842 value: 18 --- count: 3103 value: 19 --- count: 2...
MIT
1_Preliminaries.ipynb
lanhhv84/Image-Captioning
To generate batches of training data, we begin by first sampling a caption length (where the probability that any length is drawn is proportional to the number of captions with that length in the dataset). Then, we retrieve a batch of size `batch_size` of image-caption pairs, where all captions have the sampled length...
import numpy as np import torch.utils.data as data # Randomly sample a caption length, and sample indices with that length. indices = data_loader.dataset.get_train_indices() print('sampled indices:', indices) # Create and assign a batch sampler to retrieve a batch with the sampled indices. new_sampler = data.sampler....
sampled indices: [233186, 219334, 248528, 332607, 300925, 24377, 336380, 59426, 23758, 306722] images.shape: torch.Size([10, 3, 224, 224]) captions.shape: torch.Size([10, 10])
MIT
1_Preliminaries.ipynb
lanhhv84/Image-Captioning
Each time you run the code cell above, a different caption length is sampled, and a different batch of training data is returned. Run the code cell multiple times to check this out!You will train your model in the next notebook in this sequence (**2_Training.ipynb**). This code for generating training batches will be ...
# Watch for any changes in model.py, and re-load it automatically. %load_ext autoreload %autoreload 2 # Import EncoderCNN and DecoderRNN. from model import EncoderCNN, DecoderRNN %reload_ext model
_____no_output_____
MIT
1_Preliminaries.ipynb
lanhhv84/Image-Captioning
In the next code cell we define a `device` that you will use move PyTorch tensors to GPU (if CUDA is available). Run this code cell before continuing.
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
_____no_output_____
MIT
1_Preliminaries.ipynb
lanhhv84/Image-Captioning
Run the code cell below to instantiate the CNN encoder in `encoder`. The pre-processed images from the batch in **Step 2** of this notebook are then passed through the encoder, and the output is stored in `features`.
# Specify the dimensionality of the image embedding. embed_size = 256 #-#-#-# Do NOT modify the code below this line. #-#-#-# # Initialize the encoder. (Optional: Add additional arguments if necessary.) encoder = EncoderCNN(embed_size) # Move the encoder to GPU if CUDA is available. encoder.to(device) # Move la...
Downloading: "https://download.pytorch.org/models/resnet50-19c8e357.pth" to /home/hvlpr/.cache/torch/checkpoints/resnet50-19c8e357.pth 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 102502400/102502400 [00:09<00:00, 11202810.52it/s]
MIT
1_Preliminaries.ipynb
lanhhv84/Image-Captioning
The encoder that we provide to you uses the pre-trained ResNet-50 architecture (with the final fully-connected layer removed) to extract features from a batch of pre-processed images. The output is then flattened to a vector, before being passed through a `Linear` layer to transform the feature vector to have the same...
from model import EncoderCNN, DecoderRNN # Specify the number of features in the hidden state of the RNN decoder. hidden_size = 512 #-#-#-# Do NOT modify the code below this line. #-#-#-# # Store the size of the vocabulary. vocab_size = len(data_loader.dataset.vocab) # Initialize the decoder. decoder = DecoderRNN(em...
torch.Size([10, 1, 256])
MIT
1_Preliminaries.ipynb
lanhhv84/Image-Captioning
Was this Cell below what you wanted?
# remove the mean for the c low = (couple_columns[['Energy']] - couple_columns[['Energy']].mean()).min()[0] high = (couple_columns[['Energy']] - couple_columns[['Energy']].mean()).max()[0] plt.scatter(couple_columns[['helix1 phase']], couple_columns[['helix 2 phase']], c=(couple_columns[['Energy']] - couple_columns[['E...
_____no_output_____
MIT
Request/.ipynb_checkpoints/sin-checkpoint.ipynb
mrpal39/Python_Tutorials
Example 2.1 Calculation of Volume of Gas Using Ideal Gas Behaviour
"Question is to calculate the volume of 3pounds of N-Butane gas using ideal gas behaviour" #known mass = 58.123 #lbs temp = 120 #Fdegrees pressure = 60 #psia m =3 #lbs R = 10.73 V= (m/mass)*(R*(temp+460)/pressure) #ft3 print("Volume of Gas using Ideal Gas Behaviour is:", V,"ft3")
Volume of Gas using Ideal Gas Behaviour is: 5.353646577086525 ft3
MIT
Chapter 2 Reservoir Fluid Properties/Examples/Chapter 2 Examples.ipynb
boomitsheth/Reservoir-Engineering-Handbook-
Example 2.2 Calculation of Density of N-Butane
"Question is to calculate the density of N-Butane" den = m/V print("Density of N-Butane is:", den,"lb/ft3")
Density of N-Butane is: 0.5603657164893786 lb/ft3
MIT
Chapter 2 Reservoir Fluid Properties/Examples/Chapter 2 Examples.ipynb
boomitsheth/Reservoir-Engineering-Handbook-
Example 2.3 Calculation of Density & Molecular Weight
"Calcualte apparent molecular weight of gas and gas density, " spg= 0.65 Qg= 1.1 #Mmscf/d pressure= 1500 #psia temp= 150 #Fdegree Molweight= 28.96 * spg #lbs print("Molecular Weight of the gas is:", Molweight,"lbs") Gasden = (pressure * Molweight) / (10.73 * (temp+460)) #lb/ft3 print("Gas Density is:",Gasden,"lb...
Molecular Weight of the gas is: 18.824 lbs Gas Density is: 4.3139351901364344 lbs/ft3
MIT
Chapter 2 Reservoir Fluid Properties/Examples/Chapter 2 Examples.ipynb
boomitsheth/Reservoir-Engineering-Handbook-
Example 2.4 Calculation of Specific Gravity and Molecular Weight
component= pd.read_csv("F:\Tarek Ahmed Reservoir Engineering Data\Chapter 2 Reservoir Fluid Properties\example2.4.csv") component Mi= [44.01,16.04,30.07,44.11] component[ 'Mi' ] = Mi component component['yiMi'] = component['yi'] * component['Mi'] component Ma = component.sum(axis=0) Ma "Hence the apparent weight is 1...
_____no_output_____
MIT
Chapter 2 Reservoir Fluid Properties/Examples/Chapter 2 Examples.ipynb
boomitsheth/Reservoir-Engineering-Handbook-
Example 2.5 Calculation of Gas Compressibility Factor
components = pd.read_csv("F:\Tarek Ahmed Reservoir Engineering Data\Chapter 2 Reservoir Fluid Properties\example2.5.csv") components pressure = 3000 #psia temp = 180 #Fdegree Tci =[547.91,227.49,343.33,549.92,666.06,734.46,765.62] components['Tci'] = Tci components components['yiTci'] = components['yi'] * components['T...
_____no_output_____
MIT
Chapter 2 Reservoir Fluid Properties/Examples/Chapter 2 Examples.ipynb
boomitsheth/Reservoir-Engineering-Handbook-
Example 2.17 Calculate Specific Gravity of Separated Gas
"Separator tests were conducted on a crude oil sample. Results of the test in terms of GOR and Gas Specific Gravity are calculated. " results = pd.read_csv("F:\Tarek Ahmed Reservoir Engineering Data\Chapter 2 Reservoir Fluid Properties\example2.17.csv") results results['GORGasSg']= results['GOR'] * results['GasSg'] r...
_____no_output_____
MIT
Chapter 2 Reservoir Fluid Properties/Examples/Chapter 2 Examples.ipynb
boomitsheth/Reservoir-Engineering-Handbook-
Example 2.18 Using Standing Correlation, Estimate Gas Solubility at Pb
table= pd.read_csv("F:\Tarek Ahmed Reservoir Engineering Data\Chapter 2 Reservoir Fluid Properties\example2.18.csv") table #T=Reservoir Temperature #Pb=Bubble Point Pressure #Bo=Oil Formation Volume Factor #Psep=Sperator Pressure #Tsep=separator Temperature #Co=Isothermal compressibility coeffeicient of the oil table[...
_____no_output_____
MIT
Chapter 2 Reservoir Fluid Properties/Examples/Chapter 2 Examples.ipynb
boomitsheth/Reservoir-Engineering-Handbook-
Mining TwitterTwitter implements OAuth 1.0A as its standard authentication mechanism, and in order to use it to make requests to Twitter's API, you'll need to go to https://developer.twitter.com/en/apps and create a sample application. There are four primary identifiers you'll need to note for an OAuth 1.0A workflow: ...
import twitter # Go to https://developer.twitter.com/en/apps to create an app and get values # for these credentials, which you'll need to provide in place of these # empty string values that are defined as placeholders. # See https://developer.twitter.com/en/docs/basics/authentication/overview/oauth # for more inform...
_____no_output_____
BSD-2-Clause
notebooks/Chapter 1 - Mining Twitter.ipynb
KaranamVijayKumar/Mining-the-Social-Web-3rd-Edition
Retrieving trends
# The Yahoo! Where On Earth ID for the entire world is 1. # See https://dev.twitter.com/docs/api/1.1/get/trends/place and # http://developer.yahoo.com/geo/geoplanet/ WORLD_WOE_ID = 1 US_WOE_ID = 23424977 # Prefix ID with the underscore for query string parameterization. # Without the underscore, the twitter package a...
_____no_output_____
BSD-2-Clause
notebooks/Chapter 1 - Mining Twitter.ipynb
KaranamVijayKumar/Mining-the-Social-Web-3rd-Edition
Anatomy of a Tweet
import json # Set this variable to a trending topic, # or anything else for that matter. The example query below # was a trending topic when this content was being developed # and is used throughout the remainder of this chapter. q = '#MothersDay' count = 100 # Import unquote to prevent url encoding errors in nex...
_____no_output_____
BSD-2-Clause
notebooks/Chapter 1 - Mining Twitter.ipynb
KaranamVijayKumar/Mining-the-Social-Web-3rd-Edition
Extracting text, screen names, and hashtags from tweets
status_texts = [ status['text'] for status in statuses ] screen_names = [ user_mention['screen_name'] for status in statuses for user_mention in status['entities']['user_mentions'] ] hashtags = [ hashtag['text'] for status in statuses ...
_____no_output_____
BSD-2-Clause
notebooks/Chapter 1 - Mining Twitter.ipynb
KaranamVijayKumar/Mining-the-Social-Web-3rd-Edition
Creating a basic frequency distribution from the words in tweets
from collections import Counter for item in [words, screen_names, hashtags]: c = Counter(item) print(c.most_common()[:10]) # top 10 print()
_____no_output_____
BSD-2-Clause
notebooks/Chapter 1 - Mining Twitter.ipynb
KaranamVijayKumar/Mining-the-Social-Web-3rd-Edition
Using prettytable to display tuples in a nice tabular format
from prettytable import PrettyTable for label, data in (('Word', words), ('Screen Name', screen_names), ('Hashtag', hashtags)): pt = PrettyTable(field_names=[label, 'Count']) c = Counter(data) [ pt.add_row(kv) for kv in c.most_common()[:10] ] pt.align[label], ...
_____no_output_____
BSD-2-Clause
notebooks/Chapter 1 - Mining Twitter.ipynb
KaranamVijayKumar/Mining-the-Social-Web-3rd-Edition
Calculating lexical diversity for tweets
# A function for computing lexical diversity def lexical_diversity(tokens): return len(set(tokens))/len(tokens) # A function for computing the average number of words per tweet def average_words(statuses): total_words = sum([ len(s.split()) for s in statuses ]) return total_words/len(statuses) print(lex...
_____no_output_____
BSD-2-Clause
notebooks/Chapter 1 - Mining Twitter.ipynb
KaranamVijayKumar/Mining-the-Social-Web-3rd-Edition
Finding the most popular retweets
retweets = [ # Store out a tuple of these three values ... (status['retweet_count'], status['retweeted_status']['user']['screen_name'], status['retweeted_status']['id'], status['text']) # ... for each status ... for st...
_____no_output_____
BSD-2-Clause
notebooks/Chapter 1 - Mining Twitter.ipynb
KaranamVijayKumar/Mining-the-Social-Web-3rd-Edition
Looking up users who have retweeted a status
# Get the original tweet id for a tweet from its retweeted_status node # and insert it here _retweets = twitter_api.statuses.retweets(id=862359093398261760) print([r['user']['screen_name'] for r in _retweets])
_____no_output_____
BSD-2-Clause
notebooks/Chapter 1 - Mining Twitter.ipynb
KaranamVijayKumar/Mining-the-Social-Web-3rd-Edition
Plotting frequencies of words
import matplotlib.pyplot as plt %matplotlib inline word_counts = sorted(Counter(words).values(), reverse=True) plt.loglog(word_counts) plt.ylabel("Freq") plt.xlabel("Word Rank")
_____no_output_____
BSD-2-Clause
notebooks/Chapter 1 - Mining Twitter.ipynb
KaranamVijayKumar/Mining-the-Social-Web-3rd-Edition
Generating histograms of words, screen names, and hashtags
for label, data in (('Words', words), ('Screen Names', screen_names), ('Hashtags', hashtags)): # Build a frequency map for each set of data # and plot the values c = Counter(data) plt.hist(list(c.values())) # Add a title and y-label ... plt.title(l...
_____no_output_____
BSD-2-Clause
notebooks/Chapter 1 - Mining Twitter.ipynb
KaranamVijayKumar/Mining-the-Social-Web-3rd-Edition
Generating a histogram of retweet counts
# Using underscores while unpacking values in # a tuple is idiomatic for discarding them counts = [count for count, _, _, _ in retweets] plt.hist(counts) plt.title('Retweets') plt.xlabel('Bins (number of times retweeted)') plt.ylabel('Number of tweets in bin')
_____no_output_____
BSD-2-Clause
notebooks/Chapter 1 - Mining Twitter.ipynb
KaranamVijayKumar/Mining-the-Social-Web-3rd-Edition
Sentiment Analysis
# pip install nltk import nltk nltk.download('vader_lexicon') import numpy as np from nltk.sentiment.vader import SentimentIntensityAnalyzer twitter_stream = twitter.TwitterStream(auth=auth) iterator = twitter_stream.statuses.sample() tweets = [] for tweet in iterator: try: if tweet['lang'] == 'en': ...
_____no_output_____
BSD-2-Clause
notebooks/Chapter 1 - Mining Twitter.ipynb
KaranamVijayKumar/Mining-the-Social-Web-3rd-Edition
Text models, data, and training
from fastai.gen_doc.nbdoc import *
_____no_output_____
Apache-2.0
docs_src/text.ipynb
holmesal/fastai
The [`text`](/text.htmltext) module of the fastai library contains all the necessary functions to define a Dataset suitable for the various NLP (Natural Language Processing) tasks and quickly generate models you can use for them. Specifically:- [`text.transform`](/text.transform.htmltext.transform) contains all the scr...
from fastai import * from fastai.text import *
_____no_output_____
Apache-2.0
docs_src/text.ipynb
holmesal/fastai
Contrary to images in Computer Vision, text can't directly be transformed into numbers to be fed into a model. The first thing we need to do is to preprocess our data so that we change the raw texts to lists of words, or tokens (a step that is called tokenization) then transform these tokens into numbers (a step that i...
path = untar_data(URLs.IMDB_SAMPLE) path
_____no_output_____
Apache-2.0
docs_src/text.ipynb
holmesal/fastai
Creating a dataset from your raw texts is very simple if you have it in one of those ways- organized it in folders in an ImageNet style- organized in a csv file with labels columns and a text columnsHere, the sample from imdb is in a texts csv files that looks like this:
df = pd.read_csv(path/'texts.csv') df.head()
_____no_output_____
Apache-2.0
docs_src/text.ipynb
holmesal/fastai
Getting your data ready for modeling
for file in ['train_tok.npy', 'valid_tok.npy']: if os.path.exists(path/'tmp'/file): os.remove(path/'tmp'/file)
_____no_output_____
Apache-2.0
docs_src/text.ipynb
holmesal/fastai
To get a [`DataBunch`](/basic_data.htmlDataBunch) quickly, there are also several factory methods depending on how our data is structured. They are all detailed in [`text.data`](/text.data.htmltext.data), here we'll use the method from_csv of the [`TextLMDataBunch`](/text.data.htmlTextLMDataBunch) (to get the data read...
# Language model data data_lm = TextLMDataBunch.from_csv(path, 'texts.csv') # Classifier model data data_clas = TextClasDataBunch.from_csv(path, 'texts.csv', vocab=data_lm.train_ds.vocab, bs=32)
_____no_output_____
Apache-2.0
docs_src/text.ipynb
holmesal/fastai
This does all the necessary preprocessing behing the scene. For the classifier, we also pass the vocabulary (mapping from ids to words) that we want to use: this is to ensure that `data_clas` will use the same dictionary as `data_lm`.Since this step can be a bit time-consuming, it's best to save the result with:
data_lm.save() data_clas.save()
_____no_output_____
Apache-2.0
docs_src/text.ipynb
holmesal/fastai
This will create a 'tmp' directory where all the computed stuff will be stored. You can then reload those results with:
data_lm = TextLMDataBunch.load(path) data_clas = TextClasDataBunch.load(path, bs=32)
_____no_output_____
Apache-2.0
docs_src/text.ipynb
holmesal/fastai
Note that you can load the data with different [`DataBunch`](/basic_data.htmlDataBunch) parameters (batch size, `bptt`,...) Fine-tuning a language model We can use the `data_lm` object we created earlier to fine-tune a pretrained language model. [fast.ai](http://www.fast.ai/) has an English model available that we can...
learn = language_model_learner(data_lm, pretrained_model=URLs.WT103, drop_mult=0.5) learn.fit_one_cycle(1, 1e-2)
Total time: 00:04 epoch train_loss valid_loss accuracy 1 4.720898 4.212008 0.248862 (00:04)
Apache-2.0
docs_src/text.ipynb
holmesal/fastai
Like a computer vision model, we can then unfreeze the model and fine-tune it.
learn.unfreeze() learn.fit_one_cycle(1, 1e-3)
Total time: 00:22 epoch train_loss valid_loss accuracy 1 4.450525 4.127853 0.253167 (00:22)
Apache-2.0
docs_src/text.ipynb
holmesal/fastai
To evaluate your language model, you can run the [`Learner.predict`](/basic_train.htmlLearner.predict) method and specify the number of words you want it to guess.
learn.predict("This is a review about", n_words=10)
Total time: 00:00
Apache-2.0
docs_src/text.ipynb
holmesal/fastai
It doesn't make much sense (we have a tiny vocabulary here and didn't train much on it) but note that it respects basic grammar (which comes from the pretrained model).Finally we save the encoder to be able to use it for classification in the next section.
learn.save_encoder('ft_enc')
_____no_output_____
Apache-2.0
docs_src/text.ipynb
holmesal/fastai
Building a classifier We now use the `data_clas` object we created earlier to build a classifier with our fine-tuned encoder. The learner object can be done in a single line.
learn = text_classifier_learner(data_clas, drop_mult=0.5) learn.load_encoder('ft_enc') learn.fit_one_cycle(1, 1e-2)
Total time: 00:26 epoch train_loss valid_loss accuracy 1 0.686503 0.632651 0.701493 (00:26)
Apache-2.0
docs_src/text.ipynb
holmesal/fastai
Again, we can unfreeze the model and fine-tune it.
learn.freeze_to(-2) learn.fit_one_cycle(1, slice(5e-3/2., 5e-3)) learn.unfreeze() learn.fit_one_cycle(1, slice(2e-3/100, 2e-3))
Total time: 00:55 epoch train_loss valid_loss accuracy 1 0.510760 0.479997 0.791045 (00:55)
Apache-2.0
docs_src/text.ipynb
holmesal/fastai
Again, we can predict on a raw text by using the [`Learner.predict`](/basic_train.htmlLearner.predict) method.
learn.predict("This was a great movie!")
_____no_output_____
Apache-2.0
docs_src/text.ipynb
holmesal/fastai
Project 5: NLP on Financial Statements InstructionsEach problem consists of a function to implement and instructions on how to implement the function. The parts of the function that need to be implemented are marked with a ` TODO` comment. After implementing the function, run the cell to test it against the unit test...
import sys !{sys.executable} -m pip install -r requirements.txt
Collecting alphalens==0.3.2 (from -r requirements.txt (line 1)) [?25l Downloading https://files.pythonhosted.org/packages/a5/dc/2f9cd107d0d4cf6223d37d81ddfbbdbf0d703d03669b83810fa6b97f32e5/alphalens-0.3.2.tar.gz (18.9MB)  100% |β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 18.9MB 1.8MB/s eta 0:00:01 3% |β–ˆβ– ...
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Load Packages
import nltk import numpy as np import pandas as pd import pickle import pprint import project_helper import project_tests from tqdm import tqdm
_____no_output_____
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Download NLP CorporaYou'll need two corpora to run this project: the stopwords corpus for removing stopwords and wordnet for lemmatizing.
nltk.download('stopwords') nltk.download('wordnet')
[nltk_data] Downloading package stopwords to /root/nltk_data... [nltk_data] Unzipping corpora/stopwords.zip. [nltk_data] Downloading package wordnet to /root/nltk_data... [nltk_data] Unzipping corpora/wordnet.zip.
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Get 10ksWe'll be running NLP analysis on 10-k documents. To do that, we first need to download the documents. For this project, we'll download 10-ks for a few companies. To lookup documents for these companies, we'll use their CIK. If you would like to run this against other stocks, we've provided the dict `additional...
cik_lookup = { 'AMZN': '0001018724', 'BMY': '0000014272', 'CNP': '0001130310', 'CVX': '0000093410', 'FL': '0000850209', 'FRT': '0000034903', 'HON': '0000773840'} additional_cik = { 'AEP': '0000004904', 'AXP': '0000004962', 'BA': '0000012927', 'BK': '0001390777', 'CAT...
_____no_output_____
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Get list of 10-ksThe SEC has a limit on the number of calls you can make to the website per second. In order to avoid hiding that limit, we've created the `SecAPI` class. This will cache data from the SEC and prevent you from going over the limit.
sec_api = project_helper.SecAPI()
_____no_output_____
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
With the class constructed, let's pull a list of filled 10-ks from the SEC for each company.
from bs4 import BeautifulSoup def get_sec_data(cik, doc_type, start=0, count=60): newest_pricing_data = pd.to_datetime('2018-01-01') rss_url = 'https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany' \ '&CIK={}&type={}&start={}&count={}&owner=exclude&output=atom' \ .format(cik, doc_type, st...
_____no_output_____
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Let's pull the list using the `get_sec_data` function, then display some of the results. For displaying some of the data, we'll use Amazon as an example.
example_ticker = 'AMZN' sec_data = {} for ticker, cik in cik_lookup.items(): sec_data[ticker] = get_sec_data(cik, '10-K') pprint.pprint(sec_data[example_ticker][:5])
[('https://www.sec.gov/Archives/edgar/data/1018724/000101872417000011/0001018724-17-000011-index.htm', '10-K', '2017-02-10'), ('https://www.sec.gov/Archives/edgar/data/1018724/000101872416000172/0001018724-16-000172-index.htm', '10-K', '2016-01-29'), ('https://www.sec.gov/Archives/edgar/data/1018724/000101872...
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Download 10-ksAs you see, this is a list of urls. These urls point to a file that contains metadata related to each filling. Since we don't care about the metadata, we'll pull the filling by replacing the url with the filling url.
raw_fillings_by_ticker = {} for ticker, data in sec_data.items(): raw_fillings_by_ticker[ticker] = {} for index_url, file_type, file_date in tqdm(data, desc='Downloading {} Fillings'.format(ticker), unit='filling'): if (file_type == '10-K'): file_url = index_url.replace('-index.htm', '.txt'...
Downloading AMZN Fillings: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 22/22 [00:03<00:00, 6.59filling/s] Downloading BMY Fillings: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 27/27 [00:05<00:00, 4.56filling/s] Downloading CNP Fillings: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 19/19 [00:03<00:00, 5.34filling/s] Downloading CVX Fillings: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 25/25 [00:05<00:00, 4.65filling/s] Dow...
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Get DocumentsWith theses fillings downloaded, we want to break them into their associated documents. These documents are sectioned off in the fillings with the tags `` for the start of each document and `` for the end of each document. There's no overlap with these documents, so each `` tag should come after the `` wi...
import re def get_documents(text): """ Extract the documents from the text Parameters ---------- text : str The text with the document strings inside Returns ------- extracted_docs : list of str The document strings found in `text` """ # TODO: Implement ...
Tests Passed
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
With the `get_documents` function implemented, let's extract all the documents.
filling_documents_by_ticker = {} for ticker, raw_fillings in raw_fillings_by_ticker.items(): filling_documents_by_ticker[ticker] = {} for file_date, filling in tqdm(raw_fillings.items(), desc='Getting Documents from {} Fillings'.format(ticker), unit='filling'): filling_documents_by_ticker[ticker][file_...
Getting Documents from AMZN Fillings: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 17/17 [00:00<00:00, 41.88filling/s] Getting Documents from BMY Fillings: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 23/23 [00:01<00:00, 20.93filling/s] Getting Documents from CNP Fillings: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 15/15 [00:00<00:00, 21.72filling/s] Getting Documents from CVX Fillings: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ...
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Get Document TypesNow that we have all the documents, we want to find the 10-k form in this 10-k filing. Implement the `get_document_type` function to return the type of document given. The document type is located on a line with the `` tag. For example, a form of type "TEST" would have the line `TEST`. Make sure to r...
def get_document_type(doc): """ Return the document type lowercased Parameters ---------- doc : str The document string Returns ------- doc_type : str The document type lowercased """ # TODO: Implement # (?<= positive lookbehind. matches a group before ...
Tests Passed
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
With the `get_document_type` function, we'll filter out all non 10-k documents.
ten_ks_by_ticker = {} for ticker, filling_documents in filling_documents_by_ticker.items(): ten_ks_by_ticker[ticker] = [] for file_date, documents in filling_documents.items(): for document in documents: if get_document_type(document) == '10-k': ten_ks_by_ticker[ticker].appe...
[ { cik: '0001018724' file: '\n<TYPE>10-K\n<SEQUENCE>1\n<FILENAME>amzn-2016123... file_date: '2017-02-10'}, { cik: '0001018724' file: '\n<TYPE>10-K\n<SEQUENCE>1\n<FILENAME>amzn-2015123... file_date: '2016-01-29'}, { cik: '0001018724' file: '\n<TYPE>10-K\n<SEQUENCE>1\n<FILENAME>amzn...
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Preprocess the Data Clean UpAs you can see, the text for the documents are very messy. To clean this up, we'll remove the html and lowercase all the text.
def remove_html_tags(text): text = BeautifulSoup(text, 'html.parser').get_text() return text def clean_text(text): text = text.lower() text = remove_html_tags(text) return text
_____no_output_____
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Using the `clean_text` function, we'll clean up all the documents.
for ticker, ten_ks in ten_ks_by_ticker.items(): for ten_k in tqdm(ten_ks, desc='Cleaning {} 10-Ks'.format(ticker), unit='10-K'): ten_k['file_clean'] = clean_text(ten_k['file']) project_helper.print_ten_k_data(ten_ks_by_ticker[example_ticker][:5], ['file_clean'])
Cleaning AMZN 10-Ks: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 17/17 [00:35<00:00, 2.08s/10-K] Cleaning BMY 10-Ks: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 23/23 [01:15<00:00, 3.30s/10-K] Cleaning CNP 10-Ks: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 15/15 [00:57<00:00, 3.83s/10-K] Cleaning CVX 10-Ks: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 21/21 [01:52<00:00, 5.36s/10-K] Cleaning FL 10-Ks: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 16/...
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
LemmatizeWith the text cleaned up, it's time to distill the verbs down. Implement the `lemmatize_words` function to lemmatize verbs in the list of words provided.
from nltk.stem import WordNetLemmatizer from nltk.corpus import wordnet def lemmatize_words(words): """ Lemmatize words Parameters ---------- words : list of str List of words Returns ------- lemmatized_words : list of str List of lemmatized words """ # ...
Tests Passed
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
With the `lemmatize_words` function implemented, let's lemmatize all the data.
word_pattern = re.compile('\w+') for ticker, ten_ks in ten_ks_by_ticker.items(): for ten_k in tqdm(ten_ks, desc='Lemmatize {} 10-Ks'.format(ticker), unit='10-K'): ten_k['file_lemma'] = lemmatize_words(word_pattern.findall(ten_k['file_clean'])) project_helper.print_ten_k_data(ten_ks_by_ticker[example_tick...
Lemmatize AMZN 10-Ks: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 17/17 [00:04<00:00, 3.9110-K/s] Lemmatize BMY 10-Ks: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 23/23 [00:09<00:00, 2.4010-K/s] Lemmatize CNP 10-Ks: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 15/15 [00:07<00:00, 1.9210-K/s] Lemmatize CVX 10-Ks: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 21/21 [00:09<00:00, 2.3310-K/s] Lemmatize FL 10-Ks: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ...
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Remove Stopwords
from nltk.corpus import stopwords lemma_english_stopwords = lemmatize_words(stopwords.words('english')) for ticker, ten_ks in ten_ks_by_ticker.items(): for ten_k in tqdm(ten_ks, desc='Remove Stop Words for {} 10-Ks'.format(ticker), unit='10-K'): ten_k['file_lemma'] = [word for word in ten_k['file_lemma']...
Remove Stop Words for AMZN 10-Ks: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 17/17 [00:01<00:00, 9.2810-K/s] Remove Stop Words for BMY 10-Ks: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 23/23 [00:04<00:00, 5.6110-K/s] Remove Stop Words for CNP 10-Ks: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 15/15 [00:03<00:00, 4.5310-K/s] Remove Stop Words for CVX 10-Ks: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 21/21 [00:03<00:00, ...
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Analysis on 10ks Loughran McDonald Sentiment Word ListsWe'll be using the Loughran and McDonald sentiment word lists. These word lists cover the following sentiment:- Negative - Positive- Uncertainty- Litigious- Constraining- Superfluous- ModalThis will allow us to do the sentiment analysis on the 10-ks. Let's first l...
import os sentiments = ['negative', 'positive', 'uncertainty', 'litigious', 'constraining', 'interesting'] sentiment_df = pd.read_csv(os.path.join('..', '..', 'data', 'project_5_loughran_mcdonald', 'loughran_mcdonald_master_dic_2016.csv')) sentiment_df.columns = [column.lower() for column in sentiment_df.columns] # ...
_____no_output_____
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Bag of Wordsusing the sentiment word lists, let's generate sentiment bag of words from the 10-k documents. Implement `get_bag_of_words` to generate a bag of words that counts the number of sentiment words in each doc. You can ignore words that are not in `sentiment_words`.
from collections import defaultdict, Counter from sklearn.feature_extraction.text import CountVectorizer def get_bag_of_words(sentiment_words, docs): """ Generate a bag of words from documents for a certain sentiment Parameters ---------- sentiment_words: Pandas Series Words that signify ...
Tests Passed
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Using the `get_bag_of_words` function, we'll generate a bag of words for all the documents.
sentiment_bow_ten_ks = {} for ticker, ten_ks in ten_ks_by_ticker.items(): lemma_docs = [' '.join(ten_k['file_lemma']) for ten_k in ten_ks] sentiment_bow_ten_ks[ticker] = { sentiment: get_bag_of_words(sentiment_df[sentiment_df[sentiment]]['word'], lemma_docs) for sentiment in sentiments} ...
[ { negative: '[[0 0 0 ..., 0 0 0]\n [0 0 0 ..., 0 0 0]\n [0 0 0... positive: '[[16 0 0 ..., 0 0 0]\n [16 0 0 ..., 0 0 ... uncertainty: '[[0 0 0 ..., 1 1 3]\n [0 0 0 ..., 1 1 3]\n [0 0 0... litigious: '[[0 0 0 ..., 0 0 0]\n [0 0 0 ..., 0 0 0]\n [0 0 0... constraining: '[[0 0 0 ..., 0 0 2]...
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Jaccard SimilarityUsing the bag of words, let's calculate the jaccard similarity on the bag of words and plot it over time. Implement `get_jaccard_similarity` to return the jaccard similarities between each tick in time. Since the input, `bag_of_words_matrix`, is a bag of words for each time period in order, you just ...
from sklearn.metrics import jaccard_similarity_score def get_jaccard_similarity(bag_of_words_matrix): """ Get jaccard similarities for neighboring documents Parameters ---------- bag_of_words : 2-d Numpy Ndarray of int Bag of words sentiment for each document The first dimension i...
Tests Passed
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Using the `get_jaccard_similarity` function, let's plot the similarities over time.
# Get dates for the universe file_dates = { ticker: [ten_k['file_date'] for ten_k in ten_ks] for ticker, ten_ks in ten_ks_by_ticker.items()} jaccard_similarities = { ticker: { sentiment_name: get_jaccard_similarity(sentiment_values) for sentiment_name, sentiment_values in ten_k_sentiments...
_____no_output_____
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
TFIDFusing the sentiment word lists, let's generate sentiment TFIDF from the 10-k documents. Implement `get_tfidf` to generate TFIDF from each document, using sentiment words as the terms. You can ignore words that are not in `sentiment_words`.
from sklearn.feature_extraction.text import TfidfVectorizer def get_tfidf(sentiment_words, docs): """ Generate TFIDF values from documents for a certain sentiment Parameters ---------- sentiment_words: Pandas Series Words that signify a certain sentiment docs : list of str Lis...
Tests Passed
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Using the `get_tfidf` function, let's generate the TFIDF values for all the documents.
sentiment_tfidf_ten_ks = {} for ticker, ten_ks in ten_ks_by_ticker.items(): lemma_docs = [' '.join(ten_k['file_lemma']) for ten_k in ten_ks] sentiment_tfidf_ten_ks[ticker] = { sentiment: get_tfidf(sentiment_df[sentiment_df[sentiment]]['word'], lemma_docs) for sentiment in sentiments} ...
[ { negative: '[[ 0. 0. 0. ..., 0. ... positive: '[[ 0.22288432 0. 0. ..., 0. ... uncertainty: '[[ 0. 0. 0. ..., 0.005... litigious: '[[ 0. 0. 0. ..., 0. 0. 0.]\n [ 0. 0. 0. ..... constraining: '[[ 0. 0. ...
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Cosine SimilarityUsing the TFIDF values, we'll calculate the cosine similarity and plot it over time. Implement `get_cosine_similarity` to return the cosine similarities between each tick in time. Since the input, `tfidf_matrix`, is a TFIDF vector for each time period in order, you just need to computer the cosine sim...
from sklearn.metrics.pairwise import cosine_similarity def get_cosine_similarity(tfidf_matrix): """ Get cosine similarities for each neighboring TFIDF vector/document Parameters ---------- tfidf : 2-d Numpy Ndarray of float TFIDF sentiment for each document The first dimension is ...
Tests Passed
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Let's plot the cosine similarities over time.
cosine_similarities = { ticker: { sentiment_name: get_cosine_similarity(sentiment_values) for sentiment_name, sentiment_values in ten_k_sentiments.items()} for ticker, ten_k_sentiments in sentiment_tfidf_ten_ks.items()} project_helper.plot_similarities( [cosine_similarities[example_ticker]...
_____no_output_____
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Evaluate Alpha FactorsJust like we did in project 4, let's evaluate the alpha factors. For this section, we'll just be looking at the cosine similarities, but it can be applied to the jaccard similarities as well. Price DataLet's get yearly pricing to run the factor against, since 10-Ks are produced annually.
pricing = pd.read_csv('../../data/project_5_yr/yr-quotemedia.csv', parse_dates=['date']) pricing = pricing.pivot(index='date', columns='ticker', values='adj_close') pricing
_____no_output_____
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Dict to DataFrameThe alphalens library uses dataframes, so we we'll need to turn our dictionary into a dataframe.
cosine_similarities_df_dict = {'date': [], 'ticker': [], 'sentiment': [], 'value': []} for ticker, ten_k_sentiments in cosine_similarities.items(): for sentiment_name, sentiment_values in ten_k_sentiments.items(): for sentiment_values, sentiment_value in enumerate(sentiment_values): cosine_sim...
_____no_output_____
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Alphalens FormatIn order to use a lot of the alphalens functions, we need to aligned the indices and convert the time to unix timestamp. In this next cell, we'll do just that.
import alphalens as al factor_data = {} skipped_sentiments = [] for sentiment in sentiments: cs_df = cosine_similarities_df[(cosine_similarities_df['sentiment'] == sentiment)] cs_df = cs_df.pivot(index='date', columns='ticker', values='value') try: data = al.utils.get_clean_factor_and_forward_re...
/opt/conda/lib/python3.6/site-packages/statsmodels/compat/pandas.py:56: FutureWarning: The pandas.core.datetools module is deprecated and will be removed in a future version. Please use the pandas.tseries module instead. from pandas.core import datetools
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Alphalens Format with Unix TimeAlphalen's `factor_rank_autocorrelation` and `mean_return_by_quantile` functions require unix timestamps to work, so we'll also create factor dataframes with unix time.
unixt_factor_data = { factor: data.set_index(pd.MultiIndex.from_tuples( [(x.timestamp(), y) for x, y in data.index.values], names=['date', 'asset'])) for factor, data in factor_data.items()}
_____no_output_____
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Factor ReturnsLet's view the factor returns over time. We should be seeing it generally move up and to the right.
ls_factor_returns = pd.DataFrame() for factor_name, data in factor_data.items(): ls_factor_returns[factor_name] = al.performance.factor_returns(data).iloc[:, 0] (1 + ls_factor_returns).cumprod().plot()
_____no_output_____
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Basis Points Per Day per QuantileIt is not enough to look just at the factor weighted return. A good alpha is also monotonic in quantiles. Let's looks the basis points for the factor returns.
qr_factor_returns = pd.DataFrame() for factor_name, data in unixt_factor_data.items(): qr_factor_returns[factor_name] = al.performance.mean_return_by_quantile(data)[0].iloc[:, 0] (10000*qr_factor_returns).plot.bar( subplots=True, sharey=True, layout=(5,3), figsize=(14, 14), legend=False)
_____no_output_____
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Turnover AnalysisWithout doing a full and formal backtest, we can analyze how stable the alphas are over time. Stability in this sense means that from period to period, the alpha ranks do not change much. Since trading is costly, we always prefer, all other things being equal, that the ranks do not change significantl...
ls_FRA = pd.DataFrame() for factor, data in unixt_factor_data.items(): ls_FRA[factor] = al.performance.factor_rank_autocorrelation(data) ls_FRA.plot(title="Factor Rank Autocorrelation")
_____no_output_____
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Sharpe Ratio of the AlphasThe last analysis we'll do on the factors will be sharpe ratio. Let's see what the sharpe ratio for the factors are. Generally, a Sharpe Ratio of near 1.0 or higher is an acceptable single alpha for this universe.
daily_annualization_factor = np.sqrt(252) (daily_annualization_factor * ls_factor_returns.mean() / ls_factor_returns.std()).round(2)
_____no_output_____
Apache-2.0
NLP on Financial Statements/project_5_starter.ipynb
saidulislam/AI-for-Trading
Machine Learning Model Building Pipeline: Machine Learning Model BuildIn the following notebooks, I will take you through a practical example of each one of the steps in the Machine Learning model building pipeline that I learned throughout my experience and analyzing many kaggle notebooks. There will be a notebook fo...
# to handle datasets import pandas as pd import numpy as np # for plotting import matplotlib.pyplot as plt %matplotlib inline # to build the models from sklearn.linear_model import Lasso # to evaluate the models from sklearn.metrics import mean_squared_error from math import sqrt # to visualise al the columns in th...
_____no_output_____
MIT
04 Model_Building_and_Evaluaion/Model_Building.ipynb
Karthikraja-Pandian/Project---House-Prices-Prediction
Regularised linear regressionRemember to set the seed.
# train the model lin_model = Lasso(alpha=0.005, random_state=0) # remember to set the random_state / seed lin_model.fit(X_train, y_train) # evaluate the model: # remember that we log transformed the output (SalePrice) in our feature engineering notebook # In order to get the true performance of the Lasso # we need to...
_____no_output_____
MIT
04 Model_Building_and_Evaluaion/Model_Building.ipynb
Karthikraja-Pandian/Project---House-Prices-Prediction
We can see that our model is doing a pretty good job at estimating house prices.
# let's evaluate the distribution of the errors: # they should be fairly normally distributed errors = y_test - lin_model.predict(X_test) errors.hist(bins=15)
_____no_output_____
MIT
04 Model_Building_and_Evaluaion/Model_Building.ipynb
Karthikraja-Pandian/Project---House-Prices-Prediction
The distribution of the errors follows quite closely a gaussian distribution. That suggests that our model is doing a good job as well. Feature importance
# Finally, just for fun, let's look at the feature importance importance = pd.Series(np.abs(lin_model.coef_.ravel())) importance.index = features importance.sort_values(inplace=True, ascending=False) importance.plot.bar(figsize=(18,6)) plt.ylabel('Lasso Coefficients') plt.title('Feature Importance')
_____no_output_____
MIT
04 Model_Building_and_Evaluaion/Model_Building.ipynb
Karthikraja-Pandian/Project---House-Prices-Prediction
ENV / ATM 415: Climate Laboratory The planetary energy budget in CESM simulations Tuesday April 19 and Thursday April 21, 2016_____________________________________
%matplotlib inline import numpy as np import matplotlib.pyplot as plt import netCDF4 as nc
/Users/Brian/anaconda/lib/python2.7/site-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment. warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')
MIT
notes/CESM_energy_budget.ipynb
brian-rose/env-415-site
Open the output from our control simulation with the slab ocean version of the CESM:
## To read data over the internet control_filename = 'som_1850_f19.cam.h0.clim.nc' datapath = 'http://ramadda.atmos.albany.edu:8080/repository/opendap/latest/Top/Users/Brian+Rose/CESM+runs/' endstr = '/entry.das' control = nc.Dataset( datapath + 'som_1850_f19/' + control_filename + endstr ) ## To read from a local c...
_____no_output_____
MIT
notes/CESM_energy_budget.ipynb
brian-rose/env-415-site
The full file from the online server contains many many variables, describing all aspects of the model climatology.Whether we see a long list or a short list in the following code block depends on whether we are reading the full output file or the much smaller subset:
for v in control.variables: print v
lev hyam hybm ilev hyai hybi P0 time date datesec lat lon slat slon w_stag time_bnds date_written time_written ntrm ntrn ntrk ndbase nsbase nbdate nbsec mdt nlon wnummax gw ndcur nscur co2vmr ch4vmr n2ovmr f11vmr f12vmr sol_tsi nsteph AEROD_v CLDHGH CLDICE CLDLIQ CLDLOW CLDMED CLDTOT CLOUD CONCLD DCQ DTCOND DTV EMIS FI...
MIT
notes/CESM_energy_budget.ipynb
brian-rose/env-415-site
Today we need just a few of these variables:- `TS`: the surface temperature- `FLNT`: the longwave radiation at the top of the atmosphere (i.e. what we call the OLR)- `FSNT`: the net shortwave radiation at the top of the atmosphere (i.e. what we call the ASR)- `FLNTC`: the clear-sky OLR- `FSNTC`: the clear-sky ASR Take ...
for field in ['TS', 'FLNT', 'FSNT', 'FLNTC', 'FSNTC']: print control.variables[field]
<type 'netCDF4._netCDF4.Variable'> float32 TS(time, lat, lon) units: K long_name: Surface temperature (radiative) cell_methods: time: mean time: mean unlimited dimensions: time current shape = (12, 96, 144) filling off <type 'netCDF4._netCDF4.Variable'> float32 FLNT(time, lat, lon) Sampling_Sequence: r...
MIT
notes/CESM_energy_budget.ipynb
brian-rose/env-415-site
Each one of these variables has dimensions `(12, 96, 144)`, which corresponds to time (12 months), latitude and longitude.Take a look at one of the coordinate variables:
print control.variables['lat']
<type 'netCDF4._netCDF4.Variable'> float64 lat(lat) long_name: latitude units: degrees_north unlimited dimensions: current shape = (96,) filling off
MIT
notes/CESM_energy_budget.ipynb
brian-rose/env-415-site
Now let's load in the coordinate data, to use later for plotting:
lat = control.variables['lat'][:] lon = control.variables['lon'][:] print lat
[-90. -88.10526316 -86.21052632 -84.31578947 -82.42105263 -80.52631579 -78.63157895 -76.73684211 -74.84210526 -72.94736842 -71.05263158 -69.15789474 -67.26315789 -65.36842105 -63.47368421 -61.57894737 -59.68421053 -57.78947368 -55.89473684 -54. -52.10526316 -50.21052632 -48.31578947 -46.42105263 -44...
MIT
notes/CESM_energy_budget.ipynb
brian-rose/env-415-site
Surface temperature in the control simulation
# A re-usable function to make a map of a 2d field on a latitude / longitude grid def make_map(field_2d): # Make a filled contour plot fig = plt.figure(figsize=(10,5)) cax = plt.contourf(lon, lat, field_2d) # draw a single contour to outline the continents plt.contour( lon, lat, control.variables...
_____no_output_____
MIT
notes/CESM_energy_budget.ipynb
brian-rose/env-415-site
Computing a global average
# The lat/lon dimensions after taking the time average: TS_annual = np.mean(control.variables['TS'][:], axis=0) TS_annual.shape
_____no_output_____
MIT
notes/CESM_energy_budget.ipynb
brian-rose/env-415-site
Define a little re-usable function to take the global average of any of these fields:
def global_mean(field_2d): '''This function takes a 2D array on a regular latitude-longitude grid and returns the global area-weighted average''' zonal_mean = np.mean(field_2d, axis=1) return np.average(zonal_mean, weights=np.cos(np.deg2rad(lat))) # Again, a convenience function that takes just the...
_____no_output_____
MIT
notes/CESM_energy_budget.ipynb
brian-rose/env-415-site
Now compute the global average surface temperature in the simulation:
global_mean_this('TS')
_____no_output_____
MIT
notes/CESM_energy_budget.ipynb
brian-rose/env-415-site
Cloud cover in the control simulation The model simulates cloud amount in every grid box. The cloud field is thus 4-dimensional:
# This field is not included in the small subset file # so this will only work if you are reading the full file from the online server control.variables['CLOUD']
_____no_output_____
MIT
notes/CESM_energy_budget.ipynb
brian-rose/env-415-site
To simplify things we can just look at the **total cloud cover**, integrated from the surface to the top of the atmosphere:
control.variables['CLDTOT'] map_this('CLDTOT')
_____no_output_____
MIT
notes/CESM_energy_budget.ipynb
brian-rose/env-415-site
Which parts of Earth are cloudy and which are not? (at least in this simulation) Exercise 1: Make three maps: ASR, OLR, and the net radiation ASR-OLR (all annual averages)What interesting features do you see on these maps?
# To get you started, here is the ASR map_this('FSNT') map_this('FLNT') net_radiation = np.mean(control.variables['FSNT'][:] - control.variables['FLNT'][:], axis=0) make_map(net_radiation)
_____no_output_____
MIT
notes/CESM_energy_budget.ipynb
brian-rose/env-415-site
Exercise 2: Calculate the global average net radiation. Is it close to zero? What does that mean?
global_mean(net_radiation)
_____no_output_____
MIT
notes/CESM_energy_budget.ipynb
brian-rose/env-415-site
Exercise 3: Make maps of the clear-sky ASR and clear-sky OLRThese diagnostics have been calculated by the GCM. Basically at every timestep, the GCM calculates the radiation twice: once with the clouds and once without the clouds. Exercise 4: Make a map of the Cloud Radiative EffectRecall that we define $CRE$ as$$ CRE...
# The meta-data: control.variables['co2vmr'] # The data themselves, expressed in ppm: control.variables['co2vmr'][:] * 1E6
_____no_output_____
MIT
notes/CESM_energy_budget.ipynb
brian-rose/env-415-site
Answer: the CO2 concentration is 284.7 ppm in the control simulation. Now we want to see how the climate changes in the CESM when we double CO2 and run it out to equilibrium.I have done this. Because we are using a slab ocean model, it reaches equilibrium after just a few decades.Let's now open up the output file from ...
## To read data over the internet # doubleCO2_filename = 'som_1850_2xCO2.cam.h0.clim.nc' # doubleCO2 = nc.Dataset( datapath + 'som_1850_f19/' + doubleCO2_filename + endstr ) ## To read from a local copy of the file ## (just a small subset of the total list of variables, to save disk space) doubleCO2_filename = 'som...
_____no_output_____
MIT
notes/CESM_energy_budget.ipynb
brian-rose/env-415-site
This file has all the same fields as `control`, but they reflect the new equilibrium climate after doubling CO2.Let's verify the CO2 amount:
doubleCO2.variables['co2vmr'][:] * 1E6
_____no_output_____
MIT
notes/CESM_energy_budget.ipynb
brian-rose/env-415-site