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
Add the Number of Rows to be considered as training data, test data and validation data in the input CSV which contains the training data
Trainrow = 1 testrow = 45 valrow = 49
_____no_output_____
MIT
Colab NoteBooks/BertSum_and_PreSumm_preprocessing.ipynb
gagan94/PreSumm
Reading the input text from CSV file mentioned here. Change according to requirement.
import json def format_to_lines(): p_ct = 0 i = 0 for i in range(Trainrow): df_csv = pd.read_csv('./fincident.csv',encoding='cp1252') dataset = [] d = _format_to_lines_new(df_csv,i) dataset.append(d) i += 1 pt_file = "{:s}.{:s}.{:d}.json".format('bert_data', "...
_____no_output_____
MIT
Colab NoteBooks/BertSum_and_PreSumm_preprocessing.ipynb
gagan94/PreSumm
Genereate JSON file of the trianing data from th CSV
format_to_lines()
Hello Colleagues The solution creation is failing in QTC 906 with all the users with generic error message saying authorisation is missing. but with the same users the solutions were created previously also. NOTE : Even after the error message is shown the solution can be seen in solution explorer window but when clic...
MIT
Colab NoteBooks/BertSum_and_PreSumm_preprocessing.ipynb
gagan94/PreSumm
Different Modules which are required below for Preprocessing
def _get_word_ngrams(n, sentences): """Calculates word n-grams for multiple sentences. """ assert len(sentences) > 0 assert n > 0 # words = _split_into_words(sentences) words = sum(sentences, []) # words = [w for w in words if w not in stopwords] return _get_ngrams(n, words) def _get_n...
_____no_output_____
MIT
Colab NoteBooks/BertSum_and_PreSumm_preprocessing.ipynb
gagan94/PreSumm
Execute the below code for Preprocessing for PreSumm Only
# For PreSumm class BertData(): def __init__(self): self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True) self.sep_token = '[SEP]' self.cls_token = '[CLS]' self.pad_token = '[PAD]' self.tgt_bos = '[unused0]' self.tgt_eos = '[unused1...
_____no_output_____
MIT
Colab NoteBooks/BertSum_and_PreSumm_preprocessing.ipynb
gagan94/PreSumm
Execute the below code for Preprocessing for BertSumm Only
# For BertSum class BertData(): def __init__(self): self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True) self.sep_vid = self.tokenizer.vocab['[SEP]'] self.cls_vid = self.tokenizer.vocab['[CLS]'] self.pad_vid = self.tokenizer.vocab['[PAD]'] def ...
_____no_output_____
MIT
Colab NoteBooks/BertSum_and_PreSumm_preprocessing.ipynb
gagan94/PreSumm
Execute the below code for Preprocessing for PreSumm Only
## For PreSumm Only def _format_to_bert(): p_ct = 0 for i in range(Trainrow): pt_file = "{:s}.{:s}.{:d}.json".format('bert_data', "train", p_ct) json_file = pt_file save_file = pt_file.replace('.json','.pt') p_ct += 1 bert = BertData() jobs = json.load(open(json_file)) datasets = [] ...
_____no_output_____
MIT
Colab NoteBooks/BertSum_and_PreSumm_preprocessing.ipynb
gagan94/PreSumm
Execute the below code for Preprocessing for PreSumm Only
## For BertSumm Only def _format_to_bert(): p_ct = 0 for i in range(Trainrow): pt_file = "{:s}.{:s}.{:d}.json".format('bert_data', "train", p_ct) json_file = pt_file save_file = pt_file.replace('.json','.pt') p_ct += 1 bert = BertData() jobs = json.load(open(json_file)) datasets = [] ...
inside [0, 18, 22] {'src': [101, 7592, 8628, 1996, 5576, 4325, 2003, 7989, 1999, 1053, 13535, 3938, 2575, 2007, 2035, 1996, 5198, 2007, 12391, 7561, 4471, 3038, 3166, 6648, 2003, 4394, 1012, 102, 101, 2021, 2007, 1996, 2168, 5198, 1996, 7300, 2020, 2580, 3130, 2036, 1012, 102, 101, 3602, 1024, 2130, 2044, 1996, 7561, 4...
MIT
Colab NoteBooks/BertSum_and_PreSumm_preprocessing.ipynb
gagan94/PreSumm
Image analysis in Python with SciPy and scikit-imageTo participate, please follow the preparation instructions athttps://github.com/scikit-image/skimage-tutorials/(click on **preparation.md**).TL;DR: Install Python 3.6, scikit-image, and the Jupyter notebook. Then clone this repo:```pythongit clone --depth=1 https://...
%run ../../check_setup.py
[✓] scikit-image 0.15.0 [✓] numpy 1.16.2 [✓] scipy 1.2.1 [✓] matplotlib 3.0.3 [✓] notebook 5.7.6 [✓] scikit-learn 0.20.3
CC-BY-4.0
workshops/2019-scipy/index.ipynb
whocaresustc/skimage-tutorials
Tf-idf Walkthrough for scikit-learn When I was using scikit-learn extremely handy `TfidfVectorizer` I had some trouble interpreting the results since they seem to be a little bit different from the standard convention of how the *term frequency-inverse document frequency* (tf-idf) is calculated. Here, I just put toget...
import numpy as np docs = np.array([ 'The sun is shining', 'The weather is sweet', 'The sun is shining and the weather is sweet'])
_____no_output_____
MIT
pattern-classification/machine_learning/scikit-learn/tfidf_scikit-learn.ipynb
gopala-kr/ds-notebooks
Raw term frequency [[back to top](Sections)] First, we will start with the *raw term frequency* tf(t, d), which is defined by the number of times a term *t* occurs in a document *t*Alternative term frequency definitions include the binary term frequency, log-scaled term frequency, and augmented term frequency [[1](R...
from sklearn.feature_extraction.text import CountVectorizer cv = CountVectorizer() tf = cv.fit_transform(docs).toarray() tf cv.vocabulary_
_____no_output_____
MIT
pattern-classification/machine_learning/scikit-learn/tfidf_scikit-learn.ipynb
gopala-kr/ds-notebooks
Based on the vocabulary, the word "and" would be the 1st feature in each document vector in `tf`, the word "is" the 2nd, the word "shining" the 3rd, etc. Normalized term frequency [[back to top](Sections)] In this section, we will take a brief look at how the tf-feature vector can be normalized, which will be useful ...
tf_norm = tf[2] / np.sqrt(np.sum(tf[2]**2)) tf_norm
_____no_output_____
MIT
pattern-classification/machine_learning/scikit-learn/tfidf_scikit-learn.ipynb
gopala-kr/ds-notebooks
In scikit-learn, we can use the [`TfidfTransformer`](http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfTransformer.html) to normalize the term frequencies if we disable the inverse document frequency calculation (`use_idf: False` and `smooth_idf=False`):
from sklearn.feature_extraction.text import TfidfTransformer tfidf = TfidfTransformer(use_idf=False, norm='l2', smooth_idf=False) tf_norm = tfidf.fit_transform(tf).toarray() print('Normalized term frequencies of document 3:\n %s' % tf_norm[-1])
Normalized term frequencies of document 3: [ 0.2773501 0.5547002 0.2773501 0.2773501 0.2773501 0.5547002 0.2773501]
MIT
pattern-classification/machine_learning/scikit-learn/tfidf_scikit-learn.ipynb
gopala-kr/ds-notebooks
Term frequency-inverse document frequency -- tf-idf [[back to top](Sections)] Most commonly, the term frequency-inverse document frequency (tf-idf) is calculated as follows [[1](References)]: $$\text{tf-idf}(t, d) = \text{tf}(t, d) \times \text{idf}(t),$$where idf is the inverse document frequency, which we will intr...
n_docs = len(docs) df_and = 1 idf_and = np.log(n_docs / (1 + df_and)) print('idf "and": %s' % idf_and) df_is = 3 idf_is = np.log(n_docs / (1 + df_is)) print('idf "is": %s' % idf_is) df_shining = 2 idf_shining = np.log(n_docs / (1 + df_shining)) print('idf "shining": %s' % idf_shining)
idf "and": 0.405465108108 idf "is": -0.287682072452 idf "shining": 0.0
MIT
pattern-classification/machine_learning/scikit-learn/tfidf_scikit-learn.ipynb
gopala-kr/ds-notebooks
Using those idfs, we can eventually calculate the tf-idfs for the 3rd document:
print('Tf-idfs in document 3:\n') print('tf-idf "and": %s' % (1 * idf_and)) print('tf-idf "is": %s' % (2 * idf_is)) print('tf-idf "shining": %s' % (1 * idf_shining))
Tf-idfs in document 3: tf-idf "and": 0.405465108108 tf-idf "is": -0.575364144904 tf-idf "shining": 0.0
MIT
pattern-classification/machine_learning/scikit-learn/tfidf_scikit-learn.ipynb
gopala-kr/ds-notebooks
Tf-idf in scikit-learn [[back to top](Sections)] The tf-idfs in scikit-learn are calculated a little bit differently. Here, the `+1` count is added to the idf, whereas instead of the denominator if the df: $$\text{idf}(t) = log{\frac{n_d}{\text{df}(d,t)}} + 1$$ We can demonstrate this by calculating the idfs manuall...
tf_and = 1 df_and = 1 tf_and * (np.log(n_docs / df_and) + 1) tf_shining = 2 df_shining = 3 tf_shining * (np.log(n_docs / df_shining) + 1) tf_is = 1 df_is = 2 tf_is * (np.log(n_docs / df_is) + 1) tfidf = TfidfTransformer(use_idf=True, smooth_idf=False, norm=None) tfidf.fit_transform(tf).toarray()[-1][0:3]
_____no_output_____
MIT
pattern-classification/machine_learning/scikit-learn/tfidf_scikit-learn.ipynb
gopala-kr/ds-notebooks
Normalized tf-idf [[back to top](Sections)] Now, let us calculate the normalized tf-idfs. Our feature vector of un-normalized tf-idfs for document 3 would look as follows if we'd applied the equation from the previous section to all words in the document:
tf_idfs_d3 = np.array([[ 2.09861229, 2.0, 1.40546511, 1.40546511, 1.40546511, 2.0, 1.40546511]])
_____no_output_____
MIT
pattern-classification/machine_learning/scikit-learn/tfidf_scikit-learn.ipynb
gopala-kr/ds-notebooks
Using the l2-norm, we then normalize the tf-idfs as follows:
tf_idfs_d3_norm = tf_idfs_d3[-1] / np.sqrt(np.sum(tf_idfs_d3[-1]**2)) tf_idfs_d3_norm
_____no_output_____
MIT
pattern-classification/machine_learning/scikit-learn/tfidf_scikit-learn.ipynb
gopala-kr/ds-notebooks
And finally, we compare the results to the results that the `TfidfTransformer` returns.
tfidf = TfidfTransformer(use_idf=True, smooth_idf=False, norm='l2') tfidf.fit_transform(tf).toarray()[-1]
_____no_output_____
MIT
pattern-classification/machine_learning/scikit-learn/tfidf_scikit-learn.ipynb
gopala-kr/ds-notebooks
Smooth idf [[back to top](Sections)] Another parameter in the `TfidfTransformer` is the `smooth_idf`, which is described as> smooth_idf : boolean, default=True Smooth idf weights by adding one to document frequencies, as if an extra document was seen containing every term in the collection exactly once. Prevents zer...
tfidf = TfidfTransformer(use_idf=True, smooth_idf=True, norm=None) tfidf.fit_transform(tf).toarray()[-1][:3] tf_and = 1 df_and = 1 tf_and * (np.log((n_docs+1) / (df_and+1)) + 1) tf_is = 2 df_is = 3 tf_is * (np.log((n_docs+1) / (df_is+1)) + 1) tf_shining = 1 df_shining = 2 tf_shining * (np.log((n_docs+1) / (df_shi...
_____no_output_____
MIT
pattern-classification/machine_learning/scikit-learn/tfidf_scikit-learn.ipynb
gopala-kr/ds-notebooks
TfidfVectorizer defaults [[back to top](Sections)] Finally, we now understand the default settings in the `TfidfTransformer`, which are: - `use_idf=True`- `smooth_idf=True`- `norm='l2'` And the equation can be summarized as $\text{tf-idf} = \text{tf}(t) \times (\text{idf}(t, d) + 1),$ where $\text{idf}(t) = log{...
tfidf = TfidfTransformer() tfidf.fit_transform(tf).toarray()[-1] smooth_tfidfs_d3 = np.array([[ 1.69314718, 2.0, 1.28768207, 1.28768207, 1.28768207, 2.0, 1.28768207]]) smooth_tfidfs_d3_norm = smooth_tfidfs_d3[-1] / np.sqrt(np.sum(smooth_tfidfs_d3[-1]**2)) smooth_tfidfs_d3_norm
_____no_output_____
MIT
pattern-classification/machine_learning/scikit-learn/tfidf_scikit-learn.ipynb
gopala-kr/ds-notebooks
This notebook is part of the $\omega radlib$ documentation: http://wradlib.org/wradlib-docs.Copyright (c) 2018, $\omega radlib$ developers.Distributed under the MIT License. See LICENSE.txt for more info. Beam Blockage Calculation using a DEM Here, we derive (**p**artial) **b**eam-**b**lockage (**PBB**) from a **D**ig...
import wradlib as wrl import matplotlib.pyplot as pl import matplotlib as mpl import warnings warnings.filterwarnings('ignore') try: get_ipython().magic("matplotlib inline") except: pl.ion() import numpy as np
_____no_output_____
MIT
notebooks/beamblockage/wradlib_beamblock.ipynb
kmuehlbauer/wradlib-notebooks
Setup for Bonn radar First, we need to define some radar specifications (here: *University of Bonn*).
sitecoords = (7.071663, 50.73052, 99.5) nrays = 360 # number of rays nbins = 1000 # number of range bins el = 1.0 # vertical antenna pointing angle (deg) bw = 1.0 # half power beam width (deg) range_res = 100. # range resolution (meters)
_____no_output_____
MIT
notebooks/beamblockage/wradlib_beamblock.ipynb
kmuehlbauer/wradlib-notebooks
Create the range, azimuth, and beamradius arrays.
r = np.arange(nbins) * range_res beamradius = wrl.util.half_power_radius(r, bw)
_____no_output_____
MIT
notebooks/beamblockage/wradlib_beamblock.ipynb
kmuehlbauer/wradlib-notebooks
We use - [wradlib.georef.sweep_centroids](http://wradlib.org/wradlib-docs/latest/generated/wradlib.georef.sweep_centroids.html) and - [wradlib.georef.spherical_to_proj](http://wradlib.org/wradlib-docs/latest/generated/wradlib.georef.spherical_to_proj.html) to calculate the spherical coordinates of the bin centroids an...
coord = wrl.georef.sweep_centroids(nrays, range_res, nbins, el) coords = wrl.georef.spherical_to_proj(coord[..., 0], np.degrees(coord[..., 1]), coord[..., 2], sitecoords) lon = coords[..., 0] lat = coords[..., 1] alt = coords[..., 2] polcoords...
_____no_output_____
MIT
notebooks/beamblockage/wradlib_beamblock.ipynb
kmuehlbauer/wradlib-notebooks
Preprocessing the digitial elevation model - Read the DEM from a ``geotiff`` file (in `WRADLIB_DATA`);- clip the region inside the bounding box;- map the DEM values to the polar grid points. *Note*: You can choose between the coarser resolution `bonn_gtopo.tif` (from GTOPO30) and the finer resolution `bonn_new.tif` (f...
#rasterfile = wrl.util.get_wradlib_data_file('geo/bonn_gtopo.tif') rasterfile = wrl.util.get_wradlib_data_file('geo/bonn_new.tif') ds = wrl.io.open_raster(rasterfile) rastervalues, rastercoords, proj = wrl.georef.extract_raster_dataset(ds, nodata=-32768.) # Clip the region inside our bounding box ind = wrl.util.find...
_____no_output_____
MIT
notebooks/beamblockage/wradlib_beamblock.ipynb
kmuehlbauer/wradlib-notebooks
Calculate Beam-Blockage Now we can finally apply the [wradlib.qual.beam_block_frac](http://wradlib.org/wradlib-docs/latest/generated/wradlib.qual.beam_block_frac.html) function to calculate the PBB.
PBB = wrl.qual.beam_block_frac(polarvalues, alt, beamradius) PBB = np.ma.masked_invalid(PBB) print(PBB.shape)
_____no_output_____
MIT
notebooks/beamblockage/wradlib_beamblock.ipynb
kmuehlbauer/wradlib-notebooks
So far, we calculated the fraction of beam blockage for each bin.But we need to into account that the radar signal travels along a beam. Cumulative beam blockage (CBB) in one bin along a beam will always be at least as high as the maximum PBB of the preceeding bins (see [wradlib.qual.cum_beam_block_frac](http://wradlib...
CBB = wrl.qual.cum_beam_block_frac(PBB) print(CBB.shape)
_____no_output_____
MIT
notebooks/beamblockage/wradlib_beamblock.ipynb
kmuehlbauer/wradlib-notebooks
Visualize Beamblockage Now we visualize- the average terrain altitude per radar bin- a beam blockage map- interaction with terrain along a single beam
# just a little helper function to style x and y axes of our maps def annotate_map(ax, cm=None, title=""): ticks = (ax.get_xticks()/1000).astype(np.int) ax.set_xticklabels(ticks) ticks = (ax.get_yticks()/1000).astype(np.int) ax.set_yticklabels(ticks) ax.set_xlabel("Kilometers") ax.set_ylabel("Ki...
_____no_output_____
MIT
notebooks/beamblockage/wradlib_beamblock.ipynb
kmuehlbauer/wradlib-notebooks
Visualize Beam Propagation showing earth curvature Now we visualize- interaction with terrain along a single beamIn this representation the earth curvature is shown. For this we assume the earth a sphere with exactly 6370000 m radius. This is needed to get the height ticks at nice position.
def height_formatter(x, pos): x = (x - 6370000) / 1000 fmt_str = '{:g}'.format(x) return fmt_str def range_formatter(x, pos): x = x / 1000. fmt_str = '{:g}'.format(x) return fmt_str
_____no_output_____
MIT
notebooks/beamblockage/wradlib_beamblock.ipynb
kmuehlbauer/wradlib-notebooks
- The [wradlib.vis.create_cg](http://wradlib.org/wradlib-docs/latest/generated/wradlib.vis.create_cg.html)-function is facilitated to create the curved geometries. - The actual data is plottet as (theta, range) on the parasite axis. - Some tweaking is needed to get the final plot look nice.
fig = pl.figure(figsize=(10, 6)) cgax, caax, paax = wrl.vis.create_cg('RHI', fig, 111) # azimuth angle angle = 225 # fix grid_helper er = 6370000 gh = cgax.get_grid_helper() gh.grid_finder.grid_locator2._nbins=80 gh.grid_finder.grid_locator2._steps=[1,2,4,5,10] # calculate beam_height and arc_distance for ke=1 # me...
_____no_output_____
MIT
notebooks/beamblockage/wradlib_beamblock.ipynb
kmuehlbauer/wradlib-notebooks
Deploy SageMaker Serverless Endpoint Sentiment Binary Classification (fine-tuning with KoELECTRA-Small-v3 model and Naver Sentiment Movie Corpus dataset)- KoELECTRA: https://github.com/monologg/KoELECTRA- Naver Sentiment Movie Corpus Dataset: https://github.com/e9t/nsmc--- OverviewAmazon SageMaker Serverless Inference...
!pip install -qU sagemaker botocore boto3 awscli !pip install --ignore-installed PyYAML !pip install transformers==4.12.5 import torch import torchvision import torchvision.models as models import sagemaker from sagemaker import get_execution_role from sagemaker.utils import name_from_base from sagemaker.pytorch import...
_____no_output_____
MIT
key_features/ptn_4.2_serverless-inference/serverless_endpoint_kornlp_nsmc.ipynb
aws-samples/sm-model-serving-patterns
2. Create SageMaker Serverless Endpoint---SageMaker Serverless Endpoint는 기존 SageMaker 리얼타임 엔드포인트 배포와 99% 유사합니다. 1%의 차이가 무엇일까요? Endpoint 구성 설정 시, ServerlessConfig에서 메모리 크기(`MemorySizeInMB`), 최대 동시 접속(`MaxConcurrency`)에 대한 파라메터만 추가하시면 됩니다.```pythonsm_client.create_endpoint_config( ... "ServerlessConfig": { "MemoryS...
from sagemaker.image_uris import retrieve deploy_instance_type = 'ml.m5.xlarge' pt_ecr_image_uri = retrieve( framework='pytorch', region=region, version='1.7.1', py_version='py3', instance_type = deploy_instance_type, accelerator_type=None, image_scope='inference' )
_____no_output_____
MIT
key_features/ptn_4.2_serverless-inference/serverless_endpoint_kornlp_nsmc.ipynb
aws-samples/sm-model-serving-patterns
Create a SageMaker Model`create_model` API를 호출하여 위 코드 셀에서 생성한 컨테이너의 정의를 포함하는 모델을 생성합니다.
model_name = f"KorNLPServerless-{nlp_task}-{strftime('%Y-%m-%d-%H-%M-%S', gmtime())}" create_model_response = sm_client.create_model( ModelName=model_name, Containers=[ { "Image": pt_ecr_image_uri, "Mode": "SingleModel", "ModelDataUrl": model_s3_uri, "Env...
_____no_output_____
MIT
key_features/ptn_4.2_serverless-inference/serverless_endpoint_kornlp_nsmc.ipynb
aws-samples/sm-model-serving-patterns
Create Endpoint Configuration`ServerlessConfig`으로 엔드포인트에 대한 서버리스 설정을 조정할 수 있습니다. 최대 동시 호출(`MaxConcurrency`; max concurrent invocations)은 1에서 50 사이이며, `MemorySize`는 1024MB, 2048MB, 3072MB, 4096MB, 5120MB 또는 6144MB를 선택할 수 있습니다.
endpoint_config_name = f"KorNLPServerlessEndpointConfig-{nlp_task}-{strftime('%Y-%m-%d-%H-%M-%S', gmtime())}" endpoint_config_response = sm_client.create_endpoint_config( EndpointConfigName=endpoint_config_name, ProductionVariants=[ { "VariantName": "AllTraffic", "ModelName": mod...
_____no_output_____
MIT
key_features/ptn_4.2_serverless-inference/serverless_endpoint_kornlp_nsmc.ipynb
aws-samples/sm-model-serving-patterns
Create a SageMaker Multi-container endpointcreate_endpoint API로 멀티 컨테이너 엔드포인트를 생성합니다. 기존의 엔드포인트 생성 방법과 동일합니다.
endpoint_name = f"KorNLPServerlessEndpoint-{nlp_task}-{strftime('%Y-%m-%d-%H-%M-%S', gmtime())}" endpoint_response = sm_client.create_endpoint( EndpointName=endpoint_name, EndpointConfigName=endpoint_config_name ) print(f"Creating Endpoint: {endpoint_response['EndpointArn']}")
_____no_output_____
MIT
key_features/ptn_4.2_serverless-inference/serverless_endpoint_kornlp_nsmc.ipynb
aws-samples/sm-model-serving-patterns
`describe_endpoint` API를 사용하여 엔드포인트 생성 상태를 확인할 수 있습니다. SageMaker 서버리스 엔드포인트는 일반적인 엔드포인트 생성보다 빠르게 생성됩니다. (약 2-3분)
%%time waiter = boto3.client('sagemaker').get_waiter('endpoint_in_service') print("Waiting for endpoint to create...") waiter.wait(EndpointName=endpoint_name) resp = sm_client.describe_endpoint(EndpointName=endpoint_name) print(f"Endpoint Status: {resp['EndpointStatus']}")
_____no_output_____
MIT
key_features/ptn_4.2_serverless-inference/serverless_endpoint_kornlp_nsmc.ipynb
aws-samples/sm-model-serving-patterns
Direct Invocation for Model 최초 호출 시 Cold start로 지연 시간이 발생하지만, 최초 호출 이후에는 warm 상태를 유지하기 때문에 빠르게 응답합니다. 물론 수 분 동안 호출이 되지 않거나 요청이 많아지면 cold 상태로 바뀐다는 점을 유의해 주세요.
model_sample_path = 'samples/nsmc.txt' !cat $model_sample_path with open(model_sample_path, mode='rb') as file: model_input_data = file.read() model_response = sm_runtime.invoke_endpoint( EndpointName=endpoint_name, ContentType="application/jsonlines", Accept="application/jsonlines", Body=model_i...
_____no_output_____
MIT
key_features/ptn_4.2_serverless-inference/serverless_endpoint_kornlp_nsmc.ipynb
aws-samples/sm-model-serving-patterns
Check Model Latency
import time start = time.time() for _ in range(10): model_response = sm_runtime.invoke_endpoint( EndpointName=endpoint_name, ContentType="application/jsonlines", Accept="application/jsonlines", Body=model_input_data ) inference_time = (time.time()-start) print(f'Inference time is {inference_time:.4f...
_____no_output_____
MIT
key_features/ptn_4.2_serverless-inference/serverless_endpoint_kornlp_nsmc.ipynb
aws-samples/sm-model-serving-patterns
Clean Up---
sm_client.delete_endpoint(EndpointName=endpoint_name) sm_client.delete_endpoint_config(EndpointConfigName=endpoint_config_name) sm_client.delete_model(ModelName=model_name)
_____no_output_____
MIT
key_features/ptn_4.2_serverless-inference/serverless_endpoint_kornlp_nsmc.ipynb
aws-samples/sm-model-serving-patterns
Datenvalidierung mit Voluptuous (Schemadefinitionen)In diesem Notebook verwenden wir [Voluptuous](https://github.com/alecthomas/voluptuous), um Schemata für unsere Daten zu definieren. Wir können dann die Schemaprüfung an verschiedenen Stellen unserer Bereinigung verwenden, um sicherzustellen, dass wir die Kriterien e...
import logging import pandas as pd from datetime import datetime from voluptuous import Schema, Required, Range, All, ALLOW_EXTRA from voluptuous.error import MultipleInvalid, Invalid
_____no_output_____
BSD-3-Clause
docs/clean-prep/voluptuous.ipynb
veit/jupyter-tutorial-de
2. Logger
logger = logging.getLogger(0) logger.setLevel(logging.WARNING)
_____no_output_____
BSD-3-Clause
docs/clean-prep/voluptuous.ipynb
veit/jupyter-tutorial-de
3. Beispieldaten lesen
sales = pd.read_csv('https://raw.githubusercontent.com/kjam/data-cleaning-101/master/data/sales_data.csv')
_____no_output_____
BSD-3-Clause
docs/clean-prep/voluptuous.ipynb
veit/jupyter-tutorial-de
4. Daten untersuchen
sales.head() sales.dtypes
_____no_output_____
BSD-3-Clause
docs/clean-prep/voluptuous.ipynb
veit/jupyter-tutorial-de
5. Schema definieren
schema = Schema({ Required('sale_amount'): All(float, Range(min=2.50, max=1450.99)), }, extra=ALLOW_EXTRA) error_count = 0 for s_id, sale in sales.T.to_dict().items(): try: schema(sale) except MultipleInvalid as e: logging.warning('issue with sale: %s (%s) -...
_____no_output_____
BSD-3-Clause
docs/clean-prep/voluptuous.ipynb
veit/jupyter-tutorial-de
Aktuell wissen wir jedoch noch nicht, ob* wir ein falsch definiertes Schema haben* möglicherweise negative Werte zurückgegeben oder falsch markiert werden* höhere Werte kombinierte Einkäufe oder Sonderverkäufe sind 6. Hinzufügen einer benutzerdefinierten Validierung
def ValidDate(fmt='%Y-%m-%d %H:%M:%S'): return lambda v: datetime.strptime(v, fmt) schema = Schema({ Required('timestamp'): All(ValidDate()), }, extra=ALLOW_EXTRA) error_count = 0 for s_id, sale in sales.T.to_dict().items(): try: schema(sale) except MultipleInvalid as e: logging.warning(...
_____no_output_____
BSD-3-Clause
docs/clean-prep/voluptuous.ipynb
veit/jupyter-tutorial-de
7. Gültige Datumsstrukturen sind noch keine gültigen Daten
def ValidDate(fmt='%Y-%m-%d %H:%M:%S'): def validation_func(v): try: assert datetime.strptime(v, fmt) <= datetime.now() except AssertionError: raise Invalid('date is in the future! %s' % v) return validation_func schema = Schema({ Required('timestamp'): All(ValidDate(...
_____no_output_____
BSD-3-Clause
docs/clean-prep/voluptuous.ipynb
veit/jupyter-tutorial-de
open boundary spin 1/2 1-D Heisenberg model$H = J \sum_i [S_i^z S_{i+1}^z + \frac{1}{2}(S_i^+ S_{i+1}^- + S_i^- S_{i+1}^+)]$exact result (Bethe Anstatz):L E/J16 -6.911737145574924 -10.453785760409632 -13.997315618224348 -21.085956314386364 -28.1754248597421
from renormalizer.mps import Mps, Mpo, solver from renormalizer.model import MolList2, ModelTranslator from renormalizer.utils import basis as ba from renormalizer.utils import Op import numpy as np # define the # of spins nspin = 16 # define the model # sigma^+ = S^+ # sigma^- = S^- # 1/2 sigma^x,y,z = S^x,y,z mode...
_____no_output_____
Apache-2.0
example/1D-Heisenberg.ipynb
liwt31/Renormalizer
Striplog from CSV
%matplotlib inline import matplotlib.pyplot as plt import numpy as np import striplog striplog.__version__ from striplog import Lexicon, Decor, Component, Legend, Interval, Striplog
_____no_output_____
Apache-2.0
striplog_def_Matt.ipynb
ThomasMGeo/CSV2Strip
Make legendMost of the stuff in the dicts you made were about **display** — so they are going to make `Decor` objects. A collection of `Decor`s makes a `Legend`. A `Legend` determines how a striplog is displayed.First I'll make the components, since those are easy. I'll move `'train'` into there too, since it is to do...
facies = { 's': Component({'lithology': 'sandstone', 'train':'y'}), 'i': Component({'lithology': 'interbedded', 'train':'y'}), 'sh': Component({'lithology': 'shale', 'train':'y'}), 'bs': Component({'lithology': 'sandstone', 'train': 'n'}), 't': Component({'lithology': 'turbidite', 'train':'y'}), ...
_____no_output_____
Apache-2.0
striplog_def_Matt.ipynb
ThomasMGeo/CSV2Strip
Read CSV into striplog
strip = Striplog.from_csv('test.csv') strip[0]
_____no_output_____
Apache-2.0
striplog_def_Matt.ipynb
ThomasMGeo/CSV2Strip
Deal with lithologyThe lithology has been turned into a component, but it's using the abbreviation... I can't figure out an elegant way to deal with this so, for now, we'll just loop over the striplog and fix it. We read the `data` item's lithology (`'s'` in the top layer), then look up the correct lithology name in o...
for s in strip: lith = s.data['lithology'] s.components = [facies[lith]] s.data = {} strip[0]
_____no_output_____
Apache-2.0
striplog_def_Matt.ipynb
ThomasMGeo/CSV2Strip
That's better!
strip.plot(legend)
_____no_output_____
Apache-2.0
striplog_def_Matt.ipynb
ThomasMGeo/CSV2Strip
Remove non-training layers
strip strip_train = Striplog([s for s in strip if s.primary['train'] == 'y']) strip_train strip_train.plot(legend)
_____no_output_____
Apache-2.0
striplog_def_Matt.ipynb
ThomasMGeo/CSV2Strip
This notebook aims to produce Figure S2 in Supplementary Material for the preprint:
import os import random import matplotlib.pyplot as plt import numpy as np import matplotlib.dates as mdates import datetime import time import csv import math import scipy import seaborn as sns from scipy.stats import iqr import h5py import pickle from tqdm import tqdm import copy from sklearn.ensemble import RandomFo...
_____no_output_____
Apache-2.0
ROC_classification.ipynb
yuewu57/mental_health_AMoSS
Load data
test_path='./all-true-colours-matlab-2017-02-27-18-38-12-nick/' participants_list, participants_data_list,\ participants_time_list=loadParticipants(test_path) Participants=make_classes(participants_data_list,\ participants_time_list,\ participant...
14050
Apache-2.0
ROC_classification.ipynb
yuewu57/mental_health_AMoSS
**Length=20w** * Missing-response-incorporated signature-based classification model (MRSCM, level2)
y_tests_mc, y_scores_mc=model_roc(cohort, minlen=20, training=0.7,order=2, sample_size=100) ) plot_roc(y_tests_mc, y_scores_mc, "signature_method_missingcount_2ndtrial", n_classes=3,lw=2)
The PostScript backend does not support transparency; partially transparent artists will be rendered opaque. The PostScript backend does not support transparency; partially transparent artists will be rendered opaque.
Apache-2.0
ROC_classification.ipynb
yuewu57/mental_health_AMoSS
* Missing-response-incorporated signature-based classification model (MRSCM, level3)
y_tests_mc3, y_scores_mc3=model_roc(cohort, minlen=20, training=0.7,order=3, sample_size=100) plot_roc(y_tests_mc3, y_scores_mc3, "signature_method_missingcount3", n_classes=3,lw=2)
The PostScript backend does not support transparency; partially transparent artists will be rendered opaque. The PostScript backend does not support transparency; partially transparent artists will be rendered opaque.
Apache-2.0
ROC_classification.ipynb
yuewu57/mental_health_AMoSS
* Naive classification model
if __name__ == "__main__": y_tests_naive, y_scores_naive=model_roc(cohort, minlen=20,\ training=0.7,\ order=None,\ sample_size=100,\ ...
The PostScript backend does not support transparency; partially transparent artists will be rendered opaque. The PostScript backend does not support transparency; partially transparent artists will be rendered opaque.
Apache-2.0
ROC_classification.ipynb
yuewu57/mental_health_AMoSS
Copyright 2018 The TensorFlow Authors.
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under...
_____no_output_____
Apache-2.0
site/ja/tutorials/keras/classification.ipynb
KarimaTouati/docs-l10n
はじめてのニューラルネットワーク:分類問題の初歩 View on TensorFlow.org Run in Google Colab View source on GitHub Note: これらのドキュメントは私たちTensorFlowコミュニティが翻訳したものです。コミュニティによる 翻訳は**ベストエフォート**であるため、この翻訳が正確であることや[英語の公式ドキュメント](https://www.tensorflow.org/?hl=en)の 最新の状態を反映したものであることを保証することはできません。 この翻訳の品質を向上させるためのご意見をお持ちの方は、GitHubリポ...
try: # Colab only %tensorflow_version 2.x except Exception: pass from __future__ import absolute_import, division, print_function, unicode_literals # TensorFlow と tf.keras のインポート import tensorflow as tf from tensorflow import keras # ヘルパーライブラリのインポート import numpy as np import matplotlib.pyplot as plt print(t...
_____no_output_____
Apache-2.0
site/ja/tutorials/keras/classification.ipynb
KarimaTouati/docs-l10n
ファッションMNISTデータセットのロード このガイドでは、[Fashion MNIST](https://github.com/zalandoresearch/fashion-mnist)を使用します。Fashion MNISTには10カテゴリーの白黒画像70,000枚が含まれています。それぞれは下図のような1枚に付き1種類の衣料品が写っている低解像度(28×28ピクセル)の画像です。 <img src="https://tensorflow.org/images/fashion-mnist-sprite.png" alt="Fashion MNIST sprite" width="600"> ...
fashion_mnist = keras.datasets.fashion_mnist (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
_____no_output_____
Apache-2.0
site/ja/tutorials/keras/classification.ipynb
KarimaTouati/docs-l10n
ロードしたデータセットは、NumPy配列になります。* `train_images` と `train_labels` の2つの配列は、モデルの訓練に使用される**訓練用データセット**です。* 訓練されたモデルは、 `test_images` と `test_labels` 配列からなる**テスト用データセット**を使ってテストします。画像は28×28のNumPy配列から構成されています。それぞれのピクセルの値は0から255の間の整数です。**ラベル**(label)は、0から9までの整数の配列です。それぞれの数字が下表のように、衣料品の**クラス**(class)に対応しています。 Label Class ...
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
_____no_output_____
Apache-2.0
site/ja/tutorials/keras/classification.ipynb
KarimaTouati/docs-l10n
データの観察モデルの訓練を行う前に、データセットのフォーマットを見てみましょう。下記のように、訓練用データセットには28×28ピクセルの画像が60,000枚含まれています。
train_images.shape
_____no_output_____
Apache-2.0
site/ja/tutorials/keras/classification.ipynb
KarimaTouati/docs-l10n
同様に、訓練用データセットには60,000個のラベルが含まれます。
len(train_labels)
_____no_output_____
Apache-2.0
site/ja/tutorials/keras/classification.ipynb
KarimaTouati/docs-l10n
ラベルはそれぞれ、0から9までの間の整数です。
train_labels
_____no_output_____
Apache-2.0
site/ja/tutorials/keras/classification.ipynb
KarimaTouati/docs-l10n
テスト用データセットには、10,000枚の画像が含まれます。画像は28×28ピクセルで構成されています。
test_images.shape
_____no_output_____
Apache-2.0
site/ja/tutorials/keras/classification.ipynb
KarimaTouati/docs-l10n
テスト用データセットには10,000個のラベルが含まれます。
len(test_labels)
_____no_output_____
Apache-2.0
site/ja/tutorials/keras/classification.ipynb
KarimaTouati/docs-l10n
データの前処理ネットワークを訓練する前に、データを前処理する必要があります。最初の画像を調べてみればわかるように、ピクセルの値は0から255の間の数値です。
plt.figure() plt.imshow(train_images[0]) plt.colorbar() plt.grid(False) plt.show()
_____no_output_____
Apache-2.0
site/ja/tutorials/keras/classification.ipynb
KarimaTouati/docs-l10n
ニューラルネットワークにデータを投入する前に、これらの値を0から1までの範囲にスケールします。そのためには、画素の値を255で割ります。**訓練用データセット**と**テスト用データセット**は、同じように前処理することが重要です。
train_images = train_images / 255.0 test_images = test_images / 255.0
_____no_output_____
Apache-2.0
site/ja/tutorials/keras/classification.ipynb
KarimaTouati/docs-l10n
**訓練用データセット**の最初の25枚の画像を、クラス名付きで表示してみましょう。ネットワークを構築・訓練する前に、データが正しいフォーマットになっていることを確認します。
plt.figure(figsize=(10,10)) for i in range(25): plt.subplot(5,5,i+1) plt.xticks([]) plt.yticks([]) plt.grid(False) plt.imshow(train_images[i], cmap=plt.cm.binary) plt.xlabel(class_names[train_labels[i]]) plt.show()
_____no_output_____
Apache-2.0
site/ja/tutorials/keras/classification.ipynb
KarimaTouati/docs-l10n
モデルの構築ニューラルネットワークを構築するには、まずモデルの階層を定義し、その後モデルをコンパイルします。 層の設定ニューラルネットワークを形作る基本的な構成要素は**層**(layer)です。層は、入力されたデータから「表現」を抽出します。それらの「表現」は、今取り組もうとしている問題に対して、より「意味のある」ものであることが期待されます。ディープラーニングモデルのほとんどは、単純な層の積み重ねで構成されています。`tf.keras.layers.Dense` のような層のほとんどには、訓練中に学習されるパラメータが存在します。
model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(128, activation='relu'), keras.layers.Dense(10, activation='softmax') ])
_____no_output_____
Apache-2.0
site/ja/tutorials/keras/classification.ipynb
KarimaTouati/docs-l10n
このネットワークの最初の層は、`tf.keras.layers.Flatten` です。この層は、画像を(28×28ピクセルの)2次元配列から、28×28=784ピクセルの、1次元配列に変換します。この層が、画像の中に積まれているピクセルの行を取り崩し、横に並べると考えてください。この層には学習すべきパラメータはなく、ただデータのフォーマット変換を行うだけです。ピクセルが1次元化されたあと、ネットワークは2つの `tf.keras.layers.Dense` 層となります。これらの層は、密結合あるいは全結合されたニューロンの層となります。最初の `Dense` 層には、128個のノード(あるはニューロン)があります。最後の層でも...
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
_____no_output_____
Apache-2.0
site/ja/tutorials/keras/classification.ipynb
KarimaTouati/docs-l10n
モデルの訓練ニューラルネットワークの訓練には次のようなステップが必要です。1. モデルに訓練用データを投入します—この例では `train_images` と `train_labels` の2つの配列です。2. モデルは、画像とラベルの対応関係を学習します。3. モデルにテスト用データセットの予測(分類)を行わせます—この例では `test_images` 配列です。その後、予測結果と `test_labels` 配列を照合します。 訓練を開始するには、`model.fit` メソッドを呼び出します。モデルを訓練用データに "fit"(適合)させるという意味です。
model.fit(train_images, train_labels, epochs=5)
_____no_output_____
Apache-2.0
site/ja/tutorials/keras/classification.ipynb
KarimaTouati/docs-l10n
モデルの訓練の進行とともに、損失値と正解率が表示されます。このモデルの場合、訓練用データでは0.88(すなわち88%)の正解率に達します。 正解率の評価次に、テスト用データセットに対するモデルの性能を比較します。
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2) print('\nTest accuracy:', test_acc)
_____no_output_____
Apache-2.0
site/ja/tutorials/keras/classification.ipynb
KarimaTouati/docs-l10n
ご覧の通り、テスト用データセットでの正解率は、訓練用データセットでの正解率よりも少し低くなります。この訓練時の正解率とテスト時の正解率の差は、**過学習**(over fitting)の一例です。過学習とは、新しいデータに対する機械学習モデルの性能が、訓練時と比較して低下する現象です。 予測するモデルの訓練が終わったら、そのモデルを使って画像の分類予測を行うことが出来ます。
predictions = model.predict(test_images)
_____no_output_____
Apache-2.0
site/ja/tutorials/keras/classification.ipynb
KarimaTouati/docs-l10n
これは、モデルがテスト用データセットの画像のひとつひとつを分類予測した結果です。最初の予測を見てみましょう。
predictions[0]
_____no_output_____
Apache-2.0
site/ja/tutorials/keras/classification.ipynb
KarimaTouati/docs-l10n
予測結果は、10個の数字の配列です。これは、その画像が10の衣料品の種類のそれぞれに該当するかの「確信度」を表しています。どのラベルが一番確信度が高いかを見てみましょう。
np.argmax(predictions[0])
_____no_output_____
Apache-2.0
site/ja/tutorials/keras/classification.ipynb
KarimaTouati/docs-l10n
というわけで、このモデルは、この画像が、アンクルブーツ、`class_names[9]` である可能性が最も高いと判断したことになります。これが正しいかどうか、テスト用ラベルを見てみましょう。
test_labels[0]
_____no_output_____
Apache-2.0
site/ja/tutorials/keras/classification.ipynb
KarimaTouati/docs-l10n
10チャンネルすべてをグラフ化してみることができます。
def plot_image(i, predictions_array, true_label, img): predictions_array, true_label, img = predictions_array[i], true_label[i], img[i] plt.grid(False) plt.xticks([]) plt.yticks([]) plt.imshow(img, cmap=plt.cm.binary) predicted_label = np.argmax(predictions_array) if predicted_label == tru...
_____no_output_____
Apache-2.0
site/ja/tutorials/keras/classification.ipynb
KarimaTouati/docs-l10n
0番目の画像と、予測、予測配列を見てみましょう。
i = 0 plt.figure(figsize=(6,3)) plt.subplot(1,2,1) plot_image(i, predictions, test_labels, test_images) plt.subplot(1,2,2) plot_value_array(i, predictions, test_labels) plt.show() i = 12 plt.figure(figsize=(6,3)) plt.subplot(1,2,1) plot_image(i, predictions, test_labels, test_images) plt.subplot(1,2,2) plot_value_arra...
_____no_output_____
Apache-2.0
site/ja/tutorials/keras/classification.ipynb
KarimaTouati/docs-l10n
予測の中のいくつかの画像を、予測値とともに表示してみましょう。正しい予測は青で、誤っている予測は赤でラベルを表示します。数字は予測したラベルのパーセント(100分率)を示します。自信があるように見えても間違っていることがあることに注意してください。
# X個のテスト画像、予測されたラベル、正解ラベルを表示します。 # 正しい予測は青で、間違った予測は赤で表示しています。 num_rows = 5 num_cols = 3 num_images = num_rows*num_cols plt.figure(figsize=(2*2*num_cols, 2*num_rows)) for i in range(num_images): plt.subplot(num_rows, 2*num_cols, 2*i+1) plot_image(i, predictions, test_labels, test_images) plt.subplot(num_rows, 2*nu...
_____no_output_____
Apache-2.0
site/ja/tutorials/keras/classification.ipynb
KarimaTouati/docs-l10n
最後に、訓練済みモデルを使って1枚の画像に対する予測を行います。
# テスト用データセットから画像を1枚取り出す img = test_images[0] print(img.shape)
_____no_output_____
Apache-2.0
site/ja/tutorials/keras/classification.ipynb
KarimaTouati/docs-l10n
`tf.keras` モデルは、サンプルの中の**バッチ**(batch)あるいは「集まり」について予測を行うように作られています。そのため、1枚の画像を使う場合でも、リスト化する必要があります。
# 画像を1枚だけのバッチのメンバーにする img = (np.expand_dims(img,0)) print(img.shape)
_____no_output_____
Apache-2.0
site/ja/tutorials/keras/classification.ipynb
KarimaTouati/docs-l10n
そして、予測を行います。
predictions_single = model.predict(img) print(predictions_single) plot_value_array(0, predictions_single, test_labels) _ = plt.xticks(range(10), class_names, rotation=45)
_____no_output_____
Apache-2.0
site/ja/tutorials/keras/classification.ipynb
KarimaTouati/docs-l10n
`model.predict` メソッドの戻り値は、リストのリストです。リストの要素のそれぞれが、バッチの中の画像に対応します。バッチの中から、(といってもバッチの中身は1つだけですが)予測を取り出します。
np.argmax(predictions_single[0])
_____no_output_____
Apache-2.0
site/ja/tutorials/keras/classification.ipynb
KarimaTouati/docs-l10n
PA005: High Value Customer Identification (Insiders) Ciclo 0 - Planejamento da solução (IOT) Ciclo 1 - Métricas de Validação de Clusters 1. Feature Engineering* Recency* Frequency* Monetary2. Métricas de Validação de clusters* WSS - (Within-Cluster Sum of Squares)* SS - (Silhouette Score)3. Cluster Analisys* Plot ...
from yellowbrick.cluster import KElbowVisualizer from yellowbrick.cluster import SilhouetteVisualizer from matplotlib import pyplot as plt from sklearn import cluster as c from sklearn import metrics as m from sklearn import preprocessing as pp from plotly import express as ...
/home/heitor/repos/insiders_clustering/venv/lib/python3.8/site-packages/tqdm/auto.py:22: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html from .autonotebook import tqdm as notebook_tqdm
MIT
notebooks/code3.ipynb
heitorfe/insiders_clustering
0.2. Helper Functions
pd.set_option('display.float_format', lambda x: '%.2f' % x) def num_attributes(df1): num_attributes = df1.select_dtypes(['int64', 'float64']) #central tendency ct1 = pd.DataFrame(num_attributes.apply(np.mean)).T ct2 = pd.DataFrame(num_attributes.apply(np.median)).T #dispersion d1 = pd.Da...
_____no_output_____
MIT
notebooks/code3.ipynb
heitorfe/insiders_clustering
0.3. Load Data
df_raw = pd.read_csv(r'../data/Ecommerce.csv')
_____no_output_____
MIT
notebooks/code3.ipynb
heitorfe/insiders_clustering
1.0. Data Description
df1 = df_raw.copy()
_____no_output_____
MIT
notebooks/code3.ipynb
heitorfe/insiders_clustering
1.1. Rename Columns
df1.columns df1.columns = ['invoice_no', 'stock_code', 'description', 'quantity', 'invoice_date', 'unit_price', 'customer_id', 'country']
_____no_output_____
MIT
notebooks/code3.ipynb
heitorfe/insiders_clustering
1.2. Data Shape
print(f'Number of rows: {df1.shape[0]}') print(f'Number of columns: {df1.shape[1]}')
Number of rows: 541909 Number of columns: 8
MIT
notebooks/code3.ipynb
heitorfe/insiders_clustering
1.3. Data Types
df1.dtypes
_____no_output_____
MIT
notebooks/code3.ipynb
heitorfe/insiders_clustering
1.4. Check NAs
df1.isna().sum()
_____no_output_____
MIT
notebooks/code3.ipynb
heitorfe/insiders_clustering
1.5. Fill NAs
#remove na df1 = df1.dropna(axis=0) print('Data removed: {:.0f}%'.format((1-(len(df1)/len(df_raw)))*100))
Data removed: 25%
MIT
notebooks/code3.ipynb
heitorfe/insiders_clustering
1.6. Change dtypes
df1.dtypes #invoice_no # df1['invoice_no'] = df1['invoice_no'].astype(int) #stock_code # df1['stock_code'] = df1['stock_code'].astype(int) #invoice_date --> Month --> b df1['invoice_date'] = pd.to_datetime(df1['invoice_date'], format=('%d-%b-%y')) #customer_id df1['customer_id'] = df1['customer_id'].astype(int...
_____no_output_____
MIT
notebooks/code3.ipynb
heitorfe/insiders_clustering
1.7. Descriptive statistics
num_attributes = df1.select_dtypes(['int64', 'float64']) cat_attributes = df1.select_dtypes(exclude = ['int64', 'float64', 'datetime64[ns]'])
_____no_output_____
MIT
notebooks/code3.ipynb
heitorfe/insiders_clustering
1.7.1. Numerical Attributes
m = num_attributes(df1) m
_____no_output_____
MIT
notebooks/code3.ipynb
heitorfe/insiders_clustering
1.7.1.1 Investigating 1. Negative quantity (devolution?)2. Price = 0 (Promo?) 1.7.2. Categorical Attributes
cat_attributes.head()
_____no_output_____
MIT
notebooks/code3.ipynb
heitorfe/insiders_clustering
Invoice no
#invoice_no -- some of them has one char df_invoice_char = df1.loc[df1['invoice_no'].apply(lambda x: bool(re.search('[^0-9]+', x))), :] len(df_invoice_char[df_invoice_char['quantity']<0]) print('Total of invoices with letter: {}'.format(len(df_invoice_char))) print('Total of negative quantaty: {}'.format(len(df1...
_____no_output_____
MIT
notebooks/code3.ipynb
heitorfe/insiders_clustering