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
Base fee of network operations (in stroops).`100 stroops = 0.0000100 XLM = ~USD$0.0000035`Note: Higher fees might be required when the network is under heavy usage.
base_fee = 100
_____no_output_____
MIT
stellar/stellar_ucl.ipynb
xujiahuayz/stellar_workshop
2. Assets & Payments 2.1. Create the AccountsFor this demo we'll need two accounts. A "professor", and a "student".The professor will:- Issues the Xu asset to the student.- Provides liquidity to buy/sell Xu.The student will:- Receive/Buy Xu.- Uses it to pay for a timeslot.Stellar is account-based, not UTXO-based. The...
def create_account(name): """Create an account on the testnet.""" key_pair = stellar_sdk.Keypair.random() url = "https://friendbot.stellar.org" _response = requests.get(url, params={"addr": key_pair.public_key}) # Check _response.json() in case something goes wrong print(f"{name} Public Key: {key_pair.publi...
Professor Public Key: GDNQVUUGK2MZBZ7SKFPYWC2WSRALGT2A2ND6DQUHH66WS6LDCUR2AH5I Professor Secret Seed: SCFJGTAIID65P32QKEKZGXSSAI6ZXM4ROAWIJZK33VLGA4IUACZ6JEYY Professor URL: https://horizon-testnet.stellar.org/accounts/GDNQVUUGK2MZBZ7SKFPYWC2WSRALGT2A2ND6DQUHH66WS6LDCUR2AH5I Student Public Key: GB3O4WKQTMRUF7KTNXEUSBLF...
MIT
stellar/stellar_ucl.ipynb
xujiahuayz/stellar_workshop
Transactions require a valid sequence number that is specific to the sender's account.We can fetch the current sequence number for the source account from Horizon.
professor_account = horizon.load_account(professor_keys.public_key) student_account = horizon.load_account(student_keys.public_key)
_____no_output_____
MIT
stellar/stellar_ucl.ipynb
xujiahuayz/stellar_workshop
2.2. Defining Our AssetAssets are identified by: `Code:Issuer`.
# Define our asset identifier xu = stellar_sdk.Asset("XU", professor_keys.public_key) print(f"XU Asset: {xu.code}:{xu.issuer}")
_____no_output_____
MIT
stellar/stellar_ucl.ipynb
xujiahuayz/stellar_workshop
2.3. Student Establishes a Trustline for the AssetAnyone can issue an asset on stellar.You want to make sure you’re using the β€œright” one.A trustline is an explicit opt-in to hold a particular token, so it specifies both asset code and issuer.Limits your account to the subset of all assets that you trust.Student will ...
transaction = ( stellar_sdk.TransactionBuilder( source_account=student_account, network_passphrase=stellar_sdk.Network.TESTNET_NETWORK_PASSPHRASE, base_fee=base_fee, ) # we need a trust line for the xu asset .append_change_trust_op(asset=xu) .set_timeout(30) # Make this tran...
_____no_output_____
MIT
stellar/stellar_ucl.ipynb
xujiahuayz/stellar_workshop
2.4. Professor Issues Some XU to the StudentAssets are created when the issuer makes a payment.The professor pays the student 30 XU, creating the asset.
transaction = ( stellar_sdk.TransactionBuilder( source_account=professor_account, network_passphrase=stellar_sdk.Network.TESTNET_NETWORK_PASSPHRASE, base_fee=base_fee, ) # issue 30 xu to the student .append_payment_op( destination=student_keys.public_key, asset=xu...
_____no_output_____
MIT
stellar/stellar_ucl.ipynb
xujiahuayz/stellar_workshop
2.5. Student Spends XU to Book a TimeslotTo book a timeslot, the student will pay some XU to the professor.Each transaction can have a memo attached, to help applications differentiate, and transfer extra data.
transaction = ( stellar_sdk.TransactionBuilder( source_account=student_account, network_passphrase=stellar_sdk.Network.TESTNET_NETWORK_PASSPHRASE, base_fee=base_fee, ) # spend 30 xu to book a 30-minute slot .append_payment_op( destination=professor_keys.public_key, ...
_____no_output_____
MIT
stellar/stellar_ucl.ipynb
xujiahuayz/stellar_workshop
3. The DEXStellar has a DEX (decentralised exchange) built into the protocol, for doing currency conversion and exchange.Professor Xu is business-savvy, and decides that if students want more office hours, they should pay for them.The professor decides to sell their office hours on the DEX. 3.1. Professor Adds Liquid...
# build the transaction transaction = ( stellar_sdk.TransactionBuilder( source_account=professor_account, network_passphrase=stellar_sdk.Network.TESTNET_NETWORK_PASSPHRASE, base_fee=base_fee, ) # Add a "manage sell offer" operation to the transaction .append_manage_sell_offer_op(...
_____no_output_____
MIT
stellar/stellar_ucl.ipynb
xujiahuayz/stellar_workshop
3.2. Student Buys XU from the DEXPath payments are the interface to the DEX, and how assets are converted.When converting `X -> Y`, you can either specify the amount of `X` you are sending, or the amount of `Y` you'd like the destination to receive.Note: The destination can be your own (or any other) account!
transaction = ( stellar_sdk.TransactionBuilder( source_account=student_account, network_passphrase=stellar_sdk.Network.TESTNET_NETWORK_PASSPHRASE, base_fee=base_fee, ) # Buy 30 xu token .append_path_payment_strict_receive_op( destination=student_keys.public_key, s...
_____no_output_____
MIT
stellar/stellar_ucl.ipynb
xujiahuayz/stellar_workshop
ONNX and TensorFlow Lite Support in `ktrain`As of v0.24.x, `predictors` in **ktrain** provide built-in support for exports to [ONNX](https://github.com/onnx/onnx) and [TensorFlow Lite](https://www.tensorflow.org/lite) formats. This allows you to more easily take a **ktrain**-trained model and use it to make predictio...
import ktrain predictor = ktrain.load_predictor('/tmp/my_distilbert_predictor') print(predictor.model) print(predictor.preproc)
<transformers.models.distilbert.modeling_tf_distilbert.TFDistilBertForSequenceClassification object at 0x7f929b30a710> <ktrain.text.preprocessor.Transformer object at 0x7f93ed5b88d0>
Apache-2.0
examples/text/ktrain-ONNX-TFLite-examples.ipynb
husmen/ktrain
The cell above assumes that the model was previously trained on the 20 Newsgroup corpus using a GPU (e.g., on Google Colab). The files in question can be easily created with **ktrain**:```python install ktrain!pip install ktrain load text datacategories = ['alt.atheism', 'comp.graphics', 'sci.med', 'soc.religion.chris...
# export TensorFlow Lite model tflite_model_path = '/tmp/model.tflite' tflite_model_path = predictor.export_model_to_tflite(tflite_model_path) # load interpreter interpreter = tf.lite.Interpreter(model_path=tflite_model_path) interpreter.allocate_tensors() input_details = interpreter.get_input_details() output_details...
converting to TFLite format ... this may take a few moments...
Apache-2.0
examples/text/ktrain-ONNX-TFLite-examples.ipynb
husmen/ktrain
ONNX InferencesHere, we will export our trained model to ONNX and make predictions *outside* of both **ktrain** and **TensorFlow** using the ONNX runtime. Please ensure the ONNX libraries are installed before proceeding with:```pip install -q --upgrade onnxruntime==1.5.1 onnxruntime-tools onnx keras2onnx```It is possi...
# set maxlen, class_names, and tokenizer (use settings employed when training the model - see above) model_name = 'distilbert-base-uncased' maxlen = 500 # from above class_names = ['alt.atheism', 'comp.graphics', 'sci.med', 'soc.religion.christian'] ...
ONNX opset version set to: 11 Loading pipeline (model: /tmp/my_distilbert_predictor_pt, tokenizer: distilbert-base-uncased) Creating folder /tmp/my_distilbert_predictor_pt_onnx Using framework PyTorch: 1.8.0 Found input input_ids with shape: {0: 'batch', 1: 'sequence'} Found input attention_mask with shape: {0: 'batch'...
Apache-2.0
examples/text/ktrain-ONNX-TFLite-examples.ipynb
husmen/ktrain
Model Layers This module contains many layer classes that we might be interested in using in our models. These layers complement the default [Pytorch layers](https://pytorch.org/docs/stable/nn.html) which we can also use as predefined layers.
from fastai.vision import * from fastai.gen_doc.nbdoc import *
_____no_output_____
Apache-2.0
docs_src/layers.ipynb
xnutsive/fastai
Custom fastai modules
show_doc(AdaptiveConcatPool2d, title_level=3) from fastai.gen_doc.nbdoc import * from fastai.layers import *
_____no_output_____
Apache-2.0
docs_src/layers.ipynb
xnutsive/fastai
The output will be `2*sz`, or just 2 if `sz` is None. The [`AdaptiveConcatPool2d`](/layers.htmlAdaptiveConcatPool2d) object uses adaptive average pooling and adaptive max pooling and concatenates them both. We use this because it provides the model with the information of both methods and improves performance. This tec...
path = untar_data(URLs.MNIST_SAMPLE) data = ImageDataBunch.from_folder(path) def simple_cnn_max(actns:Collection[int], kernel_szs:Collection[int]=None, strides:Collection[int]=None) -> nn.Sequential: "CNN with `conv2d_relu` layers defined by `actns`, `kernel_szs` and `strides`" nl = len(actns)-1 ...
_____no_output_____
Apache-2.0
docs_src/layers.ipynb
xnutsive/fastai
Now let's try with [Adapative Average Pooling](https://pytorch.org/docs/stable/nn.htmltorch.nn.AdaptiveAvgPool2d) now.
def simple_cnn_avg(actns:Collection[int], kernel_szs:Collection[int]=None, strides:Collection[int]=None) -> nn.Sequential: "CNN with `conv2d_relu` layers defined by `actns`, `kernel_szs` and `strides`" nl = len(actns)-1 kernel_szs = ifnone(kernel_szs, [3]*nl) strides = ifnone(strides ...
_____no_output_____
Apache-2.0
docs_src/layers.ipynb
xnutsive/fastai
Finally we will try with the concatenation of them both [`AdaptiveConcatPool2d`](/layers.htmlAdaptiveConcatPool2d). We will see that, in fact, it increases our accuracy and decreases our loss considerably!
def simple_cnn(actns:Collection[int], kernel_szs:Collection[int]=None, strides:Collection[int]=None) -> nn.Sequential: "CNN with `conv2d_relu` layers defined by `actns`, `kernel_szs` and `strides`" nl = len(actns)-1 kernel_szs = ifnone(kernel_szs, [3]*nl) strides = ifnone(strides , [...
_____no_output_____
Apache-2.0
docs_src/layers.ipynb
xnutsive/fastai
This is very useful to use functions as layers in our networks inside a [Sequential](https://pytorch.org/docs/stable/nn.htmltorch.nn.Sequential) object. So, for example, say we want to apply a [log_softmax loss](https://pytorch.org/docs/stable/nn.htmltorch.nn.functional.log_softmax) and we need to change the shape of o...
model = nn.Sequential( nn.Conv2d(3, 16, kernel_size=3, stride=2, padding=1), nn.ReLU(), nn.Conv2d(16, 16, kernel_size=3, stride=2, padding=1), nn.ReLU(), nn.Conv2d(16, 10, kernel_size=3, stride=2, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d(1), ) model.cuda() for xb, yb in data.train_dl: out = (m...
_____no_output_____
Apache-2.0
docs_src/layers.ipynb
xnutsive/fastai
The function we build above is actually implemented in our library as [`Flatten`](/layers.htmlFlatten). We can see that it returns the same size when we run it.
model = nn.Sequential( nn.Conv2d(3, 16, kernel_size=3, stride=2, padding=1), nn.ReLU(), nn.Conv2d(16, 16, kernel_size=3, stride=2, padding=1), nn.ReLU(), nn.Conv2d(16, 10, kernel_size=3, stride=2, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d(1), Flatten(), ) model.cuda() for xb, yb in data.train_d...
_____no_output_____
Apache-2.0
docs_src/layers.ipynb
xnutsive/fastai
We can combine these two final layers ([AdaptiveAvgPool2d](https://pytorch.org/docs/stable/nn.htmltorch.nn.AdaptiveAvgPool2d) and [`Flatten`](/layers.htmlFlatten)) by using [`PoolFlatten`](/layers.htmlPoolFlatten).
model = nn.Sequential( nn.Conv2d(3, 16, kernel_size=3, stride=2, padding=1), nn.ReLU(), nn.Conv2d(16, 16, kernel_size=3, stride=2, padding=1), nn.ReLU(), nn.Conv2d(16, 10, kernel_size=3, stride=2, padding=1), nn.ReLU(), PoolFlatten() ) model.cuda() for xb, yb in data.train_dl: out = (model(*[xb])...
torch.Size([64, 10])
Apache-2.0
docs_src/layers.ipynb
xnutsive/fastai
Another use we give to the Lambda function is to resize batches with [`ResizeBatch`](/layers.htmlResizeBatch) when we have a layer that expects a different input than what comes from the previous one.
show_doc(ResizeBatch) a = torch.tensor([[1., -1.], [1., -1.]]) print(a) out = ResizeBatch(4) print(out(a)) show_doc(Debugger, title_level=3)
_____no_output_____
Apache-2.0
docs_src/layers.ipynb
xnutsive/fastai
The debugger module allows us to peek inside a network while its training and see in detail what is going on. We can see inputs, ouputs and sizes at any point in the network.For instance, if you run the following:``` pythonmodel = nn.Sequential( nn.Conv2d(3, 16, kernel_size=3, stride=2, padding=1), nn.ReLU(), De...
show_doc(PixelShuffle_ICNR, title_level=3) show_doc(MergeLayer, title_level=3) show_doc(PartialLayer, title_level=3) show_doc(SigmoidRange, title_level=3) show_doc(SequentialEx, title_level=3) show_doc(SelfAttention, title_level=3) show_doc(BatchNorm1dFlat, title_level=3)
_____no_output_____
Apache-2.0
docs_src/layers.ipynb
xnutsive/fastai
Loss functions
show_doc(FlattenedLoss, title_level=3)
_____no_output_____
Apache-2.0
docs_src/layers.ipynb
xnutsive/fastai
Create an instance of `func` with `args` and `kwargs`. When passing an output and target, it- puts `axis` first in output and target with a transpose- casts the target to `float` is `floatify=True`- squeezes the `output` to two dimensions if `is_2d`, otherwise one dimension, squeezes the target to one dimension- applie...
show_doc(BCEFlat) show_doc(BCEWithLogitsFlat) show_doc(CrossEntropyFlat) show_doc(MSELossFlat) show_doc(NoopLoss) show_doc(WassersteinLoss)
_____no_output_____
Apache-2.0
docs_src/layers.ipynb
xnutsive/fastai
Helper functions to create modules
show_doc(bn_drop_lin, doc_string=False)
_____no_output_____
Apache-2.0
docs_src/layers.ipynb
xnutsive/fastai
The [`bn_drop_lin`](/layers.htmlbn_drop_lin) function returns a sequence of [batch normalization](https://arxiv.org/abs/1502.03167), [dropout](https://www.cs.toronto.edu/~hinton/absps/JMLRdropout.pdf) and a linear layer. This custom layer is usually used at the end of a model. `n_in` represents the number of size of th...
show_doc(conv2d) show_doc(conv2d_trans) show_doc(conv_layer, doc_string=False)
_____no_output_____
Apache-2.0
docs_src/layers.ipynb
xnutsive/fastai
The [`conv_layer`](/layers.htmlconv_layer) function returns a sequence of [nn.Conv2D](https://pytorch.org/docs/stable/nn.htmltorch.nn.Conv2d), [BatchNorm](https://arxiv.org/abs/1502.03167) and a ReLU or [leaky RELU](https://ai.stanford.edu/~amaas/papers/relu_hybrid_icml2013_final.pdf) activation function.`n_in` represe...
show_doc(embedding, doc_string=False)
_____no_output_____
Apache-2.0
docs_src/layers.ipynb
xnutsive/fastai
Create an [embedding layer](https://arxiv.org/abs/1711.09160) with input size `ni` and output size `nf`.
show_doc(relu) show_doc(res_block) show_doc(sigmoid_range) show_doc(simple_cnn)
_____no_output_____
Apache-2.0
docs_src/layers.ipynb
xnutsive/fastai
Initialization of modules
show_doc(batchnorm_2d) show_doc(icnr) show_doc(trunc_normal_) show_doc(icnr) show_doc(NormType)
_____no_output_____
Apache-2.0
docs_src/layers.ipynb
xnutsive/fastai
Undocumented Methods - Methods moved below this line will intentionally be hidden
show_doc(Debugger.forward) show_doc(Lambda.forward) show_doc(AdaptiveConcatPool2d.forward) show_doc(NoopLoss.forward) show_doc(PixelShuffle_ICNR.forward) show_doc(WassersteinLoss.forward) show_doc(MergeLayer.forward) show_doc(SigmoidRange.forward) show_doc(MergeLayer.forward) show_doc(SelfAttention.forward) show_doc(Se...
_____no_output_____
Apache-2.0
docs_src/layers.ipynb
xnutsive/fastai
Aggregating multiple count matrices tutorialThis tutorial describes how to aggregate multiple count matrices by concatenating them into a single [AnnData](https://anndata.readthedocs.io/en/latest/anndata.AnnData.html) object with batch labels for different samples.This is similar to the Cell Ranger aggr function, how...
%%time !wget -q https://www.ebi.ac.uk/arrayexpress/files/E-MTAB-6108/iPSC_RGCscRNAseq_Sample1_L005_R1.fastq.gz !wget -q https://www.ebi.ac.uk/arrayexpress/files/E-MTAB-6108/iPSC_RGCscRNAseq_Sample1_L005_R2.fastq.gz !wget -q https://www.ebi.ac.uk/arrayexpress/files/E-MTAB-6108/iPSC_RGCscRNAseq_Sample2_L005_R1.fastq.gz !...
CPU times: user 5.42 s, sys: 839 ms, total: 6.25 s Wall time: 15min 30s
MIT
docs/tutorials/kb_aggregate/python/kb_aggregating_count_matrices.ipynb
lambdamoses/kallistobustools
Install `kb`Install `kb` for running the kallisto|bustools workflow.
!pip install --quiet kb-python
 |β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 59.1MB 77kB/s  |β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 10.3MB 34.3MB/s  |β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 13.2MB 50.1MB/s  |β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 51kB 5.6MB/s  |β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 81kB 6.8MB/s  |β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ...
MIT
docs/tutorials/kb_aggregate/python/kb_aggregating_count_matrices.ipynb
lambdamoses/kallistobustools
Download a pre-built human index__Note:__ See [this notebook]() for a tutorial on how to build custom transcriptome or RNA velocity indices.
%%time !kb ref -d human -i index.idx -g t2g.txt
[2021-03-31 20:50:10,750] INFO Downloading files for human from https://caltech.box.com/shared/static/v1nm7lpnqz5syh8dyzdk2zs8bglncfib.gz to tmp/v1nm7lpnqz5syh8dyzdk2zs8bglncfib.gz 100% 2.23G/2.23G [01:35<00:00, 25.0MB/s] [2021-03-31 20:51:47,840] INFO Extracting files from tmp/v1nm7lpnqz5syh8dyzdk2zs8bglncfib.gz...
MIT
docs/tutorials/kb_aggregate/python/kb_aggregating_count_matrices.ipynb
lambdamoses/kallistobustools
Generate an RNA count matrices in H5AD formatThe following command will generate an RNA count matrix of cells (rows) by genes (columns) in H5AD format, which is a binary format used to store [Anndata](https://anndata.readthedocs.io/en/stable/) objects. Notice we are providing the index and transcript-to-gene mapping w...
%%time !kb count -i index.idx -g t2g.txt -x 10xv2 -o sample1 --h5ad -t 2 --filter bustools \ iPSC_RGCscRNAseq_Sample1_L005_R1.fastq.gz \ iPSC_RGCscRNAseq_Sample1_L005_R2.fastq.gz
[2021-03-31 20:52:24,861] INFO Using index index.idx to generate BUS file to sample1 from [2021-03-31 20:52:24,861] INFO iPSC_RGCscRNAseq_Sample1_L005_R1.fastq.gz [2021-03-31 20:52:24,861] INFO iPSC_RGCscRNAseq_Sample1_L005_R2.fastq.gz [2021-03-31 21:15:29,824] INFO Sorting BUS file sample1/...
MIT
docs/tutorials/kb_aggregate/python/kb_aggregating_count_matrices.ipynb
lambdamoses/kallistobustools
Sample 2
%%time !kb count -i index.idx -g t2g.txt -x 10xv2 -o sample2 --h5ad -t 2 --filter bustools \ iPSC_RGCscRNAseq_Sample2_L005_R1.fastq.gz \ iPSC_RGCscRNAseq_Sample2_L005_R2.fastq.gz
[2021-03-31 21:19:22,185] INFO Using index index.idx to generate BUS file to sample2 from [2021-03-31 21:19:22,185] INFO iPSC_RGCscRNAseq_Sample2_L005_R1.fastq.gz [2021-03-31 21:19:22,185] INFO iPSC_RGCscRNAseq_Sample2_L005_R2.fastq.gz [2021-03-31 21:37:11,095] INFO Sorting BUS file sample2/...
MIT
docs/tutorials/kb_aggregate/python/kb_aggregating_count_matrices.ipynb
lambdamoses/kallistobustools
Install `anndata`
!pip install --quiet anndata
_____no_output_____
MIT
docs/tutorials/kb_aggregate/python/kb_aggregating_count_matrices.ipynb
lambdamoses/kallistobustools
Read sample1 and sample2 gene counts into anndata
import anndata sample1 = anndata.read_h5ad('sample1/counts_filtered/adata.h5ad') sample2 = anndata.read_h5ad('sample2/counts_filtered/adata.h5ad') sample1 sample1.X sample1.obs.head() sample1.var.head() sample2 sample2.X sample2.obs.head() sample2.var.head()
_____no_output_____
MIT
docs/tutorials/kb_aggregate/python/kb_aggregating_count_matrices.ipynb
lambdamoses/kallistobustools
Concatenate the anndatas
concat_samples = sample1.concatenate( sample2, join='outer', batch_categories=['sample1', 'sample2'], index_unique='-' ) concat_samples concat_samples.var.head() concat_samples.obs
_____no_output_____
MIT
docs/tutorials/kb_aggregate/python/kb_aggregating_count_matrices.ipynb
lambdamoses/kallistobustools
Making pickle files for bloom timing vs. environmental driver analysis for Juan de Fuca Strait (SJDF) (201905 only) To work this notebook, change values in the second code cell and rerun for each year.
import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib as mpl import netCDF4 as nc import datetime as dt from salishsea_tools import evaltools as et, places, viz_tools, visualisations, bloomdrivers import xarray as xr import pandas as pd import pickle import os %matplotl...
_____no_output_____
Apache-2.0
notebooks/Bloom_Timing/SJDF/makePickles201905_SJDF.ipynb
SalishSeaCast/Analysis-Aline
To recreate this notebook at a different location, only change the following cell:
# Change this to the directory you want the pickle files to be stored: savedir='/ocean/aisabell/MEOPAR/extracted_files' # Change 'S3' to the location of interest loc='SJDF' # To create the time series for a range of years, change iyear to every year within the range # and run all cells each time. iyear=2020 # Lea...
_____no_output_____
Apache-2.0
notebooks/Bloom_Timing/SJDF/makePickles201905_SJDF.ipynb
SalishSeaCast/Analysis-Aline
Creating pickles files for location specific variables:
if recalc==True or not os.path.isfile(savepath): basedir='/results2/SalishSea/nowcast-green.201905/' nam_fmt='nowcast' flen=1 # files contain 1 day of data each ftype= 'ptrc_T' # loads bio files tres=24 # 1: hourly resolution; 24: daily resolution bio_time=list() diat_alld=list() no3_a...
_____no_output_____
Apache-2.0
notebooks/Bloom_Timing/SJDF/makePickles201905_SJDF.ipynb
SalishSeaCast/Analysis-Aline
Creating pickles files for location specific mixing variables:
fname4=f'JanToMarch_Mixing_{year}_{loc}_{modver}.pkl' # for location specific mixing variables savepath4=os.path.join(savedir,fname4) if recalc==True or not os.path.isfile(savepath4): basedir='/results2/SalishSea/nowcast-green.201905/' nam_fmt='nowcast' flen=1 # files contain 1 day of data each tres=24 ...
_____no_output_____
Apache-2.0
notebooks/Bloom_Timing/SJDF/makePickles201905_SJDF.ipynb
SalishSeaCast/Analysis-Aline
Variables for bloom timing calculations
if recalc==True or not os.path.isfile(savepath3): basedir='/results2/SalishSea/nowcast-green.201905/' nam_fmt='nowcast' flen=1 # files contain 1 day of data each ftype= 'ptrc_T' # load bio files tres=24 # 1: hourly resolution; 24: daily resolution flist=et.index_model_files(forbloomstart,forbl...
_____no_output_____
Apache-2.0
notebooks/Bloom_Timing/SJDF/makePickles201905_SJDF.ipynb
SalishSeaCast/Analysis-Aline
Loops that are not location specific (do not need to be redone for each location):
# define sog region: fig, ax = plt.subplots(1,2,figsize = (6,6)) with xr.open_dataset('/data/vdo/MEOPAR/NEMO-forcing/grid/bathymetry_201702.nc') as bathy: bath=np.array(bathy.Bathymetry) ax[0].contourf(bath,np.arange(0,250,10)) viz_tools.set_aspect(ax[0],coords='grid') sogmask=np.copy(tmask[:,:,:,:]) sogmask[:,:,74...
_____no_output_____
Apache-2.0
notebooks/Bloom_Timing/SJDF/makePickles201905_SJDF.ipynb
SalishSeaCast/Analysis-Aline
Heatmap for whole slices
%reload_ext autoreload %autoreload 2 %matplotlib inline from fastai.vision import * bs = 512 path = Path("/storage_1/ds_gbm_vs_met_threshold_whole_50/") tfms = get_transforms(flip_vert=True, do_flip=True, p_affine=0., p_lighting=0., max_zoom=1.) src = ImageList.from_folder(path).split_by_folder() def get_data(size, bs...
_____no_output_____
MIT
mri_classification/04_heatmap_raw_images.ipynb
CalmScout/MoLAB
Heatmap
m = learn.model.eval(); xb,_ = data.one_item(x) xb_im = Image(data.denorm(xb)[0]) xb = xb.cuda() from fastai.callbacks.hooks import * def hooked_backward(cat=y): with hook_output(m[0]) as hook_a: with hook_output(m[0], grad=True) as hook_g: preds = m(xb) preds[0,int(cat)].backward()...
_____no_output_____
MIT
mri_classification/04_heatmap_raw_images.ipynb
CalmScout/MoLAB
NotesDifferent problems give different number of points: 2, 3 or 4.Please, fill `STUDENT` variable with your name, so that we call collect the results automatically. Each problem contains specific validation details. We will do our best to review your assignments, but please keep in mind, that for this assignment auto...
%pylab inline plt.style.use("bmh") plt.rcParams["figure.figsize"] = (6,6) import numpy as np import torch STUDENT = "Gal Dahan Evyatar Shpitzer" ASSIGNMENT = 2 TEST = False if TEST: import solutions total_grade = 0 MAX_POINTS = 19
_____no_output_____
MIT
[Py4DP] [Lecture-2] Graded Assignment.ipynb
gald1017/python-for-DS
NumPy broadcasting 1. Normalize matrix rows (2 points).For 2-dimensional array `arr`, calculate an array, in which each row is a normalized version of corresponding row from `arr`.For example, for `(3,4)` input array, the output is also `(3,4)` and `out_arr[0] = (arr[0] - np.mean(arr[0])) / np.std(arr[0])` and so on ...
def norm_rows(arr): # your code goes here return (arr - np.expand_dims(arr.mean(axis=1), axis=1))/(np.expand_dims(arr.std(axis=1),axis=1)) PROBLEM_ID = 1 if TEST: total_grade += solutions.check(STUDENT, PROBLEM_ID, norm_rows)
Problem 1: Correct
MIT
[Py4DP] [Lecture-2] Graded Assignment.ipynb
gald1017/python-for-DS
2. Normalize matrix columns (2 points).Similar to Problem 1, but normalization must be performed along columns.For example, for `(3,4)` input array, the output is also `(3,4)` and `out_arr[:, 0] = (arr[:, 0] - np.mean(arr[:, 0])) / np.std(arr[:, 0])` and so on for other columns.Result must be **2-dimensional**, and **...
def norm_cols(arr): # your code goes here return (arr - arr.mean(axis=0).T)/(arr.std(axis=0).T) PROBLEM_ID = 2 if TEST: total_grade += solutions.check(STUDENT, PROBLEM_ID, norm_cols)
Problem 2: Correct
MIT
[Py4DP] [Lecture-2] Graded Assignment.ipynb
gald1017/python-for-DS
3. Generic normalize routine (2 points).Similar to Problems 1 and 2, but normalization must be performed according to `axis` argument. `axis=0` means normalization along the columns, and `axis=1` means normalization along the rows.
def norm_cols(arr): # your code goes here return (arr - arr.mean(axis=0).T)/(arr.std(axis=0).T) def norm_rows(arr): # your code goes here return (arr - np.expand_dims(arr.mean(axis=1), axis=1))/(np.expand_dims(arr.std(axis=1),axis=1)) def norm(arr, axis): # your code goes here if axis == 0: ...
Problem 3: Correct
MIT
[Py4DP] [Lecture-2] Graded Assignment.ipynb
gald1017/python-for-DS
4. Dot product of matrix and vector (2 points).Calculate dot product of 2-dimensional array $M$ of shape $(N,K)$ and 1-dimensional row vector $v$ of shape $(K,)$. You cannot use `np.dot` in this exercise.Result must be **1-dimensional** of shape $(N,)$, and **will be tested against three random combinations of input a...
def dot(m, v): # your code goes here return (m*v).sum(axis=1) PROBLEM_ID = 4 if TEST: total_grade += solutions.check(STUDENT, PROBLEM_ID, dot)
Problem 4: Correct
MIT
[Py4DP] [Lecture-2] Graded Assignment.ipynb
gald1017/python-for-DS
5. Calculate recurrence matrix (3 points).In signals (or time series) analysis, it's usualy important to quickly assess the structure (if any) of the data. This can be done in many different ways. You can test, whether a signal is stationary or look at Fourier transform to understand the frequency composition of a sig...
def recm_naive(ts, eps): """Loop implementation of recurrent matrix.""" ln = len(ts) rm = np.zeros((ln, ln), dtype=bool) for i in range(ln): for j in range(ln): rm[i, j] = np.abs(ts[i]-ts[j])<eps return rm random_signal = np.random.randn(200) plt.imshow(recm_naive(random_s...
Problem 5: Correct
MIT
[Py4DP] [Lecture-2] Graded Assignment.ipynb
gald1017/python-for-DS
PyTorch 6. ReLU activation (2 points).ReLU is the most commonly used activation function in many deep learning application. It's defined as$$ReLU(x) = \max(0, x).$$Outpu must be of the same shape as input, and **will be tested against three random combinations of input array dimensions ($100 \leq n < 1000 $)**, while...
def relu(arr): arr[arr<0] = 0 return arr PROBLEM_ID = 6 if TEST: total_grade += solutions.check(STUDENT, PROBLEM_ID, relu)
Problem 6: Correct
MIT
[Py4DP] [Lecture-2] Graded Assignment.ipynb
gald1017/python-for-DS
7. Mean squared error (2 points).In this problem you need to calculate MSE for a pair of tensors `y_true` and `y_pred`. MSE is defined as usual:$$L_{MSE} = \frac{1}{N} \sum_i \left(y_i - \hat y_i\right)^2$$Note, however, that `y_true` and `y_pred`may be of **different shape**. While `y_true` is always $(N,)$, `y_pred`...
def mse(y_true, y_pred): # your code goes here return (torch.sum((y_true - y_pred.reshape(y_true.shape))**2)) / y_true.shape[0] PROBLEM_ID = 7 if TEST: total_grade += solutions.check(STUDENT, PROBLEM_ID, mse)
_____no_output_____
MIT
[Py4DP] [Lecture-2] Graded Assignment.ipynb
gald1017/python-for-DS
8. Character-level encoding (4 points).In computations in general and in machine learning specifically letters cannot be used directly, as computers only know aboun numbers. Text data may be encoded in many different ways in natural language processing tasks.One of the simplest ways to encode letters is to use one-hot...
def word_2_int(w): alphabet = 'abcdefghijklmnopqrstuvwxyz' char_to_int = dict((c, i) for i, c in enumerate(alphabet)) return torch.as_tensor([char_to_int[char] for char in w]) def onehot(labels, tensor_size): # your code goes here b = torch.zeros(( tensor_size, 26 )) b[torch.arange(len(lab...
Problem 8: Correct
MIT
[Py4DP] [Lecture-2] Graded Assignment.ipynb
gald1017/python-for-DS
Your grade
if TEST: print(f"{STUDENT}: {int(100 * total_grade / MAX_POINTS)}")
Gal Dahan Evyatar Shpitzer: 0
MIT
[Py4DP] [Lecture-2] Graded Assignment.ipynb
gald1017/python-for-DS
Given running cost $g(x_t,u_t)$ and terminal cost $h(x_T)$ the finite horizon $(t=0 \ldots T)$ optimal control problem seeks to find the optimal control, $$u^*_{1:T} = \text{argmin}_{u_{1:T}} L(x_{1:T},u_{1:T})$$ $$u^*_{1:T} = \text{argmin}_{u_{1:T}} h(x_T) + \sum_{t=0}^T g(x_t,u_t)$$subject to the dynamics constraint:...
# NN parameters Nsamples = 10000 epochs = 500 latent_dim = 1024 batch_size = 8 lr = 3e-4 # Torch environment wrapping gym pendulum torch_env = Pendulum() # Test parameters Nsteps = 100 # Set up model (fully connected neural network) model = FCN(latent_dim=latent_dim,d=torch_env.d,ud=torch_env.ud) optimizer = torch....
_____no_output_____
MIT
Model-based-CEM-policy.ipynb
mgb45/OC-notebooks
Callback> Miscellaneous callbacks for timeseriesAI.
#export from tsai.imports import * from tsai.utils import * from tsai.data.preprocessing import * from tsai.data.transforms import * from tsai.models.layers import * from fastai.callback.all import * #export import torch.multiprocessing torch.multiprocessing.set_sharing_strategy('file_system')
_____no_output_____
Apache-2.0
nbs/060_callback.core.ipynb
Attol8/timeseriesAI
Events A callback can implement actions on the following events:* before_fit: called before doing anything, ideal for initial setup.* before_epoch: called at the beginning of each epoch, useful for any behavior you need to reset at each epoch.* before_train: called at the beginning of the training part of an epoch.* b...
#export class GamblersCallback(Callback): "A callback to use metrics with gambler's loss" def after_loss(self): self.learn.pred = self.learn.pred[..., :-1] from tsai.data.all import * from tsai.models.InceptionTime import * from tsai.models.layers import * dsid = 'NATOPS' X, y, splits = get_UCR_data(dsid, retur...
_____no_output_____
Apache-2.0
nbs/060_callback.core.ipynb
Attol8/timeseriesAI
Transform scheduler
# export class TransformScheduler(Callback): "A callback to schedule batch transforms during training based on a function (sched_lin, sched_exp, sched_cos (default), etc)" def __init__(self, schedule_func:callable, show_plot:bool=False): self.schedule_func,self.show_plot = schedule_func,show_plot ...
_____no_output_____
Apache-2.0
nbs/060_callback.core.ipynb
Attol8/timeseriesAI
ShowGraph
#export class ShowGraph(Callback): "(Modified) Update a graph of training and validation loss" order,run_valid=65,False names = ['train', 'valid'] def __init__(self, plot_metrics:bool=True, final_losses:bool=False): store_attr("plot_metrics,final_losses") def before_fit(self): self...
_____no_output_____
Apache-2.0
nbs/060_callback.core.ipynb
Attol8/timeseriesAI
Uncertainty-based data augmentation
#export class UBDAug(Callback): r"""A callback to implement the uncertainty-based data augmentation.""" def __init__(self, batch_tfms:list, N:int=2, C:int=4, S:int=1): r''' Args: batch_tfms: list of available transforms applied to the combined batch. They will be applied in a...
_____no_output_____
Apache-2.0
nbs/060_callback.core.ipynb
Attol8/timeseriesAI
Import preprocessed data
df = pd.read_csv(join('..', 'data', 'tugas_preprocessed.csv')) df.head() df.columns # Splitting feature names into groups non_metric_features = df.columns[df.columns.str.startswith('x')] pc_features = df.columns[df.columns.str.startswith('PC')] metric_features = df.columns[~df.columns.str.startswith('x') & ~df.columns....
_____no_output_____
MIT
notebooks/lab10_kmeans_clustering.ipynb
tiago-oom/Data-Mining-21-22
K-Means ClusteringWhat is K-Means clustering? How does it work? How is it computed?![](../figures/kmeans.png) Characteristics:- *Number of clusters* need to be set apriori- One of the *fastest* clustering algorithms- The results *depend on the initialization* (stochastic)- Prone to *local optima*- Favors *convex* (ro...
kmclust = KMeans(n_clusters=5, init='random', n_init=1, random_state=None) # n_clusters=8, # *, # init='k-means++', # n_init=10, --> Number of time the k-means algorithm will run with different centroid seeds. Final results will be the best output of # n_init consecutive runs in terms of ...
_____no_output_____
MIT
notebooks/lab10_kmeans_clustering.ipynb
tiago-oom/Data-Mining-21-22
How can we improve the initialization step?
# Better initialization method and provide more n_init # init='k-means++' & n_init=15 kmclust = KMeans(n_clusters=5, init='k-means++', n_init=15, random_state=1) kmclust.fit(df[metric_features]) kmclust.predict(df[metric_features]) # Returns the same result everytime
_____no_output_____
MIT
notebooks/lab10_kmeans_clustering.ipynb
tiago-oom/Data-Mining-21-22
*init='k-means++'* initializes the centroids to be (generally) distant from each other, leading to probably better results than random initialization. *n_init=K* allows to initialize KMeans K times and pick the best clustering in terms of Inertia. This can been shown in the link below.**Empirical evaluation of the impa...
range_clusters = range(2, 11) # Goes from 2 to 10 inertia = [] for n_clus in range_clusters: # iterate over desired ncluster range kmclust = KMeans(n_clusters=n_clus, init='k-means++', n_init=15, random_state=42) kmclust.fit(df[metric_features]) inertia.append(kmclust.inertia_) # save the inert...
[67166.77874914452, 52973.55241023803, 46736.65485715153, 42189.58282488099, 39883.766299443174, 37885.24251203413, 36277.77069520268, 34921.02592728754, 33556.1286728264]
MIT
notebooks/lab10_kmeans_clustering.ipynb
tiago-oom/Data-Mining-21-22
**Inertia (within-cluster sum-of-squares distance) Formula:**$$\sum_{j=0}^{C}\sum_{i=0}^{n_j}(||x_i - \mu_j||^2)$$, where:$C$: Set of identified clusters.$n_j$: Set of observations belonging to cluster $j$.$x_i$: Observation $i$.$\mu_j$: Centroid of cluster $j$.
# The inertia plot plt.figure(figsize=(9,5)) plt.plot(pd.Series(inertia, index = range_clusters)) plt.ylabel("Inertia: SSw") plt.xlabel("Number of clusters") plt.title("Inertia plot over clusters", size=15) plt.show() # I would say the elbow is on number of cluster = 4, so we can try with 3, 4 or 5 and evaluate the r...
_____no_output_____
MIT
notebooks/lab10_kmeans_clustering.ipynb
tiago-oom/Data-Mining-21-22
**Silhouette Coefficient formula for a single sample:**$$s = \frac{b - a}{max(a, b)}$$, where:- $a$: The mean distance between a sample and all other points in the same cluster.- $b$: The mean distance between a sample and all other points in the next nearest cluster
# Adapted from: # https://scikit-learn.org/stable/auto_examples/cluster/plot_kmeans_silhouette_analysis.html#sphx-glr-auto-examples-cluster-plot-kmeans-silhouette-analysis-py # Storing average silhouette metric avg_silhouette = [] for nclus in range_clusters: # Skip nclus == 1, start with 2 clusters if n...
_____no_output_____
MIT
notebooks/lab10_kmeans_clustering.ipynb
tiago-oom/Data-Mining-21-22
Final KMeans clustering solution
# final cluster solution number_clusters = 3 kmclust = KMeans(n_clusters=number_clusters, init='k-means++', n_init=15, random_state=1) km_labels = kmclust.fit_predict(df[metric_features]) km_labels # Characterizing the final clusters df_concat = pd.concat((df, pd.Series(km_labels, name='labels')), axis=1) df_concat.gro...
_____no_output_____
MIT
notebooks/lab10_kmeans_clustering.ipynb
tiago-oom/Data-Mining-21-22
Actividad: Realizar un chatbot
from time import sleep def print_words(sentence): for word in sentence.split(): for l in word: sleep(.05) print(l, end = '') print(end = ' ') s1 = 'Hola, bienvenido, mi nombre es Jarvis' print_words(s1) s2 = 'ΒΏCuΓ‘l es tu nombre?' print_words(s2) prompt = ' >> ' nomb...
_____no_output_____
Apache-2.0
Chatbot JARVIS.ipynb
douglasparism/Hello-World
This notebook trains a neural network model to classify images of clothing, like sneakers and shirts. This notebook uses [tf.keras](https://www.tensorflow.org/guide/keras), a high-level API to build and train models in TensorFlow.
try: # %tensorflow_version only exists in Colab. %tensorflow_version 2.x except Exception: pass from __future__ import absolute_import, division, print_function, unicode_literals # TensorFlow and tf.keras import tensorflow as tf from tensorflow import keras # Helper libraries import numpy as np import matplotli...
2.0.0
MIT
Image Classification - Keras TF2.0.ipynb
msunil10052/Image-Classification-1
Import the Fashion MNIST dataset
fashion_mnist = keras.datasets.fashion_mnist (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-labels-idx1-ubyte.gz 32768/29515 [=================================] - 0s 0us/step Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-images-idx3-ubyte.gz 26427392/26421880 [=====================...
MIT
Image Classification - Keras TF2.0.ipynb
msunil10052/Image-Classification-1
Loading the dataset returns four NumPy arrays:* The `train_images` and `train_labels` arrays are the *training set*β€”the data the model uses to learn.* The model is tested against the *test set*, the `test_images`, and `test_labels` arrays.The images are 28x28 NumPy arrays, with pixel values ranging from 0 to 255. The *...
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
_____no_output_____
MIT
Image Classification - Keras TF2.0.ipynb
msunil10052/Image-Classification-1
Explore the dataLet's explore the format of the dataset before training the model. The following shows there are 60,000 images in the training set, with each image represented as 28 x 28 pixels:
train_images.shape
_____no_output_____
MIT
Image Classification - Keras TF2.0.ipynb
msunil10052/Image-Classification-1
Likewise, there are 60,000 labels in the training set:
len(train_labels)
_____no_output_____
MIT
Image Classification - Keras TF2.0.ipynb
msunil10052/Image-Classification-1
Each label is an integer between 0 and 9:
train_labels[0:2]
_____no_output_____
MIT
Image Classification - Keras TF2.0.ipynb
msunil10052/Image-Classification-1
There are 10,000 images in the test set. Again, each image is represented as 28 x 28 pixels:
test_images.shape
_____no_output_____
MIT
Image Classification - Keras TF2.0.ipynb
msunil10052/Image-Classification-1
And the test set contains 10,000 images labels:
len(test_labels)
_____no_output_____
MIT
Image Classification - Keras TF2.0.ipynb
msunil10052/Image-Classification-1
Preprocess the dataThe data must be preprocessed before training the network. If you inspect the first image in the training set, you will see that the pixel values fall in the range of 0 to 255:
plt.figure() plt.imshow(train_images[0]) plt.colorbar() plt.grid(False) plt.show()
_____no_output_____
MIT
Image Classification - Keras TF2.0.ipynb
msunil10052/Image-Classification-1
Scale these values to a range of 0 to 1 before feeding them to the neural network model. To do so, divide the values by 255. It's important that the *training set* and the *testing set* be preprocessed in the same way:
train_images = train_images / 255.0 test_images = test_images / 255.0
_____no_output_____
MIT
Image Classification - Keras TF2.0.ipynb
msunil10052/Image-Classification-1
To verify that the data is in the correct format and that you're ready to build and train the network, let's display the first 25 images from the *training set* and display the class name below each image.
plt.figure(figsize=(10,10)) for i in range(25): plt.subplot(5,5,i+1) plt.xticks([]) plt.yticks([]) plt.grid(False) plt.imshow(train_images[i], cmap=plt.cm.binary) plt.xlabel(class_names[train_labels[i]]) plt.show()
_____no_output_____
MIT
Image Classification - Keras TF2.0.ipynb
msunil10052/Image-Classification-1
Build the modelBuilding the neural network requires configuring the layers of the model, then compiling the model. Set up the layersThe basic building block of a neural network is the *layer*. Layers extract representations from the data fed into them. Hopefully, these representations are meaningful for the problem a...
model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(128, activation='relu'), keras.layers.Dense(10, activation='softmax') ])
_____no_output_____
MIT
Image Classification - Keras TF2.0.ipynb
msunil10052/Image-Classification-1
The first layer in this network, `tf.keras.layers.Flatten`, transforms the format of the images from a two-dimensional array (of 28 by 28 pixels) to a one-dimensional array (of 28 * 28 = 784 pixels). Think of this layer as unstacking rows of pixels in the image and lining them up. This layer has no parameters to learn;...
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
_____no_output_____
MIT
Image Classification - Keras TF2.0.ipynb
msunil10052/Image-Classification-1
Train the modelTraining the neural network model requires the following steps:1. Feed the training data to the model. In this example, the training data is in the `train_images` and `train_labels` arrays.2. The model learns to associate images and labels.3. You ask the model to make predictions about a test setβ€”in thi...
model.fit(train_images, train_labels, epochs=10)
Train on 60000 samples Epoch 1/10 60000/60000 [==============================] - 6s 96us/sample - loss: 0.4973 - accuracy: 0.8264 Epoch 2/10 60000/60000 [==============================] - 5s 76us/sample - loss: 0.3788 - accuracy: 0.8635 Epoch 3/10 60000/60000 [==============================] - 5s 81us/sample - loss: 0....
MIT
Image Classification - Keras TF2.0.ipynb
msunil10052/Image-Classification-1
As the model trains, the loss and accuracy metrics are displayed. This model reaches an accuracy of about 0.88 (or 88%) on the training data. Evaluate accuracyNext, compare how the model performs on the test dataset:
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2) print('\nTest accuracy:', test_acc)
10000/1 - 1s - loss: 0.2432 - accuracy: 0.8808 Test accuracy: 0.8808
MIT
Image Classification - Keras TF2.0.ipynb
msunil10052/Image-Classification-1
It turns out that the accuracy on the test dataset is a little less than the accuracy on the training dataset. This gap between training accuracy and test accuracy represents *overfitting*. Overfitting is when a machine learning model performs worse on new, previously unseen inputs than on the training data. Make pred...
predictions = model.predict(test_images)
_____no_output_____
MIT
Image Classification - Keras TF2.0.ipynb
msunil10052/Image-Classification-1
Here, the model has predicted the label for each image in the testing set. Let's take a look at the first prediction:
predictions[0]
_____no_output_____
MIT
Image Classification - Keras TF2.0.ipynb
msunil10052/Image-Classification-1
A prediction is an array of 10 numbers. They represent the model's "confidence" that the image corresponds to each of the 10 different articles of clothing. You can see which label has the highest confidence value:
np.argmax(predictions[0]) predictions[0]
_____no_output_____
MIT
Image Classification - Keras TF2.0.ipynb
msunil10052/Image-Classification-1
So, the model is most confident that this image is an ankle boot, or `class_names[9]`. Examining the test label shows that this classification is correct:
test_labels[0]
_____no_output_____
MIT
Image Classification - Keras TF2.0.ipynb
msunil10052/Image-Classification-1
Graph this to look at the full set of 10 class predictions.
def plot_image(i, predictions_array, true_label, img): predictions_array, true_label, img = predictions_array, true_label[i], img[i] plt.grid(False) plt.xticks([]) plt.yticks([]) plt.imshow(img, cmap=plt.cm.binary) predicted_label = np.argmax(predictions_array) if predicted_label == true_label: colo...
_____no_output_____
MIT
Image Classification - Keras TF2.0.ipynb
msunil10052/Image-Classification-1
Let's look at the 0th image, predictions, and prediction array. Correct prediction labels are blue and incorrect prediction labels are red. The number gives the percentage (out of 100) for the predicted label.
i = 0 plt.figure(figsize=(6,3)) plt.subplot(1,2,1) plot_image(i, predictions[i], test_labels, test_images) plt.subplot(1,2,2) plot_value_array(i, predictions[i], test_labels) plt.show() i = 12 plt.figure(figsize=(6,3)) plt.subplot(1,2,1) plot_image(i, predictions[i], test_labels, test_images) plt.subplot(1,2,2) plot_v...
_____no_output_____
MIT
Image Classification - Keras TF2.0.ipynb
msunil10052/Image-Classification-1
Let's plot several images with their predictions. Note that the model can be wrong even when very confident.
# Plot the first X test images, their predicted labels, and the true labels. # Color correct predictions in blue and incorrect predictions in red. num_rows = 5 num_cols = 3 num_images = num_rows*num_cols plt.figure(figsize=(2*2*num_cols, 2*num_rows)) for i in range(num_images): plt.subplot(num_rows, 2*num_cols, 2*i+1...
_____no_output_____
MIT
Image Classification - Keras TF2.0.ipynb
msunil10052/Image-Classification-1
Finally, use the trained model to make a prediction about a single image.
# Grab an image from the test dataset. img = test_images[1] print(img.shape)
(28, 28)
MIT
Image Classification - Keras TF2.0.ipynb
msunil10052/Image-Classification-1
`tf.keras` models are optimized to make predictions on a *batch*, or collection, of examples at once. Accordingly, even though you're using a single image, you need to add it to a list:
# Add the image to a batch where it's the only member. img = (np.expand_dims(img,0)) print(img.shape)
(1, 28, 28)
MIT
Image Classification - Keras TF2.0.ipynb
msunil10052/Image-Classification-1
Now predict the correct label for this image:
predictions_single = model.predict(img) print(predictions_single) plot_value_array(1, predictions_single[0], test_labels) _ = plt.xticks(range(10), class_names, rotation=45)
_____no_output_____
MIT
Image Classification - Keras TF2.0.ipynb
msunil10052/Image-Classification-1
`model.predict` returns a list of listsβ€”one list for each image in the batch of data. Grab the predictions for our (only) image in the batch:
np.argmax(predictions_single[0])
_____no_output_____
MIT
Image Classification - Keras TF2.0.ipynb
msunil10052/Image-Classification-1
And the model predicts a label as expected.
_____no_output_____
MIT
Image Classification - Keras TF2.0.ipynb
msunil10052/Image-Classification-1
Links to intermediate files Click on the hyperlinks below to see the intermediate experiment files generated as part of this experiment.
from rsmtool.utils.notebook import show_files show_files(output_dir, experiment_id, file_format)
_____no_output_____
Apache-2.0
rsmtool/notebooks/intermediate_file_paths.ipynb
srhrshr/rsmtool
Chapter 4: Classes and MethodsSo far, we have dealt only with functions. Functions are convenient because they generalize some exercise given a certain type of input. In the last chapter we created a function that takes the mean value of a list of elements. It may be useful to create a function that is not owned by a ...
#arithmetic.py # you may ignore import jdc, used to split class development # other cells that edits a class will include the magic command %% add_to import jdc class Arithmetic(): def __init__(self): pass
_____no_output_____
MIT
.ipynb_checkpoints/ Chapter 4 - Classes and Methods-checkpoint.ipynb
hunterluepke/Learn-Python-for-Stats-and-Econ
We can create an object that is an instance of the class. At the bottom of the script, add:
arithmetic = Arithmetic() print(arithmetic)
<__main__.Arithmetic object at 0x0000022F00CAF470>
MIT
.ipynb_checkpoints/ Chapter 4 - Classes and Methods-checkpoint.ipynb
hunterluepke/Learn-Python-for-Stats-and-Econ