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 |
|---|---|---|---|---|---|
__Exercise 2__ | import nltk
from nltk.corpus import names
import random
names = ([(name, 'male') for name in names.words('male.txt')] + [(name, 'female') for name in names.words('female.txt')])
random.shuffle(names)
test, devtest, training = names[:500], names[500:1000], names[1000:]
def gender_features1(name):
features = {}
... | _____no_output_____ | MIT | chapter_6_exercises.ipynb | JuliaNeumann/nltk_book_exercises |
__Exercise 3)__ | from nltk.corpus import senseval
instances = senseval.instances('serve.pos')
size = int(len(instances) * 0.1)
training, test = instances[size:], instances[:size]
training[0]
def sense_features(instance):
features = {}
features["word-type"] = instance.word
features["word-tag"] = instance.context[instance.pos... | 0.807780320366
| MIT | chapter_6_exercises.ipynb | JuliaNeumann/nltk_book_exercises |
__Exercise 4)__ | from nltk.corpus import movie_reviews
documents = [(list(movie_reviews.words(fileid)), category) for category in movie_reviews.categories() for fileid in movie_reviews.fileids(category)]
random.shuffle(documents)
all_words = nltk.FreqDist(w.lower() for w in movie_reviews.words())
word_features = all_words.keys()[:2000... | _____no_output_____ | MIT | chapter_6_exercises.ipynb | JuliaNeumann/nltk_book_exercises |
def isBalanced(S):
stack = []
brac = {"{": "}", "[": "]", "(" : ")"}
for i in S:
if i in brac.keys():
stack.append(i)
elif i in brac.values():
if i == brac.get(stack[-1]):
stack.pop()
else:
stack.append(i)
return "Succes... | {[}
3
| Unlicense | Lab7_1.ipynb | hocthucv/bt | |
Table of Contents1 Figure 1: Introduction2 Figure 2: Model Performance2.1 Load KaiABC model2.1.1 Estimate Errors2.2 Plot KaiABC model with $N_{\rm eff}$3 Figure 3: Plot all data together4 Figure 4: New Model5 Supplemental Plots | import numpy as np
import matplotlib.pyplot as plt
from decimal import Decimal
import pandas as pd
import pickle
from matplotlib.backends import backend_pdf as bpdf
from kaic_analysis.scripts import FirstPassage, RunModel, Current, StateData, FindParam, LoadExperiment, PlotExperiment, EntropyRate
from kaic_analysis.toy... | _____no_output_____ | MIT | data/Generate Plots.ipynb | robertvsiii/kaic-analysis |
Figure 1: Introduction | fig,ax = plt.subplots(figsize=(3.25,1.75))
fig.subplots_adjust(left=0.17,bottom=0.25,right=0.95)
code_folder = '../KMC_KaiC_rev2'
data_low=RunModel(folder=code_folder,paramdict={'volume':1,'sample_cnt':1e4,'tequ':50,'rnd_seed':np.random.randint(1e6),'ATPfrac':0.45},name='data_low')
data_WT=RunModel(folder=code_folder,... | _____no_output_____ | MIT | data/Generate Plots.ipynb | robertvsiii/kaic-analysis |
Figure 2: Model Performance Load KaiABC model | param_name = 'ATPfrac'
run_nums = list(range(1,13))
data = LoadExperiment(param_name,run_nums,date='2018-08-23',folder='kaic_data')[2]
run_nums = list(range(13,22))
data.update(LoadExperiment(param_name,run_nums,date='2018-08-24',folder='kaic_data')[2])
keylist = list(data.keys())
ATPfracs = [Decimal(keylist[j].split(... | _____no_output_____ | MIT | data/Generate Plots.ipynb | robertvsiii/kaic-analysis |
Estimate Errors The graphs of the bootstrap error versus number of cycles indicate that the standard deviation of the completion time increases linearly with the number of cycles. This is what we would expect to happen if each run of the experiment (making the same number of trajectories and estimating the variance fo... | with open('ModelData.dat','rb') as f:
[T,D,D_err,Scyc] = pickle.load(f)
DelWmin = 2000
DelWmax = 3100
DelWvec = np.exp(np.linspace(np.log(DelWmin),np.log(DelWmax),5000))
M = 180*2
Neff = 1.1
Ncoh = T/D
Ncoh_err = (T/D**2)*D3_err
k=0
Scyc = Scyc[:-1]
Ncoh = Ncoh[:-1]
Ncoh_err = Ncoh_err[:-1]
fig,ax=plt.subpl... | _____no_output_____ | MIT | data/Generate Plots.ipynb | robertvsiii/kaic-analysis |
Figure 3: Plot all data together Empirical curve:\begin{align}\frac{V}{\mathcal{N}} - C &= W_0 (W-W_c)^\alpha\\\frac{\mathcal{N}}{V} &= \frac{1}{C+ W_0(W-W_c)^\alpha}\end{align} | with open('ModelData.dat','rb') as f:
[T,D,D_err,Scyc] = pickle.load(f)
def CaoN(DelW,params = {}):
N = (params['C']+params['W0']*(DelW-params['Wc'])**params['alpha'])**(-1)
N[np.where(DelW<params['Wc'])[0]] = np.nan
return N
#For comparing experiment data:
VKai = 3e13 #Convert volume to single hexame... | /anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:5: RuntimeWarning: invalid value encountered in power
"""
| MIT | data/Generate Plots.ipynb | robertvsiii/kaic-analysis |
Figure 4: New Model | date = '2018-08-23'
date2 = '2018-08-24'
date3 = '2018-08-25'
D0 = []
D0_err = []
T = []
Scyc = []
sigy =[]
colors = sns.color_palette("RdBu_r",20)
k = 0
for expt_number in range(3):
low = 18*expt_number+1
high = 18*(expt_number+1)
if expt_number == 2: #Skip simulations that failed
low = 48
for ... | _____no_output_____ | MIT | data/Generate Plots.ipynb | robertvsiii/kaic-analysis |
Supplemental Plots | data = []
N = 6
M = 100
C = 5
kwargs = {'tmax':4,'nsteps':1,'N':N,'M':M,'A':4.4,'C':C}
out1 = SimulateClockKinetic(**kwargs)
kwargs = {'tmax':4,'nsteps':1,'N':N,'M':M,'A':9.529,'C':C}
out2 = SimulateClockKinetic(**kwargs)
fig,ax=plt.subplots()
ax.plot(out1['t'],out1['f'][:,0], label=r'$\dot{S} = 160\,k_B/{\rm hr}$')
ax... | _____no_output_____ | MIT | data/Generate Plots.ipynb | robertvsiii/kaic-analysis |
Note* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps. | # Dependencies and Setup
import pandas as pd
# File to Load (Remember to Change These)
school_data_to_load = "Resources/schools_complete.csv"
student_data_to_load = "Resources/students_complete.csv"
# Read School and Student Data File and store into Pandas Data Frames
school_data = pd.read_csv(school_data_to_load)
st... | _____no_output_____ | ADSL | PyCitySchools/Resources/PyCitySchools_starter_unsolved.ipynb | fkokro/Pandas---Challenge |
District Summary* Calculate the total number of schools* Calculate the total number of students* Calculate the total budget* Calculate the average math score * Calculate the average reading score* Calculate the overall passing rate (overall average score), i.e. (avg. math score + avg. reading score)/2* Calculate the p... | #Calculates the total number of schools
arr_of_schools = school_data_complete["school_name"].unique()
total_schools = len(arr_of_schools)
#Calulates the number of students
arr_of_students = school_data_complete["student_name"]
total_students = len(arr_of_students)
#Calulates the total budget for all schools
arr_of_budg... | _____no_output_____ | ADSL | PyCitySchools/Resources/PyCitySchools_starter_unsolved.ipynb | fkokro/Pandas---Challenge |
School Summary * Create an overview table that summarizes key metrics about each school, including: * School Name * School Type * Total Students * Total School Budget * Per Student Budget * Average Math Score * Average Reading Score * % Passing Math * % Passing Reading * Overall Passing Rate (Average of the ... | #Sets index to school name
school_data_complete_name_index = school_data_complete.set_index("school_name") | _____no_output_____ | ADSL | PyCitySchools/Resources/PyCitySchools_starter_unsolved.ipynb | fkokro/Pandas---Challenge |
Bottom Performing Schools (By Passing Rate) * Sort and display the five worst-performing schools | _____no_output_____ | ADSL | PyCitySchools/Resources/PyCitySchools_starter_unsolved.ipynb | fkokro/Pandas---Challenge | |
Math Scores by Grade * Create a table that lists the average Reading Score for students of each grade level (9th, 10th, 11th, 12th) at each school. * Create a pandas series for each grade. Hint: use a conditional statement. * Group each series by school * Combine the series into a dataframe * Optional: give ... | # Sample bins. Feel free to create your own bins.
spending_bins = [0, 585, 615, 645, 675]
group_names = ["<$585", "$585-615", "$615-645", "$645-675"] | _____no_output_____ | ADSL | PyCitySchools/Resources/PyCitySchools_starter_unsolved.ipynb | fkokro/Pandas---Challenge |
Scores by School Size * Perform the same operations as above, based on school size. | # Sample bins. Feel free to create your own bins.
size_bins = [0, 1000, 2000, 5000]
group_names = ["Small (<1000)", "Medium (1000-2000)", "Large (2000-5000)"] | _____no_output_____ | ADSL | PyCitySchools/Resources/PyCitySchools_starter_unsolved.ipynb | fkokro/Pandas---Challenge |
Copyright 2020 The TensorFlow Authors. | #@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | _____no_output_____ | Apache-2.0 | site/en/guide/graph_optimization.ipynb | atharva1503/docs |
TensorFlow graph optimization with Grappler View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook OverviewTensorFlow uses both graph and eager executions to execute computations. A `tf.Graph` contains a set of `tf.Operation` objects (ops) which represent units... | from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
import timeit
import traceback
import contextlib
try:
%tensorflow_version 2.x
except Exception:
pass
import tensorflow as tf | _____no_output_____ | Apache-2.0 | site/en/guide/graph_optimization.ipynb | atharva1503/docs |
Create a context manager to easily toggle optimizer states. | @contextlib.contextmanager
def options(options):
old_opts = tf.config.optimizer.get_experimental_options()
tf.config.optimizer.set_experimental_options(options)
try:
yield
finally:
tf.config.optimizer.set_experimental_options(old_opts) | _____no_output_____ | Apache-2.0 | site/en/guide/graph_optimization.ipynb | atharva1503/docs |
Compare execution performance with and without GrapplerTensorFlow 2 and beyond executes [eagerly](../eager.md) by default. Use `tf.function` to switch the default execution to Graph mode. Grappler runs automatically in the background to apply the graph optimizations above and improve execution performance. Constant ... | def test_function_1():
@tf.function
def simple_function(input_arg):
print('Tracing!')
a = tf.constant(np.random.randn(2000,2000), dtype = tf.float32)
c = a
for n in range(50):
c = c@a
return tf.reduce_mean(c+input_arg)
return simple_function | _____no_output_____ | Apache-2.0 | site/en/guide/graph_optimization.ipynb | atharva1503/docs |
Turn off the constant folding optimizer and execute the function: | with options({'constant_folding': False}):
print(tf.config.optimizer.get_experimental_options())
simple_function = test_function_1()
# Trace once
x = tf.constant(2.2)
simple_function(x)
print("Vanilla execution:", timeit.timeit(lambda: simple_function(x), number = 1), "s") | _____no_output_____ | Apache-2.0 | site/en/guide/graph_optimization.ipynb | atharva1503/docs |
Enable the constant folding optimizer and execute the function again to observe a speed-up in function execution. | with options({'constant_folding': True}):
print(tf.config.optimizer.get_experimental_options())
simple_function = test_function_1()
# Trace once
x = tf.constant(2.2)
simple_function(x)
print("Constant folded execution:", timeit.timeit(lambda: simple_function(x), number = 1), "s") | _____no_output_____ | Apache-2.0 | site/en/guide/graph_optimization.ipynb | atharva1503/docs |
Debug stripper optimizerConsider a simple function that checks the numeric value of its input argument and returns it. | def test_function_2():
@tf.function
def simple_func(input_arg):
output = input_arg
tf.debugging.check_numerics(output, "Bad!")
return output
return simple_func | _____no_output_____ | Apache-2.0 | site/en/guide/graph_optimization.ipynb | atharva1503/docs |
First, execute the function with the debug stripper optimizer turned off. | test_func = test_function_2()
p1 = tf.constant(float('inf'))
try:
test_func(p1)
except tf.errors.InvalidArgumentError as e:
traceback.print_exc(limit=2) | _____no_output_____ | Apache-2.0 | site/en/guide/graph_optimization.ipynb | atharva1503/docs |
`tf.debugging.check_numerics` raises an invalid argument error because of the `Inf` argument to `test_func`. Enable the debug stripper optimizer and execute the function again. | with options({'debug_stripper': True}):
test_func2 = test_function_2()
p1 = tf.constant(float('inf'))
try:
test_func2(p1)
except tf.errors.InvalidArgumentError as e:
traceback.print_exc(limit=2) | _____no_output_____ | Apache-2.0 | site/en/guide/graph_optimization.ipynb | atharva1503/docs |
Part I. ETL Pipeline for Pre-Processing the Files Import Python packages | # Import Python packages
import pandas as pd
import cassandra
import re
import os
import glob
import numpy as np
import json
import csv | _____no_output_____ | MIT | sparkify_cassandra_project.ipynb | iamfeniak/sparkify-etl-pipeline-cassandra |
Creating list of filepaths to process original event csv data files | # checking your current working directory
print(os.getcwd())
# Get your current folder and subfolder event data
filepath = os.getcwd() + '/event_data'
# Create a for loop to create a list of files and collect each filepath
for root, dirs, files in os.walk(filepath):
# join the file path and roots with the subdir... | /home/workspace
| MIT | sparkify_cassandra_project.ipynb | iamfeniak/sparkify-etl-pipeline-cassandra |
Processing the files to create the data file csv that will be used for Apache Casssandra tables | # initiating an empty list of rows that will be generated from each file
full_data_rows_list = []
# for every filepath in the file path list
for f in file_path_list:
# reading csv file
with open(f, 'r', encoding = 'utf8', newline='') as csvfile:
# creating a csv reader object
csvreade... | 6821
| MIT | sparkify_cassandra_project.ipynb | iamfeniak/sparkify-etl-pipeline-cassandra |
The event_datafile_new.csv now contains the following columns: - artist - firstName of user- gender of user- item number in session- last name of user- length of the song- level (paid or free song)- location of the user- sessionId- song title- userIdThe image below is a screenshot of what the denormalized data should ... | from cassandra.cluster import Cluster
try:
# This should make a connection to a Cassandra instance your local machine
# (127.0.0.1)
cluster = Cluster(['127.0.0.1'])
# To establish connection and begin executing queries, need a session
session = cluster.connect()
except Exception as e:
print(e... | _____no_output_____ | MIT | sparkify_cassandra_project.ipynb | iamfeniak/sparkify-etl-pipeline-cassandra |
Create Keyspace | try:
session.execute("""
CREATE KEYSPACE IF NOT EXISTS sparkify
WITH REPLICATION =
{ 'class' : 'SimpleStrategy', 'replication_factor' : 1 }""")
except Exception as e:
print(e) | _____no_output_____ | MIT | sparkify_cassandra_project.ipynb | iamfeniak/sparkify-etl-pipeline-cassandra |
Set Keyspace | try:
session.set_keyspace('sparkify')
except Exception as e:
print(e) | _____no_output_____ | MIT | sparkify_cassandra_project.ipynb | iamfeniak/sparkify-etl-pipeline-cassandra |
Part II. Time to answer important query questions Query 1. Give me the artist, song title and song's length in the music app history that was heard during sessionId = 338, and itemInSession = 4This query focuses on session history, so the table will be named accordingly.Filtering needs to be done by session_id AND ... | session_history_create = """CREATE TABLE IF NOT EXISTS session_history(
session_id int,
item_in_session int,
artist_name text,
song_title text,
song_length float,
PRIMARY KEY(session_id, item_in_session));"""
try:
session.execute(session_history_create)
except Ex... | _____no_output_____ | MIT | sparkify_cassandra_project.ipynb | iamfeniak/sparkify-etl-pipeline-cassandra |
Let's test query 1 with an example | query = """SELECT artist_name, song_title, song_length
FROM session_history
WHERE session_id=338 AND item_in_session=4;"""
try:
result = pd.DataFrame(list(session.execute(query)))
print(result.to_string())
except Exception as e:
print(e) | artist_name song_title song_length
0 Faithless Music Matters (Mark Knight Dub) 495.307312
| MIT | sparkify_cassandra_project.ipynb | iamfeniak/sparkify-etl-pipeline-cassandra |
Query 2. Give me only the following: name of artist, song (sorted by itemInSession) and user (first and last name) for userid = 10, sessionid = 182This query focuses on specific user session history. We will be retrieving specific listening details by user_id and session_id. To support query, user_id, session_id and i... | user_session_history_create = """
CREATE TABLE IF NOT EXISTS user_session_history(
user_id int,
session_id int,
item_in_session int,
artist_name text,
song_title text,
user_first_name text,
user_last_name text,
PRIMARY KEY(user_id, session_id, item_... | _____no_output_____ | MIT | sparkify_cassandra_project.ipynb | iamfeniak/sparkify-etl-pipeline-cassandra |
Let's test query 2 with an example | query = """SELECT artist_name, song_title, user_first_name, user_last_name
FROM user_session_history
WHERE user_id=10 AND session_id=182;"""
try:
result = pd.DataFrame(list(session.execute(query)))
print(result.to_string())
except Exception as e:
print(e) | artist_name song_title user_first_name user_last_name
0 Down To The Bone Keep On Keepin' On Sylvie Cruz
1 Three Drives Greece 2000 Sylvie Cruz
2 Sebastie... | MIT | sparkify_cassandra_project.ipynb | iamfeniak/sparkify-etl-pipeline-cassandra |
Query 3. Give me every user name (first and last) in my music app history who listened to the song 'All Hands Against His Own'This query focuses on song history, highlighting which songs are being listened to by which users. We will be retrieving specific listening details by song_title. To support query, song_title a... | song_user_history_create = """
CREATE TABLE IF NOT EXISTS song_user_history(
user_id int,
song_title text,
user_first_name text,
user_last_name text,
PRIMARY KEY(song_title, user_id));"""
try:
session.execute(song_user_history_create)
except Exception as e:
print(e)... | _____no_output_____ | MIT | sparkify_cassandra_project.ipynb | iamfeniak/sparkify-etl-pipeline-cassandra |
Let's test query 3 with an example | query = """SELECT user_first_name, user_last_name
FROM song_user_history
WHERE song_title='All Hands Against His Own';"""
try:
result = pd.DataFrame(list(session.execute(query)))
print(result.to_string())
except Exception as e:
print(e) | user_first_name user_last_name
0 Jacqueline Lynch
1 Tegan Levine
2 Sara Johnson
| MIT | sparkify_cassandra_project.ipynb | iamfeniak/sparkify-etl-pipeline-cassandra |
Dropping the tables before closing out the sessions | drop_session_history = "DROP TABLE IF EXISTS session_history;"
session.execute(drop_session_history)
drop_user_session_history = "DROP TABLE IF EXISTS user_session_history;"
session.execute(drop_user_session_history)
drop_song_user_history = "DROP TABLE IF EXISTS song_user_history;"
session.execute(drop_song_user_histo... | _____no_output_____ | MIT | sparkify_cassandra_project.ipynb | iamfeniak/sparkify-etl-pipeline-cassandra |
Don't forget to close the session and cluster connection¶ | session.shutdown()
cluster.shutdown() | _____no_output_____ | MIT | sparkify_cassandra_project.ipynb | iamfeniak/sparkify-etl-pipeline-cassandra |
Welcome! In finance momentum refers to the phenomenon of cross-sectional predictability of returns by past price data. A standard example would be the well documented tendency of stocks that have had high returns over the past one to twelve months to continue outperform stocks that have performed poorly over the same p... | import csv
import random
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as statfunc
import pandas as pd
import plotly.graph_objs as go
import mplfinance as mpf
from sklearn import mixture as mix
import seaborn as sns
from pandas_datareader import data as web
df= web.get_data_yahoo('RELIANCE.NS',... | Mean for regime 0: 10784.766638714711
Co-Variancefor regime 0: 36141.444765725864
Mean for regime 1: 12047.572769668644
Co-Variancefor regime 1: 23143.320584827794
Mean for regime 2: 9447.270093875897
Co-Variancefor regime 2: 453141.17885501473
Mean for regime 3: 11509.5640340791
Co-Variancefor regime 3: 30112.... | MIT | FinanceProjectMain.ipynb | AmaaniGoose/FinanceProject |
Version 2: Using technical indicators | print(df)
def RSI(df, base="Close", period=21):
"""
Function to compute Relative Strength Index (RSI)
Args :
df : Pandas DataFrame which contains ['date', 'open', 'high', 'low', 'close', 'volume'] columns
base : String indicating the column name from which the MACD needs to be computed ... | _____no_output_____ | MIT | FinanceProjectMain.ipynb | AmaaniGoose/FinanceProject |
Objectives* Consider only two features of the dataset obtained after t-sne* Find out best performing value of perplexity for t-sne using cross-validation* Use linear model with no calibration vs non linear model to see how well these perform | def get_training_set(train):
X = train[train.columns.drop('Activity')]
y = train.Activity
return X, y
X, y = get_training_set(train)
Xtest = test
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, test_size=0.3, random_state=44) | _____no_output_____ | MIT | Kaggle-Competitions/Predict-Bio-Response/Predict-Bio-Response-Model-Building.ipynb | gopala-kr/ds-notebooks |
Cross validation | def get_cross_val_scores_by_perplexity(X, y, clf):
skf = StratifiedKFold(y, n_folds=3, shuffle=True, random_state=43)
perplexity = [50, 75, 100]
errors = []
for p in perplexity:
tsne = TSNE(n_components=2, perplexity=p)
Xhat = tsne.fit_transform(X)
cv_scores = cross... | _____no_output_____ | MIT | Kaggle-Competitions/Predict-Bio-Response/Predict-Bio-Response-Model-Building.ipynb | gopala-kr/ds-notebooks |
Old way - csv | #js = json.load(open('ref_1554219251.json'))
#csv = open('ref_1554219251.csv').read()
csv = open('ref_1558361146.csv').read()
csv_data = []
for rec in [x.strip() for x in csv.split("\n")]:
p = rec.split(';')
if len(p) < 6:
continue
cur = collections.OrderedDict([
('method', p[0]),
... | _____no_output_____ | MIT | bool-pvalues.ipynb | sobuch/polynomial-distinguishers |
pvalues - pvalue = probability (in the null hypothesis distribution) to be observed as a value equal to or more extreme than the value observed computation - Derive CDF -> find 0 regions = extremes - Integrate from 0 regions towards region of increasing integral value. - Once sum of all integrations is alpha, stop.... | np.arange(-1, 1, 1/20.)
counter = [0] * 8
MAXV = 2
def inc(counter):
global MAXV
ln = len(counter) - 1
while ln >= 0:
counter[ln] = (counter[ln] + 1) % MAXV
if (counter[ln] != 0):
return(counter)
ln-=1
raise ValueError('Overflow')
def dec(counter):
global M... | _____no_output_____ | MIT | bool-pvalues.ipynb | sobuch/polynomial-distinguishers |
GradCAM (Gradient class activation mappinng)这个版本主要用来了解制作Grad_Cam的过程,并没有特意封装每行代码几乎都有注解---CNN卷积一直都是一个神秘的过程过去一直被以黑盒来形容能够窥探CNN是一件很有趣的事情, 特别是还能够帮助我们在进行一些任务的时候了解模型判别目标物的过程是不是出了什么问题而Grad-CAM就是一个很好的可视化选择因为能够生成高分辨率的图并叠加在原图上, 让我们在研究一些模型判别错误的时候, 有个更直观的了解那么具体是如何生成Grad CAM的呢?老规矩先上图, 说明流程一定要配图:
"""
1. 提取目标层特征
2. register 目标层梯度
"""
def __init__(self, model, target_layers):
self.model = model
self.model_features = model.features
... | /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ipykernel_launcher.py:47: UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor).
| OML | PaddleCare/Deep_learning/Grad_CAM_Pytorch-1.01-Stephenfang51-patch-1/Grad_CAM_Pytorch_1_tutorialv2.ipynb | momozi1996/Medical_AI_analysis |
1 ~ 9 (NO transistor) | GPIO.output(Pin.A.value, GPIO.LOW)
GPIO.output(Pin.B.value, GPIO.LOW)
GPIO.output(Pin.C.value,GPIO.LOW)
GPIO.output(Pin.D.value, GPIO.LOW)
GPIO.output(Pin.A.value,GPIO.HIGH)
GPIO.output(Pin.B.value,GPIO.LOW)
GPIO.output(Pin.C.value,GPIO.LOW)
GPIO.output(Pin.D.value, GPIO.LOW)
GPIO.output(Pin.A.value,GPIO.LOW)
GPIO.outp... | _____no_output_____ | MIT | nixie/nixie.ipynb | tanico-rikudo/raspi4 |
(experimental) Channels Last Memory Format in PyTorch*********************************************************Author**: `Vitaly Fedyunin `_What is Channels Last---------------------Channels Last memory format is an alternative way of ordering NCHW tensors in memory preserving dimensions ordering. Channels Last tensors ... | import torch
N, C, H, W = 10, 3, 32, 32 | _____no_output_____ | BSD-3-Clause | docs/_downloads/f11c58c36c9b8a5daf09d3f9a792ef84/memory_format_tutorial.ipynb | creduo/PyTorch-tutorials-kr |
Memory Format API-----------------------Here is how to convert tensors between contiguous and channels last memory formats. Classic PyTorch contiguous tensor | x = torch.empty(N, C, H, W)
print(x.stride()) # Ouputs: (3072, 1024, 32, 1) | _____no_output_____ | BSD-3-Clause | docs/_downloads/f11c58c36c9b8a5daf09d3f9a792ef84/memory_format_tutorial.ipynb | creduo/PyTorch-tutorials-kr |
Conversion operator | x = x.contiguous(memory_format=torch.channels_last)
print(x.shape) # Outputs: (10, 3, 32, 32) as dimensions order preserved
print(x.stride()) # Outputs: (3072, 1, 96, 3) | _____no_output_____ | BSD-3-Clause | docs/_downloads/f11c58c36c9b8a5daf09d3f9a792ef84/memory_format_tutorial.ipynb | creduo/PyTorch-tutorials-kr |
Back to contiguous | x = x.contiguous(memory_format=torch.contiguous_format)
print(x.stride()) # Outputs: (3072, 1024, 32, 1) | _____no_output_____ | BSD-3-Clause | docs/_downloads/f11c58c36c9b8a5daf09d3f9a792ef84/memory_format_tutorial.ipynb | creduo/PyTorch-tutorials-kr |
Alternative option | x = x.to(memory_format=torch.channels_last)
print(x.stride()) # Ouputs: (3072, 1, 96, 3) | _____no_output_____ | BSD-3-Clause | docs/_downloads/f11c58c36c9b8a5daf09d3f9a792ef84/memory_format_tutorial.ipynb | creduo/PyTorch-tutorials-kr |
Format checks | print(x.is_contiguous(memory_format=torch.channels_last)) # Ouputs: True | _____no_output_____ | BSD-3-Clause | docs/_downloads/f11c58c36c9b8a5daf09d3f9a792ef84/memory_format_tutorial.ipynb | creduo/PyTorch-tutorials-kr |
Create as Channels Last | x = torch.empty(N, C, H, W, memory_format=torch.channels_last)
print(x.stride()) # Ouputs: (3072, 1, 96, 3) | _____no_output_____ | BSD-3-Clause | docs/_downloads/f11c58c36c9b8a5daf09d3f9a792ef84/memory_format_tutorial.ipynb | creduo/PyTorch-tutorials-kr |
``clone`` preserves memory format | y = x.clone()
print(y.stride()) # Ouputs: (3072, 1, 96, 3) | _____no_output_____ | BSD-3-Clause | docs/_downloads/f11c58c36c9b8a5daf09d3f9a792ef84/memory_format_tutorial.ipynb | creduo/PyTorch-tutorials-kr |
``to``, ``cuda``, ``float`` ... preserves memory format | if torch.cuda.is_available():
y = x.cuda()
print(y.stride()) # Ouputs: (3072, 1, 96, 3) | _____no_output_____ | BSD-3-Clause | docs/_downloads/f11c58c36c9b8a5daf09d3f9a792ef84/memory_format_tutorial.ipynb | creduo/PyTorch-tutorials-kr |
``empty_like``, ``*_like`` operators preserves memory format | y = torch.empty_like(x)
print(y.stride()) # Ouputs: (3072, 1, 96, 3) | _____no_output_____ | BSD-3-Clause | docs/_downloads/f11c58c36c9b8a5daf09d3f9a792ef84/memory_format_tutorial.ipynb | creduo/PyTorch-tutorials-kr |
Pointwise operators preserves memory format | z = x + y
print(z.stride()) # Ouputs: (3072, 1, 96, 3) | _____no_output_____ | BSD-3-Clause | docs/_downloads/f11c58c36c9b8a5daf09d3f9a792ef84/memory_format_tutorial.ipynb | creduo/PyTorch-tutorials-kr |
Conv, Batchnorm modules support Channels Last(only works for CudNN >= 7.6) | if torch.backends.cudnn.version() >= 7603:
input = torch.randint(1, 10, (2, 8, 4, 4), dtype=torch.float32, device="cuda", requires_grad=True)
model = torch.nn.Conv2d(8, 4, 3).cuda().float()
input = input.contiguous(memory_format=torch.channels_last)
model = model.to(memory_format=torch.channels_last) #... | _____no_output_____ | BSD-3-Clause | docs/_downloads/f11c58c36c9b8a5daf09d3f9a792ef84/memory_format_tutorial.ipynb | creduo/PyTorch-tutorials-kr |
Performance Gains-------------------------------------------------------------------------------------------The most significant performance gains are observed on NVidia's hardware with Tensor Cores support. We were able to archive over 22% perf gains while running 'AMP (Automated Mixed Precision) training scripts sup... | # opt_level = O2
# keep_batchnorm_fp32 = None <class 'NoneType'>
# loss_scale = None <class 'NoneType'>
# CUDNN VERSION: 7603
# => creating model 'resnet50'
# Selected optimization level O2: FP16 training with FP32 batchnorm and FP32 master weights.
# Defaults for this optimization level are:
# enabled ... | _____no_output_____ | BSD-3-Clause | docs/_downloads/f11c58c36c9b8a5daf09d3f9a792ef84/memory_format_tutorial.ipynb | creduo/PyTorch-tutorials-kr |
Passing ``--channels-last true`` allows running a model in Channels Last format with observed 22% perf gain.``python main_amp.py -a resnet50 --b 200 --workers 16 --opt-level O2 --channels-last true ./data`` | # opt_level = O2
# keep_batchnorm_fp32 = None <class 'NoneType'>
# loss_scale = None <class 'NoneType'>
#
# CUDNN VERSION: 7603
#
# => creating model 'resnet50'
# Selected optimization level O2: FP16 training with FP32 batchnorm and FP32 master weights.
#
# Defaults for this optimization level are:
# enabled ... | _____no_output_____ | BSD-3-Clause | docs/_downloads/f11c58c36c9b8a5daf09d3f9a792ef84/memory_format_tutorial.ipynb | creduo/PyTorch-tutorials-kr |
The following list of models has the full support of Channels Last and showing 8%-35% perf gains on Volta devices:``alexnet``, ``mnasnet0_5``, ``mnasnet0_75``, ``mnasnet1_0``, ``mnasnet1_3``, ``mobilenet_v2``, ``resnet101``, ``resnet152``, ``resnet18``, ``resnet34``, ``resnet50``, ``resnext50_32x4d``, ``shufflenet_v2_x... | # Need to be done once, after model initialization (or load)
model = model.to(memory_format=torch.channels_last) # Replace with your model
# Need to be done for every input
input = input.to(memory_format=torch.channels_last) # Replace with your input
output = model(input) | _____no_output_____ | BSD-3-Clause | docs/_downloads/f11c58c36c9b8a5daf09d3f9a792ef84/memory_format_tutorial.ipynb | creduo/PyTorch-tutorials-kr |
However, not all operators fully converted to support Channels Last (usually returning contiguous output instead). That means you need to verify the list of used operators against supported operators list https://github.com/pytorch/pytorch/wiki/Operators-with-Channels-Last-support, or introduce memory format checks int... | def contains_cl(args):
for t in args:
if isinstance(t, torch.Tensor):
if t.is_contiguous(memory_format=torch.channels_last) and not t.is_contiguous():
return True
elif isinstance(t, list) or isinstance(t, tuple):
if contains_cl(list(t)):
return... | _____no_output_____ | BSD-3-Clause | docs/_downloads/f11c58c36c9b8a5daf09d3f9a792ef84/memory_format_tutorial.ipynb | creduo/PyTorch-tutorials-kr |
Live in Lab**Neuro Video Series****By Neuromatch Academy****Content creators**: Anne Churchland, Chaoqun Yin, Alex Kostiuk, Lukas Oesch,Michael Ryan, Ashley Chen, Joao Couto**Content reviewers**: Tara van Viegen, Oluwatomisin Faniyan, Pooya Pakarian, Sirisha Sripada**Video editors, captioners, and translators**: Jere... | # @markdown
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id... | _____no_output_____ | CC-BY-4.0 | tutorials/W0D0_NeuroVideoSeries/student/W0D0_Tutorial4.ipynb | janeite/course-content |
**Chapter 2 – End-to-end Machine Learning project***Welcome to Machine Learning Housing Corp.! Your task is to predict median house values in Californian districts, given a number of features from these districts.**This notebook contains all the sample code and solutions to the exercices in chapter 2.* Setup First, le... | # Python ≥3.5 is required
import sys
assert sys.version_info >= (3, 5)
# Scikit-Learn ≥0.20 is required
import sklearn
assert sklearn.__version__ >= "0.20"
# Common imports
import numpy as np
import os
# To plot pretty figures
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rc('axes',... | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
Get the data | import os
import tarfile
import urllib
DOWNLOAD_ROOT = "https://raw.githubusercontent.com/ageron/handson-ml2/master/"
HOUSING_PATH = os.path.join("datasets", "housing")
HOUSING_URL = DOWNLOAD_ROOT + "datasets/housing/housing.tgz"
def fetch_housing_data(housing_url=HOUSING_URL, housing_path=HOUSING_PATH):
if not o... | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
The implementation of `test_set_check()` above works fine in both Python 2 and Python 3. In earlier releases, the following implementation was proposed, which supported any hash function, but was much slower and did not support Python 2: | import hashlib
def test_set_check(identifier, test_ratio, hash=hashlib.md5):
return hash(np.int64(identifier)).digest()[-1] < 256 * test_ratio | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
If you want an implementation that supports any hash function and is compatible with both Python 2 and Python 3, here is one: | def test_set_check(identifier, test_ratio, hash=hashlib.md5):
return bytearray(hash(np.int64(identifier)).digest())[-1] < 256 * test_ratio
housing_with_id = housing.reset_index() # adds an `index` column
train_set, test_set = split_train_test_by_id(housing_with_id, 0.2, "index")
housing_with_id["id"] = housing["l... | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
Discover and visualize the data to gain insights | housing = strat_train_set.copy()
housing.plot(kind="scatter", x="longitude", y="latitude")
save_fig("bad_visualization_plot")
housing.plot(kind="scatter", x="longitude", y="latitude", alpha=0.1)
save_fig("better_visualization_plot") | Saving figure better_visualization_plot
| Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
The argument `sharex=False` fixes a display bug (the x-axis values and legend were not displayed). This is a temporary fix (see: https://github.com/pandas-dev/pandas/issues/10611 ). Thanks to Wilmer Arellano for pointing it out. | housing.plot(kind="scatter", x="longitude", y="latitude", alpha=0.4,
s=housing["population"]/100, label="population", figsize=(10,7),
c="median_house_value", cmap=plt.get_cmap("jet"), colorbar=True,
sharex=False)
plt.legend()
save_fig("housing_prices_scatterplot")
import matplotlib.image as mpimg
california... | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
Prepare the data for Machine Learning algorithms | housing = strat_train_set.drop("median_house_value", axis=1) # drop labels for training set
housing_labels = strat_train_set["median_house_value"].copy()
sample_incomplete_rows = housing[housing.isnull().any(axis=1)].head()
sample_incomplete_rows
sample_incomplete_rows.dropna(subset=["total_bedrooms"]) # option 1
sa... | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
Remove the text attribute because median can only be calculated on numerical attributes: | housing_num = housing.drop("ocean_proximity", axis=1)
# alternatively: housing_num = housing.select_dtypes(include=[np.number])
imputer.fit(housing_num)
imputer.statistics_ | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
Check that this is the same as manually computing the median of each attribute: | housing_num.median().values | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
Transform the training set: | X = imputer.transform(housing_num)
housing_tr = pd.DataFrame(X, columns=housing_num.columns,
index=housing.index)
housing_tr.loc[sample_incomplete_rows.index.values]
imputer.strategy
housing_tr = pd.DataFrame(X, columns=housing_num.columns,
index=housing_num.index)
ho... | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
Now let's preprocess the categorical input feature, `ocean_proximity`: | housing_cat = housing[["ocean_proximity"]]
housing_cat.head(10)
from sklearn.preprocessing import OrdinalEncoder
ordinal_encoder = OrdinalEncoder()
housing_cat_encoded = ordinal_encoder.fit_transform(housing_cat)
housing_cat_encoded[:10]
ordinal_encoder.categories_
from sklearn.preprocessing import OneHotEncoder
cat_... | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
By default, the `OneHotEncoder` class returns a sparse array, but we can convert it to a dense array if needed by calling the `toarray()` method: | housing_cat_1hot.toarray() | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
Alternatively, you can set `sparse=False` when creating the `OneHotEncoder`: | cat_encoder = OneHotEncoder(sparse=False)
housing_cat_1hot = cat_encoder.fit_transform(housing_cat)
housing_cat_1hot
cat_encoder.categories_ | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
Let's create a custom transformer to add extra attributes: | from sklearn.base import BaseEstimator, TransformerMixin
# column index
rooms_ix, bedrooms_ix, population_ix, households_ix = 3, 4, 5, 6
class CombinedAttributesAdder(BaseEstimator, TransformerMixin):
def __init__(self, add_bedrooms_per_room = True): # no *args or **kargs
self.add_bedrooms_per_room = add_... | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
Now let's build a pipeline for preprocessing the numerical attributes: | from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
num_pipeline = Pipeline([
('imputer', SimpleImputer(strategy="median")),
('attribs_adder', CombinedAttributesAdder()),
('std_scaler', StandardScaler()),
])
housing_num_tr = num_pipeline.fit_transform(hou... | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
For reference, here is the old solution based on a `DataFrameSelector` transformer (to just select a subset of the Pandas `DataFrame` columns), and a `FeatureUnion`: | from sklearn.base import BaseEstimator, TransformerMixin
# Create a class to select numerical or categorical columns
class OldDataFrameSelector(BaseEstimator, TransformerMixin):
def __init__(self, attribute_names):
self.attribute_names = attribute_names
def fit(self, X, y=None):
return self
... | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
Now let's join all these components into a big pipeline that will preprocess both the numerical and the categorical features: | num_attribs = list(housing_num)
cat_attribs = ["ocean_proximity"]
old_num_pipeline = Pipeline([
('selector', OldDataFrameSelector(num_attribs)),
('imputer', SimpleImputer(strategy="median")),
('attribs_adder', CombinedAttributesAdder()),
('std_scaler', StandardScaler()),
])
old_cat... | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
The result is the same as with the `ColumnTransformer`: | np.allclose(housing_prepared, old_housing_prepared) | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
Select and train a model | from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(housing_prepared, housing_labels)
# let's try the full preprocessing pipeline on a few training instances
some_data = housing.iloc[:5]
some_labels = housing_labels.iloc[:5]
some_data_prepared = full_pipeline.transform(some_data)... | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
Compare against the actual values: | print("Labels:", list(some_labels))
some_data_prepared
from sklearn.metrics import mean_squared_error
housing_predictions = lin_reg.predict(housing_prepared)
lin_mse = mean_squared_error(housing_labels, housing_predictions)
lin_rmse = np.sqrt(lin_mse)
lin_rmse
from sklearn.metrics import mean_absolute_error
lin_mae =... | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
Fine-tune your model | from sklearn.model_selection import cross_val_score
scores = cross_val_score(tree_reg, housing_prepared, housing_labels,
scoring="neg_mean_squared_error", cv=10)
tree_rmse_scores = np.sqrt(-scores)
def display_scores(scores):
print("Scores:", scores)
print("Mean:", scores.mean())
p... | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
**Note**: we specify `n_estimators=100` to be future-proof since the default value is going to change to 100 in Scikit-Learn 0.22 (for simplicity, this is not shown in the book). | from sklearn.ensemble import RandomForestRegressor
forest_reg = RandomForestRegressor(n_estimators=100, random_state=42)
forest_reg.fit(housing_prepared, housing_labels)
housing_predictions = forest_reg.predict(housing_prepared)
forest_mse = mean_squared_error(housing_labels, housing_predictions)
forest_rmse = np.sqrt... | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
The best hyperparameter combination found: | grid_search.best_params_
grid_search.best_estimator_ | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
Let's look at the score of each hyperparameter combination tested during the grid search: | cvres = grid_search.cv_results_
for mean_score, params in zip(cvres["mean_test_score"], cvres["params"]):
print(np.sqrt(-mean_score), params)
pd.DataFrame(grid_search.cv_results_)
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint
param_distribs = {
'n_estimators': randi... | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
We can compute a 95% confidence interval for the test RMSE: | from scipy import stats
confidence = 0.95
squared_errors = (final_predictions - y_test) ** 2
np.sqrt(stats.t.interval(confidence, len(squared_errors) - 1,
loc=squared_errors.mean(),
scale=stats.sem(squared_errors))) | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
We could compute the interval manually like this: | m = len(squared_errors)
mean = squared_errors.mean()
tscore = stats.t.ppf((1 + confidence) / 2, df=m - 1)
tmargin = tscore * squared_errors.std(ddof=1) / np.sqrt(m)
np.sqrt(mean - tmargin), np.sqrt(mean + tmargin) | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
Alternatively, we could use a z-scores rather than t-scores: | zscore = stats.norm.ppf((1 + confidence) / 2)
zmargin = zscore * squared_errors.std(ddof=1) / np.sqrt(m)
np.sqrt(mean - zmargin), np.sqrt(mean + zmargin) | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
Extra material A full pipeline with both preparation and prediction | full_pipeline_with_predictor = Pipeline([
("preparation", full_pipeline),
("linear", LinearRegression())
])
full_pipeline_with_predictor.fit(housing, housing_labels)
full_pipeline_with_predictor.predict(some_data) | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
Model persistence using joblib | my_model = full_pipeline_with_predictor
import joblib
joblib.dump(my_model, "my_model.pkl") # DIFF
#...
my_model_loaded = joblib.load("my_model.pkl") # DIFF | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
Example SciPy distributions for `RandomizedSearchCV` | from scipy.stats import geom, expon
geom_distrib=geom(0.5).rvs(10000, random_state=42)
expon_distrib=expon(scale=1).rvs(10000, random_state=42)
plt.hist(geom_distrib, bins=50)
plt.show()
plt.hist(expon_distrib, bins=50)
plt.show() | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
Exercise solutions 1. Question: Try a Support Vector Machine regressor (`sklearn.svm.SVR`), with various hyperparameters such as `kernel="linear"` (with various values for the `C` hyperparameter) or `kernel="rbf"` (with various values for the `C` and `gamma` hyperparameters). Don't worry about what these hyperparamet... | from sklearn.model_selection import GridSearchCV
param_grid = [
{'kernel': ['linear'], 'C': [10., 30., 100., 300., 1000., 3000., 10000., 30000.0]},
{'kernel': ['rbf'], 'C': [1.0, 3.0, 10., 30., 100., 300., 1000.0],
'gamma': [0.01, 0.03, 0.1, 0.3, 1.0, 3.0]},
]
svm_reg = SVR()
grid_search ... | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
The best model achieves the following score (evaluated using 5-fold cross validation): | negative_mse = grid_search.best_score_
rmse = np.sqrt(-negative_mse)
rmse | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
That's much worse than the `RandomForestRegressor`. Let's check the best hyperparameters found: | grid_search.best_params_ | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
The linear kernel seems better than the RBF kernel. Notice that the value of `C` is the maximum tested value. When this happens you definitely want to launch the grid search again with higher values for `C` (removing the smallest values), because it is likely that higher values of `C` will be better. 2. Question: Try ... | from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import expon, reciprocal
# see https://docs.scipy.org/doc/scipy/reference/stats.html
# for `expon()` and `reciprocal()` documentation and more probability distribution functions.
# Note: gamma is ignored when kernel is "linear"
param_distribs = {... | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
The best model achieves the following score (evaluated using 5-fold cross validation): | negative_mse = rnd_search.best_score_
rmse = np.sqrt(-negative_mse)
rmse | _____no_output_____ | Apache-2.0 | 02_end_to_end_machine_learning_project.ipynb | Ruqyai/handson-ml2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.