markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
We can now go down in the tree by using the id tag in the metadata we fetched. Let's say we are interested in the population statistics. | scb.go_down('BE') | pyscbwrapper_en.ipynb | KiraHG/pyscbwrapper | gpl-3.0 |
To fetch the metadata about the population statistics, we once again run the function info(): | scb.info() | pyscbwrapper_en.ipynb | KiraHG/pyscbwrapper | gpl-3.0 |
We can keep going down in the tree: | scb.go_down('BE0001')
scb.info() | pyscbwrapper_en.ipynb | KiraHG/pyscbwrapper | gpl-3.0 |
Whoops! We did not want the name statistics, but the population statistics. We go up one step and back down to the correct node: | scb.go_up()
scb.go_down('BE0101')
scb.info() | pyscbwrapper_en.ipynb | KiraHG/pyscbwrapper | gpl-3.0 |
Direct route to specific nodes
If we know where in the tree we want to go, we can initialise an object using the id tags as extra variables: | scb = SCB('en', 'BE', 'BE0101')
scb.info() | pyscbwrapper_en.ipynb | KiraHG/pyscbwrapper | gpl-3.0 |
As you can see, we end up directly in the population statistics.
The specific initialisation of the object does not stop us from navigating in the tree: | scb.go_up()
scb.info() | pyscbwrapper_en.ipynb | KiraHG/pyscbwrapper | gpl-3.0 |
Anyway, we go directly back to population density: | scb.go_down('BE0101', 'BE0101C')
scb.info() | pyscbwrapper_en.ipynb | KiraHG/pyscbwrapper | gpl-3.0 |
Now there is only one nod to go to, so we do that: | scb.go_down('BefArealTathetKon')
scb.info() | pyscbwrapper_en.ipynb | KiraHG/pyscbwrapper | gpl-3.0 |
Note how the metadata differs from previous nodes: The keyword variables is there, which indicates that we are in a leaf node. From here we can therefore fetch the actual data.
It is not necessary to call info() after each go_down() but it is a good idea to do anyway, if you are not very sure of what the database loo... | scb.get_variables() | pyscbwrapper_en.ipynb | KiraHG/pyscbwrapper | gpl-3.0 |
Now that we have these, we can choose what we are interested in and create a json query. Let's say we are interested in the number of inhabitants per square kilometer in Örebro county the latest five years. | scb.set_query(region=["Örebro county"],
observations=["Population density per sq. km"],
year=["2014", "2015", "2016", "2017", "2018"]) | pyscbwrapper_en.ipynb | KiraHG/pyscbwrapper | gpl-3.0 |
Now we can check how the query looks: | scb.get_query() | pyscbwrapper_en.ipynb | KiraHG/pyscbwrapper | gpl-3.0 |
The query is automatically formatted in the right way to fetch the data from the API. We fetch the data: | scb.get_data() | pyscbwrapper_en.ipynb | KiraHG/pyscbwrapper | gpl-3.0 |
This is the same data that one can fetch from the Statistical Database on the website. Via a function in pyscbwrapper we can get the URL to the page with the data: | scb.get_url() | pyscbwrapper_en.ipynb | KiraHG/pyscbwrapper | gpl-3.0 |
The data can of course be fetched without pyscbwrapper, by navigating to the URL above. There we select "Population density per sq. km", choose region County and select Örebro county, and select the last five years. On the next page we can click "API for this table" and get the query and a URL to post it to via e.g. th... | import requests
import json
session = requests.Session()
query = {
"query": [
{
"code": "Region",
"selection": {
"filter": "vs:RegionLän99EjAggr",
"values": [
"18"
]
}
},
{
"code": "ContentsCode",
"selection": {
"filter": "item",
... | pyscbwrapper_en.ipynb | KiraHG/pyscbwrapper | gpl-3.0 |
As you can see, we get the exact same data.
More advanced calls
Now that we have seen what the data looks like we can fetch more of it to make interesting graphs. Since we already are on the correct place in the API structure we only have to construct a new query. Let's say we want data from every available year for e... | import re
regions = scb.get_variables()['region']
r = re.compile(r'.* county')
county = list(filter(r.match, regions))
scb.set_query(region=county,
observations=["Population density per sq. km"])
scb.get_query() | pyscbwrapper_en.ipynb | KiraHG/pyscbwrapper | gpl-3.0 |
This is the exact query we need. We fetch the data and place it in a variable so we can use it later: | scb_data = scb.get_data() | pyscbwrapper_en.ipynb | KiraHG/pyscbwrapper | gpl-3.0 |
As is good practice we look at the data before we do anything else: | scb_data | pyscbwrapper_en.ipynb | KiraHG/pyscbwrapper | gpl-3.0 |
The actual data we look for is here: | scb_fetch = scb_data['data'] | pyscbwrapper_en.ipynb | KiraHG/pyscbwrapper | gpl-3.0 |
Once again we check that we have gotten the correct data: | scb_fetch | pyscbwrapper_en.ipynb | KiraHG/pyscbwrapper | gpl-3.0 |
Now we need to understand the structure of the data. We have gotten a list of dictionaries where the first variable 'key' contains the domain (in this case county and year), and the variable 'values' contains the value of the observation variable (in this case inhabitants per square kilometer). To change this into time... | codes = scb.get_query()['query'][0]['selection']['values']
countydic = {}
for i in range(len(codes)):
countydic[codes[i]] = county[i]
countydata = {}
for code in countydic:
countydata[countydic[code]] = {}
for i in range(len(scb_fetch)):
if scb_fetch[i]['key'][0] == code:
countydata[countydic[code]]... | pyscbwrapper_en.ipynb | KiraHG/pyscbwrapper | gpl-3.0 |
This got a bit hacky, so let's see if we got the structure we wanted: | countydata | pyscbwrapper_en.ipynb | KiraHG/pyscbwrapper | gpl-3.0 |
This looks about right. Now we can loop over the keys and plot the values using key on the x axis and value on the y axis.
Data visualisation
We need numpy, pandas, and matplotlib for this. We install and import. | !pip install -q matplotlib
!pip install -q pandas
!pip install -q numpy
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt | pyscbwrapper_en.ipynb | KiraHG/pyscbwrapper | gpl-3.0 |
Now we can make a neat graph. | df = pd.DataFrame(countydata)
df = df.reset_index()
df = df.rename(columns={"index":"Year"})
ax = df.plot(x=df.index, xticks=np.arange(len(df.index)), colormap='hsv')
ax.set_xticklabels(df["Year"], rotation=45)
plt.title("Population density per county")
plt.xlabel("Year")
plt.ylabel("Inhabitants per square kilometer")
... | pyscbwrapper_en.ipynb | KiraHG/pyscbwrapper | gpl-3.0 |
Let's make our system so that the boosting effects will be quite noticeable. | b['rpole@primary'] = 1.8
b['rpole@secondary'] = 0.96
b['teff@primary'] = 10000
b['gravb_bol@primary'] = 1.0
b['teff@secondary'] = 5200
b['gravb_bol@secondary'] = 0.32
b['q@binary'] = 0.96/1.8
b['incl@binary'] = 88
b['period@binary'] = 1.0
b['sma@binary'] = 6.0 | 2.0/tutorials/beaming_boosting.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
We'll add lc, rv, and mesh datasets so that we can see how they're each affected by beaming and boosting. | times = np.linspace(0,1,101)
b.add_dataset('lc', times=times, dataset='lc01')
b.add_dataset('rv', times=times, dataset='rv01')
b.add_dataset('mesh', times=times[::10], dataset='mesh01') | 2.0/tutorials/beaming_boosting.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Influence on Light Curves (fluxes) | b.run_compute(boosting_method='none', model='boosting_none')
b.run_compute(boosting_method='linear', model='boosting_linear')
axs, artists = b['lc01'].plot()
leg = plt.legend()
axs, artists = b['lc01'].plot(ylim=(1.01,1.03))
leg = plt.legend() | 2.0/tutorials/beaming_boosting.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Influence on Radial Velocities | fig = plt.figure(figsize=(10,6))
ax1, ax2 = fig.add_subplot(121), fig.add_subplot(122)
axs, artists = b['rv01@boosting_none'].plot(ax=ax1)
axs, artists = b['rv01@boosting_linear'].plot(ax=ax2) | 2.0/tutorials/beaming_boosting.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Influence on Meshes | fig = plt.figure(figsize=(10,6))
ax1, ax2 = fig.add_subplot(121), fig.add_subplot(122)
axs, artists = b['mesh@boosting_none'].plot(time=0.6, facecolor='boost_factors@lc01', edgecolor=None, ax=ax1)
axs, artists = b['mesh@boosting_linear'].plot(time=0.6, facecolor='boost_factors@lc01', edgecolor=None, ax=ax2) | 2.0/tutorials/beaming_boosting.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
1. Признаки по одному
1.1. Количественные
Гистограмма и боксплот | df['Total day minutes'].hist();
sns.boxplot(df['Total day minutes']);
df.hist(); | visualization/telecom_churn_inclass_as_is.ipynb | andreyf/machine-learning-examples | gpl-3.0 |
1.2. Категориальные
countplot | df['State'].value_counts().head()
df['Churn'].value_counts()
sns.countplot(df['Churn']);
sns.countplot(df['State']);
sns.countplot(df[df['State'].\
isin(df['State'].value_counts().head().index)]['State']); | visualization/telecom_churn_inclass_as_is.ipynb | andreyf/machine-learning-examples | gpl-3.0 |
2. Взаимодействия признаков
2.1. Количественный с количественным
pairplot, scatterplot, корреляции, heatmap | feat = [f for f in df.columns if 'charge' in f]
df[feat].hist();
sns.pairplot(df[feat]);
df['Churn'].map({False: 'blue', True: 'orange'}).head()
df[~df['Churn']].head()
plt.scatter(df[df['Churn']]['Total eve charge'],
df[df['Churn']]['Total intl charge'],
color='orange', label='churn');
plt... | visualization/telecom_churn_inclass_as_is.ipynb | andreyf/machine-learning-examples | gpl-3.0 |
2.2. Количественный с категориальным
boxplot, violinplot | sns.boxplot(x='Churn', y='Total day minutes', data=df);
sns.boxplot(x='State', y='Total day minutes', data=df);
sns.violinplot(x='Churn', y='Total day minutes', data=df);
df.groupby('International plan')['Total day minutes'].mean()
sns.boxplot(x='International plan', y='Total day minutes', data=df); | visualization/telecom_churn_inclass_as_is.ipynb | andreyf/machine-learning-examples | gpl-3.0 |
2.3. Категориальный с категориальным
countplot | pd.crosstab(df['Churn'], df['International plan'])
sns.countplot(x='International plan', hue='Churn', data=df);
sns.countplot(x='Customer service calls', hue='Churn', data=df); | visualization/telecom_churn_inclass_as_is.ipynb | andreyf/machine-learning-examples | gpl-3.0 |
3. Прочее
Manifold learning, один из представителей – t-SNE | from sklearn.manifold import TSNE
tsne = TSNE(random_state=0)
df2 = df.drop(['State', 'Churn'], axis=1)
df2['International plan'] = df2['International plan'].map({'Yes': 1,
'No': 0})
df2['Voice mail plan'] = df2['Voice mail plan'].map({'Yes': 1,
... | visualization/telecom_churn_inclass_as_is.ipynb | andreyf/machine-learning-examples | gpl-3.0 |
You may see a warning message from Kubeflow Pipeline logs saying "Insufficient nvidia.com/gpu". If so, this probably means that your GPU-enabled node is still spinning up; please wait for few minutes. You can check the current nodes in your cluster like this:
kubectl get nodes -o wide
If everything runs as expected, th... | import kfp
from kfp import dsl
def gpu_p100_op():
return dsl.ContainerOp(
name='check_p100',
image='tensorflow/tensorflow:latest-gpu',
command=['sh', '-c'],
arguments=['nvidia-smi']
).add_node_selector_constraint('cloud.google.com/gke-accelerator', 'nvidia-tesla-p100').container... | samples/tutorials/gpu/gpu.ipynb | kubeflow/pipelines | apache-2.0 |
You should see different "nvidia-smi" logs from the two pipeline steps.
Using Preemptible GPUs
A Preemptible GPU resource is cheaper, but use of these instances means that a pipeline step has the potential to be aborted and then retried. This means that pipeline steps used with preemptible instances must be idempotent... | import kfp
import kfp.gcp as gcp
from kfp import dsl
def gpu_p100_op():
return dsl.ContainerOp(
name='check_p100',
image='tensorflow/tensorflow:latest-gpu',
command=['sh', '-c'],
arguments=['nvidia-smi']
).add_node_selector_constraint('cloud.google.com/gke-accelerator', 'nvidia-... | samples/tutorials/gpu/gpu.ipynb | kubeflow/pipelines | apache-2.0 |
You will work with the Housing Prices Competition for Kaggle Learn Users dataset from the previous exercise.
Run the next code cell without changes to load the training and validation sets in X_train, X_valid, y_train, and y_valid. The test set is loaded in X_test. | import pandas as pd
from sklearn.model_selection import train_test_split
# Read the data
X = pd.read_csv('../input/train.csv', index_col='Id')
X_test_full = pd.read_csv('../input/test.csv', index_col='Id')
# Remove rows with missing target, separate target from predictors
X.dropna(axis=0, subset=['SalePrice'], inplac... | notebooks/ml_intermediate/raw/ex6.ipynb | Kaggle/learntools | apache-2.0 |
Step 1: Build model
Part A
In this step, you'll build and train your first model with gradient boosting.
Begin by setting my_model_1 to an XGBoost model. Use the XGBRegressor class, and set the random seed to 0 (random_state=0). Leave all other parameters as default.
Then, fit the model to the training data in X_tra... | from xgboost import XGBRegressor
# Define the model
my_model_1 = ____ # Your code here
# Fit the model
____ # Your code here
# Check your answer
step_1.a.check()
#%%RM_IF(PROD)%%
from sklearn.utils.validation import check_is_fitted
my_model_1 = XGBRegressor(random_state=0)
step_1.a.assert_check_failed()
#%%RM_IF(P... | notebooks/ml_intermediate/raw/ex6.ipynb | Kaggle/learntools | apache-2.0 |
Part B
Set predictions_1 to the model's predictions for the validation data. Recall that the validation features are stored in X_valid. | from sklearn.metrics import mean_absolute_error
# Get predictions
predictions_1 = ____ # Your code here
# Check your answer
step_1.b.check()
#%%RM_IF(PROD)%%
predictions_1 = my_model_1.predict(X_valid)
step_1.b.assert_check_passed()
# Lines below will give you a hint or solution code
#_COMMENT_IF(PROD)_
step_1.b.hi... | notebooks/ml_intermediate/raw/ex6.ipynb | Kaggle/learntools | apache-2.0 |
Part C
Finally, use the mean_absolute_error() function to calculate the mean absolute error (MAE) corresponding to the predictions for the validation set. Recall that the labels for the validation data are stored in y_valid. | # Calculate MAE
mae_1 = ____ # Your code here
# Uncomment to print MAE
# print("Mean Absolute Error:" , mae_1)
# Check your answer
step_1.c.check()
#%%RM_IF(PROD)%%
mae_1 = mean_absolute_error(predictions_1, y_valid)
print("Mean Absolute Error:" , mae_1)
step_1.c.assert_check_passed()
# Lines below will give you a ... | notebooks/ml_intermediate/raw/ex6.ipynb | Kaggle/learntools | apache-2.0 |
Step 2: Improve the model
Now that you've trained a default model as baseline, it's time to tinker with the parameters, to see if you can get better performance!
- Begin by setting my_model_2 to an XGBoost model, using the XGBRegressor class. Use what you learned in the previous tutorial to figure out how to change th... | # Define the model
my_model_2 = ____ # Your code here
# Fit the model
____ # Your code here
# Get predictions
predictions_2 = ____ # Your code here
# Calculate MAE
mae_2 = ____ # Your code here
# Uncomment to print MAE
# print("Mean Absolute Error:" , mae_2)
# Check your answer
step_2.check()
#%%RM_IF(PROD)%%
my_... | notebooks/ml_intermediate/raw/ex6.ipynb | Kaggle/learntools | apache-2.0 |
Step 3: Break the model
In this step, you will create a model that performs worse than the original model in Step 1. This will help you to develop your intuition for how to set parameters. You might even find that you accidentally get better performance, which is ultimately a nice problem to have and a valuable learn... | # Define the model
my_model_3 = ____
# Fit the model
____ # Your code here
# Get predictions
predictions_3 = ____
# Calculate MAE
mae_3 = ____
# Uncomment to print MAE
# print("Mean Absolute Error:" , mae_3)
# Check your answer
step_3.check()
#%%RM_IF(PROD)%%
my_model_3 = XGBRegressor(n_estimators=1)
my_model_3.f... | notebooks/ml_intermediate/raw/ex6.ipynb | Kaggle/learntools | apache-2.0 |
Все есть объект, что это значит
Очень часто можно услышать такую фразу в отношении Python. Что это значит и какое влияние оказывает на программирование на языке? | # Объявим переменную
num = 10
# На самом деле num - это не имя переменной, ссылающейся на численное значение в памяти, а имя, связанное с объектом.
num.__add__
# И даже больше
#dir(num) | lectures/02_Data_Structures/notebook.ipynb | park-python/course | bsd-3-clause |
Все типы в Python "отнаследованы" (на самом деле речь скорее о композиции) от С структуры PyObject:
typedef struct _object {
_PyObject_HEAD_EXTRA
Py_ssize_t ob_refcnt;
struct _typeobject *ob_type;
} PyObject;
Или от PyVarObject:
typedef struct {
PyObject ob_base;
Py_ssize_t ob_size; /* Number of ite... | # создаем связь имени переменной foo cо строковым объектом
foo = "Испания"
# связываем имя с новым строковым объектом, строковый объект со строкой "Испания" остался нетронутым.
# В этот момент на куче живет 2 объекта. Один из них сборщик мусора может удалить, но для нас важно не это.
foo = "Бразилия" | lectures/02_Data_Structures/notebook.ipynb | park-python/course | bsd-3-clause |
При этом в Python имя, привязанное к объекту, используется только в пределах скоупа (scope), в котором имя объявлено. Scope имени определяется блоком питоновского кода. Блоками являются модуль, определение класса, тело функции. Интерпретатор при обращении к переменной ищет ее имя начиная с локального пространства имен,... | top_level = 3
def print_result():
inner_level = 4
def print_calculation():
print(top_level * inner_level)
print_calculation()
print_result() | lectures/02_Data_Structures/notebook.ipynb | park-python/course | bsd-3-clause |
Чуть более сложный пример | country = 'Испания'
countries = []
countries.append(country)
another_list_of_countries = countries
another_list_of_countries.append('Бразилия')
country = 'Россия'
#print(country, countries, another_list_of_countries) | lectures/02_Data_Structures/notebook.ipynb | park-python/course | bsd-3-clause |
Упс, появилась первая структура данных - list (список). Пожалуй, сначала рассмотрим ее, а потом вернемся к этому примеру.
Структуры данных
Мы рассмотрим для начала структуры данных, доступные "из коробки" | # built-in структуры данных
list, tuple, dict, set, frozenset | lectures/02_Data_Structures/notebook.ipynb | park-python/course | bsd-3-clause |
Список: list
Sequence тип. Позволяет хранить последовательность элементов одного или разного типа. Это не linked list! | # создаем list используя квадратные скобки или ф-ю list
empty_list = []
empty_list = list()
sys.getsizeof(empty_list)
# list может содержать любые объекты, внутри Python они хранятся как массив указателей
example_list = [1, True, "a"]
for element in example_list:
print(element)
list_of_lists = [example_list, exam... | lectures/02_Data_Structures/notebook.ipynb | park-python/course | bsd-3-clause |
Продолжение следует...
Присваивание (Часть 2) | country = 'Испания'
countries = []
countries.append(country)
another_list_of_countries = countries
another_list_of_countries.append('Бразилия')
country = 'Россия'
#print(country, countries, another_list_of_countries) | lectures/02_Data_Structures/notebook.ipynb | park-python/course | bsd-3-clause |
В Python есть 2 типа объектов. Mutable (изменяемые) и Immutable (неизменяемые).
Любые изменения в mutable объекте видны во всем привязанных к нему именах переменных. Список - пример изменяемого объекта.
Значение неизменяемого объекта поменять нельзя, все что можно сделать - прочитать его и создать новый объект на основ... | def foo(bar):
# bar в данном случае связь нового имени с объектом, к которому привязан country_list.
# Этот объект mutable - следовательно ф-я изменит его.
bar.append("Испания")
country_list = []
foo(country_list)
#print(country_list) | lectures/02_Data_Structures/notebook.ipynb | park-python/course | bsd-3-clause |
Теперь пример с неизменяемым объектом - строкой: | def foo(bar):
# bar это имя, которое связано с изначальным строковым объектом,
# но это связь имени и объекта в локальном пространстве ф-ии.
# так как bar в данном случае immutable - все что ф-я может
# сделать - изменить связь имени, привязав к новому объекту в своем
# локальном неймспейсе. Тем ... | lectures/02_Data_Structures/notebook.ipynb | park-python/course | bsd-3-clause |
Вывод - важно, что объект в Питоне передается как связь (binding) имени аргумента ф-ии c объектом (pass-by-object). По большому счету эта связь - новая ссылка на изначальный объект.
В зависимости от того, изменяемый объект или нет можно понять, способна ли функция изменить его.
Список: list, продолжение | # при простом присваивании новая переменная ссылается на тот же список
example_list = [1, 2, 3, 4, 5]
another_list = example_list
another_list[0] = 100
# print(example_list)
# копирование списка
example_list = [0, 1, 2, 3, 4, 5]
another_list = example_list[:]
another_list[0] = 100
print(example_list)
# но вложенные о... | lectures/02_Data_Structures/notebook.ipynb | park-python/course | bsd-3-clause |
Сортировка | # Сортировка списка
unsorted_list = [2, 1, 5, 4, 3]
unsorted_list.sort()
print(unsorted_list)
# сортировка in-place
unsorted_list = [2, 1, 5, 4, 3]
print(sorted(unsorted_list))
print(unsorted_list) | lectures/02_Data_Structures/notebook.ipynb | park-python/course | bsd-3-clause |
Задача - соединить все числа от нуля до 10000 в одну длинную строку
?
Кортеж: tuple
Так же как и список позволяет хранить последовательность элементов одного или разного типа
Неизменяемые (Immutable) => защищают данные
Быстрее списка
Хешируемые (Hashable) | # создадим пустой tuple используя круглые скобки или ф-ю tuple
empty_tuple = ()
empty_tuple = tuple()
sys.getsizeof(empty_tuple)
len(empty_tuple)
hash(empty_tuple)
example_tuple = (1, "a", True)
for element in example_tuple:
print(element)
len(example_tuple)
example_tuple = (1, 2, 3)
print(example_tuple[0])
pr... | lectures/02_Data_Structures/notebook.ipynb | park-python/course | bsd-3-clause |
Важно понимать, что неизменяемым является сам tuple, но не объекты, которые он содержит!. Например: | first_list = [1, 2]
second_list = [3, 4]
example_tuple = (first_list, second_list)
print(example_tuple)
first_list.append(5)
print(example_tuple) | lectures/02_Data_Structures/notebook.ipynb | park-python/course | bsd-3-clause |
Словарь: dict
Позволяет хранить пары ключ-значение, для быстрого доступа к значению по ключу. | # создаем словарь используя фигурные скобки или ф-ю dict
empty_dict = dict()
empty_dict = {}
sys.getsizeof(empty_dict)
example_dict = {"a": 1, "b": True, (1, 2, 3): True}
# Добавляем ключ и соответствующее ему значение в словарь O(1)
example_dict["c"] = 4
print(example_dict)
# Поиск значения по ключу O(1)
print(exam... | lectures/02_Data_Structures/notebook.ipynb | park-python/course | bsd-3-clause |
Объект является hashable объектом, если он имеет hash-значение, неизменное в процессе его жизни (т.е. у объекта должен быть определен __hash____() метод) и объект можно сравнить с другими объектами (_eq_() или _cmp_() методы). Одинаковые объекты должны иметь одинаковое знаение hash.
Если объект hashable, то он может бы... | # если мы не уверены, что ключ есть в словаре - можно воспользоваться методом get
print(example_dict.get("x"))
print(example_dict.get("x", "default value"))
# итерируемся по ключам и значениям - внимание, порядок недетерминирован (до Python 3.6)!
for key, value in example_dict.items():
print("{}: {}".format(key, v... | lectures/02_Data_Structures/notebook.ipynb | park-python/course | bsd-3-clause |
Задача - есть список элементов. Известно, что у большинства элементов в списке есть пары, то есть их по 2. Но есть некоторое количество элементов, у которых пары нет - их по 1 в списке. Цель - найти эти одиночные элементы.
Вот решение с помощью словаря: | elements = [2, 1, 5, 2, 4, 3, 1, 4]
solution_dict = {}
# TODO by hand | lectures/02_Data_Structures/notebook.ipynb | park-python/course | bsd-3-clause |
Множество: set
Неупорядоченная коллекция, содержащая только уникальные элементы. | # создадим пустой set c помощью ф-ии set()
empty_set = set()
sys.getsizeof(empty_set)
# непустое множество можно также задать фигурными скобками
example_set = {1, 2, 3}
# добавляем элемент в set
example_set.add(4)
print(example_set)
# добавляем уже присутствующий элемент в set - ничего не меняется
example_set.add(1)... | lectures/02_Data_Structures/notebook.ipynb | park-python/course | bsd-3-clause |
Основная задача, очень часто возникающая на практике. Есть список элементов, нужно оставить только уникальные. Это одна строка с использованием сета: | elements = ["yellow", "yellow", "green", "red", "blue", "blue", "magenta", "orange", "red"]
set(elements) | lectures/02_Data_Structures/notebook.ipynb | park-python/course | bsd-3-clause |
frozenset
Так как set может содержать только hashable объекты, а иногда нужен сет сетов - существует frozenset | example_set = set()
example_set.add(frozenset([1,2,3]))
print(example_set) | lectures/02_Data_Structures/notebook.ipynb | park-python/course | bsd-3-clause |
collections | import collections
print([x for x in collections.__dict__.keys() if not x.startswith("_")])
# counter
counter = collections.Counter([1,2,3,4,1,2,1,1,1])
for elem, count in counter.most_common(3):
print("{}: {} times".format(elem, count))
# defaultdict
default_dict = collections.defaultdict(int)
default_dict["not_... | lectures/02_Data_Structures/notebook.ipynb | park-python/course | bsd-3-clause |
queue | import queue
print("Queue:", queue.Queue.__doc__)
print()
print("PriorityQueue:", queue.PriorityQueue.__doc__)
print()
print("LifoQueue:", queue.LifoQueue.__doc__) | lectures/02_Data_Structures/notebook.ipynb | park-python/course | bsd-3-clause |
Queue
PriorityQueue
LifoQueue
Разберем позже, когда будем говорить о многопоточности, так как доступ к этим структурам синхронизирован.
heapq | import heapq
from random import shuffle
heap = []
data = list(range(10))
shuffle(data)
for i in data:
heapq.heappush(heap, i)
# Порядок элементов будет совсем не случайным, как может показаться.
# Элементы идут не строго по порядку, но удовлетворяют правилу:
# heap[k] <= heap[2*k+1] and heap[k] <= heap[2*k+2] дл... | lectures/02_Data_Structures/notebook.ipynb | park-python/course | bsd-3-clause |
Другие структуры данных
Связанные списки
Деревья
Графы
...
Если вам нужна реализация какой-то конкретно структуры данных - скорее всего вы найдете готовую open-source реализацию.
Анализ сложности, визуализация некоторых операций | %matplotlib inline
plotting = True
try:
import matplotlib
import seaborn as sbn
import matplotlib.pyplot as plt
except ImportError:
# Не удалось импортировать модуль, не будем рисовать.
plotting = False
print("can't import plotting tools")
else:
# задаем ширину и высоту графиков
matplotl... | lectures/02_Data_Structures/notebook.ipynb | park-python/course | bsd-3-clause |
Ссылки:
https://docs.python.org/3/tutorial/datastructures.html
https://pymbook.readthedocs.io/en/latest/datastructure.html
http://interactivepython.org/runestone/static/pythonds/index.html
Немного практики в завершение | from so import get_best_answer
from IPython.core.display import display, HTML
answer = get_best_answer("What is Python GIL")
if answer:
display(HTML(answer["body"]))
else:
print("Answer not found") | lectures/02_Data_Structures/notebook.ipynb | park-python/course | bsd-3-clause |
First we prepare the dataset, which is used for training, testing and the finally prediction.
Note: You can easily switch to a different dataset, such as the Breast Cancer dataset, by replacing 'ad_hoc_data' to 'Breast_cancer' below. | n = 2 # dimension of each data point
training_dataset_size = 20
testing_dataset_size = 10
sample_Total, training_input, test_input, class_labels = ad_hoc_data(training_size=training_dataset_size,
test_size=testing_dataset_size,
... | community/aqua/artificial_intelligence/qsvm_kernel_directly.ipynb | antoniomezzacapo/qiskit-tutorial | apache-2.0 |
With the dataset ready we initialize the necessary inputs for the algorithm:
- build all components required by SVM
- feature_map
- multiclass_extension (optional) | svm = get_algorithm_instance("QSVM.Kernel")
svm.random_seed = 10598
svm.setup_quantum_backend(backend='statevector_simulator')
feature_map = get_feature_map_instance('SecondOrderExpansion')
feature_map.init_args(num_qubits=2, depth=2, entanglement='linear')
svm.init_args(training_input, test_input, datapoints[0], fea... | community/aqua/artificial_intelligence/qsvm_kernel_directly.ipynb | antoniomezzacapo/qiskit-tutorial | apache-2.0 |
With everything setup, we can now run the algorithm.
The run method includes training, testing and predict on unlabeled data.
For the testing, the result includes the success ratio.
For the prediction, the result includes the predicted class names for each data.
After that the trained model is also stored in the svm in... | result = svm.run()
print("kernel matrix during the training:")
kernel_matrix = result['kernel_matrix_training']
img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r')
plt.show()
print("testing success ratio: ", result['testing_accuracy'])
print("predicted classes:", result['... | community/aqua/artificial_intelligence/qsvm_kernel_directly.ipynb | antoniomezzacapo/qiskit-tutorial | apache-2.0 |
Use the trained model to evaluate data directly, and we store a label_to_class and class_to_label for helping converting between label and class name | predicted_labels = svm.predict(datapoints[0])
predicted_classes = map_label_to_class_name(predicted_labels, svm.label_to_class)
print("ground truth: {}".format(datapoints[1]))
print("preduction: {}".format(predicted_labels)) | community/aqua/artificial_intelligence/qsvm_kernel_directly.ipynb | antoniomezzacapo/qiskit-tutorial | apache-2.0 |
Validation Curves | from sklearn.datasets import load_digits
from sklearn.ensemble import RandomForestClassifier
from sklearn.learning_curve import validation_curve
digits = load_digits()
X, y = digits.data, digits.target
model = RandomForestClassifier(n_estimators=20)
param_range = range(1, 13)
training_scores, validation_scores = vali... | day3-machine-learning/06 - Model Complexity.ipynb | AstroHackWeek/AstroHackWeek2015 | gpl-2.0 |
Exercise
Plot the validation curve on the digit dataset for:
* a LinearSVC with a logarithmic range of regularization parameters C.
* KNeighborsClassifier with a linear range of neighbors n_neighbors.
What do you expect them to look like? How do they actually look like? | # %load solutions/validation_curve.py | day3-machine-learning/06 - Model Complexity.ipynb | AstroHackWeek/AstroHackWeek2015 | gpl-2.0 |
Predicting on sample validation data
For each row in the sample_validation_data, write code to make model_5 predict whether or not the loan is classified as a safe loan.
Hint: Use the predict method in model_5 for this.
Quiz question: What percentage of the predictions on sample_validation_data did model_5 get correct?... | print "Your loans : %s\n" % validation_data['predictions'].head(4)
print "Expected answer : %s" % [0.4492515948736132, 0.6119100103640573,
0.3835981314851436, 0.3693306705994325] | ml-classification/blank/module-8-boosting-assignment-1-blank.ipynb | dnc1994/MachineLearning-UW | mit |
Now, we are ready to go to Step 3. You can now use the prediction column to sort the loans in validation_data (in descending order) by prediction probability. Find the top 5 loans with the highest probability of being predicted as a safe loan.
Quiz question: What grades are the top 5 loans?
Let us repeat this excercis... | model_10 = graphlab.boosted_trees_classifier.create(train_data, validation_set=None,
target = target, features = features, max_iterations = 10, verbose=False) | ml-classification/blank/module-8-boosting-assignment-1-blank.ipynb | dnc1994/MachineLearning-UW | mit |
Now, train 4 models with max_iterations to be:
* max_iterations = 50,
* max_iterations = 100
* max_iterations = 200
* max_iterations = 500.
Let us call these models model_50, model_100, model_200, and model_500. You can pass in verbose=False in order to suppress the printed output.
Warning: This could take a couple o... | model_50 =
model_100 =
model_200 =
model_500 = | ml-classification/blank/module-8-boosting-assignment-1-blank.ipynb | dnc1994/MachineLearning-UW | mit |
Compare accuracy on entire validation set
Now we will compare the predicitve accuracy of our models on the validation set. Evaluate the accuracy of the 10, 50, 100, 200, and 500 tree models on the validation_data. Use the .evaluate method.
Quiz Question: Which model has the best accuracy on the validation_data?
Quiz Qu... | import matplotlib.pyplot as plt
%matplotlib inline
def make_figure(dim, title, xlabel, ylabel, legend):
plt.rcParams['figure.figsize'] = dim
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
if legend is not None:
plt.legend(loc=legend, prop={'size':15})
plt.rcParams.update({'font.s... | ml-classification/blank/module-8-boosting-assignment-1-blank.ipynb | dnc1994/MachineLearning-UW | mit |
In order to plot the classification errors (on the train_data and validation_data) versus the number of trees, we will need lists of these accuracies, which we get by applying the method .evaluate.
Steps to follow:
Step 1: Calculate the classification error for model on the training data (train_data).
Step 2: Store t... | training_errors = [train_err_10, train_err_50, train_err_100,
train_err_200, train_err_500] | ml-classification/blank/module-8-boosting-assignment-1-blank.ipynb | dnc1994/MachineLearning-UW | mit |
Now, onto Step 3. Write code to compute the classification error on the validation_data for models model_10, model_50, model_100, model_200, and model_500.
Now, let us run Step 4. Save the training errors into a list called validation_errors | validation_errors = [validation_err_10, validation_err_50, validation_err_100,
validation_err_200, validation_err_500] | ml-classification/blank/module-8-boosting-assignment-1-blank.ipynb | dnc1994/MachineLearning-UW | mit |
Normalize the features
Hint: You solved this in TensorFlow lab Problem 1. | # TODO: Normalize the data features to the variable X_normalized
def normalize(X, a=0, b=1):
"""
Normalize the image data with Min-Max scaling to a range of [0.1, 0.9]
:param image_data: The image data to be normalized
:return: Normalized image data
"""
# TODO: Implement Min-Max scaling for gray... | CarND-Keras-Lab/traffic-sign-classification-with-keras.ipynb | phuongxuanpham/SelfDrivingCar | gpl-3.0 |
One-Hot Encode the labels
Hint: You can use the scikit-learn LabelBinarizer function to one-hot encode the labels. | # TODO: One Hot encode the labels to the variable y_one_hot
from sklearn.preprocessing import LabelBinarizer
lb = LabelBinarizer()
y_one_hot = lb.fit_transform(y_train)
# STOP: Do not change the tests below. Your implementation should pass these tests.
import collections
assert y_one_hot.shape == (39209, 43), 'y_one... | CarND-Keras-Lab/traffic-sign-classification-with-keras.ipynb | phuongxuanpham/SelfDrivingCar | gpl-3.0 |
Keras Sequential Model
```python
from keras.models import Sequential
Create the Sequential model
model = Sequential()
``
Thekeras.models.Sequentialclass is a wrapper for the neural network model. Just like many of the class models in scikit-learn, it provides common functions likefit(),evaluate(), andcompile()`. We'll... | from keras.models import Sequential
from keras.layers.core import Dense, Activation, Flatten
model = Sequential()
# TODO: Build a Multi-layer feedforward neural network with Keras here.
# 1st Layer - Add a flatten layer
model.add(Flatten(input_shape=(32, 32, 3)))
# 2nd Layer - Add a fully connected layer
model.add(De... | CarND-Keras-Lab/traffic-sign-classification-with-keras.ipynb | phuongxuanpham/SelfDrivingCar | gpl-3.0 |
Training a Sequential Model
You built a multi-layer neural network in Keras, now let's look at training a neural network.
```python
from keras.models import Sequential
from keras.layers.core import Dense, Activation
model = Sequential()
...
Configures the learning process and metrics
model.compile('sgd', 'mean_squared_... | # TODO: Compile and train the model here.
# Configures the learning process and metrics
# Compile the network using adam optimizer and categorical_crossentropy loss function.
model.compile('adam', 'categorical_crossentropy', ['accuracy'])
# Train the model
# History is a record of training loss and metrics
# Train th... | CarND-Keras-Lab/traffic-sign-classification-with-keras.ipynb | phuongxuanpham/SelfDrivingCar | gpl-3.0 |
Convolutions
Re-construct the previous network
Add a convolutional layer with 32 filters, a 3x3 kernel, and valid padding before the flatten layer.
Add a ReLU activation after the convolutional layer.
Hint 1: The Keras example of a convolutional neural network for MNIST would be a good example to review. | from keras.models import Sequential
from keras.layers.core import Dense, Activation, Flatten
from keras.layers.convolutional import Convolution2D, Conv2D
# TODO: Re-construct the network and add a convolutional layer before the flatten layer.
model = Sequential()
# TODO: Build a Multi-layer feedforward neural network ... | CarND-Keras-Lab/traffic-sign-classification-with-keras.ipynb | phuongxuanpham/SelfDrivingCar | gpl-3.0 |
Pooling
Re-construct the network
Add a 2x2 max pooling layer immediately following your convolutional layer. | from keras.models import Sequential
from keras.layers.core import Dense, Activation, Flatten
from keras.layers.convolutional import Convolution2D, Conv2D
from keras.layers.pooling import MaxPooling2D
# TODO: Re-construct the network and add a pooling layer after the convolutional layer.
model = Sequential()
# TODO: Bu... | CarND-Keras-Lab/traffic-sign-classification-with-keras.ipynb | phuongxuanpham/SelfDrivingCar | gpl-3.0 |
Dropout
Re-construct the network
Add a dropout layer after the pooling layer. Set the dropout rate to 50%. | from keras.layers.core import Dense, Activation, Flatten, Dropout
from keras.layers.convolutional import Convolution2D
from keras.layers.pooling import MaxPooling2D
# TODO: Re-construct the network and add dropout after the pooling layer.
model = Sequential()
# TODO: Build a Multi-layer feedforward neural network with ... | CarND-Keras-Lab/traffic-sign-classification-with-keras.ipynb | phuongxuanpham/SelfDrivingCar | gpl-3.0 |
Optimization
Congratulations! You've built a neural network with convolutions, pooling, dropout, and fully-connected layers, all in just a few lines of code.
Have fun with the model and see how well you can do! Add more layers, or regularization, or different padding, or batches, or more training epochs.
What is the be... | # TODO: Build a model
from keras.layers.core import Dense, Activation, Flatten, Dropout
from keras.layers.convolutional import Convolution2D
from keras.layers.pooling import MaxPooling2D
# TODO: Re-construct the network and add dropout after the pooling layer.
model = Sequential()
# TODO: Build a Multi-layer feedforwar... | CarND-Keras-Lab/traffic-sign-classification-with-keras.ipynb | phuongxuanpham/SelfDrivingCar | gpl-3.0 |
batch_size=128, nb_epoch=20, border_mode='valid' | # TODO: Build a model
from keras.layers.core import Dense, Activation, Flatten, Dropout
from keras.layers.convolutional import Convolution2D
from keras.layers.pooling import MaxPooling2D
# TODO: Re-construct the network and add dropout after the pooling layer.
model = Sequential()
# TODO: Build a Multi-layer feedforwar... | CarND-Keras-Lab/traffic-sign-classification-with-keras.ipynb | phuongxuanpham/SelfDrivingCar | gpl-3.0 |
Add one more convolution layer with dropout 50%, batch_size=50, nb_epoch=10 | # TODO: Build a model
from keras.layers.core import Dense, Activation, Flatten, Dropout
from keras.layers.convolutional import Convolution2D
from keras.layers.pooling import MaxPooling2D
# TODO: Re-construct the network and add dropout after the pooling layer.
model = Sequential()
# TODO: Build a Multi-layer feedforwar... | CarND-Keras-Lab/traffic-sign-classification-with-keras.ipynb | phuongxuanpham/SelfDrivingCar | gpl-3.0 |
Add one more convolution layer with dropout 50%, batch_size=50, nb_epoch=20, border_mode='same' | # TODO: Build a model
from keras.layers.core import Dense, Activation, Flatten, Dropout
from keras.layers.convolutional import Convolution2D
from keras.layers.pooling import MaxPooling2D
# TODO: Re-construct the network and add dropout after the pooling layer.
model = Sequential()
# TODO: Build a Multi-layer feedforwar... | CarND-Keras-Lab/traffic-sign-classification-with-keras.ipynb | phuongxuanpham/SelfDrivingCar | gpl-3.0 |
Add one more convolution layer with dropout 50%, batch_size=128, nb_epoch=20, border_mode='valid' | # TODO: Build a model
from keras.layers.core import Dense, Activation, Flatten, Dropout
from keras.layers.convolutional import Convolution2D
from keras.layers.pooling import MaxPooling2D
# TODO: Re-construct the network and add dropout after the pooling layer.
model = Sequential()
# TODO: Build a Multi-layer feedforwar... | CarND-Keras-Lab/traffic-sign-classification-with-keras.ipynb | phuongxuanpham/SelfDrivingCar | gpl-3.0 |
Best Validation Accuracy: 0.9897
Testing
Once you've picked out your best model, it's time to test it.
Load up the test data and use the evaluate() method to see how well it does.
Hint 1: The evaluate() method should return an array of numbers. Use the metrics_names property to get the labels. | # TODO: Load test data
with open('test.p', 'rb') as f:
test_data = pickle.load(f)
# TODO: Load the feature data to the variable X_train
X_test = test_data['features']
# TODO: Load the label data to the variable y_train
y_test = test_data['labels']
# TODO: Preprocess data & one-hot encode the labels
X_normaliz... | CarND-Keras-Lab/traffic-sign-classification-with-keras.ipynb | phuongxuanpham/SelfDrivingCar | gpl-3.0 |
Show me what you got! <img src=https://staticdelivery.nexusmods.com/mods/1151/images/543-1-1447533110.png style="width:40px;"> | # uncomment to see the values
# carbon_monoxide | Day_2/17-Pandas-Intro.ipynb | ueapy/enveast_python_course_materials | mit |
It is easy to create other useful plots using DataFrame: | fig, (ax0, ax1) = plt.subplots(ncols=2)
air_quality.boxplot(ax=ax0, column=['O3', 'PM10'])
air_quality.O3.plot(ax=ax1, kind="kde") | Day_2/17-Pandas-Intro.ipynb | ueapy/enveast_python_course_materials | mit |
Q: the plot is too small. How to make it bigger?
As well as just a simple line plot: | air_quality.O3.plot(grid=True, figsize=(12, 2)) | Day_2/17-Pandas-Intro.ipynb | ueapy/enveast_python_course_materials | mit |
Setting missing values
As you may notice, we have negative values of ozone concentration, which does not make sense. So, let us replace those negative values with NaN:
Q: how to list data entries with negative O3? | # your code here | Day_2/17-Pandas-Intro.ipynb | ueapy/enveast_python_course_materials | mit |
Some statistics | # air_quality.describe() | Day_2/17-Pandas-Intro.ipynb | ueapy/enveast_python_course_materials | mit |
Correlations and regressions
Is there correlations between the timeseries we loaded?
First, let's take a glance at the whole DataFrame using a fancy scatter_matrix function. | from pandas.tools.plotting import scatter_matrix
# with plt.style.context('ggplot'):
# scatter_matrix(air_quality, figsize=(7, 7)) | Day_2/17-Pandas-Intro.ipynb | ueapy/enveast_python_course_materials | mit |
Creating DataFrames
DataFrame can also be created manually, by grouping several Series together.
Now just for fun we switch to another dataset
create 2 Series objects from 2 CSV files
create a DataFrame by combining the two Series
Data are monthly values of
Southern Oscillation Index (SOI)
Outgoing Longwave Radi... | soi_df = pd.read_csv('../data/soi.csv', skiprows=1, parse_dates=[0], index_col=0, na_values=-999.9,
date_parser=lambda x: pd.datetime.strptime(x, '%Y%m'))
olr_df = pd.read_csv('../data/olr.csv', skiprows=1, parse_dates=[0], index_col=0, na_values=-999.9,
date_parser=lambda x: ... | Day_2/17-Pandas-Intro.ipynb | ueapy/enveast_python_course_materials | mit |
Ordinary Least Square (OLS) regressions
<img src=http://statsmodels.sourceforge.net/devel/_static/statsmodels_hybi_banner.png>
The recommeded way to build ordinaty least square regressions is by using statsmodels. | # import statsmodels.formula.api as sm
# sm_model = sm.ols(formula="SOI ~ OLR", data=df).fit()
# df['SOI'].plot()
# df['OLR'].plot()
# ax = sm_model.fittedvalues.plot(label="model prediction")
# ax.legend(loc="lower center", ncol=3) | Day_2/17-Pandas-Intro.ipynb | ueapy/enveast_python_course_materials | mit |
Advanced scatter plot
Using the power of matplotlib, we can create a scatter plot with points coloured by the date index. To do this we need to import one additional submodule: | # import matplotlib.dates as mdates | Day_2/17-Pandas-Intro.ipynb | ueapy/enveast_python_course_materials | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.