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 |
|---|---|---|---|---|---|
Applying functionsThis step allows for the application of a function to each group independently. There are many types of operations we can perform here. AggregationThis involves generating a descriptive statistic for each of the groups. | grouped.agg(np.mean) # the mean value of each column (only relevant for one column)
grouped.agg(len) # how many samples does each group have | _____no_output_____ | MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
We can even select a **different** aggregation function for each column. | grouped.agg({'B': len, # number of values in each group
'C': lambda x: len(x.unique()), # unique values in each group
'D': np.sum}) # sum the values of each group | _____no_output_____ | MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
TransformationThis involves changing some values in the data (each group's values are changed in a different manner). For example: | grouped.transform(lambda x: (x - x.min()) / (x.max() - x.min())) # normalize values in each group
grouped.transform(lambda x: (x - x.mean()) / x.std()) # standardize values in each group
grouped.transform(lambda x: x.fillna(x.mean())) # replace nan values with the mean of each group | _____no_output_____ | MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
All the above operations are relevant only for column `'D'` (since it is the only containing numeric values) and are **not** performed inplace. FilteringThis operation filters groups based on some condition. | grouped.filter(lambda x: x['D'].sum() > 15) # keep only groups that have a sum of values in column 'D' greater than 15 | _____no_output_____ | MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
Regular `.apply()`All of the above three effects can be accomplished through `.apply()`. | # Aggregation:
grouped['D'].apply(np.sum) # same as: grouped.apply(lambda x: x['D'].sum())
# Transformation:
grouped['D'].apply(lambda x: (x - x.min()) / (x.max() - x.min()))
# equivalent with: grouped.apply(lambda x: (x['D'] - x['D'].min()) / (x['D'].max() - x['D'].min()))
# Filtering:
grouped.apply(lambda x: x if ... | _____no_output_____ | MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
The "group by" process can be done on multiple indices. However, we won't go more details about this. | df2.groupby(['A','B']).sum() # roughly equivalent to the pivot_table we did previously | _____no_output_____ | MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
Shape manipulationUnlike *numpy* arrays, *DataFrames* usually aren't made to be reshaped. Nevertheless, *pandas* offers support for stacking and unstacking. | # The stack() method “compresses” a level in the DataFrame’s columns.
stk = df.stack()
print(stk)
# The inverse operation is unstack()
stk.unstack() | _____no_output_____ | MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
Input / output operationsThe most common format associated with *DataFrames* is csv. CSV Writing a *DataFrame* to a csv file can be accomplished with a single line. | df.to_csv('tmp/my_dataframe.csv') # writes df to file 'my_dataframe.csv' in folder 'tmp' | _____no_output_____ | MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
`DataFrame.to_csv()` by default stores **both row and column labels**. Usually we don't want to write the row labels and sometimes we might not even want to write the column labels. This can be accomplished with the following arguments: | df.to_csv('tmp/my_dataframe.csv', header=False, index=False) | _____no_output_____ | MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
To load a csv into a *DataFrame* we can use `pd.read_csv()`. | tmp = pd.read_csv('tmp/my_dataframe.csv')
tmp | _____no_output_____ | MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
As you can see, by default, *pandas* uses the first line of the csv as its column names. If this isn't desirable, we can use the `header` argument. | tmp = pd.read_csv('tmp/my_dataframe.csv', header=None)
tmp | _____no_output_____ | MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
MS ExcelPandas can read and write to excel files through two simple functions: `pd.read_excel(file.xlsx)` and `DataFrame.to_excel(file.xlsx)`. Note that this requires an extra library (`xlrd`) Other options Other options include pickle, json, SQL databases, clipboard, URLs and even integration with the google analytic... | url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data'
data = pd.read_csv(url, header=None)
data.columns = ['age', 'workclass', 'fnlwgt', 'education', 'education-num', 'marital-status',
'occupation', 'relationship', 'race', 'sex', 'capital-gain', 'capital-loss',
... | _____no_output_____ | MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
The first thing we want to do is inspect the shape of the *DataFrame*. | data.shape | _____no_output_____ | MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
Our data contains 32561 rows and 15 columns. If we take a look at the [description](https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.names) of the dataset we see that it contains both continuous valued variables (age, working hours etc.) and categorical ones (sex, relationship etc.). When performin... | data.head() | _____no_output_____ | MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
For each variable we'll see what values it can take. | print('minimum:', data['age'].min())
print('maximum:', data['age'].max())
print('mean: ', data['age'].mean()) | minimum: 17
maximum: 90
mean: 38.58164675532078
| MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
`age` is a numeric variable that has a minimum value of $17$ and a max of $90$. While we can run any descriptive statistics on this variable, to have a complete perspective we must visualize it (see a later tutorial on how to do so). | data['workclass'].value_counts() | _____no_output_____ | MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
Here we find our first occurrence of missing values. In this dataset, these are represented by question marks (`?`). | print('minimum:', data['fnlwgt'].min())
print('maximum:', data['fnlwgt'].max())
print('mean: ', data['fnlwgt'].mean()) | minimum: 12285
maximum: 1484705
mean: 189778.36651208502
| MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
This variable is continuous-valued and represents the demographics of the individual. >Description of fnlwgt (final weight)> The weights on the CPS files are controlled to independent estimates of the civilian noninstitutional population of the US. These are prepared monthly for us by Population Division here at the... | data['education'].value_counts()
data['education-num'].value_counts() | _____no_output_____ | MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
The latter is simply an encoded version of the first. | data['marital-status'].value_counts()
data['occupation'].value_counts()
data['relationship'].value_counts()
data['race'].value_counts()
data['sex'].value_counts()
print(len(data[data['capital-gain'] == 0]))
print(len(data[data['capital-gain'] != 0]))
print(len(data[data['capital-loss'] == 0]))
print(len(data[data['capi... | _____no_output_____ | MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
Data PreparationNext, well look at several ways we might have to manipulate our data, including data cleaning, imputing and transforming Because the unknown values are represented as question marks this dataset, we need to handle them. Example: fill the occupation with the most frequent element | most_freq = data['occupation'].mode()[0] # find the most common element
data['occupation'] = data['occupation'].apply(lambda x: most_freq if x == ' ?' else x)
# the line above first keeps just the column that represents the occupations from the dataframe
# then it applies a function which checks if those values are q... | _____no_output_____ | MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
Notice that all elements are proceeded by a whitespace? Can we remove it and clean our data? | print('Before cleaning: `{}`'.format(data.occupation[0]))
data.occupation = data['occupation'].apply(lambda x: x.strip())
print('After cleaning: `{}`'.format(data.occupation[0])) | Before cleaning: ` Adm-clerical`
After cleaning: `Adm-clerical`
| MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
Exercise 2Fill the missing values of the DataFrame's `native-country` column with whatever strategy you wish. SolutionThis time we'll drop the rows containing missing values. | print('DataFrame length:', len(data))
print('missing: ', len(data[data['native-country'] == ' ?']))
data = data.drop(data[data['native-country'] == ' ?'].index)
print('DataFrame length:', len(data))
print('missing: ', len(data[data['native-country'] == ' ?'])) | DataFrame length: 32561
missing: 583
DataFrame length: 31978
missing: 0
| MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
Finally, let's try to **encode** our data. To illustrate how they would be performed in *pandas*: We will first encode the `education` variable preserving its sequential nature. Next, we will perform a custom encoding on the `marital-status` variable so that we keep only two categories (i.e. currently married and not)... | data['education'] = data['education'].apply(lambda x: x.strip()) # clean whitespace on category
# Create a dictionary mapping the categories to their encodings.
# This has to be done manually as the exact sequence has to be taken into consideration.
mappings = {'Preschool': 1, '1st-4th': 2, '5th-6th': 3, '7th-8th': 4... | _____no_output_____ | MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
Next, `marital-status`. | data['marital-status'] = np.where(data["marital-status"] == ' Married-civ-spouse', 1, 0)
# the above function replaces ' Married-civ-spouse' with 1 and all the rest with 0
data['marital-status'].value_counts() | _____no_output_____ | MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
After this, we'll one-hot encode all rest categorical variables. Note that we haven't dealt with all missing values yet (in a real scenario we should). | print('Before one-hot encoding:', data.shape)
data = pd.get_dummies(data) # one-hot encode all categorical variables
print('After one-hot encoding: ', data.shape) | Before one-hot encoding: (31978, 15)
After one-hot encoding: (31978, 87)
| MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
Finally, we'll see how we can split numerical values to separate bins, in order to convert them to categorical. This time around we won't replace the numerical data but create a new variable. | data['age_categories'] = pd.cut(data.age, 3, labels=['young', 'middle aged', 'old'])
data['age_categories'].value_counts() | _____no_output_____ | MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
When binning would usually want each bin to have the same number of samples. In order to do this we need to manually find there to cut each bin input the *cut points* instead of the number of bins we want. But we'll leave that up to you! Bonus material: Data wrangling:- [extended data wrangling tutorial](http://nbview... | df6 = pd.DataFrame({'fname':['George', 'george ', 'GEORGIOS', 'Giorgos', ' Peter', 'Petet'],
'sname':['Papadopoulos', 'alexakos ', 'Georgiou', 'ANTONOPOULOS', ' Anastasiou', 'Κ'],
'age': [46, 34, 75, 24, 54, 33]})
df6 | _____no_output_____ | MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
When looking at the example above, several inconsistencies become apparent. The first thing we want to do when dealing with strings is to convert them all to lowercase (or uppercase depending on preference) and remove preceding and succeeding whitespace. | def clean_text(text):
text = text.strip() # strip whitespace
text = text.lower() # convert to lowercase
return text
df6['fname'] = df6['fname'].apply(clean_text)
df6['sname'] = df6['sname'].apply(clean_text)
# same could be done through a lambda function
# df.fname.apply(lambda x: x.strip().lower())
df... | _____no_output_____ | MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
Another problem originates from the way each name was entered. There are two ways to deal with this, one is to manually look and change errors, and the other is to compare the strings to find differences.We are going to try the second, through the python package [fuzzywuzzy](https://github.com/seatgeek/fuzzywuzzy). | from fuzzywuzzy import process
process.extract('george', df6['fname'], limit=None) | c:\users\thano\appdata\local\programs\python\python36\lib\site-packages\fuzzywuzzy\fuzz.py:35: UserWarning: Using slow pure-python SequenceMatcher. Install python-Levenshtein to remove this warning
warnings.warn('Using slow pure-python SequenceMatcher. Install python-Levenshtein to remove this warning')
| MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
*Fuzzywuzzy* compares strings and outputs a score depending on how close they are. Let's replace the close ones: | def replace_matches_in_column(df, column, target_string, min_ratio=50):
# find unique elements in specified column
strings = df[column].unique()
# see how close these elements are to the target string
matches = process.extract(target_string, strings, limit=None)
# keep only the closest on... | _____no_output_____ | MIT | notebooks/16_pandas.ipynb | sniafas/python_ml_tutorial |
Обработка и разбор данных от Semantic Hub Клетки, которые выводят информацию о данных предоставленных Semantic Hub, были очищены | import pandas as pd
import os
from tqdm import tqdm
import re
import json
from collections import Counter
import ast
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import nltk | _____no_output_____ | MIT | preprocessing_pipeline.ipynb | toskn/diploma |
Заходим в папку с полученными данными и получаем список файлов | # путь к папке со всеми файлами
path = '/Users/egor/Desktop/SemanticHub/diploma/relatives_data/jsons'
list_of_files = os.listdir(path) # список названий файлов | _____no_output_____ | MIT | preprocessing_pipeline.ipynb | toskn/diploma |
Делаем список json объектов, с которыми удобно работать | list_full_file_json = [] # список, в котором каждый элемент - содержимое одного файла
# цикл для прохода по всем файлам и сбора их содержимого
for filename in tqdm(list_of_files):
# абсолютный путь к единичному файлу
path_single = path + '/' + filename
# открываем
with open(path_single) as file:
... | _____no_output_____ | MIT | preprocessing_pipeline.ipynb | toskn/diploma |
Подготовим поле *text* к обработке | # для этого удалим все, кроме текста самого сообщения
# вообще можно будет пытаться еще пол вытягивать и всякие другие данные типа даты, города, имени
# 1
# текст окружен двумя пробелами странной длины, это нам поможет
pattern = re.compile(' (.*) ')
# это будет список номеров те... | _____no_output_____ | MIT | preprocessing_pipeline.ipynb | toskn/diploma |
Поле **text** подготовлено, можно провести количественный анализ и построить разные визуализации Анализ текстового содержания – поле *text* Для проведения анализа заполним датафрейм пандас важными для анализа характеристиками:+ количество слов в каждом документе+ количество предложений в каждом документе+ количество ц... | # список количеств слов
words_list = []
# паттерн для деления по пробелам/переносам
pattern = re.compile('\s+')
for message in tqdm(list_full_file_json):
words_message = len(pattern.split(message['text']))
words_list.append(words_message)
# посмотрим на самые частые количества слов на одно сообщение
c = Counte... | _____no_output_____ | MIT | preprocessing_pipeline.ipynb | toskn/diploma |
Распределение количества предложений в каждом документе | # список количеств слов
sentences_list = []
# паттерн для деления на предложения, объяснение:(https://regex101.com/r/he9d1P/1)
# почти всегда делит правильно, в предлоежниях с именем и отчеством через точку ошибается на +1, что
# для выборки в 400к незначительно
pattern = re.compile('.*?(\.|\?|\!|…)(?= *[А-Я]|$)')
for... | _____no_output_____ | MIT | preprocessing_pipeline.ipynb | toskn/diploma |
Количество кореференциальных цепочек в каждом документе | # скрипт для приведения каждого размеченного для кореференции элемента к JSON виду
# для удобного обращения к параметрам
files_chain_list = []
for message in tqdm(list_full_file_json):
list_coref_ent = message['annotation_sets']['']['annotations']
message_chain_list = []
for entity in list_coref_ent:
... | _____no_output_____ | MIT | preprocessing_pipeline.ipynb | toskn/diploma |
Распределение количества слов, выделенных, как значимые для кореференции. | # сделаем список, каждый элемент которого - количество выделенных сущностей на файл
chain_entity_count_list = []
for chain_list in tqdm(files_chain_list):
file_chain = len(chain_list)
chain_entity_count_list.append(file_chain)
# посмотрим на самые частые количества выделенных слов на одно сообщение
c = Counter... | _____no_output_____ | MIT | preprocessing_pipeline.ipynb | toskn/diploma |
Общее количество кореференциальных цепочек | # список количества цепочек в сообщении
c = Counter(chain_amount_list).most_common()
# счетчик цепочек
counter = 0
for pair in tqdm(c):
counter += pair[0]*pair[1]
counter | 100%|██████████| 64/64 [00:00<00:00, 292413.35it/s]
| MIT | preprocessing_pipeline.ipynb | toskn/diploma |
Общее количество элементов в кореференциальных цепочках | # список количества выделенных слов в сообщении
c = Counter(chain_entity_count_list).most_common()
# счетчик цепочек
counter = 0
for pair in tqdm(c):
counter += pair[0]*pair[1]
counter | 100%|██████████| 136/136 [00:00<00:00, 245028.07it/s]
| MIT | preprocessing_pipeline.ipynb | toskn/diploma |
Отношение количества слов в сообщении к количеству цепочек | # количество слов по сообщениям уже есть
# количество цепочек по сообщениям уже есть
# осталось посчитать количество каждых возможных пар
word_chain_count_list = []
for word_count, chain_count in zip(words_list, chain_amount_list):
word_chain_count_list.append((word_count, chain_count, ))
c = Counter(word_chain_cou... | _____no_output_____ | MIT | preprocessing_pipeline.ipynb | toskn/diploma |
Перевод данных в формат CoNLL Имеющиеся переменные:+ количество слов+ количество предложений+ количество кореференциальных цеопчек+ количество выделенных слов+ список джейсонов аннотаций+ список полных джейсонов | words_list[:10]
sentences_list[:10]
files_chain_list[:1]
list_full_file_json[8]['text']
conll_df = pd.DataFrame({'doc_name': [], 'zeros': [], 'word_num_sent': [], 'sent_entry': [], 'pos': [], 'star1': [], 'empty1': [], 'empty2': [],'empty3': [],'empty4': [],'empty5': [], 'star2': [], 'coref': [],})
conll_df.head()
nam... | _____no_output_____ | MIT | preprocessing_pipeline.ipynb | toskn/diploma |
Результаты 180 часов работы программы.Было обработано и внесено в датафрейм 11 932 678 элементов из 64 851 795.Осталось обработать 52 919 117 элементовНа настоящем этапе правильно будет остановиться на этом и выделить доступные компьютерные мощности на запуск следующих этапов пайплайна. | # нужна функция для добавления колонки номера предложения зфтвф
sentence_number_list = []
i = 0
for document in tqdm(tagged_sentences_list):
for sentence in document:
for word in sentence:
sentence_number_list.append(i)
i += 1
len(sentence_number_list)
sentence_number_list_180h = sentenc... | _____no_output_____ | MIT | preprocessing_pipeline.ipynb | toskn/diploma |
Заменить тире на два нижних подчеркивания (__) | def remean_points(cell):
cell = "__"
return cell
conll_df.empty5 = conll_df.empty5.apply(remean_points)
conll_df.head() | _____no_output_____ | MIT | preprocessing_pipeline.ipynb | toskn/diploma |
Замена успешна Заменить двойные кавычки | changed_cells = []
def remean_points(cell):
if str(cell) == '"':
cell = "'"
changed_cells.append(1)
else:
changed_cells.append(0)
return cell
conll_df.sent_entry.apply(remean_points)
len(changed_cells)
[i for i, e in enumerate(changed_cells) if e == 1] | _____no_output_____ | MIT | preprocessing_pipeline.ipynb | toskn/diploma |
Двойных кавычек нет, можно будет спокойно удалять. | # правкой тегов имеет смысл заняться после получения результатов на имеющемся тегсете. | _____no_output_____ | MIT | preprocessing_pipeline.ipynb | toskn/diploma |
Подготовка документа | conll_df['join'] = conll_df['doc_name'] + ' ' + conll_df['zeros'].astype(str) + ' ' + conll_df['word_num_sent'].astype(str) + ' ' + conll_df['sent_entry'] + ' ' + conll_df['pos'] + ' ' + conll_df['star1'] + ' ' + conll_df['empty1'] + ' ' + conll_df['empty2'... | Exception ignored in: <function tqdm.__del__ at 0x7fba6d99a4d0>
Traceback (most recent call last):
File "/Users/egor/opt/anaconda3/lib/python3.7/site-packages/tqdm/std.py", line 1145, in __del__
self.close()
File "/Users/egor/opt/anaconda3/lib/python3.7/site-packages/tqdm/std.py", line 1274, in close
if sel... | MIT | preprocessing_pipeline.ipynb | toskn/diploma |
Деление на подгруппы для заданий берта | from sklearn.model_selection import train_test_split
RANDOM_SEED = 1
np.random.seed(RANDOM_SEED)
!pwd | /Users/egor/Desktop/SemanticHub/diploma
| MIT | preprocessing_pipeline.ipynb | toskn/diploma |
К сожалению тетрадка упала, поэтому придется загрузить документ сначала. | path = 'diploma_data_12m.txt'
with open(path) as f:
contents = f.readlines()
contents[:5]
len(contents)
# удаление
# pattern = re.compile('\"')
conll = []
for row in tqdm(contents):
row = re.sub(r'"','', row)
conll.append(row)
len(conll) | _____no_output_____ | MIT | preprocessing_pipeline.ipynb | toskn/diploma |
Лишние артефактные кавычки очищены. | # файл со всеми вхождениями
with open('conll_clear_12m.txt', 'w') as f:
f.writelines(conll) | _____no_output_____ | MIT | preprocessing_pipeline.ipynb | toskn/diploma |
В окошки ниже впишу номера кусков **conll [ ]** для быстрого создания вручную файлов для трейн/тест/дев, таким образом можно будет избежать нарезки предложений. train = 95%, dev = 2.5%, test = 2.5% | # файл test
# group 1 паттерна будет имя документа, ноль и пробелы для уверенности, но матч должен и без них работать
pattern = re.compile(r'(.*xml) 0')
# заполним позицию предыдущего файла первым файлом в списке для удобства.
previous_filename = pattern.match(conll[0]).group(1)
# счетчик документов
doc_num =... | _____no_output_____ | MIT | preprocessing_pipeline.ipynb | toskn/diploma |
DBT 1. Activate virtual environment, because airflow and dbt have both a lot of dependencies | source /home/flo/dbt-env/bin/activate | _____no_output_____ | MIT | notebooks/bash.ipynb | elcolumbio/waipawama |
2. Compile your sql model to a runable query, its nice for debugging | dbt compile --vars 'timespan: 2018-10' | _____no_output_____ | MIT | notebooks/bash.ipynb | elcolumbio/waipawama |
2. If you only want to run 1 modal a time | dbt run --models bankkonto_monthly --vars 'timespan: 2018-01' | _____no_output_____ | MIT | notebooks/bash.ipynb | elcolumbio/waipawama |
Config | class Config:
n_folds=10
random_state=42
tbs = 1024
vbs = 512
data_path="data"
result_path="results"
models_path="models" | _____no_output_____ | MIT | work2.ipynb | Mo5mami/kinasa_2nd_place |
plot and util | def write_to_txt(file_name,column):
with open(file_name, 'w') as f:
for item in column:
f.write("%s\n" % item) | _____no_output_____ | MIT | work2.ipynb | Mo5mami/kinasa_2nd_place |
Load data | train=pd.read_csv(os.path.join(Config.data_path,"train.csv"))
test=pd.read_csv(os.path.join(Config.data_path,"test.csv"))
aae=pd.read_csv(os.path.join(Config.data_path,"amino_acid_embeddings.csv"))
submission=pd.read_csv(os.path.join(Config.data_path,"SampleSubmission.csv")) | _____no_output_____ | MIT | work2.ipynb | Mo5mami/kinasa_2nd_place |
Prepare and split data | train["Sequence_len"]=train["Sequence"].apply(lambda x : len(x))
test["Sequence_len"]=test["Sequence"].apply(lambda x : len(x))
max_seq_length = 550 # max seq length in this data set is 550
#stratified k fold
train["folds"]=-1
kf = StratifiedKFold(n_splits=Config.n_folds, random_state=Config.random_state, shuffle=True... | _____no_output_____ | MIT | work2.ipynb | Mo5mami/kinasa_2nd_place |
Model | def model():
name = "seq"
dropout_rate = 0.1
learning_rate = 0.001
sequnce = Input([None],name="sequnce")
EMB_layer = Embedding(input_dim = len(voc_set)+1, output_dim = 64, name = "emb_layer")
GRU_layer_2 = GRU(units=256, name = "gru_2", return_sequences = False)
BIDIR_layer_2 = Bi... | _____no_output_____ | MIT | work2.ipynb | Mo5mami/kinasa_2nd_place |
training | def trainn(fold):
model_path=f"model_{fold}.h5"
df_train = train[train["folds"] != fold].reset_index(drop=True)
df_valid = train[train["folds"] == fold].reset_index(drop=True)
write_to_txt(f"data/train_{fold}.txt",df_train.Sequence)
write_to_txt(f"data/valid_{fold}.txt",df_valid.Sequence)
train_... | _____no_output_____ | MIT | work2.ipynb | Mo5mami/kinasa_2nd_place |
Dependencies | import json, warnings, shutil, glob
from jigsaw_utility_scripts import *
from scripts_step_lr_schedulers import *
from transformers import TFXLMRobertaModel, XLMRobertaConfig
from tensorflow.keras.models import Model
from tensorflow.keras import optimizers, metrics, losses, layers
SEED = 0
seed_everything(SEED)
warnin... | _____no_output_____ | MIT | Model backlog/Train/75-jigsaw-fold1-xlm-roberta-large-cls-tail.ipynb | dimitreOliveira/Jigsaw-Multilingual-Toxic-Comment-Classification |
TPU configuration | strategy, tpu = set_up_strategy()
print("REPLICAS: ", strategy.num_replicas_in_sync)
AUTO = tf.data.experimental.AUTOTUNE | Running on TPU grpc://10.0.0.2:8470
REPLICAS: 8
| MIT | Model backlog/Train/75-jigsaw-fold1-xlm-roberta-large-cls-tail.ipynb | dimitreOliveira/Jigsaw-Multilingual-Toxic-Comment-Classification |
Load data | database_base_path = '/kaggle/input/jigsaw-data-split-roberta-192-ratio-2-upper/'
k_fold = pd.read_csv(database_base_path + '5-fold.csv')
valid_df = pd.read_csv("/kaggle/input/jigsaw-multilingual-toxic-comment-classification/validation.csv",
usecols=['comment_text', 'toxic', 'lang'])
print('Tra... | Train samples: 400830
| MIT | Model backlog/Train/75-jigsaw-fold1-xlm-roberta-large-cls-tail.ipynb | dimitreOliveira/Jigsaw-Multilingual-Toxic-Comment-Classification |
Model parameters | base_path = '/kaggle/input/jigsaw-transformers/XLM-RoBERTa/'
config = {
"MAX_LEN": 192,
"BATCH_SIZE": 128,
"EPOCHS": 4,
"LEARNING_RATE": 1e-5,
"ES_PATIENCE": None,
"base_model_path": base_path + 'tf-xlm-roberta-large-tf_model.h5',
"config_path": base_path + 'xlm-roberta-large-config.json'
}
with open('... | _____no_output_____ | MIT | Model backlog/Train/75-jigsaw-fold1-xlm-roberta-large-cls-tail.ipynb | dimitreOliveira/Jigsaw-Multilingual-Toxic-Comment-Classification |
Learning rate schedule | lr_min = 1e-7
lr_start = 1e-7
lr_max = config['LEARNING_RATE']
step_size = len(k_fold[k_fold['fold_1'] == 'train']) // config['BATCH_SIZE']
total_steps = config['EPOCHS'] * step_size
hold_max_steps = 0
warmup_steps = step_size * 1
decay = .9997
rng = [i for i in range(0, total_steps, config['BATCH_SIZE'])]
y = [expone... | Learning rate schedule: 1e-07 to 9.84e-06 to 1.06e-06
| MIT | Model backlog/Train/75-jigsaw-fold1-xlm-roberta-large-cls-tail.ipynb | dimitreOliveira/Jigsaw-Multilingual-Toxic-Comment-Classification |
Model | module_config = XLMRobertaConfig.from_pretrained(config['config_path'], output_hidden_states=False)
def model_fn(MAX_LEN):
input_ids = layers.Input(shape=(MAX_LEN,), dtype=tf.int32, name='input_ids')
attention_mask = layers.Input(shape=(MAX_LEN,), dtype=tf.int32, name='attention_mask')
base_model = TF... | _____no_output_____ | MIT | Model backlog/Train/75-jigsaw-fold1-xlm-roberta-large-cls-tail.ipynb | dimitreOliveira/Jigsaw-Multilingual-Toxic-Comment-Classification |
Train | # Load data
x_train = np.load(base_data_path + 'x_train.npy')
y_train = np.load(base_data_path + 'y_train_int.npy').reshape(x_train.shape[1], 1).astype(np.float32)
x_valid_ml = np.load(database_base_path + 'x_valid.npy')
y_valid_ml = np.load(database_base_path + 'y_valid.npy').reshape(x_valid_ml.shape[1], 1).astype(np.... | Train for 5010 steps, validate for 62 steps
EPOCH 1/4
time: 1715.0s loss: 0.2442 auc: 0.9590 val_loss: 0.2856 val_auc: 0.9211
EPOCH 2/4
time: 1520.0s loss: 0.1623 auc: 0.9816 val_loss: 0.2865 val_auc: 0.9164
EPOCH 3/4
time: 1519.8s loss: 0.1449 auc: 0.9852 val_loss: 0.3106 val_auc: 0.9086
EPOCH 4/4
time: 1520.0s lo... | MIT | Model backlog/Train/75-jigsaw-fold1-xlm-roberta-large-cls-tail.ipynb | dimitreOliveira/Jigsaw-Multilingual-Toxic-Comment-Classification |
Model loss graph | plot_metrics(history)
# ML fine-tunned preds
plot_metrics(history_ml) | _____no_output_____ | MIT | Model backlog/Train/75-jigsaw-fold1-xlm-roberta-large-cls-tail.ipynb | dimitreOliveira/Jigsaw-Multilingual-Toxic-Comment-Classification |
Model evaluation | # display(evaluate_model(k_fold, 1, label_col='toxic_int').style.applymap(color_map)) | _____no_output_____ | MIT | Model backlog/Train/75-jigsaw-fold1-xlm-roberta-large-cls-tail.ipynb | dimitreOliveira/Jigsaw-Multilingual-Toxic-Comment-Classification |
Confusion matrix | # train_set = k_fold[k_fold['fold_1'] == 'train']
# validation_set = k_fold[k_fold['fold_1'] == 'validation']
# plot_confusion_matrix(train_set['toxic_int'], train_set['pred_1'],
# validation_set['toxic_int'], validation_set['pred_1']) | _____no_output_____ | MIT | Model backlog/Train/75-jigsaw-fold1-xlm-roberta-large-cls-tail.ipynb | dimitreOliveira/Jigsaw-Multilingual-Toxic-Comment-Classification |
Model evaluation by language | display(evaluate_model_lang(valid_df, 1).style.applymap(color_map))
# ML fine-tunned preds
display(evaluate_model_lang(valid_df, 1, pred_col='pred_ml').style.applymap(color_map)) | _____no_output_____ | MIT | Model backlog/Train/75-jigsaw-fold1-xlm-roberta-large-cls-tail.ipynb | dimitreOliveira/Jigsaw-Multilingual-Toxic-Comment-Classification |
Visualize predictions | pd.set_option('max_colwidth', 120)
print('English validation set')
display(k_fold[['comment_text', 'toxic'] + [c for c in k_fold.columns if c.startswith('pred')]].head(10))
print('Multilingual validation set')
display(valid_df[['comment_text', 'toxic'] + [c for c in valid_df.columns if c.startswith('pred')]].head(10)) | English validation set
| MIT | Model backlog/Train/75-jigsaw-fold1-xlm-roberta-large-cls-tail.ipynb | dimitreOliveira/Jigsaw-Multilingual-Toxic-Comment-Classification |
Test set predictions | x_test = np.load(database_base_path + 'x_test.npy')
test_preds = model.predict(get_test_dataset(x_test, config['BATCH_SIZE'], AUTO))
submission = pd.read_csv('/kaggle/input/jigsaw-multilingual-toxic-comment-classification/sample_submission.csv')
submission['toxic'] = test_preds
submission.to_csv('submission.csv', index... | _____no_output_____ | MIT | Model backlog/Train/75-jigsaw-fold1-xlm-roberta-large-cls-tail.ipynb | dimitreOliveira/Jigsaw-Multilingual-Toxic-Comment-Classification |
Sparse GP Regression 14th January 2014 James Hensman 29th September 2014 Neil Lawrence (added sub-titles, notes and some references). This example shows the variational compression effect of so-called 'sparse' Gaussian processes. In particular we show how using the variational free energy framework of [Titsias, 2009](... | %matplotlib inline
%config InlineBackend.figure_format = 'svg'
import GPy
import numpy as np
np.random.seed(101) | _____no_output_____ | BSD-3-Clause | GPy/sparse_gp_regression.ipynb | olumighty1/notebook |
Sample FunctionNow we'll sample a Gaussian process regression problem directly from a Gaussian process prior. We'll use an exponentiated quadratic covariance function with a lengthscale and variance of 1 and sample 50 equally spaced points. | N = 50
noise_var = 0.05
X = np.linspace(0,10,50)[:,None]
k = GPy.kern.RBF(1)
y = np.random.multivariate_normal(np.zeros(N),k.K(X)+np.eye(N)*np.sqrt(noise_var)).reshape(-1,1) | _____no_output_____ | BSD-3-Clause | GPy/sparse_gp_regression.ipynb | olumighty1/notebook |
Full Gaussian Process FitNow we use GPy to optimize the parameters of a Gaussian process given the sampled data. Here, there are no approximations, we simply fit the full Gaussian process. | m_full = GPy.models.GPRegression(X,y)
m_full.optimize('bfgs')
m_full.plot()
print m_full |
Name : GP regression
Objective : 50.0860723468
Number of Parameters : 3
Number of Optimization Parameters : 3
Updates : True
Parameters:
[1mGP_regression. [0;0m | value | constraints | priors
[1mrbf.variance [0;0m | 1.65824860473 | +ve |
[1mrbf.lengthsc... | BSD-3-Clause | GPy/sparse_gp_regression.ipynb | olumighty1/notebook |
A Poor `Sparse' GP FitNow we construct a sparse Gaussian process. This model uses the inducing variable approximation and initialises the inducing variables in two 'clumps'. Our initial fit uses the *correct* covariance function parameters, but a badly placed set of inducing points. | Z = np.hstack((np.linspace(2.5,4.,3),np.linspace(7,8.5,3)))[:,None]
m = GPy.models.SparseGPRegression(X,y,Z=Z)
m.likelihood.variance = noise_var
m.plot()
print m |
Name : sparse gp
Objective : 260.809828016
Number of Parameters : 9
Number of Optimization Parameters : 9
Updates : True
Parameters:
[1msparse_gp. [0;0m | value | constraints | priors
[1minducing inputs [0;0m | (6, 1) | |
[1mrbf.variance [0;0m |... | BSD-3-Clause | GPy/sparse_gp_regression.ipynb | olumighty1/notebook |
Notice how the fit is reasonable where there are inducing points, but bad elsewhere. Optimizing Covariance ParametersNext, we will try and find the optimal covariance function parameters, given that the inducing inputs are held in their current location. | m.inducing_inputs.fix()
m.optimize('bfgs')
m.plot()
print m |
Name : sparse gp
Objective : 53.9735537142
Number of Parameters : 9
Number of Optimization Parameters : 3
Updates : True
Parameters:
[1msparse_gp. [0;0m | value | constraints | priors
[1minducing inputs [0;0m | (6, 1) | fixed |
[1mrbf.variance ... | BSD-3-Clause | GPy/sparse_gp_regression.ipynb | olumighty1/notebook |
The poor location of the inducing inputs causes the model to 'underfit' the data. The lengthscale is much longer than the full GP, and the noise variance is larger. This is because in this case the Kullback Leibler term in the objective free energy is dominating, and requires a larger lengthscale to improve the quality... | m.randomize()
m.Z.unconstrain()
m.optimize('bfgs')
m.plot() | _____no_output_____ | BSD-3-Clause | GPy/sparse_gp_regression.ipynb | olumighty1/notebook |
The inducing points spread out to cover the data space, but the fit isn't quite there. We can try increasing the number of the inducing points. Train with More Inducing PointsNow we try 12 inducing points, rather than the original six. We then compare with the full Gaussian process likelihood. | Z = np.random.rand(12,1)*12
m = GPy.models.SparseGPRegression(X,y,Z=Z)
m.optimize('bfgs')
m.plot()
m_full.plot()
print m.log_likelihood(), m_full.log_likelihood() | [[-50.09844715]] -50.0860723468
| BSD-3-Clause | GPy/sparse_gp_regression.ipynb | olumighty1/notebook |
1. Experimentally prove weak law of large numbers. $$\lim_{n\to \infty} P[\vert M_n-m_x\vert>\epsilon]=0$$ Where, $M_n$ is the sample mean, $m_x$ is the actual mean, $\epsilon$ is a small positive number and $n$ is the number of sample points. | #Law of weak numbers
#write code here
#sample = np.random.normal(0, 1, 1000)
#p= np.zeros(sample.shape)
#for i in range(0,9999):
#p[i]=np.sum(sample[0:i])/(i+1)
count=0
for i in range (1,1000):
sample = np.random.normal(0, 1, 1000) #n=1000
meanv= np.mean(sample)
if meanv<0.1: #epsilon
count+=1
count... | 0.997
| MIT | CT/314_statistical_communication_theory/mv_joshi/2019/lab_sessions/lab8.ipynb | u-square2/AcadVault |
2. Experimentally prove strong law of large numbers. $$P[\lim_{n\to \infty} M_n=m_x]=1,$$ Where, $M_n$ is the sample mean, $m_x$ is the actual mean, and $n$ is the number of sample points. | #Law of strong numbers
#write code here
itr=np.arange(10000)
actual_mean=np.zeros(10000)
sample = np.random.normal(0, 1, 10000)
Mn= np.zeros(sample.shape)
for i in range(0,9999):
Mn[i]=np.sum(sample[0:i])/(i+1)
plt.figure()
plt.plot(itr,actual_mean,label='actual_mean')
plt.plot(itr,Mn,label='Mn')
plt.legend()
plt.f... | _____no_output_____ | MIT | CT/314_statistical_communication_theory/mv_joshi/2019/lab_sessions/lab8.ipynb | u-square2/AcadVault |
3. Experimentally prove central limit theorem. $$\frac{S_N-E[S_N]}{\sqrt{var(S_N)}}=\frac{\sum_{i=1}^{N}{X_i}-\sum_{i=1}^{N}{E[X_i]}}{\sqrt{\sum_{i=1}^{N}{var[X_i]}}}\to N(0,1)$$,Where, $X_1, X_2, . . , X_N$ are random variables with mean $E[X_i]$ and variance $var[X_i]$, $i=1,2,…, N$. | N=100
M=10000
x = np.zeros([M,N])
#write code here
x=np.random.uniform(0,10,[M,N])
plt.hist(x[:,0],normed=True)
plt.figure()
Sn=np.sum(x,0)
Sn_mean=np.mean(Sn)
sig=np.var(Sn)
lim=(Sn-Sn_mean)/np.sqrt(sig)
#write code here
plt.figure()
plt.hist(lim,normed=True)
x=np.linspace(-4,4,1000)
fx=(1/(np.sqrt(2*np.pi)))*np.ex... | _____no_output_____ | MIT | CT/314_statistical_communication_theory/mv_joshi/2019/lab_sessions/lab8.ipynb | u-square2/AcadVault |
Generate a NumPy array containing 301 values from 0 to 3 and assign to x, then Transform x by applying the function: `y = -(x^2) + 3x - 1` and assign the resulting array of transformed values to y. | def transform(x):
return -(x**2) + (3 * x) - 1
x = np.linspace(0, 3, 301)
f = lambda x : -(x**2) + (3 * x) - 1
y = f(x) | _____no_output_____ | Unlicense | dataquest/notebooks/lesson_linear_nonlinear_functions/Lesson - Linear and Nonlinear Functions.ipynb | monocongo/datascience_portfolio |
Plot the X vs. Y using a simple matplotlib line plot: | %matplotlib inline
plt.plot(x, y) | _____no_output_____ | Unlicense | dataquest/notebooks/lesson_linear_nonlinear_functions/Lesson - Linear and Nonlinear Functions.ipynb | monocongo/datascience_portfolio |
Hash Tables**Attendance code: 4482**Arrays have O(1) data retrieval _if you have the index_.If you have to search for the data/index, arrays are O(n). That's a bummer.What if we had a magic function that would tell you the index for a given "key"?Store data as _key/value pairs_.With `dict`s:```d = {}d["key"] = value`... | d = {}
d["goatcount"] = 9
d["key"] = 'value'
print(d)
print(d["key"]) # should print 'value', should also take O(1) time over the number of keys
class HashTable:
def __init__(self):
self.table = [None] * 8 # Build an array of 8 elements to hold values
def hashing_function(self, key):
""... | _____no_output_____ | MIT | CS42_DS_&_A_1_M2_Hash_Tables_I.ipynb | juancaruizc/CS42-DS-A-1-M2-Hash-Tables-I |
Applications of Hash TablesGoing to use `dict` for these.```d = {} PUTd["key"] = value GETprint(d["key"])``` Counting Items | #%%timeit
a = [1,6,7,9,5,3,3,5,7,8,8,6,5,4,3,4,6,7,8,8,5,4,6,7,8,9,7] * 70
def counter1(): # O(n^2)
for e in a:
count = 0
for e2 in a:
if e == e2:
count += 1
#print(e,count)
def counter2(): # O(n)
count = {}
for e in a:
if e not in co... | 22
| MIT | CS42_DS_&_A_1_M2_Hash_Tables_I.ipynb | juancaruizc/CS42-DS-A-1-M2-Hash-Tables-I |
Your first neural networkIn this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementation of the neural network up to you (for the most part). After you've submitted this project, feel free to explore the data and th... | %matplotlib inline
%config InlineBackend.figure_format = 'retina'
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt | _____no_output_____ | MIT | nd101/p1-bike-sharing/DLND Your first neural network.ipynb | julianogalgaro/udacity |
Load and prepare the dataA critical step in working with neural networks is preparing the data correctly. Variables on different scales make it difficult for the network to efficiently learn the correct weights. Below, we've written the code to load and prepare the data. You'll learn more about this soon! | data_path = 'Bike-Sharing-Dataset/hour.csv'
rides = pd.read_csv(data_path)
rides.head() | _____no_output_____ | MIT | nd101/p1-bike-sharing/DLND Your first neural network.ipynb | julianogalgaro/udacity |
Checking out the dataThis dataset has the number of riders for each hour of each day from January 1 2011 to December 31 2012. The number of riders is split between casual and registered, summed up in the `cnt` column. You can see the first few rows of the data above.Below is a plot showing the number of bike riders ov... | rides[:24*10].plot(x='dteday', y='cnt') | _____no_output_____ | MIT | nd101/p1-bike-sharing/DLND Your first neural network.ipynb | julianogalgaro/udacity |
Dummy variablesHere we have some categorical variables like season, weather, month. To include these in our model, we'll need to make binary dummy variables. This is simple to do with Pandas thanks to `get_dummies()`. | dummy_fields = ['season', 'weathersit', 'mnth', 'hr', 'weekday']
for each in dummy_fields:
dummies = pd.get_dummies(rides[each], prefix=each, drop_first=False)
rides = pd.concat([rides, dummies], axis=1)
fields_to_drop = ['instant', 'dteday', 'season', 'weathersit',
'weekday', 'atemp', 'mnth... | _____no_output_____ | MIT | nd101/p1-bike-sharing/DLND Your first neural network.ipynb | julianogalgaro/udacity |
Scaling target variablesTo make training the network easier, we'll standardize each of the continuous variables. That is, we'll shift and scale the variables such that they have zero mean and a standard deviation of 1.The scaling factors are saved so we can go backwards when we use the network for predictions. | quant_features = ['casual', 'registered', 'cnt', 'temp', 'hum', 'windspeed']
# Store scalings in a dictionary so we can convert back later
scaled_features = {}
for each in quant_features:
mean, std = data[each].mean(), data[each].std()
scaled_features[each] = [mean, std]
data.loc[:, each] = (data[each] - me... | _____no_output_____ | MIT | nd101/p1-bike-sharing/DLND Your first neural network.ipynb | julianogalgaro/udacity |
Splitting the data into training, testing, and validation setsWe'll save the data for the last approximately 21 days to use as a test set after we've trained the network. We'll use this set to make predictions and compare them with the actual number of riders. | # Save data for approximately the last 21 days
test_data = data[-21*24:]
# Now remove the test data from the data set
data = data[:-21*24]
# Separate the data into features and targets
target_fields = ['cnt', 'casual', 'registered']
features, targets = data.drop(target_fields, axis=1), data[target_fields]
test_feat... | _____no_output_____ | MIT | nd101/p1-bike-sharing/DLND Your first neural network.ipynb | julianogalgaro/udacity |
We'll split the data into two sets, one for training and one for validating as the network is being trained. Since this is time series data, we'll train on historical data, then try to predict on future data (the validation set). | # Hold out the last 60 days or so of the remaining data as a validation set
train_features, train_targets = features[:-60*24], targets[:-60*24]
val_features, val_targets = features[-60*24:], targets[-60*24:] | _____no_output_____ | MIT | nd101/p1-bike-sharing/DLND Your first neural network.ipynb | julianogalgaro/udacity |
Time to build the networkBelow you'll build your network. We've built out the structure and the backwards pass. You'll implement the forward pass through the network. You'll also set the hyperparameters: the learning rate, the number of hidden units, and the number of training passes.The network has two layers, a hidd... | class NeuralNetwork(object):
def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate):
# Set number of nodes in input, hidden and output layers.
self.input_nodes = input_nodes
self.hidden_nodes = hidden_nodes
self.output_nodes = output_nodes
# Initialize we... | _____no_output_____ | MIT | nd101/p1-bike-sharing/DLND Your first neural network.ipynb | julianogalgaro/udacity |
Training the networkHere you'll set the hyperparameters for the network. The strategy here is to find hyperparameters such that the error on the training set is low, but you're not overfitting to the data. If you train the network too long or have too many hidden nodes, it can become overly specific to the training se... | import sys
### Set the hyperparameters here ###
epochs = 1500
learning_rate = 0.01
hidden_nodes = 8
output_nodes = 1
N_i = train_features.shape[1]
network = NeuralNetwork(N_i, hidden_nodes, output_nodes, learning_rate)
losses = {'train':[], 'validation':[]}
for e in range(epochs):
# Go through a random batch of ... | _____no_output_____ | MIT | nd101/p1-bike-sharing/DLND Your first neural network.ipynb | julianogalgaro/udacity |
Check out your predictionsHere, use the test data to view how well your network is modeling the data. If something is completely wrong here, make sure each step in your network is implemented correctly. | fig, ax = plt.subplots(figsize=(8,4))
mean, std = scaled_features['cnt']
predictions = network.run(test_features)*std + mean
ax.plot(predictions[0], label='Prediction')
ax.plot((test_targets['cnt']*std + mean).values, label='Data')
ax.set_xlim(right=len(predictions))
ax.legend()
dates = pd.to_datetime(rides.ix[test_d... | _____no_output_____ | MIT | nd101/p1-bike-sharing/DLND Your first neural network.ipynb | julianogalgaro/udacity |
OPTIONAL: Thinking about your results(this question will not be evaluated in the rubric). Answer these questions about your results. How well does the model predict the data? Where does it fail? Why does it fail where it does?> **Note:** You can edit the text in this cell by double clicking on it. When you want to ren... | import unittest
inputs = [0.5, -0.2, 0.1]
targets = [0.4]
test_w_i_h = np.array([[0.1, 0.4, -0.3],
[-0.2, 0.5, 0.2]])
test_w_h_o = np.array([[0.3, -0.1]])
class TestMethods(unittest.TestCase):
##########
# Unit tests for data loading
##########
def test_data_path(self... | .....
----------------------------------------------------------------------
Ran 5 tests in 0.014s
OK
| MIT | nd101/p1-bike-sharing/DLND Your first neural network.ipynb | julianogalgaro/udacity |
**** Generation of Test Data**** In this notebook we generate some test data for the interactive histogram. We create both unbinned energy values and binned efficiency curves. | import numpy as np
import matplotlib.pyplot as plt
%config InlineBackend.figure_formats = ['svg'] | _____no_output_____ | CC-BY-4.0 | data/test_data/generate_data.ipynb | fewagner/excess |
Energy Data We generate the data randomly sampled from some standard distributions for three exemplary experiments. | exp_A = np.concatenate((np.random.exponential(scale=1, size=100000),
np.random.normal(loc=5,scale=0.2, size=100000)))
exp_B = np.concatenate((np.random.exponential(scale=0.5, size=50000),
np.random.uniform(low=0,high=15, size=20000)))
exp_C = np.concatenate((np.random.e... | _____no_output_____ | CC-BY-4.0 | data/test_data/generate_data.ipynb | fewagner/excess |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.