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 |
|---|---|---|---|---|---|
6) Create A New ModelCreate a new model called `second_fashion_model` in the cell below. Make some changes so it is different than `fashion_model` that you've trained above. The change could be using a different number of layers, different number of convolutions in the layers, etc.Define the model, compile it and fit... | # Your code below
second_fashion_model = Sequential()
second_fashion_model.add(Conv2D(16, kernel_size=3, activation='relu', input_shape=(img_rows, img_cols, 1)))
second_fashion_model.add(Conv2D(24, kernel_size=2, activation='relu'))
second_fashion_model.add(Conv2D(32, kernel_size=2, activation='relu'))
second_fashion_m... | _____no_output_____ | MIT | deep_learning/07-deep-learning-from-scratch.ipynb | drakearch/kaggle-courses |
[](https://colab.sandbox.google.com/github/kornia/tutorials/blob/master/source/hello_world_tutorial.ipynb) Hello world: Planet KorniaWelcome to Planet Kornia: a set of tutorials to learn about **Computer Vision** in [PyTorch](https://pytorch.org)... | %%capture
!pip install kornia
import cv2
from matplotlib import pyplot as plt
import numpy as np
import torch
import torchvision
import kornia as K | _____no_output_____ | Apache-2.0 | source/hello_world_tutorial.ipynb | oskarflordal/tutorials |
Download first an image form internet to start to work. | %%capture
!wget https://github.com/kornia/data/raw/main/arturito.jpg | _____no_output_____ | Apache-2.0 | source/hello_world_tutorial.ipynb | oskarflordal/tutorials |
Load an image with OpenCVWe can use OpenCV to load an image. By default, OpenCV loads images in BGR format and casts to a `numpy.ndarray` with the data layout `(H,W,C)`. However, because matplotlib saves an image in RGB format, in OpenCV you need to change the BGR to RGB so that an image is displayed properly. | img_bgr: np.array = cv2.imread('arturito.jpg') # HxWxC / np.uint8
img_rgb: np.array = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
plt.imshow(img_rgb); plt.axis('off'); | _____no_output_____ | Apache-2.0 | source/hello_world_tutorial.ipynb | oskarflordal/tutorials |
Load an image with TorchvisionThe images can be also loaded using `torchvision` which directly returns the images in a `torch.Tensor` in the shape `(C,H,W)`. | x_rgb: torch.tensor = torchvision.io.read_image('arturito.jpg') # CxHxW / torch.uint8
x_rgb = x_rgb.unsqueeze(0) # BxCxHxW
print(x_rgb.shape) | torch.Size([1, 3, 144, 256])
| Apache-2.0 | source/hello_world_tutorial.ipynb | oskarflordal/tutorials |
Load an image with KorniaWith Kornia we can do all the preceding.We have a couple of utilities to cast the image to a `torch.Tensor` to make it compliant to the other Kornia components and arrange the data in `(B,C,H,W)`. The utility is [`kornia.image_to_tensor`](https://kornia.readthedocs.io/en/latest/utils.htmlkor... | x_bgr: torch.tensor = K.image_to_tensor(img_bgr) # CxHxW / torch.uint8
x_bgr = x_bgr.unsqueeze(0) # 1xCxHxW
print(f"convert from '{img_bgr.shape}' to '{x_bgr.shape}'") | convert from '(144, 256, 3)' to 'torch.Size([1, 3, 144, 256])'
| Apache-2.0 | source/hello_world_tutorial.ipynb | oskarflordal/tutorials |
We can convert from BGR to RGB with a [`kornia.color`](https://kornia.readthedocs.io/en/latest/color.html) component. | x_rgb: torch.tensor = K.color.bgr_to_rgb(x_bgr) # 1xCxHxW / torch.uint8 | _____no_output_____ | Apache-2.0 | source/hello_world_tutorial.ipynb | oskarflordal/tutorials |
Visualize an image with Matplotib We will use [Matplotlib](https://matplotlib.org/) for the visualisation inside the notebook. Matplotlib requires a `numpy.ndarray` in the `(H,W,C)` format, and for doing so we will go back with [`kornia.tensor_to_image`](https://kornia.readthedocs.io/en/latest/utils.htmlkornia.utils.i... | img_bgr: np.array = K.tensor_to_image(x_bgr)
img_rgb: np.array = K.tensor_to_image(x_rgb) | _____no_output_____ | Apache-2.0 | source/hello_world_tutorial.ipynb | oskarflordal/tutorials |
Create a subplot to visualize the original an a modified image | fig, axs = plt.subplots(1, 2, figsize=(32, 16))
axs = axs.ravel()
axs[0].axis('off')
axs[0].imshow(img_rgb)
axs[1].axis('off')
axs[1].imshow(img_bgr)
plt.show() | _____no_output_____ | Apache-2.0 | source/hello_world_tutorial.ipynb | oskarflordal/tutorials |
Data cleaning GoalIn this notebook, we will be taking in raw.csv and cleaning/parsing its different columns. The notebook contains the transformations below in order:1. Read in the data2. Removing unused columns for this analysis3. Removing rows with certain null columns4. Cleaning of columns * ad_age * ad_impre... | import pandas as pd
import numpy as np
import re
# We read in the data
ads_df = pd.read_csv('../raw_data/raw.csv')
# Output first 2 rows
ads_df.head(2) | _____no_output_____ | MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
Removing unused columnsOur first step will be to remove columns we will not be using for this analysis.| Column name | Reason for removal||-------------| ------------------|| Unnamed | Index column added by accident in the data production step. || ad_id | We will be using the file_name column as identifier. || ad_text... | # Columns we will not be using
columns_to_remove = ['Unnamed: 0', 'ad_id', 'ad_text', 'ad_landing_page', 'ad_targeting_location', 'ad_targeting_custom_audience', 'ad_targeting_excluded_connections', 'ad_targeting_language', 'ad_targeting_placements']
ads_df = ads_df.drop(columns=columns_to_remove)
ads_df.head(2) | _____no_output_____ | MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
Removing rows with null columnsWe will be removing rows with null for: ad_creation_date, ad_spend, ad_targeting_age, ad_impressions and ad_clicks. Our first step will be to create a dictionary which can keep track of the number of rows remaining after a given operation. We will be using this dictionary when summarizin... | # Dictionary to keep track of row removals
cleaning_summary_format = {'before_cleaning_count': len(ads_df)}
# Function to remove null rows for a given column
def remove_nulls(ads_df, column_name):
# np.where returns a tuple, we want the first member (the indexes of rows)
null_indexes = np.where(pd.isnull(ads_d... | Before cleaning our dataset had 3517 columns.
After removing rows with null creation dates: 3497 columns.
After removing rows with null ad spending: 3497 columns.
After removing rows with null ad targeting age: 3497 columns.
After removing rows with null ad impressions: 3497 columns.
After removing rows with null ad cl... | MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
Cleaning ad_ageFirst we look at the values for the field and whether we will be able to leverage them in our analysis. | ads_df.ad_targeting_age.value_counts().index | _____no_output_____ | MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
The initial parsing for this field was not perfect... Let's simplify this bucketing by removing gender information. To do so we crop the string at 8 characters. | # Crop the ad_targeting_age to 8 characters
ads_df.ad_targeting_age = ads_df.ad_targeting_age.apply(lambda s: s if len(s)<=8 else s[0:8])
# Count rows for the different values
count_table = ads_df.ad_targeting_age.value_counts().to_frame()
# Rename the column for clarity
count_table.columns = ['Ad count']
# Output t... | _____no_output_____ | MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
As per this table, almost all ads targeted voting age facebook users (18+). Bucketing the ads by age groups will not result in significant/interesting analysis. We drop the column. | ads_df = ads_df.drop(columns=['ad_targeting_age']) | _____no_output_____ | MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
Cleaning ad_impressions and ad_clicksBoth these columns are numerical and do not contain None and or NaN values. [The Oxford study](https://comprop.oii.ox.ac.uk/wp-content/uploads/sites/93/2018/12/IRA-Report.pdf), mention that ads without impressions or clicks where unlikely to have been shown to Facebook users.* We w... | # Parsing of string to integer
def format_string_to_integer(string):
# Removing dots and commas and semicolons
s = string.replace(',', '').replace('.', '').replace(';', '')
# Removing typos betwee o, O (lower, upper letter o) and 0 (zero digit)
s = s.replace('o', '0').replace('O', '0')
# A... | Before removing 0 ad_impressions or ad_clicks our dataset had 3497 columns.
After removing rows with 0 ad impressions: 2588 columns.
After removing rows with 0 ad clicks: 2450 columns.
| MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
Parsing creation date and end dateCreation date and end date are written in a complex format: 04/13/16 07:48:33 AM PDT. Our analysis only requires the date. In this section, we will extract the first 8 characters mm/dd/yy and convert them to a datetime object. We take a look at the entries: | ads_df['ad_creation_date'] | _____no_output_____ | MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
We find that sometimes the first few characters contain spaces. We write a regular expression for this and apply the removal of these white space as part of a function. We also need to complete the year to be 4 characters for later date parsing. | # We first compile our date extraction regex to improve performance
date_regex = re.compile(r'(?P<date>\d\s*\d\s*\/\s*\d\s*\d\s*\/\s*\d\s*\d)')
# Given a string beginning with mm/dd/yy we produce mm/dd/YYYY
# Function returns 'parse_error' on failure to parse and null if the
# input string was null
def extract_date_fr... | _____no_output_____ | MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
We apply the function to every row and create a new column: 'ad_creation_date_parsed' | ads_df['ad_creation_date_parsed'] = ads_df.ad_creation_date.apply(extract_date_from_string) | _____no_output_____ | MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
We check how many dates could not be parsed: | (ads_df['ad_creation_date_parsed'] == 'parse_error').sum() | _____no_output_____ | MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
Since only one date could not be parsed we validate its value: | row = ads_df[ads_df['ad_creation_date_parsed'] == 'parse_error']
row | _____no_output_____ | MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
In this case the date should be 02/21/2017. An l was mistaken to a 1. We replace it manually. | ads_df.loc[row.index, 'ad_creation_date_parsed'] = '02/21/2017'
ads_df.loc[row.index] | _____no_output_____ | MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
Now that all dates have been parsed, we replace the original column with the parsed one and remove the temporary parsed column. Since no columns were lost in the process we will not be adding an entry to the summary. | # Replace original column with parsed
ads_df['ad_creation_date'] = ads_df['ad_creation_date_parsed']
# Drop temporary parsed column
ads_df = ads_df.drop(columns=['ad_creation_date_parsed']) | _____no_output_____ | MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
We now execute the same steps for the end date. | ads_df['ad_end_date_parsed'] = ads_df.ad_end_date.apply(extract_date_from_string) | _____no_output_____ | MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
We check how many dates could not be parsed: | (ads_df['ad_end_date_parsed'] == 'parse_error').sum()
ads_df['ad_end_date'] = ads_df['ad_end_date_parsed']
ads_df = ads_df.drop(columns=['ad_end_date_parsed']) | _____no_output_____ | MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
Now that both ad_start_date and ad_end_date are properly parsed strings, we can apply a pandas function to transform them into datetime objects. This will make date handling easier during our analysis. | ads_df.ad_creation_date = ads_df.ad_creation_date.apply(lambda date_string : pd.to_datetime(date_string, format='%m/%d/%Y'))
ads_df.ad_end_date = ads_df.ad_end_date.apply(lambda date_string : pd.to_datetime(date_string, format='%m/%d/%Y'))
# Output first 3 rows
ads_df.head(3) | _____no_output_____ | MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
Parsing ad_spendSometimes the ad_spend field contains spaces, dots instead of commas to seperate thousands and the 'RUB' currency shorthand. We use a regular expression to extract the amount of the ad_spend field. We then convert the string to a float. | ads_df['ad_spend']
# Pre compile regex for performance
amount_regex = re.compile(r'(?P<amount>([0-9]{1,3}(\.|,)?)+(\.|,)?[0-9]{2})')
# Function returns 'parse_error' on failure to parse and null if the
# input string was null or the string 'None'
def extract_amount_from_string(string):
matches = None
amount = ... | _____no_output_____ | MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
We run the function over our dataset and output the number of parsing errors we've encountered. | ads_df['ad_spend_parsed'] = ads_df.ad_spend.apply(extract_amount_from_string)
(ads_df['ad_spend_parsed'] == 'parse_error').sum() | _____no_output_____ | MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
We validate nan values and remove them from the dataset. | cleaning_summary_format['none_ad_spend_count'] = (~pd.isnull(ads_df['ad_spend_parsed'])).sum()
print('There are a total of ' + str(pd.isnull(ads_df['ad_spend_parsed']).sum()) + ' nan values.')
ads_df[pd.isnull(ads_df['ad_spend_parsed'])]
# Remove nulls
ads_df = ads_df[~pd.isnull(ads_df['ad_spend_parsed'])]
# Replace a... | _____no_output_____ | MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
We transform the ad_spend field from string into a float. | ads_df['ad_spend'] = ads_df['ad_spend'].astype(float) | _____no_output_____ | MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
We validate that all values are positive and remove other values after validation. | print('There are ' + str((ads_df['ad_spend'] > 0).sum()) + ' positive values and a total of ' + str(len(ads_df)) + ' entries.')
cleaning_summary_format['non_positive_ad_spend_count'] = (ads_df['ad_spend'] > 0).sum()
ads_df[ads_df['ad_spend'] <= 0] | _____no_output_____ | MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
We remove the two entries with values equal to zero and print out the summary. | ads_df = ads_df[ads_df['ad_spend'] > 0]
cleaning_summary_format['before_ad_spend_count'] = cleaning_summary_format['zeros_ad_clicks_count']
# Reporting
print('''Before formating ad_spend our dataset had {before_ad_spend_count} columns.
After removing rows with 'None': {none_ad_spend_count} columns.
After removing row... | Before formating ad_spend our dataset had 2450 columns.
After removing rows with 'None': 2442 columns.
After removing rows with 0 ad clicks: 2440 columns.
| MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
Parsing ad_targeting_interests & ad_targeting_people_who_matchThe ad_targeting_interests column is split between its own column and a portion of the ad_targeting_people_who_match column's string. To make treatment of this column simpler, our first step will be to extract the 'interest' portion of ad_targeting_people_w... | count_null = 0
count_interests = 0
count_other = 0
for s in ads_df['ad_targeting_people_who_match']:
if pd.isnull(s):
count_null += 1
elif 'Interests' in s:
count_interests += 1
else:
count_other +=1
print(s)
print('Null:' + str(count_null) +
' Interests: ' + str(count_... | Null:822 Interests: 1243 Other: 375 Total: 2440
| MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
From this print out, we see that although some rows belonging to the "Other" category have the 'interests' field missing, we can grab a proxy by taking the "like" groups. We can grab the value of the "like" groups correctly by taking the string after 'Friends of people who are connected to'. We've created the function ... | # Utility function to crop everything after a given word
def crop_everything_after(string, contains):
return string[:string.index(contains)] if contains in string else string
# Returns a string containing everything after 'Friends of people who are connected to '
def treat_string_with_friends(string):
friends_... | _____no_output_____ | MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
During this operation we lost a few rows that could not be parsed as it did not contain interests. | cleaning_summary_format['null_people_who_match_count'] = pd.isnull(ads_df['ad_targeting_people_who_match']).sum() - count_null
print(str(cleaning_summary_format['null_people_who_match_count']) + ' rows where lost.') | 29 rows where lost.
| MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
The last cleaning step for this field is to remove the 'Interests' keyword which is sometimes followed by a colon. We use a regular expression to replace this string. | interests_regex = re.compile(r'Interests\s*:?')
def remove_interests_marker(string):
if not pd.isnull(string):
string = interests_regex.sub('', string)
return string
ads_df['ad_targeting_people_who_match'] = ads_df['ad_targeting_people_who_match'].apply(remove_interests_marker)
ads_df.head(3) | _____no_output_____ | MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
We now do the same exercise with ad_targeting_interests. We first identify non-null rows that may contain an extra field. We do so by looking for the ':' character and printing out these rows. | non_null_interests = ads_df[~pd.isnull(ads_df['ad_targeting_interests'])]['ad_targeting_interests']
for row_with_colon in non_null_interests[non_null_interests.str.contains(':')]:
print(row_with_colon) | BlackNews.com or HuffPost Black Voices Behaviors: African American (US)
BlackNews.com or HuffPost Black Voices Behaviors: African American (US)
Humanitarianism, Human rights or Humanitarian aid Behaviors: African American (US)
Black Power Behaviors: Multicultural Affinity: African American (US)
Human rights or Malcolm ... | MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
Most of these rows seem to contain an additional field "Behaviors" we will remove it from the rows as we can easily use the interest part to identify the targeted demographic. | # Removes additional section part of the ad_targeting_interests string
def treat_interest(string):
if not pd.isnull(string):
# Strings identified by visual inspections of entries
crop_after = [
'And Must Also Match',
'School:',
'Behaviors:',
'expansion... | After treatment, there are 0 rows with more than one field.
| MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
Now that both ad_targeting_interests and ad_targeting_people_who_match have been cleaned, we can now merge the two columns into one. First let's verify that there are no rows where both columns are non-null or both null. | def interests_both_null(row):
return (pd.isnull(row.ad_targeting_interests) and pd.isnull(row.ad_targeting_people_who_match))
def interests_both_non_null(row):
return (not pd.isnull(row.ad_targeting_interests) and not pd.isnull(row.ad_targeting_people_who_match))
# How many rows have both columns as null ... | We have a total of 214 rows with both columns null and a total of 0 rows which have both values set.
| MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
We drop rows that do not contain interests information in both columns. We will merge the other rows by replacing the values of ad_targeting_interests with ad_targeting_people_who_match. | def merge_interests(row):
return row.ad_targeting_interests if not pd.isnull(row.ad_targeting_interests) else row.ad_targeting_people_who_match
# Merge interests
ads_df['ad_targeting_interests'] = ads_df.apply(merge_interests, axis=1)
# Drop 'ad_targeting_people_who_match'
ads_df = ads_df.drop(columns=['ad_target... | _____no_output_____ | MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
Writing to file | ads_df.head(3)
ads_df.to_csv('../clean_data/clean_data.csv', index=None, header=True) | _____no_output_____ | MIT | src/data_cleaning.ipynb | ALotOfData/data-512-a5 |
Initialize the framework Import torch libraries and try to use the GPU device (if available) | import torch
from torch import nn
import random
# Try to use GPU device
device = "cuda" if torch.cuda.is_available() else "cpu"
print("Using %s device" %(device)) | Using cpu device
| MIT | Lyrics_generator.ipynb | NLP-Lyrics-Team/nlp-lyrics |
Mount Google Drive to load* the lyrics dataset,* the word2vec pretrained embedding dictionaries,* the one hot encoding dictionary for the genres,* the lyrics generator neural network | from google.colab import drive
drive.mount("/content/drive") | Mounted at /content/drive
| MIT | Lyrics_generator.ipynb | NLP-Lyrics-Team/nlp-lyrics |
Load the dictionaries to convert words to indices and viceversa | #import pickle
import json
FILENAME_W2I = '/content/drive/MyDrive/DM project - NLP lyrics generation/Dictionaries/words2indices'
FILENAME_I2W = '/content/drive/MyDrive/DM project - NLP lyrics generation/Dictionaries/indices2words'
# Load a dictionary from a stored file converting keys to integers if needed
def load_d... | _____no_output_____ | MIT | Lyrics_generator.ipynb | NLP-Lyrics-Team/nlp-lyrics |
Load the word vectors tensor (word2vec embedding) | FILENAME = '/content/drive/MyDrive/DM project - NLP lyrics generation/Dictionaries/word_vectors.pt'
word_vectors = torch.load(FILENAME, map_location=device) | _____no_output_____ | MIT | Lyrics_generator.ipynb | NLP-Lyrics-Team/nlp-lyrics |
Load the one hot encoding dictionary for the genres | FILENAME = '/content/drive/MyDrive/DM project - NLP lyrics generation/Dictionaries/one_hot_encoding_genres'
one_hot_encoding_genres = load_dictionary(FILENAME)
NUMBER_GENRES = len(one_hot_encoding_genres) | _____no_output_____ | MIT | Lyrics_generator.ipynb | NLP-Lyrics-Team/nlp-lyrics |
Define vocabulary functions | # Get word from index
def get_word_from_index(idx):
# Use get to automatically return None if the index is not present in the dictionary
return indices2words.get(idx)
# Get index from word
def get_index_from_word(word):
# Use get to automatically return None if the word is not present in the dictionary
return ... | _____no_output_____ | MIT | Lyrics_generator.ipynb | NLP-Lyrics-Team/nlp-lyrics |
Define the generator neural network | class Generator(nn.Module):
def __init__(
self,
word_vectors: torch.Tensor,
lstm_hidden_size: int,
dense_size: int,
vocab_size: int
):
super().__init__()
# Embedding layer
self.embedding = torch.nn.Embedding.from_pretrained(word_vectors)
# Recurrent layer (LS... | _____no_output_____ | MIT | Lyrics_generator.ipynb | NLP-Lyrics-Team/nlp-lyrics |
Load the generator model | PATH = '/content/drive/MyDrive/DM project - NLP lyrics generation/Models/generator_model.pt'
#PATH = '/content/drive/MyDrive/DM project - NLP lyrics generation/generator_model_GAN.pt'
gen = Generator(
word_vectors,
lstm_hidden_size=256,
dense_size=256+NUMBER_GENRES,
vocab_size=len(word_vectors))
check... | _____no_output_____ | MIT | Lyrics_generator.ipynb | NLP-Lyrics-Team/nlp-lyrics |
User input Sort genres | genres = [key for key in one_hot_encoding_genres]
genres.sort() | _____no_output_____ | MIT | Lyrics_generator.ipynb | NLP-Lyrics-Team/nlp-lyrics |
Display input form | from ipywidgets import Layout, Box, Label, Dropdown, Text
print("Enter a word and a genre to generate a lyrics\n")
form_item_layout = Layout(
display='flex',
flex_flow='row',
justify_content='space-between'
)
word_widget = Text()
genres_widget = Dropdown(options=genres)
form_items = [
Box([Label(va... | Enter a word and a genre to generate a lyrics
| MIT | Lyrics_generator.ipynb | NLP-Lyrics-Team/nlp-lyrics |
Get user input | word = word_widget.value
genre = genres_widget.value
##@title # Insert a word and a genre to generate a lyrics
#word = "" #@param {type:"string", required: true}
#genre = "Country" #@param ["Country", "Electronic", "Folk", "Hip-Hop", "Indie", "Jazz", "Metal", "Pop", "Rock", "R&B"] | _____no_output_____ | MIT | Lyrics_generator.ipynb | NLP-Lyrics-Team/nlp-lyrics |
Preprocess the user input | # Split entered words on whitespaces to support also sequences of words
input_words = word.strip().split()
if not input_words:
raise ValueError("No word entered")
# Check if every input word is present in the vocabulary (or in lowercase form)
for word in input_words:
if word not in words2indices and word.lower() ... | _____no_output_____ | MIT | Lyrics_generator.ipynb | NLP-Lyrics-Team/nlp-lyrics |
Generate the lyrics | TEXT_LENGTH = 100 # Truncate the text when the goal text length has been generated (hard truncation)
LINES = random.randrange(10, 50) # Truncate the text when the goal lines number has been generated (soft truncation)
states = None
text = ""
prev_word = ""
lines = 0
generated_words = 0
word2c... | Word: ['saturday']
Genre: Rock
lines: 27
generated words: 233
Lyrics:
Saturday night
In the midnight room for the street
She walked dressed to themselves
You should have took her away, in a call as she cried for me
I was given to: about your mom. Punisher's bad news
You living why a girl I told you before
Don't you t... | MIT | Lyrics_generator.ipynb | NLP-Lyrics-Team/nlp-lyrics |
core> This is module which provide core utilities | #hide
from nbdev.showdoc import *
#export
def say_hello():
return "Hello From Learnathon Module"
#export
def say_hello2():
return "This is a test for new function" | _____no_output_____ | Apache-2.0 | 00_core.ipynb | Rahuketu86/Learnathon |
SMA Percent Band 1. The SPY closes above its upper band, buy 2. If the SPY closes below its lower band, sell your long position. Optimize: sma, percent band. | import datetime
import matplotlib.pyplot as plt
import pandas as pd
from talib.abstract import *
import pinkfish as pf
import strategy
# Format price data
pd.options.display.float_format = '{:0.2f}'.format
%matplotlib inline
# Set size of inline plots
'''note: rcParams can't be in same cell as import matplotlib
... | _____no_output_____ | MIT | examples/090.sma-percent-band/optimize.ipynb | alialamiidrissi/pinkfish |
Some global data | symbol = '^GSPC'
#symbol = 'SPY'
#symbol = 'ES=F'
#symbol = 'DIA'
#symbol = 'QQQ'
#symbol = 'IWM'
#symbol = 'TLT'
#symbol = 'GLD'
#symbol = 'AAPL'
#symbol = 'BBRY'
#symbol = 'GDX'
capital = 10000
start = datetime.datetime(1900, 1, 1)
#start = datetime.datetime(*pf.SP500_BEGIN)
end = datetime.datetime.now() | _____no_output_____ | MIT | examples/090.sma-percent-band/optimize.ipynb | alialamiidrissi/pinkfish |
Define Optimizations | # pick one
optimize_sma = True
optimize_band = False
# define SMAs ranges
if optimize_sma:
Xs = range(50, 525, 25)
Xs = [str(X) for X in Xs]
# define band ranges
elif optimize_band:
Xs = range(0, 100, 5)
Xs = [str(X) for X in Xs]
options = {
'use_adj' : True,
'use_cache' : True,
'sma' : 2... | _____no_output_____ | MIT | examples/090.sma-percent-band/optimize.ipynb | alialamiidrissi/pinkfish |
Run Strategy | strategies = pd.Series(dtype=object)
for X in Xs:
print(X, end=" ")
if optimize_sma:
options['sma'] = int(X)
elif optimize_band:
options['band'] = int(X)/10
strategies[X] = strategy.Strategy(symbol, capital, start, end, options)
strategies[X].run() | 50 75 100 125 150 175 200 225 250 275 300 325 350 375 400 425 450 475 500 | MIT | examples/090.sma-percent-band/optimize.ipynb | alialamiidrissi/pinkfish |
Summarize results | metrics = ('annual_return_rate',
'max_closed_out_drawdown',
'annualized_return_over_max_drawdown',
'drawdown_recovery_period',
'expected_shortfall',
'best_month',
'worst_month',
'sharpe_ratio',
'sortino_ratio',
'monthly_s... | _____no_output_____ | MIT | examples/090.sma-percent-band/optimize.ipynb | alialamiidrissi/pinkfish |
Bar graphs | pf.optimizer_plot_bar_graph(df, 'annual_return_rate')
pf.optimizer_plot_bar_graph(df, 'sharpe_ratio')
pf.optimizer_plot_bar_graph(df, 'max_closed_out_drawdown') | _____no_output_____ | MIT | examples/090.sma-percent-band/optimize.ipynb | alialamiidrissi/pinkfish |
Run Benchmark | s = strategies[Xs[0]]
benchmark = pf.Benchmark(symbol, capital, s.start, s.end)
benchmark.run() | _____no_output_____ | MIT | examples/090.sma-percent-band/optimize.ipynb | alialamiidrissi/pinkfish |
Equity curve | if optimize_sma : Y = '200'
elif optimize_band: Y = '30'
pf.plot_equity_curve(strategies[Y].dbal, benchmark=benchmark.dbal) | _____no_output_____ | MIT | examples/090.sma-percent-band/optimize.ipynb | alialamiidrissi/pinkfish |
sklearn-porterRepository: [https://github.com/nok/sklearn-porter](https://github.com/nok/sklearn-porter) MLPClassifierDocumentation: [sklearn.neural_network.MLPClassifier](http://scikit-learn.org/stable/modules/generated/sklearn.neural_network.MLPClassifier.html) | import sys
sys.path.append('../../../../..') | _____no_output_____ | MIT | examples/estimator/classifier/MLPClassifier/js/basics_imported.pct.ipynb | karoka/sklearn-porter |
Load data | from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
iris_data = load_iris()
X = iris_data.data
y = iris_data.target
X = shuffle(X, random_state=0)
y = shuffle(y, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(
X, y, te... | ((90, 4), (90,))
((60, 4), (60,))
| MIT | examples/estimator/classifier/MLPClassifier/js/basics_imported.pct.ipynb | karoka/sklearn-porter |
Train classifier | from sklearn.neural_network import MLPClassifier
clf = MLPClassifier(activation='relu', hidden_layer_sizes=50,
max_iter=500, alpha=1e-4, solver='sgd',
tol=1e-4, random_state=1, learning_rate_init=.1)
clf.fit(X_train, y_train) | _____no_output_____ | MIT | examples/estimator/classifier/MLPClassifier/js/basics_imported.pct.ipynb | karoka/sklearn-porter |
Transpile classifier | from sklearn_porter import Porter
porter = Porter(clf, language='js')
output = porter.export(export_data=True)
print(output) | if (typeof XMLHttpRequest === 'undefined') {
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
}
var MLPClassifier = function(jsonFile) {
this.mdl = undefined;
var promise = new Promise(function(resolve, reject) {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystat... | MIT | examples/estimator/classifier/MLPClassifier/js/basics_imported.pct.ipynb | karoka/sklearn-porter |
Run classification in JavaScript | # Save classifier:
# with open('MLPClassifier.js', 'w') as f:
# f.write(output)
# Check model data:
# $ cat data.json
# Run classification:
# if hash node 2/dev/null; then
# python -m SimpleHTTPServer 8877 & serve_pid=$!
# node MLPClassifier.js http://127.0.0.1:8877/data.json 1 2 3 4
# kill $serve_pid... | _____no_output_____ | MIT | examples/estimator/classifier/MLPClassifier/js/basics_imported.pct.ipynb | karoka/sklearn-porter |
Core> Basic functions used in the fastai library | # export
defaults = SimpleNamespace() | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
Metaclasses | #export
class PrePostInitMeta(type):
"A metaclass that calls optional `__pre_init__` and `__post_init__` methods"
def __new__(cls, name, bases, dct):
x = super().__new__(cls, name, bases, dct)
def _pass(self, *args,**kwargs): pass
for o in ('__init__', '__pre_init__', '__post_init__'):
... | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
Foundational functions Decorators | #export
def patch_to(cls, as_prop=False):
"Decorator: add `f` to `cls`"
def _inner(f):
nf = copy(f)
# `functools.update_wrapper` when passing patched function to `Pipeline`, so we do it manually
for o in functools.WRAPPER_ASSIGNMENTS: setattr(nf, o, getattr(f,o))
nf.__qualname__ ... | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
Type checking Runtime type checking is handy, so let's make it easy! | #export core
#NB: Please don't move this to a different line or module, since it's used in testing `get_source_link`
def chk(f): return typechecked(always=True)(f) | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
Decorator for a function to check that type-annotated arguments receive arguments of the right type. | @chk
def test_chk(a:int=1): return a
test_eq(test_chk(2), 2)
test_eq(test_chk(), 1)
test_fail(lambda: test_chk('a'), contains='"a" must be int') | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
Decorated functions will pickle correctly. | t = pickle.loads(pickle.dumps(test_chk))
test_eq(t(2), 2)
test_eq(t(), 1) | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
Context managers | @contextmanager
def working_directory(path):
"Change working directory to `path` and return to previous on exit."
prev_cwd = Path.cwd()
os.chdir(path)
try: yield
finally: os.chdir(prev_cwd) | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
Monkey-patching | def is_listy(x): return isinstance(x,(list,tuple,Generator))
#export
def tensor(x, *rest, **kwargs):
"Like `torch.as_tensor`, but handle lists too, and can pass multiple vector elements directly."
if len(rest): x = (x,)+rest
# Pytorch bug in dataloader using num_workers>0
if isinstance(x, (tuple,list)) ... | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
`Tensor.ndim` We add an `ndim` property to `Tensor` with same semantics as [numpy ndim](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.ndim.html), which allows tensors to be used in matplotlib and other places that assume this property exists. | test_eq(torch.tensor([1,2]).ndim,1)
test_eq(torch.tensor(1).ndim,0)
test_eq(torch.tensor([[1]]).ndim,2) | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
Documentation functions | #export core
def add_docs(cls, cls_doc=None, **docs):
"Copy values from `docs` to `cls` docstrings, and confirm all public methods are documented"
if cls_doc is not None: cls.__doc__ = cls_doc
for k,v in docs.items():
f = getattr(cls,k)
if hasattr(f,'__func__'): f = f.__func__ # required for... | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
GetAttr - | #export
class GetAttr(BaseObj):
"Inherit from this to have all attr accesses in `self._xtra` passed down to `self.default`"
@property
def _xtra(self): return [o for o in dir(self.default) if not o.startswith('_')]
def __getattr__(self,k):
if k in self._xtra: return getattr(self.default, k)
... | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
L - | # export
def coll_repr(c, max_n=10):
"String repr of up to `max_n` items of (possibly lazy) collection `c`"
return f'(#{len(c)}) [' + ','.join(itertools.islice(map(str,c), max_n)) + ('...'
if len(c)>10 else '') + ']'
test_eq(coll_repr(range(1000), 5), '(#1000) [0,1,2,3,4...]')
# export
def mask2idxs... | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
You can create an `L` from an existing iterable (e.g. a list, range, etc) and access or modify it with an int list/tuple index, mask, int, or slice. All `list` methods can also be used with `L`. | t = L(range(12))
test_eq(t, list(range(12)))
test_ne(t, list(range(11)))
t.reverse()
test_eq(t[0], 11)
t[3] = "h"
test_eq(t[3], "h")
t[3,5] = ("j","k")
test_eq(t[3,5], ["j","k"])
test_eq(t, L(t))
t | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
There are optimized indexers for arrays, tensors, and DataFrames. | arr = np.arange(9).reshape(3,3)
t = L(arr, use_list=None)
test_eq(t[1,2], arr[[1,2]])
arr = torch.arange(9).view(3,3)
t = L(arr, use_list=None)
test_eq(t[1,2], arr[[1,2]])
df = pd.DataFrame({'a':[1,2,3]})
t = L(df, use_list=None)
test_eq(t[1,2], L(pd.DataFrame({'a':[2,3]}), use_list=None)) | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
You can also modify an `L` with `append`, `+`, and `*`. | t = L()
test_eq(t, [])
t.append(1)
test_eq(t, [1])
t += [3,2]
test_eq(t, [1,3,2])
t = t + [4]
test_eq(t, [1,3,2,4])
t = 5 + t
test_eq(t, [5,1,3,2,4])
test_eq(L(1,2,3), [1,2,3])
test_eq(L(1,2,3), L(1,2,3))
t = L(1)*5
t = t.mapped(operator.neg)
test_eq(t,[-1]*5)
test_eq(~L([True,False,False]), L([False,True,True]))
t = L... | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
An `L` can be constructed from anything iterable, although tensors and arrays will not be iterated over on construction, unless you pass `use_list` to the constructor. | test_eq(L([1,2,3]),[1,2,3])
test_eq(L(L([1,2,3])),[1,2,3])
test_ne(L([1,2,3]),[1,2,])
test_eq(L('abc'),['abc'])
test_eq(L(range(0,3)),[0,1,2])
test_eq(L(o for o in range(0,3)),[0,1,2])
test_eq(L(tensor(0)),[tensor(0)])
test_eq(L([tensor(0),tensor(1)]),[tensor(0),tensor(1)])
test_eq(L(tensor([0.,1.1]))[0],tensor([0.,1.1... | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
If `match` is not `None` then the created list is same len as `match`, either by:- If `len(items)==1` then `items` is replicated,- Otherwise an error is raised if `match` and `items` are not already the same size. | test_eq(L(1,match=[1,2,3]),[1,1,1])
test_eq(L([1,2],match=[2,3]),[1,2])
test_fail(lambda: L([1,2],match=[1,2,3])) | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
If you create an `L` from an existing `L` then you'll get back the original object (since `L` uses the `NewChkMeta` metaclass). | test_is(L(t), t) | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
Methods | show_doc(L.__getitem__)
t = L(range(12))
test_eq(t[1,2], [1,2]) # implicit tuple
test_eq(t[[1,2]], [1,2]) # list
test_eq(t[:3], [0,1,2]) # slice
test_eq(t[[False]*11 + [True]], [11]) # mask
test_eq(t[tensor(3)], 3)
show_doc(L.__setitem__)
t[4,6] = 0
test_eq(t[4,6], [0,0])
t[4,6... | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
There are shortcuts for `torch.stack` and `torch.cat` if your `L` contains tensors or something convertible. You can manually convert with `tensored`. | t = L(([1,2],[3,4]))
test_eq(t.tensored(), [tensor(1,2),tensor(3,4)])
show_doc(L.stack)
test_eq(t.stack(), tensor([[1,2],[3,4]]))
show_doc(L.cat)
test_eq(t.cat(), tensor([1,2,3,4])) | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
Utility functions Basics | # export
def ifnone(a, b):
"`b` if `a` is None else `a`"
return b if a is None else a | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
Since `b if a is None else a` is such a common pattern, we wrap it in a function. However, be careful, because python will evaluate *both* `a` and `b` when calling `ifnone` (which it doesn't do if using the `if` version directly). | test_eq(ifnone(None,1), 1)
test_eq(ifnone(2 ,1), 2)
#export
def get_class(nm, *fld_names, sup=None, doc=None, funcs=None, **flds):
"Dynamically create a class, optionally inheriting from `sup`, containing `fld_names`"
attrs = {}
for f in fld_names: attrs[f] = None
for f in L(funcs): attrs[f.__name__] ... | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
Most often you'll want to call `mk_class`, since it adds the class to your module. See `mk_class` for more details and examples of use (which also apply to `get_class`). | #export
def mk_class(nm, *fld_names, sup=None, doc=None, funcs=None, mod=None, **flds):
"Create a class using `get_class` and add to the caller's module"
if mod is None: mod = inspect.currentframe().f_back.f_locals
res = get_class(nm, *fld_names, sup=sup, doc=doc, funcs=funcs, **flds)
mod[nm] = res | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
Any `kwargs` will be added as class attributes, and `sup` is an optional (tuple of) base classes. | mk_class('_t', a=1, sup=GetAttr)
t = _t()
test_eq(t.a, 1)
assert(isinstance(t,GetAttr)) | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
A `__init__` is provided that sets attrs for any `kwargs`, and for any `args` (matching by position to fields), along with a `__repr__` which prints all attrs. The docstring is set to `doc`. You can pass `funcs` which will be added as attrs with the function names. | def foo(self): return 1
mk_class('_t', 'a', sup=GetAttr, doc='test doc', funcs=foo)
t = _t(3, b=2)
test_eq(t.a, 3)
test_eq(t.b, 2)
test_eq(t.foo(), 1)
test_eq(t.__doc__, 'test doc')
t
#export
def wrap_class(nm, *fld_names, sup=None, doc=None, funcs=None, **flds):
"Decorator: makes function a method of a new class ... | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
Subclassing `Tensor` | #export
class TensorBase(Tensor, metaclass=BypassNewMeta):
def _new_meta(self, *args, **kwargs): return tensor(self)
#export
def _patch_tb():
def get_f(fn):
def _f(self, *args, **kwargs):
cls = self.__class__
res = getattr(super(TensorBase, self), fn)(*args, **kwargs)
... | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
Collection functions | #export
def tuplify(o, use_list=False, match=None):
"Make `o` a tuple"
return tuple(L(o, use_list=use_list, match=match))
test_eq(tuplify(None),())
test_eq(tuplify([1,2,3]),(1,2,3))
test_eq(tuplify(1,match=[1,2,3]),(1,1,1))
#export
def replicate(item,match):
"Create tuple of `item` copied `len(match)` times... | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
The following functions are provided matching the behavior of the equivalent versions in `operator`: - *lt gt le ge eq ne add sub mul truediv* | lt(3,5),gt(3,5) | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
However, they also have additional functionality: if you only pass one param, they return a partial function that passes that param as the second positional parameter. | lt(5)(3),gt(5)(3)
#export
class _InfMeta(type):
@property
def count(self): return itertools.count()
@property
def zeros(self): return itertools.cycle([0])
@property
def ones(self): return itertools.cycle([1])
@property
def nones(self): return itertools.cycle([None])
#export
class Inf(me... | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
`Inf` defines the following properties: - `count: itertools.count()`- `zeros: itertools.cycle([0])`- `ones : itertools.cycle([1])`- `nones: itertools.cycle([None])` | test_eq([o for i,o in zip(range(5), Inf.count)],
[0, 1, 2, 3, 4])
test_eq([o for i,o in zip(range(5), Inf.zeros)],
[0, 0, 0, 0, 0])
#export
def true(*args, **kwargs):
"Predicate: always `True`"
return True
#export
def stop(e=StopIteration):
"Raises exception `e` (by default `StopException`)... | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
Chunks - | #export
class Chunks:
"Slice and int indexing into a list of lists"
def __init__(self, chunks, lens=None):
self.chunks = chunks
self.lens = L(map(len,self.chunks) if lens is None else lens)
self.cumlens = np.cumsum(0+self.lens)
self.totlen = self.cumlens[-1]
def __getitem__(... | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
Functions on functions | #export
def trace(f):
"Add `set_trace` to an existing function `f`"
def _inner(*args,**kwargs):
set_trace()
return f(*args,**kwargs)
return _inner
# export
def compose(*funcs, order=None):
"Create a function that composes all functions in `funcs`, passing along remaining `*args` and `**k... | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.