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 |
|---|---|---|---|---|---|
Create train/test split | x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=.33, random_state=42)
print("%d training samples" % x_train.shape[0])
print("%d test samples" % x_test.shape[0]) | 30021 training samples
14787 test samples
| BSD-3-Clause | examples/02_advanced_usage.ipynb | gavehan/openTSNE |
Create a t-SNE embeddingLike in the *simple_usage* notebook, we will run the standard t-SNE optimization.This example shows the standard t-SNE optimization. Much can be done in order to better preserve global structure and improve embedding quality. Please refer to the *preserving_global_structure* notebook for some e... | %%time
affinities_train = affinity.PerplexityBasedNN(
x_train,
perplexity=30,
metric="euclidean",
n_jobs=8,
random_state=42,
verbose=True,
) | ===> Finding 90 nearest neighbors using Annoy approximate search using euclidean distance...
--> Time elapsed: 3.78 seconds
===> Calculating affinity matrix...
--> Time elapsed: 0.43 seconds
CPU times: user 19.3 s, sys: 794 ms, total: 20.1 s
Wall time: 4.22 s
| BSD-3-Clause | examples/02_advanced_usage.ipynb | gavehan/openTSNE |
**2. Generate initial coordinates for our embedding** | %time init_train = initialization.pca(x_train, random_state=42) | CPU times: user 448 ms, sys: 88.3 ms, total: 536 ms
Wall time: 86.9 ms
| BSD-3-Clause | examples/02_advanced_usage.ipynb | gavehan/openTSNE |
**3. Construct the `TSNEEmbedding` object** | embedding_train = TSNEEmbedding(
init_train,
affinities_train,
negative_gradient_method="fft",
n_jobs=8,
verbose=True,
) | _____no_output_____ | BSD-3-Clause | examples/02_advanced_usage.ipynb | gavehan/openTSNE |
**4. Optimize embedding** 1. Early exaggeration phase | %time embedding_train_1 = embedding_train.optimize(n_iter=250, exaggeration=12, momentum=0.5)
utils.plot(embedding_train_1, y_train, colors=utils.MACOSKO_COLORS) | _____no_output_____ | BSD-3-Clause | examples/02_advanced_usage.ipynb | gavehan/openTSNE |
2. Regular optimization | %time embedding_train_2 = embedding_train_1.optimize(n_iter=500, momentum=0.8)
utils.plot(embedding_train_2, y_train, colors=utils.MACOSKO_COLORS) | _____no_output_____ | BSD-3-Clause | examples/02_advanced_usage.ipynb | gavehan/openTSNE |
Transform | %%time
embedding_test = embedding_train_2.prepare_partial(
x_test,
initialization="median",
k=25,
perplexity=5,
)
utils.plot(embedding_test, y_test, colors=utils.MACOSKO_COLORS)
%time embedding_test_1 = embedding_test.optimize(n_iter=250, learning_rate=0.1, momentum=0.8)
utils.plot(embedding_test_1, y_t... | _____no_output_____ | BSD-3-Clause | examples/02_advanced_usage.ipynb | gavehan/openTSNE |
TogetherWe superimpose the transformed points onto the original embedding with larger opacity. | fig, ax = plt.subplots(figsize=(8, 8))
utils.plot(embedding_train_2, y_train, colors=utils.MACOSKO_COLORS, alpha=0.25, ax=ax)
utils.plot(embedding_test_1, y_test, colors=utils.MACOSKO_COLORS, alpha=0.75, ax=ax) | _____no_output_____ | BSD-3-Clause | examples/02_advanced_usage.ipynb | gavehan/openTSNE |
Practice: BiLSTM for PoS Tagging*This notebook is based on [open-source implementation](https://github.com/bentrevett/pytorch-pos-tagging) of PoS Tagging in PyTorch.* IntroductionIn this series we'll be building a machine learning model that produces an output for every element in an input sequence, using PyTorch and ... | import torch
import torch.nn as nn
import torch.optim as optim
from torchtext.legacy import data
from torchtext.legacy import datasets
import spacy
import numpy as np
import time
import random | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
Next, we'll set the random seeds for reproducability. | SEED = 1234
random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
torch.backends.cudnn.deterministic = True | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
One of the key parts of TorchText is the `Field`. The `Field` handles how your dataset is processed.Our `TEXT` field handles how the text that we need to tag is dealt with. All we do here is set `lower = True` which lowercases all of the text.Next we'll define the `Fields` for the tags. This dataset actually has two di... | TEXT = data.Field(lower = True)
UD_TAGS = data.Field(unk_token = None)
PTB_TAGS = data.Field(unk_token = None) | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
We then define `fields`, which handles passing our fields to the dataset.Note that order matters, if you only wanted to load the PTB tags your field would be:```fields = (("text", TEXT), (None, None), ("ptbtags", PTB_TAGS))```Where `None` tells TorchText to not load those tags. | fields = (("text", TEXT), ("udtags", UD_TAGS), ("ptbtags", PTB_TAGS)) | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
Next, we load the UDPOS dataset using our defined fields. | train_data, valid_data, test_data = datasets.UDPOS.splits(fields) | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
We can check how many examples are in each section of the dataset by checking their length. | print(f"Number of training examples: {len(train_data)}")
print(f"Number of validation examples: {len(valid_data)}")
print(f"Number of testing examples: {len(test_data)}") | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
Let's print out an example: | print(vars(train_data.examples[0])) | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
We can also view the text and tags separately: | print(vars(train_data.examples[0])['text'])
print(vars(train_data.examples[0])['udtags'])
print(vars(train_data.examples[0])['ptbtags']) | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
Next, we'll build the vocabulary - a mapping of tokens to integers. We want some unknown tokens within our dataset in order to replicate how this model would be used in real life, so we set the `min_freq` to 2 which means only tokens that appear twice in the training set will be added to the vocabulary and the rest wil... | MIN_FREQ = 2
TEXT.build_vocab(train_data,
min_freq = MIN_FREQ,
vectors = "glove.6B.100d",
unk_init = torch.Tensor.normal_)
UD_TAGS.build_vocab(train_data)
PTB_TAGS.build_vocab(train_data) | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
We can check how many tokens and tags are in our vocabulary by getting their length: | print(f"Unique tokens in TEXT vocabulary: {len(TEXT.vocab)}")
print(f"Unique tokens in UD_TAG vocabulary: {len(UD_TAGS.vocab)}")
print(f"Unique tokens in PTB_TAG vocabulary: {len(PTB_TAGS.vocab)}") | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
Exploring the vocabulary, we can check the most common tokens within our texts: | print(TEXT.vocab.freqs.most_common(20)) | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
We can see the vocabularies for both of our tags: | print(UD_TAGS.vocab.itos)
print(PTB_TAGS.vocab.itos) | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
We can also see how many of each tag are in our vocabulary: | print(UD_TAGS.vocab.freqs.most_common())
print(PTB_TAGS.vocab.freqs.most_common()) | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
We can also view how common each of the tags are within the training set: | def tag_percentage(tag_counts):
total_count = sum([count for tag, count in tag_counts])
tag_counts_percentages = [(tag, count, count/total_count) for tag, count in tag_counts]
return tag_counts_percentages
print("Tag\t\tCount\t\tPercentage\n")
for tag, count, percent in tag_percentage(UD... | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
The final part of data preparation is handling the iterator. This will be iterated over to return batches of data to process. Here, we set the batch size and the `device` - which is used to place the batches of tensors on our GPU, if we have one. | BATCH_SIZE = 128
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
train_iterator, valid_iterator, test_iterator = data.BucketIterator.splits(
(train_data, valid_data, test_data),
batch_size = BATCH_SIZE,
device = device) | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
Building the ModelNext up, we define our model - a multi-layer bi-directional LSTM. The image below shows a simplified version of the model with only one LSTM layer and omitting the LSTM's cell state for clarity.The model takes in a sequence of tokens, $X = \{x_1, x_2,...,x_T\}$, ... | class BiLSTMPOSTagger(nn.Module):
def __init__(self,
input_dim,
embedding_dim,
hidden_dim,
output_dim,
n_layers,
bidirectional,
dropout,
pad_idx):
super().... | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
Training the ModelNext, we instantiate the model. We need to ensure the embedding dimensions matches that of the GloVe embeddings we loaded earlier.The rest of the hyperparmeters have been chosen as sensible defaults, though there may be a combination that performs better on this model and dataset.The input and output... | INPUT_DIM = len(TEXT.vocab)
EMBEDDING_DIM = 100
HIDDEN_DIM = 128
OUTPUT_DIM = len(UD_TAGS.vocab)
N_LAYERS = 2
BIDIRECTIONAL = True
DROPOUT = 0.25
PAD_IDX = TEXT.vocab.stoi[TEXT.pad_token]
model = BiLSTMPOSTagger(INPUT_DIM,
EMBEDDING_DIM,
HIDDEN_DIM,
... | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
We initialize the weights from a simple Normal distribution. Again, there may be a better initialization scheme for this model and dataset. | def init_weights(m):
for name, param in m.named_parameters():
nn.init.normal_(param.data, mean = 0, std = 0.1)
model.apply(init_weights) | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
Next, a small function to tell us how many parameters are in our model. Useful for comparing different models. | def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f'The model has {count_parameters(model):,} trainable parameters') | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
We'll now initialize our model's embedding layer with the pre-trained embedding values we loaded earlier.This is done by getting them from the vocab's `.vectors` attribute and then performing a `.copy` to overwrite the embedding layer's current weights. | pretrained_embeddings = TEXT.vocab.vectors
print(pretrained_embeddings.shape)
model.embedding.weight.data.copy_(pretrained_embeddings) | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
It's common to initialize the embedding of the pad token to all zeros. This, along with setting the `padding_idx` in the model's embedding layer, means that the embedding should always output a tensor full of zeros when a pad token is input. | model.embedding.weight.data[PAD_IDX] = torch.zeros(EMBEDDING_DIM)
print(model.embedding.weight.data) | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
We then define our optimizer, used to update our parameters w.r.t. their gradients. We use Adam with the default learning rate. | optimizer = optim.Adam(model.parameters()) | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
Next, we define our loss function, cross-entropy loss.Even though we have no `` tokens within our tag vocab, we still have `` tokens. This is because all sentences within a batch need to be the same size. However, we don't want to calculate the loss when the target is a `` token as we aren't training our model to recog... | TAG_PAD_IDX = UD_TAGS.vocab.stoi[UD_TAGS.pad_token]
criterion = nn.CrossEntropyLoss(ignore_index = TAG_PAD_IDX) | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
We then place our model and loss function on our GPU, if we have one. | model = model.to(device)
criterion = criterion.to(device) | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
We will be using the loss value between our predicted and actual tags to train the network, but ideally we'd like a more interpretable way to see how well our model is doing - accuracy.The issue is that we don't want to calculate accuracy over the `` tokens as we aren't interested in predicting them.The function below ... | def categorical_accuracy(preds, y, tag_pad_idx):
"""
Returns accuracy per batch, i.e. if you get 8/10 right, this returns 0.8, NOT 8
"""
max_preds = preds.argmax(dim = 1, keepdim = True) # get the index of the max probability
non_pad_elements = (y != tag_pad_idx).nonzero()
correct = max_preds[no... | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
Next is the function that handles training our model.We first set the model to `train` mode to turn on dropout/batch-norm/etc. (if used). Then we iterate over our iterator, which returns a batch of examples. For each batch: - we zero the gradients over the parameters from the last gradient calculation- insert the batch... | def train(model, iterator, optimizer, criterion, tag_pad_idx):
epoch_loss = 0
epoch_acc = 0
model.train()
for batch in iterator:
text = batch.text
tags = batch.udtags
optimizer.zero_grad()
#text = [sent len, batch size]
... | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
The `evaluate` function is similar to the `train` function, except with changes made so we don't update the model's parameters.`model.eval()` is used to put the model in evaluation mode, so dropout/batch-norm/etc. are turned off. The iteration loop is also wrapped in `torch.no_grad` to ensure we don't calculate any gra... | def evaluate(model, iterator, criterion, tag_pad_idx):
epoch_loss = 0
epoch_acc = 0
model.eval()
with torch.no_grad():
for batch in iterator:
text = batch.text
tags = batch.udtags
predictions = model(text)
... | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
Next, we have a small function that tells us how long an epoch takes. | def epoch_time(start_time, end_time):
elapsed_time = end_time - start_time
elapsed_mins = int(elapsed_time / 60)
elapsed_secs = int(elapsed_time - (elapsed_mins * 60))
return elapsed_mins, elapsed_secs | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
Finally, we train our model!After each epoch we check if our model has achieved the best validation loss so far. If it has then we save the parameters of this model and we will use these "best" parameters to calculate performance over our test set. | N_EPOCHS = 15
best_valid_loss = float('inf')
for epoch in range(N_EPOCHS):
start_time = time.time()
train_loss, train_acc = train(model, train_iterator, optimizer, criterion, TAG_PAD_IDX)
valid_loss, valid_acc = evaluate(model, valid_iterator, criterion, TAG_PAD_IDX)
end_time = time.time()
... | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
We then load our "best" parameters and evaluate performance on the test set. | model.load_state_dict(torch.load('tut1-model.pt'))
test_loss, test_acc = evaluate(model, test_iterator, criterion, TAG_PAD_IDX)
print(f'Test Loss: {test_loss:.3f} | Test Acc: {test_acc*100:.2f}%') | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
Inference88% accuracy looks pretty good, but let's see our model tag some actual sentences.We define a `tag_sentence` function that will:- put the model into evaluation mode- tokenize the sentence with spaCy if it is not a list- lowercase the tokens if the `Field` did- numericalize the tokens using the vocabulary- fin... | def tag_sentence(model, device, sentence, text_field, tag_field):
model.eval()
if isinstance(sentence, str):
nlp = spacy.load('en')
tokens = [token.text for token in nlp(sentence)]
else:
tokens = [token for token in sentence]
if text_field.lower:
tokens = [t.lo... | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
We'll get an already tokenized example from the training set and test our model's performance. | example_index = 1
sentence = vars(train_data.examples[example_index])['text']
actual_tags = vars(train_data.examples[example_index])['udtags']
print(sentence) | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
We can then use our `tag_sentence` function to get the tags. Notice how the tokens referring to subject of the sentence, the "respected cleric", are both `` tokens! | tokens, pred_tags, unks = tag_sentence(model,
device,
sentence,
TEXT,
UD_TAGS)
print(unks) | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
We can then check how well it did. Surprisingly, it got every token correct, including the two that were unknown tokens! | print("Pred. Tag\tActual Tag\tCorrect?\tToken\n")
for token, pred_tag, actual_tag in zip(tokens, pred_tags, actual_tags):
correct = '✔' if pred_tag == actual_tag else '✘'
print(f"{pred_tag}\t\t{actual_tag}\t\t{correct}\t\t{token}") | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
Let's now make up our own sentence and see how well the model does.Our example sentence below has every token within the model's vocabulary. | sentence = 'The Queen will deliver a speech about the conflict in North Korea at 1pm tomorrow.'
tokens, tags, unks = tag_sentence(model,
device,
sentence,
TEXT,
UD_TAGS)
print(un... | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
Looking at the sentence it seems like it gave sensible tags to every token! | print("Pred. Tag\tToken\n")
for token, tag in zip(tokens, tags):
print(f"{tag}\t\t{token}") | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
We've now seen how to implement PoS tagging with PyTorch and TorchText! The BiLSTM isn't a state-of-the-art model, in terms of performance, but is a strong baseline for PoS tasks and is a good tool to have in your arsenal. Going deeperWhat if we could combine word-level and char-level approaches? 
UD_TAG = data.Field(unk_token = None)
PTB_TAG = data.Field(unk_token = None)
# We'll use NestedField to tokenize each word into list of chars
CHAR_NESTING = data.Field(tokenize=list, init_token="<bos>", eos_token="<eos>")
CHAR = data.Nes... | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
**Congratulations, you've got LSTM which relies on GRU output on each step.**Now we need only to train it. Same actions, very small adjustments. | def init_weights(m):
for name, param in m.named_parameters():
nn.init.normal_(param.data, mean = 0, std = 0.1)
model.apply(init_weights)
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f'The model has {count_parameters(model):,} trainable... | _____no_output_____ | MIT | week05_transformer_pos_tagging/week05_bilstm_for_pos_tagging.ipynb | JustM57/natural-language-processing |
1. Imports | import tensorflow as tf
from PIL.Image import DecompressionBombError
import matplotlib.pyplot as plt
import json
import numpy as np
import cv2
import praw,requests
import psaw
import datetime as dt
import os
import sys
from tensorflow.keras import models
from tensorflow.keras import layers
from tensorflow.keras import ... | _____no_output_____ | MIT | src/main.ipynb | kevinlinxc/ArtRater |
2. Functions | #Checks if two images are identical, returns true if they are, returns true if a file is blank
def compare2images(original,duplicate):
if original is None or duplicate is None:
return True #delete emtpy pictures
if original.shape == duplicate.shape:
#print("The images have same size and channels... | _____no_output_____ | MIT | src/main.ipynb | kevinlinxc/ArtRater |
3. Set up Reddit api for downloading images | #Set up API keys from .gitignored file
with open('config.json') as config_file:
config = json.load(config_file)['keys']
# Sign into Reddit using API Key
reddit = praw.Reddit(user_agent="Downloading images from r/art for a machine learning project",
client_id=config['client_id'],
... | _____no_output_____ | MIT | src/main.ipynb | kevinlinxc/ArtRater |
4. Downloading pictures from Reddit r/art using PSAW and PRAW | #187mb for 200 pics, approx 18.7gb for 20000
#Time periods to choose to download from
Jan12018 = int(dt.datetime(2018,1,1).timestamp())
Jan12019 = int(dt.datetime(2019,1,1).timestamp())
Jan12020 = int(dt.datetime(2020,1,1).timestamp())
Jan12021 = int(dt.datetime(2021,1,1).timestamp())
#Pass a PRAW instance into PSAW s... | _____no_output_____ | MIT | src/main.ipynb | kevinlinxc/ArtRater |
5. Processing code that removes pictures that are deleted/corruptMight need to run multiple times if low on ram | #Path to delete bad pictures from
path = "pics2/"
files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
cull = []
counter = 0
length = len(files)
print(f"Original Number of files: {length}")
#Template of a bad picture
deletedtemplate = cv2.imread("exampledeleted.jpg")
deletedtemplate2 = cv2.im... | Original Number of files: 11377
Deleting bad files: 100.0%
Final Number of files: 11364
| MIT | src/main.ipynb | kevinlinxc/ArtRater |
6. Preprocessing code that corrects grayscale images to RGB and rescales pictures to have maximum width or height of 1000If I ran nn training with large images, it would take too long, and if I ran on google colab,I wouldn't have the drive space for all the pictrues | #Path being read from
path = 'pics2/'
#Path writing to
path2 = 'picsfix/'
files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
length = len(files)
counter = 0
failures = []
for file in files:
try:
progress("Resizing and fixing pictures",counter,length)
#OpenCV doesn't open ... | _____no_output_____ | MIT | src/main.ipynb | kevinlinxc/ArtRater |
7. Plot histogram of scores to see how bad the bias towards lower scores is | path = "picsfix2"
files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
numpics = len(files)
labelsall = []
for file in files:
labelsall.append(int(file.split(".")[0].split("_")[0]))
#print(labelsall)
plt.hist(labelsall)
plt.yscale("log")
plt.ylabel("Frequency")
plt.xlabel("Score")
plt.titl... | _____no_output_____ | MIT | src/main.ipynb | kevinlinxc/ArtRater |
7. Split files into training and testing sets and write the names of files to txt filesI'm following [this guide](https://www.pyimagesearch.com/2018/12/24/how-to-use-keras-fit-and-fit_generator-a-hands-on-tutorial/)and using a file reader to reset the index to 0 seemed like the easiest solution to mimic what the autho... | #Path of pictures to split and write txts for
path = "picsfix2/"
trainingpath = "training.txt"
testingpath = "testing.txt"
files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
#randomize to avoid passing pictures to the neural net in alphabetical order
random.shuffle(files)
#print(files)
train... | _____no_output_____ | MIT | src/main.ipynb | kevinlinxc/ArtRater |
8. Actual neural net training using Convolutional Neural NetI didn't have enough ram to train locally, so I ended porting to Google Colab and training there.The trainin has not been succesful so far, and I haven't taken the time to diagnose why yet. | #Path of preprocessed pictures
path = "picsfix2/"
#Paths of training and testing txts that have file names
trainPath = 'training.txt'
testpath = 'testing.txt'
#Get all file names
files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
numpics = len(files)
labelsall = []
for file in files:
lab... | Highest score: 54157
Epoch 1/12
1443/14918 [=>............................] - ETA: 1:37:21 - loss: 0.0014 - acc: 0.0049 | MIT | src/main.ipynb | kevinlinxc/ArtRater |
load data | import pandas as pd
import joblib
from urllib.request import urlopen
import numpy as np
df_url = 'https://c620.s3-ap-northeast-1.amazonaws.com/c620_train.csv'
c_url = 'https://c620.s3-ap-northeast-1.amazonaws.com/c620_col_names.pkl'
df = pd.read_csv(df_url,index_col=0)
c = joblib.load(urlopen(c_url))
case_col = c['c... | _____no_output_____ | MIT | notebook/experiment/gan_style_model.ipynb | skywalker0803r/c620 |
preprocess data | from sklearn.utils import shuffle
from torch.utils.data import TensorDataset,DataLoader
from sklearn.preprocessing import MinMaxScaler
import torch
# split data
df = shuffle(df)
p1 = int(len(df)*0.8)
p2 = int(len(df)*0.9)
# to FloatTensor
train = torch.FloatTensor(df[all_col].values[:p1])
vaild = torch.FloatTensor(df... | _____no_output_____ | MIT | notebook/experiment/gan_style_model.ipynb | skywalker0803r/c620 |
def model,loss,optimizer | import torch
from torch import nn
import torch.nn.functional as F
def mlp(sizes, activation, output_activation=nn.Identity):
layers = []
for j in range(len(sizes)-1):
act = activation if j < len(sizes)-2 else output_activation
layers += [nn.Linear(sizes[j], sizes[j+1]), act()]
return nn.Sequential(*layer... | torch.Size([64, 10])
torch.Size([64, 164])
torch.Size([64, 164])
| MIT | notebook/experiment/gan_style_model.ipynb | skywalker0803r/c620 |
tensorboard | from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter()
case,feed,op,sp,wt = next(iter(train_iter))
writer.add_graph(model,[case,feed])
writer.close()
%load_ext tensorboard
%tensorboard --logdir runs | The tensorboard extension is already loaded. To reload it, use:
%reload_ext tensorboard
| MIT | notebook/experiment/gan_style_model.ipynb | skywalker0803r/c620 |
train model | import matplotlib.pyplot as plt
from tqdm import tqdm_notebook as tqdm
from copy import deepcopy
# train step
def train_step(model):
model.train()
total_loss = 0
for t,(case,feed,op,sp,wt) in enumerate(train_iter):
op_hat,sp_hat,wt_hat = model(case,feed)
op_loss = loss_fn(op_hat,op)
sp_loss = loss_fn... | _____no_output_____ | MIT | notebook/experiment/gan_style_model.ipynb | skywalker0803r/c620 |
練習1. 数値 `x` の絶対値を求める関数 `absolute(x)` を定義してください。 (Pythonには `abs` という組み込み関数が用意されていますが。)2. `x` が正ならば 1、負ならば -1、ゼロならば 0 を返す `sign(x)` という関数を定義してください。定義ができたら、その次のセルを実行して、`True` のみが表示されることを確認してください。 | def absolute(x):
...
def sign(x):
...
print(absolute(5) == 5)
print(absolute(-5) == 5)
print(absolute(0) == 0)
print(sign(5) == 1)
print(sign(-5) == -1)
print(sign(0) == 0) | _____no_output_____ | MIT | 1/1-3.ipynb | petrluner/utpython_lab |
練習の解答 | def absolute(x):
if x<0:
return -x
else:
return x
def sign(x):
if x<0:
return -1
if x>0:
return 1
return 0 | _____no_output_____ | MIT | 1/1-3.ipynb | petrluner/utpython_lab |
ObjectiveIn my previous tutorial, I showed how to use `apply_rows` and `apply_chunks` methods in cuDF to implement customized data transformations. Under the hood, they are all using [Numba library](https://numba.pydata.org/) to compile the normal python code into GPU kernels. Numba is an excellent python library that... | import cudf
import numpy as np
from numba import cuda
array_len = 1000
number_of_threads = 128
number_of_blocks = (array_len + (number_of_threads - 1)) // number_of_threads
df = cudf.DataFrame()
df['in'] = np.arange(array_len, dtype=np.float64)
@cuda.jit
def double_kernel(result, array_len):
"""
double ea... | <class 'numba.cuda.cudadrv.devicearray.DeviceNDArray'>
| Apache-2.0 | cudf/notebooks_numba_cuDF_integration.ipynb | rocketmlhq/rapids-notebooks |
From the output of this code, it shows the underlying GPU array is of type `numba.cuda.cudadrv.devicearray.DeviceNDArray`. We can directly pass it to the kernel function that is compiled by the `cuda.jit`. Because we passed in the reference, the effect of number transformation will automatically show up in the original... | %reset -s -f
import cudf
import numpy as np
import pandas as pd
from numba import cuda
import numba
import time
array_len = int(5e8)
average_window = 3000
number_of_threads = 128
number_of_blocks = (array_len + (number_of_threads - 1)) // number_of_threads
df = cudf.DataFrame()
df['in'] = np.arange(array_len, dtype=n... | Numba with comipile time 2.067620038986206
Numba without comipile time 1.9229750633239746
pandas time 5.2932703495025635
| Apache-2.0 | cudf/notebooks_numba_cuDF_integration.ipynb | rocketmlhq/rapids-notebooks |
Note, in order to compare the computation time accurately, I launch the kernel twice. The first time kernel launching will include the kernel compilation time. In this example, it takes 1.9s for the kernel to run without compilation. Use shared memoryIn the baseline code, each thread is reading the numbers from the g... | %reset -s -f
import cudf
import numpy as np
import pandas as pd
from numba import cuda
import numba
import time
array_len = int(5e8)
average_window = 3000
number_of_threads = 128
number_of_blocks = (array_len + (number_of_threads - 1)) // number_of_threads
shared_buffer_size = number_of_threads + average_window - 1
d... | Numba with comipile time 1.3115026950836182
Numba without comipile time 1.085998773574829
pandas time 5.594487428665161
| Apache-2.0 | cudf/notebooks_numba_cuDF_integration.ipynb | rocketmlhq/rapids-notebooks |
Running this, the computation time is reduced to 1.09s without kernel compilation time. Reduced redundant summationsEach thread in the above code is doing one moving average in a for-loop. It is easy to see that there are a lot of redundant summation operations done by different threads. To reduce the redundancy, the... | %reset -s -f
import cudf
import numpy as np
import pandas as pd
from numba import cuda
import numba
import time
array_len = int(5e8)
average_window = 3000
number_of_threads = 64
thread_tile = 48
number_of_blocks = (array_len + (number_of_threads * thread_tile - 1)) // (number_of_threads * thread_tile)
shared_buffer_s... | Numba with comipile time 0.6331000328063965
Numba without comipile time 0.30219364166259766
pandas time 6.03054666519165
| Apache-2.0 | cudf/notebooks_numba_cuDF_integration.ipynb | rocketmlhq/rapids-notebooks |
DS107 Big Data : Lesson Five Companion Notebook Table of Contents * [Table of Contents](DS107L5_toc) * [Page 1 - Introduction](DS107L5_page_1) * [Page 2 - Spark](DS107L5_page_2) * [Page 3 - Running Spark in Hadoop](DS107L5_page_3) * [Page 4 - Spark Data Storage](DS107L5_page_4) * [Page 5 - Introduction... | from IPython.display import VimeoVideo
# Tutorial Video Name: Spark 2.0 and Zeppelin
VimeoVideo('388865681', width=720, height=480) | _____no_output_____ | MIT | Data Science and Machine Learning/Machine-Learning-In-Python-THOROUGH/RECAP_DS/06_BIG_DATA/L05.ipynb | okara83/Becoming-a-Data-Scientist |
6. Similarity Functions - **Created by Andrés Segura Tinoco**- **Created on May 20, 2019**- **Updated on Mar 19, 2021** In statistics and related fields, a **similarity measure** or similarity function is a real-valued function that quantifies the similarity between two objects. In short, a similarity function quantif... | # Load the Python libraries
from math import *
from decimal import Decimal
from scipy import stats as ss
import sklearn.metrics.pairwise as sm
import math | _____no_output_____ | MIT | similarity-functions/SimilarityFunctions.ipynb | ansegura7/Algorithms |
\begin{align} similarity(X, Y) = d(X, Y) = \sqrt{\sum_{i=1}^n (X_i - Y_i)^2} \tag{1}\end{align} | # (1) Euclidean distance function
def euclidean_distance(x, y):
return sqrt(sum(pow(a-b,2) for a, b in zip(x, y))) | _____no_output_____ | MIT | similarity-functions/SimilarityFunctions.ipynb | ansegura7/Algorithms |
\begin{align} similarity(X, Y) = d(X, Y) = \sum_{i=1}^n |X_i - Y_i| \tag{2}\end{align} | # (2) manhattan distance function
def manhattan_distance(x, y):
return sum(abs(a-b) for a,b in zip(x,y)) | _____no_output_____ | MIT | similarity-functions/SimilarityFunctions.ipynb | ansegura7/Algorithms |
\begin{align} similarity(X, Y) = d(X, Y) = (\sum_{i=1}^n |X_i - Y_i|^p)^\frac{1}{p} \tag{3}\end{align} | # (3) Minkowski distance function
def _nth_root(value, n_root):
root_value = 1/float(n_root)
return round(Decimal(value) ** Decimal(root_value),3)
def minkowski_distance(x, y, p = 3):
return float(_nth_root(sum(pow(abs(a-b), p) for a,b in zip(x, y)), p)) | _____no_output_____ | MIT | similarity-functions/SimilarityFunctions.ipynb | ansegura7/Algorithms |
\begin{align} similarity(X, Y) = cos(\theta) = \frac{\vec{X}.\vec{Y}}{\|\vec{X}\|.\|\vec{Y}\|} = \frac{\sum_{i=1}^n X_i.Y_i}{\sqrt{\sum_{i=1}^n X_i^2}.\sqrt{\sum_{i=1}^n Y_i^2}} \tag{4}\end{align} | # (4) Cosine similarity function
def _square_rooted(x):
return round(sqrt(sum([a*a for a in x])),3)
def cosine_similarity(x, y):
numerator = sum(a*b for a,b in zip(x,y))
denominator = _square_rooted(x) * _square_rooted(y)
return round(numerator/float(denominator),3) | _____no_output_____ | MIT | similarity-functions/SimilarityFunctions.ipynb | ansegura7/Algorithms |
\begin{align} similarity(X, Y) = \frac{cov(X, Y)}{\sigma_X . \sigma_Y} = \frac{\sum_{i=1}^n (X_i - \bar{X}).(Y_i - \bar{Y})}{\sqrt{\sum_{i=1}^n (X_i - \bar{X})^2 . (Y_i - \bar{Y})^2}} \tag{5}\end{align} | # (5) Pearson similarity function
def _avg(x):
assert len(x) > 0
return float(sum(x)) / len(x)
def pearson_similarity(x, y):
assert len(x) == len(y)
n = len(x)
assert n > 0
avg_x = _avg(x)
avg_y = _avg(y)
diffprod = 0
xdiff2 = 0
ydiff2 = 0
for idx in range(n):
xdiff ... | _____no_output_____ | MIT | similarity-functions/SimilarityFunctions.ipynb | ansegura7/Algorithms |
\begin{align} similarity(X, Y) = J(X, Y) = \frac{|X \cap Y|}{|X \cup Y|} = \frac{|X \cap Y|}{|X| + |Y| - |X \cap Y|} \tag{6}\end{align} | # (6) Jaccard similarity function
def jaccard_similarity(x, y):
intersection_cardinality = len(set.intersection(*[set(x), set(y)]))
union_cardinality = len(set.union(*[set(x), set(y)]))
return intersection_cardinality / float(union_cardinality) | _____no_output_____ | MIT | similarity-functions/SimilarityFunctions.ipynb | ansegura7/Algorithms |
6.2. Manual examples | # Vectors
x = [-4.593481, -5.478033, 1.127111, 1.252885, -2.286953] # Messi
y = [-4.080334, -3.406618, 4.334073, -0.485612, -2.817897] # CR
z = [-4.048185, -5.546171, 0.505673, 0.616553, -1.730906] # Neymar | _____no_output_____ | MIT | similarity-functions/SimilarityFunctions.ipynb | ansegura7/Algorithms |
Euclidean distance | euclidean_distance(x, y)
euclidean_distance(x, z) | _____no_output_____ | MIT | similarity-functions/SimilarityFunctions.ipynb | ansegura7/Algorithms |
Manhattan distance | manhattan_distance(x, y)
manhattan_distance(x, z) | _____no_output_____ | MIT | similarity-functions/SimilarityFunctions.ipynb | ansegura7/Algorithms |
Minkowski distance | minkowski_distance(x, y)
minkowski_distance(x, z) | _____no_output_____ | MIT | similarity-functions/SimilarityFunctions.ipynb | ansegura7/Algorithms |
Cosine similarity | cosine_similarity(x, y)
cosine_similarity(x, z) | _____no_output_____ | MIT | similarity-functions/SimilarityFunctions.ipynb | ansegura7/Algorithms |
Pearson similarity | pearson_similarity(x, y)
pearson_similarity(x, z) | _____no_output_____ | MIT | similarity-functions/SimilarityFunctions.ipynb | ansegura7/Algorithms |
Jaccard similarity | a = [0, 1, 2, 3, 4, 5]
b = [-1, 1, 2, 0, 3, 5]
jaccard_similarity(a, b) | _____no_output_____ | MIT | similarity-functions/SimilarityFunctions.ipynb | ansegura7/Algorithms |
6.3. Sklearn examples | corr = sm.euclidean_distances([x], [y])
float(corr[0])
corr = sm.manhattan_distances([x], [y])
float(corr[0])
corr = sm.cosine_similarity([x], [y])
float(corr[0])
corr, p_value = ss.pearsonr(x, y)
corr | _____no_output_____ | MIT | similarity-functions/SimilarityFunctions.ipynb | ansegura7/Algorithms |
This notebook is part of the `nbsphinx` documentation: https://nbsphinx.readthedocs.io/. Pre-Executing NotebooksAutomatically executing notebooks during the Sphinx build process is an important feature of `nbsphinx`.However, there are a few use cases where pre-executing a notebook and storing the outputs might be pref... | import time
%time time.sleep(60 * 60)
6 * 7 | CPU times: user 160 ms, sys: 56 ms, total: 216 ms
Wall time: 1h 1s
| MIT | doc/pre-executed.ipynb | gehuazhen/nbsphinx |
If you *do* want to execute your notebooks, but some cells run for a long time, you can change the timeout, see [Cell Execution Timeout](timeout.ipynb). Rare LibrariesYou might have created results with a library that's hard to install and therefore you have only managed to install it on one very old computer in the b... | from a_very_rare_library import calculate_the_answer
calculate_the_answer() | _____no_output_____ | MIT | doc/pre-executed.ipynb | gehuazhen/nbsphinx |
ExceptionsIf an exception is raised during the Sphinx build process, it is stopped (the build process, not the exception!).If you want to show to your audience how an exception looks like, you have two choices:1. Allow errors -- either generally or on a per-notebook or per-cell basis -- see [Ignoring Errors](allow-err... | 1 / 0 | _____no_output_____ | MIT | doc/pre-executed.ipynb | gehuazhen/nbsphinx |
Client-specific OutputsWhen `nbsphinx` executes notebooks,it uses the `nbconvert` module to do so.Certain Jupyter clients might produce outputthat differs from what `nbconvert` would produce.To preserve those original outputs,the notebook has to be executed and savedbefore running Sphinx.For example,the JupyterLab hel... | sorted? | _____no_output_____ | MIT | doc/pre-executed.ipynb | gehuazhen/nbsphinx |
Understanding ROS node APIs in Arduino Following is a basic structure ROS Arduino node. We can see the function of each line of code: | #include <ros.h>
ros::NodeHandle nh;
void setup()
{
nh.initNode();
}
void loop()
{
nh.spinOnce();
} | _____no_output_____ | MIT | Modules/Bonus Module - Arduino-ROS Interface/2. Understanding ROS node APIs in Arduino.ipynb | mlsdpk/ROS_Basic_Course |
INIT | # transforms
transform = transforms.Compose([
transforms.ToTensor(),
])
# dataset
root = '/Users/Marco/Documents/DATASETS/GUITAR-FX-DIST/Mono_Discrete/Features'
excl_folders = ['MT2']
spectra_folder= 'mel_22050_1024_512'
proc_settings_csv = 'proc_settings.csv'
max_num_settings=3
dataset = dataset.FxDatase... | dataset size: 123552
train set size: 88956
val set size: 9885
test set size: 24711
| BSD-3-Clause | src/train_setnetcond_on_mono_disc.ipynb | mcomunita/gfx_classifier |
TRAIN SetNetCond | # model
setnetcond = models.SettingsNetCond(n_settings= dataset.max_num_settings,
mel_shape=dataset.mel_shape,
num_embeddings=dataset.num_fx,
embedding_dim=50)
# optimizer
optimizer = optim.Adam(setnetcond.para... | <ipython-input-7-490bdd120e03>:4: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
best_train_results... | BSD-3-Clause | src/train_setnetcond_on_mono_disc.ipynb | mcomunita/gfx_classifier |
Quickstart Example with Multi-class Classificatoin Data---This notebook provides an example of conducting OPE of an evaluate policy using multi-class classification dataset as logged bandit feedback data.Our example with multi-class classification data contains the follwoing four major steps:- (1) Bandit Reduction- (2... | import numpy as np
from sklearn.datasets import load_digits
from sklearn.ensemble import RandomForestClassifier as RandomForest
from sklearn.linear_model import LogisticRegression
# import open bandit pipeline (obp)
import obp
from obp.dataset import MultiClassToBanditReduction
from obp.ope import (
OffPolicyEvalua... | 0.3.3
| Apache-2.0 | examples/quickstart/multiclass.ipynb | nmasahiro/zr-obp |
(1) Bandit ReductionWe prepare easy-to-use interface for bandit reduction of multi-class classificatoin dataset: `MultiClassToBanditReduction` class in the dataset module.It takes feature vectors (`X`), class labels (`y`), classifier to construct behavior policy (`base_classifier_b`), paramter of behavior policy (`alp... | # load raw digits data
# `return_X_y` splits feature vectors and labels, instead of returning a Bunch object
X, y = load_digits(return_X_y=True)
# convert the raw classification data into a logged bandit dataset
# we construct a behavior policy using Logistic Regression and parameter alpha_b
# given a pair of a featur... | _____no_output_____ | Apache-2.0 | examples/quickstart/multiclass.ipynb | nmasahiro/zr-obp |
(2) Off-Policy LearningAfter generating logged bandit feedback, we now obtain an evaluation policy using the training set. | # obtain action choice probabilities by an evaluation policy
# we construct an evaluation policy using Random Forest and parameter alpha_e
action_dist = dataset.obtain_action_dist_by_eval_policy(
base_classifier_e=RandomForest(random_state=12345),
alpha_e=0.9,
) | _____no_output_____ | Apache-2.0 | examples/quickstart/multiclass.ipynb | nmasahiro/zr-obp |
(3) Off-Policy Evaluation (OPE)OPE attempts to estimate the performance of evaluation policies using their action choice probabilities.Here, we use the **InverseProbabilityWeighting (IPW)**, **DirectMethod (DM)**, and **Doubly Robust (DR)** estimators and visualize the OPE results. | # estimate the mean reward function by using ML model (Logistic Regression here)
# the estimated rewards are used by model-dependent estimators such as DM and DR
regression_model = RegressionModel(
n_actions=dataset.n_actions,
base_model=LogisticRegression(random_state=12345, max_iter=1000),
)
# please refer to... | mean 95.0% CI (lower) 95.0% CI (upper)
ipw 0.890339 0.826724 0.975248
dm 0.787085 0.779634 0.793370
dr 0.882536 0.808637 0.937305
| Apache-2.0 | examples/quickstart/multiclass.ipynb | nmasahiro/zr-obp |
(4) Evaluation of OPE estimatorsOur final step is **the evaluation of OPE**, which evaluates and compares the estimation accuracy of OPE estimators.With the multi-class classification data, we can calculate the ground-truth policy value of the evaluation policy. Therefore, we can compare the policy values estimated by... | # calculate the ground-truth performance of the evaluation policy
ground_truth = dataset.calc_ground_truth_policy_value(action_dist=action_dist)
print(f'ground-truth policy value (classification accuracy): {ground_truth}')
# evaluate the estimation performances of OPE estimators
# by comparing the estimated policy va... | _____no_output_____ | Apache-2.0 | examples/quickstart/multiclass.ipynb | nmasahiro/zr-obp |
Filter comparison | import scipy
from scipy import signal
import matplotlib.pyplot as plt
import numpy as np
import scipy.io as sio
import matplotlib.pyplot as plt
import statistics as stats
import pandas as pd
from scipy.fft import fft, fftfreq, fftshift
from scipy import signal
from scipy.signal import savgol_filter
from scipy.signal.si... | _____no_output_____ | MIT | FailurePrediction/VariableRotationalSpeed/GraphicalComparisons/FilterComparison.ipynb | judithspd/predictive-maintenance |
Question 1:Write a program that calculates and prints the value according to the given formula:Q = Square root of [(2 * C * D)/H]Following are the fixed values of C and H:C is 50. H is 30.D is the variable whose values should be input to your program in a comma-separated sequence.ExampleLet us assume the following com... | import math
C = 50
H = 30
numbers = input('Please enter the comma-separated values of D: ').split(',')
output = []
for D in numbers:
Q = math.sqrt((2*C*int(D))/H)
output.append(i)
print(round(Q), end=' ')
| Please enter the comma-separated values of D: 23,50,86
9 13 17 | CNRI-Python | Programming_Assingment13.ipynb | 14vpankaj/iNeuron_Programming_Assignments |
Question 2:Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array.The element value in the i-th row and j-th column of the array should be i*j.Note: i=0,1.., X-1; j=0,1,¡¬Y-1.ExampleSuppose the following inputs are given to the program:3,5Then, the output of the program should be:[[0, 0... | def Matrix(x,y):
M = []
for i in range(x):
row = []
for j in range(y):
row.append(i*j)
M.append(row)
return M
X = int(input('Enter the value of X: '))
Y = int(input('Enter the value of Y: '))
Matrix(X,Y) | Enter the value of X: 3
Enter the value of Y: 5
| CNRI-Python | Programming_Assingment13.ipynb | 14vpankaj/iNeuron_Programming_Assignments |
Question 3:Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically.Suppose the following input is supplied to the program:without,hello,bag,worldThen, the output should be:bag,hello,without,world | string = input('Please enter a comma separated sequence of words: ').split(',')
string.sort()
print(','.join(string)) | Please enter a comma separated sequence of words: without,hello,bag,world
bag,hello,without,world
| CNRI-Python | Programming_Assingment13.ipynb | 14vpankaj/iNeuron_Programming_Assignments |
Question 4:Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically.Suppose the following input is supplied to the program:hello world and practice makes perfect and hello world againThen, the output should ... | string = input('Enter the sequence of white separated words: ').split(' ')
print(' '.join(sorted(set(string)))) | Enter the sequence of white separated words: hello world and practice makes perfect and hello world again
again and hello makes perfect practice world
| CNRI-Python | Programming_Assingment13.ipynb | 14vpankaj/iNeuron_Programming_Assignments |
Question 5:Write a program that accepts a sentence and calculate the number of letters and digits.Suppose the following input is supplied to the program:hello world! 123Then, the output should be:LETTERS 10DIGITS 3 | string = input('Enter a sentence: ')
letter = 0
digit = 0
for i in string:
if i.isalpha():
letter += 1
elif i.isdigit():
digit += 1
else:
pass
print('LETTERS', letter)
print('DIGITS', digit)
| Enter a sentence: hello world! 123
LETTERS 10
DIGITS 3
| CNRI-Python | Programming_Assingment13.ipynb | 14vpankaj/iNeuron_Programming_Assignments |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.