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
Do NMF analysis and plot results:
nmf_results = imstack.imblock_nmf(4, plot_results=True)
_____no_output_____
MIT
examples/notebooks/atomai_atomstat.ipynb
aghosh92/atomai
Load Estonian weather service- https://www.ilmateenistus.ee/teenused/ilmainfo/ilmatikker/
import requests import datetime import xml.etree.ElementTree as ET import pandas as pd from pandas.api.types import is_string_dtype from pandas.api.types import is_numeric_dtype import geopandas as gpd import fiona from fiona.crs import from_epsg import numpy as np from shapely.geometry import Point import matplot...
_____no_output_____
MIT
interpol_precip.ipynb
allixender/py_interpol_demo
IDW in Python from scratch blogposthttps://www.geodose.com/2019/09/creating-idw-interpolation-from-scratch-python.html- IDW Algorithm Implementation in Python - IDW Interpolation Algorithm Based on Block Radius Sampling Point - IDW Interpolation based on Minimum Number of Sampling Point
geo_df_3301.dtypes from idw_basic import idw_rblock, idw_npoint x_idw_list1, y_idw_list1, z_head1 = idw_rblock(x=geo_df_3301['x'].astype(float).values.tolist(), y=geo_df_3301['y'].astype(float).values.tolist(), z=geo_df_3301['precip...
_____no_output_____
MIT
interpol_precip.ipynb
allixender/py_interpol_demo
_idw_npoint_ might take very long, due to ierative search radius increase to find at least n nearest neighbours
x_idw_list2, y_idw_list2, z_head2 = idw_npoint(x=geo_df_3301['x'].astype(float).values.tolist(), y=geo_df_3301['y'].astype(float).values.tolist(), z=geo_df_3301['airtemperature'].values.tolist(), ...
_____no_output_____
MIT
interpol_precip.ipynb
allixender/py_interpol_demo
Inverse distance weighting (IDW) in Python with a KDTreeBy Copyright (C) 2016 Paul Brodersen under GPL-3.0code: https://github.com/paulbrodersen/inverse_distance_weightingInverse distance weighting is an interpolation method that computes the score of query points based on the scores of their k-nearest neighbours, we...
import numpy as np import matplotlib.pyplot as plt %matplotlib inline import idw_knn XY_obs_coords = np.vstack([geo_df_3301['x'].values, geo_df_3301['y'].values]).T z_arr = geo_df_3301['precipitations'].values display(XY_obs_coords.shape) display(z_arr.shape) # returns a function that is trained (the tree setup) fo...
_____no_output_____
MIT
interpol_precip.ipynb
allixender/py_interpol_demo
Interpolation in Python with Radial Basis Function - https://stackoverflow.com/a/3114117
from scipy.interpolate import Rbf def scipy_idw(x, y, z, xi, yi): interp = Rbf(x, y, z, function='linear') return interp(xi, yi) def plot(x,y,z,grid): plt.figure() grid_flipped = np.flipud(grid) plt.imshow(grid, extent=(x.min(), x.max(), y.min(), y.max()), origin='lower') # plt.hold(True) ...
_____no_output_____
MIT
interpol_precip.ipynb
allixender/py_interpol_demo
surface/contour/mesh plotting of interpolated gridshttps://matplotlib.org/3.1.0/gallery/images_contours_and_fields/pcolormesh_levels.htmlsphx-glr-gallery-images-contours-and-fields-pcolormesh-levels-py
from matplotlib.colors import BoundaryNorm from matplotlib.ticker import MaxNLocator from matplotlib import cm nbins=15 levels = MaxNLocator(nbins=nbins).tick_values(z_arr_interp.min(), z_arr_interp.max()) # pick the desired colormap, sensible levels, and define a normalization # instance which takes data values and ...
_____no_output_____
MIT
interpol_precip.ipynb
allixender/py_interpol_demo
Writing interpolated array to a raster file- GeoTiff raster with GDAL Python
from fiona.crs import from_epsg import pyproj import osgeo.osr import gdal gdal.UseExceptions() # wkt_projection = CRS("EPSG:3301") -> techniclly should tae crs from the geodataframe crs = pyproj.Proj(from_epsg(3301)) srs = osgeo.osr.SpatialReference() srs.ImportFromProj4(crs.srs) wkt_projection = srs.ExportToWkt() ...
_____no_output_____
MIT
interpol_precip.ipynb
allixender/py_interpol_demo
Point Query RasterStats- https://pythonhosted.org/rasterstats/manual.htmlbasic-example
from rasterstats import point_query xm = gpd.read_file('ilmateenistus_precip_stations.shp', encoding="utf-8") pts_kd = point_query('ilmateenistus_precip_stations.shp', "kdtree_precip_rasterout1.tif") pts_rbf = point_query('ilmateenistus_precip_stations.shp', "rbf_precip_rasterout1.tif") pts_idw = point_query('ilmatee...
_____no_output_____
MIT
interpol_precip.ipynb
allixender/py_interpol_demo
Distirbuted Training of Mask-RCNN in Amazon SageMaker using EFSThis notebook is a step-by-step tutorial on distributed tranining of [Mask R-CNN](https://arxiv.org/abs/1703.06870) implemented in [TensorFlow](https://www.tensorflow.org/) framework. Mask R-CNN is also referred to as heavy weight object detection model an...
aws_region = # aws-region-code e.g. us-east-1 s3_bucket = # your-s3-bucket-name
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Stage COCO 2017 dataset in Amazon S3We use [COCO 2017 dataset](http://cocodataset.org/home) for training. We download COCO 2017 training and validation dataset to this notebook instance, extract the files from the dataset archives, and upload the extracted files to your Amazon [S3 bucket](https://docs.aws.amazon.com/A...
!cat ./prepare-s3-bucket.sh
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Using your *Amazon S3 bucket* as argument, run the cell below. If you have already uploaded COCO 2017 dataset to your Amazon S3 bucket, you may skip this step.
%%time !./prepare-s3-bucket.sh {s3_bucket}
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Copy COCO 2017 dataset from S3 to Amazon EFSNext, we copy COCO 2017 dataset from S3 to EFS file-system. The ```prepare-efs.sh``` script executes this step.
!cat ./prepare-efs.sh
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-efs.ipynb
fhirschmann/amazon-sagemaker-examples
If you have already copied COCO 2017 dataset from S3 to your EFS file-system, skip this step.
%%time !./prepare-efs.sh {s3_bucket}
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Build and push SageMaker training imagesFor this step, the [IAM Role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) attached to this notebook instance needs full access to Amazon ECR service. If you created this notebook instance using the ```./stack-sm.sh``` script in this repository, the IAM Role a...
!cat ./container/build_tools/build_and_push.sh
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Using your *AWS region* as argument, run the cell below.
%%time ! ./container/build_tools/build_and_push.sh {aws_region}
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Set ```tensorpack_image``` below to Amazon ECR URI of the image you pushed above.
tensorpack_image = # mask-rcnn-tensorpack-sagemaker ECR URI
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-efs.ipynb
fhirschmann/amazon-sagemaker-examples
AWS Samples Mask R-CNNUse ```./container-optimized/build_tools/build_and_push.sh``` script to build and push the AWS Samples Mask R-CNN training image to Amazon ECR.
!cat ./container-optimized/build_tools/build_and_push.sh
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Using your *AWS region* as argument, run the cell below.
%%time ! ./container-optimized/build_tools/build_and_push.sh {aws_region}
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Set ```aws_samples_image``` below to Amazon ECR URI of the image you pushed above.
aws_samples_image = # mask-rcnn-tensorflow-sagemaker ECR URI
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-efs.ipynb
fhirschmann/amazon-sagemaker-examples
SageMaker Initialization First we upgrade SageMaker to 2.3.0 API. If your notebook is already using latest Sagemaker 2.x API, you may skip the next cell.
! pip install --upgrade pip ! pip install sagemaker==2.3.0
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-efs.ipynb
fhirschmann/amazon-sagemaker-examples
We have staged the data and we have built and pushed the training docker image to Amazon ECR. Now we are ready to start using Amazon SageMaker.
%%time import os import time import boto3 import sagemaker from sagemaker import get_execution_role from sagemaker.estimator import Estimator role = get_execution_role() # provide a pre-existing role ARN as an alternative to creating a new role print(f'SageMaker Execution Role:{role}') client = boto3.client('sts') ac...
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Next, we set the Amazon ECR image URI used for training. You saved this URI in a previous step.
training_image = # set to tensorpack_image or aws_samples_image print(f'Training image: {training_image}')
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Define SageMaker Data ChannelsNext, we define the *train* and *log* data channels using EFS file-system. To do so, we need to specify the EFS file-system id, which is shown in the output of the command below.
!df -kh | grep 'fs-' | sed 's/\(fs-[0-9a-z]*\).*/\1/'
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Set the EFS ```file_system_id``` below to the ouput of the command shown above. In the cell below, we define the `train` data input channel.
from sagemaker.inputs import FileSystemInput # Specify EFS ile system id. file_system_id = # 'fs-xxxxxxxx' print(f"EFS file-system-id: {file_system_id}") # Specify directory path for input data on the file system. # You need to provide normalized and absolute path below. file_system_directory_path = '/mask-rcnn/sage...
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Below we create the log output directory and define the `log` data output channel.
# Specify directory path for log output on the EFS file system. # You need to provide normalized and absolute path below. # For example, '/mask-rcnn/sagemaker/output/log' # Log output directory must not exist file_system_directory_path = f'/mask-rcnn/sagemaker/output/log-{int(time.time())}' # Create the log output dir...
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Next, we define the model output location in S3. Set ```s3_bucket``` to your S3 bucket name prior to running the cell below. The model checkpoints, logs and Tensorboard events will be written to the log output directory on the EFS file system you created above. At the end of the model training, they will be copied from...
prefix = "mask-rcnn/sagemaker" #prefix in your bucket s3_output_location = f's3://{s3_bucket}/{prefix}/output' print(f'S3 model output location: {s3_output_location}')
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Configure Hyper-parametersNext we define the hyper-parameters. Note, some hyper-parameters are different between the two implementations. The batch size per GPU in TensorPack Faster-RCNN/Mask-RCNN is fixed at 1, but is configurable in AWS Samples Mask-RCNN. The learning rate schedule is specified in units of steps in ...
hyperparameters = { "mode_fpn": "True", "mode_mask": "True", "eval_period": 1, "batch_norm": "FreezeBN" }
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Define Training MetricsNext, we define the regular expressions that SageMaker uses to extract algorithm metrics from training logs and send them to [AWS CloudWatch metrics](https://docs.aws.amazon.com/en_pv/AmazonCloudWatch/latest/monitoring/working_with_metrics.html). These algorithm metrics are visualized in SageMak...
metric_definitions=[ { "Name": "fastrcnn_losses/box_loss", "Regex": ".*fastrcnn_losses/box_loss:\\s*(\\S+).*" }, { "Name": "fastrcnn_losses/label_loss", "Regex": ".*fastrcnn_losses/label_loss:\\s*(\\S+).*" }...
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Define SageMaker Training JobNext, we use SageMaker [Estimator](https://sagemaker.readthedocs.io/en/stable/estimators.html) API to define a SageMaker Training Job. We recommned using 32 GPUs, so we set ```instance_count=4``` and ```instance_type='ml.p3.16xlarge'```, because there are 8 Tesla V100 GPUs per ```ml.p3.16x...
# Give Amazon SageMaker Training Jobs Access to FileSystem Resources in Your Amazon VPC. security_group_ids = # ['sg-xxxxxxxx'] subnets = # [ 'subnet-xxxxxxx', 'subnet-xxxxxxx', 'subnet-xxxxxxx' ] sagemaker_session = sagemaker.session.Session(boto_session=session) mask_rcnn_estimator = Estimator(image_uri=trainin...
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Finally, we launch the SageMaker training job. See ```Training Jobs``` in SageMaker console to monitor the training job.
import time job_name=f'mask-rcnn-efs-{int(time.time())}' print(f"Launching Training Job: {job_name}") # set wait=True below if you want to print logs in cell output mask_rcnn_estimator.fit(inputs=data_channels, job_name=job_name, logs="All", wait=False)
_____no_output_____
Apache-2.0
advanced_functionality/distributed_tensorflow_mask_rcnn/mask-rcnn-efs.ipynb
fhirschmann/amazon-sagemaker-examples
Plotting and Programming in Python (Continued) Plotting
%matplotlib inline import matplotlib.pyplot as plt time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot(time, position) plt.xlabel('Time (hr)') plt.ylabel('Position (km)')
_____no_output_____
MIT
notebooks/Plotting_Tutorial/Tutorial_pt2.ipynb
chazbethelbrescia/pei2020
Plot direclty from Pandas DataFrame
import pandas as pd data = pd.read_csv('./gapminder_gdp_oceania.csv', index_col='country') # so we want to keep the (year) part only for clarity when plotting GDP vs. years # To do this we use strip(), which removes from the string the characters stated in the argument # This method works on stri...
_____no_output_____
MIT
notebooks/Plotting_Tutorial/Tutorial_pt2.ipynb
chazbethelbrescia/pei2020
Can plot many sets of data together
# Select two countries' worth of data. gdp_australia = data.loc['Australia'] gdp_nz = data.loc['New Zealand'] # Plot with differently-colored markers. plt.plot(years, gdp_australia, 'b-', label='Australia') plt.plot(years, gdp_nz, 'y-', label='New Zealand') # Create legend. plt.legend(loc='upper left') # location pa...
_____no_output_____
MIT
notebooks/Plotting_Tutorial/Tutorial_pt2.ipynb
chazbethelbrescia/pei2020
Save your plot to a file
# fig = plt.gcf() --> get current figure data.T.plot(kind='line') # must get the current figure AFTER it has been plotted fig = plt.gcf() plt.legend(loc='upper left') plt.xlabel('GDP per capita') plt.ylabel('Year') fig.savefig('my_figure.png')
_____no_output_____
MIT
notebooks/Plotting_Tutorial/Tutorial_pt2.ipynb
chazbethelbrescia/pei2020
ДекораторыДекоратор это функция, которая в качестве одного из аргументов принимает объект и что-то возвращает. Декораторы в Python можно применять ко всему: функциям, классам и методам. Основная цель декораторов – изменить поведение объекта, не меняя сам объект. Это очень гибкая функциональная возможность языка.Декори...
import time def timeit(f): def inner(*args, **kwargs): start = time.time() res = f(*args, **kwargs) end = time.time() print(f'{end - start} seconds') return res return inner @timeit def my_sum(*args, **kwargs): """Функция суммы""" return sum(*args, **kwargs) ...
0.0019989013671875 seconds
MIT
python_pd/04_functions/07_decorators.ipynb
AsakoKabe/python-bp
В такой реализации есть несколько проблем:- нет возможности отключить трассировку;- вывод в стандартный поток вывода (```sys.stdout```);- пропала строка документации и атрибуты декорируемой функции.
print(f'{my_sum.__name__ = }') print(f'{my_sum.__doc__ = }') help(my_sum)
my_sum.__name__ = 'inner' my_sum.__doc__ = None Help on function inner in module __main__: inner(*args, **kwargs)
MIT
python_pd/04_functions/07_decorators.ipynb
AsakoKabe/python-bp
Так как в Python функции являются объектами, то их можно изменять во время выполнения. В этом кроется решение этой проблемы. Можно скопировать нужные атрибуты декорируемой функции.Чтобы не копировать каждый атрибут вручную существует готовая реализация этого функционала в модуле ```functools``` стандартной библиотеки.
from functools import wraps def timeit(f): @wraps(f) def inner(*args, **kwargs): start = time.time() res = f(*args, **kwargs) end = time.time() print(f'{end - start} seconds') return res return inner @timeit def my_sum(*args, **kwargs): """Функция суммы""" ...
my_sum.__name__ = 'my_sum' my_sum.__doc__ = 'Функция суммы' Help on function my_sum in module __main__: my_sum(*args, **kwargs) Функция суммы
MIT
python_pd/04_functions/07_decorators.ipynb
AsakoKabe/python-bp
Параметризованные декораторыУ реализованного нами декоратора сильно ограниченное применения, попробуем его расширить.Отключение декоратора можно реализовать, используя глобальную переменную, например, ```dec_enabled```, принимающую значение ```True```, если декоратор активен и ```False``` в противном случае.Возможност...
import sys dec_enabled = True def timeit(file): def dec(func): @wraps(func) def inner(*args, **kwargs): start = time.time() res = func(*args, **kwargs) end = time.time() print(f'{end - start} seconds', file=file) return res return...
4999950000 0.0009996891021728516 seconds
MIT
python_pd/04_functions/07_decorators.ipynb
AsakoKabe/python-bp
Такой вариант будет работать при декорировании следующим образом ```@timeit(sys.stderr)```. Однако постоянно писать декораторы с тройной вложенностью это не путь питониста. Можно один раз сделать декоратор для декоратора, позволяющий передавать аргументы (да, декоратор для декоратора).
from functools import update_wrapper def with_args(dec): @wraps(dec) def wrapper(*args, **kwargs): def decorator(func): res = dec(func, *args, **kwargs) update_wrapper(res, func) return res return decorator return wrapper
_____no_output_____
MIT
python_pd/04_functions/07_decorators.ipynb
AsakoKabe/python-bp
Функция ```with_args``` принимает декоратор, оборачивает его в обертку ```wrapper```, внутри которой происходит создание нового декоратора. Исходный декоратор при этом не изменяется.
dec_enabled = True @with_args def timeit(func, file): def inner(*args, **kwargs): start = time.time() res = func(*args, **kwargs) end = time.time() print(f'{end - start} seconds', file=file) return res return inner if dec_enabled else func @timeit(sys.stderr) def my_sum...
4999950000 0.001997709274291992 seconds
MIT
python_pd/04_functions/07_decorators.ipynb
AsakoKabe/python-bp
Однако это все еще слишком сложно. Гораздо удобнее добавить возможность вызывать декоратор без аргументов. Попробуем воспользоваться только ключевыми аргументами.
dec_enabled = True def timeit(func=None, *, file=sys.stderr): if func is None: def dec(func): return timeit(func, file=file) return dec if dec_enabled else func @wraps(func) def inner(*args, **kwargs): start = time.time() res = func(*args, **kwargs) end =...
_____no_output_____
MIT
python_pd/04_functions/07_decorators.ipynb
AsakoKabe/python-bp
Теперь декоратор ```timeit``` можно вызывать двумя способами. Во-первых, не передавая никаких аргументов. Тогда вывод будет осуществляться в стандартный поток вывода. При этом помня, что декоратор раскрывается как ```f = timeit(f)```, можно видеть, что аргумент ```func``` принимает значение функции ```f```. Тогда перво...
dec_enabled = True @timeit def my_sum(*args, **kwargs): """Функция суммы""" return sum(*args, **kwargs) res = my_sum([i for i in range(int(1e5))]) print(res)
4999950000 0.0009999275207519531 seconds
MIT
python_pd/04_functions/07_decorators.ipynb
AsakoKabe/python-bp
Во-вторых, передавая в качестве именованного аргумента ```file``` ```sys.stderr``` или имя файла. В этом случае происходит явный вызов декоратора ```timeit(file=sys.stderr)``` без передачи аргумента ```func```, в связи с этим он принимает значение ```None```, а значит, выполняется первое условие и создается обертка ```...
dec_enabled = True @timeit(file=sys.stderr) def my_sum(*args, **kwargs): """Функция суммы""" return sum(*args, **kwargs) res = my_sum([i for i in range(int(1e5))]) print(res)
4999950000 0.000997304916381836 seconds
MIT
python_pd/04_functions/07_decorators.ipynb
AsakoKabe/python-bp
Благодаря переменной ```dec_enabled``` измерение времени можно отключить. В этом случае никаких накладных расходов, связанных с вызовом дополнительных функций не будет.К одной функции можно применить сразу несколько декораторов, порядок их работы будет зависеть от порядка их применения к функции. Рассмотрим на примере ...
def with_bun(f): @wraps(f) def inner(): print('-' * 8) f() print('-' * 8) return inner def with_vegetables(f): @wraps(f) def inner(): print(' onion') f() print(' tomato') return inner def with_sauce(f): @wraps(f) def inner(): prin...
_____no_output_____
MIT
python_pd/04_functions/07_decorators.ipynb
AsakoKabe/python-bp
Определим основную функцию и задекорируем ее.
@with_bun @with_vegetables @with_sauce def burger(): print(' cutlet') burger()
-------- onion sauce cutlet tomato --------
MIT
python_pd/04_functions/07_decorators.ipynb
AsakoKabe/python-bp
Если явно такое декорирование, то получиться следующая последовательность вызовов:
def burger(): print(' cutlet') burger = with_sauce(burger) burger = with_vegetables(burger) burger = with_bun(burger) burger()
-------- onion sauce cutlet tomato --------
MIT
python_pd/04_functions/07_decorators.ipynb
AsakoKabe/python-bp
Первым будет применяться самый нижний (внутренний) декоратор. Если изменить последовательность декорирования, то результат ожидаемо измениться.Вот еще пару примеров декораторов. Декоратор трассировки вызовов функций:
def trace(function=None, *, file=sys.stderr): if function is None: def dec(function): return trace(function, file=file) return dec if dec_enabled else function @wraps(function) def inner(*args, **kwargs): print(f'{function.__name__}, {args}, {kwargs}') return...
foo, (), {} Nothing
MIT
python_pd/04_functions/07_decorators.ipynb
AsakoKabe/python-bp
Декоратор проверки входа пользователя в систему (в упрощенном виде).
def is_authenticated(user): return user in ('monty', 'guido') def login_required(function=None, login_url=''): def user_passes_test(view_func): @wraps(view_func) def wrapped(user, *args, **kwargs): if is_authenticated(user): return view_func(user, *args, **kwargs) ...
user = 'monty' user = 'guido' Пользователь pyuty перенаправлен на страницу логина: localhost/login
MIT
python_pd/04_functions/07_decorators.ipynb
AsakoKabe/python-bp
TIME-SERIES DECOMPOSITION**File:** Decomposition.ipynb**Course:** Data Science Foundations: Data Mining in Python IMPORT LIBRARIES
import pandas as pd import numpy as np from matplotlib import pyplot as plt from matplotlib.dates import DateFormatter from statsmodels.tsa.seasonal import seasonal_decompose
_____no_output_____
Apache-2.0
Decomposition.ipynb
VladimirsHisamutdinovs/data-mining
LOAD AND PREPARE DATA
df = pd.read_csv('data/AirPassengers.csv', parse_dates=['Month'], index_col=['Month'])
_____no_output_____
Apache-2.0
Decomposition.ipynb
VladimirsHisamutdinovs/data-mining
PLOT DATA
fig, ax = plt.subplots() plt.xlabel('Year: 1949-1960') plt.ylabel('Monthly Passengers (1000s)') plt.title('Monthly Intl Air Passengers') plt.plot(df, color='black') ax.xaxis.set_major_formatter(DateFormatter('%Y'))
_____no_output_____
Apache-2.0
Decomposition.ipynb
VladimirsHisamutdinovs/data-mining
DECOMPOSE TIME SERIES - Decompose the time series into three components: trend, seasonal, and residuals or noise.- This commands also plots the components. - The argument `period` specifies that there are 12 observations (i.e., months) in the cycle.- By default, `seasonal_decompose` performs an additive (as opposed to...
# Set the figure size plt.rcParams['figure.figsize'] = [7, 8] # Plot the decomposition components sd = seasonal_decompose(df, period=12).plot()
_____no_output_____
Apache-2.0
Decomposition.ipynb
VladimirsHisamutdinovs/data-mining
- For growth over time, it may be more appropriate to use a multiplicative trend.- The approach can show consistent changes by percentage.- In this approach, the residuals should be centered on 1 instead of 0.
sd = seasonal_decompose(df, model='multiplicative').plot()
_____no_output_____
Apache-2.0
Decomposition.ipynb
VladimirsHisamutdinovs/data-mining
The Explicit Forward Time Centered Space (FTCS) Difference Equation for the Heat Equation John S Butler john.s.butler@tudublin.ie [Course Notes](https://johnsbutler.netlify.com/files/Teaching/Numerical_Analysis_for_Differential_Equations.pdf) [Github](https://github.com/john-s-butler-dit/Numerical-Analysis-Pytho...
# LIBRARY # vector manipulation import numpy as np # math functions import math # THIS IS FOR PLOTTING %matplotlib inline import matplotlib.pyplot as plt # side-stepping mpl backend import warnings warnings.filterwarnings("ignore")
_____no_output_____
MIT
Chapter 08 - Heat Equations/801_Heat Equation- FTCS.ipynb
jjcrofts77/Numerical-Analysis-Python
Discete GridThe region $\Omega$ is discretised into a uniform mesh $\Omega_h$. In the space $x$ direction into $N$ steps giving a stepsize of\begin{equation}h=\frac{1-0}{N},\end{equation}resulting in \begin{equation}x[i]=0+ih, \ \ \ i=0,1,...,N,\end{equation}and into $N_t$ steps in the time $t$ direction giving a ste...
N=10 Nt=1000 h=1/N k=1/Nt r=k/(h*h) time_steps=15 time=np.arange(0,(time_steps+.5)*k,k) x=np.arange(0,1.0001,h) X, Y = np.meshgrid(x, time) fig = plt.figure() plt.plot(X,Y,'ro'); plt.plot(x,0*x,'bo',label='Initial Condition'); plt.plot(np.ones(time_steps+1),time,'go',label='Boundary Condition'); plt.plot(x,0*x,'bo'); p...
_____no_output_____
MIT
Chapter 08 - Heat Equations/801_Heat Equation- FTCS.ipynb
jjcrofts77/Numerical-Analysis-Python
Discrete Initial and Boundary ConditionsThe discrete initial conditions are \begin{equation} w[i,0]=2x[i], \ \ 0 \leq x[i] \leq \frac{1}{2} \end{equation}\begin{equation}w[i,0]=2(1-x[i]), \ \ \frac{1}{2} \leq x[i] \leq 1 \end{equation}and the discrete boundary conditions are \begin{equation} w[0,j]=0, w[10,j]=0, \en...
w=np.zeros((N+1,time_steps+1)) b=np.zeros(N-1) # Initial Condition for i in range (1,N): w[i,0]=2*x[i] if x[i]>0.5: w[i,0]=2*(1-x[i]) # Boundary Condition for k in range (0,time_steps): w[0,k]=0 w[N,k]=0 fig = plt.figure(figsize=(8,4)) plt.plot(x,w[:,0],'o:',label='Initial Condition') plt...
_____no_output_____
MIT
Chapter 08 - Heat Equations/801_Heat Equation- FTCS.ipynb
jjcrofts77/Numerical-Analysis-Python
The Explicit Forward Time Centered Space (FTCS) Difference EquationThe explicit Forwards Time Centered Space (FTCS) difference equation of the Heat Equationis derived by discretising \begin{equation} \frac{\partial u_{ij}}{\partial t} = \frac{\partial^2 u_{ij}}{\partial x^2},\end{equation}around $(x_i,t_{j})$ giving ...
A=np.zeros((N-1,N-1)) for i in range (0,N-1): A[i,i]=1-2*r # DIAGONAL for i in range (0,N-2): A[i+1,i]=r # UPPER DIAGONAL A[i,i+1]=r # LOWER DIAGONAL fig = plt.figure(figsize=(6,4)); #plt.matshow(A); plt.imshow(A,interpolation='none'); plt.xticks(np.arange(N-1), np.arange(1,N-0.9,1)); plt.y...
_____no_output_____
MIT
Chapter 08 - Heat Equations/801_Heat Equation- FTCS.ipynb
jjcrofts77/Numerical-Analysis-Python
ResultsTo numerically approximate the solution at $t[1]$ the matrix equation becomes \begin{equation} \mathbf{w}_{1}=A\mathbf{w}_{0} +\mathbf{b}_{0} \end{equation}where all the right hand side is known. To approximate solution at time $t[2]$ we use the matrix equation\begin{equation} \mathbf{w}_{2}=A\mathbf{w}_{1} +\m...
fig = plt.figure(figsize=(12,6)) plt.subplot(121) for j in range (1,time_steps+1): b[0]=r*w[0,j-1] b[N-2]=r*w[N,j-1] w[1:(N),j]=np.dot(A,w[1:(N),j-1]) plt.plot(x,w[:,j],'o:',label='t[%s]=%s'%(j,np.round(time[j],4))) plt.xlabel('x') plt.ylabel('w') #plt.legend(loc='bottom', bbox_to_anchor=(0.5, -0.1)) p...
_____no_output_____
MIT
Chapter 08 - Heat Equations/801_Heat Equation- FTCS.ipynb
jjcrofts77/Numerical-Analysis-Python
Local Trunction ErrorThe local truncation error of the classical explicit difference approach to \begin{equation}\frac{\partial U}{\partial t} - \frac{\partial^2 U}{\partial x^2}=0,\end{equation} with\begin{equation}F_{ij}(w)=\frac{w_{ij+1}-w_{ij}}{k}-\frac{w_{i+1j}-2w_{ij}+w_{i-1j}}{h^2}=0,\end{equation} is \begin{eq...
_____no_output_____
MIT
Chapter 08 - Heat Equations/801_Heat Equation- FTCS.ipynb
jjcrofts77/Numerical-Analysis-Python
DS/CMPSC 410 MiniProject 3 Spring 2021 Instructor: John Yen TA: Rupesh Prajapati and Dongkuan Xu Learning Objectives- Be able to apply thermometer encoding to encode numerical variables into binary variable format.- Be able to apply k-means clustering to the Darknet dataset based on both thermometer encoding and one-h...
import pyspark import csv from pyspark import SparkContext from pyspark.sql import SparkSession from pyspark.sql.types import StructField, StructType, StringType, LongType from pyspark.sql.functions import col, column from pyspark.sql.functions import expr from pyspark.sql.functions import split from pyspark.sql.functi...
_____no_output_____
MIT
10. Thermometer Encoding and Cluster Evaluation/kMeans_OHE_TE_Eval.ipynb
yedkk/spark-data-mining
Exercise 1 (5 points)Complete the path for input file in the code below and enter your name in this Markdown cell:- Name: Kangdong Yuan
Scanners_df = ss.read.csv("/storage/home/kky5082/ds410/Lab10/sampled_profile.csv", header= True, inferSchema=True )
_____no_output_____
MIT
10. Thermometer Encoding and Cluster Evaluation/kMeans_OHE_TE_Eval.ipynb
yedkk/spark-data-mining
We can use printSchema() to display the schema of the DataFrame Scanners_df to see whether it was inferred correctly.
Scanners_df.printSchema() Scanners_df.where(col('mirai')).count()
_____no_output_____
MIT
10. Thermometer Encoding and Cluster Evaluation/kMeans_OHE_TE_Eval.ipynb
yedkk/spark-data-mining
Part A: One Hot Encoding This part is identical to that of Miniproject Deliverable 2We want to apply one hot encoding to the set of ports scanned by scanners. - A.1 Like Mini Project deliverable 1 and 2, we first convert the feature "ports_scanned_str" to a feature that is an Array of ports- A.2 We then calculate th...
# Scanners_df.select("ports_scanned_str").show(30) Scanners_df2=Scanners_df.withColumn("Ports_Array", split(col("ports_scanned_str"), "-") ) # Scanners_df2.persist().show(10)
_____no_output_____
MIT
10. Thermometer Encoding and Cluster Evaluation/kMeans_OHE_TE_Eval.ipynb
yedkk/spark-data-mining
A.1 We only need the column ```Ports_Array``` to calculate the top ports being scanned
Ports_Scanned_RDD = Scanners_df2.select("Ports_Array").rdd # Ports_Scanned_RDD.persist().take(5)
_____no_output_____
MIT
10. Thermometer Encoding and Cluster Evaluation/kMeans_OHE_TE_Eval.ipynb
yedkk/spark-data-mining
Because each port number in the Ports_Array column for each row occurs only once, we can count the total occurance of each port number through flatMap.
Ports_list_RDD = Ports_Scanned_RDD.map(lambda row: row[0] ) # Ports_list_RDD.persist() Ports_list2_RDD = Ports_Scanned_RDD.flatMap(lambda row: row[0] ) Port_count_RDD = Ports_list2_RDD.map(lambda x: (x, 1)) # Port_count_RDD.take(2) Port_count_total_RDD = Port_count_RDD.reduceByKey(lambda x,y: x+y, 1) # Port_count_total...
_____no_output_____
MIT
10. Thermometer Encoding and Cluster Evaluation/kMeans_OHE_TE_Eval.ipynb
yedkk/spark-data-mining
Exercise 2 (5%)Select top_ports to be the number of top ports you want to use for one-hot encoding. I recommend a number between 20 and 40.
top_ports=30 Sorted_Ports_RDD= Sorted_Count_Port_RDD.map(lambda x: x[1]) Top_Ports_list = Sorted_Ports_RDD.take(top_ports) # Top_Ports_list # Scanners_df3=Scanners_df2.withColumn(FeatureName, array_contains("Ports_Array", Top_Ports_list[0])) # Scanners_df3.show(10)
_____no_output_____
MIT
10. Thermometer Encoding and Cluster Evaluation/kMeans_OHE_TE_Eval.ipynb
yedkk/spark-data-mining
A.4 Generate Hot-One Encoded Feature for each of the top ports in the Top_Ports_list- Iterate through the Top_Ports_list so that each top port is one-hot encoded. Exercise 3 (5 %)Complete the following PySpark code for encoding the n ports using One Hot Encoding, where n is specified by the variable ```top_ports```
for i in range(0, top_ports - 1): # "Port" + Top_Ports_list[i] is the name of each new feature created through One Hot Encoding Scanners_df3 = Scanners_df2.withColumn("Port" + Top_Ports_list[i], array_contains("Ports_Array", Top_Ports_list[i])) Scanners_df2 = Scanners_df3 Scanners_df2.printSchema()
root |-- _c0: integer (nullable = true) |-- id: integer (nullable = true) |-- numports: integer (nullable = true) |-- lifetime: double (nullable = true) |-- Bytes: integer (nullable = true) |-- Packets: integer (nullable = true) |-- average_packetsize: integer (nullable = true) |-- MinUniqueDests: integer (null...
MIT
10. Thermometer Encoding and Cluster Evaluation/kMeans_OHE_TE_Eval.ipynb
yedkk/spark-data-mining
Part B Thermometer Encoding of Numerical Variables We encode the numerical variable numports (number of ports being scanned) using thermometer encoding
pow(2,15) Scanners_df3=Scanners_df2.withColumn("TE_numports_0", col("numports") > 0) Scanners_df2 = Scanners_df3 Scanners_df3.count() Scanners_df3.where(col('TE_numports_0')).count()
_____no_output_____
MIT
10. Thermometer Encoding and Cluster Evaluation/kMeans_OHE_TE_Eval.ipynb
yedkk/spark-data-mining
Exercise 4 (15%)Complete the following pyspark code to use the column "numports" to create 16 additional columns as follows:- TE_numports_0 : True, if the scanner scans more than 0 ports, otherwise False.- TE_numports_1 : True, if the scanner scans more than 2**0 (1) port, otherwise False.- TE_numports_2 : True, if th...
for i in range(0, 16): # "TE_numports_" + str(i+1) is the name of each new feature created for each Bin in Thermometer Encoding Scanners_df3 = Scanners_df2.withColumn("TE_numports_" + str(i+1), col("numports") > pow(2,i)) Scanners_df2 = Scanners_df3 Scanners_df2.printSchema()
root |-- _c0: integer (nullable = true) |-- id: integer (nullable = true) |-- numports: integer (nullable = true) |-- lifetime: double (nullable = true) |-- Bytes: integer (nullable = true) |-- Packets: integer (nullable = true) |-- average_packetsize: integer (nullable = true) |-- MinUniqueDests: integer (null...
MIT
10. Thermometer Encoding and Cluster Evaluation/kMeans_OHE_TE_Eval.ipynb
yedkk/spark-data-mining
Exercise 5 (5 points)What is the total number of scanners that scan more than 2^15 (i.e., 32768) ports? Complete the code below using Scanners_df2 to find out the answer.
HFScanners_df2 = Scanners_df2.where(col('TE_numports_15')) HFScanners_df2.count()
_____no_output_____
MIT
10. Thermometer Encoding and Cluster Evaluation/kMeans_OHE_TE_Eval.ipynb
yedkk/spark-data-mining
Exercise 6 (10 points)Complete the following code to use k-means to cluster the scanners using the following - thermometer encoding of 'numports' numerical feature- one-hot encoding of top k ports (k chosen by you in Exercise 2). Specify Parameters for k Means Clustering
km = KMeans(featuresCol="features", predictionCol="prediction").setK(50).setSeed(123) km.explainParams() input_features = [] for i in range(0, top_ports - 1): input_features.append( "Port"+Top_Ports_list[i] ) for i in range(0, 15): input_features.append( "TE_numports_" + str(i)) print(input_features) va = Vecto...
_____no_output_____
MIT
10. Thermometer Encoding and Cluster Evaluation/kMeans_OHE_TE_Eval.ipynb
yedkk/spark-data-mining
Exercise 7 (5 points)Complete the following code to find the size of all of the clusters generated.
summary = kmModel.summary summary.clusterSizes
_____no_output_____
MIT
10. Thermometer Encoding and Cluster Evaluation/kMeans_OHE_TE_Eval.ipynb
yedkk/spark-data-mining
Exercise 8 (5 points)Complete the following code to find the Silhouette Score of the clustering result.
evaluator = ClusteringEvaluator() silhouette = evaluator.evaluate(predictions) print('Silhouette Score of the Clustering Result is ', silhouette) centers = kmModel.clusterCenters() centers[0] print("Cluster Centers:") i=0 for center in centers: print("Cluster ", str(i+1), center) i = i+1
Cluster Centers: Cluster 1 [9.87079646e-01 9.83893805e-01 9.85663717e-01 9.87256637e-01 9.84424779e-01 9.82477876e-01 7.07964602e-04 8.84955752e-04 1.94690265e-03 1.00000000e+00 9.40707965e-01 5.30973451e-04 3.53982301e-04 6.37168142e-03 1.76991150e-04 1.59292035e-03 0.00000000e+00 0.00000000e+00 0.00000000e+00 0....
MIT
10. Thermometer Encoding and Cluster Evaluation/kMeans_OHE_TE_Eval.ipynb
yedkk/spark-data-mining
Part C Percentage of Mirai Malwares in Each Cluster Exercise 9 (10 points)Complete the following code to compute the percentage of Mirai Malwares, Zmap, and Masscan in each cluster.
cluster_eval_df = pd.DataFrame( columns = ['cluster ID', 'size', 'cluster center', 'mirai_ratio', 'zmap_ratio', 'masscan_ratio'] ) for i in range(0, 50): cluster_i = predictions.where(col('prediction')==i) cluster_i_size = cluster_i.count() cluster_i_mirai_count = cluster_i.where(col('mirai')).count() ...
Cluster 5 ; Mirai Ratio: 0.8424333084018948 ; Cluster Size: 16044 Cluster 10 ; Mirai Ratio: 0.009066183136899365 ; Cluster Size: 3309 Cluster 18 ; Mirai Ratio: 0.06232736223164228 ; Cluster Size: 36565 Cluster 20 ; Mirai Ratio: 0.07641921397379912 ; Cluster Size: 916 Cluster 22 ; Mirai Ratio: 0.007064364207221...
MIT
10. Thermometer Encoding and Cluster Evaluation/kMeans_OHE_TE_Eval.ipynb
yedkk/spark-data-mining
Exercise 10 (5 points) Identify all of the clusters that have a large percentage of Mirai malware. For example, you can choose clusters with at least 80% of Mirai ratio. If you use a different threshold (other than 80%), describe the threshold you used and the rational of your choice. Answer to Exercise 10: if I choo...
# You can filter predictions DataFrame (Spark) to get all scanners in a cluster. # For example, the code below selects scanners in cluster 5. However, you should # replace 5 with the ID of the cluster you want to investigate. cluster_selected = predictions.where((col('prediction')==5) | (col('prediction')==37)) # If y...
root |-- _c0: integer (nullable = true) |-- id: integer (nullable = true) |-- numports: integer (nullable = true) |-- lifetime: double (nullable = true) |-- Bytes: integer (nullable = true) |-- Packets: integer (nullable = true) |-- average_packetsize: integer (nullable = true) |-- MinUniqueDests: integer (null...
MIT
10. Thermometer Encoding and Cluster Evaluation/kMeans_OHE_TE_Eval.ipynb
yedkk/spark-data-mining
Exercise 11 (10 points)Complete the following code to find out, for each of the clusters you identified in Exercise 10, - (1) (5 points) determine whether they scan a common port, and - (2) (5 points) what is the port number if most of them in a cluster scan a common port. You canuse the code below to find out what to...
# You fill in the ??? based on the cluster you want to investigate. cluster_5= predictions.where(col('prediction')==5) cluster_37= predictions.where(col('prediction')==37) for i in range(0, top_ports -1): port_num = "Port" + Top_Ports_list[i] port_i_count = cluster_5.where(col(port_num)).count() if port_i_c...
Scanners of Port 23 = 1192 Scanners of Port 445 = 1 Scanners of Port 54594 = 1 Scanners of Port 80 = 30 Scanners of Port 8080 = 34 Scanners of Port 0 = 1 Scanners of Port 2323 = 1204 Scanners of Port 5555 = 17 Scanners of Port 81 = 14 Scanners of Port 1023 = 22 Scanners of Port 52869 = ...
MIT
10. Thermometer Encoding and Cluster Evaluation/kMeans_OHE_TE_Eval.ipynb
yedkk/spark-data-mining
Dictionaries in Python Welcome! This notebook will teach you about the dictionaries in the Python Programming Language. By the end of this lab, you'll know the basics dictionary operations in Python, including what it is, and the operations on it. Table of Contents Dictiona...
# Create the dictionary Dict = {"key1": 1, "key2": "2", "key3": [3, 3, 3], "key4": (4, 4, 4), ('key5'): 5, (0, 1): 6} Dict
_____no_output_____
RSA-MD
Python for DS, AI & Development/PY0101EN-2-3-Dictionaries.ipynb
mesbahiba/IBM_Professional_Data_Analyst
The keys can be strings:
# Access to the value by the key Dict["key1"]
_____no_output_____
RSA-MD
Python for DS, AI & Development/PY0101EN-2-3-Dictionaries.ipynb
mesbahiba/IBM_Professional_Data_Analyst
Keys can also be any immutable object such as a tuple:
# Access to the value by the key Dict[(0, 1)]
_____no_output_____
RSA-MD
Python for DS, AI & Development/PY0101EN-2-3-Dictionaries.ipynb
mesbahiba/IBM_Professional_Data_Analyst
Each key is separated from its value by a colon ":". Commas separate the items, and the whole dictionary is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this "{}".
# Create a sample dictionary release_year_dict = {"Thriller": "1982", "Back in Black": "1980", \ "The Dark Side of the Moon": "1973", "The Bodyguard": "1992", \ "Bat Out of Hell": "1977", "Their Greatest Hits (1971-1975)": "1976", \ "Saturday Night Fever": "1...
_____no_output_____
RSA-MD
Python for DS, AI & Development/PY0101EN-2-3-Dictionaries.ipynb
mesbahiba/IBM_Professional_Data_Analyst
In summary, like a list, a dictionary holds a sequence of elements. Each element is represented by a key and its corresponding value. Dictionaries are created with two curly braces containing keys and values separated by a colon. For every key, there can only be one single value, however, multiple keys can hold the sa...
# Get value by keys release_year_dict['Thriller']
_____no_output_____
RSA-MD
Python for DS, AI & Development/PY0101EN-2-3-Dictionaries.ipynb
mesbahiba/IBM_Professional_Data_Analyst
This corresponds to: Similarly for The Bodyguard
# Get value by key release_year_dict['The Bodyguard']
_____no_output_____
RSA-MD
Python for DS, AI & Development/PY0101EN-2-3-Dictionaries.ipynb
mesbahiba/IBM_Professional_Data_Analyst
Now let you retrieve the keys of the dictionary using the method release_year_dict():
# Get all the keys in dictionary release_year_dict.keys()
_____no_output_____
RSA-MD
Python for DS, AI & Development/PY0101EN-2-3-Dictionaries.ipynb
mesbahiba/IBM_Professional_Data_Analyst
You can retrieve the values using the method values():
# Get all the values in dictionary release_year_dict.values()
_____no_output_____
RSA-MD
Python for DS, AI & Development/PY0101EN-2-3-Dictionaries.ipynb
mesbahiba/IBM_Professional_Data_Analyst
We can add an entry:
# Append value with key into dictionary release_year_dict['Graduation'] = '2007' release_year_dict
_____no_output_____
RSA-MD
Python for DS, AI & Development/PY0101EN-2-3-Dictionaries.ipynb
mesbahiba/IBM_Professional_Data_Analyst
We can delete an entry:
# Delete entries by key del(release_year_dict['Thriller']) del(release_year_dict['Graduation']) release_year_dict
_____no_output_____
RSA-MD
Python for DS, AI & Development/PY0101EN-2-3-Dictionaries.ipynb
mesbahiba/IBM_Professional_Data_Analyst
We can verify if an element is in the dictionary:
# Verify the key is in the dictionary 'The Bodyguard' in release_year_dict
_____no_output_____
RSA-MD
Python for DS, AI & Development/PY0101EN-2-3-Dictionaries.ipynb
mesbahiba/IBM_Professional_Data_Analyst
Quiz on Dictionaries You will need this dictionary for the next two questions:
# Question sample dictionary soundtrack_dic = {"The Bodyguard":"1992", "Saturday Night Fever":"1977"} soundtrack_dic
_____no_output_____
RSA-MD
Python for DS, AI & Development/PY0101EN-2-3-Dictionaries.ipynb
mesbahiba/IBM_Professional_Data_Analyst
a) In the dictionary soundtrack_dict what are the keys ?
# Write your code below and press Shift+Enter to execute soundtrack_dic.keys()
_____no_output_____
RSA-MD
Python for DS, AI & Development/PY0101EN-2-3-Dictionaries.ipynb
mesbahiba/IBM_Professional_Data_Analyst
Double-click __here__ for the solution.<!-- Your answer is below:soundtrack_dic.keys() The Keys "The Bodyguard" and "Saturday Night Fever" --> b) In the dictionary soundtrack_dict what are the values ?
# Write your code below and press Shift+Enter to execute soundtrack_dic.values()
_____no_output_____
RSA-MD
Python for DS, AI & Development/PY0101EN-2-3-Dictionaries.ipynb
mesbahiba/IBM_Professional_Data_Analyst
Double-click __here__ for the solution.<!-- Your answer is below:soundtrack_dic.values() The values are "1992" and "1977"--> You will need this dictionary for the following questions: The Albums Back in Black, The Bodyguard and Thriller have the following music recording sales in millions 50, 50 and 65 respectively: ...
# Write your code below and press Shift+Enter to execute album_sales_dict = {"Back in Black":50, "The Bodyguard":50, "Thriller":65} album_sales_dict
_____no_output_____
RSA-MD
Python for DS, AI & Development/PY0101EN-2-3-Dictionaries.ipynb
mesbahiba/IBM_Professional_Data_Analyst
Double-click __here__ for the solution.<!-- Your answer is below:album_sales_dict = {"The Bodyguard":50, "Back in Black":50, "Thriller":65}--> b) Use the dictionary to find the total sales of Thriller:
# Write your code below and press Shift+Enter to execute album_sales_dict["Thriller"]
_____no_output_____
RSA-MD
Python for DS, AI & Development/PY0101EN-2-3-Dictionaries.ipynb
mesbahiba/IBM_Professional_Data_Analyst
Double-click __here__ for the solution.<!-- Your answer is below:album_sales_dict["Thriller"]--> c) Find the names of the albums from the dictionary using the method keys:
# Write your code below and press Shift+Enter to execute album_sales_dict.keys()
_____no_output_____
RSA-MD
Python for DS, AI & Development/PY0101EN-2-3-Dictionaries.ipynb
mesbahiba/IBM_Professional_Data_Analyst
Double-click __here__ for the solution.<!-- Your answer is below:album_sales_dict.keys()--> d) Find the names of the recording sales from the dictionary using the method values:
# Write your code below and press Shift+Enter to execute album_sales_dict.values()
_____no_output_____
RSA-MD
Python for DS, AI & Development/PY0101EN-2-3-Dictionaries.ipynb
mesbahiba/IBM_Professional_Data_Analyst
In this assignment, you'll continue working with the U.S. Education Dataset from Kaggle. The data gives detailed state level information on several facets of education on an annual basis. To learn more about the data and the column descriptions, you can view the Kaggle link above.Access this data using the Thinkful dat...
import matplotlib.pyplot as plt import numpy as np import pandas as pd from sqlalchemy import create_engine import warnings warnings.filterwarnings('ignore') postgres_user = 'dsbc_student' postgres_pw = '7*.8G9QH21' postgres_host = '142.93.121.174' postgres_port = '5432' postgres_db = 'useducation' engine = create_e...
_____no_output_____
MIT
Data_cleaning_Outlier_EDA_Practice.ipynb
sgf-afk/Class_Assignments
1. Consider the two variables: TOTAL_REVENUE and TOTAL_EXPENDITURE. Do these variables have outlier values?
education_df.info() education_df.head()
_____no_output_____
MIT
Data_cleaning_Outlier_EDA_Practice.ipynb
sgf-afk/Class_Assignments
__Time series data, I can interpolate the missing values__ Z-Score Test
from scipy.stats import zscore z_scores = zscore(education_df['TOTAL_REVENUE']) for threshold in range(1,10): print("The score threshold is: {}".format(threshold)) print("The indices of the outliers:") print(np.where(z_scores > threshold)) print("Number of outliers is: {}".format(len((np.where(z_scores...
The score threshold is: 1 The indices of the outliers: (array([ 3, 26, 52, 61, 89, 100, 112, 140, 151, 163, 168, 189, 191, 197, 202, 214, 220, 224, 241, 243, 249, 254, 266, 271, 275, 292, 294, 300, 305, 317, 322, 326, 343, 345, 351, 356, 368, 373, 377, 394, 396, 402, 407], dtype=int64),) Numbe...
MIT
Data_cleaning_Outlier_EDA_Practice.ipynb
sgf-afk/Class_Assignments
According to Zscores both have outliers 2. If you detect outliers in the TOTAL_REVENUE and TOTAL_EXPENDITURE variables, apply the techniques you learned in this checkpoint to eliminate them and validate that there's no outlier values after you handled them.
from scipy.stats.mstats import winsorize winsorized_revenue = winsorize(education_df["TOTAL_REVENUE"], (0, 0.05)) winsorized_expenditure = winsorize(education_df["TOTAL_EXPENDITURE"], (0, 0.05)) z_scores = zscore(winsorized_revenue) for threshold in range(1,10): print("The score threshold is: {}".format(threshold...
The score threshold is: 1 The indices of the outliers: (array([ 3, 19, 26, 52, 61, 66, 70, 87, 89, 95, 100, 112, 117, 121, 130, 138, 140, 143, 146, 151, 163, 168, 172, 181, 189, 191, 194, 197, 202, 214, 220, 224, 233, 241, 243, 246, 249, 254, 266, 271, 275, 292, 294, 297, 300, 305, 317, 3...
MIT
Data_cleaning_Outlier_EDA_Practice.ipynb
sgf-afk/Class_Assignments
After the outlier threshold of 3 (75%) we lose our outliers, Winsorization worked. 3. Create another variable by subtracting the original TOTAL_EXPENDITURE from TOTAL_REVENUE (before you eliminated the outliers). You can think of it as a kind of budget deficit in education. Do you find any outlier values in this new v...
education_df['Deficit'] = education_df['TOTAL_REVENUE'] - education_df['TOTAL_EXPENDITURE'] plt.boxplot(education_df['Deficit'], whis = 5)
_____no_output_____
MIT
Data_cleaning_Outlier_EDA_Practice.ipynb
sgf-afk/Class_Assignments