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 |
|---|---|---|---|---|---|
Next, we need to preprocess our data so that it matches the data BERT was trained on. For this, we'll need to do a couple of things (but don't worry--this is also included in the Python library):1. Lowercase our text (if we're using a BERT lowercase model)2. Tokenize it (i.e. "sally says hi" -> ["sally", "says", "hi"])... | # This is a path to an uncased (all lowercase) version of BERT
BERT_MODEL_HUB = "https://tfhub.dev/google/bert_uncased_L-12_H-768_A-12/1"
def create_tokenizer_from_hub_module():
"""Get the vocab file and casing info from the Hub module."""
with tf.Graph().as_default():
bert_module = hub.Module(BERT_MODEL_HUB)
... | I0414 10:19:59.282109 140105573619520 saver.py:1499] Saver not created because there are no variables in the graph to restore
W0414 10:20:00.810749 140105573619520 deprecation_wrapper.py:119] From /usr/local/lib/python3.6/dist-packages/bert/tokenization.py:125: The name tf.gfile.GFile is deprecated. Please use tf.io.gf... | Apache-2.0 | predicting_movie_reviews_with_bert_on_tf_hub.ipynb | bedman3/bert |
Great--we just learned that the BERT model we're using expects lowercase data (that's what stored in tokenization_info["do_lower_case"]) and we also loaded BERT's vocab file. We also created a tokenizer, which breaks words into word pieces: | tokenizer.tokenize("This here's an example of using the BERT tokenizer") | _____no_output_____ | Apache-2.0 | predicting_movie_reviews_with_bert_on_tf_hub.ipynb | bedman3/bert |
Using our tokenizer, we'll call `run_classifier.convert_examples_to_features` on our InputExamples to convert them into features BERT understands. | # We'll set sequences to be at most 128 tokens long.
MAX_SEQ_LENGTH = 128
# Convert our train and test features to InputFeatures that BERT understands.
train_features = bert.run_classifier.convert_examples_to_features(train_InputExamples, label_list, MAX_SEQ_LENGTH, tokenizer)
test_features = bert.run_classifier.conver... | W0414 10:20:00.919758 140105573619520 deprecation_wrapper.py:119] From /usr/local/lib/python3.6/dist-packages/bert/run_classifier.py:774: The name tf.logging.info is deprecated. Please use tf.compat.v1.logging.info instead.
I0414 10:20:00.921136 140105573619520 run_classifier.py:774] Writing example 0 of 20000
I0414 1... | Apache-2.0 | predicting_movie_reviews_with_bert_on_tf_hub.ipynb | bedman3/bert |
Creating a modelNow that we've prepared our data, let's focus on building a model. `create_model` does just this below. First, it loads the BERT tf hub module again (this time to extract the computation graph). Next, it creates a single new layer that will be trained to adapt BERT to our sentiment task (i.e. classifyin... | def create_model(is_predicting, input_ids, input_mask, segment_ids, labels,
num_labels):
"""Creates a classification model."""
bert_module = hub.Module(
BERT_MODEL_HUB,
trainable=True)
bert_inputs = dict(
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segme... | _____no_output_____ | Apache-2.0 | predicting_movie_reviews_with_bert_on_tf_hub.ipynb | bedman3/bert |
Next we'll wrap our model function in a `model_fn_builder` function that adapts our model to work for training, evaluation, and prediction. | # model_fn_builder actually creates our model function
# using the passed parameters for num_labels, learning_rate, etc.
def model_fn_builder(num_labels, learning_rate, num_train_steps,
num_warmup_steps):
"""Returns `model_fn` closure for TPUEstimator."""
def model_fn(features, labels, mode, pa... | I0414 10:20:36.028532 140105573619520 estimator.py:209] Using config: {'_model_dir': 'output_files', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': 500, '_save_checkpoints_secs': None, '_session_config': allow_soft_placement: true
graph_options {
rewrite_options {
meta_optimizer_i... | Apache-2.0 | predicting_movie_reviews_with_bert_on_tf_hub.ipynb | bedman3/bert |
Next we create an input builder function that takes our training feature set (`train_features`) and produces a generator. This is a pretty standard design pattern for working with Tensorflow [Estimators](https://www.tensorflow.org/guide/estimators). | # Create an input function for training. drop_remainder = True for using TPUs.
train_input_fn = bert.run_classifier.input_fn_builder(
features=train_features,
seq_length=MAX_SEQ_LENGTH,
is_training=True,
drop_remainder=False) | _____no_output_____ | Apache-2.0 | predicting_movie_reviews_with_bert_on_tf_hub.ipynb | bedman3/bert |
Now we train our model! For me, using a Colab notebook running on Google's GPUs, my training time was about 14 minutes. | print(f'Beginning Training!')
current_time = datetime.now()
estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)
print("Training took time ", datetime.now() - current_time) | W0414 10:20:36.153037 140105573619520 deprecation.py:323] From /usr/local/lib/python3.6/dist-packages/tensorflow/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.
Instructions for updating:
Use Variable.read_val... | Apache-2.0 | predicting_movie_reviews_with_bert_on_tf_hub.ipynb | bedman3/bert |
Now let's use our test data to see how well our model did: | test_input_fn = run_classifier.input_fn_builder(
features=test_features,
seq_length=MAX_SEQ_LENGTH,
is_training=False,
drop_remainder=False)
estimator.evaluate(input_fn=test_input_fn, steps=None) | _____no_output_____ | Apache-2.0 | predicting_movie_reviews_with_bert_on_tf_hub.ipynb | bedman3/bert |
Now let's write code to make predictions on new sentences: | def getPrediction(in_sentences):
labels = ["Negative", "Positive"]
input_examples = [run_classifier.InputExample(guid="", text_a = x, text_b = None, label = 0) for x in in_sentences] # here, "" is just a dummy label
input_features = run_classifier.convert_examples_to_features(input_examples, label_list, MAX_SEQ_L... | _____no_output_____ | Apache-2.0 | predicting_movie_reviews_with_bert_on_tf_hub.ipynb | bedman3/bert |
Voila! We have a sentiment classifier! | predictions | _____no_output_____ | Apache-2.0 | predicting_movie_reviews_with_bert_on_tf_hub.ipynb | bedman3/bert |
UCI Daphnet dataset (Freezing of gait for Parkinson's disease patients) | import numpy as np
import pandas as pd
import os
from typing import List
from pathlib import Path
from config import data_raw_folder, data_processed_folder
from timeeval import Datasets
import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (20, 10)
dataset_collection_name... | _____no_output_____ | MIT | notebooks/data-prep/UCI-Daphnet.ipynb | HPI-Information-Systems/TimeEval |
ExperimentationAnnotations- `0`: not part of the experiment. For instance the sensors are installed on the user or the user is performing activities unrelated to the experimental protocol, such as debriefing- `1`: experiment, no freeze (can be any of stand, walk, turn)- `2`: freeze | columns = ["timestamp", "ankle_horiz_fwd", "ankle_vert", "ankle_horiz_lateral", "leg_horiz_fwd", "leg_vert", "leg_horiz_lateral",
"trunk_horiz_fwd", "trunk_vert", "trunk_horiz_lateral", "annotation"]
df1 = pd.read_csv(source_folder / "S01R01.txt", sep=' ', header=None)
df1.columns = columns
df1["timestamp"] =... | _____no_output_____ | MIT | notebooks/data-prep/UCI-Daphnet.ipynb | HPI-Information-Systems/TimeEval |
Amy Green - 200930437 5990M: Introduction to Programming for Geographical Information Analysis - Core Skills __**Assignment 2: Investigating the Black Death**__ ------------------------------------------------------------- Project AimThe aim of the project hopes to build a model, based upon initial agent-based ... | '''Step 1 - Set up initial imports for programme'''
import random
%matplotlib inline
import matplotlib.pyplot
import matplotlib
import matplotlib.animation
import os
import requests
import tkinter
import pandas as pd #Shortened in standard python documentation format
import numpy as np #Shortened in standard python d... | _____no_output_____ | BSL-1.0 | .ipynb | AGreen0/BlackDeathProject |
Map 1 - Rat Populations (Average Rats caught per week) | '''Step 2 - Import data for the rat populations and generate environment from the 2D array'''
#Set up a base path for the import of the rats txt file
base_path = "C:\\Users\\Home\\Documents\\MSc GIS\\Programming\\Black_Death\\BlackDeathProject" #Basepath
deathrats = "deathrats.txt" #Saved filename
path_to_file = os.pa... | _____no_output_____ | BSL-1.0 | .ipynb | AGreen0/BlackDeathProject |
This map contains the data for the average rat populations denoted from the amount of rats caught per week. The data is initially placed into a text file which can be seen through print(mapA), but then has been put into an environment which is shown. The different colours show the different amounts of rats, however, t... | '''Step 3 - Import data for the parish population densities and generate environment from the 2D array'''
#Set up a base path for the import of the parish txt file
#base_path = "C:\\Users\\Home\\Documents\\MSc GIS\\Programming\\Black_Death\\BlackDeathProject" #Basepath
deathparishes = "deathparishes.txt" #Saved filena... | _____no_output_____ | BSL-1.0 | .ipynb | AGreen0/BlackDeathProject |
This map contains the data for the average population densities per the 16 parishes investigated. The data is initially placed into a text file which can be seen through print(mapB), but then has been put into an environment which is shown. The different colours show the different populations per parish. ------------... | '''Step 4 - Calculate Map of Average death rates '''
#Sets up a list named results to append all calculated values to
result = []
for r in range(len(environmentA)):#Goes through both environments' (A and B) rows
row_a = environmentA[r]
row_b = environmentB[r]
rowlist = []
result.append(rowlist) #Appe... | _____no_output_____ | BSL-1.0 | .ipynb | AGreen0/BlackDeathProject |
The output map within Part 2 displays the average death rate calculations within the 400x400 environment of the parishes investigated. The results array has been saved as a result.txt file (rounded to two decimal points) that can be manipulated and utilised for further investigation. ------------------------------... | '''Step 7 - Set up Rat Population Parameter Slider'''
#Generate a slider for the rats parameter
sR = widgets.FloatSlider(
value=0.8, #Initial parameter value set by the equation
min=0, #Minimum of range is 0
max=5.0, #Maximum of range is 5
step=0.1, #Values get to 1 decimal place increments
descrip... | _____no_output_____ | BSL-1.0 | .ipynb | AGreen0/BlackDeathProject |
The sliders above are available to alter to investigate the relationship between the rat population values and the average population density amounts. These will then be the next set parameters when the proceeding cell is run. | '''Step 9 - Display the Changed Parameters '''
#Formatting to display parameter amounts to correlate to the underlying map
print('Changed Parameter Values')
print('Rats:', sR.value)
print('Parishes:', sP.value)
'''Step 10 - Create a map of the death rate average with new changed parameters'''
#Alter the results li... | Changed Parameter Values
Rats: 2.9
Parishes: 1.0
Average weekly death rate at these parameters = 29754.0
| BSL-1.0 | .ipynb | AGreen0/BlackDeathProject |
SDLib> Shilling simulated attacks and detection methods Setup | !mkdir -p results | _____no_output_____ | Apache-2.0 | docs/T006054_SDLib.ipynb | sparsh-ai/recsys-attacks |
Imports | from collections import defaultdict
import numpy as np
import random
import os
import os.path
from os.path import abspath
from os import makedirs,remove
from re import compile,findall,split
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics.pairwise import pairwise_distances,cosine_similarity
fr... | _____no_output_____ | Apache-2.0 | docs/T006054_SDLib.ipynb | sparsh-ai/recsys-attacks |
Data | !mkdir -p dataset/amazon
!cd dataset/amazon && wget -q --show-progress https://github.com/Coder-Yu/SDLib/raw/master/dataset/amazon/profiles.txt
!cd dataset/amazon && wget -q --show-progress https://github.com/Coder-Yu/SDLib/raw/master/dataset/amazon/labels.txt
!mkdir -p dataset/averageattack
!cd dataset/averageattack &... | ratings.txt 100%[===================>] 367.62K --.-KB/s in 0.006s
trust.txt 100%[===================>] 19.15K --.-KB/s in 0s
| Apache-2.0 | docs/T006054_SDLib.ipynb | sparsh-ai/recsys-attacks |
Config Configure the Detection Method Entry Example Description ratings dataset/averageattack/ratings.txt Set the path to the dirty recommendation dataset. Format: each row separated by empty, tab or comma symbol. label dataset/averageattack/labels.txt Set the path to labels (fo... | %%writefile BayesDetector.conf
ratings=dataset/amazon/profiles.txt
ratings.setup=-columns 0 1 2
label=dataset/amazon/labels.txt
methodName=BayesDetector
evaluation.setup=-cv 5
item.ranking=off -topN 50
num.max.iter=100
learnRate=-init 0.03 -max 0.1
reg.lambda=-u 0.3 -i 0.3
BayesDetector=-k 10 -negCount 256 -gamma 1 -fi... | Writing SemiSAD.conf
| Apache-2.0 | docs/T006054_SDLib.ipynb | sparsh-ai/recsys-attacks |
Baseclass | class SDetection(object):
def __init__(self,conf,trainingSet=None,testSet=None,labels=None,fold='[1]'):
self.config = conf
self.isSave = False
self.isLoad = False
self.foldInfo = fold
self.labels = labels
self.dao = RatingDAO(self.config, trainingSet, testSet)
... | _____no_output_____ | Apache-2.0 | docs/T006054_SDLib.ipynb | sparsh-ai/recsys-attacks |
Utils | class Config(object):
def __init__(self,fileName):
self.config = {}
self.readConfiguration(fileName)
def __getitem__(self, item):
if not self.contains(item):
print('parameter '+item+' is invalid!')
exit(-1)
return self.config[item]
def getOptions(sel... | _____no_output_____ | Apache-2.0 | docs/T006054_SDLib.ipynb | sparsh-ai/recsys-attacks |
Shilling models Attack base class | class Attack(object):
def __init__(self,conf):
self.config = Config(conf)
self.userProfile = FileIO.loadDataSet(self.config,self.config['ratings'])
self.itemProfile = defaultdict(dict)
self.attackSize = float(self.config['attackSize'])
self.fillerSize = float(self.config['fil... | _____no_output_____ | Apache-2.0 | docs/T006054_SDLib.ipynb | sparsh-ai/recsys-attacks |
Relation attack | class RelationAttack(Attack):
def __init__(self,conf):
super(RelationAttack, self).__init__(conf)
self.spamLink = defaultdict(list)
self.relation = FileIO.loadRelationship(self.config,self.config['social'])
self.trustLink = defaultdict(list)
self.trusteeLink = defaultdict(lis... | _____no_output_____ | Apache-2.0 | docs/T006054_SDLib.ipynb | sparsh-ai/recsys-attacks |
Random relation attack | class RandomRelationAttack(RelationAttack):
def __init__(self,conf):
super(RandomRelationAttack, self).__init__(conf)
self.scale = float(self.config['linkSize'])
def farmLink(self): # 随机注入虚假关系
for spam in self.spamProfile:
#对购买了目标项目的用户种植链接
for item in self.spa... | _____no_output_____ | Apache-2.0 | docs/T006054_SDLib.ipynb | sparsh-ai/recsys-attacks |
Random attack | class RandomAttack(Attack):
def __init__(self,conf):
super(RandomAttack, self).__init__(conf)
def insertSpam(self,startID=0):
print('Modeling random attack...')
itemList = list(self.itemProfile.keys())
if startID == 0:
self.startUserID = len(self.userProfile)
... | _____no_output_____ | Apache-2.0 | docs/T006054_SDLib.ipynb | sparsh-ai/recsys-attacks |
Average attack | class AverageAttack(Attack):
def __init__(self,conf):
super(AverageAttack, self).__init__(conf)
def insertSpam(self,startID=0):
print('Modeling average attack...')
itemList = list(self.itemProfile.keys())
if startID == 0:
self.startUserID = len(self.userProfile)
... | _____no_output_____ | Apache-2.0 | docs/T006054_SDLib.ipynb | sparsh-ai/recsys-attacks |
Random average relation | class RA_Attack(RandomRelationAttack,AverageAttack):
def __init__(self,conf):
super(RA_Attack, self).__init__(conf) | _____no_output_____ | Apache-2.0 | docs/T006054_SDLib.ipynb | sparsh-ai/recsys-attacks |
Bandwagon attack | class BandWagonAttack(Attack):
def __init__(self,conf):
super(BandWagonAttack, self).__init__(conf)
self.hotItems = sorted(iter(self.itemProfile.items()), key=lambda d: len(d[1]), reverse=True)[
:int(self.selectedSize * len(self.itemProfile))]
def insertSpam(self,startID=0):... | _____no_output_____ | Apache-2.0 | docs/T006054_SDLib.ipynb | sparsh-ai/recsys-attacks |
Random bandwagon relation | class RB_Attack(RandomRelationAttack,BandWagonAttack):
def __init__(self,conf):
super(RB_Attack, self).__init__(conf) | _____no_output_____ | Apache-2.0 | docs/T006054_SDLib.ipynb | sparsh-ai/recsys-attacks |
Hybrid attack | class HybridAttack(Attack):
def __init__(self,conf):
super(HybridAttack, self).__init__(conf)
self.aveAttack = AverageAttack(conf)
self.bandAttack = BandWagonAttack(conf)
self.randAttack = RandomAttack(conf)
def insertSpam(self,startID=0):
self.aveAttack.insertSpam()
... | _____no_output_____ | Apache-2.0 | docs/T006054_SDLib.ipynb | sparsh-ai/recsys-attacks |
Generate data | %%writefile config.conf
ratings=dataset/filmtrust/ratings.txt
ratings.setup=-columns 0 1 2
social=dataset/filmtrust/trust.txt
social.setup=-columns 0 1 2
attackSize=0.1
fillerSize=0.05
selectedSize=0.005
targetCount=20
targetScore=4.0
threshold=3.0
maxScore=4.0
minScore=1.0
minCount=5
maxCount=50
linkSize=0.001
outputD... | loading training data...
Selecting target items...
--------------------------------------------------------------------------------
Target item Average rating of the item
877 2.875
472 2.5833333333333335
715 2.8
528 2.7142857142857144
169... | Apache-2.0 | docs/T006054_SDLib.ipynb | sparsh-ai/recsys-attacks |
Data access objects | class RatingDAO(object):
'data access control'
def __init__(self,config, trainingData, testData):
self.config = config
self.ratingConfig = LineConfig(config['ratings.setup'])
self.user = {} #used to store the order of users in the training set
self.item = {} #used to store the or... | _____no_output_____ | Apache-2.0 | docs/T006054_SDLib.ipynb | sparsh-ai/recsys-attacks |
Methods BayesDetector | #BayesDetector: Collaborative Shilling Detection Bridging Factorization and User Embedding
class BayesDetector(SDetection):
def __init__(self, conf, trainingSet=None, testSet=None, labels=None, fold='[1]'):
super(BayesDetector, self).__init__(conf, trainingSet, testSet, labels, fold)
def readConfigurat... | _____no_output_____ | Apache-2.0 | docs/T006054_SDLib.ipynb | sparsh-ai/recsys-attacks |
CoDetector | #CoDetector: Collaborative Shilling Detection Bridging Factorization and User Embedding
class CoDetector(SDetection):
def __init__(self, conf, trainingSet=None, testSet=None, labels=None, fold='[1]'):
super(CoDetector, self).__init__(conf, trainingSet, testSet, labels, fold)
def readConfiguration(self)... | _____no_output_____ | Apache-2.0 | docs/T006054_SDLib.ipynb | sparsh-ai/recsys-attacks |
DegreeSAD | class DegreeSAD(SDetection):
def __init__(self, conf, trainingSet=None, testSet=None, labels=None, fold='[1]'):
super(DegreeSAD, self).__init__(conf, trainingSet, testSet, labels, fold)
def buildModel(self):
self.MUD = {}
self.RUD = {}
self.QUD = {}
# computing MUD,RUD,Q... | _____no_output_____ | Apache-2.0 | docs/T006054_SDLib.ipynb | sparsh-ai/recsys-attacks |
FAP | class FAP(SDetection):
def __init__(self, conf, trainingSet=None, testSet=None, labels=None, fold='[1]'):
super(FAP, self).__init__(conf, trainingSet, testSet, labels, fold)
def readConfiguration(self):
super(FAP, self).readConfiguration()
# # s means the number of seedUser who be rega... | _____no_output_____ | Apache-2.0 | docs/T006054_SDLib.ipynb | sparsh-ai/recsys-attacks |
PCASelectUsers | class PCASelectUsers(SDetection):
def __init__(self, conf, trainingSet=None, testSet=None, labels=None, fold='[1]', k=None, n=None ):
super(PCASelectUsers, self).__init__(conf, trainingSet, testSet, labels, fold)
def readConfiguration(self):
super(PCASelectUsers, self).readConfiguration()
... | _____no_output_____ | Apache-2.0 | docs/T006054_SDLib.ipynb | sparsh-ai/recsys-attacks |
SemiSAD | class SemiSAD(SDetection):
def __init__(self, conf, trainingSet=None, testSet=None, labels=None, fold='[1]'):
super(SemiSAD, self).__init__(conf, trainingSet, testSet, labels, fold)
def readConfiguration(self):
super(SemiSAD, self).readConfiguration()
# K = top-K vals of cov
sel... | _____no_output_____ | Apache-2.0 | docs/T006054_SDLib.ipynb | sparsh-ai/recsys-attacks |
Main | class SDLib(object):
def __init__(self,config):
self.trainingData = [] # training data
self.testData = [] # testData
self.relation = []
self.measure = []
self.config =config
self.ratingConfig = LineConfig(config['ratings.setup'])
self.labels = FileIO.loadLab... | ================================================================================
Supervised Methods:
1. DegreeSAD 2.CoDetector 3.BayesDetector
Semi-Supervised Methods:
4. SemiSAD
Unsupervised Methods:
5. PCASelectUsers 6. FAP 7.timeIndex
----------------------------------------------------------------------... | Apache-2.0 | docs/T006054_SDLib.ipynb | sparsh-ai/recsys-attacks |
Calculate the AMOC in density space$VVEL*DZT*DXT (x,y,z)$ -> $VVEL*DZT*DXT (x,y,$\sigma$)$ -> $\sum_{x=W}^E$ -> $\sum_{\sigma=\sigma_{max/min}}^\sigma$ | import os
import sys
import xgcm
import numpy as np
import xarray as xr
import cmocean
import pop_tools
import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
matplotlib.rc_file('rc_file_paper')
%config InlineBackend.print_figure_kwargs={'bbox_inches':None}
%load_ext autoreload
%autoreload 2
from MOC impo... | _____no_output_____ | BSD-3-Clause | src/Fig5.ipynb | AJueling/FW-code |
A sample of running the horizontal cylinder code through the pipeline, and visualizing it with Meshcat. | folder_name = "vert_cylinders"
rgb_filename = os.path.join("..", "src", "tests", "data", folder_name, "1.png")
camera_matrix_filename = os.path.join("..", "src", "tests", "data", folder_name, "camera_matrix.json")
pointcloud_filename = os.path.join("..", "src", "tests", "data", folder_name, "1.ply")
reference_mesh = me... | RMSE = 1.6844201070129325, density= 1.7608021498435062
[ 0.00533419 -0.11536905 0.99330838]
| MIT | notebooks/alignment.ipynb | Code-128/depth-quality |
We can use Meshcat to visualize our geometry directly in a Jupyter Notebook. | import meshcat
import meshcat.geometry as g
import meshcat.transformations as tfms
import numpy as np
vis = meshcat.Visualizer()
vis.jupyter_cell()
vis['reference'].set_object(g.ObjMeshGeometry.from_file(reference_mesh.path))
vis['reference'].set_transform(tfms.scale_matrix(0.001))
vis['transformed_cloud'].set_object(
... | _____no_output_____ | MIT | notebooks/alignment.ipynb | Code-128/depth-quality |
ENGR 213 Project Demonstration: Toast Falling from Counter Iteration AND slipping of toastThis is a Jupyter notebook created to explore the utility of notebooks as an engineering/physics tool. As I consider integrating this material into physics and engineering courses I am having a hard time clarifying the outcomes t... | %matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
plt.rcParams["figure.figsize"] = (20,10)
plt.rcParams.update({'font.size': 22})
import numpy as np | _____no_output_____ | MIT | Toast2.2.ipynb | smithrockmaker/PH213 |
Defining constantsIn this problem it seems prudent to allow for a variety of 'toast' like objects of different materials and sizes. To that end I want to establish a set of constants that describe the particular setting I am considering. Note that I am working in cm and s for convenience which may turn out to be a bad... | tlength = 10.0
twidth = 10.0
tthick = 1.0
tdensity = 0.45
counterheight = 100.0
gravity = 981.0
anglimit = np.pi/2
lindensity = tdensity*tlength*tthick # linear density of toast
tmass = lindensity*twidth # mass of toast
tinertiacm = tmass*(twidth*twidth)/12.0 # moment of inertia around CM
tinertiamax = tmass*(twidth*... | _____no_output_____ | MIT | Toast2.2.ipynb | smithrockmaker/PH213 |
Updated Freebody DiagramSince I know from experiment that the toast rotates almost exactly a full $2\pi$ if I start it hanging 3/4 of it's width over the edge that would mean that the rotational velocity when the toast disconnects from the table is around 12 rad/s (since the fall time is abut 0.5 s). The previous note... | # Solicit model parameters from user.....
tstep = float(input("Define time step in ms (ms)? "))
numit = int(input("How many interations? "))
overhang = float(input("What is the initial overhang of the toast (% as in 1.0 = 100%)? "))
coeffric = float(input("What is the coefficient of friction? "))
print("Overhang is %.3... | Define time step in ms (ms)? 3
How many interations? 10
What is the initial overhang of the toast (% as in 1.0 = 100%)? 1
What is the coefficient of friction? .2
| MIT | Toast2.2.ipynb | smithrockmaker/PH213 |
Set up variable arraysGetting these arrays set up is a little bit of an iterative process itself. I set up all the arrays I think I need and invariably I find later that I need several others. Some of that process will be hidden so I apologise. I started out this just a giant list of arrays but later decided I needed ... | # Define variable arrays needed
# time variables
count = np.linspace(0,numit,num=numit+1) # start at 0, go to numit, because it started at there is 1 more element in the array
currenttime = np.full_like(count,0.0) # same size as count will all values = 0 for starters
# moment of inertia variables
dparallel = np.full_l... | _____no_output_____ | MIT | Toast2.2.ipynb | smithrockmaker/PH213 |
Initialize the arrays....In the process of taking my original notebook apart and creating separate notebooks for each model I am finding that I can do this in a more understandable way than I did the first time around. Feel free to look back at the orginal notebook which I abandoned when it got too cumbersome.Each tim... | # Set first term of each variable
# time variables
# count : count is aready completely filled from 0 to numit
# currenttime[0] is already set to 0
# general location of cm variables
rside[0] = twidth*overhang
lside[0] = twidth-rside[0]
# torque calculation variables
armr[0] = rside[0]/2.0
arml[0] = lside[0]/2.0
weig... | _____no_output_____ | MIT | Toast2.2.ipynb | smithrockmaker/PH213 |
...same calculation but using variables differently.....I still need to calculate torqpos and torqneg but these will be based on my new nomenclature that tries to make it more explicit how the torques are calculated as well as the normal force on the corner and the friction generated.One of the features I have NOT dea... | ndex1 = 0
while (ndex1 < numit) and (angpos[ndex1] < anglimit):
print("iteration: ",ndex1)
# These calculations take place in every iteration regardless of whether it's slipping or not.
# moment of inertia NOW - ndex1
dparallel[ndex1] = rside[ndex1] - twidth/2. # value changes if slipping
... | iteration: 0
iteration: 1
iteration: 2
iteration: 3
iteration: 4
iteration: 5
iteration: 6
iteration: 7
iteration: 8
iteration: 9
final index: 10
Tpos: 0.000 Tneg 0.000 Ttot 0.000 angaccel 0.000 : torque 0.0 and angaccel 0.0
pos 0.066 vel 4.413 : angular position 1.55ish
Angle at which slipping begins is 0.0... | MIT | Toast2.2.ipynb | smithrockmaker/PH213 |
Plot lateral g force and friction to see crossover point.....This introduces a different plotting requirement. I'm looking to understand where in the process the frictional force falls below the lateral g force resulting in the toast slipping. In previous dual plot I allowed the plot routines to set the scales on the ... | plt.plot(currenttime, latgforce, color = "blue", label = "lateral g force")
plt.plot(currenttime, friction, color = "red", label = "friction")
plt.title("Is it slipping?")
plt.ylabel("force");
plt.legend(); | _____no_output_____ | MIT | Toast2.2.ipynb | smithrockmaker/PH213 |
AnalysisThe first time I ran the analysis above with the possibility of slipping I screwed up the cos/sin thing and it started slipping right away. Fixed that and then it began slipping, with a coefficient of friction of 0.4, at the 6th interation (60 ms). I increased the coefficient of friction to 0.8 and it went up ... | quadcoef[0] = -gravity/2.0
quadcoef[2] = counterheight
quadcoef[1] = slipvely[ndexfinal-1]
droptime = np.roots(quadcoef)
if droptime[0] > 0.0: # assume 2 roots and only one is positive....could be a problem
finalrotation = droptime[0]*angvel[ndexfinal]
timetofloor = droptime[0]
else:
finalrotation = dropt... | Final Report:
Final Rotation at Floor (rad): 6.387420535890989
Angular velocity coming off the table (rad/s): 15.015067546165607
Time to reach floor (s): 0.4254007193941757
Initial overhang (%): 0.75
Coefficient of Friction: 0.8
Angle at which slipping started (rad): 0.7006976411024474
Time until comes off edge (ms): ... | MIT | Toast2.2.ipynb | smithrockmaker/PH213 |
Deep learning for Natural Language Processing * Simple text representations, bag of words * Word embedding and... not just another word2vec this time * 1-dimensional convolutions for text * Aggregating several data sources "the hard way" * Solving ~somewhat~ real ML problem with ~almost~ end-to-end deep learning Speci... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline | _____no_output_____ | MIT | Seminar9/Bonus-seminar.ipynb | Omrigan/dl-course |
DatasetEx-kaggle-competition on job salary predictionOriginal conest - https://www.kaggle.com/c/job-salary-prediction DownloadGo [here](https://www.kaggle.com/c/job-salary-prediction) and download as usualCSC cloud: data should alread... | df = pd.read_csv("./Train_rev1.csv",sep=',')
print df.shape, df.SalaryNormalized.mean()
df[:5] | (244768, 12) 34122.5775755
| MIT | Seminar9/Bonus-seminar.ipynb | Omrigan/dl-course |
TokenizingFirst, we create a dictionary of all existing words.Assign each word a number - it's Id | from nltk.tokenize import RegexpTokenizer
from collections import Counter,defaultdict
tokenizer = RegexpTokenizer(r"\w+")
#Dictionary of tokens
token_counts = Counter()
#All texts
all_texts = np.hstack([df.FullDescription.values,df.Title.values])
#Compute token frequencies
for s in all_texts:
if type(s) is not ... | _____no_output_____ | MIT | Seminar9/Bonus-seminar.ipynb | Omrigan/dl-course |
Remove rare tokensWe are unlikely to make use of words that are only seen a few times throughout the corpora.Again, if you want to beat Kaggle competition metrics, consider doing something better. | #Word frequency distribution, just for kicks
_=plt.hist(token_counts.values(),range=[0,50],bins=50)
#Select only the tokens that had at least 10 occurences in the corpora.
#Use token_counts.
min_count = 5
tokens = <tokens from token_counts keys that had at least min_count occurences throughout the dataset>
token_to_i... | # Tokens: 44867
| MIT | Seminar9/Bonus-seminar.ipynb | Omrigan/dl-course |
Replace words with IDsSet a maximum length for titles and descriptions. * If string is longer that that limit - crop it, if less - pad with zeros. * Thus we obtain a matrix of size [n_samples]x[max_length] * Element at i,j - is an identifier of word j within sample i | def vectorize(strings, token_to_id, max_len=150):
token_matrix = []
for s in strings:
if type(s) is not str:
token_matrix.append([0]*max_len)
continue
s = s.decode('utf8').lower()
tokens = tokenizer.tokenize(s)
token_ids = map(lambda token: token_to_id.get... | _____no_output_____ | MIT | Seminar9/Bonus-seminar.ipynb | Omrigan/dl-course |
Data format examples | print "Matrix size:",title_tokens.shape
for title, tokens in zip(df.Title.values[:3],title_tokens[:3]):
print title,'->', tokens[:10],'...' | Размер матрицы: (244768, 15)
Engineering Systems Analyst -> [38462 12311 1632 0 0 0 0 0 0 0] ...
Stress Engineer Glasgow -> [19749 41620 5861 0 0 0 0 0 0 0] ...
Modelling and simulation analyst -> [23387 16330 32144 1632 0 0 0 0 0 0] ...... | MIT | Seminar9/Bonus-seminar.ipynb | Omrigan/dl-course |
__ As you can see, our preprocessing is somewhat crude. Let us see if that is enough for our network __ Non-sequencesSome data features are categorical data. E.g. location, contract type, companyThey require a separate preprocessing step. | #One-hot-encoded category and subcategory
from sklearn.feature_extraction import DictVectorizer
categories = []
data_cat = df[["Category","LocationNormalized","ContractType","ContractTime"]]
categories = [A list of dictionaries {"category":category_name, "subcategory":subcategory_name} for each data sample]
... | _____no_output_____ | MIT | Seminar9/Bonus-seminar.ipynb | Omrigan/dl-course |
Split data into training and test | #Target variable - whether or not sample contains prohibited material
target = df.is_blocked.values.astype('int32')
#Preprocessed titles
title_tokens = title_tokens.astype('int32')
#Preprocessed tokens
desc_tokens = desc_tokens.astype('int32')
#Non-sequences
df_non_text = df_non_text.astype('float32')
#Split into trai... | _____no_output_____ | MIT | Seminar9/Bonus-seminar.ipynb | Omrigan/dl-course |
Save preprocessed data [optional]* The next tab can be used to stash all the essential data matrices and get rid of the rest of the data. * Highly recommended if you have less than 1.5GB RAM left* To do that, you need to first run it with save_prepared_data=True, then restart the notebook and only run this tab with re... |
save_prepared_data = True #save
read_prepared_data = False #load
#but not both at once
assert not (save_prepared_data and read_prepared_data)
if save_prepared_data:
print "Saving preprocessed data (may take up to 3 minutes)"
import pickle
with open("preprocessed_data.pcl",'w') as fout:
pickle.d... | _____no_output_____ | MIT | Seminar9/Bonus-seminar.ipynb | Omrigan/dl-course |
Train the monsterSince we have several data sources, our neural network may differ from what you used to work with.* Separate input for titles * cnn+global max or RNN* Separate input for description * cnn+global max or RNN* Separate input for categorical features * Few dense layers + some black magic if you want These... | #libraries
import lasagne
from theano import tensor as T
import theano
#3 inputs and a refere output
title_token_ids = T.matrix("title_token_ids",dtype='int32')
desc_token_ids = T.matrix("desc_token_ids",dtype='int32')
categories = T.matrix("categories",dtype='float32')
target_y = T.vector("is_blocked",dtype='float32') | _____no_output_____ | MIT | Seminar9/Bonus-seminar.ipynb | Omrigan/dl-course |
NN architecture | title_inp = lasagne.layers.InputLayer((None,title_tr.shape[1]),input_var=title_token_ids)
descr_inp = lasagne.layers.InputLayer((None,desc_tr.shape[1]),input_var=desc_token_ids)
cat_inp = lasagne.layers.InputLayer((None,nontext_tr.shape[1]), input_var=categories)
# Descriptions
#word-wise embedding. We recommend to s... | _____no_output_____ | MIT | Seminar9/Bonus-seminar.ipynb | Omrigan/dl-course |
Loss function* The standard way: * prediction * loss * updates * training and evaluation functions | #All trainable params
weights = lasagne.layers.get_all_params(nn,trainable=True)
#Simple NN prediction
prediction = lasagne.layers.get_output(nn)[:,0]
#loss function
loss = lasagne.objectives.squared_error(prediction,target_y).mean()
#Weight optimization step
updates = <your favorite optimizer> | _____no_output_____ | MIT | Seminar9/Bonus-seminar.ipynb | Omrigan/dl-course |
Determinitic prediction * In case we use stochastic elements, e.g. dropout or noize * Compile a separate set of functions with deterministic prediction (deterministic = True) * Unless you think there's no neet for dropout there ofc. Btw is there? | #deterministic version
det_prediction = lasagne.layers.get_output(nn,deterministic=True)[:,0]
#equivalent loss function
det_loss = <an excercise in copy-pasting and editing>
| _____no_output_____ | MIT | Seminar9/Bonus-seminar.ipynb | Omrigan/dl-course |
Coffee-lation | train_fun = theano.function([desc_token_ids,title_token_ids,categories,target_y],[loss,prediction],updates = updates)
eval_fun = theano.function([desc_token_ids,title_token_ids,categories,target_y],[det_loss,det_prediction]) | _____no_output_____ | MIT | Seminar9/Bonus-seminar.ipynb | Omrigan/dl-course |
Training loop* The regular way with loops over minibatches* Since the dataset is huge, we define epoch as some fixed amount of samples isntead of all dataset | # Out good old minibatch iterator now supports arbitrary amount of arrays (X,y,z)
def iterate_minibatches(*arrays,**kwargs):
batchsize=kwargs.get("batchsize",100)
shuffle = kwargs.get("shuffle",True)
if shuffle:
indices = np.arange(len(arrays[0]))
np.random.shuffle(indices)
fo... | _____no_output_____ | MIT | Seminar9/Bonus-seminar.ipynb | Omrigan/dl-course |
Tweaking guide* batch_size - how many samples are processed per function call * optimization gets slower, but more stable, as you increase it. * May consider increasing it halfway through training* minibatches_per_epoch - max amount of minibatches per epoch * Does not affect training. Lesser value means more freque... | from sklearn.metrics import mean_squared_error,mean_absolute_error
n_epochs = 100
batch_size = 100
minibatches_per_epoch = 100
for i in range(n_epochs):
#training
epoch_y_true = []
epoch_y_pred = []
b_c = b_loss = 0
for j, (b_desc,b_title,b_cat, b_y) in enumerate(
iterate_minib... | If you are seeing this, it's time to backup your notebook. No, really, 'tis too easy to mess up everything without noticing.
| MIT | Seminar9/Bonus-seminar.ipynb | Omrigan/dl-course |
Final evaluationEvaluate network over the entire test set | #evaluation
epoch_y_true = []
epoch_y_pred = []
b_c = b_loss = 0
for j, (b_desc,b_title,b_cat, b_y) in enumerate(
iterate_minibatches(desc_ts,title_ts,nontext_ts,target_ts,batchsize=batch_size,shuffle=True)):
loss,pred_probas = eval_fun(b_desc,b_title,b_cat,b_y)
b_loss += loss
b_c +=1
epoch_y_tru... | _____no_output_____ | MIT | Seminar9/Bonus-seminar.ipynb | Omrigan/dl-course |
Linear Algebra (CpE210A) Midterms Project Coded and submitted by:Galario, Adrian Q. 201814169 58051 DirectionsThis Jupyter Notebook will serve as your base code for your Midterm Project. You must further format and provide complete discussion on the given topic. - Provide all necessary explanations for specific c... | import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
import seaborn as sns
%matplotlib inline
df_prices = pd.read_csv(r'C:\Users\EyyGiee\Desktop\Bebang\bebang prices.csv')
df_sales = pd.read_csv(r'C:\Users\EyyGiee\Desktop\Bebang\bebang sales.csv')
df_prices
df... | _____no_output_____ | Apache-2.0 | LinAlg_Midterms (1).ipynb | adriangalarion/Lab-Activities-1.1 |
Part 1: Monthly Sales | sales_mat = np.array(df_sales.set_index('flavor'))
prices_mat = np.array(df_prices.set_index('Unnamed: 0'))[0]
costs_mat = np.array(df_prices.set_index('Unnamed: 0'))[1]
price_reshaped=np.reshape(prices_mat,(12,1))
cost_reshaped=np.reshape(costs_mat,(12,1))
print(sales_mat.shape)
print(price_reshaped.shape)
print(co... | (12, 12)
(12, 1)
(12, 1)
| Apache-2.0 | LinAlg_Midterms (1).ipynb | adriangalarion/Lab-Activities-1.1 |
Formulas Take note that the fomula for revenue is: $revenue = sales * price $ In this case, think that revenue, sales, and price are vectors instead of individual values The formula of cost per item sold is: $cost_{sold} = sales * cost$ The formula for profit is: $profit = revenue - cost_{sold}$ Solving for the monthl... | ## Function that returns and prints the monthly sales and profit for each month
def monthly_sales(price, cost, sales):
monthly_revenue = sum(sales*price)
monthly_costs = sum(sales*cost)
monthly_profits = (monthly_revenue - monthly_costs)
return monthly_revenue.flatten(), monthly_costs.flatten(), monthly... | Monthly Revenue(Starting from the month of January):
[216510 116750 84900 26985 208850 17360 18760 19035 12090 22960
260775 422010]
Yearly Revenue:
1426985
Monthly Cost(Starting from the month of January):
[154650 70050 42450 15420 146195 13454 14070 10575 6045 14350
185440 290718]
Yearly Cos... | Apache-2.0 | LinAlg_Midterms (1).ipynb | adriangalarion/Lab-Activities-1.1 |
Part 2: Flavor Sales | ## Function that returns and prints the flavor profits for the whole year
def flavor_sales(price, cost, sales):
flavor_revenue = sales*price
flavor_costs = sales*cost
flavor_profits = flavor_revenue - flavor_costs
return flavor_profits.flatten()
### Using the flavor_sales function to compute for the... | Best Selling Flavors:
[['choco butter naught'], ['sugar glazed'], ['red velvet']]
Worst Selling Flavors:
[['almond honey'], ['furits and nuts'], ['oreo']]
| Apache-2.0 | LinAlg_Midterms (1).ipynb | adriangalarion/Lab-Activities-1.1 |
Part 3: Visualizing the Data (Optional for +40%)You can try to visualize the data in the most comprehensible chart that you can use. | import matplotlib.pyplot as plt
import matplotlib
import seaborn as sns
import pandas as pd
import csv
%matplotlib inline | _____no_output_____ | Apache-2.0 | LinAlg_Midterms (1).ipynb | adriangalarion/Lab-Activities-1.1 |
Entire Dataset | ## Graph for Sales of each flavor
## Table inside the original file(bebang sales) was transposed in the excel, columns were converted to rows
df_sales_Transposed = pd.read_csv(r"C:\Users\EyyGiee\Desktop\Bebang\bebang sales(transpose).csv")
## Transposing the table makes it easier to plot the data inside it
## The colu... | _____no_output_____ | Apache-2.0 | LinAlg_Midterms (1).ipynb | adriangalarion/Lab-Activities-1.1 |
Monthly Sales | ## Graph for Revenue vs Cost per Month
## Declaring the font size and weight to be used in the graph
font = {'weight' : 'bold',
'size' : 15}
matplotlib.rc('font', **font)
## Declaration of the figure to be used in the graph
fig = plt.figure()
ax = fig.add_axes([0,0,4,4])
ax.set_title('Revenue vs Cost per Mon... | _____no_output_____ | Apache-2.0 | LinAlg_Midterms (1).ipynb | adriangalarion/Lab-Activities-1.1 |
Flavor Sales | ## Graph for Flavor profit
## Declaration of the figure to be used
fig = plt.figure()
ax = fig.add_axes([0,0,3,2])
ax.set_ylabel('Profit')
ax.set_xlabel('Flavors')
ax.set_title('Flavor Profit')
## Declaring the values of each axis
flavors = ['Red Velvet', 'Oreo', 'Super \nGlazed', 'Almond \nHoney', 'Matcha', 'Strawber... | _____no_output_____ | Apache-2.0 | LinAlg_Midterms (1).ipynb | adriangalarion/Lab-Activities-1.1 |
Let's plot one of the Time Series. | from io_utils import load_sensor_data, file_names
df = load_sensor_data(file_names[20])
df.head()
df.info() | <class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 276048 entries, 2012-01-01 00:10:00 to 2017-03-31 00:00:00
Data columns (total 18 columns):
pr 276020 non-null float64
f_pr 276048 non-null int64
max_ws 275923 non-null float64
f_max_ws 276048 non-null int64
ave_wv 275917 non-null float64... | MIT | .ipynb_checkpoints/data_visualization-checkpoint.ipynb | qlongyinqw/gcn-japan-weather-forecast |
Extracting Data using Web Scraping | # import
import requests
from bs4 import BeautifulSoup
# HTML String
html_string = """
<!doctype html>
<html lang="en">
<head>
<title>Doing Data Science With Python</title>
</head>
<body>
<h1 style="color:#F15B2A;">Doing Data Science With Python</h1>
<p id="author">Author : Abhishek Kumar</p>
<p id="descr... | _____no_output_____ | MIT | notebooks/03 Web Scraping.ipynb | RaduMihut/titanic |
!pip -V
!python -V
!pip install --upgrade youtube-dl
!youtube-dl https://drive.google.com/file/d/16-xNP_Ez-3WgFF3vfsP9KJl4ka9hXDlV/view?usp=sharing
!youtube-dl https://drive.google.com/file/d/1rP5tveZgNXJZe_uipJNWUaSqJiow_LGc/view?usp=sharing
!ls
!mv main_DATASET_VAL.zip-1rP5tveZgNXJZe_uipJNWUaSqJiow_LGc.zip val.zip
!m... | _____no_output_____ | Apache-2.0 | Final_file_for_tata_innoverse.ipynb | abhinav090/pothole_detection | |
MoveOver for Getting Testing Images Similar to S3 Bucket | !youtube-dl https://drive.google.com/file/d/1FTvc361O9BBURgsTMb6dJoE6InAoic_O/view?usp=sharing
!ls
!mv images.zip-1FTvc361O9BBURgsTMb6dJoE6InAoic_O.zip images.zip
!mkdir S3_Images
!mv images.zip S3_Images/
%cd S3_Images/
!ls
!unzip images.zip
!ls
!rm -rf images.zip
!rm -rf __MACOSX/
!mv images\ 2 images
!ls
!ls images
... | adding: content/Mask_RCNN/videos/save/ (stored 0%)
adding: content/Mask_RCNN/videos/save/[4556]-[0.99999726].jpg (deflated 0%)
adding: content/Mask_RCNN/videos/save/[100835, 4752, 31860]-[0.99894387 0.9983626 0.99591905].jpg (deflated 0%)
adding: content/Mask_RCNN/videos/save/[250, 260]-[0.9999243 0.8455281].j... | Apache-2.0 | Final_file_for_tata_innoverse.ipynb | abhinav090/pothole_detection |
Credit Risk Resampling Techniques | import warnings
warnings.filterwarnings('ignore')
import numpy as np
import pandas as pd
from pathlib import Path
from collections import Counter | _____no_output_____ | ADSL | Starter_Code/credit_risk_resampling.ipynb | AntoJKumar/Risky_Business |
Read the CSV into DataFrame | # Load the data
file_path = Path('Resources/lending_data.csv')
df = pd.read_csv(file_path)
df.head() | _____no_output_____ | ADSL | Starter_Code/credit_risk_resampling.ipynb | AntoJKumar/Risky_Business |
Split the Data into Training and Testing | from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
le.fit(df["homeowner"])
df["homeowner"] = le.transform(df["homeowner"])
# Create our features
X = X = df.copy()
X.drop("loan_status", axis=1, inplace=True)
# Create our target
y = y = df['loan_status']
X.describe()
# Check the balance of our target va... | _____no_output_____ | ADSL | Starter_Code/credit_risk_resampling.ipynb | AntoJKumar/Risky_Business |
Data Pre-ProcessingScale the training and testing data using the `StandardScaler` from `sklearn`. Remember that when scaling the data, you only scale the features data (`X_train` and `X_testing`). | # Create the StandardScaler instance
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
# Fit the Standard Scaler with the training data
# When fitting scaling functions, only train on the training dataset
X_scaler = scaler.fit(X_train)
# Scale the training and testing data
X_train_scaled = X_sc... | _____no_output_____ | ADSL | Starter_Code/credit_risk_resampling.ipynb | AntoJKumar/Risky_Business |
Simple Logistic Regression | from sklearn.linear_model import LogisticRegression
model = LogisticRegression(solver='lbfgs', random_state=1)
model.fit(X_train, y_train)
# Calculated the balanced accuracy score
from sklearn.metrics import balanced_accuracy_score
y_pred = model.predict(X_test)
balanced_accuracy_score(y_test, y_pred)
# Display the con... | pre rec spe f1 geo iba sup
high_risk 0.85 0.91 0.99 0.88 0.95 0.90 619
low_risk 1.00 0.99 0.91 1.00 0.95 0.91 18765
avg / total 0.99 0.99 0.91 0.99 0.95 0... | ADSL | Starter_Code/credit_risk_resampling.ipynb | AntoJKumar/Risky_Business |
OversamplingIn this section, you will compare two oversampling algorithms to determine which algorithm results in the best performance. You will oversample the data using the naive random oversampling algorithm and the SMOTE algorithm. For each algorithm, be sure to complete the folliowing steps:1. View the count of t... | # Resample the training data with the RandomOversampler
from imblearn.over_sampling import RandomOverSampler
ros = RandomOverSampler(random_state=1)
X_resampled1, y_resampled1 = ros.fit_resample(X_train, y_train)
# View the count of target classes with Counter
Counter(y_resampled1)
# Train the Logistic Regression mod... | pre rec spe f1 geo iba sup
high_risk 0.84 0.99 0.99 0.91 0.99 0.99 619
low_risk 1.00 0.99 0.99 1.00 0.99 0.99 18765
avg / total 0.99 0.99 0.99 0.99 0.99 0... | ADSL | Starter_Code/credit_risk_resampling.ipynb | AntoJKumar/Risky_Business |
SMOTE Oversampling | # Resample the training data with SMOTE
from imblearn.over_sampling import SMOTE
X_resampled2, y_resampled2 = SMOTE(random_state=1, sampling_strategy=1.0).fit_resample(X_train, y_train)
# View the count of target classes with Counter
Counter(y_resampled2)
# Train the Logistic Regression model using the resampled data... | pre rec spe f1 geo iba sup
high_risk 0.84 0.99 0.99 0.91 0.99 0.99 619
low_risk 1.00 0.99 0.99 1.00 0.99 0.99 18765
avg / total 0.99 0.99 0.99 0.99 0.99 0... | ADSL | Starter_Code/credit_risk_resampling.ipynb | AntoJKumar/Risky_Business |
UndersamplingIn this section, you will test an undersampling algorithm to determine which algorithm results in the best performance compared to the oversampling algorithms above. You will undersample the data using the Cluster Centroids algorithm and complete the folliowing steps:1. View the count of the target classe... | # Resample the data using the ClusterCentroids resampler
from imblearn.under_sampling import ClusterCentroids
cc = ClusterCentroids(random_state=1)
X_resampled3, y_resampled3 = cc.fit_resample(X_train, y_train)
# View the count of target classes with Counter
Counter(y_resampled3)
# Train the Logistic Regression model... | pre rec spe f1 geo iba sup
high_risk 0.8440 0.9790 0.9940 0.9065 0.9865 0.9717 619
low_risk 0.9993 0.9940 0.9790 0.9967 0.9865 0.9746 18765
avg / total 0.9943 0.9936 0.9795 0.9938 0.9865 0.9... | ADSL | Starter_Code/credit_risk_resampling.ipynb | AntoJKumar/Risky_Business |
Combination (Over and Under) SamplingIn this section, you will test a combination over- and under-sampling algorithm to determine if the algorithm results in the best performance compared to the other sampling algorithms above. You will resample the data using the SMOTEENN algorithm and complete the folliowing steps:1... | # Resample the training data with SMOTEENN
from imblearn.combine import SMOTEENN
sm = SMOTEENN(random_state=1)
X_resampled4, y_resampled4 = sm.fit_resample(X_train, y_train)
# View the count of target classes with Counter
Counter(y_resampled4)
# Train the Logistic Regression model using the resampled data
model4 = Lo... | pre rec spe f1 geo iba sup
high_risk 0.83 0.99 0.99 0.91 0.99 0.99 619
low_risk 1.00 0.99 0.99 1.00 0.99 0.99 18765
avg / total 0.99 0.99 0.99 0.99 0.99 0... | ADSL | Starter_Code/credit_risk_resampling.ipynb | AntoJKumar/Risky_Business |
Gráficos de desempenho das Caches Import libs | %matplotlib inline
##Bibliotecas importadas
# Biblioteca usada para abrir arquivos CSV
import csv
# Bibilioteca para fazer leitura de datas
from datetime import datetime, timedelta
# Fazer o ajuste de datas no gráfico
import matplotlib.dates as mdate
# Biblioteca mateḿática
import numpy as np
# Bibloteca para traçar gr... | _____no_output_____ | MIT | trabalho2/Caches.ipynb | laurocruz/MC733 |
Generate miss % graphs | for file in os.listdir('cache_csv/percentage'):
filepath = 'cache_csv/percentage/'+file
dados = list(csv.reader(open(filepath,'r')))
alg = file.split('.')[0]
mr1 = list()
mr2 = list()
mw1 = list()
mw2 = list()
mrw1 = list()
mrw2 = list()
mi1 = list()
mi2 = list()
... | _____no_output_____ | MIT | trabalho2/Caches.ipynb | laurocruz/MC733 |
Generate graphs of miss numbers | for file in os.listdir('cache_csv/num'):
filepath = 'cache_csv/num/'+file
dados = list(csv.reader(open(filepath,'r')))
alg = file.split('.')[0]
mr1 = list()
mr2 = list()
mw1 = list()
mw2 = list()
mrw1 = list()
mrw2 = list()
mi1 = list()
mi2 = list()
for dad... | _____no_output_____ | MIT | trabalho2/Caches.ipynb | laurocruz/MC733 |
Loading libraries and looking at given data | import numpy as np
import pandas as pd
import seaborn as sns
import re
appendix_3=pd.read_excel("Appendix_3_august.xlsx")
appendix_3
print(appendix_3["Language"].value_counts(),)
print(appendix_3["Country"].value_counts())
pd.set_option("display.max_rows", None, "display.max_columns", None)
print(appendix_3['Country'].... | United States
France
Korea
Italy
Germany
Australia
China
United Kingdom
Spain
Canada
Netherlands
Ireland
... | MIT | teaching_material/session_6/gruppe_8/3shape_final.ipynb | tlh957/DO2021 |
Removing useless data | appendix_3=appendix_3[appendix_3.Language!="Københavnsk"]
appendix_3=appendix_3.drop(["Meaningless_ID"], axis=1)
appendix_3
appendix_3=appendix_3[appendix_3.Licenses!=0]
appendix_3 | _____no_output_____ | MIT | teaching_material/session_6/gruppe_8/3shape_final.ipynb | tlh957/DO2021 |
Making usefull languages | def language(var):
"""Function that returns languages spoken by 3Shapes present support teams.
If not spoken, return English"""
if var.lower() in ['english','american']: #If english or "american"
return 'English' #Return English
if var.lower() in ['spanish']:
return 'Spanish'
... | _____no_output_____ | MIT | teaching_material/session_6/gruppe_8/3shape_final.ipynb | tlh957/DO2021 |
Making a column that "groups" countries into 3 regions/timezones of the world (Americas, Europe (incl. Middle East and Africa) and Asia) | def region(var):
"""Function that returns region based on country"""
if var in ['United States','Canada','Brazil','Mexico','Colombia','Argentina','Uruguay',
'Costa Rica','Chile','Paraguay','Bolivia','Venezuela','Puerto Rico']:
return 'Americas'
if var in ['France',... | _____no_output_____ | MIT | teaching_material/session_6/gruppe_8/3shape_final.ipynb | tlh957/DO2021 |
New DataFrame with our three regions/support centers | New_regions=appendix_3.groupby(["Region"])["Licenses"].sum().sort_values(ascending=False).to_frame().reset_index()
New_regions
def employees_needed(var):
""" Function that gives number of recuired employees based on licenses"""
if var <300:
return 3
else:
return np.ceil((var-300)/200+3)
New_... | _____no_output_____ | MIT | teaching_material/session_6/gruppe_8/3shape_final.ipynb | tlh957/DO2021 |
Loking at appendix 2 and cleaning useless data, and converting to int. | appendix_2=pd.read_excel("Appendix_2_august.xlsx")
appendix_2
appendix_2=appendix_2.drop([5])
appendix_2
appendix_2['Total cost']=appendix_2['Total cost'].astype(int)
appendix_2['Average FTE']=appendix_2['Average FTE'].astype(int)
print(appendix_2.dtypes) | Support Center object
Total cost int64
Average FTE int64
dtype: object
| MIT | teaching_material/session_6/gruppe_8/3shape_final.ipynb | tlh957/DO2021 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.