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
This dataset contains measurements taken on penguins. We will formulate thefollowing problem: using the flipper length of a penguin, we would liketo infer its mass.
import seaborn as sns feature_names = "Flipper Length (mm)" target_name = "Body Mass (g)" data, target = penguins[[feature_names]], penguins[target_name] ax = sns.scatterplot(data=penguins, x=feature_names, y=target_name) ax.set_title("Flipper length in function of the body mass")
_____no_output_____
CC-BY-4.0
notebooks/linear_regression_without_sklearn.ipynb
brospars/scikit-learn-mooc
TipThe function scatterplot from searborn take as input the full dataframeand the parameter x and y allows to specify the name of the columns tobe plotted. Note that this function returns a matplotlib axis(named ax in the example above) that can be further used to add element onthe same matplotlib axis (such as a title...
def linear_model_flipper_mass(flipper_length, weight_flipper_length, intercept_body_mass): """Linear model of the form y = a * x + b""" body_mass = weight_flipper_length * flipper_length + intercept_body_mass return body_mass
_____no_output_____
CC-BY-4.0
notebooks/linear_regression_without_sklearn.ipynb
brospars/scikit-learn-mooc
Using the model we defined above, we can check the body mass valuespredicted for a range of flipper lengths. We will set `weight_flipper_length`to be 45 and `intercept_body_mass` to be -5000.
import numpy as np weight_flipper_length = 45 intercept_body_mass = -5000 flipper_length_range = np.linspace(data.min(), data.max(), num=300) predicted_body_mass = linear_model_flipper_mass( flipper_length_range, weight_flipper_length, intercept_body_mass)
_____no_output_____
CC-BY-4.0
notebooks/linear_regression_without_sklearn.ipynb
brospars/scikit-learn-mooc
We can now plot all samples and the linear model prediction.
label = "{0:.2f} (g / mm) * flipper length + {1:.2f} (g)" ax = sns.scatterplot(data=penguins, x=feature_names, y=target_name) ax.plot(flipper_length_range, predicted_body_mass, color="tab:orange") _ = ax.set_title(label.format(weight_flipper_length, intercept_body_mass))
_____no_output_____
CC-BY-4.0
notebooks/linear_regression_without_sklearn.ipynb
brospars/scikit-learn-mooc
The variable `weight_flipper_length` is a weight applied to the feature`flipper_length` in order to make the inference. When this coefficient ispositive, it means that penguins with longer flipper lengths will have largerbody masses. If the coefficient is negative, it means that penguins withshorter flipper lengths hav...
weight_flipper_length = -40 intercept_body_mass = 13000 predicted_body_mass = linear_model_flipper_mass( flipper_length_range, weight_flipper_length, intercept_body_mass)
_____no_output_____
CC-BY-4.0
notebooks/linear_regression_without_sklearn.ipynb
brospars/scikit-learn-mooc
We can now plot all samples and the linear model prediction.
ax = sns.scatterplot(data=penguins, x=feature_names, y=target_name) ax.plot(flipper_length_range, predicted_body_mass, color="tab:orange") _ = ax.set_title(label.format(weight_flipper_length, intercept_body_mass))
_____no_output_____
CC-BY-4.0
notebooks/linear_regression_without_sklearn.ipynb
brospars/scikit-learn-mooc
In our case, this coefficient has a meaningful unit: g/mm.For instance, a coefficient of 40 g/mm, means that for eachadditional millimeter in flipper length, the body weight predicted willincrease by 40 g.
body_mass_180 = linear_model_flipper_mass( flipper_length=180, weight_flipper_length=40, intercept_body_mass=0) body_mass_181 = linear_model_flipper_mass( flipper_length=181, weight_flipper_length=40, intercept_body_mass=0) print(f"The body mass for a flipper length of 180 mm " f"is {body_mass_180} g and...
_____no_output_____
CC-BY-4.0
notebooks/linear_regression_without_sklearn.ipynb
brospars/scikit-learn-mooc
We can also see that we have a parameter `intercept_body_mass` in our model.This parameter corresponds to the value on the y-axis if `flipper_length=0`(which in our case is only a mathematical consideration, as in our data, the value of `flipper_length` only goes from 170mm to 230mm). This y-valuewhen x=0 is called the...
weight_flipper_length = 25 intercept_body_mass = 0 # redefined the flipper length to start at 0 to plot the intercept value flipper_length_range = np.linspace(0, data.max(), num=300) predicted_body_mass = linear_model_flipper_mass( flipper_length_range, weight_flipper_length, intercept_body_mass) ax = sns.scatterp...
_____no_output_____
CC-BY-4.0
notebooks/linear_regression_without_sklearn.ipynb
brospars/scikit-learn-mooc
Otherwise, it will pass through the `intercept_body_mass` value:
weight_flipper_length = 45 intercept_body_mass = -5000 predicted_body_mass = linear_model_flipper_mass( flipper_length_range, weight_flipper_length, intercept_body_mass) ax = sns.scatterplot(data=penguins, x=feature_names, y=target_name) ax.plot(flipper_length_range, predicted_body_mass, color="tab:orange") _ = ax...
_____no_output_____
CC-BY-4.0
notebooks/linear_regression_without_sklearn.ipynb
brospars/scikit-learn-mooc
IntroductionThis notebook describe how you can use VietOcr to train OCR model
# pip install --quiet vietocr==0.3.2
[?25l  |█████▌ | 10kB 26.4MB/s eta 0:00:01  |███████████ | 20kB 1.7MB/s eta 0:00:01  |████████████████▋ | 30kB 2.3MB/s eta 0:00:01  |██████████████████████▏ | 40kB 2.5MB/s eta 0:00:01  |███████████████████████████▋ ...
Apache-2.0
vietocr_gettingstart.ipynb
lexuanthinh/vietocr
Inference
import matplotlib.pyplot as plt from PIL import Image from vietocr.tool.predictor import Predictor from vietocr.tool.config import Cfg config = Cfg.load_config_from_name('vgg_transformer')
_____no_output_____
Apache-2.0
vietocr_gettingstart.ipynb
lexuanthinh/vietocr
Change weights to your weights or using default weights from our pretrained model. Path can be url or local file
# config['weights'] = './weights/transformerocr.pth' config['weights'] = 'https://drive.google.com/uc?id=13327Y1tz1ohsm5YZMyXVMPIOjoOA0OaA' config['cnn']['pretrained']=False config['device'] = 'cpu' config['predictor']['beamsearch']=False detector = Predictor(config) ! gdown --id 1uMVd6EBjY4Q0G2IkU5iMOQ34X0bysm0b ! unz...
_____no_output_____
Apache-2.0
vietocr_gettingstart.ipynb
lexuanthinh/vietocr
Download sample dataset
! gdown https://drive.google.com/uc?id=19QU4VnKtgm3gf0Uw_N2QKSquW1SQ5JiE ! unzip -qq -o ./data_line.zip
_____no_output_____
Apache-2.0
vietocr_gettingstart.ipynb
lexuanthinh/vietocr
Train model 1. Load your config2. Train model using your dataset above Load the default config, we adopt VGG for image feature extraction
from vietocr.tool.config import Cfg from vietocr.model.trainer import Trainer
_____no_output_____
Apache-2.0
vietocr_gettingstart.ipynb
lexuanthinh/vietocr
Change the config * *data_root*: the folder save your all images* *train_annotation*: path to train annotation* *valid_annotation*: path to valid annotation* *print_every*: show train loss at every n steps* *valid_every*: show validation loss at every n steps* *iters*: number of iteration to train your model* *export*...
config = Cfg.load_config_from_name('vgg_transformer') #config['vocab'] = 'aAàÀảẢãÃáÁạẠăĂằẰẳẲẵẴắẮặẶâÂầẦẩẨẫẪấẤậẬbBcCdDđĐeEèÈẻẺẽẼéÉẹẸêÊềỀểỂễỄếẾệỆfFgGhHiIìÌỉỈĩĨíÍịỊjJkKlLmMnNoOòÒỏỎõÕóÓọỌôÔồỒổỔỗỖốỐộỘơƠờỜởỞỡỠớỚợỢpPqQrRsStTuUùÙủỦũŨúÚụỤưƯừỪửỬữỮứỨựỰvVwWxXyYỳỲỷỶỹỸýÝỵỴzZ0123456789!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ ' dataset_para...
_____no_output_____
Apache-2.0
vietocr_gettingstart.ipynb
lexuanthinh/vietocr
you can change any of these params in this full list below
config
_____no_output_____
Apache-2.0
vietocr_gettingstart.ipynb
lexuanthinh/vietocr
You should train model from our pretrained
trainer = Trainer(config, pretrained=True)
Downloading: "https://download.pytorch.org/models/vgg19_bn-c79401a0.pth" to /root/.cache/torch/hub/checkpoints/vgg19_bn-c79401a0.pth
Apache-2.0
vietocr_gettingstart.ipynb
lexuanthinh/vietocr
Save model configuration for inference, load_config_from_file
trainer.config.save('config.yml')
_____no_output_____
Apache-2.0
vietocr_gettingstart.ipynb
lexuanthinh/vietocr
Visualize your dataset to check data augmentation is appropriate
trainer.visualize_dataset()
_____no_output_____
Apache-2.0
vietocr_gettingstart.ipynb
lexuanthinh/vietocr
Train now
trainer.train()
iter: 000200 - train loss: 1.657 - lr: 1.91e-05 - load time: 1.08 - gpu time: 158.33 iter: 000400 - train loss: 1.429 - lr: 3.95e-05 - load time: 0.76 - gpu time: 158.76 iter: 000600 - train loss: 1.331 - lr: 7.14e-05 - load time: 0.73 - gpu time: 158.38 iter: 000800 - train loss: 1.252 - lr: 1.12e-04 - load time: 1.29...
Apache-2.0
vietocr_gettingstart.ipynb
lexuanthinh/vietocr
Visualize prediction from our trained model
trainer.visualize_prediction()
_____no_output_____
Apache-2.0
vietocr_gettingstart.ipynb
lexuanthinh/vietocr
Compute full seq accuracy for full valid dataset
trainer.precision()
_____no_output_____
Apache-2.0
vietocr_gettingstart.ipynb
lexuanthinh/vietocr
RNNIn this section, we will introduce how to use recurrent neural networks for text classification.The dataset we use is the IMDB Movie Reviews.We use the reviews written by the users as the input and try to predict whether the they are positive or negative. Preparing the dataYou can use the following code to load the...
import tensorflow as tf tf.random.set_seed(42) from tensorflow.keras.datasets import imdb from tensorflow.keras.preprocessing import sequence max_words = 10000 embedding_dim = 32 (train_data, train_labels), (test_data, test_labels) = imdb.load_data( num_words=max_words) print(train_data.shape) print(train_labels...
(25000,) (25000,) [list([1, 14, 22, 16, 43, 530, 973, 1622, 1385, 65, 458, 4468, 66, 3941, 4, 173, 36, 256, 5, 25, 100, 43, 838, 112, 50, 670, 2, 9, 35, 480, 284, 5, 150, 4, 172, 112, 167, 2, 336, 385, 39, 4, 172, 4536, 1111, 17, 546, 38, 13, 447, 4, 192, 50, 16, 6, 147, 2025, 19, 14, 22, 4, 1920, 4613, 469, 4, 22, 71,...
MIT
3.3-RNN.ipynb
datamllab/automl-in-action-notebooks
The code above would load the reviews into train_data and test_data, load the labels (positive or negative) into train_labels and test_labels. As you can see the reviews in train_data are lists of integers instead of texts. It is because the raw texts cannot be used as an input to a neural network. Neural networks only...
# Pad the sequence to length max_len. maxlen = 100 print(len(train_data[0])) print(len(train_data[1])) train_data = sequence.pad_sequences(train_data, maxlen=maxlen) test_data = sequence.pad_sequences(test_data, maxlen=maxlen) print(train_data.shape) print(train_labels.shape)
218 189 (25000, 100) (25000,)
MIT
3.3-RNN.ipynb
datamllab/automl-in-action-notebooks
Building your networkThe next step is to build your neural network model and train it.We will introduce the neural network in three steps.The first step is the embedding, which transform each integer list into a list of vectors.The second step is to feed the vectors to the recurrent neural network.The third step is to...
from tensorflow.keras.layers import Embedding from tensorflow.keras import Sequential max_words = 10000 embedding_dim = 32 model = Sequential() model.add(Embedding(max_words, embedding_dim)) model.summary()
Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= embedding (Embedding) (None, None, 32) 320000 ====================================...
MIT
3.3-RNN.ipynb
datamllab/automl-in-action-notebooks
In the code above, we initialized an Embedding layer.The max_words is the vocabulary size, which is an integer meaning how many different words are there in the input data.The integer 16 means the length of the vector representation fro each word is 32.The output tensor of the Embedding layer is (batch_size, max_len, e...
from tensorflow.keras.layers import SimpleRNN model.add(SimpleRNN(embedding_dim, return_sequences=True)) model.add(SimpleRNN(embedding_dim, return_sequences=True)) model.add(SimpleRNN(embedding_dim, return_sequences=True)) model.add(SimpleRNN(embedding_dim)) model.summary()
Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= embedding (Embedding) (None, None, 32) 320000 ____________________________________...
MIT
3.3-RNN.ipynb
datamllab/automl-in-action-notebooks
The return_sequences parameter controlls whether to collect all the output vectors of an RNN or only collect the last output. It is set to False by default. Classification HeadThen we will use the output of the last SimpleRNN layer, which is a vector of length 32, as the input to the classification head.In the classifi...
from tensorflow.keras.layers import Dense model.add(Dense(1, activation='sigmoid')) model.compile(optimizer='adam', metrics=['acc'], loss='binary_crossentropy') model.fit(train_data, train_labels, epochs=2, batch_size=128)
Epoch 1/2 196/196 [==============================] - 30s 119ms/step - loss: 0.6258 - acc: 0.6111 Epoch 2/2 196/196 [==============================] - 23s 117ms/step - loss: 0.3361 - acc: 0.8573
MIT
3.3-RNN.ipynb
datamllab/automl-in-action-notebooks
Then we can validate our model on the testing data.
model.evaluate(test_data, test_labels)
782/782 [==============================] - 28s 35ms/step - loss: 0.3684 - acc: 0.8402
MIT
3.3-RNN.ipynb
datamllab/automl-in-action-notebooks
Business Results Recomendação de compra dos imóveis: Para decidir quais imóveis deverão ser comprados, iremos comparar os imóveis pelo zipcode e selecionar as casas que estão abaixo da média. Como explicado anteriormente, estaremos selecionando as casas que possuem 'condition' maior ou igual a 3.
import pandas as pd data = pd.read_csv('datasets/kc_house_clean.csv') pd.set_option( 'display.float_format', lambda x: '%.2f' % x) pd.options.display.max_columns = None pd.options.display.max_rows = None #comparar a média do 'zipcode' e se o valor for abaixo da média e a condição >= 3 então comprar df = data[['price',...
_____no_output_____
MIT
business_results.ipynb
gustweing/house_rocket
[mlcourse.ai](https://mlcourse.ai) – Open Machine Learning Course Author: [Yury Kashnitskiy](https://yorko.github.io). Translated by [Sergey Oreshkov](https://www.linkedin.com/in/sergeoreshkov/). This material is subject to the terms and conditions of the [Creative Commons CC BY-NC-SA 4.0](https://creativecommons....
import numpy as np import pandas as pd from sklearn.base import BaseEstimator from sklearn.metrics import log_loss, mean_squared_error, roc_auc_score from sklearn.model_selection import train_test_split from tqdm import tqdm %matplotlib inline import seaborn as sns from matplotlib import pyplot as plt from sklearn.pre...
_____no_output_____
Unlicense
jupyter_english/assignments_demo/assignment08_implement_sgd_regressor_solution.ipynb
salman394/AI-ml--course
Implement class `SGDRegressor`. Specification:- class is inherited from `sklearn.base.BaseEstimator`- constructor takes parameters `eta` – gradient step ($10^{-3}$ by default) and `n_epochs` – dataset pass count (3 by default)- constructor also creates `mse_` and `weights_` lists in order to track mean squared error an...
class SGDRegressor(BaseEstimator): def __init__(self, eta=1e-3, n_epochs=3): self.eta = eta self.n_epochs = n_epochs self.mse_ = [] self.weights_ = [] def fit(self, X, y): X = np.hstack([np.ones([X.shape[0], 1]), X]) w = np.zeros(X.shape[1]) for it in t...
_____no_output_____
Unlicense
jupyter_english/assignments_demo/assignment08_implement_sgd_regressor_solution.ipynb
salman394/AI-ml--course
Let's test out the algorithm on height/weight data. We will predict heights (in inches) based on weights (in lbs).
data_demo = pd.read_csv("../../data/weights_heights.csv") plt.scatter(data_demo["Weight"], data_demo["Height"]) plt.xlabel("Weight (lbs)") plt.ylabel("Height (Inch)") plt.grid(); X, y = data_demo["Weight"].values, data_demo["Height"].values
_____no_output_____
Unlicense
jupyter_english/assignments_demo/assignment08_implement_sgd_regressor_solution.ipynb
salman394/AI-ml--course
Perform train/test split and scale data.
X_train, X_valid, y_train, y_valid = train_test_split( X, y, test_size=0.3, random_state=17 ) scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train.reshape([-1, 1])) X_valid_scaled = scaler.transform(X_valid.reshape([-1, 1]))
_____no_output_____
Unlicense
jupyter_english/assignments_demo/assignment08_implement_sgd_regressor_solution.ipynb
salman394/AI-ml--course
Train created `SGDRegressor` with `(X_train_scaled, y_train)` data. Leave default parameter values for now.
# you code here sgd_reg = SGDRegressor() sgd_reg.fit(X_train_scaled, y_train)
_____no_output_____
Unlicense
jupyter_english/assignments_demo/assignment08_implement_sgd_regressor_solution.ipynb
salman394/AI-ml--course
Draw a chart with training process – dependency of mean squared error from the i-th SGD iteration number.
# you code here plt.plot(range(len(sgd_reg.mse_)), sgd_reg.mse_) plt.xlabel("#updates") plt.ylabel("MSE");
_____no_output_____
Unlicense
jupyter_english/assignments_demo/assignment08_implement_sgd_regressor_solution.ipynb
salman394/AI-ml--course
Print the minimal value of mean squared error and the best weights vector.
# you code here np.min(sgd_reg.mse_), sgd_reg.w_
_____no_output_____
Unlicense
jupyter_english/assignments_demo/assignment08_implement_sgd_regressor_solution.ipynb
salman394/AI-ml--course
Draw chart of model weights ($w_0$ and $w_1$) behavior during training.
# you code here plt.subplot(121) plt.plot(range(len(sgd_reg.weights_)), [w[0] for w in sgd_reg.weights_]) plt.subplot(122) plt.plot(range(len(sgd_reg.weights_)), [w[1] for w in sgd_reg.weights_]);
_____no_output_____
Unlicense
jupyter_english/assignments_demo/assignment08_implement_sgd_regressor_solution.ipynb
salman394/AI-ml--course
Make a prediction for hold-out set `(X_valid_scaled, y_valid)` and check MSE value.
# you code here sgd_holdout_mse = mean_squared_error(y_valid, sgd_reg.predict(X_valid_scaled)) sgd_holdout_mse
_____no_output_____
Unlicense
jupyter_english/assignments_demo/assignment08_implement_sgd_regressor_solution.ipynb
salman394/AI-ml--course
Do the same thing for `LinearRegression` class from `sklearn.linear_model`. Evaluate MSE for hold-out set.
# you code here from sklearn.linear_model import LinearRegression lm = LinearRegression().fit(X_train_scaled, y_train) print(lm.coef_, lm.intercept_) linreg_holdout_mse = mean_squared_error(y_valid, lm.predict(X_valid_scaled)) linreg_holdout_mse try: assert (sgd_holdout_mse - linreg_holdout_mse) < 1e-4 print("...
_____no_output_____
Unlicense
jupyter_english/assignments_demo/assignment08_implement_sgd_regressor_solution.ipynb
salman394/AI-ml--course
Dynamic Costs ReportingCalculate DV360 cost at the dynamic creative combination level. LicenseCopyright 2020 Google LLC,Licensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License at https://www.apache.org/licenses/...
!pip install git+https://github.com/google/starthinker
_____no_output_____
Apache-2.0
colabs/dynamic_costs.ipynb
Ressmann/starthinker
2. Set ConfigurationThis code is required to initialize the project. Fill in required fields and press play.1. If the recipe uses a Google Cloud Project: - Set the configuration **project** value to the project identifier from [these instructions](https://github.com/google/starthinker/blob/master/tutorials/cloud_proje...
from starthinker.util.configuration import Configuration CONFIG = Configuration( project="", client={}, service={}, user="/content/user.json", verbose=True )
_____no_output_____
Apache-2.0
colabs/dynamic_costs.ipynb
Ressmann/starthinker
3. Enter Dynamic Costs Reporting Recipe Parameters 1. Add a sheet URL. This is where you will enter advertiser and campaign level details. 1. Specify the CM network ID. 1. Click run now once, and a tab called Dynamic Costs will be added to the sheet with instructions. 1. Follow the instructions on the sheet; this will ...
FIELDS = { 'dcm_account': '', 'auth_read': 'user', # Credentials used for reading data. 'configuration_sheet_url': '', 'auth_write': 'service', # Credentials used for writing data. 'bigquery_dataset': 'dynamic_costs', } print("Parameters Set To: %s" % FIELDS)
_____no_output_____
Apache-2.0
colabs/dynamic_costs.ipynb
Ressmann/starthinker
4. Execute Dynamic Costs ReportingThis does NOT need to be modified unless you are changing the recipe, click play.
from starthinker.util.configuration import execute from starthinker.util.recipe import json_set_fields TASKS = [ { 'dynamic_costs': { 'auth': 'user', 'account': {'field': {'name': 'dcm_account', 'kind': 'string', 'order': 0, 'default': ''}}, 'sheet': { 'template': { 'url': '...
_____no_output_____
Apache-2.0
colabs/dynamic_costs.ipynb
Ressmann/starthinker
Capítulo 2: Toma de Decisiones y Neutrosofía Distancia Euclidiana entre números SVN
def euclideanNeu(a1,a2): a=0 c=len(a1) for i in range(c): a=a+pow(a1[i][0]-a2[i][0],2)+pow(a1[i][1]-a2[i][1],2)+pow(a1[i][2]-a2[i][2],2) a=pow(1.0/3.0*a,0.5) return(a)
_____no_output_____
MIT
Cap2..ipynb
mleyvaz/Neutrosofia
Ejemplo de uso de la distancia Euclidiana
EB=(1,0,0) MMB=(0.9, 0.1, 0.1) MB=(0.8,0.15,0.20) B=(0.70,0.25,0.30) MDB=(0.60,0.35,0.40) M=(0.50,0.50,0.50) MDM=(0.40,0.65,0.60) MA=(0.30,0.75,0.70) MM=(0.20,0.85,0.80) MMM=(0.10,0.90,0.90) EM=(0,1,1) r1=[MDB,B,B] i=[MMB, MMB, MB] euclideanNeu(r1,i)
_____no_output_____
MIT
Cap2..ipynb
mleyvaz/Neutrosofia
Operador SVNWA
def SVNWA(list,W): t=1 i=1 f=1 c=0 for j in list: t=t*(1-j[0])**W[c] i=i*j[1]**W[c] f=f*j[2]**W[c] c=c+1 return (1-t,i,f)
_____no_output_____
MIT
Cap2..ipynb
mleyvaz/Neutrosofia
Ejemplo de uso SVNWA
A=[MDB,B,MDB] W = [0.55, 0.26, 0.19] # W:Vector de pesos SVNWA(A,W)
_____no_output_____
MIT
Cap2..ipynb
mleyvaz/Neutrosofia
Operador SVNGA
def SVNGA(list,W): t=1 i=1 f=1 c=0 for j in list: t=t*j[0]**W[c] i=i*j[1]**W[c] f=f*j[2]**W[c] c=c+1 return (t,i,f) A=[MDB,B,MDB] W = [0.55, 0.26, 0.19] # W:Vector de pesos SVNGA(A,W)
_____no_output_____
MIT
Cap2..ipynb
mleyvaz/Neutrosofia
---layout: posttitle: Project Euler - Problem 5post-order: 005--- 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.What is the smallest positive number that is **evenly divisible** by all of the numbers from 1 to 20? Solution 1 Let's brute-force it and see what ...
import math import time # let's setle "floor" first: the products of all primes from 1 to 20 def primes_up_to(n): product = 2 for candidate_for_prime in range (3,n+1): for i in range (2,candidate_for_prime): if (candidate_for_prime % i == 0): break elif ((candi...
232792560 162.78695583343506
MIT
_posts/Problem-005.ipynb
bru1987/euler
As you may notice, the running time is extremely high (and it will get higher if we choose a greater `divisible_up_to`). We need to find a more efficient way to tacke this problem. Solution 2 - Greatest power of primes The solution for this problem actually requires **no computation**. And the reason for that is, if w...
def primes_list(n): list_of_primes = [1,2] for i in range (3,n+1): for ii in range (2,i): if (i % ii == 0): break elif ((i % ii != 0) & (ii + 1 == i)): list_of_primes.append(i) return list_of_primes list_of_primes = primes_l...
[1, 2, 3, 5, 7, 11, 13, 17, 19]
MIT
_posts/Problem-005.ipynb
bru1987/euler
Let's build a new list, with the same number of elements, but now filled with zeros. It will receive the greatest power for each prime:
list_of_powers = [1] * len(list_of_primes) print(list_of_powers)
[1, 1, 1, 1, 1, 1, 1, 1, 1]
MIT
_posts/Problem-005.ipynb
bru1987/euler
Now we need to check what is the greatest power that shows up, for each of the primes, from 1 to 20.
for i in list_of_primes: print (i) # if it's prime, there's no need to check: the power will be 1 # do the prime factorization of all numbers up to 20
1 2 3 5 7 11 13 17 19
MIT
_posts/Problem-005.ipynb
bru1987/euler
tips on drawing histograms: bin alignment vs labels
import pandas as pd, numpy as np, seaborn as sns import os # Remove the most annoying pandas warning # A value is trying to be set on a copy of a slice from a DataFrame. pd.options.mode.chained_assignment = None data_dir = '../../data' src_file = 'sample01.csv' f = os.path.join(data_dir, src_file) import sys sys.path...
_____no_output_____
MIT
notebooks/histograms.ipynb
altanova/stuff
example: 2d histogramshowing bin allignments: incorrect, and correct
data = df sns.set() import matplotlib.pyplot as plt; import matplotlib.colors as mcolors fig, ax = plt.subplots(1, 3, figsize=(20,4)) ax = ax.flatten() fig.suptitle("some histograms", fontsize=20, y=1.1) axis = ax[0] h = axis.hist(x = data.weekday) axis.set_xlabel('days of week (0=Mon)') axis.set_ylabel('frequenc...
_____no_output_____
MIT
notebooks/histograms.ipynb
altanova/stuff
same problem with Seaborn (v 0.11) displot or joinplot, type hist
# bad sns.jointplot(x="weekday", y="hour", data=df.sample(1000), kind='hist', ax = ax[0]) # still bad sns.jointplot(x="weekday", y="hour", data=df.sample(1000), kind='hist',bins = [7, 24]) #good bins = (np.arange(7 + 1)-0.5, np.arange(24 + 1) - 0.5) sns.jointplot(x="weekday", y="hour", data=df.sample(1000), kind='his...
_____no_output_____
MIT
notebooks/histograms.ipynb
altanova/stuff
more problems with bin allignment
# I will now demonstrate how bad bins lead to bad conclusions # store previous df under separate variable df0 = df data_dir = '../../data' src_file = 'sample02.csv' f = os.path.join(data_dir, src_file) df = pd.read_csv(f, sep = ';') df['created'] = pd.to_datetime(df['created'], format = hd.format_dash, errors = 'coerc...
_____no_output_____
MIT
notebooks/histograms.ipynb
altanova/stuff
Problems with binning and rounding days and weeks (pd.Timestamp)The below is a long version. The compact version has been summarized in handy-showcase workbook.
data_dir = '../../data' src_file = 'sample01.csv' f = os.path.join(data_dir, src_file) df = pd.read_csv(f, sep = ';') df['created'] = pd.to_datetime(df['created'], format = hd.format_dash, errors = 'coerce') df['resolved'] = pd.to_datetime(df['resolved'], format = hd.format_dash, errors = 'coerce') df = hd.augment_colu...
_____no_output_____
MIT
notebooks/histograms.ipynb
altanova/stuff
set feature model weights and distribution to good start parametersm
n_dims = np.prod(train_inputs[0].shape[1:]) i_class_dims = [int(n_dims*0.25), int(n_dims * 0.75)] from reversible2.constantmemory import clear_ctx_dicts from reversible2.distribution import TwoClassDist feature_model.data_init(th.cat((train_inputs[0], train_inputs[1]), dim=0)) # Check that forward + inverse is reall...
_____no_output_____
MIT
notebooks/bhno-with-adversary/21ChansOTNoFFTOtherClassDims.ipynb
robintibor/reversible2
Downloading GloVe
dir = HTTP.download("http://ann-benchmarks.com/glove-100-angular.hdf5", update_period=60) data = h5open(dir, "r") do file read(file); end train = data["train"] queries = data["test"] groundtruth = data["neighbors"].+1; #zero-indexed train = train ./ mapslices(norm, train, dims=1); train_backup...
_____no_output_____
MIT
docs/AHPQ_for_GloVe.ipynb
AxelvL/AHPQ.jl
100 Bits Graph
n_codebooks = 25 n_centers = 16 n_neighbors = 100 stopcond=1e-1;
_____no_output_____
MIT
docs/AHPQ_for_GloVe.ipynb
AxelvL/AHPQ.jl
L2 loss
ahpq = builder(train; T=0, n_codebooks=n_codebooks, n_centers=n_centers, verbose=true, stopcond=stopcond, a=0, inverted_index=true, multithreading=fal...
_____no_output_____
MIT
docs/AHPQ_for_GloVe.ipynb
AxelvL/AHPQ.jl
Anisotropic Loss
train = deepcopy(train_backup) ahpq = builder(train; T=0.2, n_codebooks=n_codebooks, n_centers=n_centers, verbose=true, stopcond=stopcond, a=0, inverted_index=false, ...
_____no_output_____
MIT
docs/AHPQ_for_GloVe.ipynb
AxelvL/AHPQ.jl
Comparison
plot(1:100, anisotropic_scores_1, label="Anisotropic Loss") plot!(1:100, L2_scores_1, label="Reconstruction Loss") plot!(title="Recall of Glove-1.2M - 100 bits", xlabel="N", ylabel="Recall 1@N", legend=:bottomright, xticks=0:20:100, yticks=0.1:0.1:0.9)
_____no_output_____
MIT
docs/AHPQ_for_GloVe.ipynb
AxelvL/AHPQ.jl
200 Bits Graph
n_codebooks = 50 n_centers = 16 n_neighbors = 100 stopcond=1e-1;
_____no_output_____
MIT
docs/AHPQ_for_GloVe.ipynb
AxelvL/AHPQ.jl
L2 loss
train = deepcopy(train_backup) ahpq = builder(train; T=0, n_codebooks=n_codebooks, n_centers=n_centers, verbose=true, stopcond=stopcond, a=0, inverted_index=true, ...
_____no_output_____
MIT
docs/AHPQ_for_GloVe.ipynb
AxelvL/AHPQ.jl
Anisotropic Loss
train = deepcopy(train_backup) ahpq = builder(train; T=0.2, n_codebooks=n_codebooks, n_centers=n_centers, verbose=true, stopcond=stopcond, a=0, inverted_index=true, ...
_____no_output_____
MIT
docs/AHPQ_for_GloVe.ipynb
AxelvL/AHPQ.jl
Comparison
plot(1:100, anisotropic_scores_2, label="Anisotropic Loss") plot!(1:100, L2_scores_2, label="Reconstruction Loss") plot!(title="Recall of Glove-1.2M - 200 bits", xlabel="N", ylabel="Recall 1@N", legend=:bottomright, xticks=0:20:100, yticks=0.1:0.1:0.9)
_____no_output_____
MIT
docs/AHPQ_for_GloVe.ipynb
AxelvL/AHPQ.jl
Exercise 11.2 Task Try to extend the model to obtain a reasonable fit of the following polynomial of order 3:$$f(x)=4-3x-2x^2+3x^3$$for $x \in [-1,1]$.In order to make practice with NN, explore reasonable different choices for:- the number of layers- the number of neurons in each layer- the activation function- the...
import numpy as np import math from tensorflow import keras from matplotlib import pyplot as plt #function = 3x^3 - 2x^2 - 3x + 4 def polynomial(x_array,a,b,c,d): x_array = np.asfarray(x_array) return a*x_array**3 + b*x_array**2 + c*x_array + d # np.random.seed(0) x_train = np.random.uniform(-1, 1, 1000) # da...
_____no_output_____
MIT
es11/11.2.ipynb
lorycontixd/PNS
Using model from Ex11.1This section utilizes the linear model used in Exercise 11.1, just to prove that it should not function and another model must be defined for polynomials.
# Using model from ex11.1 # Load previous model for extension oldmodel = keras.models.load_model('models/model_ex1') oldmodel.summary() print() history = oldmodel.fit(x=x_train, y=y_train, batch_size=32, epochs=100, shuffle=True, # validation_data=(x_valid, y_valid), verbose=0 ) score = oldmodel.eva...
Model: "sequential_184" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense_184 (Dense) (None, 1) 2 ================================...
MIT
es11/11.2.ipynb
lorycontixd/PNS
New model
from tensorflow.keras import models from tensorflow.keras import layers from tensorflow.keras import optimizers from tensorflow.keras import backend as K from tensorflow.keras import callbacks from tensorflow.keras import losses from tensorflow.keras import activations from tensorflow.keras.utils import get_custom_obje...
_____no_output_____
MIT
es11/11.2.ipynb
lorycontixd/PNS
Dependance on layers & neurons Using the code above, various NNs have been trained with different layers and neurons for each layer, to study the accuracy in approximating the polynomial in $[\frac{-3}{2},\frac{3}{2}]$ Different Neural Networks
opt = optimizers.SGD(learning_rate=0.1) run([layers.Dense(500,input_shape=(1,)),layers.Dense(1,activation="relu")],optimizer=opt,testing=False) run([layers.Dense(1,input_shape=(1,)),layers.Dense(30,activation="relu"),layers.Dense(1,activation="relu")],optimizer=opt,testing=False) run([layers.Dense(500,input_shape=(1,))...
************** 2 Layers 500 input neurons optimizer=SGD loss=mse Model: "sequential_1" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense_3 (Dense) (None...
MIT
es11/11.2.ipynb
lorycontixd/PNS
ResultsDiscuss results on layers/neurons Dependance on optimizers The following section defines different optimizer functions for a Neural Network with 3 layers and 500 input neurons.Which optimizers to choseExpectations  Adam Optimizer Adam, short for adaptive moment estimation, is an optimization algorithm t...
opt_layers = [ layers.Dense(1,input_shape=(1,)), layers.Dense(50,activation="relu"), layers.Dense(1,activation="selu") ] opts = [ optimizers.SGD(learning_rate=1e-1), optimizers.Adam(learning_rate=1e-1), optimizers.RMSprop(learning_rate=1e-1), optimizers.Adagrad(learning_rate=1e-1...
************** 3 Layers 1 input neurons optimizer=SGD loss=mse Model: "sequential_6" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense_23 (Dense) (None, ...
MIT
es11/11.2.ipynb
lorycontixd/PNS
Learning rateAs with all optimization algorithms, it is defined by numerous parameters, including the learning rate, which determines the step size at each iteration while moving toward a minimum of a loss function.In the following section, I will study the impact of the learning rate parameter on the learning efficie...
#--- LR = 0.001 lr = 0.001 adam1 = optimizers.Adam( learning_rate=lr, beta_1=0.9, beta_2=0.999, epsilon=1e-07, amsgrad=False, name="Adam2" ) print("---> Learning rate: ",lr) run( [ layers.Dense(500,input_shape=(1,)), layers.Dense(100, activation="relu"), layers.Dens...
Model: "sequential_13" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense_35 (Dense) (None, 500) 1000 _________________________________...
MIT
es11/11.2.ipynb
lorycontixd/PNS
The choice of the value for learning rate can impact two things: How fast the algorithm learns Whether the cost function is minimized or notFor an optimal value of the learning rate, the cost function value is minimized in a few iterations. If your learning rate is too low, training will progress very slowly as t...
loss_functions = [ losses.MeanSquaredError(), losses.MeanAbsoluteError(reduction="auto", name="mean_absolute_error"), losses.CategoricalCrossentropy(reduction="auto",name="categorical_crossentropy"), losses.Poisson(reduction="auto", name="poisson") ] opt = optimizers.SGD(learning_rate=0.01) ll = [ ...
************** 3 Layers 500 input neurons optimizer=SGD loss=MeanSquaredError Model: "sequential_14" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense_38 (Dense) ...
MIT
es11/11.2.ipynb
lorycontixd/PNS
Results... Dependance on activation function Lastly, I reported a study on the dependance of the model on the activation function of the neurons. The structure of the Neural Network is defined by 4 layers, respectively with 500, 250, 100 and 1 neurons.The chosen activation functions are:...
lossfunc = losses.MeanSquaredError() opt = optimizers.SGD(learning_rate=0.01) all_layers = [[ layers.Dense(500, input_shape=(1,)), layers.Dense(250, activation="relu"), layers.Dense(100, activation="relu"), layers.Dense(1, activation="relu") ],[ layers.Dense(500, input_shape=(1,)), layers.Dense(...
_____no_output_____
MIT
es11/11.2.ipynb
lorycontixd/PNS
Boolean Operator
x=1 y=2 print(x>y) print(10>11) print(10==10) print(10!=11) #using bool()function print(bool("Hello")) print(bool(15)) print(bool(1)) print(bool(True)) print(bool(False)) print(bool(None)) print(bool(0)) print(bool([]))
True True True True False False False False
Apache-2.0
Expressions_and_Operations.ipynb
khloemaritonigloria08/CPEN-21A-ECE-2-1
Functions can return Boolean
def myFunction():return False print(myFunction()) def yourFunction():return False if yourFunction(): print("Yes!") else: print("No")
No
Apache-2.0
Expressions_and_Operations.ipynb
khloemaritonigloria08/CPEN-21A-ECE-2-1
You Try!
a=6 b=7 print(a==b) print(a!=a)
False False
Apache-2.0
Expressions_and_Operations.ipynb
khloemaritonigloria08/CPEN-21A-ECE-2-1
Arithmetic Operators
print(10+5) print(10-5) print(10*5) print(10/5) print(10%5) #modulo division, remainder print(10//5) #floor division print(10//3) #floor division print(10%3) #3x3=9+1
15 5 50 2.0 0 2 3 1
Apache-2.0
Expressions_and_Operations.ipynb
khloemaritonigloria08/CPEN-21A-ECE-2-1
Bitwise Operators
a=60 #0011 1100 b=13 #0000 1101 print(a&b) print(a|b) print(a^b) print(~a) print(a<<1) #0111 1000 print(a<<2) #1111 0000 print(b>>1) #1 0000 0110 print(b>>2) #0000 0110 carry flag bit = 01
12 61 49 -61 120 240 6 3
Apache-2.0
Expressions_and_Operations.ipynb
khloemaritonigloria08/CPEN-21A-ECE-2-1
Python Assignment Operators
a+=3 #Same As a=a+3 #Same As a=60+3, a=63 print(a)
63
Apache-2.0
Expressions_and_Operations.ipynb
khloemaritonigloria08/CPEN-21A-ECE-2-1
Logical Operators
#and Logical Operator a=True b=False print(a and b) print(not(a and b)) print(a or b) print(not(a or b)) print(a is b) print(a is not b)
False True
Apache-2.0
Expressions_and_Operations.ipynb
khloemaritonigloria08/CPEN-21A-ECE-2-1
Searching For Simple PatternsBeing able to match letters and metacharacters is the simplest task that regular expressions can do. In this section we will see how we can use regular expressions to perform more complex pattern matching. We can form any pattern we want by using the metacharacters mentioned in the previou...
# Import re module import re # Sample text sample_text = 'Alice lives in 1230 First St., Ocean City, MD 156789.' # Create a regular expression object with the regular expression '\d' regex = re.compile(r'\d') # Search the sample_text for the regular expression matches = regex.finditer(sample_text) # Print all the m...
<_sre.SRE_Match object; span=(15, 16), match='1'> <_sre.SRE_Match object; span=(16, 17), match='2'> <_sre.SRE_Match object; span=(17, 18), match='3'> <_sre.SRE_Match object; span=(18, 19), match='0'> <_sre.SRE_Match object; span=(46, 47), match='1'> <_sre.SRE_Match object; span=(47, 48), match='5'> <_sre.SRE_Match obje...
Apache-2.0
TradingAI/AI Algorithms in Trading/Lesson 05 - Financial Statements/simple_patterns.ipynb
Quananhle/Python
As we can see, all the matches found above correspond to only decimal digits between 0 and 9.Conversely, if wanted to find all the characters that are **not** decimal digits, we will use `\D` as our regular expression, as shown below:
# Import re module import re # Sample text sample_text = 'Alice lives in 1230 First St., Ocean City, MD 156789.' # Create a regular expression object with the regular expression '\D' regex = re.compile(r'\D') # Search the sample_text for the regular expression matches = regex.finditer(sample_text) # Print all the m...
<_sre.SRE_Match object; span=(0, 1), match='A'> <_sre.SRE_Match object; span=(1, 2), match='l'> <_sre.SRE_Match object; span=(2, 3), match='i'> <_sre.SRE_Match object; span=(3, 4), match='c'> <_sre.SRE_Match object; span=(4, 5), match='e'> <_sre.SRE_Match object; span=(5, 6), match=' '> <_sre.SRE_Match object; span=(6,...
Apache-2.0
TradingAI/AI Algorithms in Trading/Lesson 05 - Financial Statements/simple_patterns.ipynb
Quananhle/Python
We can see that none of the matches are decimal digits. We also see, that by using `\D` we were able to match all characters, including periods (`.`) and white spaces. TODO: Find IP AddressesIn the cell below, our `sample_text` string contains three IP addresses. Write a single regular expression that can match any IP...
# Import re module import re # Sample text sample_text = 'Here are three IP address: 123.456.789.123, 999.888.777.666, 111.222.333.444' # Create a regular expression object with the regular expression regex = re.compile(r'\d\d\d.\d\d\d.\d\d\d.\d\d\d') # Search the sample_text for the regular expression matches = reg...
<_sre.SRE_Match object; span=(27, 42), match='123.456.789.123'> <_sre.SRE_Match object; span=(44, 59), match='999.888.777.666'> <_sre.SRE_Match object; span=(61, 76), match='111.222.333.444'>
Apache-2.0
TradingAI/AI Algorithms in Trading/Lesson 05 - Financial Statements/simple_patterns.ipynb
Quananhle/Python
If you wrote your regex correctly you should see three matches above corresponding to the three IP addresses in our `sample_text` string. Matching Whitespace Characters Using `\s`In the code below, we will use `\s` as our regular expression to find all the whitespace characters in our `sample_text` string. For this ex...
# Import re module import re # Sample text sample_text = ''' \tAlice lives in:\f 1230 First St.\r Ocean City, MD 156789.\v ''' # Create a regular expression object with the regular expression '\s' regex = re.compile(r'\s') # Search the sample_text for the regular expression matches = regex.finditer(sample_text) # P...
<_sre.SRE_Match object; span=(0, 1), match='\n'> <_sre.SRE_Match object; span=(1, 2), match='\t'> <_sre.SRE_Match object; span=(7, 8), match=' '> <_sre.SRE_Match object; span=(13, 14), match=' '> <_sre.SRE_Match object; span=(17, 18), match='\x0c'> <_sre.SRE_Match object; span=(18, 19), match='\n'> <_sre.SRE_Match obje...
Apache-2.0
TradingAI/AI Algorithms in Trading/Lesson 05 - Financial Statements/simple_patterns.ipynb
Quananhle/Python
As we can see, all the matches found correspond to white spaces, tabs (`\t`), newlines (`\n`), carriage returns (`\r`), form feeds (`\f`), and vertical tabs (`\v`). Notice that form feeds appear as `\x0c` and vertical tabs as `\x0b`. Conversely, if wanted to find all the characters that are **not** whitespace character...
# Import re module import re # Sample text sample_text = ''' \tAlice lives in:\f 1230 First St.\r Ocean City, MD 156789.\v ''' # Create a regular expression object with the regular expression '\S' regex = re.compile(r'\S') # Search the sample_text for the regular expression matches = regex.finditer(sample_text) # P...
<_sre.SRE_Match object; span=(2, 3), match='A'> <_sre.SRE_Match object; span=(3, 4), match='l'> <_sre.SRE_Match object; span=(4, 5), match='i'> <_sre.SRE_Match object; span=(5, 6), match='c'> <_sre.SRE_Match object; span=(6, 7), match='e'> <_sre.SRE_Match object; span=(8, 9), match='l'> <_sre.SRE_Match object; span=(9,...
Apache-2.0
TradingAI/AI Algorithms in Trading/Lesson 05 - Financial Statements/simple_patterns.ipynb
Quananhle/Python
We can see that none of the matches above are whitespace characters. We also see, that by using `\S` we were able to match all characters, including periods (`.`), letters, and numbers. TODO: Print The Numbers Between Whitespace CharactersIn the cell below, our `sample_text` consists of a multi-line string with numbe...
# Import re module import re # Sample text sample_text = ''' 123\t45\t7895 1\t222\t33 ''' # Print sample_text print('Sample Text:\n', sample_text) # Create a regular expression object with the regular expression regex = re.compile(r'\s') # Search the sample_text for the regular expression matches = regex.finditer(s...
Sample Text: 123 45 7895 1 222 33 123 45 7895 1 222 33
Apache-2.0
TradingAI/AI Algorithms in Trading/Lesson 05 - Financial Statements/simple_patterns.ipynb
Quananhle/Python
Matching Alphanumeric Characters Using `\w`In the code below, we will use `\w` as our regular expression to find all the alphanumeric characters in our `sample_text` string. This includes the underscore ( `_` ), all the numbers from 0 through 9, and all the uppercase and lowercase letters:
# Import re module import re # Sample text sample_text = ''' You can contact FAKE Company at: fake_company12@email.com. ''' # Create a regular expression object with the regular expression '\w' regex = re.compile(r'\w') # Search the sample_text for the regular expression matches = regex.finditer(sample_text) # Prin...
<_sre.SRE_Match object; span=(1, 2), match='Y'> <_sre.SRE_Match object; span=(2, 3), match='o'> <_sre.SRE_Match object; span=(3, 4), match='u'> <_sre.SRE_Match object; span=(5, 6), match='c'> <_sre.SRE_Match object; span=(6, 7), match='a'> <_sre.SRE_Match object; span=(7, 8), match='n'> <_sre.SRE_Match object; span=(9,...
Apache-2.0
TradingAI/AI Algorithms in Trading/Lesson 05 - Financial Statements/simple_patterns.ipynb
Quananhle/Python
As we can see, all the matches found correspond to alphanumeric characters only, including the underscore in the email address.Conversely, if wanted to find all the characters that are **not** alphanumeric characters, we will use `\W` as our regular expression, as shown below:
# Import re module import re # Sample text sample_text = ''' You can contact FAKE Company at: fake_company12@email.com. ''' # Create a regular expression object with the regular expression '\W' regex = re.compile(r'\W') # Search the sample_text for the regular expression matches = regex.finditer(sample_text) # Prin...
<_sre.SRE_Match object; span=(0, 1), match='\n'> <_sre.SRE_Match object; span=(4, 5), match=' '> <_sre.SRE_Match object; span=(8, 9), match=' '> <_sre.SRE_Match object; span=(16, 17), match=' '> <_sre.SRE_Match object; span=(21, 22), match=' '> <_sre.SRE_Match object; span=(29, 30), match=' '> <_sre.SRE_Match object; s...
Apache-2.0
TradingAI/AI Algorithms in Trading/Lesson 05 - Financial Statements/simple_patterns.ipynb
Quananhle/Python
We can see that none of the matches are alphanumeric characters. We also see, that by using `\W` we were able to match all whitespace characters, and the `@` symbol in the email address. TODO: Find emailsIn the cell below, our `sample_text` consists of a multi-line string that contains three email addresses:```j.s@ema...
# Import re module import re # Sample text sample_text = ''' John Sanders: j.s@email.com Alice Walters: a.w@email.com Mary Jones: m.j@email.com ''' # Print sample_text print('Sample Text:\n', sample_text) # Create a regular expression object with the regular expression regex = re.compile(r'[0-9a-zA-Z].[0-9a-zA-Z]@em...
Sample Text: John Sanders: j.s@email.com Alice Walters: a.w@email.com Mary Jones: m.j@email.com <_sre.SRE_Match object; span=(15, 28), match='j.s@email.com'> <_sre.SRE_Match object; span=(44, 57), match='a.w@email.com'> <_sre.SRE_Match object; span=(70, 83), match='m.j@email.com'>
Apache-2.0
TradingAI/AI Algorithms in Trading/Lesson 05 - Financial Statements/simple_patterns.ipynb
Quananhle/Python
Creating variables In this notebook we will look into the concept of variables.Python, like R, is a dynamically-typed language, meaning you can change the class/type of a variable on the go. This is convenient in many places, but dangerous in many other ways. It is impossible to rely on the type of the variable, and y...
name = "Edinburgh" name
_____no_output_____
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
This generates a string variable. They can be easily printed, although it is safer to use the print function:
print(name)
Edinburgh
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
It is also wise to check the type of the variable, in case you are lost:
type(name)
_____no_output_____
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
This confirms that we are dealing with a string. There are a few things we can do with strings (which we can denote by using one or two apostrophes):
name = 'university of edinburgh' print(name.lower()) print(name.upper()) print(name.title())
university of edinburgh UNIVERSITY OF EDINBURGH University Of Edinburgh
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
We can concatenate strings easily using +, or using a comma in a print statement:
print('University', 'of Edinburgh') print('University' + ' ' + 'of Edinburgh')
University of Edinburgh University of Edinburgh
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Writing print('The University of Edinburgh is '+ 439) will not work, as the + operator only works for strings, we can convert any object into a string however:
print('The University of Edinburgh is '+ str(439))
The University of Edinburgh is 439
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
A few other useful tricks:
name = " edinburgh " print("|"+name.lstrip()+"|") print("|"+name.rstrip()+"|") print("|"+name.strip()+"|")
|edinburgh | | edinburgh| |edinburgh|
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
You can use control characters as well:
print('Edinburgh\thas a university\nrunning web & social network analytics course')
Edinburgh has a university running web & social network analytics course
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Numbers
a = 10 b = -10.1023 #Some operations illustrated (\t stands for a tab) print("a: \t\t\t" + str(a)) print("b: \t\t\t" + str(b)) print("absolute of b: \t\t" + str(abs(b))) print("rounded b: \t\t" + str(round(b,3))) print("square of a: \t\t" + str(pow(a,2))) print("cube of a: \t\t" + str(a**3)) print("integer part of b: ...
a: 10 b: -10.1023 absolute of b: 10.1023 rounded b: -10.102 square of a: 100 cube of a: 1000 integer part of b: -10
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes