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 |
|---|---|---|---|---|---|
The `multiscale.io` package handles file conversion. In general, one can call `multiscale.io.read_file.tohdf5` to convert the data type.*If the data type is not currently compatible, either code a conversion function or ask Loic/Ralph/Iaroslav.* | multiscale.io.read_file.tohdf5(original_filename) | file successfully converted
| CC-BY-4.0 | examples/Basics/Multiscale_Basics_Tutorial.ipynb | Coilm/hystorian |
If you open the newly produced file `SD_P4_zB5_050mV_-2550mV_0002` in HDFView, you will see four folders:1. **`datasets`** contains the main converted data from the .ibw files. It contains a subfolder for each of the original scans (in this case, only one), and each of these subfolders contain the 8 data channels obtai... | pt.m_apply(filename, msplt.save_image, 'datasets/SD_P4_zB5_050mV_-2550mV_0002/Phase2Retrace', image_name = 'Original_Phase', show=True) | _____no_output_____ | CC-BY-4.0 | examples/Basics/Multiscale_Basics_Tutorial.ipynb | Coilm/hystorian |
You might notice we added extra arguments to `m_apply`. In general, if `m_apply` is given extra arguments, these arguments are passed to the subfunction: in this case, `msplt.save_image`. Thus, `msplt.save_image` knows to set `image_name` to `'Original_Phase'`, and to set `show` to `True`. You should now also see the i... | pt.m_apply(filename, twodim.phase_linearisation, 'datasets/SD_P4_zB5_050mV_-2550mV_0002/Phase2Retrace')
print('Linearisation Complete!') | Linearisation Complete!
| CC-BY-4.0 | examples/Basics/Multiscale_Basics_Tutorial.ipynb | Coilm/hystorian |
If you open HDFView right now, you should see a new folder in `process` called `001-phase_linearisation` which contains the newly linearised data. If an error did occur at some point, you might also see other files of the form `abc-phase_linearisation`, where abc is some number. Don't worry; simply mark the correct (or... | pt.m_apply(filename, twodim.phase_binarisation, 'process/001-phase_linearisation/SD_P4_zB5_050mV_-2550mV_0002/Phase2Retrace')
print('Binarisation Complete!') | Binarisation Complete!
| CC-BY-4.0 | examples/Basics/Multiscale_Basics_Tutorial.ipynb | Coilm/hystorian |
Finally, we can view our final image. This requires the `msplt.save_image` function, which we used earlier. | pt.m_apply(filename, msplt.save_image, 'process/002-phase_binarisation/SD_P4_zB5_050mV_-2550mV_0002/Phase2Retrace', image_name = 'Binarised_Phase', show=True) | _____no_output_____ | CC-BY-4.0 | examples/Basics/Multiscale_Basics_Tutorial.ipynb | Coilm/hystorian |
If we want to, we can also go back and see the intermediate, linearised phase: | pt.m_apply(filename, msplt.save_image, 'process/001-phase_linearisation/SD_P4_zB5_050mV_-2550mV_0002/Phase2Retrace', image_name = 'Linearised_Phase', show=True) | _____no_output_____ | CC-BY-4.0 | examples/Basics/Multiscale_Basics_Tutorial.ipynb | Coilm/hystorian |
Our Mission Spam detection is one of the major applications of Machine Learning in the interwebs today. Pretty much all of the major email service providers have spam detection systems built in and automatically classify such mail as 'Junk Mail'. In this mission we will be using the Naive Bayes algorithm to create a m... | # '!' allows you to run bash commands from jupyter notebook.
print("List all the files in the current directory\n")
!ls
# The required data table can be found under smsspamcollection/SMSSpamCollection
print("\n List all the files inside the smsspamcollection directory\n")
!ls smsspamcollection
!cat smsspamcollection/SM... | _____no_output_____ | MIT | Exercises/4_Bayesian_Interference/Bayesian_Inference.ipynb | psnx/artificial-intelligence |
Step 1.2: Data Preprocessing Now that we have a basic understanding of what our dataset looks like, let's convert our labels to binary variables, 0 to represent 'ham'(i.e. not spam) and 1 to represent 'spam' for ease of computation. You might be wondering why do we need to do this step? The answer to this lies in how ... | '''
Solution
'''
df['names'] = df.label.map(lambda x: 1 if x == "spam" else 0)
| _____no_output_____ | MIT | Exercises/4_Bayesian_Interference/Bayesian_Inference.ipynb | psnx/artificial-intelligence |
Step 2.1: Bag of Words What we have here in our data set is a large collection of text data (5,572 rows of data). Most ML algorithms rely on numerical data to be fed into them as input, and email/sms messages are usually text heavy. Here we'd like to introduce the Bag of Words (BoW) concept which is a term used to spe... | '''
Solution:
'''
documents = ['Hello, how are you!',
'Win money, win from home.',
'Call me now.',
'Hello, Call hello you tomorrow?']
lower_case_documents = [w.lower() for w in documents]
print(lower_case_documents) | ['hello, how are you!', 'win money, win from home.', 'call me now.', 'hello, call hello you tomorrow?']
| MIT | Exercises/4_Bayesian_Interference/Bayesian_Inference.ipynb | psnx/artificial-intelligence |
**Step 2: Removing all punctuation**>>**Instructions:**Remove all punctuation from the strings in the document set. Save the strings into a list called 'sans_punctuation_documents'. | '''
Solution:
'''
punctuation = ",.?!"
import string
sans_punctuation_documents = [w.translate({ord(c): None for c in ".,_!?"})for w in lower_case_documents]
print(sans_punctuation_documents) | ['hello how are you', 'win money win from home', 'call me now', 'hello call hello you tomorrow']
| MIT | Exercises/4_Bayesian_Interference/Bayesian_Inference.ipynb | psnx/artificial-intelligence |
**Step 3: Tokenization**Tokenizing a sentence in a document set means splitting up the sentence into individual words using a delimiter. The delimiter specifies what character we will use to identify the beginning and end of a word. Most commonly, we use a single space as the delimiter character for identifying words,... | '''
Solution:
'''
import itertools
preprocessed_documents = [w.split() for w in sans_punctuation_documents]
preprocessed_documents = list(itertools.chain(*preprocessed_documents))
print(preprocessed_documents) | ['hello', 'how', 'are', 'you', 'win', 'money', 'win', 'from', 'home', 'call', 'me', 'now', 'hello', 'call', 'hello', 'you', 'tomorrow']
| MIT | Exercises/4_Bayesian_Interference/Bayesian_Inference.ipynb | psnx/artificial-intelligence |
**Step 4: Count frequencies**Now that we have our document set in the required format, we can proceed to counting the occurrence of each word in each document of the document set. We will use the `Counter` method from the Python `collections` library for this purpose. `Counter` counts the occurrence of each item in the... | '''
Solution
'''
frequency_list = []
import pprint
from collections import Counter
frequency_list = Counter(preprocessed_documents)
pprint.pprint(frequency_list) | Counter({'hello': 3,
'you': 2,
'win': 2,
'call': 2,
'how': 1,
'are': 1,
'money': 1,
'from': 1,
'home': 1,
'me': 1,
'now': 1,
'tomorrow': 1})
| MIT | Exercises/4_Bayesian_Interference/Bayesian_Inference.ipynb | psnx/artificial-intelligence |
Congratulations! You have implemented the Bag of Words process from scratch! As we can see in our previous output, we have a frequency distribution dictionary which gives a clear view of the text that we are dealing with.We should now have a solid understanding of what is happening behind the scenes in the `sklearn.fea... | '''
Here we will look to create a frequency matrix on a smaller document set to make sure we understand how the
document-term matrix generation happens. We have created a sample document set 'documents'.
'''
documents = ['Hello, how are you!',
'Win money, win from home.',
'Call me now.'... | _____no_output_____ | MIT | Exercises/4_Bayesian_Interference/Bayesian_Inference.ipynb | psnx/artificial-intelligence |
>>**Instructions:**Import the sklearn.feature_extraction.text.CountVectorizer method and create an instance of it called 'count_vector'. | '''
Solution
'''
from sklearn.feature_extraction.text import CountVectorizer
count_vector = CountVectorizer(documents)
count_vector | _____no_output_____ | MIT | Exercises/4_Bayesian_Interference/Bayesian_Inference.ipynb | psnx/artificial-intelligence |
**Data preprocessing with CountVectorizer()**In Step 2.2, we implemented a version of the CountVectorizer() method from scratch that entailed cleaning our data first. This cleaning involved converting all of our data to lower case and removing all punctuation marks. CountVectorizer() has certain parameters which take c... | '''
Practice node:
Print the 'count_vector' object which is an instance of 'CountVectorizer()'
'''
# No need to revise this code
print(count_vector) | CountVectorizer(analyzer='word', binary=False, decode_error='strict',
dtype=<class 'numpy.int64'>, encoding='utf-8',
input=['Hello, how are you!', 'Win money, win from home.', 'Call me now.', 'Hello, Call hello you tomorrow?'],
lowercase=True, max_df=1.0, max_features=None, min_df=1,
ngr... | MIT | Exercises/4_Bayesian_Interference/Bayesian_Inference.ipynb | psnx/artificial-intelligence |
>>**Instructions:**Fit your document dataset to the CountVectorizer object you have created using fit(), and get the list of words which have been categorized as features using the get_feature_names() method. | '''
Solution:
'''
# No need to revise this code
count_vector.fit(documents)
count_vector.get_feature_names() | _____no_output_____ | MIT | Exercises/4_Bayesian_Interference/Bayesian_Inference.ipynb | psnx/artificial-intelligence |
The `get_feature_names()` method returns our feature names for this dataset, which is the set of words that make up our vocabulary for 'documents'. >>**Instructions:**Create a matrix with each row representing one of the 4 documents, and each column representing a word (feature name). Each value in the matrix will repr... | '''
Solution
'''
doc_array = [d for d in documents]
doc_array | _____no_output_____ | MIT | Exercises/4_Bayesian_Interference/Bayesian_Inference.ipynb | psnx/artificial-intelligence |
Now we have a clean representation of the documents in terms of the frequency distribution of the words in them. To make it easier to understand our next step is to convert this array into a dataframe and name the columns appropriately. >>**Instructions:**Convert the 'doc_array' we created into a dataframe, with the co... | '''
Solution
'''
import pandas as pd
frequency_matrix = pd.DataFrame(doc_array)
frequency_matrix | _____no_output_____ | MIT | Exercises/4_Bayesian_Interference/Bayesian_Inference.ipynb | psnx/artificial-intelligence |
Congratulations! You have successfully implemented a Bag of Words problem for a document dataset that we created. One potential issue that can arise from using this method is that if our dataset of text is extremely large (say if we have a large collection of news articles or email data), there will be certain values t... | '''
Solution
'''
# split into training and testing sets
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(df['sms_message'],
df['label'],
random_state=1)
p... | _____no_output_____ | MIT | Exercises/4_Bayesian_Interference/Bayesian_Inference.ipynb | psnx/artificial-intelligence |
Step 3.2: Applying Bag of Words processing to our dataset. Now that we have split the data, our next objective is to follow the steps from "Step 2: Bag of Words," and convert our data into the desired matrix format. To do this we will be using CountVectorizer() as we did before. There are two steps to consider here:*... | '''
[Practice Node]
The code for this segment is in 2 parts. First, we are learning a vocabulary dictionary for the training data
and then transforming the data into a document-term matrix; secondly, for the testing data we are only
transforming the data into a document-term matrix.
This is similar to the process w... | _____no_output_____ | MIT | Exercises/4_Bayesian_Interference/Bayesian_Inference.ipynb | psnx/artificial-intelligence |
Step 4.1: Bayes Theorem implementation from scratch Now that we have our dataset in the format that we need, we can move onto the next portion of our mission which is the algorithm we will use to make our predictions to classify a message as spam or not spam. Remember that at the start of the mission we briefly discu... | '''
Instructions:
Calculate probability of getting a positive test result, P(Pos)
'''
'''
Solution (skeleton code will be provided)
'''
# P(D)
p_diabetes = 0.01
# P(~D)
p_no_diabetes = 0.99
# Sensitivity or P(Pos|D)
p_pos_diabetes = 0.9
# Specificity or P(Neg|~D)
p_neg_no_diabetes = 0.9
# P(Pos)
p_pos = # TODO
prin... | _____no_output_____ | MIT | Exercises/4_Bayesian_Interference/Bayesian_Inference.ipynb | psnx/artificial-intelligence |
**Using all of this information we can calculate our posteriors as follows:** The probability of an individual having diabetes, given that, that individual got a positive test result:`P(D|Pos) = (P(D) * Sensitivity)) / P(Pos)`The probability of an individual not having diabetes, given that, that individual got a pos... | '''
Instructions:
Compute the probability of an individual having diabetes, given that, that individual got a positive test result.
In other words, compute P(D|Pos).
The formula is: P(D|Pos) = (P(D) * P(Pos|D) / P(Pos)
'''
'''
Solution
'''
# P(D|Pos)
p_diabetes_pos = # TODO
print('Probability of an individual having d... | _____no_output_____ | MIT | Exercises/4_Bayesian_Interference/Bayesian_Inference.ipynb | psnx/artificial-intelligence |
Congratulations! You have implemented Bayes Theorem from scratch. Your analysis shows that even if you get a positive test result, there is only an 8.3% chance that you actually have diabetes and a 91.67% chance that you do not have diabetes. This is of course assuming that only 1% of the entire population has diabetes... | '''
Instructions: Compute the probability of the words 'freedom' and 'immigration' being said in a speech, or
P(F,I).
The first step is multiplying the probabilities of Jill Stein giving a speech with her individual
probabilities of saying the words 'freedom' and 'immigration'. Store this in a variable called p_j_tex... | _____no_output_____ | MIT | Exercises/4_Bayesian_Interference/Bayesian_Inference.ipynb | psnx/artificial-intelligence |
Now we can compute the probability of `P(J|F,I)`, the probability of Jill Stein saying the words 'freedom' and 'immigration' and `P(G|F,I)`, the probability of Gary Johnson saying the words 'freedom' and 'immigration'. | '''
Instructions:
Compute P(J|F,I) using the formula P(J|F,I) = (P(J) * P(F|J) * P(I|J)) / P(F,I) and store it in a variable p_j_fi
'''
'''
Solution
'''
p_j_fi = # TODO
print('The probability of Jill Stein saying the words Freedom and Immigration: ', format(p_j_fi))
'''
Instructions:
Compute P(G|F,I) using the formula ... | _____no_output_____ | MIT | Exercises/4_Bayesian_Interference/Bayesian_Inference.ipynb | psnx/artificial-intelligence |
And as we can see, just like in the Bayes' theorem case, the sum of our posteriors is equal to 1. Congratulations! You have implemented the Naive Bayes' theorem from scratch. Our analysis shows that there is only a 6.6% chance that Jill Stein of the Green Party uses the words 'freedom' and 'immigration' in her speech a... | '''
Instructions:
We have loaded the training data into the variable 'training_data' and the testing data into the
variable 'testing_data'.
Import the MultinomialNB classifier and fit the training data into the classifier using fit(). Name your classifier
'naive_bayes'. You will be training the classifier using 'tra... | _____no_output_____ | MIT | Exercises/4_Bayesian_Interference/Bayesian_Inference.ipynb | psnx/artificial-intelligence |
Now that predictions have been made on our test set, we need to check the accuracy of our predictions. Step 6: Evaluating our model Now that we have made predictions on our test set, our next goal is to evaluate how well our model is doing. There are various mechanisms for doing so, so first let's review them.**Accura... | '''
Instructions:
Compute the accuracy, precision, recall and F1 scores of your model using your test data 'y_test' and the predictions
you made earlier stored in the 'predictions' variable.
'''
'''
Solution
'''
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
print('Accuracy score: '... | _____no_output_____ | MIT | Exercises/4_Bayesian_Interference/Bayesian_Inference.ipynb | psnx/artificial-intelligence |
Visualizing Large Graphs with Datashader`DatashaderVisualizer` is capable of responsively showing very large graphs, but is lessinteractive than the [CytoscapeVisualizer](./Cytoscape_Example.ipynb). | import ipywidgets as W
import traitlets as T
from rdflib import Graph
from ipyradiant import DatashaderVisualizer, LayoutSelector | _____no_output_____ | BSD-3-Clause | examples/Datashader_Example.ipynb | lnijhawan/ipyradiant |
Here a `DatashaderVisualizer` is linked to a to show largest dataset from the[example data](./data/README.md). The `LayoutSelector` changes the layout algorithmused. A small `HTML` widget also reports which nodes are selected. Try exploring thevarious tools offered in the toolbar. | g = Graph().parse("data/tree.jsonld", format="json-ld")
ds = DatashaderVisualizer(graph=g)
ls = LayoutSelector(vis=ds)
sn = W.HTML()
T.dlink(
(ds, "selected_nodes"),
(sn, "value"),
lambda n: "Selected Nodes: <pre>{}</pre>".format("\n".join(sorted(n))),
)
ds_ex = W.HBox([ds, W.VBox([ls, sn])])
ds_ex | _____no_output_____ | BSD-3-Clause | examples/Datashader_Example.ipynb | lnijhawan/ipyradiant |
Setup Installing Dependencies and Mounting | %%capture
!pip install transformers
# Mount Google Drive
from google.colab import drive # import drive from google colab
ROOT = "/content/drive"
drive.mount(ROOT, force_remount=True) | Mounted at /content/drive
| MIT | notebooks/AutoCompose.ipynb | prajwalcr/AutoCompose |
Imports | import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
% matplotlib inline
import random
import json
import time
import datetime
import os
from transformers import GPT2Tokenizer, GPT2LMHeadModel, GPT2Config, AdamW, get_linear_schedule_with_warmup
import torch
torch.manual_seed(64... | Name: torch
Version: 1.8.1+cu101
Summary: Tensors and Dynamic neural networks in Python with strong GPU acceleration
Home-page: https://pytorch.org/
Author: PyTorch Team
Author-email: packages@pytorch.org
License: BSD-3
Location: /usr/local/lib/python3.7/dist-packages
Requires: numpy, typing-extensions
Required-by: tor... | MIT | notebooks/AutoCompose.ipynb | prajwalcr/AutoCompose |
Setting Device | %cd /content/drive/MyDrive/AutoCompose/
!nvidia-smi
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
device | _____no_output_____ | MIT | notebooks/AutoCompose.ipynb | prajwalcr/AutoCompose |
Data Preparation Data Collection | with open("data/anticipation.json", "r") as f:
data = json.load(f)
data = [poem for poem in data if len(poem["poem"].split()) < 100]
print(len(data))
data[:5] | 25070
| MIT | notebooks/AutoCompose.ipynb | prajwalcr/AutoCompose |
Data Model | class PoemDataset(Dataset):
def __init__(self, poems, tokenizer, max_length=768, gpt2_type="gpt2"):
self.tokenizer = tokenizer
self.input_ids = []
self.attn_masks = []
for poem in poems:
encodings_dict = tokenizer("<|startoftext|>"+poem["poem"]+"<|endoftext|>",
... | _____no_output_____ | MIT | notebooks/AutoCompose.ipynb | prajwalcr/AutoCompose |
Rough | print(tokenizer.encode("<|startoftext|> Hello World <|endoftext|>", padding="max_length", max_length=10))
print(len(tokenizer))
# Finding length of maximum token in dataset
max_length = max([len(tokenizer.encode(poem["poem"])) for poem in data])
print(max_length)
max_length = 100
x = [len(tokenizer.encode(poem["poem"])... | 1967 382741
| MIT | notebooks/AutoCompose.ipynb | prajwalcr/AutoCompose |
Dataset Creation | batch_size = 32
max_length = 100
dataset = PoemDataset(data, tokenizer, max_length=max_length)
# Split data into train and validation sets
train_size = int(0.9*len(dataset))
val_size = len(dataset) - train_size
train_dataset, val_dataset = random_split(dataset, [train_size, val_size])
print("Number of samples for tra... | _____no_output_____ | MIT | notebooks/AutoCompose.ipynb | prajwalcr/AutoCompose |
Finetune GPT2 Language Model Importing Pre-Trained GPT2 Model | # Load model configuration
config = GPT2Config.from_pretrained("gpt2")
# Create model instance and set embedding length
model = GPT2LMHeadModel.from_pretrained("gpt2", config=config)
model.resize_token_embeddings(len(tokenizer))
# Running the model on GPU
model = model.to(device)
# <<< Optional >>>
# Setting seeds to... | _____no_output_____ | MIT | notebooks/AutoCompose.ipynb | prajwalcr/AutoCompose |
Scheduling Optimizer | epochs = 4
warmup_steps = 1e2
sample_every = 100
print(len(train_dataloader))
print(len(train_dataset))
# Using AdamW optimizer with default parameters
optimizer = AdamW(model.parameters(), lr=5e-4, eps=1e-8)
# Toatl training steps is the number of data points times the number of epochs
total_training_steps = len(trai... | _____no_output_____ | MIT | notebooks/AutoCompose.ipynb | prajwalcr/AutoCompose |
Training | def format_time(elapsed):
return str(datetime.timedelta(seconds=int(round(elapsed))))
total_t0 = time.time()
training_stats = []
model = model.to(device)
for epoch_i in range(epochs):
print(f'Beginning epoch {epoch_i+1} of {epochs}')
t0 = time.time()
total_train_loss = 0
model.train()
# Labels are shif... | Beginning epoch 1 of 4
| MIT | notebooks/AutoCompose.ipynb | prajwalcr/AutoCompose |
Visualizations | pd.set_option('precision', 2)
df_stats = pd.DataFrame(data=training_stats)
df_stats = df_stats.set_index('epoch')
# Use plot styling from seaborn.
sns.set(style='darkgrid')
# Increase the plot size and font size.
sns.set(font_scale=1.5)
plt.rcParams["figure.figsize"] = (12,6)
# Plot the learning curve.
plt.plot(df_s... | _____no_output_____ | MIT | notebooks/AutoCompose.ipynb | prajwalcr/AutoCompose |
Generate Poems | model.eval()
prompt = "<|startoftext|>"
generated = torch.tensor(tokenizer.encode(prompt)).unsqueeze(0)
generated = generated.to(device)
sample_outputs = model.generate(
generated,
do_sample=True,
top_k=50,
... | Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation.
| MIT | notebooks/AutoCompose.ipynb | prajwalcr/AutoCompose |
Saving and Loading Finetuned Model | output_dir = "/content/drive/My Drive/AutoCompose/models/anticipation2"
# Save generated poems
# sample_outputs = model.generate(
# generated,
# do_sample=True,
# top_k=50,
# max_length ... | _____no_output_____ | MIT | notebooks/AutoCompose.ipynb | prajwalcr/AutoCompose |
Version Control | !git config --global user.email "prajwalguptacr@gmail.com"
!git config --global user.name "prajwal"
import json
f = open("AutoComposeCreds.json")
data = json.load(f)
f.close()
print(data)
username="prajwalcr"
repository="AutoCompose"
git_token = data["git-token"]
!git clone https://{git_token}@github.com/{username}/{re... | _____no_output_____ | MIT | notebooks/AutoCompose.ipynb | prajwalcr/AutoCompose |
Define the Convolutional Neural NetworkIn this notebook and in `models.py`:1. Define a CNN with images as input and keypoints as output2. Construct the transformed FaceKeypointsDataset, just as before3. Train the CNN on the training data, tracking loss4. See how the trained model performs on test data5. If necessary, ... | # load the data if you need to; if you have already loaded the data, you may comment this cell out
# -- DO NOT CHANGE THIS CELL -- #
!mkdir /data
!wget -P /data/ https://s3.amazonaws.com/video.udacity-data.com/topher/2018/May/5aea1b91_train-test-data/train-test-data.zip
!unzip -n /data/train-test-data.zip -d /data | mkdir: cannot create directory ‘/data’: File exists
--2019-02-24 07:21:17-- https://s3.amazonaws.com/video.udacity-data.com/topher/2018/May/5aea1b91_train-test-data/train-test-data.zip
Resolving s3.amazonaws.com (s3.amazonaws.com)... 52.216.176.157
Connecting to s3.amazonaws.com (s3.amazonaws.com)|52.216.176.157|:443.... | MIT | 2. Define the Network Architecture.ipynb | SyedaZainabAkhtar/Facial-Keypoint-Detection |
**Note:** Workspaces automatically close connections after 30 minutes of inactivity (including inactivity while training!). Use the code snippet below to keep your workspace alive during training. (The active_session context manager is imported below.)```from workspace_utils import active_sessionwith active_session(): ... | # import the usual resources
import matplotlib.pyplot as plt
import numpy as np
# import utilities to keep workspaces alive during model training
from workspace_utils import active_session
# watch for any changes in model.py, if it changes, re-load it automatically
%load_ext autoreload
%autoreload 2
## Define the Net... | Net(
(conv1): Conv2d(1, 32, kernel_size=(5, 5), stride=(1, 1))
(pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(conv2): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1))
(conv3): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1))
(conv3_bn): BatchNorm2d(128, eps=1e-05, momen... | MIT | 2. Define the Network Architecture.ipynb | SyedaZainabAkhtar/Facial-Keypoint-Detection |
Transform the dataset To prepare for training, we have created a transformed dataset of images and keypoints. Define a data transformIn PyTorch, a convolutional neural network expects a torch image of a consistent size as input. For efficient training, and so our model's loss does not blow up during training, it is al... | from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
# the dataset we created in Notebook 1 is copied in the helper file `data_load.py`
from data_load import FacialKeypointsDataset
# the transforms we defined in Notebook 1 are in the helper file `data_load.py`
from data_load impor... | Number of images: 3462
0 torch.Size([1, 224, 224]) torch.Size([68, 2])
1 torch.Size([1, 224, 224]) torch.Size([68, 2])
2 torch.Size([1, 224, 224]) torch.Size([68, 2])
3 torch.Size([1, 224, 224]) torch.Size([68, 2])
| MIT | 2. Define the Network Architecture.ipynb | SyedaZainabAkhtar/Facial-Keypoint-Detection |
Batching and loading dataNext, having defined the transformed dataset, we can use PyTorch's DataLoader class to load the training data in batches of whatever size as well as to shuffle the data for training the model. You can read more about the parameters of the DataLoader in [this documentation](http://pytorch.org/d... | # load training data in batches
batch_size = 10
train_loader = DataLoader(transformed_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=4)
| _____no_output_____ | MIT | 2. Define the Network Architecture.ipynb | SyedaZainabAkhtar/Facial-Keypoint-Detection |
Before trainingTake a look at how this model performs before it trains. You should see that the keypoints it predicts start off in one spot and don't match the keypoints on a face at all! It's interesting to visualize this behavior so that you can compare it to the model after training and see how the model has improv... | # load in the test data, using the dataset class
# AND apply the data_transform you defined above
# create the test dataset
test_dataset = FacialKeypointsDataset(csv_file='/data/test_frames_keypoints.csv',
root_dir='/data/test/',
... | _____no_output_____ | MIT | 2. Define the Network Architecture.ipynb | SyedaZainabAkhtar/Facial-Keypoint-Detection |
Apply the model on a test sampleTo test the model on a test sample of data, we have to follow these steps:1. Extract the image and ground truth keypoints from a sample2. Wrap the image in a Variable, so that the net can process it as input and track how it changes as the image moves through the network.3. Make sure th... | # test the model on a batch of test images
def net_sample_output():
# iterate through the test dataset
for i, sample in enumerate(test_loader):
# get sample data: images and ground truth keypoints
images = sample['image']
key_pts = sample['keypoints']
# convert im... | _____no_output_____ | MIT | 2. Define the Network Architecture.ipynb | SyedaZainabAkhtar/Facial-Keypoint-Detection |
Debugging tipsIf you get a size or dimension error here, make sure that your network outputs the expected number of keypoints! Or if you get a Tensor type error, look into changing the above code that casts the data into float types: `images = images.type(torch.FloatTensor)`. | # call the above function
# returns: test images, test predicted keypoints, test ground truth keypoints
test_images, test_outputs, gt_pts = net_sample_output()
# print out the dimensions of the data to see if they make sense
print(test_images.data.size())
print(test_outputs.data.size())
print(gt_pts.size()) | torch.Size([10, 1, 224, 224])
torch.Size([10, 68, 2])
torch.Size([10, 68, 2])
| MIT | 2. Define the Network Architecture.ipynb | SyedaZainabAkhtar/Facial-Keypoint-Detection |
Visualize the predicted keypointsOnce we've had the model produce some predicted output keypoints, we can visualize these points in a way that's similar to how we've displayed this data before, only this time, we have to "un-transform" the image/keypoint data to display it.The *new* function, `show_all_keypoints` disp... | def show_all_keypoints(image, predicted_key_pts, gt_pts=None):
"""Show image with predicted keypoints"""
# image is grayscale
plt.imshow(image, cmap='gray')
plt.scatter(predicted_key_pts[:, 0], predicted_key_pts[:, 1], s=20, marker='.', c='m')
# plot ground truth points as green pts
if gt_p... | _____no_output_____ | MIT | 2. Define the Network Architecture.ipynb | SyedaZainabAkhtar/Facial-Keypoint-Detection |
Un-transformationNext, you'll see a helper function. `visualize_output` that takes in a batch of images, predicted keypoints, and ground truth keypoints and displays a set of those images and their true/predicted keypoints.This function's main role is to take batches of image and keypoint data (the input and output of... | # visualize the output
# by default this shows a batch of 10 images
def visualize_output(test_images, test_outputs, gt_pts=None, batch_size=10):
for i in range(batch_size):
plt.figure(figsize=(20,10))
ax = plt.subplot(1, batch_size, i+1)
# un-transform the image data
image = test_i... | _____no_output_____ | MIT | 2. Define the Network Architecture.ipynb | SyedaZainabAkhtar/Facial-Keypoint-Detection |
Training Loss functionTraining a network to predict keypoints is different than training a network to predict a class; instead of outputting a distribution of classes and using cross entropy loss, we have to choose a loss function that is suited for regression, which directly compares a predicted value and target valu... | ## Define the loss and optimization
import torch.optim as optim
criterion = nn.MSELoss()
optimizer = optim.Adam(net.parameters(), lr = 0.001)
| _____no_output_____ | MIT | 2. Define the Network Architecture.ipynb | SyedaZainabAkhtar/Facial-Keypoint-Detection |
Training and Initial ObservationNow, we will train on our batched training data from `train_loader` for a number of epochs. | def train_net(n_epochs):
# prepare the net for training
net.train()
training_loss = []
for epoch in range(n_epochs): # loop over the dataset multiple times
running_loss = 0.0
# train on batches of data, assumes you already have train_loader
for batch_i, data in enume... | _____no_output_____ | MIT | 2. Define the Network Architecture.ipynb | SyedaZainabAkhtar/Facial-Keypoint-Detection |
Test dataSee how the model performs on previously unseen, test data. We've already loaded and transformed this data, similar to the training data. Next, run the trained model on these images to see what kind of keypoints are produced. | # get a sample of test data again
test_images, test_outputs, gt_pts = net_sample_output()
print(test_images.data.size())
print(test_outputs.data.size())
print(gt_pts.size())
## visualize test output
# you can use the same function as before, by un-commenting the line below:
visualize_output(test_images, test_outputs... | _____no_output_____ | MIT | 2. Define the Network Architecture.ipynb | SyedaZainabAkhtar/Facial-Keypoint-Detection |
Once we have found a good model (or two), we have to save the model so we can load it and use it later! | ## change the name to something uniqe for each new model
model_dir = 'saved_models/'
model_name = 'facial_keypoints_model.pt'
# after training, save your model parameters in the dir 'saved_models'
torch.save(net.state_dict(), model_dir+model_name) | _____no_output_____ | MIT | 2. Define the Network Architecture.ipynb | SyedaZainabAkhtar/Facial-Keypoint-Detection |
Feature VisualizationSometimes, neural networks are thought of as a black box, given some input, they learn to produce some output. CNN's are actually learning to recognize a variety of spatial patterns and you can visualize what each convolutional layer has been trained to recognize by looking at the weights that mak... | # Get the weights in the first conv layer, "conv1"
# if necessary, change this to reflect the name of your first conv layer
weights1 = net.conv1.weight.data
w = weights1.numpy()
filter_index = 0
print(w[filter_index][0])
print(w[filter_index][0].shape)
# display the filter weights
plt.imshow(w[filter_index][0], cma... | [[ 0.15470788 -0.03103321 0.14474995 -0.09415503 -0.17265566]
[ 0.25098324 0.1987015 -0.0861486 -0.18626866 0.02080246]
[ 0.21582745 0.20678866 0.02022225 -0.2662425 -0.10517941]
[-0.0465669 -0.06400613 0.11120261 -0.18623494 0.01846401]
[ 0.03995793 0.116187 -0.08362331 -0.1171196 -0.09572858]]
(5, ... | MIT | 2. Define the Network Architecture.ipynb | SyedaZainabAkhtar/Facial-Keypoint-Detection |
Feature mapsEach CNN has at least one convolutional layer that is composed of stacked filters (also known as convolutional kernels). As a CNN trains, it learns what weights to include in it's convolutional kernels and when these kernels are applied to some input image, they produce a set of **feature maps**. So, featu... | ## load in and display any image from the transformed test dataset
import cv2
image = cv2.imread('images/mona_lisa.jpg')
# convert image to grayscale
image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) / 255.0
## Using cv's filter2D function
filter_kernel = np.array([[ 0, 1, 1],
[-1, 0, 1],
... | _____no_output_____ | MIT | 2. Define the Network Architecture.ipynb | SyedaZainabAkhtar/Facial-Keypoint-Detection |
Project 4: Neural Networks ProjectAll code was complied and run in Google Colab as Neural models take time to run and the university laptops donot have enough processing power to run the same. All comments and conclusions have been added right below each code block for easier analysis and understanding Task 1. Autom... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
from sklearn.preprocessing import PolynomialFeatures
from sklearn.model_selection import GridSearchCV, cross_val_score, KFold
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_err... | _____no_output_____ | MIT | araghug_NN/Final_NN.ipynb | adithyarganesh/CSC591_004_Neural_Nets |
From the correlation values determined for the dataset, we notice that there is a high correlation with the first column in comparison with the restSplitting the data into train and test with a 2000 - 300 split | dataset = data.values
X = dataset[:,0:5]
Y = dataset[:,5]
X_test = X[-300:]
X = X[:-300]
Y_test = Y[-300:]
Y = Y[:-300] | _____no_output_____ | MIT | araghug_NN/Final_NN.ipynb | adithyarganesh/CSC591_004_Neural_Nets |
First, I decided to run a baseline model and see how the mse value for it is coming to be as this would give a perspective of how the values can increase with modification and hyperparameter tuning. | # define base model
def baseline():
model = Sequential()
model.add(Dense(5, input_dim=5, kernel_initializer='normal', activation='relu'))
model.add(Dense(1, kernel_initializer='normal'))
model.compile(loss='mean_squared_error', optimizer='adam')
return model
estimator = KerasRegressor(build_fn=base... | Baseline: -8204048.46 (24315010.89) MSE
| MIT | araghug_NN/Final_NN.ipynb | adithyarganesh/CSC591_004_Neural_Nets |
As seen above, for a simple multilayer perceptron regressor, a very high mse value has been determined. This allows us to conclude that better hyperparameter tuning is required with modifications to other parameters such as learning rate, dropout, epochs etc.Initially, I decided to nail down which an ideal optimizer wo... | def custom_model( momentum=0, dropout_rate=0.0, learn_rate=0.01, epochs = 10, verbose=0):
model = Sequential()
model.add(Dense(128, input_dim=X.shape[1], activation='relu'))
model.add(Dense(64, activation='relu'))
model.add(Dense(1))
adam = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, deca... | _____no_output_____ | MIT | araghug_NN/Final_NN.ipynb | adithyarganesh/CSC591_004_Neural_Nets |
I then created a model with two dense layers and used the Adam optimizer to perform the remaining hyperparameter tuning. There were the outputs that were obtained | print("Best mse is %f with params --> %s" % (grid_result.best_score_, grid_result.best_params_))
means = grid_result.cv_results_['mean_test_score']
std_dev = grid_result.cv_results_['std_test_score']
tuned_params = grid_result.cv_results_['params' ]
for mean, stdev, param in zip(means, std_dev, tuned_params):
print... | Best mse is -24887.330078 with params --> {'batch_size': 10, 'dropout_rate': 0.2, 'epochs': 100, 'learn_rate': 0.01}
-83463.160156, 25271.865298 ----> {'batch_size': 10, 'dropout_rate': 0.0, 'epochs': 10, 'learn_rate': 0.0001}
-88775.615625, 23038.250922 ----> {'batch_size': 10, 'dropout_rate': 0.0, 'epochs': 10, 'lear... | MIT | araghug_NN/Final_NN.ipynb | adithyarganesh/CSC591_004_Neural_Nets |
From the above values, we notice that the most optimal set of attributes were found to be. 'batch_size': 10, 'dropout_rate': 0.2, 'epochs': 100, 'learn_rate': 0.01 Task 2 - Compare the trained neural networkwith multivariable regression | X2 = sm.add_constant(X)
est = sm.OLS(Y, X2)
est2 = est.fit()
print(est2.summary())
reg2 = LinearRegression()
reg2.fit(X, Y)
print("The linear model is: Y = {:.5} + {:.5}*X1 + {:.5}*X2 + {:.5}*X3 + {:.5}*X4 + {:.5}*X5".format(reg2.intercept_, reg2.coef_[0], reg2.coef_[1], reg2.coef_[2], reg2.coef_[3], reg2.coef_[4]))
p... | The linear model is: Y = -2567.9 + 55.037*X1 + 2.2014*X2 + 5.6969*X3 + 6.9531*X4 + 9.1432*X5
Y = a0 + a1X1 + a3X3 + a4X4 + a5X5
| MIT | araghug_NN/Final_NN.ipynb | adithyarganesh/CSC591_004_Neural_Nets |
We now calculate the sum of squared errors (SSE) for each of the models and determine which is the better model | LR_sse = 0
for v in Y - reg2.predict(X):
LR_sse += v**2
NN_sse = 0
for v in Y - grid_result.predict(X):
NN_sse += v**2
print("SSE for Multivariate regression: ", LR_sse)
print("SSE for estimation with Neural Moedl: ", NN_sse) | SSE for Multivariate regression: 164973673.90797538
SSE for estimation with Neural Moedl: 44258448.18429801
| MIT | araghug_NN/Final_NN.ipynb | adithyarganesh/CSC591_004_Neural_Nets |
It can be seen that the SSE value for the custom neural model created with hyperparameter tuning seems to fare better in comparison to the Multivariable linear regression.Below are two sample predictions made on untrained test data by both the models. To plain sight, the difference is minimal but on further analysis wi... | Y_test_pred = reg2.predict(X_test)
plt.plot(Y_test_pred[:50])
plt.plot(Y_test[:50])
Y_test_pred_NN = grid_result.predict(X_test)
plt.plot(Y_test_pred_NN[:50])
plt.plot(Y_test[:50]) | _____no_output_____ | MIT | araghug_NN/Final_NN.ipynb | adithyarganesh/CSC591_004_Neural_Nets |
Problem StatementFind and return the `nth` row of Pascal's triangle in the form a list. `n` is 0-based.For exmaple, if `n = 4`, then `output = [1, 4, 6, 4, 1]`.To know more about Pascal's triangle: https://www.mathsisfun.com/pascals-triangle.html | #%% Imports and functions declarations
from math import factorial
def combinations(total_num: int, choosen_num: int) -> int:
"""
Returns the number of available combinations given a number of elements and the subspace selected
:param total_num: number of total elements
:param choosen_num: number of e... | _____no_output_____ | MIT | Arrays and Linked Lists/011_Pascal's-Triangle.ipynb | parikshitsaikia1619/DSA_Mastery |
Show Solution | def test_function(test_case):
n = test_case[0]
solution = test_case[1]
output = nth_row_pascal(n)
if solution == output:
print("Pass")
else:
print("Fail")
n = 0
solution = [1]
test_case = [n, solution]
test_function(test_case)
n = 1
solution = [1, 1]
test_case = [n, solution]
test_... | Pass
| MIT | Arrays and Linked Lists/011_Pascal's-Triangle.ipynb | parikshitsaikia1619/DSA_Mastery |
Dependencies | import json, warnings, shutil
from tweet_utility_scripts import *
from tweet_utility_preprocess_roberta_scripts import *
from transformers import TFRobertaModel, RobertaConfig
from tokenizers import ByteLevelBPETokenizer
from tensorflow.keras.models import Model
from tensorflow.keras import optimizers, metrics, losses,... | _____no_output_____ | MIT | Model backlog/Train/53-tweet-train-3fold-roberta-base-pb2.ipynb | dimitreOliveira/Tweet-Sentiment-Extraction |
Load data | database_base_path = '/kaggle/input/tweet-dataset-split-roberta-base-96/'
k_fold = pd.read_csv(database_base_path + '5-fold.csv')
display(k_fold.head())
# Unzip files
!tar -xvf /kaggle/input/tweet-dataset-split-roberta-base-96/fold_1.tar.gz
!tar -xvf /kaggle/input/tweet-dataset-split-roberta-base-96/fold_2.tar.gz
!tar... | _____no_output_____ | MIT | Model backlog/Train/53-tweet-train-3fold-roberta-base-pb2.ipynb | dimitreOliveira/Tweet-Sentiment-Extraction |
Model parameters | vocab_path = database_base_path + 'vocab.json'
merges_path = database_base_path + 'merges.txt'
base_path = '/kaggle/input/qa-transformers/roberta/'
config = {
"MAX_LEN": 96,
"BATCH_SIZE": 32,
"EPOCHS": 5,
"LEARNING_RATE": 3e-5,
"ES_PATIENCE": 1,
"question_size": 4,
"N_FOLDS": 1,
"base_model_path": base... | _____no_output_____ | MIT | Model backlog/Train/53-tweet-train-3fold-roberta-base-pb2.ipynb | dimitreOliveira/Tweet-Sentiment-Extraction |
Model | module_config = RobertaConfig.from_pretrained(config['config_path'], output_hidden_states=False)
def model_fn(MAX_LEN):
input_ids = layers.Input(shape=(MAX_LEN,), dtype=tf.int32, name='input_ids')
attention_mask = layers.Input(shape=(MAX_LEN,), dtype=tf.int32, name='attention_mask')
base_model = TFRob... | _____no_output_____ | MIT | Model backlog/Train/53-tweet-train-3fold-roberta-base-pb2.ipynb | dimitreOliveira/Tweet-Sentiment-Extraction |
Tokenizer | tokenizer = ByteLevelBPETokenizer(vocab_file=vocab_path, merges_file=merges_path, lowercase=True, add_prefix_space=True)
tokenizer.save('./') | _____no_output_____ | MIT | Model backlog/Train/53-tweet-train-3fold-roberta-base-pb2.ipynb | dimitreOliveira/Tweet-Sentiment-Extraction |
Train | history_list = []
AUTO = tf.data.experimental.AUTOTUNE
for n_fold in range(config['N_FOLDS']):
n_fold +=1
print('\nFOLD: %d' % (n_fold))
# Load data
base_data_path = 'fold_%d/' % (n_fold)
x_train = np.load(base_data_path + 'x_train.npy')
y_train = np.load(base_data_path + 'y_train.npy')
x_v... |
FOLD: 1
Train on 21984 samples, validate on 5496 samples
Epoch 1/5
21984/21984 - 292s - loss: 2.1388 - y_start_loss: 1.0514 - y_end_loss: 1.0873 - y_start_categorical_accuracy: 0.6546 - y_end_categorical_accuracy: 0.6529 - val_loss: 1.6510 - val_y_start_loss: 0.8545 - val_y_end_loss: 0.7959 - val_y_start_categorical_a... | MIT | Model backlog/Train/53-tweet-train-3fold-roberta-base-pb2.ipynb | dimitreOliveira/Tweet-Sentiment-Extraction |
Model loss graph | sns.set(style="whitegrid")
for n_fold in range(config['N_FOLDS']):
print('Fold: %d' % (n_fold+1))
plot_metrics(history_list[n_fold]) | Fold: 1
| MIT | Model backlog/Train/53-tweet-train-3fold-roberta-base-pb2.ipynb | dimitreOliveira/Tweet-Sentiment-Extraction |
Model evaluation | display(evaluate_model_kfold(k_fold, config['N_FOLDS']).style.applymap(color_map)) | _____no_output_____ | MIT | Model backlog/Train/53-tweet-train-3fold-roberta-base-pb2.ipynb | dimitreOliveira/Tweet-Sentiment-Extraction |
Visualize predictions | display(k_fold[[c for c in k_fold.columns if not (c.startswith('textID') or
c.startswith('text_len') or
c.startswith('selected_text_len') or
c.startswith('text_wordCnt... | _____no_output_____ | MIT | Model backlog/Train/53-tweet-train-3fold-roberta-base-pb2.ipynb | dimitreOliveira/Tweet-Sentiment-Extraction |
メモelixir を齧る。かじる。今のイメージ $\quad$ erlang 上で、erlang は 並行処理のためのシステムで、その erlang 上で理想的な言語を作ろうとしたら、ruby + clojure みたいな言語になった。Dave Thomas と まつもとゆきひろ が勧めているのだからいい言語なのだろう。 * https://elixirschool.com/ja/lessons/basics/control-structures/* https://magazine.rubyist.net/articles/0054/0054-ElixirBook.* https://dev.to/gumi/elixir-01... | %%capture
!wget https://packages.erlang-solutions.com/erlang-solutions_2.0_all.deb && sudo dpkg -i erlang-solutions_2.0_all.deb
!sudo apt update
!sudo apt install elixir
!elixir -v
!date | Erlang/OTP 24 [erts-12.2.1] [source] [64-bit] [smp:2:2] [ds:2:2:10] [async-threads:1] [jit]
Elixir 1.13.0 (compiled with Erlang/OTP 24)
Wed Mar 16 16:43:56 UTC 2022
| MIT | learnelixir.ipynb | kalz2q/myjupyternotebooks |
---メモ`!elixir -h` (ヘルプ)としたらシェルワンライナー `elixir -e` が使えるらしいことがわかった。`iex` というのがインタラクティブ環境なのだが、colab では使いにくいので `elixir -e` で代用する。 | !elixir -e 'IO.puts 3 + 3'
!elixir -e 'IO.puts "hello world!"'
# 次のようにすればファイルが作れる
%%writefile temp.exs
IO.puts "this is a pen."
# cat してみる
!cat temp.exs
# ファイルを elixir で実行する
!elixir temp.exs | this is a pen.
| MIT | learnelixir.ipynb | kalz2q/myjupyternotebooks |
---ネットで紹介されていた次のコードセルのコードはどうやって実行するのだろう。 今はわからなくていいと思うがとりあえず転記しておく。説明:このプログラムでは、Parallel というモジュールに pmap という関数を定義しているmap は、与えられたコレクションに対して map(Ruby での Enumerablemap と同じようなものと考えて下さい)を行なうのですが、 各要素の処理を、要素数の分だけプロセスを生成し、各プロセスで並行に実行する、というものです。 ちょっと見ても、よくわからないような気がしますが、大丈夫、本書を読めば、わかるようになりるとのこと。 | %%writefile temp.exs
defmodule Parallel do
def pmap(collection, func) do
collection
|> Enum.map(&(Task.async(fn -> func.(&1) end)))
|> Enum.map(&Task.await/1)
end
end
result = Parallel.pmap 1..1000, &(&1 * &1)
IO.inspect result
!elixir temp.exs | [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324,
361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089,
1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116,
2209, 2304, 2401, 2500, ...]
| MIT | learnelixir.ipynb | kalz2q/myjupyternotebooks |
上の例で colab 環境で非同期処理が問題なく動くことが確認できたみたい。 ---次のもネットで紹介されていた例で、ハローワールド並行処理版 | %%writefile temp.exs
parent = self()
spawn_link(fn ->
send parent, {:msg, "hello world"}
end)
receive do
{:msg, contents} -> IO.puts contents
end
!elixir temp.exs | hello world
| MIT | learnelixir.ipynb | kalz2q/myjupyternotebooks |
上の例でやっていることはつぎのような流れである。1. spawn_linkという関数に渡された関数が、関数の内容を実行する。2. 新しく作られたプロセス側では、メインプロセス側(parent)に “hello world” というメッセージを送る。3. メインプロセス側は、どこからかメッセージが来ないかを待ち受けて(receive)、メッセージが来たらそれをコンソールに表示する。 | # 実験 とりあえず理解しない。 colab 環境でどうかだけ調べる。
%%writefile chain.exs
defmodule Chain do
def counter(next_pid) do
receive do
n -> send next_pid, n + 1
end
end
def create_processes(n) do
last = Enum.reduce 1..n, self(),
fn (_, send_to) -> spawn(Chain, :counter, [send_to]) end
send last, 0
rec... | {4638957, "Result is 1000000"}
| MIT | learnelixir.ipynb | kalz2q/myjupyternotebooks |
記事 https://ubiteku.oinker.me/2015/12/22/elixir試飲-2-カルチャーショックに戸惑う-並行指向プ/ のマシン Macbook Pro – 3 GHz Intel Core i7, 16GB RAM では 7 秒のところ、colab では 5 秒で終わってるね!!!!手元のwindowsマシン intel core i5-9400 8gb ram でやったら次のようになった。 {3492935, "Result is 1000000"}あれ、速いじゃん!!!! ---コメントは `` | %%writefile temp.exs
# コメント実験
str = "helloworld!!!!"
IO.puts str
!elixir temp.exs | helloworld!!!!
| MIT | learnelixir.ipynb | kalz2q/myjupyternotebooks |
---n 進数、整数 integer | !elixir -e 'IO.puts 0b1111'
!elixir -e 'IO.puts 0o7777'
!elixir -e 'IO.puts 0xffff'
!elixir -e 'IO.puts 1000_000_00_0' | 15
4095
65535
1000000000
| MIT | learnelixir.ipynb | kalz2q/myjupyternotebooks |
整数型に上限下限 fixed limit はない。 factorial(10000) が計算できる。今はしない。 ---問題10進数を $n$ 進数にベースを変えるのはどうするか。 python では `int()`, `bin()`, `oct()`, `hex()` があった。 | # python
print(0b1111)
print(0o7777)
print(0xffff)
print(int('7777',8))
print(bin(15))
print(oct(4095))
print(hex(65535))
!elixir -e 'IO.puts 0b1111'
!elixir -e 'IO.puts 0o7777'
!elixir -e 'IO.puts 0xffff'
!echo
# Integer.to_string() と言う関数を使う
# <> はバイナリー連結
!elixir -e 'IO.puts "0b" <> Integer.to_string(15,2)'
!elixir -e... | 15
4095
65535
0b1111
0o7777
0xFFFF
| MIT | learnelixir.ipynb | kalz2q/myjupyternotebooks |
浮動小数点数 floating-point number | !elixir -e 'IO.puts 1.532e-4'
# .0 とか 1. とかはエラーになる
!elixir -e 'IO.puts 98099098.0809898888'
!elixir -e 'IO.puts 0.00000000000000000000000001' #=> 1.0e-26
!elixir -e 'IO.puts 90000000000000000000000000000000000000000000000000000000' | 1.532e-4
98099098.08098988
1.0e-26
999999999999999999999999999999999999999
90000000000000000000000000000000000000000000000000000000
| MIT | learnelixir.ipynb | kalz2q/myjupyternotebooks |
文字列 stringstring という型はない、みたい。---質問 型を調べる関数はあるか。type() とか。 | !elixir -e 'IO.puts "日本語が書けますか"'
!elixir -e 'IO.puts "日本語が書けます"'
# 関数に括弧をつけることができる
# \ で escape できる
!elixir -e 'IO.puts (0b1111)'
!elixir -e 'IO.puts ("にほんご\n日本語")'
!elixir -e "IO.puts ('にほんご\n\"日本語\"')"
# 文字連結 `+` ではない!!!!
!elixir -e 'IO.puts("ABCD"<>"EFGH")' | ABCDEFGH
| MIT | learnelixir.ipynb | kalz2q/myjupyternotebooks |
`` と言う記号はバイナリ連結ということらしい。 ---値の埋め込み`{変数名}` を記述することで、変数の値を埋め込むことができる。 | !elixir -e 'val = 1000; IO.puts "val = #{val}"' | val = 1000
| MIT | learnelixir.ipynb | kalz2q/myjupyternotebooks |
---真偽値elixir の 真偽値は true と false (小文字) で false と nil が false でそれ以外は true | !elixir -e 'if true do IO.puts "true" end'
!elixir -e 'if True do IO.puts "true" end'
!elixir -e 'if False do IO.puts "true" end' # False が大文字なので
!elixir -e 'if false do IO.puts "true" else IO.puts "false" end'
!elixir -e 'if nil do IO.puts "true" else IO.puts "false" end'
!elixir -e 'if 0 do IO.puts "true" else IO.put... | true
true
true
false
false
true
true
true
true
| MIT | learnelixir.ipynb | kalz2q/myjupyternotebooks |
`null` はない。 ---**マッチ演算子 `=`**マッチ演算子 `=` はマッチ演算子である。 マッチ演算子を通して値を代入し、その後、マッチさせることができる。マッチすると、方程式の結果が返され、失敗すると、エラーになる。 | !elixir -e 'IO.puts a = 1'
!elixir -e 'a =1; IO.puts 1 = a'
!elixir -e 'a =1; IO.puts 2 = a'
!elixir -e 'IO.inspect a = [1,2,3]' # リストは puts で表示できないので inspect を使う
!elixir -e '[a,b,c] = [1,2,3]; IO.puts c; IO.puts b'
| [1, 2, 3]
3
2
| MIT | learnelixir.ipynb | kalz2q/myjupyternotebooks |
上の例は、elixir は マッチ演算子 `=` があると左右がマッチするように最善を尽くす。 そのため、`[a,b,c] = [1,2,3]` で a,b,c に値が代入される。 | !elixir -e 'IO.inspect [1,2,[3,4,5]]'
!elixir -e '[a,b,c] = [1,2,[3,4,5]]; IO.inspect c; IO.inspect b'
# 実験 => エラー
!elixir -e 'IO.insepct [a,b] = [1,2,3]'
# 実験
!elixir -e 'IO.inspect a = [[1,2,3]]'
!elixir -e 'IO.inspect [a] = [[1,2,3]]'
!elixir -e '[a] = [[1,2,3]]; IO.inspect a'
# 実験 => エラー
!elixir -e 'IO.insepct [a,b... | a
:a
a
b
| MIT | learnelixir.ipynb | kalz2q/myjupyternotebooks |
アンダースコア `_` で値を無視する。 ワルドカード。なんでも受け付ける。 | !elixir -e 'IO.inspect [1,_,_]=[1,2,3]'
!elixir -e 'IO.inspect [1,_,_]=[1,"cat","dog"]' | [1, "cat", "dog"]
| MIT | learnelixir.ipynb | kalz2q/myjupyternotebooks |
変数は、バインド (束縛、紐付け) されると変更できない。かと思ったらできてしまう。 | !elixir -e 'a = 1; IO.puts a = 2' | 2
| MIT | learnelixir.ipynb | kalz2q/myjupyternotebooks |
元の変数を指し示すピン演算子 (`^` カレット) がある。 | !elixir -e 'a = 1; IO.puts ^a = 2' | ** (MatchError) no match of right hand side value: 2
(stdlib 3.15) erl_eval.erl:450: :erl_eval.expr/5
(stdlib 3.15) erl_eval.erl:893: :erl_eval.expr_list/6
(stdlib 3.15) erl_eval.erl:408: :erl_eval.expr/5
(elixir 1.12.0) lib/code.ex:656: Code.eval_string_with_error_handling/3
| MIT | learnelixir.ipynb | kalz2q/myjupyternotebooks |
メモ $\quad$ 普通の関数型言語のように変数は変更できないルールにしてしまった方が簡単ではなかったか、と思わないでもない。 変数を不変にする、const 宣言みたいなのはないのか。リストは不変 immutable なので安心。 | # 大文字にする capitalize
!elixir -e 'IO.puts name = String.capitalize "elixir"'
# 大文字にする upcase
!elixir -e 'IO.puts String.upcase "elixir"' | ELIXIR
| MIT | learnelixir.ipynb | kalz2q/myjupyternotebooks |
アトムアトムは名前がそのまま値となる定数である。**名前の前にコロン `:` をつけることでアトムになる。**アトムの名前は utf-8 文字列 (記号を含む)、数字、アンダースコア `_` 、`@` で、終端文字としてのみ「!」や「?」が使える。:fred $\quad$ :is_binary? $\quad$ :var@2 $\quad$ : $\quad$ :=== :"func/3" $\quad$ :"long john silver" $\quad$ :эликсир:mötley_crüeメモ | # 実験 アトムは宣言しないで突然使える
!elixir -e 'IO.puts :fred'
# 実験
!elixir -e 'IO.puts true === :true'
!elixir -e 'IO.puts :true'
!elixir -e 'IO.puts false === :false'
# 実験
!elixir -e 'IO.puts :fred'
!elixir -e 'IO.puts :is_binary?'
!elixir -e 'IO.puts :var@2'
!elixir -e 'IO.puts :<>'
!elixir -e 'IO.puts :==='
# セミコロンを含むアトムは iex 上で... | fred
is_binary?
var@2
<>
===
эликсир
mötley_crüe
日本語はどうか
| MIT | learnelixir.ipynb | kalz2q/myjupyternotebooks |
演算子 | !elixir -e 'IO.puts 1 + 2'
!elixir -e 'x = 10; IO.puts x + 1'
!elixir -e 'IO.puts 1 - 2'
!elixir -e 'x = 10; IO.puts x - 1'
!elixir -e 'IO.puts 5 * 2'
!elixir -e 'x = 10; IO.puts x * 4'
!echo
!elixir -e 'IO.puts 5 / 2'
!elixir -e 'x = 10; IO.puts x / 3'
# 浮動少数ではなく整数としての結果がほしい場合は div 関数を使用
!elixir -e 'IO.puts div(10,5)... | true
false
true
false
false
false
true
| MIT | learnelixir.ipynb | kalz2q/myjupyternotebooks |
rangeメモ $\quad$ range は型ではなく、struct である。 構造体?`start..end` で表現される、とあるが、1..10 と書けばそれで range なのか? | !elixir -e 'IO.inspect Enum.to_list(1..3)'
!elixir -e 'IO.inspect Enum.to_list(0..10//3)'
!elixir -e 'IO.inspect Enum.to_list(0..10//-3)'
!elixir -e 'IO.inspect Enum.to_list(10..0//-3)'
!elixir -e 'IO.inspect Enum.to_list(1..1)'
!elixir -e 'IO.inspect Enum.to_list(1..-1)'
!elixir -e 'IO.inspect Enum.to_list(1..1//2)'
!... | 1..9//2
| MIT | learnelixir.ipynb | kalz2q/myjupyternotebooks |
正規表現 regular expression正規表現も型ではなく、struct である。 | !elixir -e 'IO.inspect Regex.run ~r{[aiueo]},"catapillar"'
!elixir -e 'IO.inspect Regex.scan ~r{[aiueo]},"catapillar"'
!elixir -e 'IO.inspect Regex.split ~r{[aiueo]},"catapillar"'
!elixir -e 'IO.inspect Regex.replace ~r{[aiueo]},"catapillar", "*"' | "c*t*p*ll*r"
| MIT | learnelixir.ipynb | kalz2q/myjupyternotebooks |
コレクション型 タプルタプルは波括弧 brace を用いて定義する。タプルに限らず elixir のコレクションはすべて要素のタイプを限定しない。通常 2 から 4 の要素であり、それ以上の要素数の場合、map や struct の利用を考える。タプルは関数の返り値に便利に利用される。パターンマッチングと組み合わせて使われる。---cf. タプル以外の波括弧 brace の使用* 値の代入`{変数名}` * 正規表現 Regex `r{}` * マップ `%{}` | !elixir -e 'IO.inspect {3.14, :pie, "Apple"}'
!elixir -e '{status, count, action} = {3.14, :pie, "next"}; IO.puts action'
# 実験
# タプルの使い方の例
!echo hello > temp.txt
!elixir -e '{status, file} = File.open("temp.txt"); IO.inspect {status, file}'
!elixir -e '{status, file} = File.read("temp.txt"); IO.inspect {status, file}'... | {3.14, :pie, "Apple", {3}}
| MIT | learnelixir.ipynb | kalz2q/myjupyternotebooks |
リスト他の言語の配列 array と elixir のリストは違うので注意。 lisp のリストと似たような概念である。カラのリストでなければ、head (hd) と tail (tl) がある。hd は頭の1つで tl はそれ以降全部。 | # リスト
!elixir -e 'IO.inspect [3.14, :pie, "Apple"]'
!elixir -e 'IO.inspect hd [3.14]'
!elixir -e 'IO.inspect tl [3.14]'
# リスト先頭への追加(高速)
!elixir -e 'IO.inspect ["π" | [3.14, :pie, "Apple"]]'
# リスト末尾への追加(低速)
!elixir -e 'IO.inspect [3.14, :pie, "Apple"] ++ ["Cherry"]' | ["π", 3.14, :pie, "Apple"]
[3.14, :pie, "Apple", "Cherry"]
| MIT | learnelixir.ipynb | kalz2q/myjupyternotebooks |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.