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
**Option 3:** Draw once before loop
np.random.seed(1917) x = np.random.normal(0,1,size=100) print(f'var(x) = {np.var(x):.3f}') y_ = np.random.normal(0,1,size=x.size) for sigma in [0.5,1.0,0.5]: y = sigma*y_ print(f'sigma = {sigma:2f}: f = {f(x,y):.4f}')
var(x) = 0.951 sigma = 0.500000: f = 0.5522 sigma = 1.000000: f = 0.0143 sigma = 0.500000: f = 0.5522
MIT
web/06/Examples_and_overview.ipynb
Jovansam/lectures-2021
Image Combination Joint Single Dish and Interferometer Image Reconstruction The SDINT imaging algorithm allows joint reconstruction of wideband single dish and interferometer data. This algorithm is available in the task [sdintimaging](../api/casatasks.rstimaging) and described in [Rau, Naik & Braun (2019)](https://...
_____no_output_____
Apache-2.0
docs/notebooks/image_combination.ipynb
yohei99/casadocs
IPL Dataset Analysis Problem StatementWe want to know as to what happens during an IPL match which raises several questions in our mind with our limited knowledge about the game called cricket on which it is based. This analysis is done to know as which factors led one of the team to win and how does it matter. Abou...
import numpy as np # Not every data format will be in csv there are other file formats also. # This exercise will help you deal with other file formats and how toa read it. path = './ipl_matches_small.csv' data_ipl = np.genfromtxt(path, delimiter=',', skip_header=1, dtype=str) print(data_ipl)
[['392203' '2009-05-01' 'East London' ... '' '' ''] ['392203' '2009-05-01' 'East London' ... '' '' ''] ['392203' '2009-05-01' 'East London' ... '' '' ''] ... ['335987' '2008-04-21' 'Jaipur' ... '' '' ''] ['335987' '2008-04-21' 'Jaipur' ... '' '' ''] ['335987' '2008-04-21' 'Jaipur' ... '' '' '']]
MIT
Manipulating_Data_with_NumPy_Code_Along.ipynb
vidSanas/greyatom-python-for-data-science
Calculate the unique no. of matches in the provided dataset ?
# How many matches were held in total we need to know so that we can analyze further statistics keeping that in mind.im import numpy as np unique_match_code=np.unique(data_ipl[:,0]) print(unique_match_code)
['335987' '392197' '392203' '392212' '501226' '729297']
MIT
Manipulating_Data_with_NumPy_Code_Along.ipynb
vidSanas/greyatom-python-for-data-science
Find the set of all unique teams that played in the matches in the data set.
# this exercise deals with you getting to know that which are all those six teams that played in the tournament. import numpy as np unique_match_team3=np.unique(data_ipl[:,3]) print(unique_match_team3) unique_match_team4=np.unique(data_ipl[:,4]) print(unique_match_team4) union=np.union1d(unique_match_team3,unique_matc...
_____no_output_____
MIT
Manipulating_Data_with_NumPy_Code_Along.ipynb
vidSanas/greyatom-python-for-data-science
Find sum of all extras in all deliveries in all matches in the dataset
# An exercise to make you familiar with indexing and slicing up within data. import numpy as np extras=data_ipl[:,17] data=extras.astype(np.int) print(sum(data))
88
MIT
Manipulating_Data_with_NumPy_Code_Along.ipynb
vidSanas/greyatom-python-for-data-science
Get the array of all delivery numbers when a given player got out. Also mention the wicket type.
import numpy as np deliveries=[] wicket_type=[] for i in data_ipl: if(i[20]!=""): a=i[11] b=i[21] deliveries.append(a) wicket_type.append(b) print(deliveries) print(wicket_type)
_____no_output_____
MIT
Manipulating_Data_with_NumPy_Code_Along.ipynb
vidSanas/greyatom-python-for-data-science
How many matches the team `Mumbai Indians` has won the toss?
data_arr=[] for i in data_ipl: if(i[5]=="Mumbai Indians"): data_arr.append(i[0]) unique_match_id=np.unique(data_arr) print(unique_match_id) print(len(unique_match_id))
['392197' '392203'] 2
MIT
Manipulating_Data_with_NumPy_Code_Along.ipynb
vidSanas/greyatom-python-for-data-science
Create a filter that filters only those records where the batsman scored 6 runs. Also who has scored the maximum no. of sixes overall ?
# An exercise to know who is the most aggresive player or maybe the scoring player import numpy as np counter=0 run_dict={} arr=[] for i in data_ipl: #print(i[13]) #current_run = i[16] #prev_run = run_dict[batsman_nm] #batsman_nm = i[13] #if prev_run == None: #run_dict[batsman_nm] = current_run #else: ...
_____no_output_____
MIT
Manipulating_Data_with_NumPy_Code_Along.ipynb
vidSanas/greyatom-python-for-data-science
读取数据
import torchvision.transforms as T img_shape = (3, 224, 224) def read_raw_img(path, resize, L=False): img = Image.open(path) if resize: img = img.resize(resize) if L: img = img.convert('L') return np.asarray(img) class DogCat(data.Dataset): def __init__(self,path, img_shape): # ...
_____no_output_____
Apache-2.0
Pytorch/Task4.ipynb
asd55667/DateWhale
构建模型
import math class Vgg16(nn.Module): def __init__(self, features, num_classes=1, init_weights=True): super(Vgg16, self).__init__() self.features = features self.classifier = nn.Sequential( nn.Linear(512 * 7 * 7, 4096), nn.ReLU(True), nn.Dropout(), ...
_____no_output_____
Apache-2.0
Pytorch/Task4.ipynb
asd55667/DateWhale
损失函数与优化器
vgg = Vgg16(make_layers(cfg, 'RGB')).cuda() print(vgg) criterion = nn.BCELoss() optimizer = t.optim.Adam(vgg.parameters(),lr=0.001)
Vgg16( (features): Sequential( (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (1): ReLU(inplace) (2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (3): ReLU(inplace) (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False) (5):...
Apache-2.0
Pytorch/Task4.ipynb
asd55667/DateWhale
模型训练
use_cuda = t.cuda.is_available() device = t.device("cuda:0" if use_cuda else "cpu") # cudnn.benchmark = True # Parameters params = {'batch_size': 64, 'shuffle': True, 'num_workers': 6} max_epochs = 1 # train = DogCat(path+'train', img_shape) training_generator = data.DataLoader(train, **params...
/home/wcw/anaconda3/envs/tf/lib/python3.6/site-packages/torch/nn/functional.py:2016: UserWarning: Using a target size (torch.Size([64])) that is different to the input size (torch.Size([64, 1])) is deprecated. Please ensure they have the same size. "Please ensure they have the same size.".format(target.size(), input....
Apache-2.0
Pytorch/Task4.ipynb
asd55667/DateWhale
模型评估
accs = [] test = DogCat(path+'test', img_shape=img_shape) test_loader = data.DataLoader(test, **params) with t.set_grad_enabled(False): for x, y_ in test_loader: x, y_ = x.float().to(device), y_.float().to(device) y = vgg(x) acc = y.eq(y_).sum().item()/y.shape[0] # ...
_____no_output_____
Apache-2.0
Pytorch/Task4.ipynb
asd55667/DateWhale
<imgsrc="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"><imgsrc="https://img.shields.io/badge/GitHub-100000?logo=github&logoColor=white" alt="GitHub"> Text Annotation Import* This notebook will provide examples of each supported annotation type for text assets. It will cover the foll...
!pip install -q 'labelbox[data]'
_____no_output_____
Apache-2.0
examples/model_assisted_labeling/ner_mal.ipynb
Cyniikal/labelbox-python
Imports
from labelbox.schema.ontology import OntologyBuilder, Tool, Classification, Option from labelbox import Client, LabelingFrontend, LabelImport, MALPredictionImport from labelbox.data.annotation_types import ( Label, TextData, Checklist, Radio, ObjectAnnotation, TextEntity, ClassificationAnnotation, Classificatio...
_____no_output_____
Apache-2.0
examples/model_assisted_labeling/ner_mal.ipynb
Cyniikal/labelbox-python
API Key and ClientProvide a valid api key below in order to properly connect to the Labelbox Client.
# Add your api key API_KEY = None client = Client(api_key=API_KEY)
INFO:labelbox.client:Initializing Labelbox client at 'https://api.labelbox.com/graphql'
Apache-2.0
examples/model_assisted_labeling/ner_mal.ipynb
Cyniikal/labelbox-python
---- Steps1. Make sure project is setup2. Collect annotations3. Upload Project setup We will be creating two projects, one for model-assisted labeling, and one for label imports
ontology_builder = OntologyBuilder( tools=[ Tool(tool=Tool.Type.NER, name="named_entity") ], classifications=[ Classification(class_type=Classification.Type.CHECKLIST, instructions="checklist", options=[ Option(value="first_checklist_answer"), Option(value="second...
_____no_output_____
Apache-2.0
examples/model_assisted_labeling/ner_mal.ipynb
Cyniikal/labelbox-python
Create Label using Annotation Type Objects* It is recommended to use the Python SDK's annotation types for importing into Labelbox. Object Annotations
def create_objects(): named_enity = TextEntity(start=10,end=20) named_enity_annotation = ObjectAnnotation(value=named_enity, name="named_entity") return named_enity_annotation
_____no_output_____
Apache-2.0
examples/model_assisted_labeling/ner_mal.ipynb
Cyniikal/labelbox-python
Classification Annotations
def create_classifications(): checklist = Checklist(answer=[ClassificationAnswer(name="first_checklist_answer"),ClassificationAnswer(name="second_checklist_answer")]) checklist_annotation = ClassificationAnnotation(value=checklist, name="checklist") radio = Radio(answer = ClassificationAnswer(name = "second_radio...
_____no_output_____
Apache-2.0
examples/model_assisted_labeling/ner_mal.ipynb
Cyniikal/labelbox-python
Create a Label object with all of our annotations
image_data = TextData(uid=data_row.uid) named_enity_annotation = create_objects() checklist_annotation, radio_annotation = create_classifications() label = Label( data=image_data, annotations = [ named_enity_annotation, checklist_annotation, radio_annotation ] ) label.__dict__
_____no_output_____
Apache-2.0
examples/model_assisted_labeling/ner_mal.ipynb
Cyniikal/labelbox-python
Model Assisted Labeling To do model-assisted labeling, we need to convert a Label object into an NDJSON. This is easily done with using the NDJSONConverter classWe will create a Label called mal_label which has the same original structure as the label aboveNotes:* Each label requires a valid feature schema id. We wil...
mal_label = Label( data=image_data, annotations = [ named_enity_annotation, checklist_annotation, radio_annotation ] ) mal_label.assign_feature_schema_ids(ontology_builder.from_project(mal_project)) ndjson_labels = list(NDJsonConverter.serialize([mal_label])) ndjson_labels upload_job = MALPredict...
INFO:labelbox.schema.annotation_import:Sleeping for 10 seconds...
Apache-2.0
examples/model_assisted_labeling/ner_mal.ipynb
Cyniikal/labelbox-python
Label Import Label import is very similar to model-assisted labeling. We will need to re-assign the feature schema before continuing, but we can continue to use our NDJSonConverterWe will create a Label called li_label which has the same original structure as the label above
#for the purpose of this notebook, we will need to reset the schema ids of our checklist and radio answers image_data = TextData(uid=data_row.uid) named_enity_annotation = create_objects() checklist_annotation, radio_annotation = create_classifications() li_label = Label( data=image_data, annotations = [ ...
INFO:labelbox.schema.annotation_import:Sleeping for 10 seconds...
Apache-2.0
examples/model_assisted_labeling/ner_mal.ipynb
Cyniikal/labelbox-python
Hough Lines Import resources and display the image
import numpy as np import matplotlib.pyplot as plt import cv2 %matplotlib inline # Read in the image image = cv2.imread('images/phone.jpg') # Change color to RGB (from BGR) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) plt.imshow(image)
_____no_output_____
MIT
1_2_Convolutional_Filters_Edge_Detection/.ipynb_checkpoints/6_1. Hough lines-checkpoint.ipynb
sxtien/CVND_Exercises
Perform edge detection
# Convert image to grayscale gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) # Define our parameters for Canny low_threshold = 50 high_threshold = 100 edges = cv2.Canny(gray, low_threshold, high_threshold) plt.imshow(edges, cmap='gray')
_____no_output_____
MIT
1_2_Convolutional_Filters_Edge_Detection/.ipynb_checkpoints/6_1. Hough lines-checkpoint.ipynb
sxtien/CVND_Exercises
Find lines using a Hough transform
# Define the Hough transform parameters # Make a blank the same size as our image to draw on rho = 1 theta = np.pi/180 threshold = 60 min_line_length = 50 max_line_gap = 5 line_image = np.copy(image) #creating an image copy to draw lines on # Run Hough on the edge-detected image lines = cv2.HoughLinesP(edges, rho, th...
_____no_output_____
MIT
1_2_Convolutional_Filters_Edge_Detection/.ipynb_checkpoints/6_1. Hough lines-checkpoint.ipynb
sxtien/CVND_Exercises
import torch x = torch.arange(18).view(3,2,3) print(x) print(x[0,0,0]) print(x[1,0,0]) print(x[1,1,1]) x[1,0:2,0:2]
_____no_output_____
MIT
Chapter3_Slicing_3D_Tensors.ipynb
SokichiFujita/PyTorch-for-Deep-Learning-and-Computer-Vision
Using the same code as before, please solve the following exercises 1. Change the number of observations to 100,000 and see what happens. 2. Play around with the learning rate. Values like 0.0001, 0.001, 0.1, 1 are all interesting to observe. 3. Change the loss function. An alternative loss for regressions i...
# We must always import the relevant libraries for our problem at hand. NumPy and TensorFlow are required for this example. import numpy as np import matplotlib.pyplot as plt import tensorflow as tf
_____no_output_____
Apache-2.0
17 - Deep Learning with TensorFlow 2.0/5_Introduction to TensorFlow 2/8_Exercises/TensorFlow_Minimal_example_All_exercises.ipynb
olayinka04/365-data-science-courses
Data generationWe generate data using the exact same logic and code as the example from the previous notebook. The only difference now is that we save it to an npz file. Npz is numpy's file type which allows you to save numpy arrays into a single .npz file. We introduce this change because in machine learning most oft...
# First, we should declare a variable containing the size of the training set we want to generate. observations = 1000 # We will work with two variables as inputs. You can think about them as x1 and x2 in our previous examples. # We have picked x and z, since it is easier to differentiate them. # We generate them rand...
_____no_output_____
Apache-2.0
17 - Deep Learning with TensorFlow 2.0/5_Introduction to TensorFlow 2/8_Exercises/TensorFlow_Minimal_example_All_exercises.ipynb
olayinka04/365-data-science-courses
Solving with TensorFlowNote: This intro is just the basics of TensorFlow which has way more capabilities and depth than that.
# Load the training data from the NPZ training_data = np.load('TF_intro.npz') # Declare a variable where we will store the input size of our model # It should be equal to the number of variables you have input_size = 2 # Declare the output size of the model # It should be equal to the number of outputs you've got (for ...
Epoch 1/100 1000/1000 - 0s - loss: 24.5755 Epoch 2/100 1000/1000 - 0s - loss: 1.1773 Epoch 3/100 1000/1000 - 0s - loss: 0.4253 Epoch 4/100 1000/1000 - 0s - loss: 0.3853 Epoch 5/100 1000/1000 - 0s - loss: 0.3727 Epoch 6/100 1000/1000 - 0s - loss: 0.3932 Epoch 7/100 1000/1000 - 0s - loss: 0.3817 Epoch 8/100 1000/1000 - 0...
Apache-2.0
17 - Deep Learning with TensorFlow 2.0/5_Introduction to TensorFlow 2/8_Exercises/TensorFlow_Minimal_example_All_exercises.ipynb
olayinka04/365-data-science-courses
Extract the weights and biasExtracting the weight(s) and bias(es) of a model is not an essential step for the machine learning process. In fact, usually they would not tell us much in a deep learning context. However, this simple example was set up in a way, which allows us to verify if the answers we get are correct.
# Extracting the weights and biases is achieved quite easily model.layers[0].get_weights() # We can save the weights and biases in separate variables for easier examination # Note that there can be hundreds or thousands of them! weights = model.layers[0].get_weights()[0] weights # We can save the weights and biases in ...
_____no_output_____
Apache-2.0
17 - Deep Learning with TensorFlow 2.0/5_Introduction to TensorFlow 2/8_Exercises/TensorFlow_Minimal_example_All_exercises.ipynb
olayinka04/365-data-science-courses
Extract the outputs (make predictions)Once more, this is not an essential step, however, we usually want to be able to make predictions.
# We can predict new values in order to actually make use of the model # Sometimes it is useful to round the values to be able to read the output # Usually we use this method on NEW DATA, rather than our original training data model.predict_on_batch(training_data['inputs']).round(1) # If we display our targets (actual ...
_____no_output_____
Apache-2.0
17 - Deep Learning with TensorFlow 2.0/5_Introduction to TensorFlow 2/8_Exercises/TensorFlow_Minimal_example_All_exercises.ipynb
olayinka04/365-data-science-courses
Plotting the data
# The model is optimized, so the outputs are calculated based on the last form of the model # We have to np.squeeze the arrays in order to fit them to what the plot function expects. # Doesn't change anything as we cut dimensions of size 1 - just a technicality. plt.plot(np.squeeze(model.predict_on_batch(training_data...
_____no_output_____
Apache-2.0
17 - Deep Learning with TensorFlow 2.0/5_Introduction to TensorFlow 2/8_Exercises/TensorFlow_Minimal_example_All_exercises.ipynb
olayinka04/365-data-science-courses
Loan Default Risk - Exploratory Data Analysis This notebook is focused on data exploration. The key objective is to familiarise myself with the data and to identify any issues. This could lead to data cleaning or feature engineering. Contents 1. Importing Relevant Libraries, Reading In Data 2. Anomly Detection and...
#Importing data wrangling library import pandas as pd #Data Wrangling/Cleaning package for mixed data import numpy as np #Data wrangling & manipulation for numerical data import os #Importing visulization libraries from matplotlib i...
_____no_output_____
MIT
notebooks/ExploratoryDataAnalysis.ipynb
geracharu/DataScienceProject
1.2 Reading In Data
rawfilepath = 'C:/Users/chara.geru/OneDrive - Avanade/DataScienceProject/HomeCreditModel/data/raw/' filename = 'application_train.csv' interimfilepath1 = 'C:/Users/chara.geru/OneDrive - Avanade/DataScienceProject/HomeCreditModel/data/interim/' filename1 = 'df1.csv' filename2 = 'df2.csv' application_train = pd.read_c...
Size of application_train data: (307511, 122)
MIT
notebooks/ExploratoryDataAnalysis.ipynb
geracharu/DataScienceProject
This dataset has: - 122 columns (features)- 307511 rows
application_train.columns.values #Printing all column names pd.set_option('display.max_columns', None) #Display all columns application_train.describe() #Get summary statistics for all columns application_train.head() ...
_____no_output_____
MIT
notebooks/ExploratoryDataAnalysis.ipynb
geracharu/DataScienceProject
Generally the data looks good based on the statistics shown from the describe method. Potentional issues - Values in DAYS_BIRTH column are negative. They represent number of days a person was before they applied for a loan. For a better representation, I will convert them to positive values and convert days to years, ...
(application_train['DAYS_BIRTH']).describe() (application_train['DAYS_EMPLOYED']).describe()
_____no_output_____
MIT
notebooks/ExploratoryDataAnalysis.ipynb
geracharu/DataScienceProject
3.1 Check for Nulls
# "This function creates a table to summarize the null values" def nulltable(df): """ This function creates a table to summarize the null values """ total = df.isnull().sum().sort_values(ascending = False) percent = (df.isnull().sum()/df.isnull().count()*100).sort_values(ascending = False) ...
_____no_output_____
MIT
notebooks/ExploratoryDataAnalysis.ipynb
geracharu/DataScienceProject
- There are a large number of columns(features) with more than 50% NULLS.- I've deicided to drop these columns as they will not provide much information for training the model.- If a feaure has less than 50% NULLS, these maybe filled up using an appropriate calcualtion such as mean, median or mode 3.2 Data balanced or...
#Data balanced or imbalanced temp = application_train["TARGET"].value_counts() fig1, ax1 = plt.subplots() ax1.pie(temp, labels=['Loan Repayed','Loan Not Repayed'], autopct='%1.1f%%',wedgeprops={'edgecolor':'black'}) ax1.axis('equal') plt.title('Loan Repayed or Not') plt.show()
_____no_output_____
MIT
notebooks/ExploratoryDataAnalysis.ipynb
geracharu/DataScienceProject
Data is higly imbalanced - This emphasises the importance of assessing the precision/recall to evaluate results. For example, predicting all rows as not defaulted would lead to an accuracy of 91.9%.- Consider rebalancing the training data 3.3 Number of each type of column
# Number of each type of column application_train.dtypes.value_counts()
_____no_output_____
MIT
notebooks/ExploratoryDataAnalysis.ipynb
geracharu/DataScienceProject
- There are 16 object columns.- These will need to be encoded when building the model (using label encoder or one hot encoder) 3.4 Number of unique classes in each object column
# Number of unique classes in each object column application_train.select_dtypes('object').apply(pd.Series.nunique, axis = 0)
_____no_output_____
MIT
notebooks/ExploratoryDataAnalysis.ipynb
geracharu/DataScienceProject
- Gender has 3 values. This needs investigation and correction. 4. SummaryBased on the analysis so far we have identified the need to handle: - skewed data - removing rows with large number of NULLS - remove rows with third gender This led to the development of 2 new datasets, as we can't be sure whic...
# Set the style of plots plt.style.use('fivethirtyeight') plt.figure(figsize = (10, 12)) plt.subplot(2, 1, 1) plt.title("Distribution of AMT_CREDIT") plt.hist(df1["AMT_CREDIT"], bins =20) plt.xlabel("AMT_CREDIT") plt.subplot(2, 1, 2) plt.title(" Log Distribution of AMT_CREDIT") plt.his...
_____no_output_____
MIT
notebooks/ExploratoryDataAnalysis.ipynb
geracharu/DataScienceProject
- It is not resonable to have such high years of employment (> 40-60 years).- As there are amny rows, I would try and repalce the values with average years of employment- I would plot the distribution of the reasonable values to get a clearer picture of the disrtibution.- Based on the ditribution, I would decide to tak...
less_years = df1[df1.YEARS_EMPLOYED <= 80] more_years = df1[df1.YEARS_EMPLOYED >80] plt.hist(less_years['YEARS_EMPLOYED']) plt.xlabel('Distribution of Lesser Years of Employment')
_____no_output_____
MIT
notebooks/ExploratoryDataAnalysis.ipynb
geracharu/DataScienceProject
log this data and change it in df1
less_years['YEARS_EMPLOYED'].mean() df1['YEARS_EMPLOYED'] = np.where(df1['YEARS_EMPLOYED'] > 80, 7, df1['YEARS_EMPLOYED']) plt.hist(df1['YEARS_EMPLOYED']) plt.xlabel('Years of Employment') plt.hist(df2['YEARS_EMPLOYED']) plt.xlabel('Years of Employment') ##Defaul = df1[df1['TARGET'] == 1] Not_defaul = df1[df1['TARGET']...
_____no_output_____
MIT
notebooks/ExploratoryDataAnalysis.ipynb
geracharu/DataScienceProject
DAYS_BIRTH is positively correlated with EXT_SOURCE_1 indicating that maybe one of the factors in this score is the client age.so try build model with EXT_SOURCE_1 and/or DAYS_BIRTH
plt.figure(figsize = (10, 12)) # iterate through the sources for i, source in enumerate(['EXT_SOURCE_1', 'EXT_SOURCE_2', 'EXT_SOURCE_3']): # create a new subplot for each source # plt.subplot(3, 1, i+1) # plot repaid loans sns.kdeplot(df1.loc[df1['TARGET'] == 0, source], label = 'target == 0')...
_____no_output_____
MIT
notebooks/ExploratoryDataAnalysis.ipynb
geracharu/DataScienceProject
import numpy as np A=([1,2,-1],[4,6,-2],[-1,3,3]) print(A) print(round(np.linalg.det(A)))
_____no_output_____
Apache-2.0
Determinant_of_Matrix.ipynb
jnrtnan/Linear-Algebra-58020
Copyright 2020 DeepMind Technologies Limited. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); Full license text
# 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under ...
_____no_output_____
Apache-2.0
examples/mnist_gan.ipynb
tirkarthi/dm-haiku
A (very) basic GAN for MNIST in JAX/HaikuBased on a TensorFlow tutorial written by Mihaela Rosca.Original GAN paper: https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf Imports
# Uncomment the line below if running on colab.research.google.com. # !pip install dm-haiku import functools from typing import Any, NamedTuple import haiku as hk import jax from jax.experimental import optix import jax.numpy as jnp import matplotlib.pyplot as plt import numpy as np import seaborn as sns import tenso...
_____no_output_____
Apache-2.0
examples/mnist_gan.ipynb
tirkarthi/dm-haiku
Define the dataset
# Download the data once. mnist = tfds.load("mnist") def make_dataset(batch_size, seed=1): def _preprocess(sample): # Convert to floats in [0, 1]. image = tf.image.convert_image_dtype(sample["image"], tf.float32) # Scale the data to [-1, 1] to stabilize training. return 2.0 * image - 1.0 ds = mni...
_____no_output_____
Apache-2.0
examples/mnist_gan.ipynb
tirkarthi/dm-haiku
Define the model
class Generator(hk.Module): """Generator network.""" def __init__(self, output_channels=(32, 1), name=None): super().__init__(name=name) self.output_channels = output_channels def __call__(self, x): """Maps noise latents to images.""" x = hk.Linear(7 * 7 * 64)(x) x = jnp.reshape(x, x.shape[:...
_____no_output_____
Apache-2.0
examples/mnist_gan.ipynb
tirkarthi/dm-haiku
Train the model
#@title {vertical-output: true} num_steps = 20001 log_every = num_steps // 100 # Let's see what hardware we're working with. The training takes a few # minutes on a GPU, a bit longer on CPU. print(f"Number of devices: {jax.device_count()}") print("Device:", jax.devices()[0].device_kind) print("") # Make the dataset....
_____no_output_____
Apache-2.0
examples/mnist_gan.ipynb
tirkarthi/dm-haiku
Visualize the lossesUnlike losses for classifiers or VAEs, GAN losses do not decrease steadily, instead going up and down depending on the training dynamics.
sns.set_style("whitegrid") fig, axes = plt.subplots(1, 2, figsize=(20, 6)) # Plot the discriminator loss. axes[0].plot(steps, disc_losses, "-") axes[0].plot(steps, np.log(2) * np.ones_like(steps), "r--", label="Discriminator is being fooled") axes[0].legend(fontsize=20) axes[0].set_title("Discriminator ...
_____no_output_____
Apache-2.0
examples/mnist_gan.ipynb
tirkarthi/dm-haiku
Visualize samples
#@title {vertical-output: true} def make_grid(samples, num_cols=8, rescale=True): batch_size, height, width = samples.shape assert batch_size % num_cols == 0 num_rows = batch_size // num_cols # We want samples.shape == (height * num_rows, width * num_cols). samples = samples.reshape(num_rows, num_cols, heig...
_____no_output_____
Apache-2.0
examples/mnist_gan.ipynb
tirkarthi/dm-haiku
¿Cómo podemos calcular con las funciones de Python los autovectores y los autovalores?
# Importamos las bibliotecas %matplotlib inline import numpy as np import matplotlib.pyplot as plt # Creamos una matriz X = np.array([[3, 2], [4, 1]]) print(X) # Vemos la biblioteca para calcular los autovectores y autovalores de Numpy print(np.linalg.eig(X)) # Pedimos que muestre los autovalores autovalores, autovec...
_____no_output_____
MIT
Code/4.-Cómo calcular los autovalores y autovectores.ipynb
DataEngel/Linear-algebra-applied-to-ML-with-Python
Alert Statistics
plt.figure(figsize=(base_width, base_height), dpi=dpi) ax1 = plt.subplot(111) reasons = [x if x != "Poor Signalness and Localisation" else "Poor Signalness \n and Localisation" for x in non["Rejection reason"]] reasons = [x if x != "Separation from Galactic Plane" else "Separation from \n Galactic Plane" for x in reas...
['Observed', 'Alert Retraction', 'Low Altitude', 'Poor Signalness \n and Localisation', 'Proximity to Sun', 'Separation from \n Galactic Plane', 'Southern Sky', 'Telescope Maintenance']
MIT
notebooks/stats_alerts.ipynb
robertdstein/nuztfpaper
Observed alerts (Table 1)
text = r""" \begin{table*} \centering \begin{tabular}{||c | c c c c c c ||} \hline \textbf{Event} & \textbf{R.A. (J2000)} & \textbf{Dec (J2000)} & \textbf{90\% area} & \textbf{ZTF obs} &~ \textbf{Signalness}& \textbf{Refs}\\ & \textbf{[deg]}&\textbf{[deg]}& \textbf{[sq. deg.]}& \textbf{[...
\begin{table*} \centering \begin{tabular}{||c | c c c c c c ||} \hline \textbf{Event} & \textbf{R.A. (J2000)} & \textbf{Dec (J2000)} & \textbf{90\% area} & \textbf{ZTF obs} &~ \textbf{Signalness}& \textbf{Refs}\\ & \textbf{[deg]}&\textbf{[deg]}& \textbf{[sq. deg.]}& \textbf{[sq. deg.]} ...
MIT
notebooks/stats_alerts.ipynb
robertdstein/nuztfpaper
Not observed
reasons = ["Alert Retraction", "Proximity to Sun", "Low Altitude", "Southern Sky", "Separation from Galactic Plane", "Poor Signalness and Localisation", "Telescope Maintenance"] seps = [1, 0, 0, 0, 1, 1, 1] full_mask = np.array([float(x[2:6]) > 1802 for x in non["Event"]]) text = r""" \begin{table*} \centering ...
\begin{table*} \centering \begin{tabular}{||c c ||} \hline \textbf{Cause} & \textbf{Events} \\ \hline Alert Retraction & IC180423A \citep{ic180423a}, IC181031A \citep{ic181031a} \\ & IC190205A \citep{ic190205a}, IC190529A \citep{ic190529a} \\ & IC200120A \citep{ic200120a}, IC...
MIT
notebooks/stats_alerts.ipynb
robertdstein/nuztfpaper
Full Neutrino List
text = fr""" \begin{{longtable}}[c]{{||c c c c c c ||}} \caption{{Summary of all {len(joint)} neutrino alerts issued since under the IceCube Realtime Program. Directions are not indicated for retracted events.}} \label{{tab:all_nu_alerts}} \\ \hline \textbf{{Event}} & \textbf{{R.A. (J2000)}} & \textbf{{Dec (J2000)}} ...
1 V1 alerts, 23 V2 alerts
MIT
notebooks/stats_alerts.ipynb
robertdstein/nuztfpaper
Exploratory Data Analysis of Stringer Dataset @authors: Simone Azeglio, Chetan Dhulipalla , Khalid Saifullah Part of the code here has been taken from [Neuromatch Academy's Computational Neuroscience Course](https://compneuro.neuromatch.io/projects/neurons/README.html), and specifically from [this notebook](https://co...
#@title Data retrieval import os, requests fname = "stringer_spontaneous.npy" url = "https://osf.io/dpqaj/download" if not os.path.isfile(fname): try: r = requests.get(url) except requests.ConnectionError: print("!!! Failed to download data !!!") else: if r.status_code != requests.codes.ok: pr...
_____no_output_____
MIT
src/NeuronBlock.ipynb
sazio/NMAs
Exploratory Data Analysis (EDA)
#@title Data loading import numpy as np dat = np.load('stringer_spontaneous.npy', allow_pickle=True).item() print(dat.keys()) # functions def moving_avg(array, factor = 5): """Reducing the number of compontents by averaging of N = factor subsequent elements of array""" zeros_ = np.zeros((array.shape[0], 2)) a...
_____no_output_____
MIT
src/NeuronBlock.ipynb
sazio/NMAs
Extracting Data for RNN (or LFADS)The first problem to address is that for each layer we don't have the exact same number of neurons. We'd like to have a single RNN encoding all the different layers activities, to make it easier we can take the number of neurons ($N_{neurons} = 1131$ of the least represented class (la...
# Extract labels from z - coordinate from sklearn import preprocessing x, y, z = dat['xyz'] le = preprocessing.LabelEncoder() labels = le.fit_transform(z) ### least represented class (layer with less neurons) n_samples = np.histogram(labels, bins=9)[0][-1] resp = np.array(dat['sresp']) xyz = np.array(dat['xyz']) prin...
_____no_output_____
MIT
src/NeuronBlock.ipynb
sazio/NMAs
issue: does the individual scaling by layer introduce bias that may artificially increase performance of the network? Data Loader
import torch import torch.nn as nn import torch.nn.functional as F device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # set the seed np.random.seed(42) # number of neurons NN = dataRNN.shape[0] # let's use 270 latent components ncomp = 10 # swapping the axes to maintain consistency with seq2seq no...
_____no_output_____
MIT
src/NeuronBlock.ipynb
sazio/NMAs
Training
from tqdm.notebook import tqdm # you can keep re-running this cell if you think the cost might decrease further cost = nn.MSELoss() niter = 100000 for k in tqdm(range(niter)): # the network outputs the single-neuron prediction and the latents z, y = net(x1) # our cost loss = cost(z, x2) # train the networ...
_____no_output_____
MIT
src/NeuronBlock.ipynb
sazio/NMAs
Import CSV log
data = readfile("ver3.txt") ## normal discogan dloss = [] gloss = [] time= [] epouch = [] for i in range(len(data)): try: t = data[i][data[i].find('time: ')+5: data[i].find(', [d_loss:') - len(data[i])].replace(" ","") if len(t)<3: continue time.append(t) glossA = (float(data[i][d...
_____no_output_____
MIT
MylogReader.ipynb
Telexine/colorizeSketch
L'objectif de ce notebook sera de réaliser une ébauche de solution ETL en python
#Import des packages necessaires à la réalisation du projet import pyodbc import pyspark import pandas as pd import pandasql as ps import sqlalchemy #creation des variables depuis le fichier de configuration qui doit être placé dans le même dossier que le notebook from configparser import ConfigParser #recuperation de...
_____no_output_____
CNRI-Python
Poc_ETL.ipynb
charlesLavignasse/POC-Python-ETL
Utilisation de pyodbc pour la connexion à la base de donnée SQL SERVER
#String de connexion procare connection_string_procare ='DRIVER={SQL Server Native Client 11.0};SERVER='+sqlsUrl+';DATABASE='+database_procare+';UID='+username+';PWD='+password+';Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;Authentication=ActiveDirectoryIntegrated' #String de connexion date connection_st...
_____no_output_____
CNRI-Python
Poc_ETL.ipynb
charlesLavignasse/POC-Python-ETL
Utilisation des packages pandas et pandasql pour respecter les règles de gestion * On cree la query qui sert à faire la jointure entre les deux dataframes precedemment crees* On fait une jointure glissante sur les dates de début et de fin de contrats* Le filtre nous permet de récupérer les données cohérentes (le premi...
psql_join_query =''' SELECT * FROM data_procare pro INNER JOIN data_date DAT ON DAT.DT_DATE BETWEEN PRO.StartAppliesTo AND PRO.EndAppliesTo WHERE (PRO.DayNumber = 1 AND DAT.LB_DAY_NAME ='LUNDI') OR (PRO.DayNumber = 2 AND DAT.LB_DAY_NAME ='MARDI') OR (PRO.DayNumber = 3 AND DAT.LB_DAY_NAME ='MERCREDI') OR (PRO.DayNumber ...
_____no_output_____
CNRI-Python
Poc_ETL.ipynb
charlesLavignasse/POC-Python-ETL
* Execution de la query via pandasql pui affichage des 5 premières lignes
df_psql = ps.sqldf(psql_join_query) df_psql.head(5)
_____no_output_____
CNRI-Python
Poc_ETL.ipynb
charlesLavignasse/POC-Python-ETL
On recupere les donnees etp dans un dataframe pour les rajouter dans le dataframe final
df_etp = pd.read_csv('etp.csv',sep=';')
_____no_output_____
CNRI-Python
Poc_ETL.ipynb
charlesLavignasse/POC-Python-ETL
* Conversion des donnees en decimal
df_etp_int = df_etp.astype('float64') sql_etp_query = ''' SELECT PRO.*, ETP.[Correspondance ETP] FROM df_psql PRO INNER JOIN df_etp ETP ON PRO.HoursWorked BETWEEN ETP.MinDailyHour AND ETP.MaxDailyHour ''' df_join_etp = ps.sqldf(sql_etp_query) df_join_etp.head(2)
_____no_output_____
CNRI-Python
Poc_ETL.ipynb
charlesLavignasse/POC-Python-ETL
Creation de la table dans SQL Server via Pyodbc
#on établit une nouvelle connexion avec la base DW_BABILOU connexion_dwh = pyodbc.connect(connection_string_date) dwh_crusor = connexion_dwh.cursor() #Table déjà installée # dwh_crusor.execute(''' # CREATE TABLE [dbo].PROCARE_ETP( # Jour DATE, # DayNumber INT, # [Database] VARCHAR(40), # PersonID INT, #...
_____no_output_____
CNRI-Python
Poc_ETL.ipynb
charlesLavignasse/POC-Python-ETL
on efface les données de la table dont l'extractdate est à la date du jour
dwh_crusor.execute('''DELETE FROM PROCARE_ETP WHERE ExtractDate = CONVERT (date, GETDATE())''') connexion_dwh.commit()
_____no_output_____
CNRI-Python
Poc_ETL.ipynb
charlesLavignasse/POC-Python-ETL
Insertion des donnees dans la table PROCATE_ETP nouvellement creee
# On créé un nouveau DataFrame à l'image de la table finale df_insert_procareETP = ps.sqldf('''SELECT date(DT_DATE) AS jour, DayNumber, [Database], PersonID, SchoolID, [Correspondance ETP] AS ETP, date(ExtractDate) as ExtractDate FROM df_join_etp''') df_insert_procareETP.head(2)
_____no_output_____
CNRI-Python
Poc_ETL.ipynb
charlesLavignasse/POC-Python-ETL
* quelques tests de connexion infructeux
for index,row in df_insert_procareETP.iterrows(): dwh_crusor.execute('''INSERT INTO PROCATE_ETP( [jour], [DayNumber], [Database], PersonID, SchoolID, ETP, ExtractDate) val...
_____no_output_____
CNRI-Python
Poc_ETL.ipynb
charlesLavignasse/POC-Python-ETL
Script d'insertion dans la table, pandas.to_sql et sqlachemy * On cree les informations de connexion à la table en utilisant le connexion string utilise precedemment dans pyodbc
from sqlalchemy.engine import URL,create_engine connection_url = URL.create("mssql+pyodbc", query={"odbc_connect": connection_string_date}) engine = create_engine(connection_url,fast_executemany=True) #https://docs.sqlalchemy.org/en/14/dialects/mssql.html#module-sqlalchemy.dialects.mssql.pyodbc #https://pandas.pydata...
_____no_output_____
CNRI-Python
Poc_ETL.ipynb
charlesLavignasse/POC-Python-ETL
Classfication report* A Classification report is used to measure the quality of predictions from a classification algorithm. ... The report shows the main classification metrics precision, recall and f1-score on a per-class basis. The metrics are calculated by using true and false positives, true and false negatives.`...
import numpy as np from sklearn.metrics import classification_report from matplotlib import pyplot as plt y_true = np.array([1., 0., 1, 1, 0, 0, 1]) y_pred = np.array([1., 1., 1., 0., 0. ,1, 0])
_____no_output_____
MIT
04_Evaluation_Methods/06_Classification_Report/.ipynb_checkpoints/Classification_Report-checkpoint.ipynb
CrispenGari/keras-api
Using `scikit-learn` to generate the classification report for our predictions
labels = np.array([0., 1]) report = classification_report(y_true, y_pred, labels=labels) print(report)
precision recall f1-score support 0.0 0.33 0.33 0.33 3 1.0 0.50 0.50 0.50 4 accuracy 0.43 7 macro avg 0.42 0.42 0.42 7 weighted avg 0.43 0.43 0.43 ...
MIT
04_Evaluation_Methods/06_Classification_Report/.ipynb_checkpoints/Classification_Report-checkpoint.ipynb
CrispenGari/keras-api
Ploting the ``classification_report``
import numpy as np import seaborn as sns from sklearn.metrics import classification_report import pandas as pd report = classification_report(y_true, y_pred, labels=labels, output_dict=True) sns.heatmap(pd.DataFrame(report).iloc[:-1, :].T, annot=True) plt.title("Classification Report") plt.show()
_____no_output_____
MIT
04_Evaluation_Methods/06_Classification_Report/.ipynb_checkpoints/Classification_Report-checkpoint.ipynb
CrispenGari/keras-api
Синхронизация потоков Спасибо Сове Глебу, Голяр Димитрису и Николаю Васильеву за участие в написании текста Сегодня в программе:* Мьютексы MUTEX ~ MUTual EXclusion* Spinlock'и и атомики [Атомики в С на cppreference](https://ru.cppreference.com/w/c/atomic) Atomic в C и как с этим жить (раздел от Николая Васильев...
%%cpp mutex.c %# Санитайзер отслеживает небезопасный доступ %# к одному и тому же участку в памяти из разных потоков %# (а так же другие небезопасные вещи). %# В таких задачах советую всегда использовать %run gcc -fsanitize=thread mutex.c -lpthread -o mutex.exe # вспоминаем про санитайзеры %run ./mutex.exe #define _...
_____no_output_____
MIT
sem20-synchronizing/synchronizing.ipynb
Disadvantaged/caos_2019-2020
Spinlock[spinlock в стандартной библиотеке](https://linux.die.net/man/3/pthread_spin_init)
%%cpp spinlock.c %run gcc -fsanitize=thread -std=c11 spinlock.c -lpthread -o spinlock.exe %run ./spinlock.exe #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/syscall.h> #include <sys/types.h> #include <sys/time.h> #include <pthread.h> #include <stdatomic.h> //! Этот заголов...
_____no_output_____
MIT
sem20-synchronizing/synchronizing.ipynb
Disadvantaged/caos_2019-2020
Condition variable
%%cpp condvar.c %run gcc -fsanitize=thread condvar.c -lpthread -o condvar.exe %run ./condvar.exe > out.txt //%run cat out.txt #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/syscall.h> #include <sys/time.h> #include <pthread.h> #include <stdatomic.h> const char* log_pre...
_____no_output_____
MIT
sem20-synchronizing/synchronizing.ipynb
Disadvantaged/caos_2019-2020
Способ достичь успеха без боли: все изменения данных делаем под mutex. Операции с condvar тоже делаем только под заблокированным mutex. Пример thread-safe очереди
%%cpp condvar_queue.c %run gcc -fsanitize=thread condvar_queue.c -lpthread -o condvar_queue.exe %run (for i in $(seq 0 100000); do echo -n "$i " ; done) | ./condvar_queue.exe > out.txt //%run cat out.txt #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/syscall.h> #include...
_____no_output_____
MIT
sem20-synchronizing/synchronizing.ipynb
Disadvantaged/caos_2019-2020
Atomic в C и как с этим житьВ C++ атомарные переменные реализованы через `std::atomic` в силу объектной ориентированности языка. В C же к объявлению переменной приписывается _Atomic или _Atomic(). Лучше использовать второй вариант (почему, будет ниже). Ситуация усложняется отсуствием документации. Про атомарные функц...
%%cpp atomic_example1.c %run gcc -fsanitize=thread atomic_example1.c -lpthread -o atomic_example1.exe %run ./atomic_example1.exe > out.txt %run cat out.txt #include <stdatomic.h> #include <stdint.h> #include <stdio.h> // _Atomic навешивается на `int` _Atomic int x; int main(int argc, char* argv[]) { atomic_store...
_____no_output_____
MIT
sem20-synchronizing/synchronizing.ipynb
Disadvantaged/caos_2019-2020
Казалось бы все хорошо, но давайте попробуем с указателями
%%cpp atomic_example2.c %run gcc -fsanitize=thread atomic_example2.c -lpthread -o atomic_example2.exe %run ./atomic_example2.exe > out.txt %run cat out.txt #include <stdatomic.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> // ПЛОХОЙ КОД!!! _Atomic int* x; int main(int argc, char* argv[]) { int dat...
_____no_output_____
MIT
sem20-synchronizing/synchronizing.ipynb
Disadvantaged/caos_2019-2020
Получаем ад из warning/error от компилятора(все в зависимости от компилятора и платформы: `gcc 7.4.0 Ubuntu 18.04.1` - warning, `clang 11.0.0 macOS` - error).Может появиться желание написать костыль, явно прикастовав типы:
%%cpp atomic_example3.c %run gcc -fsanitize=thread atomic_example3.c -lpthread -o atomic_example3.exe %run ./atomic_example3.exe > out.txt %run cat out.txt #include <stdatomic.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> // ПЛОХОЙ КОД!!! _Atomic int* x; int main(int argc, char* argv[]) { int dat...
_____no_output_____
MIT
sem20-synchronizing/synchronizing.ipynb
Disadvantaged/caos_2019-2020
Теперь gcc перестает кидать warnings (в clang до сих пор error). Но код может превратиться в ад из кастов. Но! Этот код идейно полностью некорректен.Посмотрим на `_Atomic int* x;`В данном случае это работает как `(_Atomic int)* x`, а не как `_Atomic (int*) x` что легко подумать!То есть получается неатомарный указатель ...
%%cpp atomic_example4.c %run gcc -fsanitize=thread atomic_example4.c -lpthread -o atomic_example4.exe %run ./atomic_example4.exe > out.txt %run cat out.txt #include <stdatomic.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> // Теперь именно атомарный указатель. Как и должно было быть. _Atomic (int*) x; ...
_____no_output_____
MIT
sem20-synchronizing/synchronizing.ipynb
Disadvantaged/caos_2019-2020
reference for calulating quartile [here](http://web.mnstate.edu/peil/MDEV102/U4/S36/S363.html:~:text=The%20third%20quartile%2C%20denoted%20by,25%25%20lie%20above%20Q3%20)
mean(case_duration_dic.values()) # quartile calculation import statistics def calc_third_quartile(lis): lis.sort() size = len(lis) lis_upper_half = lis[size//2:-1] third_quartile = statistics.median(lis_upper_half) return third_quartile case_durations = list(case_duration_dic.values()) third_qu...
_____no_output_____
MIT
src/dataset_div/dataset_div_bpi_12_w.ipynb
avani17101/goal-oriented-next-best-activity-recomendation
Filter dataset for RL model
cases_gs = [] cases_gv = [] for k,v in case_duration_dic.items(): if v <= third_quartile: cases_gs.append(k) else: cases_gv.append(k) len(cases_gs), len(cases_gv) tot = len(cases_gs)+ len(cases_gv) percent_gs_cases = len(cases_gs) / tot print(percent_gs_cases) cases_train = cases_gs cases_test =...
_____no_output_____
MIT
src/dataset_div/dataset_div_bpi_12_w.ipynb
avani17101/goal-oriented-next-best-activity-recomendation
Analysing unique events
a = get_unique_act(data_train) len(a) tot = get_unique_act(df) len(tot) lis = [] for act in tot: if act not in a: lis.append(act) lis for act in lis: df_sub = df[df["class"] == act] caseid_lis = list(df_sub["CaseID"]) l = len(caseid_lis) caseid_sel = caseid_lis[:l//2] if len(case...
_____no_output_____
MIT
src/dataset_div/dataset_div_bpi_12_w.ipynb
avani17101/goal-oriented-next-best-activity-recomendation
Implementing the Gradient Descent AlgorithmIn this lab, we'll implement the basic functions of the Gradient Descent algorithm to find the boundary in a small dataset. First, we'll start with some functions that will help us plot and visualize the data.
import matplotlib.pyplot as plt import numpy as np import pandas as pd #Some helper functions for plotting and drawing lines def plot_points(X, y): admitted = X[np.argwhere(y==1)] rejected = X[np.argwhere(y==0)] plt.scatter([s[0][0] for s in rejected], [s[0][1] for s in rejected], s = 25, color = 'blue', ...
_____no_output_____
MIT
intro-neural-networks/gradient-descent/GradientDescent.ipynb
Abhinav2604/deep-learning-v2-pytorch
Reading and plotting the data
data = pd.read_csv('data.csv', header=None) X = np.array(data[[0,1]]) y = np.array(data[2]) plot_points(X,y) plt.show()
_____no_output_____
MIT
intro-neural-networks/gradient-descent/GradientDescent.ipynb
Abhinav2604/deep-learning-v2-pytorch
TODO: Implementing the basic functionsHere is your turn to shine. Implement the following formulas, as explained in the text.- Sigmoid activation function$$\sigma(x) = \frac{1}{1+e^{-x}}$$- Output (prediction) formula$$\hat{y} = \sigma(w_1 x_1 + w_2 x_2 + b)$$- Error function$$Error(y, \hat{y}) = - y \log(\hat{y}) - (...
# Implement the following functions # Activation (sigmoid) function def sigmoid(x): y=1/(1+np.exp(-x)) return y # Output (prediction) formula def output_formula(features, weights, bias): y_hat=sigmoid(np.dot(features,weights)+bias) return y_hat # Error (log-loss) formula def error_formula(y,...
_____no_output_____
MIT
intro-neural-networks/gradient-descent/GradientDescent.ipynb
Abhinav2604/deep-learning-v2-pytorch
Training functionThis function will help us iterate the gradient descent algorithm through all the data, for a number of epochs. It will also plot the data, and some of the boundary lines obtained as we run the algorithm.
np.random.seed(44) epochs = 100 learnrate = 0.01 def train(features, targets, epochs, learnrate, graph_lines=False): errors = [] n_records, n_features = features.shape last_loss = None weights = np.random.normal(scale=1 / n_features**.5, size=n_features) bias = 0 for e in range(epochs): ...
_____no_output_____
MIT
intro-neural-networks/gradient-descent/GradientDescent.ipynb
Abhinav2604/deep-learning-v2-pytorch
Time to train the algorithm!When we run the function, we'll obtain the following:- 10 updates with the current training loss and accuracy- A plot of the data and some of the boundary lines obtained. The final one is in black. Notice how the lines get closer and closer to the best fit, as we go through more epochs.- A ...
train(X, y, epochs, learnrate, True)
========== Epoch 0 ========== Train loss: 0.7135845195381634 Accuracy: 0.4 ========== Epoch 10 ========== Train loss: 0.6225835210454962 Accuracy: 0.59 ========== Epoch 20 ========== Train loss: 0.5548744083669508 Accuracy: 0.74 ========== Epoch 30 ========== Train loss: 0.501606141872473 Accuracy: 0.84 ==...
MIT
intro-neural-networks/gradient-descent/GradientDescent.ipynb
Abhinav2604/deep-learning-v2-pytorch
ElasticNet with RobustScaler & Power Transformer This Code template is for regression analysis using the ElasticNet regressor where rescaling method used is RobustScaler and feature transformation is done via Power Transformer. Required Packages
import numpy as np import pandas as pd import seaborn as se import warnings import matplotlib.pyplot as plt from sklearn.pipeline import make_pipeline from sklearn.model_selection import train_test_split from sklearn.linear_model import ElasticNet from imblearn.over_sampling import RandomOverSampler from sklearn.prepro...
_____no_output_____
Apache-2.0
Regression/Linear Models/ElasticNet_RobustScaler_PowerTransformer.ipynb
shreepad-nade/ds-seed
InitializationFilepath of CSV file
#filepath file_path= ""
_____no_output_____
Apache-2.0
Regression/Linear Models/ElasticNet_RobustScaler_PowerTransformer.ipynb
shreepad-nade/ds-seed
List of features which are required for model training.
#x_values features=[]
_____no_output_____
Apache-2.0
Regression/Linear Models/ElasticNet_RobustScaler_PowerTransformer.ipynb
shreepad-nade/ds-seed
Target feature for prediction.
#y_value target=''
_____no_output_____
Apache-2.0
Regression/Linear Models/ElasticNet_RobustScaler_PowerTransformer.ipynb
shreepad-nade/ds-seed
Data FetchingPandas is an open-source, BSD-licensed library providing high-performance, easy-to-use data manipulation and data analysis tools.We will use panda's library to read the CSV file using its storage path.And we use the head function to display the initial row or entry.
df=pd.read_csv(file_path) #reading file df.head()
_____no_output_____
Apache-2.0
Regression/Linear Models/ElasticNet_RobustScaler_PowerTransformer.ipynb
shreepad-nade/ds-seed
Feature SelectionsIt is the process of reducing the number of input variables when developing a predictive model. Used to reduce the number of input variables to both reduce the computational cost of modelling and, in some cases, to improve the performance of the model.We will assign all the required input features to...
X=df[features] Y=df[target]
_____no_output_____
Apache-2.0
Regression/Linear Models/ElasticNet_RobustScaler_PowerTransformer.ipynb
shreepad-nade/ds-seed