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
Test out your code by calling your function and printing the result.
# call the function to calculate the fraud percentage fraud_percentage = fraudulent_percentage(transaction_df) print('Fraudulent percentage = ', fraud_percentage) print('Total # of fraudulent pts: ', fraud_percentage*transaction_df.shape[0]) print('Out of (total) pts: ', transaction_df.shape[0])
Fraudulent percentage = 0.001727485630620034 Total # of fraudulent pts: 492.0 Out of (total) pts: 284807
MIT
Payment_Fraud_Detection/Fraud_Detection_Exercise.ipynb
simonmijares/ML-case-studies
EXERCISE: Split into train/test datasetsIn this example, we'll want to evaluate the performance of a fraud classifier; training it on some training data and testing it on *test data* that it did not see during the training process. So, we'll need to split the data into separate training and test sets.Complete the `tra...
from sklearn import model_selection # split into train/test def train_test_split(transaction_df, train_frac= 0.7, seed=1): '''Shuffle the data and randomly split into train and test sets; separate the class labels (the column in transaction_df) from the features. :param df: Dataframe of all credit car...
_____no_output_____
MIT
Payment_Fraud_Detection/Fraud_Detection_Exercise.ipynb
simonmijares/ML-case-studies
Test CellIn the cells below, I'm creating the train/test data and checking to see that result makes sense. The tests below test that the above function splits the data into the expected number of points and that the labels are indeed, class labels (0, 1).
# get train/test data (train_features, train_labels), (test_features, test_labels) = train_test_split(transaction_df, train_frac=0.7) train_labels # manual test # for a split of 0.7:0.3 there should be ~2.33x as many training as test pts print('Training data pts: ', len(train_features)) print('Test data pts: ', len(te...
Training data pts: 199364 Test data pts: 85443 First item: [ 1.2912400e+05 -1.9007544e-01 2.0332274e-01 -9.9623245e-01 -1.5969852e+00 3.1925786e+00 3.3569350e+00 2.8829932e-01 8.9500278e-01 -3.3002400e-01 -6.4690042e-01 -2.8278485e-01 2.3240909e-02 -4.2109159e-01 3.6824697e-01 -1.5846483e-01 -3.3475593e...
MIT
Payment_Fraud_Detection/Fraud_Detection_Exercise.ipynb
simonmijares/ML-case-studies
--- ModelingNow that you've uploaded your training data, it's time to define and train a model!In this notebook, you'll define and train the SageMaker, built-in algorithm, [LinearLearner](https://sagemaker.readthedocs.io/en/stable/linear_learner.html). A LinearLearner has two main applications:1. For regression tasks i...
# import LinearLearner from sagemaker import LinearLearner # instantiate LinearLearner predictor = LinearLearner(role=role, instance_count=1, instance_type='ml.c4.xlarge', predictor_type = 'binary_classifier', )
_____no_output_____
MIT
Payment_Fraud_Detection/Fraud_Detection_Exercise.ipynb
simonmijares/ML-case-studies
EXERCISE: Convert data into a RecordSet formatNext, prepare the data for a built-in model by converting the train features and labels into numpy array's of float values. Then you can use the [record_set function](https://sagemaker.readthedocs.io/en/stable/linear_learner.htmlsagemaker.LinearLearner.record_set) to forma...
# create RecordSet of training data formatted_train_data = predictor.record_set(train=train_features, labels=train_labels, channel='train')
_____no_output_____
MIT
Payment_Fraud_Detection/Fraud_Detection_Exercise.ipynb
simonmijares/ML-case-studies
EXERCISE: Train the EstimatorAfter instantiating your estimator, train it with a call to `.fit()`, passing in the formatted training data.
%%time # train the estimator on formatted training data predictor.fit(formatted_train_data)
Defaulting to the only supported framework/algorithm version: 1. Ignoring framework/algorithm version: 1. Defaulting to the only supported framework/algorithm version: 1. Ignoring framework/algorithm version: 1.
MIT
Payment_Fraud_Detection/Fraud_Detection_Exercise.ipynb
simonmijares/ML-case-studies
EXERCISE: Deploy the trained modelDeploy your model to create a predictor. We'll use this to make predictions on our test data and evaluate the model.
%%time # deploy and create a predictor linear_predictor = predictor.deploy(initial_instance_count=1, instance_type='ml.t2.medium')
Defaulting to the only supported framework/algorithm version: 1. Ignoring framework/algorithm version: 1.
MIT
Payment_Fraud_Detection/Fraud_Detection_Exercise.ipynb
simonmijares/ML-case-studies
--- Evaluating Your ModelOnce your model is deployed, you can see how it performs when applied to the test data.According to the deployed [predictor documentation](https://sagemaker.readthedocs.io/en/stable/linear_learner.htmlsagemaker.LinearLearnerPredictor), this predictor expects an `ndarray` of input features and r...
# test one prediction test_x_np = test_features.astype('float32') result = linear_predictor.predict(test_x_np[0]) print(result)
[label { key: "predicted_label" value { float32_tensor { values: 0.0 } } } label { key: "score" value { float32_tensor { values: 0.0002751190622802824 } } } ]
MIT
Payment_Fraud_Detection/Fraud_Detection_Exercise.ipynb
simonmijares/ML-case-studies
Helper function for evaluationThe provided function below, takes in a deployed predictor, some test features and labels, and returns a dictionary of metrics; calculating false negatives and positives as well as recall, precision, and accuracy.
# code to evaluate the endpoint on test data # returns a variety of model metrics def evaluate(predictor, test_features, test_labels, verbose=True): """ Evaluate a model on a test set given the prediction endpoint. Return binary classification metrics. :param predictor: A prediction endpoint :para...
_____no_output_____
MIT
Payment_Fraud_Detection/Fraud_Detection_Exercise.ipynb
simonmijares/ML-case-studies
Test ResultsThe cell below runs the `evaluate` function. The code assumes that you have a defined `predictor` and `test_features` and `test_labels` from previously-run cells.
print('Metrics for simple, LinearLearner.\n') # get metrics for linear predictor metrics = evaluate(linear_predictor, test_features.astype('float32'), test_labels, verbose=True) # verbose means we'll print out the metrics
Metrics for simple, LinearLearner. prediction (col) 0.0 1.0 actual (row) 0.0 85282 26 1.0 36 99 Recall: 0.733 Precision: 0.792 Accuracy: 0.999
MIT
Payment_Fraud_Detection/Fraud_Detection_Exercise.ipynb
simonmijares/ML-case-studies
Delete the EndpointI've added a convenience function to delete prediction endpoints after we're done with them. And if you're done evaluating the model, you should delete your model endpoint!
# Deletes a precictor.endpoint def delete_endpoint(predictor): try: boto3.client('sagemaker').delete_endpoint(EndpointName=predictor.endpoint) print('Deleted {}'.format(predictor.endpoint)) except: print('Already deleted: {}'.format(predictor.endpoint)) # delete the p...
The endpoint attribute has been renamed in sagemaker>=2. See: https://sagemaker.readthedocs.io/en/stable/v2.html for details. The endpoint attribute has been renamed in sagemaker>=2. See: https://sagemaker.readthedocs.io/en/stable/v2.html for details.
MIT
Payment_Fraud_Detection/Fraud_Detection_Exercise.ipynb
simonmijares/ML-case-studies
--- Model ImprovementsThe default LinearLearner got a high accuracy, but still classified fraudulent and valid data points incorrectly. Specifically classifying more than 30 points as false negatives (incorrectly labeled, fraudulent transactions), and a little over 30 points as false positives (incorrectly labeled, val...
# specify an output path prefix = 'creditcard' output_path = 's3://{}/{}'.format(bucket, prefix) # instantiate a LinearLearner # tune the model for a higher recall linear_recall = LinearLearner(role=role, train_instance_count=1, train_instance_type='ml.c4.xl...
train_instance_count has been renamed in sagemaker>=2. See: https://sagemaker.readthedocs.io/en/stable/v2.html for details. train_instance_type has been renamed in sagemaker>=2. See: https://sagemaker.readthedocs.io/en/stable/v2.html for details.
MIT
Payment_Fraud_Detection/Fraud_Detection_Exercise.ipynb
simonmijares/ML-case-studies
Train the tuned estimatorFit the new, tuned estimator on the formatted training data.
%%time # train the estimator on formatted training data linear_recall.fit(formatted_train_data)
Defaulting to the only supported framework/algorithm version: 1. Ignoring framework/algorithm version: 1. Defaulting to the only supported framework/algorithm version: 1. Ignoring framework/algorithm version: 1.
MIT
Payment_Fraud_Detection/Fraud_Detection_Exercise.ipynb
simonmijares/ML-case-studies
Deploy and evaluate the tuned estimatorDeploy the tuned predictor and evaluate it.We hypothesized that a tuned model, optimized for a higher recall, would have fewer false negatives (fraudulent transactions incorrectly labeled as valid); did the number of false negatives get reduced after tuning the model?
%%time # deploy and create a predictor recall_predictor = linear_recall.deploy(initial_instance_count=1, instance_type='ml.t2.medium') print('Metrics for tuned (recall), LinearLearner.\n') # get metrics for tuned predictor metrics = evaluate(recall_predictor, test_features.astype('float32'), ...
Metrics for tuned (recall), LinearLearner. prediction (col) 0.0 1.0 actual (row) 0.0 84317 991 1.0 20 115 Recall: 0.852 Precision: 0.104 Accuracy: 0.988
MIT
Payment_Fraud_Detection/Fraud_Detection_Exercise.ipynb
simonmijares/ML-case-studies
Delete the endpoint As always, when you're done evaluating a model, you should delete the endpoint. Below, I'm using the `delete_endpoint` helper function I defined earlier.
# delete the predictor endpoint delete_endpoint(recall_predictor)
The endpoint attribute has been renamed in sagemaker>=2. See: https://sagemaker.readthedocs.io/en/stable/v2.html for details. The endpoint attribute has been renamed in sagemaker>=2. See: https://sagemaker.readthedocs.io/en/stable/v2.html for details.
MIT
Payment_Fraud_Detection/Fraud_Detection_Exercise.ipynb
simonmijares/ML-case-studies
--- Improvement: Managing Class ImbalanceWe have a model that is tuned to get a higher recall, which aims to reduce the number of false negatives. Earlier, we discussed how class imbalance may actually bias our model towards predicting that all transactions are valid, resulting in higher false negatives and true negati...
# instantiate a LinearLearner # include params for tuning for higher recall # *and* account for class imbalance in training data linear_balanced = LinearLearner(role=role, train_instance_count=1, train_instance_type='ml.c4.xlarge', ...
train_instance_count has been renamed in sagemaker>=2. See: https://sagemaker.readthedocs.io/en/stable/v2.html for details. train_instance_type has been renamed in sagemaker>=2. See: https://sagemaker.readthedocs.io/en/stable/v2.html for details.
MIT
Payment_Fraud_Detection/Fraud_Detection_Exercise.ipynb
simonmijares/ML-case-studies
EXERCISE: Train the balanced estimatorFit the new, balanced estimator on the formatted training data.
%%time # train the estimator on formatted training data linear_balanced.fit(formatted_train_data)
Defaulting to the only supported framework/algorithm version: 1. Ignoring framework/algorithm version: 1. Defaulting to the only supported framework/algorithm version: 1. Ignoring framework/algorithm version: 1.
MIT
Payment_Fraud_Detection/Fraud_Detection_Exercise.ipynb
simonmijares/ML-case-studies
EXERCISE: Deploy and evaluate the balanced estimatorDeploy the balanced predictor and evaluate it. Do the results match with your expectations?
%%time # deploy and create a predictor balanced_predictor = linear_balanced.deploy(initial_instance_count=1, instance_type='ml.t2.medium') print('Metrics for balanced, LinearLearner.\n') # get metrics for balanced predictor metrics = evaluate(balanced_predictor, test_features.astype('float32'), ...
Metrics for balanced, LinearLearner. prediction (col) 0.0 1.0 actual (row) 0.0 84629 679 1.0 18 117 Recall: 0.867 Precision: 0.147 Accuracy: 0.992
MIT
Payment_Fraud_Detection/Fraud_Detection_Exercise.ipynb
simonmijares/ML-case-studies
Delete the endpoint When you're done evaluating a model, you should delete the endpoint.
# delete the predictor endpoint delete_endpoint(balanced_predictor)
The endpoint attribute has been renamed in sagemaker>=2. See: https://sagemaker.readthedocs.io/en/stable/v2.html for details. The endpoint attribute has been renamed in sagemaker>=2. See: https://sagemaker.readthedocs.io/en/stable/v2.html for details.
MIT
Payment_Fraud_Detection/Fraud_Detection_Exercise.ipynb
simonmijares/ML-case-studies
A note on metric variability: The above model is tuned for the best possible precision with recall fixed at about 90%. The recall is fixed at 90% during training, but may vary when we apply our trained model to a test set of data. --- Model DesignNow that you've seen how to tune and balance a LinearLearner. Create, tra...
%%time # instantiate and train a LinearLearner # include params for tuning for higher precision # *and* account for class imbalance in training data %%time # deploy and evaluate a predictor ## IMPORTANT # delete the predictor endpoint after evaluation
_____no_output_____
MIT
Payment_Fraud_Detection/Fraud_Detection_Exercise.ipynb
simonmijares/ML-case-studies
****** 11. 튜플과 집합****** *** 1 튜플 활용법***- 튜플(Tuples): 순서있는 임의의 객체 모음 (시퀀스형)- 튜플은 변경 불가능(Immutable)- 시퀀스형이 가지는 다음 연산 모두 지원 - 인덱싱, 슬라이싱, 연결, 반복, 멤버쉽 테스트 1-1 튜플 연산
t1 = () # 비어있는 튜플 t2 = (1,2,3) # 괄호 사용 t3 = 1,2,3 # 괄호가 없어도 튜플이 됨 print(type(t1), type(t2), type(t3)) # <type 'tuple'> <type 'tuple'> <type 'tuple'> r1 = (1,) # 자료가 한 개일 때는 반드시 콤마가 있어야 한다. r2 = 1, # 괄호는 없어도 콤마는 있어야 한다. print(type(r1)) print(type(r2)) # <type 'tuple'> # <type 'tuple'> t = (1, 2, 3) print(t ...
2 1
MIT
python3.6/.ipynb_checkpoints/python11-checkpoint.ipynb
gjbr5/python-link-e-learning
1-2 패킹과 언패킹 - 패킹 (Packing): 하나의 튜플 안에 여러 개의 데이터를 넣는 작업
t = 1, 2, 'hello' print(t) print(type(t))
(1, 2, 'hello') <class 'tuple'>
MIT
python3.6/.ipynb_checkpoints/python11-checkpoint.ipynb
gjbr5/python-link-e-learning
- 언패킹 (Unpacking): 하나의 튜플에서 여러 개의 데이터를 한꺼번에 꺼내와 각각 변수에 할당하는 작업
x, y, z = t
_____no_output_____
MIT
python3.6/.ipynb_checkpoints/python11-checkpoint.ipynb
gjbr5/python-link-e-learning
- 리스트로도 비슷한 작업이 가능하지만, 단순 패킹/언패킹 작업만을 목적으로 한다면 튜플 사용 추천
a = ['foo', 'bar', 4, 5] [x, y, z, w] = a print(x) print(y) print(z) print(w) print() x, y, z, w = a print(x) print(y) print(z) print(w)
foo bar 4 5 foo bar 4 5
MIT
python3.6/.ipynb_checkpoints/python11-checkpoint.ipynb
gjbr5/python-link-e-learning
- 튜플과 리스트와의 공통점 - 원소에 임의의 객체를 저장 - 시퀀스 자료형 - 인덱싱, 슬라이싱, 연결, 반복, 멤버쉽 테스트 연산 지원 - 리스트와 다른 튜플만의 특징 - 변경 불가능 (Immutable) - 튜플은 count와 index 외에 다른 메소드를 가지지 않는다.
T = (1, 2, 2, 3, 3, 4, 4, 4, 4, 5) print(T.count(4)) print(T.index(1))
4 0
MIT
python3.6/.ipynb_checkpoints/python11-checkpoint.ipynb
gjbr5/python-link-e-learning
- list() 와 tuple() 내장 함수를 사용하여 리스트와 튜플을 상호 변환할 수 있음
T = (1, 2, 3, 4, 5) L = list(T) L[0] = 100 print(L) T = tuple(L) print(T)
[100, 2, 3, 4, 5] (100, 2, 3, 4, 5)
MIT
python3.6/.ipynb_checkpoints/python11-checkpoint.ipynb
gjbr5/python-link-e-learning
1-3 튜플의 사용 용도 - 튜플을 사용하는 경우 1: 함수가 하나 이상의 값을 리턴하는 경우
def calc(a, b): return a+b, a*b x, y = calc(5, 4)
_____no_output_____
MIT
python3.6/.ipynb_checkpoints/python11-checkpoint.ipynb
gjbr5/python-link-e-learning
- 튜플을 사용하는 경우 2: 문자열 포멧팅
print('id : %s, name : %s' % ('gslee', 'GangSeong'))
id : gslee, name : GangSeong
MIT
python3.6/.ipynb_checkpoints/python11-checkpoint.ipynb
gjbr5/python-link-e-learning
- 튜플을 사용하는 경우 3: 고정된 값을 쌍으로 표현하는 경우
d = {'one':1, 'two':2} print(d.items()) # [('two', 2), ('one', 1)]
dict_items([('one', 1), ('two', 2)])
MIT
python3.6/.ipynb_checkpoints/python11-checkpoint.ipynb
gjbr5/python-link-e-learning
*** 2 집합 자료형***- set 내장 함수를 사용한 집합 자료 생성 - 변경 가능(Mutable)한 객체이다. - 각 원소간에 순서는 없다. - 각 원소는 중복될 수 없다. - [note] set은 컨네이너 자료형이지만 시퀀스 자료형은 아니다. 2-1 집합 자료형 생성
a = set([1, 2, 3]) print(type(a)) print(a) b = set((1, 2, 3)) print(type(b)) print(b) c = set({'a':1, 'b':2, 'c':3}) print(type(c)) print(c) d = set({'a':1, 'b':2, 'c':3}.values()) print(type(d)) print(d)
<class 'set'> {1, 2, 3}
MIT
python3.6/.ipynb_checkpoints/python11-checkpoint.ipynb
gjbr5/python-link-e-learning
- E-learning에서 언급하지 않았던 집합 만드는 방법 --> 꼭 기억하세요~
e = {1, 2, 3, 4, 5} print(type(e)) print(e)
<class 'set'> {1, 2, 3, 4, 5}
MIT
python3.6/.ipynb_checkpoints/python11-checkpoint.ipynb
gjbr5/python-link-e-learning
- set에는 동일한 자료가 중복해서 저장되지 않는다. 즉 중복이 자동으로 제거됨
f = {1, 1, 2, 2, 3, 3} g = set([1, 1, 2, 2, 3, 3]) print(f) print(g)
{1, 2, 3} {1, 2, 3}
MIT
python3.6/.ipynb_checkpoints/python11-checkpoint.ipynb
gjbr5/python-link-e-learning
- set의 원소로는 변경 불가능(Immutable)한 것만 할당 가능하다.
print(set()) # 빈 set 객체 생성 print(set([1, 2, 3, 4, 5])) # 초기 값은 일반적으로 시퀀스 자료형인 리스트를 넣어준다. print(set([1, 2, 3, 2, 3, 4])) # 중복된 원소는 한 나만 저장됨 print(set('abc')) # 문자열은 각 문자를 집합 원소로 지닌다. print(set([(1, 2, 3), (4, 5, 6)])) # 각 튜플은 원소로 가질 수 있음 print(set([[1, 2, 3], [4,...
_____no_output_____
MIT
python3.6/.ipynb_checkpoints/python11-checkpoint.ipynb
gjbr5/python-link-e-learning
- set의 기본 연산| set 연산 | 동일 연산자 | 내용 ||---------------------------|-------------|-----------------------------|| len(s) | | 원소의 개수 || x in s | | x가 집합 s의 원소인가? || x not in s | ...
A = set([1, 2, 3, 4, 5, 6, 7, 8, 9]) print(len(A)) # 집합의 원소의 수 print(5 in A) # 멤버십 테스트 print(10 not in A) # 멤버십 테스트
9 True True
MIT
python3.6/.ipynb_checkpoints/python11-checkpoint.ipynb
gjbr5/python-link-e-learning
2-2 집합 자료형 메소드 - set의 주요 메소드 - 다음 연산은 원래 집합은 변경하지 않고 새로운 집합을 반환한다. | set 연산 | 동일 연산자 | 내용 ||---------------------------|-------------|-----------------------------|| s.issubset(t) | s <= t | s가 t의 부분집합인가? || s.issuperset(t) | s >= t | s가 t의...
B = set([4, 5, 6, 10, 20, 30]) C = set([10, 20, 30]) print(C.issubset(B)) # C가 B의 부분집합? print(C <= B) print(B.issuperset(C)) # B가 C를 포함하는 집합? print(B >= C) print() A = set([1, 2, 3, 4, 5, 6, 7, 8, 9]) B = set([4, 5, 6, 10, 20, 30]) print(A.union(B)) # A와 B의 합집합 print(A | B) print(A) print(A.intersection(B)) # A와 ...
{1, 2, 3, 4, 5, 6, 7, 8, 9} True False
MIT
python3.6/.ipynb_checkpoints/python11-checkpoint.ipynb
gjbr5/python-link-e-learning
- set은 시퀀스 자료형이 아니므로 인덱싱, 슬라이싱, 정렬 등을 지원하지 않는다.
A = set([1, 2, 3, 4, 5, 6, 7, 8, 9]) print(A[0]) print(A[1:4]) print(A.sort())
_____no_output_____
MIT
python3.6/.ipynb_checkpoints/python11-checkpoint.ipynb
gjbr5/python-link-e-learning
- 집합을 리스트나 튜플로 변경가능 - 집합에 인덱싱, 슬라이싱, 정렬 등을 적용하기 위해서는 리스트나 튜플로 변경한다.
print(list(A)) print(tuple(A))
[1, 2, 3, 4, 5, 6, 7, 8, 9] (1, 2, 3, 4, 5, 6, 7, 8, 9)
MIT
python3.6/.ipynb_checkpoints/python11-checkpoint.ipynb
gjbr5/python-link-e-learning
- 하지만 집합에 for ~ in 연산은 적용 가능하다.
A = set([1, 2, 3, 4, 5, 6, 7, 8, 9]) for ele in A: print(ele,end=" ")
1 2 3 4 5 6 7 8 9
MIT
python3.6/.ipynb_checkpoints/python11-checkpoint.ipynb
gjbr5/python-link-e-learning
- set은 변경 가능(Mutable)한 자료 구조 객체 - 다음 메소드들은 set을 변경하는 집합 자료 구조 메소드들임| set 연산 | 동일 연산자 | 내용 ||---------------------------|-------------|-----------------------------|| s.update(t) | s &124;= t | s와 t의 합집합을 s에 저장 || s.intersection_update(t) | s &= t | s...
A = set([1, 2, 3, 4]) B = set([3, 4, 5, 6]) A.update(B) # A에 B 집합의 원소를 추가 시킴 print(A) A.intersection_update([4,5,6,7,8]) # &= print(A) A.difference_update([6,7,8]) # -= print(A) A.symmetric_difference_update([5,6,7]) # ^= print(A) A.add(8) # 원소 추가 print(A) A.remove(8) # 원소 제거 print(A) A.remove(10) # 없는 원소를 제거하면 Key...
set()
MIT
python3.6/.ipynb_checkpoints/python11-checkpoint.ipynb
gjbr5/python-link-e-learning
Parameter estimation in the glyoxalase system of _Leishmania infantum_. Part of the publicationSousa Silva, M. , Ferreira, A.E.N., Tomás, A.M., Cordeiro, C., Ponces Freire, A. (2005) Quantitative assessment of the glyoxalase pathway in Leishmania infantum as a therapeutic target by modelling and computer simulation....
%matplotlib inline import stimator as st
_____no_output_____
MIT
silva_et_al_2005_FEBS_J/parameter_estimation.ipynb
aeferreira/papers_repr_glyoxalases
Glyoxalase pathway in *L. infantum* This example uses **real data for a real biochemical pathway**.The main difference here is that we can actually use **two** time courses of experimental measures
glos = """ # Example file for S-timator title Glyoxalase system in L. Infantum variables SDLTSH HTA # variables (the order matches the timecourse files) #reactions (with stoichiometry and rate) glx1 : HTA -> SDLTSH, rate = V1*HTA/(Km1 + HTA) glx2 : SDLTSH ->, V2*SDLTSH/(Km2 + SDLTSH) find V1 in [0.00001, 0.0001] fi...
_____no_output_____
MIT
silva_et_al_2005_FEBS_J/parameter_estimation.ipynb
aeferreira/papers_repr_glyoxalases
DataThe data are two time courses with spectrophotometric measurements of SDL-TSH.
st.readTCs(['TSH2a.txt', 'TSH2b.txt']).plot(fig_size=(12,5))
_____no_output_____
MIT
silva_et_al_2005_FEBS_J/parameter_estimation.ipynb
aeferreira/papers_repr_glyoxalases
Parameter estimation
best = mglos.estimate() print (best) best.plot(fig_size=(12,5))
-- reading time courses ------------------------------- file C:\Users\tonho\Desktop\other_github_repos\papers_repr_glyoxalases\silva_et_al_2005_FEBS_J\TSH2a.txt: 244 time points, 2 variables file C:\Users\tonho\Desktop\other_github_repos\papers_repr_glyoxalases\silva_et_al_2005_FEBS_J\TSH2b.txt: 347 time points, 2 vari...
MIT
silva_et_al_2005_FEBS_J/parameter_estimation.ipynb
aeferreira/papers_repr_glyoxalases
Test Riksdagen SFS dokument * Denna [Jupyter Notebook](https://github.com/salgo60/open-data-examples/blob/master/Riksdagens%20dokument%20SFS.ipynb) * [KU anmälningar](https://github.com/salgo60/open-data-examples/blob/master/Riksdagens%20dokument%20KU-anm%C3%A4lningar.ipynb) * [Motioner](https://github.com/salgo60/...
from datetime import datetime now = datetime.now() print("Last run: ", datetime.now()) import urllib3, json import pandas as pd from tqdm.notebook import trange http = urllib3.PoolManager() pd.set_option("display.max.columns", None) urlbase ="http://data.riksdagen.se/dokumentlista/?sok=&doktyp=SFS&utformat=json&st...
_____no_output_____
MIT
Riksdagens dokument SFS.ipynb
salgo60/open-data-examples
Gissning * regl-riksg verkar vara Reglemente för Riksgäldskontoret * regl-riksb är nog Riksbanken
dftot.debattnamn.value_counts() ftot = dftot.sort_values(by='id', ascending=False) dftot.info() dftot.head(1000) print("End run: ", datetime.now())
_____no_output_____
MIT
Riksdagens dokument SFS.ipynb
salgo60/open-data-examples
Comparing 🌈 to 🌈Often, we'll want to directly compare two different Rainbows. A wrapper called `MultiRainbow` tries to make doing so a little simpler, by providing an interface to apply many of the familiar Rainbow methods to multiple objects at once.
from chromatic import * a = SimulatedRainbow(signal_to_noise=1000).inject_transit() b = SimulatedRainbow(signal_to_noise=np.sqrt(100*1000)).inject_transit() c = SimulatedRainbow(signal_to_noise=100).inject_transit() m = MultiRainbow([a, b, c], names=['noisy', 'noisier', 'noisiest']) m.bin(R=4).plot(spacing=0.01) m.imsh...
_____no_output_____
MIT
docs/multi.ipynb
zkbt/chromatic
m.animate_spectra()
_____no_output_____
MIT
docs/multi.ipynb
zkbt/chromatic
Implement a Stack A very common interview question is to begin by just implementing a Stack! Try your best to implement your own stack!It should have the methods:* Check if its empty* Push a new item* Pop an item* Peek at the top item* Return the size
class Stack(object): # Fill out the Stack Methods here def __init__(self): self.items = [] def isEmpty(self): return len(self.items) == 0 def push(self, e): self.items.append(e) def pop(self): return self.items.pop() def size(self): return len(self.items) ...
_____no_output_____
MIT
code/algorithms/course_udemy_1/Stacks, Queues and Deques/Interview/Questions - PRACTICE/Implement a Stack .ipynb
vicb1/miscellaneous
Lists in Python Welcome! This notebook will teach you about the lists in the Python Programming Language. By the end of this lab, you'll know the basics list operations in Python, including indexing, list operations and copy/clone list. Table of Contents About the Dataset ...
# Create a list L = ["Michael Jackson", 10.1, 1982] L
_____no_output_____
CC0-1.0
Day-2/Task-2/PY0101EN-2-2-Lists.ipynb
reddyprasade/2020-PY-101-
We can use negative and regular indexing with a list :
L[0],L[-3] # Print the elements on each index print('the same element using negative and positive indexing:\n Postive:',L[0], '\n Negative:' , L[-3] ) print('the same element using negative and positive indexing:\n Postive:',L[1], '\n Negative:' , L[-2] ) print('the same element using negative and positive indexing:...
_____no_output_____
CC0-1.0
Day-2/Task-2/PY0101EN-2-2-Lists.ipynb
reddyprasade/2020-PY-101-
List Content Lists can contain strings, floats, and integers. We can nest other lists, and we can also nest tuples and other data structures. The same indexing conventions apply for nesting:
# Sample List Sample_list = ["Michael Jackson", 10.1, 1982,2j+3,True ,[1, 2], ("A", 1)] Sample_list Sample_list[1],Sample_list[-6] Sample_list[2] Sample_list[0:5] Sample_list[-5:-1]
_____no_output_____
CC0-1.0
Day-2/Task-2/PY0101EN-2-2-Lists.ipynb
reddyprasade/2020-PY-101-
List Operations We can also perform slicing in lists. For example, if we want the last two elements, we use the following command:
# Sample List L = ["Michael Jackson", 10.1,1982,"MJ",1] L
_____no_output_____
CC0-1.0
Day-2/Task-2/PY0101EN-2-2-Lists.ipynb
reddyprasade/2020-PY-101-
# List slicing L[3:5]
_____no_output_____
CC0-1.0
Day-2/Task-2/PY0101EN-2-2-Lists.ipynb
reddyprasade/2020-PY-101-
We can use the method extend to add new elements to the list will be add at last:
# Use extend to add elements to list L = [ "Michael Jackson", 10.2] L.extend(['pop', 10]) L
_____no_output_____
CC0-1.0
Day-2/Task-2/PY0101EN-2-2-Lists.ipynb
reddyprasade/2020-PY-101-
Another similar method is append. If we apply append instead of extend, we add one element to the list:
# Use append to add elements to list L = [ "Michael Jackson", 10.2] L.append(['pop', 10]) L
_____no_output_____
CC0-1.0
Day-2/Task-2/PY0101EN-2-2-Lists.ipynb
reddyprasade/2020-PY-101-
Each time we apply a method, the list changes. If we apply extend we add two new elements to the list. The list L is then modified by adding two new elements:
# Use extend to add elements to list L = [ "Michael Jackson", 10.2] L.extend(['pop', 10]) L
_____no_output_____
CC0-1.0
Day-2/Task-2/PY0101EN-2-2-Lists.ipynb
reddyprasade/2020-PY-101-
If we append the list ['a','b'] we have one new element consisting of a nested list:
# Use append to add elements to list L.append(['a','b']) L
_____no_output_____
CC0-1.0
Day-2/Task-2/PY0101EN-2-2-Lists.ipynb
reddyprasade/2020-PY-101-
As lists are mutable, we can change them. For example, we can change the first element as follows:
# Change the element based on the index A = ["disco", 10, 1.2] print('Before change:', A) A[0] A[0] = 'hard rock' # Mutable print('After change:', A)
_____no_output_____
CC0-1.0
Day-2/Task-2/PY0101EN-2-2-Lists.ipynb
reddyprasade/2020-PY-101-
We can also delete an element of a list using the del command:
# Delete the element based on the index print('Before change:', A) del(A[0]) print('After change:', A)
_____no_output_____
CC0-1.0
Day-2/Task-2/PY0101EN-2-2-Lists.ipynb
reddyprasade/2020-PY-101-
We can convert a string to a list using split. For example, the method split translates every group of characters separated by a space into an element in a list:
# Split the string, default is by space 'hard rock'.split()
_____no_output_____
CC0-1.0
Day-2/Task-2/PY0101EN-2-2-Lists.ipynb
reddyprasade/2020-PY-101-
We can use the split function to separate strings on a specific character. We pass the character we would like to split on into the argument, which in this case is a comma. The result is a list, and each element corresponds to a set of characters that have been separated by a comma:
# Split the string by comma 'A,B,C,D'.split(',')
_____no_output_____
CC0-1.0
Day-2/Task-2/PY0101EN-2-2-Lists.ipynb
reddyprasade/2020-PY-101-
Copy and Clone List When we set one variable B equal to A; both A and B are referencing the same list in memory:
# Copy (copy by reference) the list A A = ["hard rock", 10, 1.2] B = A # copy by reference print('A:', A) print('B:', B)
_____no_output_____
CC0-1.0
Day-2/Task-2/PY0101EN-2-2-Lists.ipynb
reddyprasade/2020-PY-101-
id(A) id(B)
_____no_output_____
CC0-1.0
Day-2/Task-2/PY0101EN-2-2-Lists.ipynb
reddyprasade/2020-PY-101-
Initially, the value of the first element in B is set as hard rock. If we change the first element in A to banana, we get an unexpected side effect. As A and B are referencing the same list, if we change list A, then list B also changes. If we check the first element of B we get banana instead of hard rock:
# Examine the copy by reference print('B[0]:', B[0]) A[0] = "banana" A print('B[0]:', B[0]) B
_____no_output_____
CC0-1.0
Day-2/Task-2/PY0101EN-2-2-Lists.ipynb
reddyprasade/2020-PY-101-
This is demonstrated in the following figure: You can clone list **A** by using the following syntax:
# Clone (clone by value) the list A B = A[:] B
_____no_output_____
CC0-1.0
Day-2/Task-2/PY0101EN-2-2-Lists.ipynb
reddyprasade/2020-PY-101-
Variable **B** references a new copy or clone of the original list; this is demonstrated in the following figure: Now if you change A, B will not change:
print('B[0]:', B[0]) A[0] = "hard rock" print('B[0]:', B[0]) A B li = list(range(25,40)) # hear 25 is Starting Element and 39 Is Ending Element li li.append(10.25) li li.clear() li li_1 = [10,20,30,'hi','hello',True,2.5] li_1 li_2 = li_1.copy() li_2 li_1 li_1.append(10) li_1 li_1.count(10) li li.extend(li_1) li li_1 l...
_____no_output_____
CC0-1.0
Day-2/Task-2/PY0101EN-2-2-Lists.ipynb
reddyprasade/2020-PY-101-
|Methods|Description||--------|----------||**Append()**|it is used to add the element at last in a list||**clear()**| it is used to Clear the all the elemnts in a list||**copy()**| it is used to copy all the elements in to list||**count()**|We are counting perticular element is Reparting in list||**extend()**|Add Multi...
a = [[10,20,30], [2.5,3.5,4.5], [True,False,True]] a a[0] a[0][1] a[1] a[2]=10 a
_____no_output_____
CC0-1.0
Day-2/Task-2/PY0101EN-2-2-Lists.ipynb
reddyprasade/2020-PY-101-
Quiz on List Create a list a_list, with the following elements 1, hello, [1,2,3] and True.
# Write your code below and press Shift+Enter to execute
_____no_output_____
CC0-1.0
Day-2/Task-2/PY0101EN-2-2-Lists.ipynb
reddyprasade/2020-PY-101-
Double-click here for the solution.<!-- Your answer is below:a_list = [1, 'hello', [1, 2, 3] , True]a_list--> Find the value stored at index 1 of a_list.
# Write your code below and press Shift+Enter to execute
_____no_output_____
CC0-1.0
Day-2/Task-2/PY0101EN-2-2-Lists.ipynb
reddyprasade/2020-PY-101-
Double-click here for the solution.<!-- Your answer is below:a_list[1]--> Retrieve the elements stored at index 1, 2 and 3 of a_list.
# Write your code below and press Shift+Enter to execute
_____no_output_____
CC0-1.0
Day-2/Task-2/PY0101EN-2-2-Lists.ipynb
reddyprasade/2020-PY-101-
Double-click here for the solution.<!-- Your answer is below:a_list[1:4]--> Concatenate the following lists A = [1, 'a'] and B = [2, 1, 'd']:
# Write your code below and press Shift+Enter to execute
_____no_output_____
CC0-1.0
Day-2/Task-2/PY0101EN-2-2-Lists.ipynb
reddyprasade/2020-PY-101-
Przykład formatowania tekstu w notebooku Nagłówek 1 Nagłówek 2 Nagłówek 3Gdy piszemy jakiś tekst w snippet to może on być **pogrubiony**, *kursywa* albo ***jedno i drugie***Można również tworzyć w snippetach listy:- li1- li2Moga być one numerowane:1. li12. li3 Maginczne komendyMagiczne komendy to dodataki/usprawnie...
#lista magicznych komend wywoujemy przy użyciu poniższej komendy %lsmagic #gdy trzeba doinstalowaać jakieś biblioteki zewnętrzene to można to zrobić przy użyciu takiej metody ####Wykonywanie polceń systemu operacyjnego # instalacja dodatkowej biblioteki !pip install pydotplus x = 1.2342532345 x # zmieni liczbę cyfr ...
_____no_output_____
MIT
Dzien01/01-jupyter-intro.ipynb
gitgeoman/PAD2022
Import the data
import pandas as pd import numpy as np import networkx as nx import statsmodels import statsmodels.api as sm import scipy.stats as stats import matplotlib.pyplot as plt # import the csv file with JUST the politicians post comDB = pd.read_csv(r"/Users/tassan-mazzoccoarthur/Desktop/NETWORK SCIENCE (MOD. B)/1_Project...
_____no_output_____
CC0-1.0
Post_Group/com_matrix_and_network_creation.ipynb
Lally09-fx/net2020
Matrix creation
## Matrix creation with parties, politicians, posts #Setting variables size_df= len(df) parties=df['p_PARTITO'].unique().tolist() pol=df['p_politician'].unique().tolist() post=df['p_id'].unique().tolist() #Matrix shape= root/party/party.....pol/pol/pol/...../post/post/.../com/com total_size=1+len(parties)+len(pol)+len...
(88393, 88393)
CC0-1.0
Post_Group/com_matrix_and_network_creation.ipynb
Lally09-fx/net2020
Topic matrix:
#connect comments together on same topic -> only post and com matrix topic=df['c_topic'].unique().tolist() #Matrix creation #topic/topic/...com/com total_size=len(topic)+size_df shift_size=len(topic) topic_matrix = np.identity(total_size,dtype=int) for i in range(size_df): index_topic=topic.index(df['c_topic'][i])...
_____no_output_____
CC0-1.0
Post_Group/com_matrix_and_network_creation.ipynb
Lally09-fx/net2020
Adding attributes
import math #create a dictionnary of attributes to update a networkx graph # you should change the elements of the "attributes" array to select the attributes you want def create_attributes_dict_com(pandas_df, index_shift): #index_shift -> value to shift the index of the nodes we focus our attention on #for example: i...
_____no_output_____
CC0-1.0
Post_Group/com_matrix_and_network_creation.ipynb
Lally09-fx/net2020
Some cheks
import networkx as nx #First let's try with a small matrix m_trunc=m[:40000,:40000] np.set_printoptions(linewidth=200) print(m_trunc) G_trunc = nx.from_numpy_matrix(m_trunc) nx.write_graphml(G_trunc, "com_attributes_networkx_export.graphml")
_____no_output_____
CC0-1.0
Post_Group/com_matrix_and_network_creation.ipynb
Lally09-fx/net2020
Make your own heatmap based on Strava activitiesThis notebook shows you how to create your own heatmap based on your Strava activities.You need to create a Strava API application in order to use their API. Follow the instructions on this page to create your app: After setting up the app, note down the following inform...
!pip install stravaio folium import os import logging import json import urllib import requests import folium from stravaio import StravaIO # Paste your client id and client secret here. STRAVA_CLIENT_ID = "ENTER-YOUR-CLIENT-ID" STRAVA_CLIENT_SECRET = "ENTER-YOUR-CLIENT-SECRET"
_____no_output_____
MIT
examples/make_your_own.ipynb
rafaelschlatter/strava-heatmap
Authorization with StravaThe cell below creates the proper authorization link using the Stravaio Python library, which is used later to retrieve activities.It is important to run this cell, just pasting the access_token from your Strava settings will not work, because Stravaio needs to be authorized.- Run the cell bel...
params_oauth = { "client_id": STRAVA_CLIENT_ID, "response_type": "code", "redirect_uri": f"http://localhost:8000/authorization_successful", "scope": "read,profile:read_all,activity:read", "state": 'https://github.com/sladkovm/strava-http', # Sladkovm is the author of the Stravaio library "approv...
_____no_output_____
MIT
examples/make_your_own.ipynb
rafaelschlatter/strava-heatmap
The following cell retrieves an access token using the authorization code. That access token can then be used to retrieve Strava data.
payload = { "client_id": STRAVA_CLIENT_ID, "client_secret": STRAVA_CLIENT_SECRET, "grant_type": "authorization_code", "code": AUTHORIZATION_CODE, } response = requests.request( "POST", "https://www.strava.com/api/v3/oauth/token", data=payload ) response = json.loads(response.text) TOKEN = response...
_____no_output_____
MIT
examples/make_your_own.ipynb
rafaelschlatter/strava-heatmap
Part Two: Scaling & Normalization
from IPython.display import HTML from IPython.display import Image Image(url= "https://miro.medium.com/max/3316/1*yR54MSI1jjnf2QeGtt57PA.png") HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide(); } else { $('div.input').show(); } code_show = !code_show } $( document )...
_____no_output_____
Unlicense
Data Science/Data_Preprocessing/Notebooks/INFO7390_Assignment_3_Mini_Project_One_Part_Two.ipynb
RushabhNisher/Data
Table of Contents - 1. [Introduction](Introduction) - 1.1 [Abstract](abstract) - 1.2 [Importing Libraries](importing_libraries)- 2. [Data Scaling](data_scaling) - 2.1 [Standardization](standardization) - 2.2 [Normalization](normalization) - 2.3 [The Big Question – Normalize or Standardize?](the_bi...
# modules we'll use import pandas as pd import numpy as np # for Box-Cox Transformation from scipy import stats # for min_max scaling from sklearn import preprocessing from mlxtend.preprocessing import minmax_scaling # plotting modules import seaborn as sns import matplotlib import matplotlib.pyplot as plt from ast...
_____no_output_____
Unlicense
Data Science/Data_Preprocessing/Notebooks/INFO7390_Assignment_3_Mini_Project_One_Part_Two.ipynb
RushabhNisher/Data
2.0 Data Scaling Why Should we Use Feature Scaling?The first question we need to address – why do we need to scale the variables in our dataset? Some machine learning algorithms are sensitive to feature scaling while others are virtually invariant to it. Machine learning models learn a mapping from input variables to...
# generate 1000 data points randomly drawn from an exponential distribution original_data = np.random.exponential(size=1000) # mix-max scale the data between 0 and 1 scaled_data = minmax_scaling(original_data, columns=[0]) # plot both together to compare fig, ax = plt.subplots(1,2) sns.distplot(original_data, ax=ax[0...
_____no_output_____
Unlicense
Data Science/Data_Preprocessing/Notebooks/INFO7390_Assignment_3_Mini_Project_One_Part_Two.ipynb
RushabhNisher/Data
2.2 Normalization **Normalization:** Change in the shape of the distribution of data.Normalization scales each input variable separately to the range 0-1, which is the range for floating-point values where we have the most precision. Normalization requires that you know or are able to accurately estimate the minimum ...
# normalize the exponential data with boxcox normalized_data = stats.boxcox(original_data) # plot both together to compare fig, ax=plt.subplots(1,2) sns.distplot(original_data, ax=ax[0]) ax[0].set_title("Original Data") sns.distplot(normalized_data[0], ax=ax[1]) ax[1].set_title("Normalized data")
_____no_output_____
Unlicense
Data Science/Data_Preprocessing/Notebooks/INFO7390_Assignment_3_Mini_Project_One_Part_Two.ipynb
RushabhNisher/Data
2.3 The Big Question – Normalize or Standardize? Normalization vs. standardization is an eternal question among machine learning newcomers. Let me elaborate on the answer in this section.- Normalization is good to use when you know that the distribution of your data does not follow a Gaussian distribution. This can be...
#create columns of various distributions df = pd.DataFrame({ 'beta': np.random.beta(5, 1, 1000) * 60, # beta 'exponential': np.random.exponential(10, 1000), # exponential 'normal_p': np.random.normal(10, 2, 1000), # normal platykurtic 'normal_l': np.random.normal(10, 10, 1000), # normal...
_____no_output_____
Unlicense
Data Science/Data_Preprocessing/Notebooks/INFO7390_Assignment_3_Mini_Project_One_Part_Two.ipynb
RushabhNisher/Data
After defining the distributions, lets visualize them
# plot original distribution plot fig, (ax1) = plt.subplots(ncols=1, figsize=(10, 8)) ax1.set_title('Original Distributions') sns.kdeplot(df['beta'], ax=ax1) sns.kdeplot(df['exponential'], ax=ax1) sns.kdeplot(df['normal_p'], ax=ax1) sns.kdeplot(df['normal_l'], ax=ax1) sns.kdeplot(df['bimodal'], ax=ax1); df.describe() ...
_____no_output_____
Unlicense
Data Science/Data_Preprocessing/Notebooks/INFO7390_Assignment_3_Mini_Project_One_Part_Two.ipynb
RushabhNisher/Data
As we can clearly see from the statistics and the plots, all values are in the same ball park. But what happens if we disturb this by adding a feature with much larger values. 2.4.2 Adding a Feature with Much Larger Values This feature could be home prices, for example.[Back to Top](Introduction)
normal_big = np.random.normal(1000000, 10000, (1000,1)) # normal distribution of large values df['normal_big'] = normal_big col_names.append('normal_big') df['normal_big'].plot(kind='kde') df.normal_big.mean()
_____no_output_____
Unlicense
Data Science/Data_Preprocessing/Notebooks/INFO7390_Assignment_3_Mini_Project_One_Part_Two.ipynb
RushabhNisher/Data
We've got a normalish distribution with a mean near 1,000,0000. But if we put this on the same plot as the original distributions, you can't even see the earlier columns.
# plot original distribution plot with larger value feature fig, (ax1) = plt.subplots(ncols=1, figsize=(10, 8)) ax1.set_title('Original Distributions') sns.kdeplot(df['beta'], ax=ax1) sns.kdeplot(df['exponential'], ax=ax1) sns.kdeplot(df['normal_p'], ax=ax1) sns.kdeplot(df['normal_l'], ax=ax1) sns.kdeplot(df['bimodal'...
_____no_output_____
Unlicense
Data Science/Data_Preprocessing/Notebooks/INFO7390_Assignment_3_Mini_Project_One_Part_Two.ipynb
RushabhNisher/Data
The new, high-value distribution is way to the right. And here's a plot of the values.
df.plot()
_____no_output_____
Unlicense
Data Science/Data_Preprocessing/Notebooks/INFO7390_Assignment_3_Mini_Project_One_Part_Two.ipynb
RushabhNisher/Data
2.4.3 MinMaxScaler MinMaxScaler subtracts the column mean from each value and then divides by the range.[Back to Top](Introduction)
mm_scaler = preprocessing.MinMaxScaler() df_mm = mm_scaler.fit_transform(df) df_mm = pd.DataFrame(df_mm, columns=col_names) fig, (ax1) = plt.subplots(ncols=1, figsize=(10, 8)) ax1.set_title('After MinMaxScaler') sns.kdeplot(df_mm['beta'], ax=ax1) sns.kdeplot(df_mm['exponential'], ax=ax1) sns.kdeplot(df_mm['normal_p'...
_____no_output_____
Unlicense
Data Science/Data_Preprocessing/Notebooks/INFO7390_Assignment_3_Mini_Project_One_Part_Two.ipynb
RushabhNisher/Data
Notice how the shape of each distribution remains the same, but now the values are between 0 and 1. Our feature with much larger values was brought into scale with our other features. 2.4.4 StandardScaler StandardScaler is scales each column to have 0 mean and unit variance.[Back to Top](Introduction)
s_scaler = preprocessing.StandardScaler() df_s = s_scaler.fit_transform(df) df_s = pd.DataFrame(df_s, columns=col_names) fig, (ax1) = plt.subplots(ncols=1, figsize=(10, 8)) ax1.set_title('After StandardScaler') sns.kdeplot(df_s['beta'], ax=ax1) sns.kdeplot(df_s['exponential'], ax=ax1) sns.kdeplot(df_s['normal_p'], a...
_____no_output_____
Unlicense
Data Science/Data_Preprocessing/Notebooks/INFO7390_Assignment_3_Mini_Project_One_Part_Two.ipynb
RushabhNisher/Data
You can see that all features now have 0 mean.
df_s.describe()
_____no_output_____
Unlicense
Data Science/Data_Preprocessing/Notebooks/INFO7390_Assignment_3_Mini_Project_One_Part_Two.ipynb
RushabhNisher/Data
2.4.5 RobustScaler RobustScaler subtracts the column median and divides by the interquartile range.[Back to Top](Introduction)
r_scaler = preprocessing.RobustScaler() df_r = r_scaler.fit_transform(df) df_r = pd.DataFrame(df_r, columns=col_names) fig, (ax1) = plt.subplots(ncols=1, figsize=(10, 8)) ax1.set_title('After RobustScaler') sns.kdeplot(df_r['beta'], ax=ax1) sns.kdeplot(df_r['exponential'], ax=ax1) sns.kdeplot(df_r['normal_p'], ax=ax...
_____no_output_____
Unlicense
Data Science/Data_Preprocessing/Notebooks/INFO7390_Assignment_3_Mini_Project_One_Part_Two.ipynb
RushabhNisher/Data
Although the range of values for each feature is much smaller than for the original features, it's larger and varies more than for MinMaxScaler. The bimodal distribution values are now compressed into two small groups. Standard and RobustScalers have pretty much the same ranges. 2.4.6 Normalizer Note that normalizer o...
n_scaler = preprocessing.Normalizer() df_n = n_scaler.fit_transform(df) df_n = pd.DataFrame(df_n, columns=col_names) fig, (ax1) = plt.subplots(ncols=1, figsize=(10, 8)) ax1.set_title('After Normalizer') sns.kdeplot(df_n['beta'], ax=ax1) sns.kdeplot(df_n['exponential'], ax=ax1) sns.kdeplot(df_n['normal_p'], ax=ax1) s...
_____no_output_____
Unlicense
Data Science/Data_Preprocessing/Notebooks/INFO7390_Assignment_3_Mini_Project_One_Part_Two.ipynb
RushabhNisher/Data
Normalizer also moved the features to similar scales. Notice that the range for our much larger feature's values is now extremely small and clustered around .9999999999. 2.4.7 Combined Plot Let's look at our original and transformed distributions together. We'll exclude Normalizer because you generally want to tranfor...
# Combined plot. fig, (ax0, ax1, ax2, ax3) = plt.subplots(ncols=4, figsize=(20, 8)) ax0.set_title('Original Distributions') sns.kdeplot(df['beta'], ax=ax0) sns.kdeplot(df['exponential'], ax=ax0) sns.kdeplot(df['normal_p'], ax=ax0) sns.kdeplot(df['normal_l'], ax=ax0) sns.kdeplot(df['bimodal'], ax=ax0) sns.kdeplot(df...
_____no_output_____
Unlicense
Data Science/Data_Preprocessing/Notebooks/INFO7390_Assignment_3_Mini_Project_One_Part_Two.ipynb
RushabhNisher/Data
The below derives fromhttps://github.com/yihui/knitr/blob/master/inst/examples/knitr-spin.RThis is a special R script which can be used to generate a report. You canwrite normal text in roxygen comments.First we set up some options (you do not have to do this):
library(knitr) opts_chunk$set(fig.path = 'figure/silk-')
_____no_output_____
MIT
tests/notebooks/mirror/script_to_ipynb/knitr-spin.ipynb
kiendang/jupytext
The report begins here.
# boring examples as usual set.seed(123) x = rnorm(5) mean(x)
_____no_output_____
MIT
tests/notebooks/mirror/script_to_ipynb/knitr-spin.ipynb
kiendang/jupytext
You can not use here the special syntax {{code}} to embed inline expressions, e.g.
{{mean(x) + 2}}
_____no_output_____
MIT
tests/notebooks/mirror/script_to_ipynb/knitr-spin.ipynb
kiendang/jupytext
is the mean of x plus 2.The code itself may contain braces, but these are not checked. Thus,perfectly valid (though very strange) R code such as `{{2 + 3}} - {{4 - 5}}`can lead to errors because `2 + 3}} - {{4 - 5` will be treated as inline code.Now we continue writing the report. We can draw plots as well.
par(mar = c(4, 4, .1, .1)); plot(x)
_____no_output_____
MIT
tests/notebooks/mirror/script_to_ipynb/knitr-spin.ipynb
kiendang/jupytext
Actually you do not have to write chunk options, in which case knitr will usedefault options. For example, the code below has no options attached:
var(x) quantile(x)
_____no_output_____
MIT
tests/notebooks/mirror/script_to_ipynb/knitr-spin.ipynb
kiendang/jupytext