markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
We'll be working with data from the bike rental setup: | weather = pd.read_table('daily_weather.tsv', parse_dates=['date'])
stations = pd.read_table('stations.tsv')
usage = pd.read_table('usage_2012.tsv', parse_dates=['time_start', 'time_end']) | ipynb/pandas bikes.ipynb | joelgrus/codefellows-data-science-week | unlicense |
Let's inspect it | usage.describe() | ipynb/pandas bikes.ipynb | joelgrus/codefellows-data-science-week | unlicense |
That must be the only numeric value, let's try again: | usage
weather.describe()
weather | ipynb/pandas bikes.ipynb | joelgrus/codefellows-data-science-week | unlicense |
Wow, those season_desc values look wrong! We'll come back to that in a minute.
Now let's look at some of the columns | weather.columns
weather['is_holiday'].value_counts()
weather['temp'].describe() | ipynb/pandas bikes.ipynb | joelgrus/codefellows-data-science-week | unlicense |
Sanity checking the weather data | weather.groupby(['season_code', 'season_desc'])['date'].agg([min, max]) | ipynb/pandas bikes.ipynb | joelgrus/codefellows-data-science-week | unlicense |
The season codes look OK (1 = Winter, 2 = Spring ...), but the season descriptions look wrong. Let's fix them: | weather.season_desc = weather.season_desc.map({'Spring' : 'Winter', 'Winter' : 'Fall', 'Fall' : 'Summer', 'Summer' : 'Spring' })
weather.season_desc | ipynb/pandas bikes.ipynb | joelgrus/codefellows-data-science-week | unlicense |
That looks right, but we would rather the date be our index: | weather.index = pd.DatetimeIndex(weather['date']) | ipynb/pandas bikes.ipynb | joelgrus/codefellows-data-science-week | unlicense |
Let's start asking some questions
How many unique bikes are there? | usage.columns
usage['bike_id'].describe()
usage['bike_id'].nunique() | ipynb/pandas bikes.ipynb | joelgrus/codefellows-data-science-week | unlicense |
How many unique stations are there? | stations.shape
len(stations) | ipynb/pandas bikes.ipynb | joelgrus/codefellows-data-science-week | unlicense |
How many of those actually appear in our usage data? | usage['station_start'].nunique()
usage['station_end'].nunique()
usage['station_start'].unique() | ipynb/pandas bikes.ipynb | joelgrus/codefellows-data-science-week | unlicense |
Let's look for correlations in the weather: | weather[['temp', 'subjective_temp', 'humidity', 'windspeed', 'total_riders']].corr() | ipynb/pandas bikes.ipynb | joelgrus/codefellows-data-science-week | unlicense |
When temperature is higher, there are more riders, and when windspeed is higher there are fewer riders. Maybe these trends are different at different times of the year? | weather[weather.season_desc=='Winter'][['temp', 'subjective_temp', 'humidity', 'windspeed', 'total_riders']].corr()
weather[weather.season_desc=='Summer'][['temp', 'subjective_temp', 'humidity', 'windspeed', 'total_riders']].corr() | ipynb/pandas bikes.ipynb | joelgrus/codefellows-data-science-week | unlicense |
So in winter higher temperatures mean more riders, but in summer higher temperatures mean fewer riders. This makes a good bit of sense.
Station Success
We'll measure a station's success by its average number of daily rentals. We can take a couple of different approaches.
The first is to use groupby. We'll start by... | usage['date'] = usage.time_start.dt.date
usage.groupby('date')
station_counts = usage.groupby(['station_start']).size() / 366
station_counts.sort()
station_counts | ipynb/pandas bikes.ipynb | joelgrus/codefellows-data-science-week | unlicense |
We can also use a pivot table: | pivot = pd.pivot_table(usage, index='date', columns='station_start', values='bike_id', aggfunc=len, fill_value=0)
pivot
avg_daily_trips = pivot.mean()
avg_daily_trips.sort()
avg_daily_trips.index.name = 'station'
avg_daily_trips | ipynb/pandas bikes.ipynb | joelgrus/codefellows-data-science-week | unlicense |
There are invariably other ways to do this
Joins
We'll want to look at the avg daily trips by geographic location, which is in the stations data frame. Let's pull it out into its own: | station_geos = stations[['lat','long']]
station_geos.index = stations['station']
station_geos | ipynb/pandas bikes.ipynb | joelgrus/codefellows-data-science-week | unlicense |
And then we need to make trips into a data frame | trips = DataFrame({ 'avg_daily_trips' : avg_daily_trips})
trips
trips_by_geo = station_geos.join(trips, how='inner')
trips_by_geo | ipynb/pandas bikes.ipynb | joelgrus/codefellows-data-science-week | unlicense |
Getting Our Data Ready
Before we merge, we'd like to aggregate the usage data to the daily level: | daily_usage = usage.groupby(['date', 'station_start', 'cust_type'], as_index=False)['duration_mins'].agg(['mean', len])
daily_usage.columns = ['avg_trip_duration', 'num_trips']
daily_usage
daily_usage = daily_usage.reset_index()
daily_usage.columns
daily_usage.index
stations.columns
weather.columns
weather_rental... | ipynb/pandas bikes.ipynb | joelgrus/codefellows-data-science-week | unlicense |
Load data | data = np.loadtxt('data/features.txt', delimiter=',')
target = np.loadtxt('data/target.txt', delimiter=',') | deliver/Report-ToyProblem.ipynb | tgquintela/temporal_tasks | mit |
Function definitions | def weights_histogram(model):
title = r'Histogram of the distribution of weight values '
title += r'($\eta=0.0001$, $\lambda=1.$, $b_s={}$)'.format(model.batch_size)
fig = plt.figure(figsize=(10, 5))
_ = plt.hist(model.w, bins=20)
_ = plt.title(title)
_ = plt.xlabel('weights')
_ = plt.ylabel... | deliver/Report-ToyProblem.ipynb | tgquintela/temporal_tasks | mit |
Study with batch_size=1 | model = SVM(n_epochs=1000, batch_size=1, learning_rate=0.0001)
model = model.fit(data[:-1000], target[:-1000], data[-1000:], target[-1000:])
weights_histogram(model)
losses_accross_training(model)
acc_accross_training(model)
model.report_results() | deliver/Report-ToyProblem.ipynb | tgquintela/temporal_tasks | mit |
Study with batch_size=10 | model = SVM(n_epochs=1000, batch_size=10, learning_rate=0.0001)
model = model.fit(data[:-1000], target[:-1000], data[-1000:], target[-1000:])
weights_histogram(model)
losses_accross_training(model)
acc_accross_training(model)
model.report_results() | deliver/Report-ToyProblem.ipynb | tgquintela/temporal_tasks | mit |
Study with batch_size=100 | model = SVM(n_epochs=1000, batch_size=100, learning_rate=0.0001)
model = model.fit(data[:-1000], target[:-1000], data[-1000:], target[-1000:])
weights_histogram(model)
losses_accross_training(model)
acc_accross_training(model)
model.report_results() | deliver/Report-ToyProblem.ipynb | tgquintela/temporal_tasks | mit |
Seminararbeit - autonome Verkehrsleitsysteme
von Kay Kleinvogel und Lisa-Marie Nehring
Übersicht:
Die Hauptaufgabe dieser Arbeit ist das Forschen an effizienteren Ampelsystemen. Dies ist von Nöten, da jedes Jahr immer mehr Fahrzeuge auf den Straßen unterwegs sind. Um die Kapazitäten zu schaffen, muss entweder die Fläch... | v1 = int(input('v1: '))
v2 = int(input('v2: '))
h1 = int(input('h1: '))
h2 = int(input('h2: '))
v = v1+v2
h = h1+h2
print ('V', v)
print ('H', h) | Journal/Seminararbeit.ipynb | Ironlors/SmartIntersection-Ger | apache-2.0 |
Nun müssen wir diese Werte miteinander vergleichen. Dafür bietet es sich an die totale Anzahl an Fahrzeugen zu vergleichen. Dazu nutzen wir eine einfache Abfrage welche nach jeden Fahrzeug überprüft welche Spur mehr Fahrzeuge beeinhaltet. In diesen Beispiel haben wir zwei Möglichkeiten. Es können entweder die horizonta... | print("h v")
while(v > 0 or h > 0):
if(h>v):
h = h-1
else :
v = v-1
print(h,v) | Journal/Seminararbeit.ipynb | Ironlors/SmartIntersection-Ger | apache-2.0 |
Der Aufbau des Modells
Für den entsprechenden Aufbau des Modells nutzen wir eine Kreuzung von 2 vierspurigen Straßen, welche sich schneiden.(siehe Abbildung 1). Die rechte Spur ist jeweils für die Rechtsabbieger vorgesehen, und die linke für die Linksabbieger beziehungsweise die Fahrer, welche geradeaus fahren möchten.... | # Beispiel für "Vergleich der Spuren"
#Kompatible Kombinationen: A(G1,G3) B(G1,L1) C(L1,L3) D(G3,L3) E(L2,L4) F(G2,G4) G(G2,L2) H(G4,L3)
#<X>#S = Status der Spur (0 = rot ; 1 = grün)
G1 = int(input('G1: '))
G2 = int(input('G2: '))
G3 = int(input('G3: '))
G4 = int(input('G4: '))
L1 = int(input('L1: '))
L2 = int(input('... | Journal/Seminararbeit.ipynb | Ironlors/SmartIntersection-Ger | apache-2.0 |
Nun definieren wir unsere Reset Funktion. Diese wird benötigt, da die Ampeln vor jeden Umschalten auf rot gesetzt werden. | def reset():
G1S = 0
G2S = 0
G3S = 0
G4S = 0
L1S = 0
L2S = 0
L3S = 0
L4S = 0 | Journal/Seminararbeit.ipynb | Ironlors/SmartIntersection-Ger | apache-2.0 |
Nun addieren wir die jeweiligen numerischen Werte der Spuren, in den Kombinationen welche sich nicht beeinträchtigen. Daher finden wir heraus, welche beiden Spuren zeitgleich grün erhalten müssen, wenn wir die Anzahl an Fahrzeugen maximieren möchten. Danach erstellen wir eine Liste mit den einzelnen Werten, aus welcher... | A = G1+G2
B = G1+L1
C = L1+L3
D = G3+L3
E = L2+L4
F = G2+G4
G = G2+L2
H = G4+L3
l = [A,B,C,D,E,F,G]
m = max(l) | Journal/Seminararbeit.ipynb | Ironlors/SmartIntersection-Ger | apache-2.0 |
Nun definieren wir unsere check Funktion, welche uns erlaubt entsprechend der Werte die Ampeln umzuschalten.
Dafür nutzen wir l.index(m) um herauszufinden an welcher Stelle der Liste der Maximalwert steht. Diese Position gleichen wir nun mit der Kombination an Spuren ab, und setzen den Status der entsprechenden Spuren ... | # A(G1,G3) B(G1,L1) C(L1,L3) D(G3,L3) E(L2,L4) F(G2,G4) G(G2,L2) H(G4,L3)
def check():
reset()
if(l.index(m)==1):
print ('G1+G3')
G1S = 1
G3S = 1
elif(l.index(m)==2):
print ('G1+L1')
G1S = 1
G3S = 1
elif(l.index(m)==3):
print ('L1+L2')
L1... | Journal/Seminararbeit.ipynb | Ironlors/SmartIntersection-Ger | apache-2.0 |
Hier nutzen wir jetzt die oben beschriebene Funktion check() und geben die Menge an Fahrzeugen aus, welche mit dieser Möglichkeit der Schaltung bedient werden. | check()
print (m) | Journal/Seminararbeit.ipynb | Ironlors/SmartIntersection-Ger | apache-2.0 |
TO-DO
Abbruchbedingung
Für die Abbruchbedingung muss geschaut werden, ob die Summe der aktiven Spuren = 0 ist bevor die Grünphase vorbei ist, da sobald sich keine Fahrzeuge mehr auf der Spur befinden, auch kein Bedarf mehr für eine grüne Ampel besteht.
Grünphasentimer
Bei dem Timer für die Grünphase sollte variables ge... | data = pd.read_csv('/Users/kay/SmartIntersection-Ger/Data/DrivingStraight/lap.txt',sep=' ')
data.columns=['lap','time']
data.set_index('lap')
np_data= data.values
print(np_data)
plot = plt.plot(np_data[:,0],np_data[:,1])
plt.xlabel('Anzahl an Durchgängen')
plt.ylabel('s / runde')
plt.title('Geschwindigkeit des Fahrze... | Journal/Seminararbeit.ipynb | Ironlors/SmartIntersection-Ger | apache-2.0 |
Задание 1
Как вы уже знаете из лекций, бустинг - это метод построения композиций базовых алгоритмов с помощью последовательного добавления к текущей композиции нового алгоритма с некоторым коэффициентом.
Градиентный бустинг обучает каждый новый алгоритм так, чтобы он приближал антиградиент ошибки по ответам композиции... | def L_derivative(y_train, z):
return (y_train - z) | 2 Supervised learning/Homework/7 gradient boosting/grad_boosting.ipynb | maxis42/ML-DA-Coursera-Yandex-MIPT | mit |
Задание 2
Заведите массив для объектов DecisionTreeRegressor (будем их использовать в качестве базовых алгоритмов) и для вещественных чисел (это будут коэффициенты перед базовыми алгоритмами).
В цикле обучите последовательно 50 решающих деревьев с параметрами max_depth=5 и random_state=42 (остальные параметры - по умо... | def gbm_predict(X):
return [sum([coeff * algo.predict([x])[0] for algo, coeff in zip(base_algorithms_list, coefficients_list)]) for x in X]
base_algorithms_list = []
coefficients_list = []
z = np.zeros( (y_train.shape) )
for _ in range(50):
coefficients_list.append(0.9)
dt_regressor = DecisionTreeRegress... | 2 Supervised learning/Homework/7 gradient boosting/grad_boosting.ipynb | maxis42/ML-DA-Coursera-Yandex-MIPT | mit |
Задание 3
Вас может также беспокоить, что двигаясь с постоянным шагом, вблизи минимума ошибки ответы на обучающей выборке меняются слишком резко, перескакивая через минимум.
Попробуйте уменьшать вес перед каждым алгоритмом с каждой следующей итерацией по формуле 0.9 / (1.0 + i), где i - номер итерации (от 0 до 49). Ис... | base_algorithms_list = []
coefficients_list = []
z = np.zeros( (y_train.shape) )
for i in range(50):
coeff = 0.9 / (1. + i)
coefficients_list.append(coeff)
dt_regressor = DecisionTreeRegressor(max_depth=5, random_state=42)
dt_regressor.fit(X_train, L_derivative(y_train, z))
base_algorithms_list.ap... | 2 Supervised learning/Homework/7 gradient boosting/grad_boosting.ipynb | maxis42/ML-DA-Coursera-Yandex-MIPT | mit |
Задание 4
Реализованный вами метод - градиентный бустинг над деревьями - очень популярен в машинном обучении. Он представлен как в самой библиотеке sklearn, так и в сторонней библиотеке XGBoost, которая имеет свой питоновский интерфейс. На практике XGBoost работает заметно лучше GradientBoostingRegressor из sklearn, но... | answer = str(2) + ' ' + str(3)
with open('answer4.txt', 'w') as fout:
fout.write(answer) | 2 Supervised learning/Homework/7 gradient boosting/grad_boosting.ipynb | maxis42/ML-DA-Coursera-Yandex-MIPT | mit |
Задание 5
Сравните получаемое с помощью градиентного бустинга качество с качеством работы линейной регрессии.
Для этого обучите LinearRegression из sklearn.linear_model (с параметрами по умолчанию) на обучающей выборке и оцените для прогнозов полученного алгоритма на тестовой выборке RMSE. Полученное качество - ответ ... | lr_regressor = LinearRegression()
lr_regressor.fit(X_train, y_train)
alg_predict = lr_regressor.predict(X_test)
alg_rmse = np.sqrt(mean_squared_error(y_test, alg_predict))
print(alg_rmse)
with open('answer5.txt', 'w') as fout:
fout.write(str(alg_rmse)) | 2 Supervised learning/Homework/7 gradient boosting/grad_boosting.ipynb | maxis42/ML-DA-Coursera-Yandex-MIPT | mit |
从 Prometheus 服务器加载指标
<table class="tfo-notebook-buttons" align="left">
<td> <a target="_blank" href="https://tensorflow.google.cn/io/tutorials/prometheus"><img src="https://tensorflow.google.cn/images/tf_logo_32px.png">在 TensorFlow.org 上查看</a> </td>
<td><a target="_blank" href="https://colab.research.google.c... | import os
try:
%tensorflow_version 2.x
except Exception:
pass
!pip install tensorflow-io
from datetime import datetime
import tensorflow as tf
import tensorflow_io as tfio | site/zh-cn/io/tutorials/prometheus.ipynb | tensorflow/docs-l10n | apache-2.0 |
安装并设置 CoreDNS 和 Prometheus
出于演示目的,CoreDNS 服务器在本地开放了 9053 端口用于接收 DNS 查询,并开放了 9153 端口(默认)用于公开抓取指标。以下为 CoreDNS 的基本 Corefile 配置,可供下载:
.:9053 {
prometheus
whoami
}
有关安装的更多详细信息,请参阅 CoreDNS 文档。 | !curl -s -OL https://github.com/coredns/coredns/releases/download/v1.6.7/coredns_1.6.7_linux_amd64.tgz
!tar -xzf coredns_1.6.7_linux_amd64.tgz
!curl -s -OL https://raw.githubusercontent.com/tensorflow/io/master/docs/tutorials/prometheus/Corefile
!cat Corefile
# Run `./coredns` as a background process.
# IPython does... | site/zh-cn/io/tutorials/prometheus.ipynb | tensorflow/docs-l10n | apache-2.0 |
下一步是设置 Prometheus 服务器,并使用 Prometheus 抓取在上述 9153 端口上公开的 CoreDNS 指标。用于配置的 prometheus.yml 文件同样可供下载: | !curl -s -OL https://github.com/prometheus/prometheus/releases/download/v2.15.2/prometheus-2.15.2.linux-amd64.tar.gz
!tar -xzf prometheus-2.15.2.linux-amd64.tar.gz --strip-components=1
!curl -s -OL https://raw.githubusercontent.com/tensorflow/io/master/docs/tutorials/prometheus/prometheus.yml
!cat prometheus.yml
# R... | site/zh-cn/io/tutorials/prometheus.ipynb | tensorflow/docs-l10n | apache-2.0 |
为了展示一些活动,可以使用 dig 命令针对已设置的 CoreDNS 服务器生成一些 DNS 查询: | !sudo apt-get install -y -qq dnsutils
!dig @127.0.0.1 -p 9053 demo1.example.org
!dig @127.0.0.1 -p 9053 demo2.example.org | site/zh-cn/io/tutorials/prometheus.ipynb | tensorflow/docs-l10n | apache-2.0 |
现在设置的是 CoreDNS 服务器,Prometheus 服务器将抓取该 CoreDNS 服务器的指标并准备用于 TensorFlow。
为 CoreDNS 指标创建数据集并在 TensorFlow 中使用
可以使用 tfio.experimental.IODataset.from_prometheus 为 CoreDNS 指标创建可在 PostgreSQL 服务器上访问的数据集。至少需要两个参数。需要将 query 传递至 Prometheus 服务器以选择指标,length 为要加载到数据集的时间段。
您可以从 "coredns_dns_request_count_total" 和 "5"(秒)开始来创建以下数据集。由于在本教... | dataset = tfio.experimental.IODataset.from_prometheus(
"coredns_dns_request_count_total", 5, endpoint="http://localhost:9090")
print("Dataset Spec:\n{}\n".format(dataset.element_spec))
print("CoreDNS Time Series:")
for (time, value) in dataset:
# time is milli second, convert to data time:
time = datetime.... | site/zh-cn/io/tutorials/prometheus.ipynb | tensorflow/docs-l10n | apache-2.0 |
进一步研究数据集的规范:
```
(
TensorSpec(shape=(), dtype=tf.int64, name=None),
{
'coredns': {
'localhost:9153': {
'coredns_dns_request_count_total': TensorSpec(shape=(), dtype=tf.float64, name=None)
}
}
}
)
```
显而易见,数据集由 (time, values) 元组组成,其中 values 字段为 Python 字典,扩展为:
"job_name": {
"instance_n... | dataset = tfio.experimental.IODataset.from_prometheus(
"go_memstats_gc_sys_bytes", 5, endpoint="http://localhost:9090")
print("Time Series CoreDNS/Prometheus Comparision:")
for (time, value) in dataset:
# time is milli second, convert to data time:
time = datetime.fromtimestamp(time // 1000)
print("{}: {}/{}... | site/zh-cn/io/tutorials/prometheus.ipynb | tensorflow/docs-l10n | apache-2.0 |
现在,可以将创建的 Dataset 直接传递至 tf.keras 用于训练或推理了。
使用数据集进行模型训练
在指标数据集创建完成后,可以将数据集直接传递至 tf.keras 用于模型训练或推理。
出于演示目的,本教程将仅使用一种非常简单的 LSTM 模型,该模型以 1 个特征和 2 个步骤作为输入: | n_steps, n_features = 2, 1
simple_lstm_model = tf.keras.models.Sequential([
tf.keras.layers.LSTM(8, input_shape=(n_steps, n_features)),
tf.keras.layers.Dense(1)
])
simple_lstm_model.compile(optimizer='adam', loss='mae')
| site/zh-cn/io/tutorials/prometheus.ipynb | tensorflow/docs-l10n | apache-2.0 |
要使用的数据集为带有 10 个样本的 CoreDNS 的 'go_memstats_sys_bytes' 的值。但是,由于形成了 window=n_steps 和 shift=1 的滑动窗口,因此还需要使用其他样本(对于任意两个连续元素,将第一个元素作为 x,将第二个元素作为 y 用于训练)。总计为 10 + n_steps - 1 + 1 = 12 秒。
数据值还将缩放到 [0, 1]。 | n_samples = 10
dataset = tfio.experimental.IODataset.from_prometheus(
"go_memstats_sys_bytes", n_samples + n_steps - 1 + 1, endpoint="http://localhost:9090")
# take go_memstats_gc_sys_bytes from coredns job
dataset = dataset.map(lambda _, v: v['coredns']['localhost:9153']['go_memstats_sys_bytes'])
# find the ma... | site/zh-cn/io/tutorials/prometheus.ipynb | tensorflow/docs-l10n | apache-2.0 |
1. Decision trees
Question Cross-validate 5 different decision trees, with default parameters. | from sklearn import tree
from sklearn import metrics
# Use: clf = tree.DecisionTreeClassifier()
ypred_dt = [] # will hold the 5 arrays of predictions (1 per tree)
for tree_index in range(5):
# TODO | lab_notebooks/Lab 6 2016-11-04 Tree-based methods.ipynb | chagaz/ma2823_2016 | mit |
Question Compute the mean and standard deviation of the area under the ROC curve of these 5 trees. Plot the ROC curves of these 5 trees. | fpr_dt = [] # will hold the 5 arrays of false positive rates (1 per tree)
tpr_dt = [] # will hold the 5 arrays of true positive rates (1 per tree)
auc_dt = [] # will hold the 5 areas under the ROC curve (1 per tree)
for tree_index in range(5):
# TODO
for tree_index in range(4):
plt.plot(fpr_dt[tree_index],... | lab_notebooks/Lab 6 2016-11-04 Tree-based methods.ipynb | chagaz/ma2823_2016 | mit |
Question What parameters of DecisionTreeClassifier can you play with to define trees differently than with the default parameters? Cross-validate these using a grid search, and plot the optimal decision tree on the previous plot. Did you manage to improve performance? | from sklearn import grid_search
param_grid = # TODO
clf = grid_search.GridSearchCV(tree.DecisionTreeClassifier(), param_grid,
scoring='roc_auc')
ypred_dt_opt = cross_validate(X, y, clf, folds)
fpr_dt_opt, tpr_dt_opt, thresholds = metrics.roc_curve(y, ypred_dt_opt, pos_label=1)
auc_dt_opt... | lab_notebooks/Lab 6 2016-11-04 Tree-based methods.ipynb | chagaz/ma2823_2016 | mit |
Question How does the performance of decision trees compare to the performance of classifiers we have used previously on this data? Does this match your expectations?
2. Bagging trees
We will resort to ensemble methods to try to improve the performance of single decision trees. Let us start with bagging trees: The diff... | from sklearn import ensemble
# By default, the base estimator is a decision tree with default parameters
# TODO: Use clf = ensemble.BaggingClassifier(n_estimators=5)
| lab_notebooks/Lab 6 2016-11-04 Tree-based methods.ipynb | chagaz/ma2823_2016 | mit |
Question Use cross_validate_optimize (as defined in the previous lab) to optimize the number of decision trees to use in the bagging method. How many trees did you find to be an optimal choice? | def cross_validate_optimize(design_matrix, labels, classifier, cv_folds):
""" Perform a cross-validation and returns the predictions.
Parameters:
-----------
design_matrix: (n_samples, n_features) np.array
Design matrix for the experiment.
labels: (n_samples, ) np.array
Vector o... | lab_notebooks/Lab 6 2016-11-04 Tree-based methods.ipynb | chagaz/ma2823_2016 | mit |
Question Plot the ROC curve of the optimized cross-validated bagging tree classifier obtained with cross_validate_optimize, and compare it to the previous ROC curves (non-optimized bagging tree, decision trees).
3. Random forests
We will now use random forests.
Question What is the difference between bagging trees and... | clf = ensemble.RandomForestClassifier(n_estimators=5)
# TODO | lab_notebooks/Lab 6 2016-11-04 Tree-based methods.ipynb | chagaz/ma2823_2016 | mit |
Question Use cross_validate_optimize (as defined in the previous lab) to optimize the number of decision trees to use in the random forest. How many trees do you find to be an optimal choice? How does the optimal random forest compare to the optimal bagging trees? How do the training times of the random forest and the ... | param_grid = {'n_estimators': [5, 15, 25, 50]}
# TODO | lab_notebooks/Lab 6 2016-11-04 Tree-based methods.ipynb | chagaz/ma2823_2016 | mit |
Question How do your tree-based classifiers compare to the linear regression (regularized or not)? Plot ROC curves. | from sklearn import linear_model
param_grid = {'C':[1e-3, 1e-2, 1e-1, 1., 1e2, 1e3]}
clf = grid_search.GridSearchCV(linear_model.LogisticRegression(penalty='l1'),
param_grid, scoring='roc_auc')
ypred_l1 = cross_validate_optimize(X, y, clf, folds)
fpr_l1, tpr_l1, thresholds_l1 = metrics.r... | lab_notebooks/Lab 6 2016-11-04 Tree-based methods.ipynb | chagaz/ma2823_2016 | mit |
Dropping PassengerId, Name and Ticket because they are unique.
Dropping Cabin because of too many null values. | titanic_data = titanic.drop(['PassengerId','Name','Ticket'],1)
titanic_data.head() | titanic forked.ipynb | decisionstats/pythonfordatascience | apache-2.0 |
Now need to take care of the missing data for Age variable. Need to approximate- one way, to take mean age for all the missing values.
Or, find if age is related to Pclass, and assign respective means. | sb.boxplot(x='Pclass',y='Age',data=titanic_data) | titanic forked.ipynb | decisionstats/pythonfordatascience | apache-2.0 |
If Passenger belongs to Pclass 3, age assigned is 24, if 2, age is assigned 29, if 1 then 37. | def age_approx(cols):
age = cols[0]
pclass = cols[1]
if pd.isnull(age):
if pclass == 1:
return 37
elif pclass == 2:
return 29
else:
return 24
else:
return age
titanic_data['Age'] = titanic_data[['Age', 'Pclass']].apply(age_approx, axis... | titanic forked.ipynb | decisionstats/pythonfordatascience | apache-2.0 |
There are two null values in Embarked, we can just drop them. | titanic_data.dropna(inplace=True)
titanic_data.isnull().sum() | titanic forked.ipynb | decisionstats/pythonfordatascience | apache-2.0 |
Getting dummy variables from categorical ones. | gender = pd.get_dummies(titanic_data['Sex'],drop_first=True)
gender.head()
embark_location = pd.get_dummies(titanic_data['Embarked'],drop_first=True)
embark_location.head()
titanic_data.drop(['Sex','Embarked'],axis=1,inplace=True)
titanic_data.head()
titanic_dmy = pd.concat([titanic_data, gender, embark_location],ax... | titanic forked.ipynb | decisionstats/pythonfordatascience | apache-2.0 |
The train test split is done for parameter tuning.
We now deploy the models. | !pip install xgboost
from sklearn.ensemble import RandomForestClassifier
#from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from xgboost import XGBClassifier
from sklearn.metrics import confusion_matrix
from sklearn.ensemble import VotingClassifier
clf1 = SVC(kernel='linear',C=1.0,random... | titanic forked.ipynb | decisionstats/pythonfordatascience | apache-2.0 |
Now taking in Competition Data. | url = 'C:\\Users\\ajaohri\\Desktop\\all/test.csv'
test = pd.read_csv(url)
test.head()
test.isnull().sum() | titanic forked.ipynb | decisionstats/pythonfordatascience | apache-2.0 |
There are 86 null values in Age, so we approximate them like we did earlier.
There are 327 null values in Cabin, so we drop it altogether.
There is 1 null value in Fare, so we approximate it according to the median of each class of the null position. | test.describe()
sb.set(rc={'figure.figsize':(11.7,8.27)})
ax = sb.boxplot(x='Pclass',y='Fare',data=test,width=0.9)
def fare_approx(cols):
fare = cols[0]
pclass = cols[1]
if pd.isnull(fare):
if pclass == 1:
return 55
elif pclass == 2:
return 20
else:
... | titanic forked.ipynb | decisionstats/pythonfordatascience | apache-2.0 |
Cleaning up the test data:
Dropping variables, approximating age and fare, dummy variables. | test_data = test.drop(['Name','Ticket'],1)
test_data['Age'] = test_data[['Age', 'Pclass']].apply(age_approx, axis=1)
test_data['Fare'] = test_data[['Fare','Pclass']].apply(fare_approx, axis=1)
test_data['Cabin'] = test_data[['Cabin','Pclass']].apply(cabin_approx, axis=1)
#
gender_test = pd.get_dummies(test_data['Sex'],... | titanic forked.ipynb | decisionstats/pythonfordatascience | apache-2.0 |
Prediction for Competition Data | y_comp = eclf.predict(X_competition)
submission = pd.DataFrame({'PassengerId':test_data['PassengerId'],'Survived':y_comp})
submission.head()
filename = 'Titanic Predictions 1.csv'
submission.to_csv(filename,index=False)
print('Saved file: ' + filename)
os.getcwd()
| titanic forked.ipynb | decisionstats/pythonfordatascience | apache-2.0 |
Loading the problem and generate initial data | from emukit.test_functions import sixhumpcamel_function
f, parameter_space = sixhumpcamel_function() | notebooks/Emukit-tutorial-bayesian-optimization-integrating-model-hyperparameters.ipynb | EmuKit/emukit | apache-2.0 |
Now we define the domain of the function to optimize. | ### --- Generate data
from emukit.core.initial_designs import RandomDesign
design = RandomDesign(parameter_space) # Collect random points
num_data_points = 5
X = design.get_samples(num_data_points)
Y = f(X) | notebooks/Emukit-tutorial-bayesian-optimization-integrating-model-hyperparameters.ipynb | EmuKit/emukit | apache-2.0 |
Train the model on the initial data | import GPy
model_gpy_mcmc = GPy.models.GPRegression(X,Y)
model_gpy_mcmc.kern.set_prior(GPy.priors.Uniform(0,5))
model_gpy_mcmc.likelihood.variance.constrain_fixed(0.001) | notebooks/Emukit-tutorial-bayesian-optimization-integrating-model-hyperparameters.ipynb | EmuKit/emukit | apache-2.0 |
We wrap the model in Emukit. | from emukit.model_wrappers import GPyModelWrapper
model_emukit = GPyModelWrapper(model_gpy_mcmc)
model_emukit.model.plot()
model_emukit.model | notebooks/Emukit-tutorial-bayesian-optimization-integrating-model-hyperparameters.ipynb | EmuKit/emukit | apache-2.0 |
Create the aquisition function
We use a combination of IntegratedHyperParameterAcquisition and ExpectedImprovement classes to create the integrated expected improvement acquisition object. The IntegratedHyperParameterAcquisition can convert any acquisition function into one that is integrated over model hyper-parameter... | from emukit.core.acquisition import IntegratedHyperParameterAcquisition
from emukit.bayesian_optimization.acquisitions import ExpectedImprovement
acquisition_generator = lambda model: ExpectedImprovement(model, jitter=0)
expected_improvement_integrated = IntegratedHyperParameterAcquisition(model_emukit, acquisition_ge... | notebooks/Emukit-tutorial-bayesian-optimization-integrating-model-hyperparameters.ipynb | EmuKit/emukit | apache-2.0 |
We run the loop for 10 iterations. | max_iter = 10
bayesopt_loop.run_loop(f, max_iter) | notebooks/Emukit-tutorial-bayesian-optimization-integrating-model-hyperparameters.ipynb | EmuKit/emukit | apache-2.0 |
Now, once the loop is completed we can visualize the distribution of the hyperparameters given the data. | labels = ['rbf variance', 'rbf lengthscale']
plt.figure(figsize=(14,5))
samples = bayesopt_loop.candidate_point_calculator.acquisition.samples
plt.subplot(1,2,1)
plt.plot(samples,label = labels)
plt.title('Hyperparameters samples',size=25)
plt.xlabel('Sample index',size=15)
plt.ylabel('Value',size=15)
plt.subplot(1,... | notebooks/Emukit-tutorial-bayesian-optimization-integrating-model-hyperparameters.ipynb | EmuKit/emukit | apache-2.0 |
And we can check how the optimization evolved when you integrate out the acquisition. | plt.plot(np.minimum.accumulate(bayesopt_loop.loop_state.Y))
plt.ylabel('Current best')
plt.xlabel('Iteration'); | notebooks/Emukit-tutorial-bayesian-optimization-integrating-model-hyperparameters.ipynb | EmuKit/emukit | apache-2.0 |
Next we choose a model and hyperparameters: | from sklearn.neighbors import KNeighborsClassifier
model = KNeighborsClassifier(n_neighbors=1) | tutorials/12 Model Selection.ipynb | n-witt/MachineLearningWithText_SS2017 | gpl-3.0 |
Then we train the model, and use it to predict labels for data we already know: | model.fit(X, y)
y_model = model.predict(X) | tutorials/12 Model Selection.ipynb | n-witt/MachineLearningWithText_SS2017 | gpl-3.0 |
Finally, we compute the fraction of correctly labeled points: | from sklearn.metrics import accuracy_score
accuracy_score(y, y_model) | tutorials/12 Model Selection.ipynb | n-witt/MachineLearningWithText_SS2017 | gpl-3.0 |
We see an accuracy score of 1.0, which indicates that 100% of points were correctly labeled by our model!
But is this truly measuring the expected accuracy?
Have we really come upon a model that we expect to be correct 100% of the time?
Model validation the right way: Holdout sets
We need to use a holdout set: that is,... | from sklearn.model_selection import train_test_split
# split the data with 50% in each set
X1, X2, y1, y2 = train_test_split(X, y, random_state=0, train_size=0.5)
# fit the model on one set of data
model.fit(X1, y1)
# evaluate the model on the second set of data
y2_model = model.predict(X2)
accuracy_score(y2, y2_mode... | tutorials/12 Model Selection.ipynb | n-witt/MachineLearningWithText_SS2017 | gpl-3.0 |
The nearest-neighbor classifier is about 90% accurate on this hold-out set, which is more inline with out expactation.
The hold-out set is similar to unknown data, because the model has not "seen" it before.
But, we have lost a portion of our data to the model training.
In the above case, half the dataset does not cont... | y2_model = model.fit(X1, y1).predict(X2)
y1_model = model.fit(X2, y2).predict(X1)
accuracy_score(y1, y1_model), accuracy_score(y2, y2_model) | tutorials/12 Model Selection.ipynb | n-witt/MachineLearningWithText_SS2017 | gpl-3.0 |
We could compute the mean of the two accuracy scores to get a better measure of the global model performance.
This particular form of cross-validation is a two-fold cross-validation.
We could expand on this idea to use even more trials, and more folds.
Here is a visual depiction of five-fold cross-validation:
We spli... | from sklearn.model_selection import cross_val_score
cross_val_score(model, X, y, cv=5) | tutorials/12 Model Selection.ipynb | n-witt/MachineLearningWithText_SS2017 | gpl-3.0 |
This gives us an even better idea of the performance of the algorithm.
How could we take this idea to its extreme?
The case in which our number of folds is equal to the number of data points.
This type of cross-validation is known as leave-one-out cross validation, and can be used as follows: | from sklearn.model_selection import LeaveOneOut
import numpy as np
loo = LeaveOneOut()
loo.get_n_splits(X)
scores = []
for train_index, test_index in loo.split(X):
model.fit(X[train_index], y[train_index])
scores.append(accuracy_score(y[test_index], model.predict(X[test_index])))
scores = np.array(scores)
scor... | tutorials/12 Model Selection.ipynb | n-witt/MachineLearningWithText_SS2017 | gpl-3.0 |
Because we have 150 samples, the leave one out cross-validation yields scores for 150 trials, and the score indicates either successful (1.0) or unsuccessful (0.0) prediction.
Taking the mean of these gives an estimate of the error rate: | scores.mean() | tutorials/12 Model Selection.ipynb | n-witt/MachineLearningWithText_SS2017 | gpl-3.0 |
This gives us a good impression on the performance of our model. But there is also a problem. Can you spot it?
Selecting the Best Model
Now that we can evaluate a model's performance, we will tackle the question how to select a model and its hyperparameters.
A very important question to ask is: If my estimator is under... | from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline
def PolynomialRegression(degree=2, **kwargs):
return make_pipeline(PolynomialFeatures(degree), LinearRegression(**kwargs)) | tutorials/12 Model Selection.ipynb | n-witt/MachineLearningWithText_SS2017 | gpl-3.0 |
Now let's create some data to which we will fit our model: | import numpy as np
def make_data(N, err=1.0, rseed=1):
# randomly sample the data
rng = np.random.RandomState(rseed)
X = rng.rand(N, 1) ** 2
y = 10 - 1. / (X.ravel() + 0.1)
if err > 0:
y += err * rng.randn(N)
return X, y
X, y = make_data(40) | tutorials/12 Model Selection.ipynb | n-witt/MachineLearningWithText_SS2017 | gpl-3.0 |
We can now visualize our data, along with polynomial fits of several degrees: | %matplotlib inline
import matplotlib.pyplot as plt
import seaborn; seaborn.set() # for beautiful plotting
X_test = np.linspace(-0.1, 1.1, 500)[:, None]
plt.scatter(X.ravel(), y, color='black') # plot data
axis = plt.axis()
# plot ploynomials
for degree in [1, 3, 5]:
y_test = PolynomialRegression(degree).fit(X, ... | tutorials/12 Model Selection.ipynb | n-witt/MachineLearningWithText_SS2017 | gpl-3.0 |
We can controll the model complexity (the degree of the polynomial), which can be any non-negative integer.
A useful question to answer is this: what degree of polynomial provides a suitable trade-off between bias (under-fitting) and variance (over-fitting)?
We can make progress in this by visualizing the validation... | from sklearn.model_selection import validation_curve
degree = np.arange(0, 21)
train_score, val_score = validation_curve(PolynomialRegression(), X, y,
'polynomialfeatures__degree', degree, cv=10)
plt.plot(degree, np.median(train_score, 1), color='blue', label='training score')... | tutorials/12 Model Selection.ipynb | n-witt/MachineLearningWithText_SS2017 | gpl-3.0 |
This shows precisely the behavior we expect:
* The training score is everywhere higher than the validation score
* The training score is monotonically improving with increased model complexity
* The validation score reaches a maximum before dropping off as the model becomes over-fit.
Which degree ist optimal?
Let's plo... | plt.scatter(X.ravel(), y)
lim = plt.axis()
y_test = PolynomialRegression(3).fit(X, y).predict(X_test)
plt.plot(X_test.ravel(), y_test);
plt.axis(lim); | tutorials/12 Model Selection.ipynb | n-witt/MachineLearningWithText_SS2017 | gpl-3.0 |
Learning Curves
One important aspect of model complexity is that the optimal model will generally depend on the size of your training data.
For example, let's generate a new five times larger dataset: | X2, y2 = make_data(200)
plt.scatter(X2.ravel(), y2); | tutorials/12 Model Selection.ipynb | n-witt/MachineLearningWithText_SS2017 | gpl-3.0 |
We will duplicate the preceding code to plot the validation curve for this larger dataset; for reference let's over-plot the previous results as well: | degree = np.arange(51)
train_score2, val_score2 = validation_curve(PolynomialRegression(), X2, y2,
'polynomialfeatures__degree', degree, cv=10)
plt.plot(degree, np.median(train_score2, 1), color='blue', label='training score')
plt.plot(degree, np.median(val_score2, 1), color... | tutorials/12 Model Selection.ipynb | n-witt/MachineLearningWithText_SS2017 | gpl-3.0 |
From the validation curve it is clear that the larger dataset can support a much more complicated model:
* The peak here is probably around a degree of 6
* Even a degree-20 model is not seriously overfitting the data
Thus we see that the behavior of the validation curve has not one but two important inputs:
* the mode... | from sklearn.model_selection import learning_curve
fig, ax = plt.subplots(1, 2, figsize=(16, 6))
fig.subplots_adjust(left=0.0625, right=0.95, wspace=0.1)
for i, degree in enumerate([2, 9]):
N, train_lc, val_lc = learning_curve(PolynomialRegression(degree),
X, y, cv=10,
... | tutorials/12 Model Selection.ipynb | n-witt/MachineLearningWithText_SS2017 | gpl-3.0 |
This plot gives us a visual depiction of how our model responds to increasing training data.
When the learning curve has already converged (i.e., when the training and validation curves are already close to each other) adding more training data will not significantly improve the fit!.
This situation is seen in the left... | from sklearn.model_selection import GridSearchCV
param_grid = {'polynomialfeatures__degree': np.arange(21),
'linearregression__fit_intercept': [True, False],
'linearregression__normalize': [True, False]}
grid = GridSearchCV(PolynomialRegression(), param_grid, cv=10) | tutorials/12 Model Selection.ipynb | n-witt/MachineLearningWithText_SS2017 | gpl-3.0 |
Notice that like a normal estimator, this has not yet been applied to any data.
Calling the fit() method will fit the model at each grid point, keeping track of the scores along the way: | grid.fit(X, y); | tutorials/12 Model Selection.ipynb | n-witt/MachineLearningWithText_SS2017 | gpl-3.0 |
Now that this is fit, we can ask for the best parameters as follows: | grid.best_params_ | tutorials/12 Model Selection.ipynb | n-witt/MachineLearningWithText_SS2017 | gpl-3.0 |
Finally, if we wish, we can use the best model and show the fit to our data using code from before: | model = grid.best_estimator_
plt.scatter(X.ravel(), y)
lim = plt.axis()
y_test = model.fit(X, y).predict(X_test)
plt.plot(X_test.ravel(), y_test);
plt.axis(lim); | tutorials/12 Model Selection.ipynb | n-witt/MachineLearningWithText_SS2017 | gpl-3.0 |
Úkoly
Projděte všechny soubory v adresáři N2spec. Každý z nich obsahuje dusíkové spektrum získané při určité teplotě. Výše popsanou metodou s využitím kalibrační křivky (N2spec/calibration.txt) přiřaďte každému souboru správnou teplotu.
Jméno každého souboru skrývá souřadnice x a y. Vyneste získané hodnoty teploty do... | !ls N2spec/ | head #!ls vypíše obsah adresáře, head jej omezí na prvních 10 řádků | lekce_08/N2spec.ipynb | ziky5/F4500_Python_pro_fyziky | mit |
Předchozí přístup vlastně nevyužívá python. Pro práci s obsahem adresářů je v pythonu např. knihovna glob. S její pomocí můžeme zjistit, kolik souborů je třeba zpracovat. | import glob
filelist = glob.glob('N2spec/y*x*.txt')
print('Dnes zpracujeme ' + str(len(filelist)) + ' souborů') | lekce_08/N2spec.ipynb | ziky5/F4500_Python_pro_fyziky | mit |
Měli bychom si ověřit, jakou mají naše soubory strukturu: | !head N2spec/y0x10.txt | lekce_08/N2spec.ipynb | ziky5/F4500_Python_pro_fyziky | mit |
Vidíme, že soubory skrývají spektra ve dvou sloupcích oddělených tabulátorem. První sloupec obsahuje údaje o vlnové délce (podle něj tedy můžeme rozhodnout, v jakém intervalu budeme integrovat), ve druhém sloupci najdeme intenzitu, tedy to, co bylo ve výše ukázaných grafech na ose y. První řádek obsahuje hlavičku a zač... | import numpy
numpy.genfromtxt?
#parametr converters umozni zpracovat i nestandardni vstupy
#napr. desetinna carka misto tecky
sample = numpy.genfromtxt(filelist[0], comments='#')
import matplotlib.pyplot as plt
%matplotlib inline
plt.plot(sample[:,0], sample[:,1])
#dvojtečková notace [:,0]: čti jako "vezmi všechny ... | lekce_08/N2spec.ipynb | ziky5/F4500_Python_pro_fyziky | mit |
A jak se počítá integrál? Podívejme se na funkci numpy.trapz. | numpy.trapz? | lekce_08/N2spec.ipynb | ziky5/F4500_Python_pro_fyziky | mit |
trapz sice umí spočítat integrál, ale neumí se omezit na daný interval. Na to budeme využívat výběr z pole s podmínkou. | condition0 = (sample[:,0] > 320) & (sample[:,0] < 335)
condition1 = (sample[:,0] > 335) & (sample[:,0] < 336.9)
condition2 = sample[:,0] > 336.9
plt.plot(sample[condition0,0], sample[condition0,1], color = 'blue')
plt.plot(sample[condition1,0], sample[condition1,1], color = 'red')
plt.plot(sample[condition2,0], sample... | lekce_08/N2spec.ipynb | ziky5/F4500_Python_pro_fyziky | mit |
Můžeme tedy přistoupit k výpočtu obou integrálů i jejich podílu. | I0 = numpy.trapz(y = sample[condition0,1], x = sample[condition0,0])
I1 = numpy.trapz(y = sample[condition1,1], x = sample[condition1, 0])
I0_over_I1 = I0 / I1
print(I0_over_I1) | lekce_08/N2spec.ipynb | ziky5/F4500_Python_pro_fyziky | mit |
Teď už jen zbývá správně použít kalibrační křivku a k podílu integrálů přiřadit správnou teplotu. Soubor musíme nejdříve načíst. Nejdřív zkontrolujeme, zda můžeme zase použít numpy.genfromtxt bez zvlzvláštních nastavení: | !head N2spec/calibration.txt
#hurá, půjde to po dobrém
cal = numpy.genfromtxt('N2spec/calibration.txt')
condition_temp = (cal[:,1] == I0_over_I1)
print(cal[condition_temp,0]) | lekce_08/N2spec.ipynb | ziky5/F4500_Python_pro_fyziky | mit |
Jenomže přesná hodnota I0_over_I1 v souboru calibration.txt není! Co teď?
Budeme muset použít google. Klíčová slova: numpy find nearest value.
.
.
.
.
.
.
(obrázek tu máte, ale přece to nebudete opisovat...)
<img src="http://physics.muni.cz/~janvorac/stack_overflow.png"></img> | def find_nearest(array,value):
idx = (numpy.abs(array-value)).argmin()
return idx
nearest_index = find_nearest(cal[:,1], I0_over_I1)
print(nearest_index)
print(cal[nearest_index, 0]) | lekce_08/N2spec.ipynb | ziky5/F4500_Python_pro_fyziky | mit |
Takže teď už zbývá jenom sepsat výše uvedené do cyklu a vytvořit si vhodnou strukturu na podržení výsledných teplot v paměti. Např. slovník. | temp_dict = {}
for fname in glob.glob('N2spec/y*x*.txt'):
data = numpy.genfromtxt(fname)
I0 = numpy.trapz(y = data[condition0,1], x = data[condition0,0])
I1 = numpy.trapz(y = data[condition1,1], x = data[condition1, 0])
I0_over_I1 = I0 / I1
index = find_nearest(cal[:,1], I0_over_I1)
T = cal[ind... | lekce_08/N2spec.ipynb | ziky5/F4500_Python_pro_fyziky | mit |
Je třeba dostat informace o souřadnicích ze jména souboru: | xs = []
ys = []
for fname in temp_dict:
#nejdrive rozdelime jmeno souboru podle "/" a vezmeme jen druhy prvek [1]
#prvni bude vzdy jen tentyz adresar
fname = fname.split('/')[1]
#abychom ziskali y, rozdelime jmenu souboru podle "x" a vezmeme prvni prvek [0]
y = fname.split('x')[0]
#jmeno soub... | lekce_08/N2spec.ipynb | ziky5/F4500_Python_pro_fyziky | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.