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
Directory to store Models
import os if not os.path.exists('./models'): os.mkdir('./models') def position_index(x): if x<4: return 1 if x>10: return 3 else : return 2
_____no_output_____
UPL-1.0
beginners/04.ML_Modelling.ipynb
MKulfan/redbull-analytics-hol
Model considering only Drivers
x_d= data[['GP_name','quali_pos','driver','age_at_gp_in_days','position','driver_confidence','active_driver']] x_d = x_d[x_d['active_driver']==1] sc = StandardScaler() le = LabelEncoder() x_d['GP_name'] = le.fit_transform(x_d['GP_name']) x_d['driver'] = le.fit_transform(x_d['driver']) x_d['GP_name'] = le.fit_transform...
_____no_output_____
UPL-1.0
beginners/04.ML_Modelling.ipynb
MKulfan/redbull-analytics-hol
Model considering only Constructors
x_c = data[['GP_name','quali_pos','constructor','position','constructor_reliability','active_constructor']] x_c = x_c[x_c['active_constructor']==1] sc = StandardScaler() le = LabelEncoder() x_c['GP_name'] = le.fit_transform(x_c['GP_name']) x_c['constructor'] = le.fit_transform(x_c['constructor']) X_c = x_c.drop(['posi...
_____no_output_____
UPL-1.0
beginners/04.ML_Modelling.ipynb
MKulfan/redbull-analytics-hol
Model considering both Drivers and Constructors
cleaned_data = data[['GP_name','quali_pos','constructor','driver','position','driver_confidence','constructor_reliability','active_driver','active_constructor']] cleaned_data = cleaned_data[(cleaned_data['active_driver']==1)&(cleaned_data['active_constructor']==1)] cleaned_data.to_csv('./data_f1/cleaned_data.csv',index...
_____no_output_____
UPL-1.0
beginners/04.ML_Modelling.ipynb
MKulfan/redbull-analytics-hol
Build your X dataset with next columns:- GP_name- quali_pos to predict the classification cluster (1,2,3) - constructor- driver- position- driver confidence- constructor_reliability- active_driver- active_constructor Filter the dataset for this Model "Driver + Constructor" all active drivers and constructors Create ...
# Implement X, y
_____no_output_____
UPL-1.0
beginners/04.ML_Modelling.ipynb
MKulfan/redbull-analytics-hol
Applied the same list of ML Algorithms for cross validation of different modelsAnd Store the accuracy Mean Value in order to compare with previous ML Models
mean_results = [] results = [] name = [] # cross validation for different models
_____no_output_____
UPL-1.0
beginners/04.ML_Modelling.ipynb
MKulfan/redbull-analytics-hol
Use the same boxplot plotter used in the previous Models
# Implement boxplot
_____no_output_____
UPL-1.0
beginners/04.ML_Modelling.ipynb
MKulfan/redbull-analytics-hol
Comparing The 3 ML ModelsLet's see mean score of our three assumptions.
lr = [mean_results[0],mean_results_dri[0],mean_results_const[0]] dtc = [mean_results[1],mean_results_dri[1],mean_results_const[1]] rfc = [mean_results[2],mean_results_dri[2],mean_results_const[2]] svc = [mean_results[3],mean_results_dri[3],mean_results_const[3]] gnb = [mean_results[4],mean_results_dri[4],mean_results_c...
62.024924516677856 seconds
UPL-1.0
beginners/04.ML_Modelling.ipynb
MKulfan/redbull-analytics-hol
Model buildinghttps://www.kaggle.com/vadbeg/pytorch-nn-with-embeddings-and-catboost/notebookPyTorchmostly based off this example, plus parts of code form tutorial 5 lab 3
# import load_data function from %load_ext autoreload %autoreload 2 # fix system path import sys sys.path.append("/home/jovyan/work") import numpy as np import pandas as pd import torch from torch.utils.data import Dataset, DataLoader import random def set_seed(seed): random.seed(seed) np.random.seed(seed) ...
/opt/conda/lib/python3.7/site-packages/ipykernel_launcher.py:24: TqdmDeprecationWarning: This function will be removed in tqdm==5.0.0 Please use `tqdm.notebook.tqdm` instead of `tqdm.tqdm_notebook`
FTL
notebooks/Model Building.ipynb
Reasmey/adsi_beer_app
forgot to divide the loss and accuracy by length of data set
print('Training Accuracy: {:.2f}%'.format(5926.0/300.0)) print('Validation Accuracy: {:.2f}%'.format(2361.0/300.0))
Training Accuracy: 19.75% Validation Accuracy: 7.87%
FTL
notebooks/Model Building.ipynb
Reasmey/adsi_beer_app
Predict with test set
def predict(data_loader, model): model.eval() device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') model.to(device) with torch.no_grad(): predictions = None for i, batch in enumerate(tqdm(data_loader)): output = model(batc...
_____no_output_____
FTL
notebooks/Model Building.ipynb
Reasmey/adsi_beer_app
* 比较不同组合组合优化器在不同规模问题上的性能;* 下面的结果主要比较``alphamind``和``python``中其他优化器的性能差别,我们将尽可能使用``cvxopt``中的优化器,其次选择``scipy``;* 由于``scipy``在``ashare_ex``上面性能太差,所以一般忽略``scipy``在这个股票池上的表现;* 时间单位都是毫秒。* 请在环境变量中设置`DB_URI`指向数据库
import os import timeit import numpy as np import pandas as pd import cvxpy from alphamind.api import * from alphamind.portfolio.linearbuilder import linear_builder from alphamind.portfolio.meanvariancebuilder import mean_variance_builder from alphamind.portfolio.meanvariancebuilder import target_vol_builder pd.option...
_____no_output_____
MIT
notebooks/Example 7 - Portfolio Optimizer Performance.ipynb
wangjiehui11235/alpha-mind
0. 数据准备------------------
ref_date = '2018-02-08' u_names = ['sh50', 'hs300', 'zz500', 'zz800', 'zz1000', 'ashare_ex'] b_codes = [16, 300, 905, 906, 852, None] risk_model = 'short' factor = 'EPS' lb = 0.0 ub = 0.1 data_source = os.environ['DB_URI'] engine = SqlEngine(data_source) universes = [Universe(u_name) for u_name in u_names] codes_set =...
_____no_output_____
MIT
notebooks/Example 7 - Portfolio Optimizer Performance.ipynb
wangjiehui11235/alpha-mind
1. 线性优化(带线性限制条件)---------------------------------
df = pd.DataFrame(columns=u_names, index=['cvxpy', 'alphamind']) number = 1 for u_name, sample_data in zip(u_names, data_set): factor_data = sample_data['factor'] er = factor_data[factor].values n = len(er) lbound = np.ones(n) * lb ubound = np.ones(n) * ub risk_constraints = np.ones((n, 1...
_____no_output_____
MIT
notebooks/Example 7 - Portfolio Optimizer Performance.ipynb
wangjiehui11235/alpha-mind
2. 线性优化(带L1限制条件)-----------------------
from cvxpy import pnorm df = pd.DataFrame(columns=u_names, index=['cvxpy', 'alphamind (clp simplex)', 'alphamind (clp interior)', 'alphamind (ecos)']) turn_over_target = 0.5 number = 1 for u_name, sample_data in zip(u_names, data_set): factor_data = sample_data['factor'] er = factor_data[factor].values n ...
_____no_output_____
MIT
notebooks/Example 7 - Portfolio Optimizer Performance.ipynb
wangjiehui11235/alpha-mind
3. Mean - Variance 优化 (无约束)-----------------------
from cvxpy import * df = pd.DataFrame(columns=u_names, index=['cvxpy', 'alphamind']) number = 1 for u_name, sample_data in zip(u_names, data_set): all_styles = risk_styles + industry_styles + ['COUNTRY'] factor_data = sample_data['factor'] risk_cov = sample_data['risk_cov'][all_styles].values risk_exp...
_____no_output_____
MIT
notebooks/Example 7 - Portfolio Optimizer Performance.ipynb
wangjiehui11235/alpha-mind
4. Mean - Variance 优化 (Box约束)---------------
df = pd.DataFrame(columns=u_names, index=['cvxpy', 'alphamind']) number = 1 for u_name, sample_data in zip(u_names, data_set): all_styles = risk_styles + industry_styles + ['COUNTRY'] factor_data = sample_data['factor'] risk_cov = sample_data['risk_cov'][all_styles].values risk_exposure = factor_data[a...
_____no_output_____
MIT
notebooks/Example 7 - Portfolio Optimizer Performance.ipynb
wangjiehui11235/alpha-mind
5. Mean - Variance 优化 (Box约束以及线性约束)----------------
df = pd.DataFrame(columns=u_names, index=['cvxpy', 'alphamind']) number = 1 for u_name, sample_data in zip(u_names, data_set): all_styles = risk_styles + industry_styles + ['COUNTRY'] factor_data = sample_data['factor'] risk_cov = sample_data['risk_cov'][all_styles].values risk_exposure = factor_data[a...
_____no_output_____
MIT
notebooks/Example 7 - Portfolio Optimizer Performance.ipynb
wangjiehui11235/alpha-mind
6. 线性优化(带二次限制条件)-------------------------
df = pd.DataFrame(columns=u_names, index=['cvxpy', 'alphamind']) number = 1 target_vol = 0.5 for u_name, sample_data in zip(u_names, data_set): all_styles = risk_styles + industry_styles + ['COUNTRY'] factor_data = sample_data['factor'] risk_cov = sample_data['risk_cov'][all_styles].values risk_exposu...
_____no_output_____
MIT
notebooks/Example 7 - Portfolio Optimizer Performance.ipynb
wangjiehui11235/alpha-mind
Based on **Train-AEmodel-GRU2x32-encoding16-AEmodel-DR5-ps-SDSS-QSO-balanced-wandb.ipynb** To-do
gpu_info = !nvidia-smi gpu_info = '\n'.join(gpu_info) if gpu_info.find('failed') >= 0: print('Select the Runtime > "Change runtime type" menu to enable a GPU accelerator, ') print('and then re-execute this cell.') else: print(gpu_info) from psutil import virtual_memory ram_gb = virtual_memory().total / 1e9 print(...
Your runtime has 8.6 gigabytes of available RAM To enable a high-RAM runtime, select the Runtime > "Change runtime type" menu, and then select High-RAM in the Runtime shape dropdown. Then, re-execute this cell.
Apache-2.0
01_(Paula)TrainAE.ipynb
hernanlira/hl_stargaze
Pixel ShuffleThis notebook is a comparison between two best practices. Pixel shuffle and upsampling followed by a convolution. Imports
from fastai import * from fastai.tabular import * import pandas as pd from torchsummary import summary import torch from torch import nn import imageio import torch import glob from fastai.vision import * import os from torch import nn import torch.nn.functional as F
_____no_output_____
MIT
notebooks/cifar-10/pixelShuffle.ipynb
henriwoodcock/Applying-Modern-Best-Practices-to-Autoencoders
Data
colab = True if colab: from google.colab import drive drive.mount('/content/drive', force_remount = True) %cp "/content/drive/My Drive/autoencoder-training/data.zip" . !unzip -q data.zip image_path = "data" %cp "/content/drive/My Drive/autoencoder-training/model_layers.py" . %cp "/content/drive/My Drive/a...
_____no_output_____
MIT
notebooks/cifar-10/pixelShuffle.ipynb
henriwoodcock/Applying-Modern-Best-Practices-to-Autoencoders
Model
autoencoder = pixelShuffle_model.autoencoder() learn = Learner(data, autoencoder, loss_func = F.mse_loss) learn.fit_one_cycle(5) learn.lr_find() learn.recorder.plot(suggestion=True) learn.metrics = [mean_squared_error, mean_absolute_error, r2_score, explained_variance] learn.fit_one_cycle(10, max_lr = 1e-03)
_____no_output_____
MIT
notebooks/cifar-10/pixelShuffle.ipynb
henriwoodcock/Applying-Modern-Best-Practices-to-Autoencoders
Results Training
learn.show_results(ds_type=DatasetType.Train)
_____no_output_____
MIT
notebooks/cifar-10/pixelShuffle.ipynb
henriwoodcock/Applying-Modern-Best-Practices-to-Autoencoders
Validation
learn.show_results(ds_type=DatasetType.Valid) torch.save(autoencoder, "/content/drive/My Drive/autoencoder-training/pixelShuffle-Cifar10.pt")
_____no_output_____
MIT
notebooks/cifar-10/pixelShuffle.ipynb
henriwoodcock/Applying-Modern-Best-Practices-to-Autoencoders
y_label = np.argmax(y_data, axis=1)y_text = ['bed', 'bird', 'cat', 'dog', 'house', 'tree']y_table = {i:text for i, text in enumerate(y_text)}y_table_array = np.array([(i, text) for i, text in enumerate(y_text)]) x_train_temp, x_test, y_train_temp, y_test = train_test_split( x_2d_data, y_label, test_size=0.2, random_...
np.savez_compressed(path.join(base_path, 'imagenet_6_class_172_train_data_1.npz'), x_data=x_train, y_data=y_train, y_list=y_list) np.savez_compressed(path.join(base_path, 'imagenet_6_class_172_val_data_1.npz'), x_data=x_val, y_data=y_val, y_list=y_list)
_____no_output_____
MIT
make_172_imagenet_6_class_data-Copy1.ipynb
BbChip0103/research_2d_bspl
Control Flow Python if else
def multiply(a, b): """Function to multiply""" print(a * b) print(multiply.__doc__) multiply(5,2) def func(): """Function to check i is greater or smaller""" i=10 if i>5: print("i is greater than 5") else: print("i is less than 15") print(func.__doc__) func()
Function to check i is greater or smaller i is greater than 5
MIT
03...learn_python.ipynb
ram574/Python-Learning
Nested if
if i==20: print("i is 10") if i<15: print("i is less than 15") if i>15: print("i is greater than 15") else: print("Not present")
_____no_output_____
MIT
03...learn_python.ipynb
ram574/Python-Learning
if-elif-else ladder
def func(): i=10 if i==10: print("i is equal to 10") elif i==15: print("Not present") elif i==20: print('i am there') else: print("none") func()
_____no_output_____
MIT
03...learn_python.ipynb
ram574/Python-Learning
Python for loop
def func(): var = input("enter number:") x = int(var) for i in range(x): print(i) func() ## Lists iteration def func(): print("List Iteration") l = ["tulasi", "ram", "ponaganti"] for i in l: print(i) func() # Iterating over a tuple (immutable) def func(): print("\nTuple Iter...
List Iteration tulasi ram ponaganti Tuple Iteration tulasi ram ponaganti String Iteration t u l a s i Dictionary Iteration xyz 123 abc 345
MIT
03...learn_python.ipynb
ram574/Python-Learning
Python for Loop with Continue Statement
def func(): for letter in 'tulasiram': if letter == 'a': continue print(letter) func()
t u l s i r m
MIT
03...learn_python.ipynb
ram574/Python-Learning
Python For Loop with Break Statement
def func(): for letter in 'tulasiram': if letter == 'a': break print('Current Letter :', letter) func()
Current Letter : t Current Letter : u Current Letter : l
MIT
03...learn_python.ipynb
ram574/Python-Learning
Python For Loop with Pass Statement
list = ['tulasi','ram','ponaganti'] def func(): #An empty loop for list in 'ponaganti': pass print('Last Letter :', list) func()
Last Letter : i
MIT
03...learn_python.ipynb
ram574/Python-Learning
Python range
def func(): sum=0 for i in range(1,5): sum = sum + i print(sum) func() def func(): i=5 for x in range(i): i = i+x print(i) func()
5 6 8 11 15
MIT
03...learn_python.ipynb
ram574/Python-Learning
Python for loop with else
for i in range(1, 4): print(i) else: # Executed because no break in for print("No Break\n") for i in range(1, 4): print(i) break else: # Not executed as there is a break print("No Break") ### Using all for loop statements in small program def func(): var = input("enter number:") x = int(va...
1 * 1 = 1 1 * 2 = 2 1 * 3 = 3 1 * 4 = 4 1 * 5 = 5 1 * 6 = 6 1 * 7 = 7 1 * 8 = 8 1 * 9 = 9 1 * 10 = 10 1 * 11 = 11 1 * 12 = 12 2 * 1 = 2 2 * 2 = 4 2 * 3 = 6 2 * 4 = 8 2 * 5 = 10 2 * 6 = 12 2 * 7 = 14 2 * 8 = 16 2 * 9 = 18 2 * 10 = 20 2 * 11 = 22 2 * 12 = 24 3 * 1 = 3 3 * 2 = 6 3 * 3 = 9 3 * 4 = 12 3 * 5 = 15 3 * 6 = 18 ...
MIT
03...learn_python.ipynb
ram574/Python-Learning
Python while loop
## Single line statement def func(): '''first one''' count = 0 while (count < 5): count = count + 1; print("Tulasi Ram") print(func.__doc__) func() ### or def func(): '''Second one''' count = 0 while (count < 5): count = count + 1 print("Tulasi Ram") print(func.__doc__) func...
1 2 3 4 5 6 7 8 9 10 no break
MIT
03...learn_python.ipynb
ram574/Python-Learning
using break in loops
def func(): i=0 for i in range(10): i+=1 print(i) break else: print('no break') func()
1
MIT
03...learn_python.ipynb
ram574/Python-Learning
using continue in loops
def func(): i=0 for i in range(10): i+=1 print(i) continue else: for i in range(5): i+=1 print(i) break func() def func(): i=0 for i in range(10): i+=1 print(i) pass else: for i in range(...
1 2 3 4 5 6 7 8 9 10 1 2 3 4 5
MIT
03...learn_python.ipynb
ram574/Python-Learning
Looping techniques using enumerate()
def enumearteFunc(): list =['tulasi','ram','ponaganti'] for key in enumerate(list): print(key) enumearteFunc() def enumearteFunc(): list =['tulasi','ram','ponaganti'] for key, value in enumerate(list): print(value) enumearteFunc() def zipFunc(): list1 = ['name', 'firstname', 'lastna...
What is your name? I am ram. What is your firstname? I am tulasi. What is your lastname? I am ponaganti.
MIT
03...learn_python.ipynb
ram574/Python-Learning
""" Using iteritem(): iteritems() is used to loop through the dictionary printing the dictionary key-value pair sequentially which is used before Python 3 version Using items(): items() performs the similar task on dictionary as iteritems() but have certain disadvantages when compared with iteritems() "...
def itemFunc(): name = {"name": "tulasi", "firstname": "ram"} print("The key value pair using items is : ") for key, value in name.items(): print(key, value) itemFunc()
The key value pair using items is : name tulasi firstname ram
MIT
03...learn_python.ipynb
ram574/Python-Learning
sorting the list items using loop
def sortedFunc(): list = ['ram','tulasi','ponaganti'] for i in list: print(sorted(i)) continue for i in reversed(list): print(i, end=" ") sortedFunc()
['a', 'm', 'r'] ['a', 'i', 'l', 's', 't', 'u'] ['a', 'a', 'g', 'i', 'n', 'n', 'o', 'p', 't'] ponaganti tulasi ram
MIT
03...learn_python.ipynb
ram574/Python-Learning
Load CNNTracker
#only need to select one model #Model 1 CNN tracker for ICA TOF MRA swc_name = 'cnn_snake' import sys sys.path.append(r'U:\LiChen\AICafe\CNNTracker') from models.centerline_net import CenterlineNet max_points = 500 prob_thr = 0.85 infer_model = CenterlineNet(n_classes=max_points) checkpoint_path_infer = r"D:\tensorf...
_____no_output_____
MIT
CNNTracker1-2.ipynb
clatfd/Coronary-Artery-Tracking-via-3D-CNN-Classification
Load datasets
dbname = 'BRAVEAI' icafe_dir = r'\\DESKTOP2\GiCafe\result/' seg_model_name = 'LumenSeg2-3' with open(icafe_dir+'/'+dbname+'/db.list','rb') as fp: dblist = pickle.load(fp) train_list = dblist['train'] val_list = dblist['val'] test_list = dblist['test'] pilist = [pi.split('/')[1] for pi in dblist['test']] len(pilist...
_____no_output_____
MIT
CNNTracker1-2.ipynb
clatfd/Coronary-Artery-Tracking-via-3D-CNN-Classification
Tracking
# from s.whole.modelname to swc traces from iCafePython.connect.ext import extSnake import SimpleITK as sitk #redo artery tracing RETRACE = 1 #redo artery tree contraint RETREE = 1 #segmentation src seg_src = 's.whole.'+seg_model_name #Lumen segmentation threshold. # Lower value will cause too many noise branches, ...
_____no_output_____
MIT
CNNTracker1-2.ipynb
clatfd/Coronary-Artery-Tracking-via-3D-CNN-Classification
Artery labeling
from iCafePython.artlabel.artlabel import ArtLabel art_label_predictor = ArtLabel() for pi in pilist[:]: print('='*10,'Start processing',pilist.index(pi),'/',len(pilist),pi,'='*10) if not os.path.exists(icafe_dir+'/'+dbname+'/'+pi): os.mkdir(icafe_dir+'/'+dbname+'/'+pi) icafem = iCafe(icafe...
_____no_output_____
MIT
CNNTracker1-2.ipynb
clatfd/Coronary-Artery-Tracking-via-3D-CNN-Classification
Eval
def eval_simple(snakelist): snakelist = copy.deepcopy(snakelist) _ = snakelist.resampleSnakes(1) #ground truth snakelist from icafem.veslist all_metic = snakelist.motMetric(icafem.veslist) metric_dict = all_metic.metrics(['MOTA','IDF1','MOTP','IDS']) #ref_snakelist = icafem.readSnake('ves') ...
_____no_output_____
MIT
CNNTracker1-2.ipynb
clatfd/Coronary-Artery-Tracking-via-3D-CNN-Classification
Assignment of Day 5
lst1 = [1,5,6,4,1,2,3,5] lst2 = [1,5,6,5,1,2,3,6] lst = [1,1,5] count = 0 r=0 for x in lst: for y in lst1[r:]: r+=1 if (x==y): count+=1 break; else: pass if(count==3): print("it’s a Match") else: print("it’s Gone") count = 0 r=0 for x in...
['HEY THIS IS SAI', 'I AM IN MUMBAI', '....']
Apache-2.0
Assignment day5.ipynb
Raghavstyleking/LetsUpgrade-Python-Essentials
Day and Night Image Classifier---The day/night image dataset consists of 200 RGB color images in two categories: day and night. There are equal numbers of each example: 100 day images and 100 night images.We'd like to build a classifier that can accurately label these images as day or night, and that relies on finding...
import cv2 # computer vision library import helpers import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg %matplotlib inline
_____no_output_____
MIT
1_1_Image_Representation/6_3. Average Brightness.ipynb
georgiagn/CVND_Exercises
Training and Testing DataThe 200 day/night images are separated into training and testing datasets. * 60% of these images are training images, for you to use as you create a classifier.* 40% are test images, which will be used to test the accuracy of your classifier.First, we set some variables to keep track of some w...
# Image data directories image_dir_training = "day_night_images/training/" image_dir_test = "day_night_images/test/"
_____no_output_____
MIT
1_1_Image_Representation/6_3. Average Brightness.ipynb
georgiagn/CVND_Exercises
Load the datasetsThese first few lines of code will load the training day/night images and store all of them in a variable, `IMAGE_LIST`. This list contains the images and their associated label ("day" or "night"). For example, the first image-label pair in `IMAGE_LIST` can be accessed by index: ``` IMAGE_LIST[0][:]``...
# Using the load_dataset function in helpers.py # Load training data IMAGE_LIST = helpers.load_dataset(image_dir_training)
_____no_output_____
MIT
1_1_Image_Representation/6_3. Average Brightness.ipynb
georgiagn/CVND_Exercises
Construct a `STANDARDIZED_LIST` of input images and output labels.This function takes in a list of image-label pairs and outputs a **standardized** list of resized images and numerical labels.
# Standardize all training images STANDARDIZED_LIST = helpers.standardize(IMAGE_LIST)
_____no_output_____
MIT
1_1_Image_Representation/6_3. Average Brightness.ipynb
georgiagn/CVND_Exercises
Visualize the standardized dataDisplay a standardized image from STANDARDIZED_LIST.
# Display a standardized image and its label # Select an image by index image_num = 0 selected_image = STANDARDIZED_LIST[image_num][0] selected_label = STANDARDIZED_LIST[image_num][1] # Display image and data about it plt.imshow(selected_image) print("Shape: "+str(selected_image.shape)) print("Label [1 = day, 0 = nig...
Shape: (600, 1100, 3) Label [1 = day, 0 = night]: 1
MIT
1_1_Image_Representation/6_3. Average Brightness.ipynb
georgiagn/CVND_Exercises
Feature ExtractionCreate a feature that represents the brightness in an image. We'll be extracting the **average brightness** using HSV colorspace. Specifically, we'll use the V channel (a measure of brightness), add up the pixel values in the V channel, then divide that sum by the area of the image to get the average...
# Convert and image to HSV colorspace # Visualize the individual color channels image_num = 0 test_im = STANDARDIZED_LIST[image_num][0] test_label = STANDARDIZED_LIST[image_num][1] # Convert to HSV hsv = cv2.cvtColor(test_im, cv2.COLOR_RGB2HSV) # Print image label print('Label: ' + str(test_label)) # HSV channels h...
Label: 1
MIT
1_1_Image_Representation/6_3. Average Brightness.ipynb
georgiagn/CVND_Exercises
--- Find the average brightness using the V channelThis function takes in a **standardized** RGB image and returns a feature (a single value) that represent the average level of brightness in the image. We'll use this value to classify the image as day or night.
# Find the average Value or brightness of an image def avg_brightness(rgb_image): # Convert image to HSV hsv = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2HSV) # Add up all the pixel values in the V channel sum_brightness = np.sum(hsv[:,:,2]) ## TODO: Calculate the average brightness using the ...
Avg brightness: 35.217
MIT
1_1_Image_Representation/6_3. Average Brightness.ipynb
georgiagn/CVND_Exercises
Lab Three---For this lab we're going to be making and using a bunch of functions. Our Goals are:- Switch Case- Looping- Making our own functions- Combining functions- Structuring solutions
// Give me an example of you using switch case. String house = "BlueLions"; switch(house){ case "BlueLions": System.out.println("Dimitri"); case "BlackEagles": System.put.println("Edelgard"); case "GoldenDeer": System.out.println("Claude"); } // Give me an example of you using a for...
_____no_output_____
MIT
JupyterNotebooks/Labs/Lab 3.ipynb
CometSmudge/CMPT-220L-903-21S
class test: def __init__(self,a): self.a=a def display(self): print(self.a) obj=test() obj.display() def f1(): x=100 print(x) x=+1 f1() area = { 'living' : [400, 450], 'living' : [650, 800], 'kitchen' : [300, 250], 'garage' : [250, 0]} print (area['living']) List_1=[2,6,7,8] List_2=[2,6,7,8...
_____no_output_____
MIT
practice_project.ipynb
Abhishekauti21/dsmp-pre-work
Detecting COVID-19 with Chest X Ray using PyTorchImage classification of Chest X Rays in one of three classes: Normal, Viral Pneumonia, COVID-19Dataset from [COVID-19 Radiography Dataset](https://www.kaggle.com/tawsifurrahman/covid19-radiography-database) on Kaggle Importing Libraries
from google.colab import drive drive.mount('/gdrive') %matplotlib inline import os import shutil import copy import random import torch import torch.nn as nn import torchvision import torch.optim as optim from torch.optim import lr_scheduler import numpy as np import seaborn as sns import time from sklearn.metrics imp...
Using PyTorch version 1.7.0+cu101
Apache-2.0
Model/Resnet_18.ipynb
reyvnth/COVIDX
Preparing Training and Test Sets
class_names = ['Non-Covid', 'Covid'] root_dir = '/gdrive/My Drive/Research_Documents_completed/Data/Data/' source_dirs = ['non', 'covid']
_____no_output_____
Apache-2.0
Model/Resnet_18.ipynb
reyvnth/COVIDX
Creating Custom Dataset
class ChestXRayDataset(torch.utils.data.Dataset): def __init__(self, image_dirs, transform): def get_images(class_name): images = [x for x in os.listdir(image_dirs[class_name]) if x.lower().endswith('png') or x.lower().endswith('jpg')] print(f'Found {len(images)} {class_name} example...
_____no_output_____
Apache-2.0
Model/Resnet_18.ipynb
reyvnth/COVIDX
Image Transformations
train_transform = torchvision.transforms.Compose([ torchvision.transforms.Resize(size=(224, 224)), torchvision.transforms.RandomHorizontalFlip(), torchvision.transforms.ToTensor(), torchvision.transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) test_transform = torchvision.tr...
_____no_output_____
Apache-2.0
Model/Resnet_18.ipynb
reyvnth/COVIDX
Prepare DataLoader
train_dirs = { 'Non-Covid': '/gdrive/My Drive/Research_Documents_completed/Data/Data/non/', 'Covid': '/gdrive/My Drive/Research_Documents_completed/Data/Data/covid/' } #train_dirs = { # 'Non-Covid': '/gdrive/My Drive/Data/Data/non/', # 'Covid': '/gdrive/My Drive/Data/Data/covid/' #} train_dataset = Chest...
<torch.utils.data.dataloader.DataLoader object at 0x7f3c11961048> Number of training batches 139 Number of test batches 128
Apache-2.0
Model/Resnet_18.ipynb
reyvnth/COVIDX
Data Visualization
class_names = train_dataset.class_names def show_images(images, labels, preds): plt.figure(figsize=(30, 20)) for i, image in enumerate(images): plt.subplot(1, 25, i + 1, xticks=[], yticks=[]) image = image.numpy().transpose((1, 2, 0)) mean = np.array([0.485, 0.456, 0.406]) std...
_____no_output_____
Apache-2.0
Model/Resnet_18.ipynb
reyvnth/COVIDX
Creating the Model
resnet18 = torchvision.models.resnet18(pretrained=True) print(resnet18) resnet18.fc = torch.nn.Linear(in_features=512, out_features=2) loss_fn = torch.nn.CrossEntropyLoss() optimizer = torch.optim.Adam(resnet18.parameters(), lr=3e-5) print(resnet18) def show_preds(): resnet18.eval() images, labels = next(iter(...
_____no_output_____
Apache-2.0
Model/Resnet_18.ipynb
reyvnth/COVIDX
Training the Model
def train(epochs): best_model_wts = copy.deepcopy(resnet18.state_dict()) b_acc = 0.0 t_loss = [] t_acc = [] avg_t_loss=[] avg_t_acc=[] v_loss = [] v_acc=[] avg_v_loss = [] avg_v_acc = [] ep = [] print('Starting training..') for e in range(0, epochs): ep.append...
Starting training.. ==================== Starting epoch 1/5 ==================== Evaluating at step 0 Training Loss: 0.8522, Training Accuracy: 0.4800
Apache-2.0
Model/Resnet_18.ipynb
reyvnth/COVIDX
Final Results VALIDATION LOSS AND TRAINING LOSS VS EPOCHVALIDATION ACCURACY AND TRAINING ACCURACY VS EPOCHBEST ACCURACY ERROR..
show_preds()
_____no_output_____
Apache-2.0
Model/Resnet_18.ipynb
reyvnth/COVIDX
Plotting Target Pixel Files with Lightkurve Learning GoalsBy the end of this tutorial, you will:- Learn how to download and plot target pixel files from the data archive using [Lightkurve](https://docs.lightkurve.org).- Be able to plot the target pixel file background.- Be able to extract and plot flux from a target ...
import lightkurve as lk import matplotlib.pyplot as plt %matplotlib inline
_____no_output_____
MIT
docs/source/tutorials/1-getting-started/plotting-target-pixel-files.ipynb
alex-w/lightkurve
1. Downloading a TPF A TPF contains the original imaging data from which a light curve is derived. Besides the brightness data measured by the charge-coupled device (CCD) camera, a TPF also includes post-processing information such as an estimate of the astronomical background, and a recommended pixel aperture for ext...
search_result = lk.search_targetpixelfile("Kepler-8", author="Kepler", quarter=4, cadence="long") search_result tpf = search_result.download()
_____no_output_____
MIT
docs/source/tutorials/1-getting-started/plotting-target-pixel-files.ipynb
alex-w/lightkurve
This TPF contains data for every cadence in the quarter we downloaded. Let's focus on the first cadence for now, which we can select using zero-based indexing as follows:
first_cadence = tpf[0] first_cadence
_____no_output_____
MIT
docs/source/tutorials/1-getting-started/plotting-target-pixel-files.ipynb
alex-w/lightkurve
2. Flux and Background At each cadence the TPF has a number of photometry data properties. These are:- `flux_bkg`: the astronomical background of the image.- `flux_bkg_err`: the statistical uncertainty on the background flux.- `flux`: the stellar flux after the background is removed.- `flux_err`: the statistical uncer...
first_cadence.flux.value
_____no_output_____
MIT
docs/source/tutorials/1-getting-started/plotting-target-pixel-files.ipynb
alex-w/lightkurve
And you can plot the data as follows:
first_cadence.plot(column='flux');
_____no_output_____
MIT
docs/source/tutorials/1-getting-started/plotting-target-pixel-files.ipynb
alex-w/lightkurve
Alternatively, if you are working directly with a FITS file, you can access the data in extension 1 (for example, `first_cadence.hdu[1].data['FLUX']`). Note that you can find all of the details on the structure and contents of TPF files in Section 2.3.2 of the [*Kepler* Archive Manual](http://archive.stsci.edu/files/li...
fig, axes = plt.subplots(2,2, figsize=(16,16)) first_cadence.plot(ax=axes[0,0], column='FLUX') first_cadence.plot(ax=axes[0,1], column='FLUX_BKG') first_cadence.plot(ax=axes[1,0], column='FLUX_ERR') first_cadence.plot(ax=axes[1,1], column='FLUX_BKG_ERR');
_____no_output_____
MIT
docs/source/tutorials/1-getting-started/plotting-target-pixel-files.ipynb
alex-w/lightkurve
From looking at the color scale on both plots, you may see that the background flux is very low compared to the total flux emitted by a star. This is expected — stars are bright! But these small background corrections become important when looking at the very small scale changes caused by planets or stellar oscillation...
first_cadence.plot(bkg=True);
_____no_output_____
MIT
docs/source/tutorials/1-getting-started/plotting-target-pixel-files.ipynb
alex-w/lightkurve
In this case, the background is low and the star is bright, so it doesn't appear to make much of a difference. 3. Apertures As part of the data processing done by the *Kepler* pipeline, each TPF includes a recommended *optimal aperture mask*. This aperture mask is optimized to ensure that the stellar signal has a high...
first_cadence.pipeline_mask
_____no_output_____
MIT
docs/source/tutorials/1-getting-started/plotting-target-pixel-files.ipynb
alex-w/lightkurve
As you can see, it is a Boolean array detailing which pixels are included. We can plot this aperture over the top of our TPF using the `plot()` function, and passing in the mask to the `aperture_mask` keyword. This will highlight the pixels included in the aperture mask using red hatched lines.
first_cadence.plot(aperture_mask=first_cadence.pipeline_mask);
_____no_output_____
MIT
docs/source/tutorials/1-getting-started/plotting-target-pixel-files.ipynb
alex-w/lightkurve
You don't necessarily have to pass in the `pipeline_mask` to the `plot()` function; it can be any mask you create yourself, provided it is the right shape. An accompanying tutorial explains how to create such custom apertures, and goes into aperture photometry in more detail. For specifics on the selection of *Kepler*'...
lc = tpf.to_lightcurve()
_____no_output_____
MIT
docs/source/tutorials/1-getting-started/plotting-target-pixel-files.ipynb
alex-w/lightkurve
This method returns a `LightCurve` object which details the flux and flux centroid position at each cadence:
lc
_____no_output_____
MIT
docs/source/tutorials/1-getting-started/plotting-target-pixel-files.ipynb
alex-w/lightkurve
Note that this [`KeplerLightCurve`](https://docs.lightkurve.org/api/lightkurve.lightcurve.KeplerLightCurve.html) object has fewer data columns than in light curves downloaded directly from MAST. This is because we are extracting our light curve directly from the TPF using minimal processing, whereas light curves create...
lc.plot();
_____no_output_____
MIT
docs/source/tutorials/1-getting-started/plotting-target-pixel-files.ipynb
alex-w/lightkurve
This light curve is similar to the SAP light curve we previously encountered in the light curve tutorial. NoteThe background flux can be plotted in a similar way, using the [`get_bkg_lightcurve()`](https://docs.lightkurve.org/api/lightkurve.targetpixelfile.KeplerTargetPixelFile.htmllightkurve.targetpixelfile.KeplerTar...
bkg = tpf.get_bkg_lightcurve() bkg.plot();
_____no_output_____
MIT
docs/source/tutorials/1-getting-started/plotting-target-pixel-files.ipynb
alex-w/lightkurve
Inspecting the background in this way is useful to identify signals which appear to be present in the background rather than in the astronomical object under study. --- Exercises Some stars, such as the planet-hosting star Kepler-10, have been observed both with *Kepler* and *TESS*. In this exercise, download and plot...
#datalist = lk.search_targetpixelfile(...) #soln: datalist = lk.search_targetpixelfile("Kepler-10") datalist kep = datalist[6].download() tes = datalist[15].download() fig, axes = plt.subplots(1, 2, figsize=(14,6)) kep.plot(ax=axes[0], aperture_mask=kep.pipeline_mask, scale='log') tes.plot(ax=axes[1], aperture_mask=te...
_____no_output_____
MIT
docs/source/tutorials/1-getting-started/plotting-target-pixel-files.ipynb
alex-w/lightkurve
Copyright 2018 The TensorFlow Authors. [Licensed under the Apache License, Version 2.0](scrollTo=ByZjmtFgB_Y5).
// #@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" } // 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/LICE...
_____no_output_____
Apache-2.0
docs/site/tutorials/python_interoperability.ipynb
texasmichelle/swift
View on TensorFlow.org Run in Google Colab View source on GitHub Python interoperabilitySwift For TensorFlow supports Python interoperability.You can import Python modules from Swift, call Python functions, and convert values between Swift and Python.
import PythonKit print(Python.version)
_____no_output_____
Apache-2.0
docs/site/tutorials/python_interoperability.ipynb
texasmichelle/swift
Setting the Python version By default, when you `import Python`, Swift searches system library paths for the newest version of Python installed. To use a specific Python installation, set the `PYTHON_LIBRARY` environment variable to the `libpython` shared library provided by the installation. For example: `export PYTH...
// PythonLibrary.useVersion(2) // PythonLibrary.useVersion(3, 7)
_____no_output_____
Apache-2.0
docs/site/tutorials/python_interoperability.ipynb
texasmichelle/swift
__Note: you should run `PythonLibrary.useVersion` right after `import Python`, before calling any Python code. It cannot be used to dynamically switch Python versions.__ Set `PYTHON_LOADER_LOGGING=1` to see [debug output for Python library loading](https://github.com/apple/swift/pull/20674discussion_r235207008). Basi...
// Convert standard Swift types to Python. let pythonInt: PythonObject = 1 let pythonFloat: PythonObject = 3.0 let pythonString: PythonObject = "Hello Python!" let pythonRange: PythonObject = PythonObject(5..<10) let pythonArray: PythonObject = [1, 2, 3, 4] let pythonDict: PythonObject = ["foo": [0], "bar": [1, 2, 3]] ...
_____no_output_____
Apache-2.0
docs/site/tutorials/python_interoperability.ipynb
texasmichelle/swift
`PythonObject` defines conformances to many standard Swift protocols:* `Equatable`* `Comparable`* `Hashable`* `SignedNumeric`* `Strideable`* `MutableCollection`* All of the `ExpressibleBy_Literal` protocolsNote that these conformances are not type-safe: crashes will occur if you attempt to use protocol functionality fr...
let one: PythonObject = 1 print(one == one) print(one < one) print(one + one) let array: PythonObject = [1, 2, 3] for (i, x) in array.enumerated() { print(i, x) }
_____no_output_____
Apache-2.0
docs/site/tutorials/python_interoperability.ipynb
texasmichelle/swift
To convert tuples from Python to Swift, you must statically know the arity of the tuple.Call one of the following instance methods:- `PythonObject.tuple2`- `PythonObject.tuple3`- `PythonObject.tuple4`
let pythonTuple = Python.tuple([1, 2, 3]) print(pythonTuple, Python.len(pythonTuple)) // Convert to Swift. let tuple = pythonTuple.tuple3 print(tuple)
_____no_output_____
Apache-2.0
docs/site/tutorials/python_interoperability.ipynb
texasmichelle/swift
Python builtinsAccess Python builtins via the global `Python` interface.
// `Python.builtins` is a dictionary of all Python builtins. _ = Python.builtins // Try some Python builtins. print(Python.type(1)) print(Python.len([1, 2, 3])) print(Python.sum([1, 2, 3]))
_____no_output_____
Apache-2.0
docs/site/tutorials/python_interoperability.ipynb
texasmichelle/swift
Importing Python modulesUse `Python.import` to import a Python module. It works like the `import` keyword in `Python`.
let np = Python.import("numpy") print(np) let zeros = np.ones([2, 3]) print(zeros)
_____no_output_____
Apache-2.0
docs/site/tutorials/python_interoperability.ipynb
texasmichelle/swift
Use the throwing function `Python.attemptImport` to perform safe importing.
let maybeModule = try? Python.attemptImport("nonexistent_module") print(maybeModule)
_____no_output_____
Apache-2.0
docs/site/tutorials/python_interoperability.ipynb
texasmichelle/swift
Conversion with `numpy.ndarray`The following Swift types can be converted to and from `numpy.ndarray`:- `Array`- `ShapedArray`- `Tensor`Conversion succeeds only if the `dtype` of the `numpy.ndarray` is compatible with the `Element` or `Scalar` generic parameter type.For `Array`, conversion from `numpy` succeeds only i...
import TensorFlow let numpyArray = np.ones([4], dtype: np.float32) print("Swift type:", type(of: numpyArray)) print("Python type:", Python.type(numpyArray)) print(numpyArray.shape) // Examples of converting `numpy.ndarray` to Swift types. let array: [Float] = Array(numpy: numpyArray)! let shapedArray = ShapedArray<Flo...
_____no_output_____
Apache-2.0
docs/site/tutorials/python_interoperability.ipynb
texasmichelle/swift
Displaying imagesYou can display images in-line using `matplotlib`, just like in Python notebooks.
// This cell is here to display plots inside a Jupyter Notebook. // Do not copy it into another environment. %include "EnableIPythonDisplay.swift" print(IPythonDisplay.shell.enable_matplotlib("inline")) let np = Python.import("numpy") let plt = Python.import("matplotlib.pyplot") let time = np.arange(0, 10, 0.01) let a...
_____no_output_____
Apache-2.0
docs/site/tutorials/python_interoperability.ipynb
texasmichelle/swift
Example 1: Sandstone Model
# Importing import theano.tensor as T import theano import sys, os sys.path.append("../GeMpy") sys.path.append("../") # Importing GeMpy modules import gempy as GeMpy # Reloading (only for development purposes) import importlib importlib.reload(GeMpy) # Usuful packages import numpy as np import pandas as pn import ma...
Function profiling ================== Message: <ipython-input-6-22dcf15bad61>:3 Time in 5 calls to Function.__call__: 1.357155e+01s Time in Function.fn.__call__: 1.357096e+01s (99.996%) Time in thunks: 1.357014e+01s (99.990%) Total compile time: 2.592983e+01s Number of Apply nodes: 95 Theano Optimizer...
MIT
Prototype Notebook/Example_1_Sandstone.ipynb
nre-aachen/gempy
Below here so far is deprecated First we make a GeMpy instance with most of the parameters default (except range that is given by the project). Then we also fix the extension and the resolution of the domain we want to interpolate. Finally we compile the function, only needed once every time we open the project (the g...
# Create a class Grid so far just regular grid #GeMpy.set_grid(geo_data) #GeMpy.get_grid(geo_data)
_____no_output_____
MIT
Prototype Notebook/Example_1_Sandstone.ipynb
nre-aachen/gempy
Plotting raw data The object Plot is created automatically as we call the methods above. This object contains some methods to plot the data and the results.It is possible to plot a 2D projection of the data in a specific direction using the following method. Also is possible to choose the series you want to plot. Addi...
#GeMpy.plot_data(geo_data, 'y', geo_data.series.columns.values[1])
_____no_output_____
MIT
Prototype Notebook/Example_1_Sandstone.ipynb
nre-aachen/gempy
Class Interpolator This class will take the data from the class Data and calculate potential fields and block. We can pass as key arguments all the variables of the interpolation. I recommend not to touch them if you do not know what are you doing. The default values should be good enough. Also the first time we execu...
%debug geo_data.interpolator.results geo_data.interpolator.tg.c_o_T.get_value(), geo_data.interpolator.tg.a_T.get_value() geo_data.interpolator.compile_potential_field_function() geo_data.interpolator.compute_potential_fields('BIF_Series',verbose = 3) geo_data.interpolator.potential_fields geo_data.interpolator.results...
_____no_output_____
MIT
Prototype Notebook/Example_1_Sandstone.ipynb
nre-aachen/gempy
Now we could visualize the individual potential fields as follow: Early granite
GeMpy.plot_potential_field(geo_data,10, n_pf=0)
_____no_output_____
MIT
Prototype Notebook/Example_1_Sandstone.ipynb
nre-aachen/gempy
BIF Series
GeMpy.plot_potential_field(geo_data,13, n_pf=1, cmap = "magma", plot_data = True, verbose = 5)
_____no_output_____
MIT
Prototype Notebook/Example_1_Sandstone.ipynb
nre-aachen/gempy
SImple mafic
GeMpy.plot_potential_field(geo_data, 10, n_pf=2)
_____no_output_____
MIT
Prototype Notebook/Example_1_Sandstone.ipynb
nre-aachen/gempy
Optimizing the export of lithologiesBut usually the final result we want to get is the final block. The method `compute_block_model` will compute the block model, updating the attribute `block`. This attribute is a theano shared function that can return a 3D array (raveled) using the method `get_value()`.
GeMpy.compute_block_model(geo_data) #GeMpy.set_interpolator(geo_data, u_grade = 0, compute_potential_field=True)
_____no_output_____
MIT
Prototype Notebook/Example_1_Sandstone.ipynb
nre-aachen/gempy
And again after computing the model in the Plot object we can use the method `plot_block_section` to see a 2D section of the model
GeMpy.plot_section(geo_data, 13, direction='y')
_____no_output_____
MIT
Prototype Notebook/Example_1_Sandstone.ipynb
nre-aachen/gempy
Export to vtk. (*Under development*)
"""Export model to VTK Export the geology blocks to VTK for visualisation of the entire 3-D model in an external VTK viewer, e.g. Paraview. ..Note:: Requires pyevtk, available for free on: https://github.com/firedrakeproject/firedrake/tree/master/python/evtk **Optional keywords**: - *vtk_filename* = string : fil...
_____no_output_____
MIT
Prototype Notebook/Example_1_Sandstone.ipynb
nre-aachen/gempy