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
Imports
import os import re import cv2 import time import tensorflow import collections import numpy as np import pandas as pd from tqdm import tqdm from glob import glob from PIL import Image import requests, threading import matplotlib.pyplot as plt from datetime import datetime, timedelta import torch import torchvision im...
_____no_output_____
MIT
image/2. Flower Classification with TPUs/kaggle/fast-pytorch-xla-for-tpu-with-multiprocessing.ipynb
nishchalnishant/Completed_Kaggle_competitions
Dataset
DATASET_DIR = '/kaggle/input/104-flowers-garden-of-eden/jpeg-512x512' TRAIN_DIR = DATASET_DIR + '/train' VAL_DIR = DATASET_DIR + '/val' TEST_DIR = DATASET_DIR + '/test' BATCH_SIZE = 16 # per core NUM_EPOCH = 25 normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225]) train_transform = ...
Num training images: 16465 Num test images: 3712
MIT
image/2. Flower Classification with TPUs/kaggle/fast-pytorch-xla-for-tpu-with-multiprocessing.ipynb
nishchalnishant/Completed_Kaggle_competitions
Model
class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.base_model = torchvision.models.densenet201(pretrained=True) self.base_model.classifier = nn.Identity() self.fc = torch.nn.Sequential( torch.nn.Linear(1920, 1024, bias = T...
Downloading: "https://download.pytorch.org/models/densenet201-c1103571.pth" to /root/.cache/torch/checkpoints/densenet201-c1103571.pth
MIT
image/2. Flower Classification with TPUs/kaggle/fast-pytorch-xla-for-tpu-with-multiprocessing.ipynb
nishchalnishant/Completed_Kaggle_competitions
Training
def train_model(): train = datasets.ImageFolder(TRAIN_DIR, transform=train_transform) valid = datasets.ImageFolder(VAL_DIR, transform=train_transform) train = torch.utils.data.ConcatDataset([train, valid]) torch.manual_seed(42) train_sampler = torch.utils.data.distributed.DistributedSample...
Train for 128 steps per epoch [xla:1](0) Loss=4.989 Rate=0.89 GlobalRate=0.89 [xla:3](0) Loss=4.780 Rate=0.81 GlobalRate=0.81 [xla:4](0) Loss=4.716 Rate=0.81 GlobalRate=0.81 [xla:2](0) Loss=4.723 Rate=0.69 GlobalRate=0.69 [xla:7](0) Loss=4.702 Rate=0.83 GlobalRate=0.83 [xla:0](0) Loss=4.785 Rate=0.57 GlobalRate=0.57 [x...
MIT
image/2. Flower Classification with TPUs/kaggle/fast-pytorch-xla-for-tpu-with-multiprocessing.ipynb
nishchalnishant/Completed_Kaggle_competitions
R06725035 陳廷易* Tokenization.* Lowercasing everything.* Stemming using Porter’s algorithm.* Stopword removal.* Save the result as a txt file.
# import keras # from keras.preprocessing.text import Tokenizer # import gensim import nltk from nltk.corpus import stopwords from nltk.tokenize import wordpunct_tokenize from nltk import word_tokenize from nltk.stem.porter import * from nltk.tokenize import RegexpTokenizer # nltk.download('all')
[nltk_data] Downloading collection 'all' [nltk_data] | [nltk_data] | Downloading package abc to [nltk_data] | /home/leoqaz12/nltk_data... [nltk_data] | Package abc is already up-to-date! [nltk_data] | Downloading package alpino to [nltk_data] | /home/leoqaz12/nltk_data... [nltk_data] | ...
MIT
preprocessing/ExtractTerms.ipynb
tychen5/IR_TextMining
read data
file = open('data/28.txt','r') texts = file.read() file.close() texts
_____no_output_____
MIT
preprocessing/ExtractTerms.ipynb
tychen5/IR_TextMining
main preprocessing
with open('data/stop_words.txt') as f: stop_words_list = f.read().splitlines() ps = PorterStemmer() # Stemming stop_words = set(stopwords.words('english')) #Stopword short = ['.', ',', '"', "'", '?', '!', ':', ';', '(', ')', '[', ']', '{', '}', '\'s','\'m','\'re','\'ll','\'d','n\'t','shan\'t'] st...
_____no_output_____
MIT
preprocessing/ExtractTerms.ipynb
tychen5/IR_TextMining
Output
# output="" # for token in tokens: # output+=token+' ' # print(output) file = open('result/output.txt','w') file.write(token_result) #Save the result file.close() print(token_result) # tokenizer = Tokenizer() # tokenizer.fit_on_texts(texts) # print(tokenizer.sequences_to_texts())
_____no_output_____
MIT
preprocessing/ExtractTerms.ipynb
tychen5/IR_TextMining
FunctionsThink of mathematical functions...> 8 -------> 16> 10 ------> 20> 0.5 ------> 1Thus, the function of course is `f(x) = 2x`, which is a function f that doubles whatever input. What if we could write a doubling function too?
def f(x): return 2*x print(f(8)) print(f(10)) print(f(0.5))
_____no_output_____
MIT
19T2/2_review/functions.ipynb
photomz/learn-python3
Programmatic functions can do a lot more. For example:
def is_even(x): return not x % 2 print(is_even(100)) print(is_even(7)) def calculate_interest(principal=100,rate=0.05,year=5): # principal = initial amount, rate = interest rate, year = number of years compounded = principal for i in range(year): compounded = compounded * (1+rate) year =...
_____no_output_____
MIT
19T2/2_review/functions.ipynb
photomz/learn-python3
Prepare dataset for hiveplotThis notebook currently just exports a subset of the nodes to a DOT file for import into [`jhive`](https://www.bcgsc.ca/wiki/display/jhive/Documentation).
import random import pandas import networkx from networkx.drawing.nx_pydot import write_dot node_df = pandas.read_table('../../data/nodes.tsv') edge_df = pandas.read_table('../../data/edges.sif.gz') node_df.head(2) edge_df.head(2) graph = networkx.MultiGraph() # No colons allowed. See https://github.com/carlos-jenki...
_____no_output_____
CC0-1.0
viz/auto/3-hiveplot.ipynb
dhimmel/integrate
Normalizing the data
colsList = ["actual_area", "poolcnt", "latitude", "longitude", "unitcnt", "lotsizesquarefeet", "bedroomcnt", "calculatedbathnbr", "hashottuborspa", "fireplacecnt", "taxvaluedollarcnt", "b...
-0.130731 47739 -0.199816 8968 -0.249310 7211 -0.323551 7111 -0.447286 6024 -0.364796 5956 -0.385418 5837 -0.406041 5436 -0.298804 5319 -0.220439 4743 -0.348298 4685 -0.292617 4658 -0.261684 4585 -0.302929 4520 -0.271995 4478 -0.274057 4281 ...
Apache-2.0
HW3/HW3.ipynb
jay-z007/Data-Science-Fundamentals
Analytical Hierarchical Processing
rel_imp_matrix = pd.read_csv("rel_imp_matrix.csv", index_col=0) # rel_imp_matrix import fractions for col in rel_imp_matrix.columns.values: temp_list = rel_imp_matrix[col].tolist() rel_imp_matrix[col] = [float(fractions.Fraction(x)) for x in temp_list] # data = [float(fractions.Fraction(x)) for x in...
_____no_output_____
Apache-2.0
HW3/HW3.ipynb
jay-z007/Data-Science-Fundamentals
SAW
sum_series = pd.Series(0, index=prop_data_ahp.index,dtype='float32') for col in prop_data_ahp.columns: sum_series = sum_series+ prop_data_ahp[col] * ahp_column_score[col] prop_data_ahp["sum"] = sum_series.astype('float32') prop_data_ahp["sum"] # prop_data_ahp["sum"] = prop_data_ahp.sum(axis=1) prop_data_ahp["...
_____no_output_____
Apache-2.0
HW3/HW3.ipynb
jay-z007/Data-Science-Fundamentals
Distance MetricWe will be using weighted Manhattan distance as a distance metric
dist_imp_matrix = pd.read_csv("./dist_metric.csv", index_col=0) dist_imp_matrix import fractions for col in dist_imp_matrix.columns.values: temp_list = dist_imp_matrix[col].tolist() dist_imp_matrix[col] = [float(fractions.Fraction(x)) for x in temp_list] # dist_imp_matrix for col in dist_imp_matrix.colu...
_____no_output_____
Apache-2.0
HW3/HW3.ipynb
jay-z007/Data-Science-Fundamentals
A Crypto-Arithmetic Puzzle In this exercise we will solve the crypto-arithmetic puzzle shown in the picture below: The idea is that the letters "$\texttt{S}$", "$\texttt{E}$", "$\texttt{N}$", "$\texttt{D}$", "$\texttt{M}$", "$\texttt{O}$", "$\texttt{R}$", "$\texttt{Y}$" occurring in this puzzleare interpreted as varia...
import cspSolver
_____no_output_____
MIT
Python/Exercises/Blatt-13.ipynb
BuserLukas/Logic
For a set $V$ of variables, the function $\texttt{allDifferent}(V)$ generates a set of formulas that express that all the variables of $V$ are different.
def allDifferent(Variables): return { f'{x} != {y}' for x in Variables for y in Variables if x < y } allDifferent({ 'a', 'b', 'c' })
_____no_output_____
MIT
Python/Exercises/Blatt-13.ipynb
BuserLukas/Logic
Pause bis 14:23
def createCSP(): Variables = "your code here" Values = "your code here" Constraints = "much more code here" return [Variables, Values, Constraints]; puzzle = createCSP() puzzle %%time solution = cspSolver.solve(puzzle) print(f'Time needed: {round((stop-start) * 1000)} milliseconds.')...
_____no_output_____
MIT
Python/Exercises/Blatt-13.ipynb
BuserLukas/Logic
Solution based on Multiple Models
import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all"
_____no_output_____
MIT
3. NLP/AZ/Text Classification/Models_Template.ipynb
AmirRazaMBA/TensorFlow-Certification
Tokenize and Numerize - Make it ready
training_size = 20000 training_sentences = sentences[0:training_size] testing_sentences = sentences[training_size:] training_labels = labels[0:training_size] testing_labels = labels[training_size:] vocab_size = 1000 max_length = 120 embedding_dim = 16 trunc_type='post' padding_type='post' oov_tok = "<OOV>" toke...
_____no_output_____
MIT
3. NLP/AZ/Text Classification/Models_Template.ipynb
AmirRazaMBA/TensorFlow-Certification
Plot
def plot_graphs(history, string): plt.plot(history.history[string]) plt.plot(history.history['val_'+string]) plt.xlabel("Epochs") plt.ylabel(string) plt.legend([string, 'val_'+string]) plt.show() plot_graphs(history, "accuracy") plot_graphs(history, "loss")
_____no_output_____
MIT
3. NLP/AZ/Text Classification/Models_Template.ipynb
AmirRazaMBA/TensorFlow-Certification
Function to train and show
def fit_model_and_show_results (model, reviews): model.summary() history = model.fit(training_padded, training_labels_final, epochs=num_epochs, validation_data=(validation_padded, validation_labels_final)) plot_graphs(history, "accuracy") plot...
_____no_output_____
MIT
3. NLP/AZ/Text Classification/Models_Template.ipynb
AmirRazaMBA/TensorFlow-Certification
ANN Embedding
model = tf.keras.Sequential([ tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length), tf.keras.layers.GlobalAveragePooling1D(), tf.keras.layers.Dense(1, activation='sigmoid') ]) model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy']) model.summary() num_epoch...
_____no_output_____
MIT
3. NLP/AZ/Text Classification/Models_Template.ipynb
AmirRazaMBA/TensorFlow-Certification
CNN
num_epochs = 30 model_cnn = tf.keras.Sequential([ tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length), tf.keras.layers.Conv1D(16, 5, activation='relu'), tf.keras.layers.GlobalMaxPooling1D(), tf.keras.layers.Dense(1, activation='sigmoid') ]) # Default learning rate for the Adam ...
_____no_output_____
MIT
3. NLP/AZ/Text Classification/Models_Template.ipynb
AmirRazaMBA/TensorFlow-Certification
GRU
num_epochs = 30 model_gru = tf.keras.Sequential([ tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length), tf.keras.layers.Bidirectional(tf.keras.layers.GRU(32)), tf.keras.layers.Dense(1, activation='sigmoid') ]) learning_rate = 0.00003 # slower than the default learning rate model_gru...
_____no_output_____
MIT
3. NLP/AZ/Text Classification/Models_Template.ipynb
AmirRazaMBA/TensorFlow-Certification
Bidirectional LSTM
num_epochs = 30 model_bidi_lstm = tf.keras.Sequential([ tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length), tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(embedding_dim)), tf.keras.layers.Dense(1, activation='sigmoid') ]) learning_rate = 0.00003 model_bidi_lstm.compile(loss='...
_____no_output_____
MIT
3. NLP/AZ/Text Classification/Models_Template.ipynb
AmirRazaMBA/TensorFlow-Certification
Multiple bidirectional LSTMs
num_epochs = 30 model_multiple_bidi_lstm = tf.keras.Sequential([ tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length), tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(embedding_dim, return_sequences=True)), tf.keras.layers.B...
_____no_output_____
MIT
3. NLP/AZ/Text Classification/Models_Template.ipynb
AmirRazaMBA/TensorFlow-Certification
Prediction Define a function to prepare the new reviews for use with a modeland then use the model to predict the sentiment of the new reviews
def predict_review(model, reviews): # Create the sequences padding_type='post' sample_sequences = tokenizer.texts_to_sequences(reviews) reviews_padded = pad_sequences(sample_sequences, padding=padding_type, maxlen=max_length) classes = ...
_____no_output_____
MIT
3. NLP/AZ/Text Classification/Models_Template.ipynb
AmirRazaMBA/TensorFlow-Certification
How to use examples more_reviews = [review1, review2, review3, review4, review5, review6, review7, review8, review9, review10]predict_review(model, new_reviews)
print("============================\n","Embeddings only:\n", "============================") predict_review(model, more_reviews) print("============================\n","With CNN\n", "============================") predict_review(model_cnn, more_reviews) print("===========================\n","With bidirectional GRU\n", ...
_____no_output_____
MIT
3. NLP/AZ/Text Classification/Models_Template.ipynb
AmirRazaMBA/TensorFlow-Certification
1. Install DependenciesFirst install the libraries needed to execute recipes, this only needs to be done once, then click play.
!pip install git+https://github.com/google/starthinker
_____no_output_____
Apache-2.0
colabs/dv360_data_warehouse.ipynb
arbrown/starthinker
2. Get Cloud Project IDTo run this recipe [requires a Google Cloud Project](https://github.com/google/starthinker/blob/master/tutorials/cloud_project.md), this only needs to be done once, then click play.
CLOUD_PROJECT = 'PASTE PROJECT ID HERE' print("Cloud Project Set To: %s" % CLOUD_PROJECT)
_____no_output_____
Apache-2.0
colabs/dv360_data_warehouse.ipynb
arbrown/starthinker
3. Get Client CredentialsTo read and write to various endpoints requires [downloading client credentials](https://github.com/google/starthinker/blob/master/tutorials/cloud_client_installed.md), this only needs to be done once, then click play.
CLIENT_CREDENTIALS = 'PASTE CLIENT CREDENTIALS HERE' print("Client Credentials Set To: %s" % CLIENT_CREDENTIALS)
_____no_output_____
Apache-2.0
colabs/dv360_data_warehouse.ipynb
arbrown/starthinker
4. Enter DV360 Data Warehouse ParametersDeploy a BigQuery dataset mirroring DV360 account structure. Foundation for solutions on top. 1. Wait for BigQuery->->->* to be created. 1. Every table mimics the DV360 API Endpoints.Modify the values below for your use case, can be done multiple times, then click play.
FIELDS = { 'auth_bigquery': 'service', # Credentials used for writing data. 'auth_dv': 'service', # Credentials used for reading data. 'auth_cm': 'service', # Credentials used for reading data. 'recipe_slug': '', # Name of Google BigQuery dataset to create. 'partners': [], # List of account ids to pull. ...
_____no_output_____
Apache-2.0
colabs/dv360_data_warehouse.ipynb
arbrown/starthinker
5. Execute DV360 Data WarehouseThis does NOT need to be modified unless you are changing the recipe, click play.
from starthinker.util.configuration import Configuration from starthinker.util.configuration import execute from starthinker.util.recipe import json_set_fields USER_CREDENTIALS = '/content/user.json' TASKS = [ { 'dataset': { 'description': 'Create a dataset for bigquery tables.', 'hour': [ 4...
_____no_output_____
Apache-2.0
colabs/dv360_data_warehouse.ipynb
arbrown/starthinker
Tutorial on Python for scientific computingMarcos Duarte This tutorial is a short introduction to programming and a demonstration of the basic features of Python for scientific computing. To use Python for scientific computing we need the Python program itself with its main modules and specific packages for scientific...
1 + 2 - 30 4/5
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
If you are using Python version 2.x instead of Python 3.x, you should have got 0 as the result of 4 divided by 5, which is wrong! The problem is that for Python versions up to 2.x, the operator '/' performs division with integers and the result will also be an integer (this behavior was changed in version 3.x). If you...
4/5. from __future__ import division 4/5
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
I prefer to use the import division option (from future!); if we put this statement in the beginning of a file or IPython notebook, it will work for all subsequent commands.Another command that changed its behavior from Python 2.x to 3.x is the `print` command. In Python 2.x, the print command could be used as a stat...
print 4/5
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
With Python 3.x, the print command bahaves as a true function and has to be called with parentheses. Let's also import this future command to Python 2.x and use it from now on:
from __future__ import print_function print(4/5)
0.8
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
With the `print` function, let's explore the mathematical operations available in Python:
print('1+2 = ', 1+2, '\n', '4*5 = ', 4*5, '\n', '6/7 = ', 6/7, '\n', '8**2 = ', 8**2, sep='')
1+2 = 3 4*5 = 20 6/7 = 0.8571428571428571 8**2 = 64
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
And if we want the square-root of a number:
sqrt(9)
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
We get an error message saying that the `sqrt` function if not defined. This is because `sqrt` and other mathematical functions are available with the `math` module:
import math math.sqrt(9) from math import sqrt sqrt(9)
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
The import functionWe used the command '`import`' to be able to call certain functions. In Python functions are organized in modules and packages and they have to be imported in order to be used. A module is a file containing Python definitions (e.g., functions) and statements. Packages are a way of structuring Pyth...
import sys sys.version
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
And if you are in an IPython session:
from IPython import sys_info print(sys_info())
{'commit_hash': '681fd77', 'commit_source': 'installation', 'default_encoding': 'cp1252', 'ipython_path': 'C:\\Anaconda3\\lib\\site-packages\\IPython', 'ipython_version': '2.1.0', 'os_name': 'nt', 'platform': 'Windows-7-6.1.7601-SP1', 'sys_executable': 'C:\\Anaconda3\\python.exe', 'sys_platform': 'win32', 'sys...
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
The first option gives information about the Python version; the latter also includes the IPython version, operating system, etc. Object-oriented programmingPython is designed as an object-oriented programming (OOP) language. OOP is a paradigm that represents concepts as "objects" that have data fields (attributes tha...
help(math.degrees)
Help on built-in function degrees in module math: degrees(...) degrees(x) Convert angle x from radians to degrees.
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Or if you are in the IPython environment, simply add '?' to the function that a window will open at the bottom of your browser with the same help content:
math.degrees?
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
And if you add a second '?' to the statement you get access to the original script file of the function (an advantage of an open source language), unless that function is a built-in function that does not have a script file, which is the case of the standard modules in Python (but you can access the Python source code ...
import scipy.fftpack scipy.fftpack.fft??
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
To know all the attributes of an object, for example all the functions available in `math`, we can use the function `dir`:
print(dir(math))
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isfinite', 'isinf', 'isnan', 'ldexp', '...
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Tab completion in IPythonIPython has tab completion: start typing the name of the command (object) and press `tab` to see the names of objects available with these initials letters. When the name of the object is typed followed by a dot (`math.`), pressing `tab` will show all available attribites, scroll down to the d...
# Import the math library to access more math stuff import math math.pi # this is the pi constant; a useless comment since this is obvious
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
To insert comments spanning more than one line, use a multi-line string with a pair of matching triple-quotes: `"""` or `'''` (we will see the string data type later). A typical use of a multi-line comment is as documentation strings and are meant for anyone reading the code:
"""Documentation strings are typically written like that. A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. """
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
A docstring like above is useless and its output as a standalone statement looks uggly in IPython Notebook, but you will see its real importance when reading and writting codes.Commenting a programming code is an important step to make the code more readable, which Python cares a lot. There is a style guide for writt...
x = 1
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Spaces between the statements are optional but it helps for readability.To see the value of the variable, call it again or use the print function:
x print(x)
1
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Of course, the last assignment is that holds:
x = 2 x = 3 x
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
In mathematics '=' is the symbol for identity, but in computer programming '=' is used for assignment, it means that the right part of the expresssion is assigned to its left part. For example, 'x=x+1' does not make sense in mathematics but it does in computer programming:
x = 1 print(x) x = x + 1 print(x)
1 2
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
A value can be assigned to several variables simultaneously:
x = y = 4 print(x) print(y)
4 4
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Several values can be assigned to several variables at once:
x, y = 5, 6 print(x) print(y)
5 6
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
And with that, you can do (!):
x, y = y, x print(x) print(y)
6 5
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Variables must be “defined” (assigned a value) before they can be used, or an error will occur:
x = z
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Variables and typesThere are different types of built-in objects in Python (and remember that everything in Python is an object):
import types print(dir(types))
['BuiltinFunctionType', 'BuiltinMethodType', 'CodeType', 'DynamicClassAttribute', 'FrameType', 'FunctionType', 'GeneratorType', 'GetSetDescriptorType', 'LambdaType', 'MappingProxyType', 'MemberDescriptorType', 'MethodType', 'ModuleType', 'SimpleNamespace', 'TracebackType', '__builtins__', '__cached__', '__doc__', '__fi...
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Let's see some of them now. Numbers: int, float, complexNumbers can an integer (int), float, and complex (with imaginary part). Let's use the function `type` to show the type of number (and later for any other object):
type(6)
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
A float is a non-integer number:
math.pi type(math.pi)
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Python (IPython) is showing `math.pi` with only 15 decimal cases, but internally a float is represented with higher precision. Floating point numbers in Python are implemented using a double (eight bytes) word; the precison and internal representation of floating point numbers are machine specific and are available i...
sys.float_info
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Be aware that floating-point numbers can be trick in computers:
0.1 + 0.2 0.1 + 0.2 - 0.3
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
These results are not correct (and the problem is not due to Python). The error arises from the fact that floating-point numbers are represented in computer hardware as base 2 (binary) fractions and most decimal fractions cannot be represented exactly as binary fractions. As consequence, decimal floating-point numbers ...
1+2j print(type(1+2j))
<class 'complex'>
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Each part of a complex number is represented as a floating-point number. We can see them using the attributes `.real` and `.imag`:
print((1+2j).real) print((1+2j).imag)
1.0 2.0
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
StringsStrings can be enclosed in single quotes or double quotes:
s = 'string (str) is a built-in type in Python' s type(s)
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
String enclosed with single and double quotes are equal, but it may be easier to use one instead of the other:
'string (str) is a Python's built-in type' "string (str) is a Python's built-in type"
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
But you could have done that using the Python escape character '\':
'string (str) is a Python\'s built-in type'
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Strings can be concatenated (glued together) with the + operator, and repeated with *:
s = 'P' + 'y' + 't' + 'h' + 'o' + 'n' print(s) print(s*5)
Python PythonPythonPythonPythonPython
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Strings can be subscripted (indexed); like in C, the first character of a string has subscript (index) 0:
print('s[0] = ', s[0], ' (s[index], start at 0)') print('s[5] = ', s[5]) print('s[-1] = ', s[-1], ' (last element)') print('s[:] = ', s[:], ' (all elements)') print('s[1:] = ', s[1:], ' (from this index (inclusive) till the last (inclusive))') print('s[2:4] = ', s[2:4], ' (from first index (inclusive) till second ...
s[0] = P (s[index], start at 0) s[5] = n s[-1] = n (last element) s[:] = Python (all elements) s[1:] = ython (from this index (inclusive) till the last (inclusive)) s[2:4] = th (from first index (inclusive) till second index (exclusive)) s[:2] = Py (till this index, exclusive) s[:10] = Python (Pyt...
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
len()Python has a built-in functon to get the number of itens of a sequence:
help(len) s = 'Python' len(s)
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
The function len() helps to understand how the backward indexing works in Python. The index s[-i] should be understood as s[len(s) - i] rather than accessing directly the i-th element from back to front. This is why the last element of a string is s[-1]:
print('s = ', s) print('len(s) = ', len(s)) print('len(s)-1 = ',len(s) - 1) print('s[-1] = ', s[-1]) print('s[len(s) - 1] = ', s[len(s) - 1])
s = Python len(s) = 6 len(s)-1 = 5 s[-1] = n s[len(s) - 1] = n
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Or, strings can be surrounded in a pair of matching triple-quotes: """ or '''. End of lines do not need to be escaped when using triple-quotes, but they will be included in the string. This is how we created a multi-line comment earlier:
"""Strings can be surrounded in a pair of matching triple-quotes: \""" or '''. End of lines do not need to be escaped when using triple-quotes, but they will be included in the string. """
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
ListsValues can be grouped together using different types, one of them is list, which can be written as a list of comma-separated values between square brackets. List items need not all have the same type:
x = ['spam', 'eggs', 100, 1234] x
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Lists can be indexed and the same indexing rules we saw for strings are applied:
x[0]
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
The function len() works for lists:
len(x)
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
TuplesA tuple consists of a number of values separated by commas, for instance:
t = ('spam', 'eggs', 100, 1234) t
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
The type tuple is why multiple assignments in a single line works; elements separated by commas (with or without surrounding parentheses) are a tuple and in an expression with an '=', the right-side tuple is attributed to the left-side tuple:
a, b = 1, 2 print('a = ', a, '\nb = ', b)
a = 1 b = 2
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Is the same as:
(a, b) = (1, 2) print('a = ', a, '\nb = ', b)
a = 1 b = 2
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
SetsPython also includes a data type for sets. A set is an unordered collection with no duplicate elements.
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] fruit = set(basket) # create a set without duplicates fruit
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
As set is an unordered collection, it can not be indexed as lists and tuples.
set(['orange', 'pear', 'apple', 'banana']) 'orange' in fruit # fast membership testing
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
DictionariesDictionary is a collection of elements organized keys and values. Unlike lists and tuples, which are indexed by a range of numbers, dictionaries are indexed by their keys:
tel = {'jack': 4098, 'sape': 4139} tel tel['guido'] = 4127 tel tel['jack'] del tel['sape'] tel['irv'] = 4127 tel tel.keys() 'guido' in tel
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
The dict() constructor builds dictionaries directly from sequences of key-value pairs:
tel = dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) tel
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Built-in Constants- **False** : false value of the bool type- **True** : true value of the bool type- **None** : sole value of types.NoneType. None is frequently used to represent the absence of a value. In computer science, the Boolean or logical data type is composed by two values, true and false, intended to repres...
True == False not True == False 1 < 2 > 1 True != (False or True) True != False or True
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Indentation and whitespaceIn Python, statement grouping is done by indentation (this is mandatory), which are done by inserting whitespaces, not tabs. Indentation is also recommended for alignment of function calling that span more than one line for better clarity. We will see examples of indentation in the next ses...
if True: pass
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Which does nothing useful. Let's use the `if`...`elif`...`else` statements to categorize the [body mass index](http://en.wikipedia.org/wiki/Body_mass_index) of a person:
# body mass index weight = 100 # kg height = 1.70 # m bmi = weight / height**2 if bmi < 15: c = 'very severely underweight' elif 15 <= bmi < 16: c = 'severely underweight' elif 16 <= bmi < 18.5: c = 'underweight' elif 18.5 <= bmi < 25: c = 'normal' elif 25 <= bmi < 30: c = 'overweight' elif 30 <= ...
For a weight of 100.0 kg and a height of 1.70 m, the body mass index (bmi) is 34.6 kg/m2, which is considered moderately obese.
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
forThe `for` statement iterates over a sequence to perform operations (a loop event).```for iterating_var in sequence: statements```
for i in [3, 2, 1, 'go!']: print(i), for letter in 'Python': print(letter),
P y t h o n
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
The `range()` functionThe built-in function range() is useful if we need to create a sequence of numbers, for example, to iterate over this list. It generates lists containing arithmetic progressions:
help(range) range(10) range(1, 10, 2) for i in range(10): n2 = i**2 print(n2),
0 1 4 9 16 25 36 49 64 81
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
whileThe `while` statement is used for repeating sections of code in a loop until a condition is met (this different than the `for` statement which executes n times):```while expression: statement```Let's generate the Fibonacci series using a `while` loop:
# Fibonacci series: the sum of two elements defines the next a, b = 0, 1 while b < 1000: print(b, end=' ') a, b = b, a+b
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Function definitionA function in a programming language is a piece of code that performs a specific task. Functions are used to reduce duplication of code making easier to reuse it and to decompose complex problems into simpler parts. The use of functions contribute to the clarity of the code.A function is created wit...
def function(): pass
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
As per construction, this function does nothing when called:
function()
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
The general syntax of a function definition is:```def function_name( parameters ): """Function docstring. The help for the function """ function body return variables```A more useful function:
def fibo(N): """Fibonacci series: the sum of two elements defines the next. The series is calculated till the input parameter N and returned as an ouput variable. """ a, b, c = 0, 1, [] while b < N: c.append(b) a, b = b, a + b return c fibo(100) if 3 >...
teste
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Let's implemment the body mass index calculus and categorization as a function:
def bmi(weight, height): """Body mass index calculus and categorization. Enter the weight in kg and the height in m. See http://en.wikipedia.org/wiki/Body_mass_index """ bmi = weight / height**2 if bmi < 15: c = 'very severely underweight' elif 15 <= bmi < 16: ...
For a weight of 73.0 kg and a height of 1.70 m, the body mass index (bmi) is 25.3 kg/m2, which is considered overweight.
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Numeric data manipulation with NumpyNumpy is the fundamental package for scientific computing in Python and has a N-dimensional array package convenient to work with numerical data. With Numpy it's much easier and faster to work with numbers grouped as 1-D arrays (a vector), 2-D arrays (like a table or matrix), or hig...
import numpy as np x1d = np.array([1, 2, 3, 4, 5, 6]) print(type(x1d)) x1d x2d = np.array([[1, 2, 3], [4, 5, 6]]) x2d
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
len() and the Numpy functions size() and shape() give information aboout the number of elements and the structure of the Numpy array:
print('1-d array:') print(x1d) print('len(x1d) = ', len(x1d)) print('np.size(x1d) = ', np.size(x1d)) print('np.shape(x1d) = ', np.shape(x1d)) print('np.ndim(x1d) = ', np.ndim(x1d)) print('\n2-d array:') print(x2d) print('len(x2d) = ', len(x2d)) print('np.size(x2d) = ', np.size(x2d)) print('np.shape(x2d) = ', np.shape(x...
1-d array: [1 2 3 4 5 6] len(x1d) = 6 np.size(x1d) = 6 np.shape(x1d) = (6,) np.ndim(x1d) = 1 2-d array: [[1 2 3] [4 5 6]] len(x2d) = 2 np.size(x2d) = 6 np.shape(x2d) = (2, 3) np.ndim(x2d) = 2
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Create random data
x = np.random.randn(4,3) x
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Joining (stacking together) arrays
x = np.random.randint(0, 5, size=(2, 3)) print(x) y = np.random.randint(5, 10, size=(2, 3)) print(y) np.vstack((x,y)) np.hstack((x,y))
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Create equally spaced data
np.arange(start = 1, stop = 10, step = 2) np.linspace(start = 0, stop = 1, num = 11)
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
InterpolationConsider the following data:
y = [5, 4, 10, 8, 1, 10, 2, 7, 1, 3]
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Suppose we want to create data in between the given data points (interpolation); for instance, let's try to double the resolution of the data by generating twice as many data:
t = np.linspace(0, len(y), len(y)) # time vector for the original data tn = np.linspace(0, len(y), 2 * len(y)) # new time vector for the new time-normalized data yn = np.interp(tn, t, y) # new time-normalized data yn
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
The key is the Numpy `interp` function, from its help: interp(x, xp, fp, left=None, right=None) One-dimensional linear interpolation. Returns the one-dimensional piecewise linear interpolant to a function with given values at discrete data-points.A plot of the data will show what we have done:
%matplotlib inline import matplotlib.pyplot as plt plt.figure(figsize=(10,5)) plt.plot(t, y, 'bo-', lw=2, label='original data') plt.plot(tn, yn, '.-', color=[1, 0, 0, .5], lw=2, label='interpolated') plt.legend(loc='best', framealpha=.5) plt.show()
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC