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
** Create a countplot using seaborn showing the counts of loans by purpose, with the color hue defined by not.fully.paid. **
sns.countplot(x='purpose',data=loans,hue='not.fully.paid')
_____no_output_____
MIT
Machine Learning/Models/Comparing-the-results-of-Decision-Trees-and-Random-Forests-on-LendingClub-dataset.ipynb
KhushMody/Ds-Algo-HacktoberFest
** Let's see the trend between FICO score and interest rate.**
sns.jointplot(x='fico',y='int.rate',data=loans,color='purple')
_____no_output_____
MIT
Machine Learning/Models/Comparing-the-results-of-Decision-Trees-and-Random-Forests-on-LendingClub-dataset.ipynb
KhushMody/Ds-Algo-HacktoberFest
** Create the following lmplots to see if the trend differed between not.fully.paid and credit.policy.**
sns.lmplot(x='fico',y='int.rate',data=loans,hue='credit.policy',col='not.fully.paid')
_____no_output_____
MIT
Machine Learning/Models/Comparing-the-results-of-Decision-Trees-and-Random-Forests-on-LendingClub-dataset.ipynb
KhushMody/Ds-Algo-HacktoberFest
Setting up the DataLet's get ready to set up our data for our Random Forest Classification Model!**Check loans.info() again.**
loans.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 9578 entries, 0 to 9577 Data columns (total 14 columns): credit.policy 9578 non-null int64 purpose 9578 non-null object int.rate 9578 non-null float64 installment 9578 non-null float64 log.annual.inc 9578 non-null float64 d...
MIT
Machine Learning/Models/Comparing-the-results-of-Decision-Trees-and-Random-Forests-on-LendingClub-dataset.ipynb
KhushMody/Ds-Algo-HacktoberFest
Categorical FeaturesNotice that the **purpose** column as categorical**Create a list of 1 element containing the string 'purpose'. Call this list cat_feats.**
cat_feat = ['purpose']
_____no_output_____
MIT
Machine Learning/Models/Comparing-the-results-of-Decision-Trees-and-Random-Forests-on-LendingClub-dataset.ipynb
KhushMody/Ds-Algo-HacktoberFest
**Now use pd.get_dummies(loans,columns=cat_feats,drop_first=True) to create a fixed larger dataframe that has new feature columns with dummy variables. Set this dataframe as final_data.**
final_data = pd.get_dummies(loans,columns=cat_feat,drop_first=True) final_data.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 9578 entries, 0 to 9577 Data columns (total 19 columns): credit.policy 9578 non-null int64 int.rate 9578 non-null float64 installment 9578 non-null float64 log.annual.inc 9578 non-null float64 dti ...
MIT
Machine Learning/Models/Comparing-the-results-of-Decision-Trees-and-Random-Forests-on-LendingClub-dataset.ipynb
KhushMody/Ds-Algo-HacktoberFest
Train Test SplitNow its time to split our data into a training set and a testing set!
from sklearn.model_selection import train_test_split X = final_data.drop('not.fully.paid',axis=1) y = final_data['not.fully.paid'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
_____no_output_____
MIT
Machine Learning/Models/Comparing-the-results-of-Decision-Trees-and-Random-Forests-on-LendingClub-dataset.ipynb
KhushMody/Ds-Algo-HacktoberFest
Training a Decision Tree ModelLet's start by training a single decision tree first!** Import DecisionTreeClassifier**
from sklearn.tree import DecisionTreeClassifier
_____no_output_____
MIT
Machine Learning/Models/Comparing-the-results-of-Decision-Trees-and-Random-Forests-on-LendingClub-dataset.ipynb
KhushMody/Ds-Algo-HacktoberFest
**Create an instance of DecisionTreeClassifier() called dtree and fit it to the training data.**
dtree = DecisionTreeClassifier() dtree.fit(X_train,y_train)
_____no_output_____
MIT
Machine Learning/Models/Comparing-the-results-of-Decision-Trees-and-Random-Forests-on-LendingClub-dataset.ipynb
KhushMody/Ds-Algo-HacktoberFest
Predictions and Evaluation of Decision Tree**Create predictions from the test set and create a classification report and a confusion matrix.**
pred = dtree.predict(X_test) from sklearn.metrics import classification_report,confusion_matrix print(classification_report(y_test,pred)) print(confusion_matrix(y_test,pred))
[[2000 405] [ 364 105]]
MIT
Machine Learning/Models/Comparing-the-results-of-Decision-Trees-and-Random-Forests-on-LendingClub-dataset.ipynb
KhushMody/Ds-Algo-HacktoberFest
Training the Random Forest model**Create an instance of the RandomForestClassifier class and fit it to our training data from the previous step.**
from sklearn.ensemble import RandomForestClassifier rfc = RandomForestClassifier(n_estimators=600) rfc.fit(X_train,y_train)
_____no_output_____
MIT
Machine Learning/Models/Comparing-the-results-of-Decision-Trees-and-Random-Forests-on-LendingClub-dataset.ipynb
KhushMody/Ds-Algo-HacktoberFest
Predictions and Evaluation
pred = rfc.predict(X_test)
_____no_output_____
MIT
Machine Learning/Models/Comparing-the-results-of-Decision-Trees-and-Random-Forests-on-LendingClub-dataset.ipynb
KhushMody/Ds-Algo-HacktoberFest
**Now create a classification report from the results.**
print(classification_report(y_test,pred))
precision recall f1-score support 0 0.84 1.00 0.91 2405 1 0.75 0.01 0.03 469 accuracy 0.84 2874 macro avg 0.79 0.51 0.47 2874 weighted avg 0.82 0.84 0.77 ...
MIT
Machine Learning/Models/Comparing-the-results-of-Decision-Trees-and-Random-Forests-on-LendingClub-dataset.ipynb
KhushMody/Ds-Algo-HacktoberFest
**Show the Confusion Matrix for the predictions.**
print(confusion_matrix(y_test,pred))
[[2403 2] [ 463 6]]
MIT
Machine Learning/Models/Comparing-the-results-of-Decision-Trees-and-Random-Forests-on-LendingClub-dataset.ipynb
KhushMody/Ds-Algo-HacktoberFest
**What performed better the random forest or the decision tree?**
# RandomForestClassifier showed better results but the results are still not good enough, so future engineering is needed
_____no_output_____
MIT
Machine Learning/Models/Comparing-the-results-of-Decision-Trees-and-Random-Forests-on-LendingClub-dataset.ipynb
KhushMody/Ds-Algo-HacktoberFest
https://github.com/Opensourcefordatascience/Data-sets/blob/master/blood_pressure.csvIn this dataset fictitious and contains blood pressure readings before and after an intervention. These are variables “bp_before” and “bp_after”.
bp_reading = pd.read_csv('datasets/blood_pressure.csv') bp_reading.sample(10) bp_reading.shape bp_reading.describe().T bp_reading[['bp_before', 'bp_after']].boxplot(figsize=(12, 8))
_____no_output_____
MIT
book/_build/jupyter_execute/inferential/demo02_PairedDifferenceT-Test.ipynb
hossainlab/statswithpy
The hypothesis being tested * __Null hypothesis (H0): u1 = u2, which translates to the mean of sample 01 is equal to the mean of sample 02__* __Alternative hypothesis (H1): u1 ? u2, which translates to the means of sample 01 is not equal to sample 02__ Assumption check * The samples are independently and randomly dr...
stats.levene(bp_reading['bp_after'], bp_reading['bp_before']) bp_reading['bp_diff'] = scale(bp_reading['bp_after'] - bp_reading['bp_before']) bp_reading[['bp_diff']].head() bp_reading[['bp_diff']].hist(figsize=(12, 8))
_____no_output_____
MIT
book/_build/jupyter_execute/inferential/demo02_PairedDifferenceT-Test.ipynb
hossainlab/statswithpy
Checking Normal distribution by Q-Q plot graphhttps://www.statisticshowto.datasciencecentral.com/assumption-of-normality-test/
plt.figure(figsize=(15, 8)) stats.probplot(bp_reading['bp_diff'], plot=plt) plt.title('Blood pressure difference Q-Q plot') plt.show()
_____no_output_____
MIT
book/_build/jupyter_execute/inferential/demo02_PairedDifferenceT-Test.ipynb
hossainlab/statswithpy
**Note:-** The corresponding points are lies very close to line that means are our sample data sets are normally distributed Checking Normal distribution by method of `Shapiro stats`https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.shapiro.html
stats.shapiro(bp_reading['bp_diff']) stats.ttest_rel(bp_reading['bp_after'], bp_reading['bp_before'])
_____no_output_____
MIT
book/_build/jupyter_execute/inferential/demo02_PairedDifferenceT-Test.ipynb
hossainlab/statswithpy
**Note:-** __Here, `t-test = -3.337` and `p-value = 0.0011` since p-value is less than the significant value hence null-hypothesis is rejected`(Alpha = 0.05)`__ T-test using `researchpy`https://researchpy.readthedocs.io/en/latest/ttest_documentation.html
rp.ttest(bp_reading['bp_after'], bp_reading['bp_before'], paired = True, equal_variances=False)
_____no_output_____
MIT
book/_build/jupyter_execute/inferential/demo02_PairedDifferenceT-Test.ipynb
hossainlab/statswithpy
Photonqat基本的なゲート動作と測定を一通り行っています。
G = pq.Gaussian(2) # two qumode [0, 1] G.D(0, 2) # Displacement gate, x to x+2 G.S(0, 1) # X squeeIng gate, r=1 G.R(0, np.pi/4) # pi/4 rotation gate G.BS(0, 1, np.pi/4) # 50:50 beam splitter x = G.MeasX(1) # Measure mode 1 G.Wigner(0) # plot print('measured x =', x) print('mu0 =', G.mean(0)) # mu of qumode 0 print('cov...
_____no_output_____
Apache-2.0
examples/GaussianGates.ipynb
ryosukehata/Photonqat
Momentum Portfolio Analysis
portfolio_id = "233d16d0-3d07-4153-a4c4-b9cee6b3aef9"
_____no_output_____
MIT
analysis/notebooks/Labs/momentum_portfolio.ipynb
ksilo/LiuAlgoTrader
imports
import alpaca_trade_api as tradeapi from liualgotrader.analytics import portfolio from liualgotrader.common.market_data import index_data
_____no_output_____
MIT
analysis/notebooks/Labs/momentum_portfolio.ipynb
ksilo/LiuAlgoTrader
Load SP500 data
sp500 = await index_data("SP500")
_____no_output_____
MIT
analysis/notebooks/Labs/momentum_portfolio.ipynb
ksilo/LiuAlgoTrader
Load recommanded portfolio details
data_api = tradeapi.REST(base_url="https://api.alpaca.markets") df = await portfolio.load(data_api, portfolio_id) for i, row in df.iterrows(): df.loc[df.symbol == row.symbol, "Security"] = sp500.loc[ sp500.Symbol == row.symbol, "Security" ].values[0] df.loc[df.symbol == row.symbol, "Sector"] = sp500...
_____no_output_____
MIT
analysis/notebooks/Labs/momentum_portfolio.ipynb
ksilo/LiuAlgoTrader
Suggest Momentum Portfolio
portfolio_size = 5000 for i, row in df.iterrows(): df.loc[df.symbol==row.symbol,"subtotal"] = df.price * df.qty df['accumulatvie'] = df.subtotal.cumsum() display(df) print(f"total to invest: {df.subtotal.sum()}")
_____no_output_____
MIT
analysis/notebooks/Labs/momentum_portfolio.ipynb
ksilo/LiuAlgoTrader
Printing the names of features and label types of digits
print("Features are as follows:\n", ds_digit.data) print("\nLabels:\n", np.unique(ds_digit.target)) training_data, testing_data, training_target, testing_target = train_test_split(ds_digit.data, ds_digit.target, test_size = 0.20, random_state = 19)
_____no_output_____
Apache-2.0
CE019_Lab3/019_Lab3_Task2_Digits_Processing.ipynb
neel4888/019_Neel
Creating an instance of classifier and fitting the model.
mnb=MultinomialNB() mnb.fit(training_data,training_target)
_____no_output_____
Apache-2.0
CE019_Lab3/019_Lab3_Task2_Digits_Processing.ipynb
neel4888/019_Neel
Testing the model and getting accuracy score, confusion matrix, precision score and recall score
# Testing prediction_target = mnb.predict(testing_data) # Getting Accuracy accuracy = accuracy_score(testing_target, prediction_target) print("Accuracy Score:\n", accuracy) # Getting Confusion Matrix cm = confusion_matrix(testing_target, prediction_target) print("\nConfusion Matrix:\n",cm) # Getting Precision precis...
_____no_output_____
Apache-2.0
CE019_Lab3/019_Lab3_Task2_Digits_Processing.ipynb
neel4888/019_Neel
Simple housing version * State: $[w, n, M, e, \hat{S}, z]$, where $z$ is the stock trading experience, which took value of 0 and 1. And $\hat{S}$ now contains 27 states.* Action: $[c, b, k, q]$ where $q$ only takes 2 value: $1$ or $\frac{1}{2}$
from scipy.interpolate import interpn from multiprocessing import Pool from functools import partial from constant import * import warnings warnings.filterwarnings("ignore") #Define the utility function def u(c): return (np.float_power(c, 1-gamma) - 1)/(1 - gamma) #Define the bequeath function, which is a function...
59 58
MIT
20201106/simpleHousing.ipynb
dongxulee/lifeCycle
Chainer MNIST Model Deployment * Wrap a Chainer MNIST python model for use as a prediction microservice in seldon-core * Run locally on Docker to test * Deploy on seldon-core running on minikube Dependencies * [Helm](https://github.com/kubernetes/helm) * [Minikube](https://github.com/kubernetes/minikube) * [S2I](...
#!/usr/bin/env python import argparse import chainer import chainer.functions as F import chainer.links as L from chainer import training from chainer.training import extensions import chainerx # Network definition class MLP(chainer.Chain): def __init__(self, n_units, n_out): super(MLP, self).__init__()...
/Users/dtaniwaki/.pyenv/versions/3.7.4/lib/python3.7/site-packages/chainer/_environment_check.py:41: UserWarning: Accelerate has been detected as a NumPy backend library. vecLib, which is a part of Accelerate, is known not to work correctly with Chainer. We recommend using other BLAS libraries such as OpenBLAS. For det...
Apache-2.0
examples/models/chainer_mnist/chainer_mnist.ipynb
LueJian/seldon-core
Wrap model using s2i
!s2i build . seldonio/seldon-core-s2i-python3:1.3.0-dev chainer-mnist:0.1 !docker run --name "mnist_predictor" -d --rm -p 5000:5000 chainer-mnist:0.1
b03f58f82ca07e25261be34b75be4a0ffbbfa1ad736d3866790682bf0d8202a3
Apache-2.0
examples/models/chainer_mnist/chainer_mnist.ipynb
LueJian/seldon-core
Send some random features that conform to the contract
!seldon-core-tester contract.json 0.0.0.0 5000 -p !docker rm mnist_predictor --force
Error: No such container: mnist_predictor
Apache-2.0
examples/models/chainer_mnist/chainer_mnist.ipynb
LueJian/seldon-core
Test using Minikube**Due to a [minikube/s2i issue](https://github.com/SeldonIO/seldon-core/issues/253) you will need [s2i >= 1.1.13](https://github.com/openshift/source-to-image/releases/tag/v1.1.13)**
!minikube start --memory 4096
😄 minikube v1.2.0 on darwin (amd64) 🔥 Creating virtualbox VM (CPUs=2, Memory=4096MB, Disk=20000MB) ... 🐳 Configuring environment for Kubernetes v1.15.0 on Docker 18.09.6 🚜 Pulling images ... 🚀 Launching Kubernetes ... ⌛ Verifying: apiserver proxy etcd scheduler controller dns 🏄 Done! kubectl is now config...
Apache-2.0
examples/models/chainer_mnist/chainer_mnist.ipynb
LueJian/seldon-core
Setup Seldon CoreUse the setup notebook to [Setup Cluster](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.htmlSetup-Cluster) with [Ambassador Ingress](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.htmlAmbassador) and [Install Seldon Core](https://doc...
!eval $(minikube docker-env) && s2i build . seldonio/seldon-core-s2i-python3:1.3.0-dev chainer-mnist:0.1 !kubectl create -f chainer_mnist_deployment.json !kubectl rollout status deploy/chainer-mnist-deployment-chainer-mnist-predictor-76478b2 !seldon-core-api-tester contract.json `minikube ip` `kubectl get svc ambassado...
_____no_output_____
Apache-2.0
examples/models/chainer_mnist/chainer_mnist.ipynb
LueJian/seldon-core
An Introduction to SageMaker LDA***Finding topics in synthetic document data using Spectral LDA algorithms.***---1. [Introduction](Introduction)1. [Setup](Setup)1. [Training](Training)1. [Inference](Inference)1. [Epilogue](Epilogue) Introduction***Amazon SageMaker LDA is an unsupervised learning algorithm that attemp...
%matplotlib inline import os, re import boto3 import matplotlib.pyplot as plt import numpy as np np.set_printoptions(precision=3, suppress=True) # some helpful utility functions are defined in the Python module # "generate_example_data" located in the same directory as this # notebook from generate_example_data imp...
_____no_output_____
Apache-2.0
introduction_to_amazon_algorithms/lda_topic_modeling/LDA-Introduction.ipynb
Amirosimani/amazon-sagemaker-examples
Setup****This notebook was created and tested on an ml.m4.xlarge notebook instance.*Before we do anything at all, we need data! We also need to setup our AWS credentials so that AWS SageMaker can store and access data. In this section we will do four things:1. [Setup AWS Credentials](SetupAWSCredentials)1. [Obtain Exa...
from sagemaker import get_execution_role session = sagemaker.Session() role = get_execution_role() bucket = session.default_bucket() prefix = "sagemaker/DEMO-lda-introduction" print("Training input/output will be stored in {}/{}".format(bucket, prefix)) print("\nIAM Role: {}".format(role))
_____no_output_____
Apache-2.0
introduction_to_amazon_algorithms/lda_topic_modeling/LDA-Introduction.ipynb
Amirosimani/amazon-sagemaker-examples
Obtain Example DataWe generate some example synthetic document data. For the purposes of this notebook we will omit the details of this process. All we need to know is that each piece of data, commonly called a *"document"*, is a vector of integers representing *"word counts"* within the document. In this particular e...
print("Generating example data...") num_documents = 6000 num_topics = 5 known_alpha, known_beta, documents, topic_mixtures = generate_griffiths_data( num_documents=num_documents, num_topics=num_topics ) vocabulary_size = len(documents[0]) # separate the generated data into training and tests subsets num_documents_...
_____no_output_____
Apache-2.0
introduction_to_amazon_algorithms/lda_topic_modeling/LDA-Introduction.ipynb
Amirosimani/amazon-sagemaker-examples
Inspect Example Data*What does the example data actually look like?* Below we print an example document as well as its corresponding known *topic-mixture*. A topic-mixture serves as the "label" in the LDA model. It describes the ratio of topics from which the words in the document are found.For example, if the topic m...
print("First training document =\n{}".format(documents[0])) print("\nVocabulary size = {}".format(vocabulary_size)) print("Known topic mixture of first document =\n{}".format(topic_mixtures_training[0])) print("\nNumber of topics = {}".format(num_topics)) print("Sum of elements = {}".format(topic_mixtures_training[0].s...
_____no_output_____
Apache-2.0
introduction_to_amazon_algorithms/lda_topic_modeling/LDA-Introduction.ipynb
Amirosimani/amazon-sagemaker-examples
Later, when we perform inference on the training data set we will compare the inferred topic mixture to this known one.---Human beings are visual creatures, so it might be helpful to come up with a visual representation of these documents. In the below plots, each pixel of a document represents a word. The greyscale in...
%matplotlib inline fig = plot_lda(documents_training, nrows=3, ncols=4, cmap="gray_r", with_colorbar=True) fig.suptitle("Example Document Word Counts") fig.set_dpi(160)
_____no_output_____
Apache-2.0
introduction_to_amazon_algorithms/lda_topic_modeling/LDA-Introduction.ipynb
Amirosimani/amazon-sagemaker-examples
Store Data on S3A SageMaker training job needs access to training data stored in an S3 bucket. Although training can accept data of various formats we convert the documents MXNet RecordIO Protobuf format before uploading to the S3 bucket defined at the beginning of this notebook. We do so by making use of the SageMake...
# convert documents_training to Protobuf RecordIO format recordio_protobuf_serializer = RecordSerializer() fbuffer = recordio_protobuf_serializer.serialize(documents_training) # upload to S3 in bucket/prefix/train fname = "lda.data" s3_object = os.path.join(prefix, "train", fname) boto3.Session().resource("s3").Bucket...
_____no_output_____
Apache-2.0
introduction_to_amazon_algorithms/lda_topic_modeling/LDA-Introduction.ipynb
Amirosimani/amazon-sagemaker-examples
Training***Once the data is preprocessed and available in a recommended format the next step is to train our model on the data. There are number of parameters required by SageMaker LDA configuring the model and defining the computational environment in which training will take place.First, we specify a Docker containe...
from sagemaker.amazon.amazon_estimator import get_image_uri # select the algorithm container based on this notebook's current location region_name = boto3.Session().region_name container = get_image_uri(region_name, "lda") print("Using SageMaker LDA container: {} ({})".format(container, region_name))
_____no_output_____
Apache-2.0
introduction_to_amazon_algorithms/lda_topic_modeling/LDA-Introduction.ipynb
Amirosimani/amazon-sagemaker-examples
Particular to a SageMaker LDA training job are the following hyperparameters:* **`num_topics`** - The number of topics or categories in the LDA model. * Usually, this is not known a priori. * In this example, howevever, we know that the data is generated by five topics.* **`feature_dim`** - The size of the *"vocabula...
# specify general training job information lda = sagemaker.estimator.Estimator( container, role, output_path="s3://{}/{}/output".format(bucket, prefix), train_instance_count=1, train_instance_type="ml.c4.2xlarge", sagemaker_session=session, ) # set algorithm-specific hyperparameters lda.set_hyp...
_____no_output_____
Apache-2.0
introduction_to_amazon_algorithms/lda_topic_modeling/LDA-Introduction.ipynb
Amirosimani/amazon-sagemaker-examples
If you see the message> `===== Job Complete =====`at the bottom of the output logs then that means training sucessfully completed and the output LDA model was stored in the specified output path. You can also view information about and the status of a training job using the AWS SageMaker console. Just click on the "Job...
print("Training job name: {}".format(lda.latest_training_job.job_name))
_____no_output_____
Apache-2.0
introduction_to_amazon_algorithms/lda_topic_modeling/LDA-Introduction.ipynb
Amirosimani/amazon-sagemaker-examples
Inference***A trained model does nothing on its own. We now want to use the model we computed to perform inference on data. For this example, that means predicting the topic mixture representing a given document.We create an inference endpoint using the SageMaker Python SDK `deploy()` function from the job we defined ...
lda_inference = lda.deploy( initial_instance_count=1, instance_type="ml.m4.xlarge", # LDA inference may work better at scale on ml.c4 instances )
_____no_output_____
Apache-2.0
introduction_to_amazon_algorithms/lda_topic_modeling/LDA-Introduction.ipynb
Amirosimani/amazon-sagemaker-examples
Congratulations! You now have a functioning SageMaker LDA inference endpoint. You can confirm the endpoint configuration and status by navigating to the "Endpoints" tab in the AWS SageMaker console and selecting the endpoint matching the endpoint name, below:
print("Endpoint name: {}".format(lda_inference.endpoint_name))
_____no_output_____
Apache-2.0
introduction_to_amazon_algorithms/lda_topic_modeling/LDA-Introduction.ipynb
Amirosimani/amazon-sagemaker-examples
With this realtime endpoint at our fingertips we can finally perform inference on our training and test data.We can pass a variety of data formats to our inference endpoint. In this example we will demonstrate passing CSV-formatted data. Other available formats are JSON-formatted, JSON-sparse-formatter, and RecordIO Pr...
lda_inference.serializer = CSVSerializer() lda_inference.deserializer = JSONDeserializer()
_____no_output_____
Apache-2.0
introduction_to_amazon_algorithms/lda_topic_modeling/LDA-Introduction.ipynb
Amirosimani/amazon-sagemaker-examples
We pass some test documents to the inference endpoint. Note that the serializer and deserializer will atuomatically take care of the datatype conversion from Numpy NDArrays.
results = lda_inference.predict(documents_test[:12]) print(results)
_____no_output_____
Apache-2.0
introduction_to_amazon_algorithms/lda_topic_modeling/LDA-Introduction.ipynb
Amirosimani/amazon-sagemaker-examples
It may be hard to see but the output format of SageMaker LDA inference endpoint is a Python dictionary with the following format.```{ 'predictions': [ {'topic_mixture': [ ... ] }, {'topic_mixture': [ ... ] }, {'topic_mixture': [ ... ] }, ... ]}```We extract the topic mixtures, themselves, corresponding to...
computed_topic_mixtures = np.array( [prediction["topic_mixture"] for prediction in results["predictions"]] ) print(computed_topic_mixtures)
_____no_output_____
Apache-2.0
introduction_to_amazon_algorithms/lda_topic_modeling/LDA-Introduction.ipynb
Amirosimani/amazon-sagemaker-examples
If you decide to compare these results to the known topic mixtures generated in the [Obtain Example Data](ObtainExampleData) Section keep in mind that SageMaker LDA discovers topics in no particular order. That is, the approximate topic mixtures computed above may be permutations of the known topic mixtures correspondi...
print(topic_mixtures_test[0]) # known test topic mixture print(computed_topic_mixtures[0]) # computed topic mixture (topics permuted)
_____no_output_____
Apache-2.0
introduction_to_amazon_algorithms/lda_topic_modeling/LDA-Introduction.ipynb
Amirosimani/amazon-sagemaker-examples
Stop / Close the EndpointFinally, we should delete the endpoint before we close the notebook.To do so execute the cell below. Alternately, you can navigate to the "Endpoints" tab in the SageMaker console, select the endpoint with the name stored in the variable `endpoint_name`, and select "Delete" from the "Actions" d...
sagemaker.Session().delete_endpoint(lda_inference.endpoint_name)
_____no_output_____
Apache-2.0
introduction_to_amazon_algorithms/lda_topic_modeling/LDA-Introduction.ipynb
Amirosimani/amazon-sagemaker-examples
Cleaning up imagery for pre and post rainy seasonThe [previous tutorial](igarrs_chad_01.ipynb) addressed the identifying the extent of the rainy season near Lake Chad. This tutorial will focus on cleaning up optical imagery to make it suitable for water-detection algorithms. What to expect from this notebook- I...
import datacube dc = datacube.Datacube(app = "cloud_removal_in_chad")
_____no_output_____
Apache-2.0
notebooks/IGARSS/igarss_chad_02.ipynb
admariner/data_cube_notebooks
Like in the previous tutorial. The datacube object will be used to load data that has previously been ingested by the datacube. Defining the boundaries of the area and restricting measurements
## Define Geographic boundaries using a (min,max) tuple. latitude = (12.75, 13.0) longitude = (14.25, 14.5) ## Specify a date range using a (min,max) tuple from datetime import datetime time = (datetime(2015,1,1), datetime(2016,1,1)) ## define the name you gave your data while it was being "ingested", as well as th...
_____no_output_____
Apache-2.0
notebooks/IGARSS/igarss_chad_02.ipynb
admariner/data_cube_notebooks
As a reminder and in-notebook reference, the following line of code displays the extents of the study area. Re-orient yourself with it.
from utils.data_cube_utilities.dc_display_map import display_map display_map(latitude = (12.75, 13.0),longitude = (14.25, 14.5))
_____no_output_____
Apache-2.0
notebooks/IGARSS/igarss_chad_02.ipynb
admariner/data_cube_notebooks
Loading in Landsat 7 imagery The following code loads in landsat 7 imagery using the constraints defined above
#Load Landsat 7 data using parameters, landsat_data = dc.load(latitude = latitude, longitude = longitude, time = time, product = product, platform = platform, measurements = measurements)
_____no_output_____
Apache-2.0
notebooks/IGARSS/igarss_chad_02.ipynb
admariner/data_cube_notebooks
Explore the Landsat 7 datasetThe previous tutorial barely grazed the concept of xarray variables. To understand how we use landsat7 imagery it will be necessary to make a brief detour and explain it in greater detail. xarray - Variables & Data-arrays When you output the contents of your loaded -dataset...
print(landsat_data)
_____no_output_____
Apache-2.0
notebooks/IGARSS/igarss_chad_02.ipynb
admariner/data_cube_notebooks
.. you should notice a list of values called data-variables. These 'variables' are really 3 dimensional [data-arrays](http://xarray.pydata.org/en/stable/data-structures.html) housing values like 'red', 'green', 'blue', and 'nir', values for each lat,lon,time coordinate pair in your dataset. Think of an [xarray.Data...
landsat_data.nir
_____no_output_____
Apache-2.0
notebooks/IGARSS/igarss_chad_02.ipynb
admariner/data_cube_notebooks
The object printed above is a [data-array](http://xarray.pydata.org/en/stable/generated/xarray.DataArray.html). Unlike a data-set, data-arrays only house one type of data and has its own set of attributes and functions. xarray - Landsat 7 Values Let's explore landsat datasets in greater detail by starting wit...
## The only take-away from this code should be that a .png is produced. ## Any details about how this function is used is out of scope for this tutorial from utils.data_cube_utilities.dc_utilities import write_png_from_xr write_png_from_xr('../demo/landsat_rgb.png', landsat_data.isel(time = 11), ["red", "green", "b...
_____no_output_____
Apache-2.0
notebooks/IGARSS/igarss_chad_02.ipynb
admariner/data_cube_notebooks
![](demo/landsat_rgb.png) The need to clean up imageryConsidering the imagery above. It is hard to build a comprehensive profile on landcover. There are several objects that occlude the surface of the earth. Namely errors introduced by an SLC malfunction, as well as cloud cover. Scanline Gaps In May of 2003, Lands...
start_of_rainy_season = '2015-06-01' end_of_rainy_season = '2015-10-01'
_____no_output_____
Apache-2.0
notebooks/IGARSS/igarss_chad_02.ipynb
admariner/data_cube_notebooks
The next step after defining this would be to define the time ranges for both post and pre, then use them to select subsections from the original dataset to act as two separate datasets. (Like in the diagram below) ![](diagrams/rainy_demo/split_02.png)
start_of_year = '2015-01-01' end_of_year = '2015-12-31' pre = landsat_data.sel(time = slice(start_of_year, start_of_rainy_season)) post = landsat_data.sel(time = slice(end_of_rainy_season, end_of_year))
_____no_output_____
Apache-2.0
notebooks/IGARSS/igarss_chad_02.ipynb
admariner/data_cube_notebooks
Building a cloud-free and gap-free representation This section of the process works s by masking out clouds and gaps from the imagery and then selecting a median valued cloud/scanline-gap free pixels of an image. ![](diagrams/rainy_demo/cleanup.png) - Masking is done using the **pixel_qa** variable. - T...
import numpy as np def cloud_and_slc_removal_mask(dataset): #Create boolean Masks for clear and water pixels clear_pixels = dataset.pixel_qa.values == 2 + 64 water_pixels = dataset.pixel_qa.values == 4 + 64 a_clean_mask = np.logical_or(clear_pixels, water_pixels) return a_clean_mask
_____no_output_____
Apache-2.0
notebooks/IGARSS/igarss_chad_02.ipynb
admariner/data_cube_notebooks
The following code creates a **boolean** mask, for slc code.
mask_for_pre = cloud_and_slc_removal_mask(pre) mask_for_post = cloud_and_slc_removal_mask(post)
_____no_output_____
Apache-2.0
notebooks/IGARSS/igarss_chad_02.ipynb
admariner/data_cube_notebooks
A boolean mask is essentially what it sounds like. Let's look at its print-out
print(mask_for_post)
_____no_output_____
Apache-2.0
notebooks/IGARSS/igarss_chad_02.ipynb
admariner/data_cube_notebooks
This boolean mask contains a **true** value for pixels that are clear and un-occluded by clouds or scanline gaps and **false** values where the opposite is true. Example of mask use There are many ways to apply a mask. The following example is the xarray way. It will apply *nan* values to areas with cloud...
pre.where(mask_for_pre)
_____no_output_____
Apache-2.0
notebooks/IGARSS/igarss_chad_02.ipynb
admariner/data_cube_notebooks
Notice that a lot of the values in the array above have nan values. Compositing algorithms like the **median-pixel mosaic** below, make use of this **where** function as well as 'nans' as the marker for no-data values. Median Pixel MosaicA median pixel mosaic is used for our cloud/slc-gap free representation of sat...
from utils.data_cube_utilities.dc_mosaic import create_median_mosaic def mosaic(dataset, mask): return create_median_mosaic(dataset, clean_mask = mask)
_____no_output_____
Apache-2.0
notebooks/IGARSS/igarss_chad_02.ipynb
admariner/data_cube_notebooks
Lets use it to generate our cloud free representations of the area:
clean_pre = mosaic(pre, mask_for_pre) clean_post = mosaic(post, mask_for_post)
_____no_output_____
Apache-2.0
notebooks/IGARSS/igarss_chad_02.ipynb
admariner/data_cube_notebooks
Taking a peek at our cloud-free composites Pre Rainy Season
print(clean_pre) write_png_from_xr('../demo/pre_rain_mosaic.png', clean_pre, ["red", "green", "blue"], scale = [(0,2000),(0,2000),(0,2000)])
_____no_output_____
Apache-2.0
notebooks/IGARSS/igarss_chad_02.ipynb
admariner/data_cube_notebooks
Your png should look something like this: ![](demo/pre_rain_mosaic.png) Post Rainy Season
print(clean_post) write_png_from_xr('../demo/post_rain_mosaic.png', clean_post, ["red", "green", "blue"], scale = [(0,2000),(0,2000),(0,2000)])
_____no_output_____
Apache-2.0
notebooks/IGARSS/igarss_chad_02.ipynb
admariner/data_cube_notebooks
![](demo/post_rain_mosaic.png) Next StepsThe [next notebook](igarss_chad_03.ipynb) in the series deals with water classification on these cloud free composites! We'll need to save our work so that it can be loaded in the next notebook. The good news is that xarrays closely resemble the structure of net NETCDF files...
## Lets drop pixel qa since it doesn't make sense to house it in a composite. final_post = clean_post.drop('pixel_qa') final_pre = clean_pre.drop('pixel_qa') final_post.to_netcdf('../demo/post_rain.nc') final_pre.to_netcdf('../demo/pre_rain.nc')
_____no_output_____
Apache-2.0
notebooks/IGARSS/igarss_chad_02.ipynb
admariner/data_cube_notebooks
The entire notebook has been condensed down to a about 2 dozen lines of code below.
import datacube from datetime import datetime from utils.data_cube_utilities.dc_mosaic import create_median_mosaic def mosaic(dataset, mask): return create_median_mosaic(dataset, clean_mask = mask) def cloud_and_slc_removal_mask(dataset): clear_pixels = dataset.pixel_qa.values == 2 + 64 water_pixels = dat...
_____no_output_____
Apache-2.0
notebooks/IGARSS/igarss_chad_02.ipynb
admariner/data_cube_notebooks
%%capture # Comment this out if you don't want to install pennylane from this notebook !pip install pennylane # Comment this out if you don't want to install matplotlib from this notebook !pip install matplotlib
_____no_output_____
Apache-2.0
1_classical_ml_with_automatic_differentiation.ipynb
SaashaJoshi/pennylane-demo-cern
Training a machine learning model with automatic differentiation In this tutorial we will: * implement a toy version of a typical machine learning setup,* understand how automatic differentiation allows us to compute gradients of the machine learning model, and* use automatic differentiation to train the model.First s...
import pennylane as qml from pennylane import numpy as np # This will import a special, "differentiable" version of numpy. import matplotlib.pyplot as plt %matplotlib inline np.random.seed(42) np.array([0.1, -0.9]) # This is a tensor array with gradient import numpy as vanilla_np vanilla_np.array([0.1, -0.9]) x_a...
_____no_output_____
Apache-2.0
1_classical_ml_with_automatic_differentiation.ipynb
SaashaJoshi/pennylane-demo-cern
1. The three basic ingredients A machine learning problem usually consists of *data*, a *model (family)* and a *cost function*: *Training* selects the best model from the family by minimising the cost on a training set of data samples. If we design the optimisation problem well, the trained model will also have a low ...
n_samples = 100 X0 = np.array([[np.random.normal(loc=-1, scale=1), np.random.normal(loc=1, scale=1)] for i in range(n_samples//2)]) X1 = np.array([[np.random.normal(loc=1, scale=1), np.random.normal(loc=-1, scale=1)] for i in range(n_samples//2)]) X = np.concatenate([X0, X1], axis=0)...
_____no_output_____
Apache-2.0
1_classical_ml_with_automatic_differentiation.ipynb
SaashaJoshi/pennylane-demo-cern
Model familyNext, we construct a linear model.
def model(x, w): return np.dot(x, w)
_____no_output_____
Apache-2.0
1_classical_ml_with_automatic_differentiation.ipynb
SaashaJoshi/pennylane-demo-cern
Let's try it out.
w = np.array([-0.5, -0.2]) model(X0[0], w) # model(X0[1], w) # If we put a threshold at zero (0), X0[0] would be classified in class +1 and X0[1] will be classified in class -1
_____no_output_____
Apache-2.0
1_classical_ml_with_automatic_differentiation.ipynb
SaashaJoshi/pennylane-demo-cern
We can plot the decision boundary, or the boundary in data space where the model flips from a negative to a positive prediction
plt.scatter(X0[:,0], X0[:,1]) plt.scatter(X1[:,0], X1[:,1]) plt.arrow(0, 0, w[0], w[1], head_width=0.3, head_length=0.3, fc='r', ec='r') plt.plot([-3*w[1], 3*w[1]], [3*w[0], -3*w[0]], 'k-') plt.show()
_____no_output_____
Apache-2.0
1_classical_ml_with_automatic_differentiation.ipynb
SaashaJoshi/pennylane-demo-cern
Cost functionHow good is the model on a single input-output training pair?
def loss(a, b): return (a - b)**2 # Square of difference.
_____no_output_____
Apache-2.0
1_classical_ml_with_automatic_differentiation.ipynb
SaashaJoshi/pennylane-demo-cern
What is the average loss on a data set of multiple pairs?
def average_loss(w, data): c = 0 for x, y in data: prediction = model(x, w) c += loss(prediction, y) return c/len(data) w = np.array([1.3, -0.4]) average_loss(w, data)
_____no_output_____
Apache-2.0
1_classical_ml_with_automatic_differentiation.ipynb
SaashaJoshi/pennylane-demo-cern
2. Automatic computation of gradientsBecause we imported PennyLane's numpy version, we can now compute gradients of the average loss with respect to the weights!
gradient_fn = qml.grad(average_loss, argnum=0) gradient_fn(w, data)
_____no_output_____
Apache-2.0
1_classical_ml_with_automatic_differentiation.ipynb
SaashaJoshi/pennylane-demo-cern
We can use gradients to guess better candidates for parameters.
w_new = w - 0.05*gradient_fn(w, data) average_loss(w_new, data)
_____no_output_____
Apache-2.0
1_classical_ml_with_automatic_differentiation.ipynb
SaashaJoshi/pennylane-demo-cern
This works because the gradient always points towards the steepest ascent in the cost landscape.
# compute the gradient at some point in parameter space some_w = np.array([-0.6, 0.5]) g = 0.01*gradient_fn(some_w, data) # learning rate = 0.01 here above! # make a contourplot of the cost w1s = np.linspace(-2, 2) w2s = np.linspace(-2, 2) cost_grid = [] for w1 in w1s: for w2 in w2s: w = np.array([w1, w2])...
_____no_output_____
Apache-2.0
1_classical_ml_with_automatic_differentiation.ipynb
SaashaJoshi/pennylane-demo-cern
3. Training with gradient descentPutting it all together, we can train the linear model.
w_init = np.random.random(size=(2,)) w = np.array(w_init) history = [] for i in range(15): w_new = w - 0.05*gradient_fn(w, data) print(average_loss(w_new, data)) history.append(w_new) w = w_new
1.3500100407100541 1.102185220934838 0.9290184060813585 0.8027576735134763 0.7073372523673335 0.6331673539752455 0.5743007976098509 0.5268826928791955 0.488294380852497 0.45667438524266574 0.4306452071742513 0.4091534224361 0.3913728909446769 0.376643727003794 0.3644320177904416
Apache-2.0
1_classical_ml_with_automatic_differentiation.ipynb
SaashaJoshi/pennylane-demo-cern
We can easily visualise the path that gradient descent took in parameter space.
plt.contourf(w1s, w2s, cost_grid.T) history = np.array(history) plt.plot(history[:, 0], history[:, 1], "-o") plt.xlabel(r"$w_1$") plt.ylabel(r"$w_2$") plt.show()
_____no_output_____
Apache-2.0
1_classical_ml_with_automatic_differentiation.ipynb
SaashaJoshi/pennylane-demo-cern
Training didn't fully converge yet, but the decision boundary is already better.
plt.scatter(X0[:,0], X0[:,1]) plt.scatter(X1[:,0], X1[:,1]) plt.arrow(0, 0, w[0], w[1], head_width=0.3, head_length=0.3, fc='r', ec='r') plt.plot([-3*w[1], 3*w[1]], [3*w[0], -3*w[0]], 'k-') plt.show()
_____no_output_____
Apache-2.0
1_classical_ml_with_automatic_differentiation.ipynb
SaashaJoshi/pennylane-demo-cern
TASKS 1. Add a constant scalar bias term $b \in \mathbb{R}$ to the model, $$ f(x, w) = \langle w, x \rangle + b, $$ and train both $w$ and $b$ at the same time. 2. Change the model to a neural network with a single hidden layer. $$ f(x, w, W) = \langle w, \varphi(Wx) \rangle,$$ where $W$ is a weight matrix...
n_samples = 100 X0 = np.array([[np.random.normal(loc=-1, scale=1), np.random.normal(loc=1, scale=1)] for i in range(n_samples//2)]) X1 = np.array([[np.random.normal(loc=1, scale=1), np.random.normal(loc=-1, scale=1)] for i in range(n_samples//2)]) X = np.concatenate([X0, X1], axis=0)...
_____no_output_____
Apache-2.0
1_classical_ml_with_automatic_differentiation.ipynb
SaashaJoshi/pennylane-demo-cern
**Counting Valleys** - HackerRankGary is an avid hiker. He tracks his hikes meticulously, paying close attention to small details like topography. During his last hike he took exactly $n$ steps. For every step he took, he noted if it was an uphill, $U$, or a downhill, $D$ step. Gary's hikes start and end at sea level ...
def countingValleys(n, s): # start of solution level = 0 valley = 0 for steps in s: if steps == 'U': level += 1 if level == 0: # exit valley valley += 1 else: level -= 1 return valley # end of solution n = len('UDDDU...
2
MIT
HackerRank/counting_valleys.ipynb
shaunhyp57/coding_practice
Per trovare i materiali che compongono i cluster scegliamo di **non eseguire un fit su ogni spettro all'interno di un determinato cluster**, ma **procediamo mediando su tutti gli spettri presenti nei singoli cluster e fittiamo sul risultato della media.**Importiamo cosi i centroidi dei vari cluster, che vengono restitu...
#import dei pesi dei cluster labels=np.loadtxt("../data/processed/CLUSTERING_labels.txt") # import dei centroidi data = pd.read_csv("../data/processed/CLUSTERING_data_centres.csv") data.drop(labels='Unnamed: 0',inplace=True,axis=1) pure_material_names,pure_materials = import_pure_spectra('../data/raw/Database Raman/BAN...
_____no_output_____
MIT
notebooks/FIT.ipynb
FabioBrugnara/repo_raman
Interpolazione **Le frequenze di campionamento degli spettri puri sono diverse tra loro e diverse da quelle utilizzate per il campionamento degli spettri sperimentali.** Per poter eseguire un fit dobbiamo per prima cosa interpolare i dati degli spettri puri con quelli degli spettri sperimentali. Dopo l'interpolazione ...
pure_materials_interpoled=pd.DataFrame(data.wn.copy()) for temp in pure_material_names: pure_materials_interpoled=pure_materials_interpoled.join(pd.DataFrame(np.interp(data.wn, pure_materials[temp+'_wn'] ,pure_materials[temp+'_I']),columns=[temp]))
_____no_output_____
MIT
notebooks/FIT.ipynb
FabioBrugnara/repo_raman
Dopo aver interpolato i dati normalizziamo gli spettri puri.
#Normalizzazione for i in pure_material_names: pure_materials_interpoled[i]=pure_materials_interpoled[i]/np.trapz(abs(pure_materials_interpoled[i].dropna()), x=pure_materials_interpoled.wn)
_____no_output_____
MIT
notebooks/FIT.ipynb
FabioBrugnara/repo_raman
Fit Per fittare gli spettri puri ai dati ragioniamo in questo modo:- possiamo vedere lo spettro incognito del centroide $C$ come una combinazione lineare con coefficienti non negativi di tutti gli spettri puri $P_{i}$.- Nel nostro modello gli spettri puri $P_{i} \in \mathbb{R}^n$ dove $n$ e' la dimesnionalita' del vet...
ols=LinearRegression(positive=True) #definisco il regressore
_____no_output_____
MIT
notebooks/FIT.ipynb
FabioBrugnara/repo_raman
Per ogni cluster facciamo quindi una regressione lineare estrapolando i coefficienti e l'intercetta.
N_cluster=len(data.columns)-1 coeff=[] intercept=[] for i in range(N_cluster): ols.fit(pure_materials_interpoled[pure_material_names], data[str(i)]) #ottimizziamo il modello (lineare) su i dati di training coeff.append(ols.coef_) intercept.append(ols.intercept_)
_____no_output_____
MIT
notebooks/FIT.ipynb
FabioBrugnara/repo_raman
Plot dei vari centroidi dei cluster e del rispettivo fit
fig, axs = plt.subplots(nrows = N_cluster,figsize = (16,38)) for i in enumerate(range(N_cluster)): axs[i[0]].plot(data.wn,data[str(i[0])]) axs[i[0]].plot(pure_materials_interpoled.wn,intercept[i[0]]+np.sum(pure_materials_interpoled[pure_material_names] * coeff[i[0]] ,axis=1)) axs[i[0]].set_title('Cluster ' ...
_____no_output_____
MIT
notebooks/FIT.ipynb
FabioBrugnara/repo_raman
Determinazione dell'abbondanza del materiale Tenendo conto del numero di spettri presenti in ogni cluster, determiniamo il materiale piu' abbondande nel campione utilizzando i coefficienti dei fit. **Otteniamo così il risultato finale: le abbondanze nel campione**.
#elimino il cluster a 0 (se presente) e normalizzare i coefficienti per ogni cluster for temp in np.unique(labels): if max(data[str(int(temp))])>1e-10: coeff[int(temp)]=coeff[int(temp)]/sum(coeff[int(temp)]) else: print(f'Identificato lo spettro piatto, non utilizzato il cluster {int(temp)}') ...
_____no_output_____
MIT
notebooks/FIT.ipynb
FabioBrugnara/repo_raman
Teste para Duas Médias - ANOVA (Analysis of Variance)Análise de variância é a técnica estatística que permite avaliar afirmações sobre as médias de populações. A análise visa, fundamentalmente, verificar se existe uma diferença significativa entre as médias e se os fatores exercem influência em alguma variável depende...
import pandas as pd import statsmodels.api as sm from statsmodels.formula.api import ols from statsmodels.stats.anova import anova_lm from statsmodels.graphics.factorplots import interaction_plot import matplotlib.pyplot as plt from scipy import stats
_____no_output_____
MIT
01-python-EDA-stat-univariada/07 Inferência 2/inferencia_2_anova.ipynb
sn3fru/datascience_course
Importando os dados
datafile = "../../99 Datasets/ToothGrowth.csv.zip" data = pd.read_csv(datafile) data.head() data.info() data.describe() fig = interaction_plot(data.dose, data.supp, data.len, colors=['red','blue'], markers=['D','^'], ms=10)
_____no_output_____
MIT
01-python-EDA-stat-univariada/07 Inferência 2/inferencia_2_anova.ipynb
sn3fru/datascience_course
Calculando a soma dos quadrados
# Graus de liberdade N = len(data.len) df_a = len(data.supp.unique()) - 1 df_b = len(data.dose.unique()) - 1 df_axb = df_a*df_b df_w = N - (len(data.supp.unique())*len(data.dose.unique())) grand_mean = data['len'].mean() # SS para o fator A ssq_a = sum([(data[data.supp ==l].len.mean()-grand_mean)**2 for l in data.sup...
_____no_output_____
MIT
01-python-EDA-stat-univariada/07 Inferência 2/inferencia_2_anova.ipynb
sn3fru/datascience_course
Média dos Quadrados
# MQ da A ms_a = ssq_a/df_a # MQ de B ms_b = ssq_b/df_b # MQ de AxB ms_axb = ssq_axb/df_axb # MQ do resíduo ms_w = ssq_w/df_w
_____no_output_____
MIT
01-python-EDA-stat-univariada/07 Inferência 2/inferencia_2_anova.ipynb
sn3fru/datascience_course
F-Score
# F-Score de A f_a = ms_a/ms_w # F-Score de B f_b = ms_b/ms_w # F-Score de C f_axb = ms_axb/ms_w
_____no_output_____
MIT
01-python-EDA-stat-univariada/07 Inferência 2/inferencia_2_anova.ipynb
sn3fru/datascience_course
p-Value
# p-Value de A p_a = stats.f.sf(f_a, df_a, df_w) # p-Value de B p_b = stats.f.sf(f_b, df_b, df_w) # p-Value de C p_axb = stats.f.sf(f_axb, df_axb, df_w)
_____no_output_____
MIT
01-python-EDA-stat-univariada/07 Inferência 2/inferencia_2_anova.ipynb
sn3fru/datascience_course
Resultados
# Colocando os resultados em um DataFrame results = {'sum_sq':[ssq_a, ssq_b, ssq_axb, ssq_w], 'df':[df_a, df_b, df_axb, df_w], 'F':[f_a, f_b, f_axb, 'NaN'], 'PR(>F)':[p_a, p_b, p_axb, 'NaN']} columns=['sum_sq', 'df', 'F', 'PR(>F)'] aov_table1 = pd.DataFrame(results, columns=columns,...
_____no_output_____
MIT
01-python-EDA-stat-univariada/07 Inferência 2/inferencia_2_anova.ipynb
sn3fru/datascience_course