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 |
|---|---|---|---|---|---|
Сами вектора весов не совпали, но значения оптимизируемой функции близки, так что будем считать, что все ок. Изучаем скорость сходимости для $\lambda = 0.001$: | orac = make_oracle('breast-cancer_scale.txt', penalty='l1', reg=0.001)
point = optimizer(orac, w0)
errs = optimizer.errs
title = 'lambda = 0.001'
convergence_plot(optimizer.times, errs, 'вермя работы, с', title)
convergence_plot(optimizer.orac_calls, errs, 'кол-во вызовов оракула', title)
convergence_plot(list(range(1,... | _____no_output_____ | Apache-2.0 | HW_exam/.ipynb_checkpoints/Exam_Prazdnichnykh-checkpoint.ipynb | AntonPrazdnichnykh/HSE.optimization |
Кажется, что скорость сходимости опять линейная Изучаем зависимость скорости сходимости и количества ненулевых компонент в решении от $\lambda$ | lambdas = [10**(-i) for i in range(8, 0, -1)]
non_zeros = []
for reg in lambdas:
orac = make_oracle('breast-cancer_scale.txt', penalty='l1', reg=reg)
point = optimizer(orac, w0)
convergence_plot(list(range(1, optimizer.n_iter + 1)), optimizer.errs, 'кол-во итераций',
f"lambda = {reg}")
... | _____no_output_____ | Apache-2.0 | HW_exam/.ipynb_checkpoints/Exam_Prazdnichnykh-checkpoint.ipynb | AntonPrazdnichnykh/HSE.optimization |
Делаем те же выводы Построим напоследок грфики для значений оптимизируемой функции и критерия остановки (ещё разок) в зависимости от итерации ($\lambda = 0.001$) | orac = make_oracle('breast-cancer_scale.txt', penalty='l1', reg=0.001)
point = optimizer(orac, w0)
title = 'lambda = 0.001'
value_plot(list(range(1, optimizer.n_iter + 1)), optimizer.values, 'кол-во итераций', title)
convergence_plot(list(range(1, optimizer.n_iter + 1)), optimizer.errs, 'кол-во итераций', title) | _____no_output_____ | Apache-2.0 | HW_exam/.ipynb_checkpoints/Exam_Prazdnichnykh-checkpoint.ipynb | AntonPrazdnichnykh/HSE.optimization |
Implementing BERT with SNGP | !pip install tensorflow_text==2.7.3
!pip install -U tf-models-official==2.7.0
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import sklearn.metrics
import sklearn.calibration
import tensorflow_hub as hub
import tensorflow_datasets as tfds
import numpy as np
import tensorflow as tf
import pandas a... | _____no_output_____ | MIT | sngp_with_bert_aws.ipynb | tejashrigadre/Anomaly-detection-for-chat-bots |
Implement a standard BERT classifier following which classifies text | gpus = tf.config.list_physical_devices('GPU')
gpus
# Standard BERT model
PREPROCESS_HANDLE = 'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3'
MODEL_HANDLE = 'https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/3'
class BertClassifier(tf.keras.Model):
def __init__(self,
num_classe... | _____no_output_____ | MIT | sngp_with_bert_aws.ipynb | tejashrigadre/Anomaly-detection-for-chat-bots |
Build SNGP model To implement a BERT-SNGP model designed by Google researchers | class ResetCovarianceCallback(tf.keras.callbacks.Callback):
def on_epoch_begin(self, epoch, logs=None):
"""Resets covariance matrix at the begining of the epoch."""
if epoch > 0:
self.model.classifier.reset_covariance_matrix()
class SNGPBertClassifier(BertClassifier):
def make_classification_head(se... | _____no_output_____ | MIT | sngp_with_bert_aws.ipynb | tejashrigadre/Anomaly-detection-for-chat-bots |
Load train and test datasets | is_train = pd.read_json('is_train.json')
is_train.columns = ['question','intent']
is_test = pd.read_json('is_test.json')
is_test.columns = ['question','intent']
oos_test = pd.read_json('oos_test.json')
oos_test.columns = ['question','intent']
is_test.shape | _____no_output_____ | MIT | sngp_with_bert_aws.ipynb | tejashrigadre/Anomaly-detection-for-chat-bots |
Make the train and test data. | #Generate codes
is_data = is_train.append(is_test)
is_data.intent = pd.Categorical(is_data.intent)
is_data['code'] = is_data.intent.cat.codes
#in-scope evaluation data
is_test = is_data[15000:19500]
is_test_queries = is_test.question
is_test_labels = is_test.intent
is_test_codes = is_test.code
is_eval_data = (tf.con... | _____no_output_____ | MIT | sngp_with_bert_aws.ipynb | tejashrigadre/Anomaly-detection-for-chat-bots |
Create a OOD evaluation dataset. For this, combine the in-scope test data 'is_test' and out-of-scope 'oos_test' data. Assign label 0 for in-scope and label 1 for out-of-scope data | train_size = len(is_train)
test_size = len(is_test)
oos_size = len(oos_test)
# Combines the in-domain and out-of-domain test examples.
oos_queries= tf.concat([is_test['question'], oos_test['question']], axis=0)
oos_labels = tf.constant([0] * test_size + [1] * oos_size)
# Converts into a TF dataset.
oos_eval_dataset =... | _____no_output_____ | MIT | sngp_with_bert_aws.ipynb | tejashrigadre/Anomaly-detection-for-chat-bots |
Train and evaluate | TRAIN_EPOCHS = 4
TRAIN_BATCH_SIZE = 16
EVAL_BATCH_SIZE = 256
#@title
def bert_optimizer(learning_rate,
batch_size=TRAIN_BATCH_SIZE, epochs=TRAIN_EPOCHS,
warmup_rate=0.1):
"""Creates an AdamWeightDecay optimizer with learning rate schedule."""
train_data_size = train_size
... | _____no_output_____ | MIT | sngp_with_bert_aws.ipynb | tejashrigadre/Anomaly-detection-for-chat-bots |
Model 1 - Batch size of 32 & 3 epochs | sngp_model = SNGPBertClassifier()
sngp_model.compile(optimizer=optimizer, loss=loss, metrics=metrics)
sngp_model.fit(training_ds_queries, training_ds_labels, **fit_configs) | Epoch 1/2
938/938 [==============================] - 481s 494ms/step - loss: 0.8704 - sparse_categorical_accuracy: 0.8241 - val_loss: 0.2888 - val_sparse_categorical_accuracy: 0.9473
Epoch 2/2
938/938 [==============================] - 464s 495ms/step - loss: 0.0647 - sparse_categorical_accuracy: 0.9853 - val_loss: 0.1... | MIT | sngp_with_bert_aws.ipynb | tejashrigadre/Anomaly-detection-for-chat-bots |
Model 2 - Batch size of 16 & 2 epochs | sngp_model2 = SNGPBertClassifier()
sngp_model2.compile(optimizer=optimizer, loss=loss, metrics=metrics)
sngp_model2.fit(training_ds_queries, training_ds_labels, **fit_configs) | Epoch 1/3
938/938 [==============================] - 480s 495ms/step - loss: 0.9506 - sparse_categorical_accuracy: 0.8029 - val_loss: 0.3883 - val_sparse_categorical_accuracy: 0.9376
Epoch 2/3
938/938 [==============================] - 462s 493ms/step - loss: 0.0989 - sparse_categorical_accuracy: 0.9769 - val_loss: 0.2... | MIT | sngp_with_bert_aws.ipynb | tejashrigadre/Anomaly-detection-for-chat-bots |
Model 3 - Batch size of 16 & 4 epochs | sngp_model3 = SNGPBertClassifier()
sngp_model3.compile(optimizer=optimizer, loss=loss, metrics=metrics)
sngp_model3.fit(training_ds_queries, training_ds_labels, **fit_configs) | Epoch 1/4
938/938 [==============================] - 477s 493ms/step - loss: 0.9459 - sparse_categorical_accuracy: 0.8066 - val_loss: 0.3804 - val_sparse_categorical_accuracy: 0.9393
Epoch 2/4
938/938 [==============================] - 465s 496ms/step - loss: 0.1192 - sparse_categorical_accuracy: 0.9730 - val_loss: 0.2... | MIT | sngp_with_bert_aws.ipynb | tejashrigadre/Anomaly-detection-for-chat-bots |
Evaluate OOD performance Evaluate how well the model can detect the unfamiliar out-of-domain queries. |
def oos_predict(model, ood_eval_dataset, **model_kwargs):
oos_labels = []
oos_probs = []
ood_eval_dataset = ood_eval_dataset.batch(EVAL_BATCH_SIZE)
for oos_batch in ood_eval_dataset:
oos_text_batch = oos_batch["text"]
oos_label_batch = oos_batch["label"]
pred_logits = model(oos_text_batch, **mo... | _____no_output_____ | MIT | sngp_with_bert_aws.ipynb | tejashrigadre/Anomaly-detection-for-chat-bots |
Computes the OOD probabilities as $1 - p(x)$, where $p(x)=softmax(logit(x))$ is the predictive probability. | sngp_probs, ood_labels = oos_predict(sngp_model, oos_eval_dataset)
sngp_probs2, ood_labels2 = oos_predict(sngp_model2, oos_eval_dataset)
sngp_probs3, ood_labels3 = oos_predict(sngp_model3, oos_eval_dataset)
ood_probs = 1 - sngp_probs
ood_probs2 = 1 - sngp_probs2
ood_probs3 = 1 - sngp_probs3
plt.rcParams['figure.dpi'] =... | 0.9983203
| MIT | sngp_with_bert_aws.ipynb | tejashrigadre/Anomaly-detection-for-chat-bots |
Compute the Area under precision-recall curve (AUPRC) for OOD probability v.s. OOD detection accuracy. | precision, recall, _ = sklearn.metrics.precision_recall_curve(ood_labels, ood_probs)
precision2, recall2, _ = sklearn.metrics.precision_recall_curve(ood_labels2, ood_probs2)
precision3, recall3, _ = sklearn.metrics.precision_recall_curve(ood_labels3, ood_probs3)
print((precision3)
print(recall3) | _____no_output_____ | MIT | sngp_with_bert_aws.ipynb | tejashrigadre/Anomaly-detection-for-chat-bots |
[0.23380874 0.23362956 0.23368421 ... 1. 1. 1. ][1. 0.999 0.999 ... 0.002 0.001 0. ] | sklearn.metrics.recall_score(oos_labels, ood_labels3, average='weighted')
sklearn.metrics.precision_score(oos_labels, ood_labels3, average='weighted')
auprc = sklearn.metrics.auc(recall, precision)
print(f'SNGP AUPRC: {auprc:.4f}')
auprc2 = sklearn.metrics.auc(recall2, precision2)
print(f'SNGP AUPRC 2: {auprc2:.4f}')
a... | SNGP Model 1: ROC AUC=0.972
SNGP Model 2: ROC AUC=0.973
SNGP Model 3: ROC AUC=0.973
| MIT | sngp_with_bert_aws.ipynb | tejashrigadre/Anomaly-detection-for-chat-bots |
T81-558: Applications of Deep Neural Networks**Module 2: Python for Machine Learning*** Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)* For more information visit the [class... | try:
%tensorflow_version 2.x
COLAB = True
print("Note: using Google CoLab")
except:
print("Note: not using Google CoLab")
COLAB = False | Note: not using Google CoLab
| Apache-2.0 | t81_558_class_02_4_pandas_functional.ipynb | AritraJana1810/t81_558_deep_learning |
Part 2.4: Apply and Map If you've ever worked with Big Data or functional programming languages before, you've likely heard of map/reduce. Map and reduce are two functions that apply a task that you create to a data frame. Pandas supports functional programming techniques that allow you to use functions across en ent... | import os
import pandas as pd
import numpy as np
df = pd.read_csv(
"https://data.heatonresearch.com/data/t81-558/auto-mpg.csv",
na_values=['NA', '?'])
pd.set_option('display.max_columns', 7)
pd.set_option('display.max_rows', 5)
display(df) | _____no_output_____ | Apache-2.0 | t81_558_class_02_4_pandas_functional.ipynb | AritraJana1810/t81_558_deep_learning |
The **map** method in Pandas operates on a single column. You provide **map** with a dictionary of values to transform the target column. The map keys specify what values in the target column should be turned into values specified by those keys. The following code shows how the map function can transform the numeric... | # Apply the map
df['origin_name'] = df['origin'].map(
{1: 'North America', 2: 'Europe', 3: 'Asia'})
# Shuffle the data, so that we hopefully see
# more regions.
df = df.reindex(np.random.permutation(df.index))
# Display
pd.set_option('display.max_columns', 7)
pd.set_option('display.max_rows', 10)
display(df) | _____no_output_____ | Apache-2.0 | t81_558_class_02_4_pandas_functional.ipynb | AritraJana1810/t81_558_deep_learning |
Using Apply with DataframesThe **apply** function of the data frame can run a function over the entire data frame. You can use either be a traditional named function or a lambda function. Python will execute the provided function against each of the rows or columns in the data frame. The **axis** parameter specifies... | efficiency = df.apply(lambda x: x['displacement']/x['horsepower'], axis=1)
display(efficiency[0:10]) | _____no_output_____ | Apache-2.0 | t81_558_class_02_4_pandas_functional.ipynb | AritraJana1810/t81_558_deep_learning |
You can now insert this series into the data frame, either as a new column or to replace an existing column. The following code inserts this new series into the data frame. | df['efficiency'] = efficiency | _____no_output_____ | Apache-2.0 | t81_558_class_02_4_pandas_functional.ipynb | AritraJana1810/t81_558_deep_learning |
Feature Engineering with Apply and Map In this section, we will see how to calculate a complex feature using map, apply, and grouping. The data set is the following CSV:* https://www.irs.gov/pub/irs-soi/16zpallagi.csv This URL contains US Government public data for "SOI Tax Stats - Individual Income Tax Statistics." ... | import pandas as pd
df=pd.read_csv('https://www.irs.gov/pub/irs-soi/16zpallagi.csv') | _____no_output_____ | Apache-2.0 | t81_558_class_02_4_pandas_functional.ipynb | AritraJana1810/t81_558_deep_learning |
First, we trim all zip codes that are either 0 or 99999. We also select the three fields that we need. | df=df.loc[(df['zipcode']!=0) & (df['zipcode']!=99999),
['STATE','zipcode','agi_stub','N1']]
pd.set_option('display.max_columns', 0)
pd.set_option('display.max_rows', 10)
display(df) | _____no_output_____ | Apache-2.0 | t81_558_class_02_4_pandas_functional.ipynb | AritraJana1810/t81_558_deep_learning |
We replace all of the **agi_stub** values with the correct median values with the **map** function. | medians = {1:12500,2:37500,3:62500,4:87500,5:112500,6:212500}
df['agi_stub']=df.agi_stub.map(medians)
pd.set_option('display.max_columns', 0)
pd.set_option('display.max_rows', 10)
display(df) | _____no_output_____ | Apache-2.0 | t81_558_class_02_4_pandas_functional.ipynb | AritraJana1810/t81_558_deep_learning |
Next, we group the data frame by zip code. | groups = df.groupby(by='zipcode') | _____no_output_____ | Apache-2.0 | t81_558_class_02_4_pandas_functional.ipynb | AritraJana1810/t81_558_deep_learning |
The program applies a lambda is applied across the groups, and then calculates the AGI estimate. | df = pd.DataFrame(groups.apply(
lambda x:sum(x['N1']*x['agi_stub'])/sum(x['N1']))) \
.reset_index()
pd.set_option('display.max_columns', 0)
pd.set_option('display.max_rows', 10)
display(df) | _____no_output_____ | Apache-2.0 | t81_558_class_02_4_pandas_functional.ipynb | AritraJana1810/t81_558_deep_learning |
We can now rename the new agi_estimate column. | df.columns = ['zipcode','agi_estimate']
pd.set_option('display.max_columns', 0)
pd.set_option('display.max_rows', 10)
display(df) | _____no_output_____ | Apache-2.0 | t81_558_class_02_4_pandas_functional.ipynb | AritraJana1810/t81_558_deep_learning |
Finally, we check to see that our zip code of 63017 got the correct value. | df[ df['zipcode']==63017 ] | _____no_output_____ | Apache-2.0 | t81_558_class_02_4_pandas_functional.ipynb | AritraJana1810/t81_558_deep_learning |
Charting a path into the data science field This project attempts to shed light on the path or paths to becoming a data science professional in the United States.Data science is a rapidly growing field, and the demand for data scientists is outpacing supply. In the past, most Data Scientist positions went to people wi... | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import textwrap
%matplotlib inline
from matplotlib.ticker import PercentFormatter
import warnings
warnings.filterwarnings('ignore')
df = pd.read_csv('./kaggle_survey_2020_responses.csv')
low_memory = False | _____no_output_____ | CNRI-Python | Charting a path into the data science field.ipynb | khiara/DSND_Kaggle_2020_Survey |
Initial data exploration and cleaningLet's take a look at the survey data. | # Let's look at the first 5 rows of the dataset
df.head() | _____no_output_____ | CNRI-Python | Charting a path into the data science field.ipynb | khiara/DSND_Kaggle_2020_Survey |
One thing we can see from this: some questions are tied to a single column, with a number of answers possible; these questions only allowed survey respondents to choose one answer from among the options. Other questions take up multiple columns, with each column tied to a specific answer; these were questions that allo... | # Removing the first column and the first row
df.drop(['Time from Start to Finish (seconds)'], axis=1, inplace=True)
df = df.loc[1:, :]
df.head()
df.shape | _____no_output_____ | CNRI-Python | Charting a path into the data science field.ipynb | khiara/DSND_Kaggle_2020_Survey |
There are over 20,000 responses, with 354 answer fields. Data preparation and filtering To improve readability of visualizations, we'll aggregate some fields, shorten some labels, and re-order categories. | # Aggregating the nonbinary answers
df.loc[(df.Q2 == 'Prefer not to say'), 'Q2'] = 'Other Response'
df.loc[(df.Q2 == 'Prefer to self-describe'),'Q2'] = 'Other Response'
df.loc[(df.Q2 == 'Nonbinary'), 'Q2'] = 'Other Response'
# Abbreviating country name
df.loc[(df.Q3 == 'United States of America'),'Q3']='USA'
# Shorte... | _____no_output_____ | CNRI-Python | Charting a path into the data science field.ipynb | khiara/DSND_Kaggle_2020_Survey |
We're going to focus on the US answers from currently employed Kagglers. | # Filtering for just US responses
us_df = df[df['Q3'] == 'USA']
# Filtering to only include currently employed Kagglers
q5_order = [
'Data Scientist',
'Software Engineer',
'Data Analyst',
'Research Scientist',
'Product/Project Manager',
'Business Analyst',
'Machine Learning Engineer',
... | _____no_output_____ | CNRI-Python | Charting a path into the data science field.ipynb | khiara/DSND_Kaggle_2020_Survey |
We're interested in the demographic questions at the beginning, plus coding experience, coding languages used, and online learning platforms used. | # Filtering to only include specific question columns
us_df = us_df.loc[:, ['Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6', 'Q7_Part_1', 'Q7_Part_2','Q7_Part_3','Q7_Part_4','Q7_Part_5',
'Q7_Part_6', 'Q7_Part_7','Q7_Part_8','Q7_Part_9','Q7_Part_10','Q7_Part_11', 'Q7_Part_12', 'Q7_OTHER',
... | _____no_output_____ | CNRI-Python | Charting a path into the data science field.ipynb | khiara/DSND_Kaggle_2020_Survey |
Not much in the way of missing values in the first 6 questions; that changes for the multiple-column questions, as expected, since users only filled in the column when they were choosing that particular option. We'll address that by converting the missing values to zeros in the helper functions. | us_df.shape | _____no_output_____ | CNRI-Python | Charting a path into the data science field.ipynb | khiara/DSND_Kaggle_2020_Survey |
This will be the data for our analysis -- covering 1680 currently employed Kagglers in the US. Helper functions A few functions to help with data visualizations. The first two plot a barchart with a corresponding list of the counts and percentages for the values; one handles single-column questions and the other handl... | def list_and_bar(qnum, q_order, title):
'''
INPUT:
qnum - the y-axis variable, a single-column question
q_order - the order to display responses on the barchart
title - the title of the barchart
OUTPUT:
1. A list of responses to the selected question, in descending order
2. A h... | _____no_output_____ | CNRI-Python | Charting a path into the data science field.ipynb | khiara/DSND_Kaggle_2020_Survey |
Analysis and visualizations We'll start by looking at the age and gender distribution, just to get an overview of the response community. | plt.figure(figsize=[12,6])
us_ages = us_df['Q1'].value_counts().sort_index()
sns.countplot(data = us_df, x = 'Q1', hue = 'Q2', order = us_ages.index)
plt.title('Age and Gender Distribution') | _____no_output_____ | CNRI-Python | Charting a path into the data science field.ipynb | khiara/DSND_Kaggle_2020_Survey |
The survey response pool skews heavily male, with most US Kagglers between the ages of 25 and 45. | list_and_bar('Q6', q6_order, 'Years of Coding Experience') | Count Pct
3-5 years 367 22.00
20+ years 349 20.92
5-10 years 334 20.02
10-20 years 288 17.27
1-2 years 171 10.25
< 1 years 104 6.24
I have never written code 55 3.30
| CNRI-Python | Charting a path into the data science field.ipynb | khiara/DSND_Kaggle_2020_Survey |
Around 80 percent of those responding have 3 or more years experience coding. 1. Do you need a formal degree to become a data science professional? Let's look at formal education, and how it correlates with job title. | list_and_bar('Q4', q4_order, 'Highest Level of Education Attained')
list_and_bar('Q5', q5_order, 'Current Job Title')
heatmap('Q4', 'Q5', 'Roles by Education Level', q5_order, q4_order) | _____no_output_____ | CNRI-Python | Charting a path into the data science field.ipynb | khiara/DSND_Kaggle_2020_Survey |
Question 1 analysis With almost 49% of the responses, a Master's degree was by far the most common level of education listed, more than double the next most popular answer. Other notable observations: * Sixty-eight percent of US Kagglers hold a Master's Degree or higher. * Research scientists and statisticians ... | # creating a dataframe of the language options and the number of times each language was selected
languages = pd.DataFrame()
for col in us_df.columns:
if(col.startswith('Q7_')):
language = us_df[col].value_counts()
languages = languages.append({'Language':language.index[0], 'Count':language[0]}, ig... | _____no_output_____ | CNRI-Python | Charting a path into the data science field.ipynb | khiara/DSND_Kaggle_2020_Survey |
Question 2 analysis Python was the most widely used language, followed by SQL and R. Python held the top spot across almost all job roles -- only Statisticians listed another language (SQL) higher -- and for all education levels and coding experience. R enjoys widespread popularity across education level and years cod... | # creating a dataframe of online course providers and the number of times each was selected by users
platforms = pd.DataFrame()
for col in us_df.columns:
if(col.startswith('Q37_')):
platform = us_df[col].value_counts()
platforms = platforms.append({'Platform':platform.index[0], 'Count':platform[0]}... | _____no_output_____ | CNRI-Python | Charting a path into the data science field.ipynb | khiara/DSND_Kaggle_2020_Survey |
基本程序设计- 一切代码输入,请使用英文输入法 | print('hello word')
print 'hello' | _____no_output_____ | Apache-2.0 | 7.16.ipynb | zhayanqi/mysql |
编写一个简单的程序- 圆公式面积: area = radius \* radius \* 3.1415 | radius = 1.0
area = radius * radius * 3.14 # 将后半部分的结果赋值给变量area
# 变量一定要有初始值!!!
# radius: 变量.area: 变量!
# int 类型
print(area) | 3.14
| Apache-2.0 | 7.16.ipynb | zhayanqi/mysql |
在Python里面不需要定义数据的类型 控制台的读取与输入- input 输入进去的是字符串- eval | radius = input('请输入半径') # input得到的结果是字符串类型
radius = float(radius)
area = radius * radius * 3.14
print('面积为:',area) | 请输入半径10
面积为: 314.0
| Apache-2.0 | 7.16.ipynb | zhayanqi/mysql |
- 在jupyter用shift + tab 键可以跳出解释文档 变量命名的规范- 由字母、数字、下划线构成- 不能以数字开头 \*- 标识符不能是关键词(实际上是可以强制改变的,但是对于代码规范而言是极其不适合)- 可以是任意长度- 驼峰式命名 变量、赋值语句和赋值表达式- 变量: 通俗理解为可以变化的量- x = 2 \* x + 1 在数学中是一个方程,而在语言中它是一个表达式- test = test + 1 \* 变量在赋值之前必须有值 同时赋值var1, var2,var3... = exp1,exp2,exp3... 定义常量- 常量:表示一种定值标识符,适合于多次使用的场景。比如PI- 注意:在其他低级语言中... | day = eval(input('week'))
plus_day = eval(input('plus'))
| _____no_output_____ | Apache-2.0 | 7.16.ipynb | zhayanqi/mysql |
计算表达式和运算优先级 增强型赋值运算 类型转换- float -> int- 四舍五入 round EP:- 如果一个年营业税为0.06%,那么对于197.55e+2的年收入,需要交税为多少?(结果保留2为小数)- 必须使用科学计数法 Project- 用Python写一个贷款计算器程序:输入的是月供(monthlyPayment) 输出的是总还款数(totalpayment) Homework- 1 | celsius = input('请输入温度')
celsius = float(celsius)
fahrenheit = (9/5) * celsius + 32
print(celsius,'Celsius is',fahrenheit,'Fahrenheit') | 请输入温度43
43.0 Celsius is 109.4 Fahrenheit
| Apache-2.0 | 7.16.ipynb | zhayanqi/mysql |
- 2 | radius = input('请输入半径')
length = input('请输入高')
radius = float(radius)
length = float(length)
area = radius * radius * 3.14
volume = area * length
print('The area is',area)
print('The volume is',volume) | 请输入半径5.5
请输入高12
The area is 94.985
The volume is 1139.82
| Apache-2.0 | 7.16.ipynb | zhayanqi/mysql |
- 3 | feet = input('请输入英尺')
feet = float(feet)
meter = feet * 0.305
print(feet,'feet is',meter,'meters') | 请输入英尺16.5
16.5 feet is 5.0325 meters
| Apache-2.0 | 7.16.ipynb | zhayanqi/mysql |
- 4 | M = input('请输入水量')
initial = input('请输入初始温度')
final = input('请输入最终温度')
M = float(M)
initial = float(initial)
final = float(final)
Q = M * (final - initial) * 4184
print('The energy needed is ',Q) | 请输入水量55.5
请输入初始温度3.5
请输入最终温度10.5
The energy needed is 1625484.0
| Apache-2.0 | 7.16.ipynb | zhayanqi/mysql |
- 5 | cha = input('请输入差额')
rate = input('请输入年利率')
cha = float(cha)
rate = float(rate)
interest = cha * (rate/1200)
print(interest) | 请输入差额1000
请输入年利率3.5
2.916666666666667
| Apache-2.0 | 7.16.ipynb | zhayanqi/mysql |
- 6 | start = input('请输入初始速度')
end = input('请输入末速度')
time = input('请输入时间')
start = float(start)
end =float(end)
time = float(time)
a = (end - start)/time
print(a) | 请输入初始速度5.5
请输入末速度50.9
请输入时间4.5
10.088888888888889
| Apache-2.0 | 7.16.ipynb | zhayanqi/mysql |
- 7 进阶 - 8 进阶 | a,b = eval(input('>>'))
print(a,b)
print(type(a),type(b))
a = eval(input('>>'))
print(a) | >>1,2,3,4,5,6
(1, 2, 3, 4, 5, 6)
| Apache-2.0 | 7.16.ipynb | zhayanqi/mysql |
Part 1: Initailize Plot Agent | plot_agent = ThreeBar(big_traj_folder, data_folder) | _____no_output_____ | MIT | notebooks/sum_backbone_stack_hb_0.ipynb | yizaochen/enmspring |
Part 2: Make/Read DataFrame | makedf = False
if makedf:
plot_agent.ini_b_agent()
plot_agent.ini_s_agent()
plot_agent.ini_h_agent()
plot_agent.make_df_for_all_host()
plot_agent.read_df_for_all_host() | _____no_output_____ | MIT | notebooks/sum_backbone_stack_hb_0.ipynb | yizaochen/enmspring |
Part 2: Bar Plot | figsize = (1.817, 1.487)
hspace = 0
plot_agent.plot_main(figsize, hspace)
svg_out = path.join(drawzone_folder, 'sum_bb_st_hb.svg')
plt.savefig(svg_out, dpi=200)
plt.show()
from enmspring.graphs_bigtraj import BackboneMeanModeAgent
host = 'a_tract_21mer'
interval_time = 500
b_agent = BackboneMeanModeAgent(host, big_tra... | _____no_output_____ | MIT | notebooks/sum_backbone_stack_hb_0.ipynb | yizaochen/enmspring |
Load & Preprocess Data Cornell Movie Dialogues Corpus | corpus_name = "cornell movie-dialogs corpus"
corpus = os.path.join("data", corpus_name)
def printLines(file, n=10):
with open(file, 'rb') as datafile:
lines = datafile.readlines()
for line in lines[:n]:
print(line)
printLines(os.path.join(corpus, "movie_lines.txt"))
# Splits each line of the f... | keep_words 8610 / 20279 = 0.4246
Trimmed from 70086 pairs to 57379, 0.8187 of total
| MIT | chatbot.ipynb | Kevinz930/Alexiri-chatbot- |
Prepare Data for Models | def indexesFromSentence(voc, sentence):
return [voc.word2index[word] for word in sentence.split(' ')] + [EOS_token]
def zeroPadding(l, fillvalue=PAD_token):
return list(itertools.zip_longest(*l, fillvalue=fillvalue))
def binaryMatrix(l, value=PAD_token):
m = []
for i, seq in enumerate(l):
m.a... | input_variable: tensor([[ 33, 42, 83, 181, 279],
[ 97, 67, 59, 341, 31],
[ 32, 1089, 735, 33, 10],
[ 10, 260, 112, 32, 2],
[ 563, 33, 16, 15, 0],
[ 46, 121, 15, 2, 0],
[ 82, 1727, 2, 0, 0],
[ 10, 10, ... | MIT | chatbot.ipynb | Kevinz930/Alexiri-chatbot- |
Encoder | class EncoderRNN(nn.Module):
def __init__(self, hidden_size, embedding, n_layers=1, dropout=0):
super(EncoderRNN, self).__init__()
self.n_layers = n_layers
self.hidden_size = hidden_size
self.embedding = embedding
# Initialize GRU; the input_size and hidden_size params are b... | _____no_output_____ | MIT | chatbot.ipynb | Kevinz930/Alexiri-chatbot- |
Decoder | # Luong attention layer
class Attn(nn.Module):
def __init__(self, method, hidden_size):
super(Attn, self).__init__()
self.method = method
if self.method not in ['dot', 'general', 'concat']:
raise ValueError(self.method, "is not an appropriate attention method.")
self.hidd... | _____no_output_____ | MIT | chatbot.ipynb | Kevinz930/Alexiri-chatbot- |
Training Procedure | def maskNLLLoss(inp, target, mask):
nTotal = mask.sum()
crossEntropy = -torch.log(torch.gather(inp, 1, target.view(-1, 1)).squeeze(1))
loss = crossEntropy.masked_select(mask).mean()
loss = loss.to(device)
return loss, nTotal.item()
def train(input_variable, lengths, target_variable, mask, max_target... | _____no_output_____ | MIT | chatbot.ipynb | Kevinz930/Alexiri-chatbot- |
Evaluation | class GreedySearchDecoder(nn.Module):
def __init__(self, encoder, decoder, voc):
super(GreedySearchDecoder, self).__init__()
self.encoder = encoder
self.decoder = decoder
self.voc = voc
def forward(self, input_seq, input_length, max_length):
# Forward input through encod... | _____no_output_____ | MIT | chatbot.ipynb | Kevinz930/Alexiri-chatbot- |
Embeddings | # load pre-trained word2Vec model
import gensim.downloader as api
model = api.load('word2vec-google-news-300')
weights_w2v = torch.FloatTensor(model.vectors)
# load pre-trained Gloves 42B-300d model
# model = gensim.models.KeyedVectors.load_word2vec_format('glove.42B.300d.w2vformat.txt')
corpus = os.path.join("glove",... | Building encoder and decoder ...
Models built and ready to go!
| MIT | chatbot.ipynb | Kevinz930/Alexiri-chatbot- |
Run Model Training | # Configure training/optimization
clip = 50.0
teacher_forcing_ratio = 1.0
learning_rate = 0.0001
decoder_learning_ratio = 6.0 # 5.0 -> 4.0
n_iteration = 5000 # 4000 -> 5000
print_every = 1
save_every = 500
# Ensure dropout layers are in train mode
encoder.train()
decoder.train()
# Initialize optimizers
print('Buildin... | _____no_output_____ | MIT | chatbot.ipynb | Kevinz930/Alexiri-chatbot- |
Evaluation | # Set dropout layers to eval mode
encoder.eval()
decoder.eval()
# Initialize search module
searcher = GreedySearchDecoder(encoder, decoder, voc)
evaluateInput(encoder, decoder, searcher, voc) | > hey
all tokens words []
all tokens words ['i']
all tokens words ['i', "don't"]
all tokens words ['i', "don't", 'bacon']
all tokens words ['i', "don't", 'bacon', 'sandwich']
all tokens words ['i', "don't", 'bacon', 'sandwich', 'sandwich']
all tokens words ['i', "don't", 'bacon', 'sandwich', 'sandwich', 'bacon']
all to... | MIT | chatbot.ipynb | Kevinz930/Alexiri-chatbot- |
Data UnderstandingIn order to get a better understanding of the busiest times in seattle, we will take a look at the dataset. Access & ExploreFirst, let's read and explore the data | import pandas as pd
import matplotlib.pyplot as plt
#Import Calendar dataset
df_cal=pd.read_csv('calendar.csv', thousands=',')
pd.set_option("display.max_columns", None)
df_cal.head()
#Check if any empty records for the price
df_cal['price'].isnull().value_counts() | _____no_output_____ | CNRI-Python | Seattle Busiest Time.ipynb | ShadyHanafy/Shady |
Data Preparation & AnalysisNow we will prepare the data and make some convertions to prepare the data for visualization Wrangle and Clean | #Convert price to numerical value
df_cal["price"] = df_cal["price"].str.replace('[$,,,]',"").astype(float)
#Impute the missing data of price columns with mean
df_cal['price'].fillna((df_cal['price'].mean()), inplace=True)
#Create new feature represent the month of a year
df_cal['month'] = pd.DatetimeIndex(df_cal['date'... | _____no_output_____ | CNRI-Python | Seattle Busiest Time.ipynb | ShadyHanafy/Shady |
Data VisualizationNow we will visualize our dataset to get the required answer for the main question that which time is the busiest in seattle all over the year and its reflection on price | #Plot the busiest seattle time of the year
busytime=df_cal.groupby(['month']).price.mean()
busytime.plot(kind = 'bar', title="BusyTime")
#Plot the price range accross the year
busytime_price=df_cal.groupby(['month']).mean()['price'].sort_values().dropna()
busytime_price.plot(kind="bar");
plt.title("Price Trend over yea... | _____no_output_____ | CNRI-Python | Seattle Busiest Time.ipynb | ShadyHanafy/Shady |
0.0. IMPORTS | import math
import pandas as pd
import inflection
import numpy as np
import seaborn as sns
import matplotlib as plt
import datetime
from IPython.display import Image | _____no_output_____ | MIT | m03_v01_store_sales_prediction.ipynb | luana-afonso/DataScience-Em-Producao |
0.1. Helper Functions 0.2. Loading Data | # read_csv é um metodo da classe Pandas
# Preciso "unzipar" o arquivo antes?
# low_memory para dizer se ele lê o arquivo todo (False) ou em pedações (True), ele costuma avisar qual o melhor para a situação
df_sales_raw = pd.read_csv("data/train.csv.zip", low_memory=False)
df_store_raw = pd.read_csv("data/store.csv", lo... | _____no_output_____ | MIT | m03_v01_store_sales_prediction.ipynb | luana-afonso/DataScience-Em-Producao |
1.0. STEP 01 - DATA DESCRIPTION | df1 = df_raw.copy() | _____no_output_____ | MIT | m03_v01_store_sales_prediction.ipynb | luana-afonso/DataScience-Em-Producao |
1.1. Rename Columns Para ganhar velocidade no desenvolvimento! | df_raw.columns
# Estão até bem organizadas, formato candle (ou camble?) case, mas no mundo real pode ser bem diferente! rs
cols_old = ['Store', 'DayOfWeek', 'Date', 'Sales', 'Customers', 'Open', 'Promo',
'StateHoliday', 'SchoolHoliday', 'StoreType', 'Assortment',
'CompetitionDistance', 'CompetitionOpenSin... | _____no_output_____ | MIT | m03_v01_store_sales_prediction.ipynb | luana-afonso/DataScience-Em-Producao |
1.2. Data Dimensions Saber qual a quantidade de linhas e colunas do dataset | # O shape printa linhas e colunas do dataframe em que primeiro elemento são as rows
# Pq ali são as chaves que ele usa? Isso tem a ver com placeholder?
print( "Number of Rows: {}".format( df1.shape[0] ) )
print( "Number of Cols: {}".format( df1.shape[1] ) ) | Number of Rows: 1017209
Number of Cols: 18
| MIT | m03_v01_store_sales_prediction.ipynb | luana-afonso/DataScience-Em-Producao |
1.3. Data Types | # Atente que não usamos os parênteses aqui. Isso pq estamos vendo uma propriedade e não usando um método?
# O default do pandas é assumir o que não for int como object. Object é o "caracter" dentro do Pandas
# Atente para o date, precisamos mudar de object para datetime!
df1.dtypes
df1["date"] = pd.to_datetime( df1["da... | _____no_output_____ | MIT | m03_v01_store_sales_prediction.ipynb | luana-afonso/DataScience-Em-Producao |
1.4. Check NA | # O método isna vai mostrar todas as linhas que tem pelo menos uma coluna com um NA (vazia)
# Mas como eu quero ver a soma disso por coluna, uso o método sum
df1.isna().sum()
# Precisamos tratar esses NAs.
# Existem basicamente 3 maneiras:
# 1. Descartar essas linhas (fácil e rápido; mas jogando dado fora)
# 2. Usando ... | _____no_output_____ | MIT | m03_v01_store_sales_prediction.ipynb | luana-afonso/DataScience-Em-Producao |
1.5. Fillout NA | df1["competition_distance"].max()
#competition_distance: distance in meters to the nearest competitor store
# Se pensarmos que não ter o dado nessa coluna significa um competidor estar muito longe geograficamente e, portanto, se assumirmos os valores como muito maiores que a distancia máxima encontrada resolveria o pro... | _____no_output_____ | MIT | m03_v01_store_sales_prediction.ipynb | luana-afonso/DataScience-Em-Producao |
1.6. Change Types | # Importante checar se alguma operação feita na etapa anterior alterou algum dado anterior
# Método dtypes
# competition_open_since_month float64
# competition_open_since_year float64
# promo2_since_week float64
# promo2_since_year float64
# Na verdade essa... | _____no_output_____ | MIT | m03_v01_store_sales_prediction.ipynb | luana-afonso/DataScience-Em-Producao |
1.7. Descriptive Statistics Ganhar conhecimento de negócio e detectar alguns erros | # Central Tendency = mean, median
# Dispersion = std, min, max, range, skew, kurtosis
# Precisamos separar nossas variáveis entre numéricas e categóricas.
# A estatística descritiva funciona para os dois tipos de variáveis, mas a forma com que eu construo a estatistica
# descritiva é diferente.
# Vou separar todas a... | _____no_output_____ | MIT | m03_v01_store_sales_prediction.ipynb | luana-afonso/DataScience-Em-Producao |
1.7.1 Numerical Attributes | # Apply para aplicar uma operação em todas as colunas e transformar num dataframe pra facilitar a visualização
# Transpostas para ter metricas nas colunas e features nas linhas
# central tendency
ct1 = pd.DataFrame( num_attributes.apply ( np.mean) ).T
ct2 = pd.DataFrame( num_attributes.apply ( np.median ) ).T
# dispe... | _____no_output_____ | MIT | m03_v01_store_sales_prediction.ipynb | luana-afonso/DataScience-Em-Producao |
1.7.2 Categorical Attributes Vai de boxblot! | # ??? No do Meigarom só apareceu os: state_holiday, store_type, assortment, promo_interval e month_map
# Tirei os int32 tambem dos categoricos
cat_attributes.apply( lambda x: x.unique().shape[0] )
# Meigarom prefere o seaborn do que o matplotlib
# sns.boxplot( x= y=, data= )
# x = linha que vai ficar como referencia
# ... | _____no_output_____ | MIT | m03_v01_store_sales_prediction.ipynb | luana-afonso/DataScience-Em-Producao |
2.0. STEP 02 - FEATURE ENGINEERING Para quê fazer a Feature Engineering? Para ter as variáveis DISPONÍVEIS para ESTUDO durante a Análise Exploratória dos Dados. Pra não ter bagunça, crie as variáveis ANTES na análise exploratória!!! Vou usar uma classe Image para colocar a imagem do mapa mental: | df2 = df1.copy() | _____no_output_____ | MIT | m03_v01_store_sales_prediction.ipynb | luana-afonso/DataScience-Em-Producao |
2.1. Hypothesis Mind Map | Image ("img/mind-map-hypothesis.png") | _____no_output_____ | MIT | m03_v01_store_sales_prediction.ipynb | luana-afonso/DataScience-Em-Producao |
2.2. Hypothesis Creation 2.2.1 Store Hypothesis 1. Stores with greater number of employees should sell more. 2. Stores with greater stock size should sell more. 3. Stores with bigger size should sell more. 4. Stores with smaller size should sell less. 5. Stores with greater assortment should sell more. 6. Stores with... | # year
df2['year'] = df2['date'].dt.year
# month
df2['month'] = df2['date'].dt.month
# day
df2['day'] = df2['date'].dt.day
# week of year
df2['week_of_year'] = df2['date'].dt.isocalendar().week
# year week
# aqui não usaremos nenhum metodo, e sim mudaremos a formatação da data apenas
# ele fala do strftime no bônus... | _____no_output_____ | MIT | m03_v01_store_sales_prediction.ipynb | luana-afonso/DataScience-Em-Producao |
3.0. STEP 03 - VARIABLES FILTERING | # Antes de qualquer coisa, ao começar um novo passo, copia o dataset do passo anterior e passa a trabalhar com um novo
df3 = df2.copy()
df3.head() | _____no_output_____ | MIT | m03_v01_store_sales_prediction.ipynb | luana-afonso/DataScience-Em-Producao |
3.1. ROWS FILTERING | # "open" != 0 & "sales" > 0
df3 = df3[(df3["open"] != 0) & (df3["sales"] > 0)] | _____no_output_____ | MIT | m03_v01_store_sales_prediction.ipynb | luana-afonso/DataScience-Em-Producao |
3.2. COLUMNS SELECTION | # Vamos "dropar" as colunas que não queremos
# A "open" está aqui pois após tirarmos as linhas cujos dados da coluna "open" eram 0, só sobraram valores 1, então é uma coluna 'inútil'
cols_drop = ['customers', 'open', 'promo_interval', 'month_map']
# Drop é um metodo da classe Pandas (quais colunas e sentido); axis 0 = ... | _____no_output_____ | MIT | m03_v01_store_sales_prediction.ipynb | luana-afonso/DataScience-Em-Producao |
Dependencies | import os
import cv2
import shutil
import random
import warnings
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from tensorflow import set_random_seed
from sklearn.utils import class_weight
from sklearn.model_selection import train_test_split
from sklearn.metrics import con... | Using TensorFlow backend.
| MIT | Model backlog/DenseNet169/133 - DenseNet169 - Classification - Refactor.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Load data | hold_out_set = pd.read_csv('../input/aptos-data-split/hold-out.csv')
X_train = hold_out_set[hold_out_set['set'] == 'train']
X_val = hold_out_set[hold_out_set['set'] == 'validation']
test = pd.read_csv('../input/aptos2019-blindness-detection/test.csv')
print('Number of train samples: ', X_train.shape[0])
print('Number o... | Number of train samples: 2929
Number of validation samples: 733
Number of test samples: 1928
| MIT | Model backlog/DenseNet169/133 - DenseNet169 - Classification - Refactor.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Model parameters | # Model parameters
N_CLASSES = X_train['diagnosis'].nunique()
BATCH_SIZE = 16
EPOCHS = 40
WARMUP_EPOCHS = 5
LEARNING_RATE = 1e-4
WARMUP_LEARNING_RATE = 1e-3
HEIGHT = 320
WIDTH = 320
CHANNELS = 3
ES_PATIENCE = 5
RLROP_PATIENCE = 3
DECAY_DROP = 0.5
def kappa(y_true, y_pred, n_classes=5):
y_trues = K.cast(K.argmax(y_t... | _____no_output_____ | MIT | Model backlog/DenseNet169/133 - DenseNet169 - Classification - Refactor.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Pre-procecess images | train_base_path = '../input/aptos2019-blindness-detection/train_images/'
test_base_path = '../input/aptos2019-blindness-detection/test_images/'
train_dest_path = 'base_dir/train_images/'
validation_dest_path = 'base_dir/validation_images/'
test_dest_path = 'base_dir/test_images/'
# Making sure directories don't exist... | _____no_output_____ | MIT | Model backlog/DenseNet169/133 - DenseNet169 - Classification - Refactor.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Data generator | train_datagen=ImageDataGenerator(rescale=1./255,
rotation_range=360,
horizontal_flip=True,
vertical_flip=True)
valid_datagen=ImageDataGenerator(rescale=1./255)
train_generator=train_datagen.flow_from_dataframe(
... | Found 2929 validated image filenames belonging to 5 classes.
Found 733 validated image filenames belonging to 5 classes.
Found 1928 validated image filenames.
| MIT | Model backlog/DenseNet169/133 - DenseNet169 - Classification - Refactor.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Model | def create_model(input_shape, n_out):
input_tensor = Input(shape=input_shape)
base_model = applications.DenseNet169(weights=None,
include_top=False,
input_tensor=input_tensor)
base_model.load_weights('../input/keras-notop/d... | _____no_output_____ | MIT | Model backlog/DenseNet169/133 - DenseNet169 - Classification - Refactor.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Train top layers | model = create_model(input_shape=(HEIGHT, WIDTH, CHANNELS), n_out=N_CLASSES)
for layer in model.layers:
layer.trainable = False
for i in range(-5, 0):
model.layers[i].trainable = True
class_weights = class_weight.compute_class_weight('balanced', np.unique(X_train['diagnosis'].astype('int').values), X_tra... | Epoch 1/5
183/183 [==============================] - 81s 445ms/step - loss: 1.3357 - acc: 0.5731 - kappa: 0.3848 - val_loss: 1.0849 - val_acc: 0.5083 - val_kappa: -0.2198
Epoch 2/5
183/183 [==============================] - 68s 373ms/step - loss: 0.9705 - acc: 0.6499 - kappa: 0.6185 - val_loss: 1.0448 - val_acc: 0.5760... | MIT | Model backlog/DenseNet169/133 - DenseNet169 - Classification - Refactor.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Fine-tune the complete model | for layer in model.layers:
layer.trainable = True
# lrstep = LearningRateScheduler(step_decay)
es = EarlyStopping(monitor='val_loss', mode='min', patience=ES_PATIENCE, restore_best_weights=True, verbose=1)
rlrop = ReduceLROnPlateau(monitor='val_loss', mode='min', patience=RLROP_PATIENCE, factor=DECAY_DROP, min_lr=... | Epoch 1/40
183/183 [==============================] - 139s 757ms/step - loss: 0.6850 - acc: 0.7466 - kappa: 0.8268 - val_loss: 0.5695 - val_acc: 0.7908 - val_kappa: 0.8843
Epoch 2/40
183/183 [==============================] - 87s 478ms/step - loss: 0.5764 - acc: 0.7828 - kappa: 0.8835 - val_loss: 0.5638 - val_acc: 0.78... | MIT | Model backlog/DenseNet169/133 - DenseNet169 - Classification - Refactor.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Model loss graph | sns.set_style("whitegrid")
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex='col', figsize=(20, 18))
ax1.plot(history['loss'], label='Train loss')
ax1.plot(history['val_loss'], label='Validation loss')
ax1.legend(loc='best')
ax1.set_title('Loss')
ax2.plot(history['acc'], label='Train accuracy')
ax2.plot(history['val_... | _____no_output_____ | MIT | Model backlog/DenseNet169/133 - DenseNet169 - Classification - Refactor.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Model Evaluation Confusion Matrix Original thresholds | labels = ['0 - No DR', '1 - Mild', '2 - Moderate', '3 - Severe', '4 - Proliferative DR']
def plot_confusion_matrix(train, validation, labels=labels):
train_labels, train_preds = train
validation_labels, validation_preds = validation
fig, (ax1, ax2) = plt.subplots(1, 2, sharex='col', figsize=(24, 7))
tra... | _____no_output_____ | MIT | Model backlog/DenseNet169/133 - DenseNet169 - Classification - Refactor.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Quadratic Weighted Kappa | def evaluate_model(train, validation):
train_labels, train_preds = train
validation_labels, validation_preds = validation
print("Train Cohen Kappa score: %.3f" % cohen_kappa_score(train_preds, train_labels, weights='quadratic'))
print("Validation Cohen Kappa score: %.3f" % cohen_kappa_score(val... | Train Cohen Kappa score: 0.962
Validation Cohen Kappa score: 0.900
Complete set Cohen Kappa score: 0.950
| MIT | Model backlog/DenseNet169/133 - DenseNet169 - Classification - Refactor.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Apply model to test set and output predictions | step_size = test_generator.n//test_generator.batch_size
test_generator.reset()
preds = model.predict_generator(test_generator, steps=step_size)
predictions = np.argmax(preds, axis=1)
results = pd.DataFrame({'id_code':test['id_code'], 'diagnosis':predictions})
results['id_code'] = results['id_code'].map(lambda x: str(x... | _____no_output_____ | MIT | Model backlog/DenseNet169/133 - DenseNet169 - Classification - Refactor.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Predictions class distribution | fig = plt.subplots(sharex='col', figsize=(24, 8.7))
sns.countplot(x="diagnosis", data=results, palette="GnBu_d").set_title('Test')
sns.despine()
plt.show()
results.to_csv('submission.csv', index=False)
display(results.head()) | _____no_output_____ | MIT | Model backlog/DenseNet169/133 - DenseNet169 - Classification - Refactor.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Introduction Now that you've seen the layers a convnet uses to extract features, it's time to put them together and build a network of your own! Simple to Refined In the last three lessons, we saw how convolutional networks perform **feature extraction** through three operations: **filter**, **detect**, and **condense... | #$HIDE_INPUT$
# Imports
import os, warnings
import matplotlib.pyplot as plt
from matplotlib import gridspec
import numpy as np
import tensorflow as tf
from tensorflow.keras.preprocessing import image_dataset_from_directory
# Reproducability
def set_seed(seed=31415):
np.random.seed(seed)
tf.random.set_seed(see... | _____no_output_____ | Apache-2.0 | notebooks/computer_vision/raw/tut5.ipynb | guesswhohaha/learntools |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.