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
Following the instance of the Arithmetic class with a β€˜.’ enables the calling of objects owned by the class.Next, let's create the _add()_ method.
%%add_to Arithmetic #arithmetic.py # . . . def add(self, *args): try: total = 0 for arg in args: total += arg return total except: print("Pass int or float to add()") # make sure you define arithmetic below the script constructing the class arithmeti...
_____no_output_____
MIT
.ipynb_checkpoints/ Chapter 4 - Classes and Methods-checkpoint.ipynb
hunterluepke/Learn-Python-for-Stats-and-Econ
To account for inputs that cannot be processed, the method begins with try. This will return an error message in cases where integers or floats may not be passed to the method.The _add()_ method passes two arguments: self and \*args. Self is always implicitly passed to a method, so you will only pass one arguments that...
#aritmetic.py # . . . print(arithmetic.add(1,2,3,4,5,6,7,8,9,10))
55
MIT
.ipynb_checkpoints/ Chapter 4 - Classes and Methods-checkpoint.ipynb
hunterluepke/Learn-Python-for-Stats-and-Econ
We will add two more functions to our class: the multiply and power functions. As with the addition class, we will create a multiply class that multiplies an unspecified number of arguments.
%%add_to Arithmetic #arithmetic.py # . . . def multiply(self, *args): product = 1 try: for arg in args: product *= arg return product except: print("Pass only int or float to multiply()") # make sure you define arithmetic below the script constructing the class arithme...
24
MIT
.ipynb_checkpoints/ Chapter 4 - Classes and Methods-checkpoint.ipynb
hunterluepke/Learn-Python-for-Stats-and-Econ
The last method we will create is the exponent function. This one is straight-forward. Pass a base and an exponent to _.power()_ to yield the result a value, a, where $a=Base^{exponent}.$
%%add_to Arithmetic #arithmetic.py # . . . def power(self, base, exponent): try: value = base ** exponent return value except: print("Pass int or flaot for base and exponent") # make sure you define arithmetic below the script constructing the class arithmetic = Arithmetic() # . . . p...
8
MIT
.ipynb_checkpoints/ Chapter 4 - Classes and Methods-checkpoint.ipynb
hunterluepke/Learn-Python-for-Stats-and-Econ
Stats ClassNow that you are comfortable with classes, we can build a Stats() class. This will integrate of the core stats functions that we built in the last chapter. We will be making use of this function when we build a program to run ordinary least squares regression, so make sure that this is well ordered.Since we...
#stats.py class stats(): def __init__(self): print("You created an instance of stats()") def total(self, list_obj): total = 0 n = len(list_obj) for i in range(n): total += list_obj[i] return total def mean(self, list_obj): n = len(lis...
_____no_output_____
MIT
.ipynb_checkpoints/ Chapter 4 - Classes and Methods-checkpoint.ipynb
hunterluepke/Learn-Python-for-Stats-and-Econ
We will import stats.py using a separate script called importStats.py. Once this script is imported, call the class *stats()* and name the instance *stats_lib*.
import stats stats_lib = stats.stats() list1 = [3, 6, 9, 12, 15] list2 = [i ** 2 for i in range(3, 8)] print("sum list1 and list2", stats_lib.total(list1 + list2)) print("mean list1 and list2", stats_lib.mean(list1 + list2)) print("median list1 and list2", stats_lib.median(list1 + list2)) print("mode of list1 an...
sum list1 and list2 180 mean list1 and list2 18.0 median list1 and list2 13.5 mode of list1 and list2 [9] variance of list1 and list2 191.4 standard deviation of list1 and list2 13.83473888441701 covariance of list1 and list2 (separate) 60.0 correlation of list1 and list2 (separate) 0.9930726528736967 skewness of list1...
MIT
.ipynb_checkpoints/ Chapter 4 - Classes and Methods-checkpoint.ipynb
hunterluepke/Learn-Python-for-Stats-and-Econ
Missing value imputation using ML model
#Importing packages import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sb dataset = pd.read_excel('/Users/swaruptripathy/Desktop/Data Science and AI/datasets/stark_data.xlsx') dataset.head() dataset.shape #Information about the dataset dataset.info() #Check for null values dataset....
_____no_output_____
MIT
data_preprocessing - MVI Sci-Kit.ipynb
swaruptripathy/DataScience-Python
Create a PipelineYou can perform the various steps required to ingest data, train a model, and register the model individually by using the Azure ML SDK to run script-based experiments. However, in an enterprise environment it is common to encapsulate the sequence of discrete steps required to build a machine learning...
import azureml.core from azureml.core import Workspace # Load the workspace from the saved config file ws = Workspace.from_config() print('Ready to use Azure ML {} to work with {}'.format(azureml.core.VERSION, ws.name))
Ready to use Azure ML 1.22.0 to work with dp100_ml
MIT
08 - Create a Pipeline.ipynb
changyuanliu/mslearn-dp100
Prepare dataIn your pipeline, you'll use a dataset containing details of diabetes patients. Run the cell below to create this dataset (if you created it in previously, the code will find the existing version)
from azureml.core import Dataset default_ds = ws.get_default_datastore() if 'diabetes dataset' not in ws.datasets: default_ds.upload_files(files=['./data/diabetes.csv', './data/diabetes2.csv'], # Upload the diabetes csv files in /data target_path='diabetes-data/', # Put it in a folder path...
Dataset already registered.
MIT
08 - Create a Pipeline.ipynb
changyuanliu/mslearn-dp100
Create scripts for pipeline stepsPipelines consist of one or more *steps*, which can be Python scripts, or specialized steps like a data transfer step that copies data from one location to another. Each step can run in its own compute context. In this exercise, you'll build a simple pipeline that contains two Python s...
import os # Create a folder for the pipeline step files experiment_folder = 'diabetes_pipeline' os.makedirs(experiment_folder, exist_ok=True) print(experiment_folder)
diabetes_pipeline
MIT
08 - Create a Pipeline.ipynb
changyuanliu/mslearn-dp100
Now let's create the first script, which will read data from the diabetes dataset and apply some simple pre-processing to remove any rows with missing data and normalize the numeric features so they're on a similar scale.The script includes a argument named **--prepped-data**, which references the folder where the resu...
%%writefile $experiment_folder/prep_diabetes.py # Import libraries import os import argparse import pandas as pd from azureml.core import Run from sklearn.preprocessing import MinMaxScaler # Get parameters parser = argparse.ArgumentParser() parser.add_argument("--input-data", type=str, dest='raw_dataset_id', help='raw...
Writing diabetes_pipeline/prep_diabetes.py
MIT
08 - Create a Pipeline.ipynb
changyuanliu/mslearn-dp100
Now you can create the script for the second step, which will train a model. The script includes a argument named **--training-folder**, which references the folder where the prepared data was saved by the previous step.
%%writefile $experiment_folder/train_diabetes.py # Import libraries from azureml.core import Run, Model import argparse import pandas as pd import numpy as np import joblib import os from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import roc_auc_...
Writing diabetes_pipeline/train_diabetes.py
MIT
08 - Create a Pipeline.ipynb
changyuanliu/mslearn-dp100
Prepare a compute environment for the pipeline stepsIn this exercise, you'll use the same compute for both steps, but it's important to realize that each step is run independently; so you could specify different compute contexts for each step if appropriate.First, get the compute target you created in a previous lab (...
from azureml.core.compute import ComputeTarget, AmlCompute from azureml.core.compute_target import ComputeTargetException cluster_name = "dp100cluster" try: # Check for existing compute target pipeline_cluster = ComputeTarget(workspace=ws, name=cluster_name) print('Found existing cluster, use it.') except...
Found existing cluster, use it.
MIT
08 - Create a Pipeline.ipynb
changyuanliu/mslearn-dp100
The compute will require a Python environment with the necessary package dependencies installed, so you'll need to create a run configuration.
from azureml.core import Environment from azureml.core.conda_dependencies import CondaDependencies from azureml.core.runconfig import RunConfiguration # Create a Python environment for the experiment diabetes_env = Environment("diabetes-pipeline-env") diabetes_env.python.user_managed_dependencies = False # Let Azure M...
Run configuration created.
MIT
08 - Create a Pipeline.ipynb
changyuanliu/mslearn-dp100
Create and run a pipelineNow you're ready to create and run a pipeline.First you need to define the steps for the pipeline, and any data references that need to passed between them. In this case, the first step must write the prepared data to a folder that can be read from by the second step. Since the steps will be r...
from azureml.pipeline.core import PipelineData from azureml.pipeline.steps import PythonScriptStep # Get the training dataset diabetes_ds = ws.datasets.get("diabetes dataset") # Create a PipelineData (temporary Data Reference) for the model folder prepped_data_folder = PipelineData("prepped_data_folder", datastore=ws...
Pipeline steps defined
MIT
08 - Create a Pipeline.ipynb
changyuanliu/mslearn-dp100
OK, you're ready build the pipeline from the steps you've defined and run it as an experiment.
from azureml.core import Experiment from azureml.pipeline.core import Pipeline from azureml.widgets import RunDetails # Construct the pipeline pipeline_steps = [prep_step, train_step] pipeline = Pipeline(workspace=ws, steps=pipeline_steps) print("Pipeline is built.") # Create an experiment and run the pipeline experi...
Pipeline is built. Created step Prepare Data [275367ac][730eb0c0-98ca-4c8e-8e2f-b78374815d85], (This step will run and generate new outputs) Created step Train and Register Model [2e06e0fa][b0675b0e-f8c3-4d6a-95af-8f069378f3b8], (This step will run and generate new outputs) Submitted PipelineRun 5d9d21f5-7b67-4982-9e11...
MIT
08 - Create a Pipeline.ipynb
changyuanliu/mslearn-dp100
A graphical representation of the pipeline experiment will be displayed in the widget as it runs. Keep an eye on the kernel indicator at the top right of the page, when it turns from **&9899;** to **&9711;**, the code has finished running. You can also monitor pipeline runs in the **Experiments** page in [Azure Machine...
for run in pipeline_run.get_children(): print(run.name, ':') metrics = run.get_metrics() for metric_name in metrics: print('\t',metric_name, ":", metrics[metric_name])
Train and Register Model : Accuracy : 0.9 AUC : 0.8863896775883228 ROC : aml://artifactId/ExperimentRun/dcid.5aa58156-7e90-44bd-9338-e5dc358380f4/ROC_1615925288.png Prepare Data : raw_rows : 15000 processed_rows : 15000
MIT
08 - Create a Pipeline.ipynb
changyuanliu/mslearn-dp100
Assuming the pipeline was successful, a new model should be registered with a *Training context* tag indicating it was trained in a pipeline. Run the following code to verify this.
from azureml.core import Model for model in Model.list(ws): print(model.name, 'version:', model.version) for tag_name in model.tags: tag = model.tags[tag_name] print ('\t',tag_name, ':', tag) for prop_name in model.properties: prop = model.properties[prop_name] print ('\t',p...
diabetes_model version: 7 Training context : Pipeline AUC : 0.8863896775883228 Accuracy : 0.9 diabetes_model version: 6 Training context : Compute cluster AUC : 0.8852500572906943 Accuracy : 0.9 diabetes_model version: 5 Training context : Compute cluster AUC : 0.8852500572906943 Accuracy : 0.9 ...
MIT
08 - Create a Pipeline.ipynb
changyuanliu/mslearn-dp100
Publish the pipelineAfter you've created and tested a pipeline, you can publish it as a REST service.
# Publish the pipeline from the run published_pipeline = pipeline_run.publish_pipeline( name="diabetes-training-pipeline", description="Trains diabetes model", version="1.0") published_pipeline
_____no_output_____
MIT
08 - Create a Pipeline.ipynb
changyuanliu/mslearn-dp100
Note that the published pipeline has an endpoint, which you can see in the **Endpoints** page (on the **Pipeline Endpoints** tab) in [Azure Machine Learning studio](https://ml.azure.com). You can also find its URI as a property of the published pipeline object:
rest_endpoint = published_pipeline.endpoint print(rest_endpoint)
https://northcentralus.api.azureml.ms/pipelines/v1.0/subscriptions/8e2eae19-fb68-43d0-a429-b4d1a6bcf2d1/resourceGroups/dp100/providers/Microsoft.MachineLearningServices/workspaces/dp100_ml/PipelineRuns/PipelineSubmit/4fbd8be4-a138-4eb4-8642-f29ba99b5dda
MIT
08 - Create a Pipeline.ipynb
changyuanliu/mslearn-dp100
Call the pipeline endpointTo use the endpoint, client applications need to make a REST call over HTTP. This request must be authenticated, so an authorization header is required. A real application would require a service principal with which to be authenticated, but to test this out, we'll use the authorization heade...
from azureml.core.authentication import InteractiveLoginAuthentication interactive_auth = InteractiveLoginAuthentication() auth_header = interactive_auth.get_authentication_header() print("Authentication header ready.")
Authentication header ready.
MIT
08 - Create a Pipeline.ipynb
changyuanliu/mslearn-dp100
Now we're ready to call the REST interface. The pipeline runs asynchronously, so we'll get an identifier back, which we can use to track the pipeline experiment as it runs:
import requests experiment_name = 'mslearn-diabetes-pipeline' rest_endpoint = published_pipeline.endpoint response = requests.post(rest_endpoint, headers=auth_header, json={"ExperimentName": experiment_name}) run_id = response.json()["Id"] run_id
_____no_output_____
MIT
08 - Create a Pipeline.ipynb
changyuanliu/mslearn-dp100
Since you have the run ID, you can use it to wait for the run to complete.> **Note**: The pipeline should complete quickly, because each step was configured to allow output reuse. This was done primarily for convenience and to save time in this course. In reality, you'd likely want the first step to run every time in c...
from azureml.pipeline.core.run import PipelineRun published_pipeline_run = PipelineRun(ws.experiments[experiment_name], run_id) published_pipeline_run.wait_for_completion(show_output=True)
PipelineRunId: 6a5c86f3-5882-44c2-b2b8-ed8770beb271 Link to Azure Machine Learning Portal: https://ml.azure.com/experiments/mslearn-diabetes-pipeline/runs/6a5c86f3-5882-44c2-b2b8-ed8770beb271?wsid=/subscriptions/8e2eae19-fb68-43d0-a429-b4d1a6bcf2d1/resourcegroups/dp100/workspaces/dp100_ml PipelineRun Status: Running ...
MIT
08 - Create a Pipeline.ipynb
changyuanliu/mslearn-dp100
Schedule the PipelineSuppose the clinic for the diabetes patients collects new data each week, and adds it to the dataset. You could run the pipeline every week to retrain the model with the new data.
from azureml.pipeline.core import ScheduleRecurrence, Schedule # Submit the Pipeline every Monday at 00:00 UTC recurrence = ScheduleRecurrence(frequency="Week", interval=1, week_days=["Monday"], time_of_day="00:00") weekly_schedule = Schedule.create(ws, name="weekly-diabetes-training", ...
Pipeline scheduled.
MIT
08 - Create a Pipeline.ipynb
changyuanliu/mslearn-dp100
You can retrieve the schedules that are defined in the workspace like this:
schedules = Schedule.list(ws) schedules
_____no_output_____
MIT
08 - Create a Pipeline.ipynb
changyuanliu/mslearn-dp100
You can check the latest run like this:
pipeline_experiment = ws.experiments.get('mslearn-diabetes-pipeline') latest_run = list(pipeline_experiment.get_runs())[0] latest_run.get_details()
_____no_output_____
MIT
08 - Create a Pipeline.ipynb
changyuanliu/mslearn-dp100
Example Aggregations Aggregating data with MDF Searches using `Forge.search()` are limited to 10,000 results. However, there are two methods to circumvent this restriction: `Forge.aggregate_source()` and `Forge.aggregate()`.
import json from mdf_forge.forge import Forge mdf = Forge()
_____no_output_____
Apache-2.0
docs/examples/Example_Aggregations.ipynb
pythonpanda2/forge
aggregate_source - NIST XPS DBExample: We want to collect all records from the NIST XPS Database and analyze the binding energies. This database has almost 30,000 records, so we have to use `aggregate()`.
# First, let's aggregate all the nist_xps_db data. all_entries = mdf.aggregate_sources("nist_xps_db") print(len(all_entries)) # Now, let's parse out the enery_uncertainty_ev and print the results for analysis. uncertainties = {} for record in all_entries: if record["mdf"]["resource_type"] == "record": unc =...
{ "0": 29189 }
Apache-2.0
docs/examples/Example_Aggregations.ipynb
pythonpanda2/forge
aggregate - Multiple DatasetsExample: We want to analyze how often elements are studied with Gallium (Ga), and what the most frequent elemental pairing is. There are more than 10,000 records containing Gallium data.
# First, let's aggregate everything that has "Ga" in the list of elements. all_results = mdf.aggregate("material.elements:Ga") print(len(all_results)) # Now, let's parse out the other elements in each record and keep a running tally to print out. elements = {} for record in all_results: if record["mdf"]["resource_t...
{ "Ac": 267, "Ag": 323, "Al": 322, "Ar": 2, "As": 872, "Au": 372, "B": 301, "Ba": 342, "Be": 281, "Bi": 4172, "Br": 38, "C": 87, "Ca": 370, "Cd": 174, "Ce": 325, "Cl": 57, "Co": 381, "Cr": 315, "Cs": 160, "Cu": 403, "Dy": 317, "Er":...
Apache-2.0
docs/examples/Example_Aggregations.ipynb
pythonpanda2/forge
Housing market predictionsThe real estate markets present an interesting opportunity for data scientists to analyze and predict the behaviour and trends of property prices.In this project I focus on implementing a few advanced regression models to predict housing prices based on various property and location character...
import os import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from sklearn.feature_...
_____no_output_____
Apache-2.0
Notebooks/.ipynb_checkpoints/Housing prices-checkpoint.ipynb
pristdata/prisdata.github.io
1. Data exploration and cleaning
housing = pd.read_csv("data.csv") housing.info() housing.head() print(housing.isnull().sum())
date 0 price 0 bedrooms 0 bathrooms 0 sqft_living 0 sqft_lot 0 floors 0 waterfront 0 view 0 condition 0 sqft_above 0 sqft_basement 0 yr_built 0 yr_renovated 0 street 0 city 0 statezip ...
Apache-2.0
Notebooks/.ipynb_checkpoints/Housing prices-checkpoint.ipynb
pristdata/prisdata.github.io
The data set consists of 4600 rows of 18 columns comprising various property characteristics related to their size, room and distribution attributes and city (from the state of Washington, U.S.). There are no null values. Since the location related columns (except 'city' and 'street') and the 'date' column are homogen...
# Unnecesary columns elimination housing = housing.loc[:, housing.columns != 'country'] housing = housing.loc[:, housing.columns != 'date'] # Round the price column housing['price'] = housing['price'].round(decimals=2)
_____no_output_____
Apache-2.0
Notebooks/.ipynb_checkpoints/Housing prices-checkpoint.ipynb
pristdata/prisdata.github.io
2. Data visualization The price distribution plot below shows that most houses are in the range of 250 thousand dollars to one million, with a median of around 460 thousand dollars.
round(housing.price.median()) # Housing prices distribution plt.figure(figsize = (11,6)) sns.histplot(housing['price'], color = "c", kde=True) plt.xlabel('Price in millions', fontsize = 14) plt.ylabel('Frequency', fontsize = 14) plt.xticks(fontsize = 14) plt.yticks(fontsize = 14) plt.xlim(0, 2500000) plt.show() hous...
_____no_output_____
Apache-2.0
Notebooks/.ipynb_checkpoints/Housing prices-checkpoint.ipynb
pristdata/prisdata.github.io
 The plot above shows that there is considerable price viariability by city. This may be true also for different streets and postal codes so I decided to leave those object variables for analysis (later enconded/transformed into dummy variables).  
# Scatterplots of housing rooms, floors and condition plt.style.use('default') fig, ax = plt.subplots(2, 2, figsize = (8, 6)) housing.plot(kind='scatter', x='bedrooms', y='price', color='mediumaquamarine', alpha=0.3, ylim=(0,2500000), ax=ax[0,0]) housing.plot(kind='scatter', x='bathrooms', y='price', color='steelblu...
_____no_output_____
Apache-2.0
Notebooks/.ipynb_checkpoints/Housing prices-checkpoint.ipynb
pristdata/prisdata.github.io
 As observed in the plots above, the house condition, number of bathrooms and number of bedrooms in general show a positive correlation with price. The relation between number of floors and the house price is not entirely clear. 
# Scatterplots of house square feet variables (size) plt.style.use('seaborn-dark') fig, ax = plt.subplots(2, 2, figsize = (8, 6)) housing.plot(kind='scatter', x='sqft_living', y='price', color='blue', alpha=0.2, ylim=(0,3000000), ax=ax[0,0]) housing.plot(kind='scatter', x='sqft_lot', y='price', color='darkmagenta', a...
_____no_output_____
Apache-2.0
Notebooks/.ipynb_checkpoints/Housing prices-checkpoint.ipynb
pristdata/prisdata.github.io
 The scatterplots above show that all the variables related to the houses size show somewhat of a positive linear relationship with price. They may be amongst the most important features for price prediction. This will later be elucidated by plotting model's feature importance.  
# Correlation heatmap corr_matrix = housing.corr() plt.figure(figsize=(10, 8)) sns.heatmap(corr_matrix, vmax=1, cmap="twilight_shifted") plt.show()
_____no_output_____
Apache-2.0
Notebooks/.ipynb_checkpoints/Housing prices-checkpoint.ipynb
pristdata/prisdata.github.io
 There seems to be few pairs of highly correlated numeric variables, however, they are expected since many characteristics are related to the size and condition of the house so I decided to not remove them. 3. Data preparation All the necessary preprocessing steps for machine learning were followed below. The c...
# Encoding object variables (city, street, zip code) for col in housing.columns: if housing[col].dtype == 'object': encoded = pd.get_dummies(housing[col], drop_first=False) encoded = encoded.add_prefix('{}_'.format(col)) housing.drop(col, axis=1, inplace=True) housing = housing.join...
_____no_output_____
Apache-2.0
Notebooks/.ipynb_checkpoints/Housing prices-checkpoint.ipynb
pristdata/prisdata.github.io
4. Model fitting Since Multiple Linear Regression performed poorly, Polynomial Regression was also attempted (in case of non-linearity predominance) but the results were also deficient. So a few other regression models were fit in this analysis:- Ridge Regression - Lasso Regression- Bayesian Ridge Regression- Gradie...
# Some regression models were cross validated through the following grid search method alphas = arange(0, 1, 0.01) # range of alpha values to test grid = GridSearchCV(estimator=model, param_grid=dict(alpha=alphas)) # search grid grid.fit(X, y) # fit print(grid.best_score_) # summary of the grid search print(grid...
| Regression model | R-squared | |--------------------+-------------| | Ridge | 0.602584 | | Bayesian Ridge | 0.603049 | | Lasso | 0.460363 | | Gradient Boosting | 0.633882 | | XGBoost | 0.709033 |
Apache-2.0
Notebooks/.ipynb_checkpoints/Housing prices-checkpoint.ipynb
pristdata/prisdata.github.io
5. Discussion and conclusions * Ridge regression trades away much of the variance (due to multicollinearity) in exchange for a little bias, so it performed relatively well considering there was not that much multicollinearity.  * Bayesian ridge regression is also a linear regression model with extra regularizat...
# Feature importance plt.figure(figsize=(14, 14)) plot_importance(XGBoost, max_num_features=10) plt.show()
_____no_output_____
Apache-2.0
Notebooks/.ipynb_checkpoints/Housing prices-checkpoint.ipynb
pristdata/prisdata.github.io
Import Data
import os !git clone https://github.com/jihoo-kim/Coronavirus-Dataset PATIENT_PATH = "/content/Coronavirus-Dataset/patient.csv" import os !git clone https://github.com/ClementBM/Experiment_Coronavius.git PYRAMID_PATH = "/content/Experiment_Coronavius/data/population-pyramid-south-korea.csv" import pandas as pd df_ko...
_____no_output_____
MIT
notebook/Coronavirus_Korea_Distribution.ipynb
ClementBM/Experiment_Coronavius
EDA Patients
df_korea_patients.head() display(df_korea_patients.head()) display(df_korea_patients.shape) display(df_korea_patients.columns) display(df_korea_patients.iloc[:10,:10].dtypes)
_____no_output_____
MIT
notebook/Coronavirus_Korea_Distribution.ipynb
ClementBM/Experiment_Coronavius
Cleaning data
# drop sample if sex or birth_year is NaN not_nan = df_korea_patients['birth_year'].notna() & df_korea_patients['sex'].notna() df_korea_patients = df_korea_patients[not_nan] # typo df_korea_patients["sex"] = df_korea_patients["sex"].replace("feamle", "female") df_korea_patients['age'] = 2020 - df_korea_patients['birth...
_____no_output_____
MIT
notebook/Coronavirus_Korea_Distribution.ipynb
ClementBM/Experiment_Coronavius
Distribution
import seaborn as sns import matplotlib.pyplot as plt plt.figure(figsize=(14,10)) sns.violinplot(x="state", y="age", hue="sex", data=df_korea_patients, order=["deceased", "isolated", "released"], palette={"female": "#d98b5f", "male": "#597dbf"}, s...
_____no_output_____
MIT
notebook/Coronavirus_Korea_Distribution.ipynb
ClementBM/Experiment_Coronavius
Age pyramid
df_korea_population_pyramid.plot(kind='barh', x="age_range", color=['#597dbf', '#d98b5f'], figsize=(14, 10)) plt.xlabel("Population") plt.ylabel("Age range") plt.legend() plt.show()
_____no_output_____
MIT
notebook/Coronavirus_Korea_Distribution.ipynb
ClementBM/Experiment_Coronavius
Adding age range
import math import numpy as np import matplotlib.pyplot as plt def group_age(age, window): if age > 99: return "100+" if age % 5 != 0: lower = int(math.floor(age / float(window))) * window upper = int(math.ceil(age / float(window))) * window - 1 return f"{lower}-{upper}" else: lower =...
_____no_output_____
MIT
notebook/Coronavirus_Korea_Distribution.ipynb
ClementBM/Experiment_Coronavius
Age range dictionary for ordering values
age_range_order = df_korea_population_pyramid["age_range"].to_dict() age_range_order = {v: k for k, v in age_range_order.items()}
_____no_output_____
MIT
notebook/Coronavirus_Korea_Distribution.ipynb
ClementBM/Experiment_Coronavius
Age pyramid proportion
total_male = sum(df_korea_population_pyramid.loc[:,'male']) total_female = sum(df_korea_population_pyramid.loc[:,'female']) df_korea_population_pyramid["male_prop"] = df_korea_population_pyramid["male"] / total_male df_korea_population_pyramid["female_prop"] = df_korea_population_pyramid["female"] / total_female
_____no_output_____
MIT
notebook/Coronavirus_Korea_Distribution.ipynb
ClementBM/Experiment_Coronavius
def infected_population_normed(df): result = df.groupby(["age_range", "sex"], as_index=False)["age_range", "sex"].size() result = ( pd.DataFrame(result) .pivot_table(index=["age_range"], columns=["sex"], fill_value=0.0) .reset_index() ) result = result.set_index("age_range") result = result...
_____no_output_____
MIT
notebook/Coronavirus_Korea_Distribution.ipynb
ClementBM/Experiment_Coronavius
Normed distribution of all
display(df_korea_patients.shape[0]) plot_normed_distribution(df_korea_patients) display(df_korea_patients[df_korea_patients["age_range"] == "100+"]) display(df_korea_population_pyramid[df_korea_population_pyramid["age_range"] == "100+"]) display(df_korea_patients.shape[0]) plot_normed_distribution(df_korea_patients[df_...
_____no_output_____
MIT
notebook/Coronavirus_Korea_Distribution.ipynb
ClementBM/Experiment_Coronavius
Normed proportion of **deceased**
df_deceased = df_korea_patients[df_korea_patients["state"] == "deceased"] display(df_deceased.shape[0]) plot_normed_distribution(df_deceased)
_____no_output_____
MIT
notebook/Coronavirus_Korea_Distribution.ipynb
ClementBM/Experiment_Coronavius
Normed proportion of **released**
df_released = df_korea_patients[df_korea_patients["state"] == "released"] display(df_released.shape[0]) plot_normed_distribution(df_released)
_____no_output_____
MIT
notebook/Coronavirus_Korea_Distribution.ipynb
ClementBM/Experiment_Coronavius
Normed proportion of **isolated**
df_released = df_korea_patients[(df_korea_patients["state"] == "isolated") & (df_korea_patients["age_range"] != "100+")] display(df_released.shape[0]) plot_normed_distribution(df_released)
_____no_output_____
MIT
notebook/Coronavirus_Korea_Distribution.ipynb
ClementBM/Experiment_Coronavius
Zeisel GRN Inference and Analysis (nb duplicate) 0. Import dependencies
import os import sys sys.path.append('../../') from arboreto.core import * from arboreto.utils import * import matplotlib.pyplot as plt
_____no_output_____
BSD-3-Clause
notebooks/zeisel/Zeisel_SGBM_dup.ipynb
redst4r/arboreto
1. Load the data (outside the scope of the arboreto API)
zeisel_ex_path = '/media/tmo/data/work/datasets/zeisel/expression_sara_filtered.txt' zeisel_tf_path = '/media/tmo/data/work/datasets/TF/mm9_TFs.txt' zeisel_df = pd.read_csv(zeisel_ex_path, index_col=0, sep='\t').T zeisel_df.head() zeisel_ex_matrix = zeisel_df.as_matrix().astype(np.float) zeisel_ex_matrix assert(zeisel_...
_____no_output_____
BSD-3-Clause
notebooks/zeisel/Zeisel_SGBM_dup.ipynb
redst4r/arboreto
X. Calculate a 'signal' measure* count the number of non-zero entries per column
signal_series = zeisel_df.astype(bool).sum(axis=0) nonzero_df = signal_series.to_frame('non_zero').sort_values(by='non_zero', ascending=False).reset_index() nonzero_df.columns = ['target', 'non_zero'] nonzero_df.to_csv('zeisel_nonzero.tsv', sep='\t') nonzero_df.head() nonzero_df.merge(meta_df, on=['target'])[['n_estim...
_____no_output_____
BSD-3-Clause
notebooks/zeisel/Zeisel_SGBM_dup.ipynb
redst4r/arboreto
2. Initialize Dask client
from dask.distributed import Client, LocalCluster client = Client(LocalCluster(memory_limit=8e9)) client
_____no_output_____
BSD-3-Clause
notebooks/zeisel/Zeisel_SGBM_dup.ipynb
redst4r/arboreto
If you work remotely, use port forwarding to view the dashboard:```bash$ ssh -L 8000:localhost:8787 nostromo```
client.shutdown()
_____no_output_____
BSD-3-Clause
notebooks/zeisel/Zeisel_SGBM_dup.ipynb
redst4r/arboreto
3. Compute GRN inference graph Create the dask computation graphs
%%time network_graph, meta_graph = create_graph(zeisel_ex_matrix, zeisel_gene_names, zeisel_tf_names, "GBM", SGBM_KWARGS, ...
CPU times: user 11.4 s, sys: 1.94 s, total: 13.3 s Wall time: 10.7 s
BSD-3-Clause
notebooks/zeisel/Zeisel_SGBM_dup.ipynb
redst4r/arboreto
Persist the distributed DataFrames
%%time a, b = client.persist([network_graph, meta_graph])
_____no_output_____
BSD-3-Clause
notebooks/zeisel/Zeisel_SGBM_dup.ipynb
redst4r/arboreto
Compute results
%%time network_df = a.compute(sync=True)
CPU times: user 18.2 s, sys: 2.58 s, total: 20.8 s Wall time: 19.8 s
BSD-3-Clause
notebooks/zeisel/Zeisel_SGBM_dup.ipynb
redst4r/arboreto
* CPU times: user 8min 15s, sys: 5min 41s, total: 13min 56s* Wall time: **16min 30s**
%%time meta_df = b.compute(sync=True)
CPU times: user 16.6 s, sys: 1.51 s, total: 18.2 s Wall time: 17.3 s
BSD-3-Clause
notebooks/zeisel/Zeisel_SGBM_dup.ipynb
redst4r/arboreto
4. Save full and top_100k networks to file
len(network_df) len(meta_df) meta_df.to_csv('zeisel_meta_df.tsv', sep='\t') network_df.sort_values(by='importance', ascending=0).to_csv('zeisel_sgbm_all.txt', index=False, sep='\t') top_100k = network_df.nlargest(100000, columns=['importance']) top_100k.to_csv('zeisel_sgbm_100k.txt', index=False, sep='\t') merged_df =...
_____no_output_____
BSD-3-Clause
notebooks/zeisel/Zeisel_SGBM_dup.ipynb
redst4r/arboreto
Distribution of nr of boosting rounds per regression
meta_df.hist(bins=100, figsize=(20, 9), log=0) plt.show()
_____no_output_____
BSD-3-Clause
notebooks/zeisel/Zeisel_SGBM_dup.ipynb
redst4r/arboreto
Plot the maximum variable importance (sklearn default) vs. nr of boosting rounds* **!= the formula in Arboreto*** Using the sklearn default variable importances which normalizes regressions by dividing by nr of trees in the ensemble.* Effect is that regressions with few trees also deliver high feature importances (aka...
max_imp2_by_rounds =\ meta_df.merge(merged_df.groupby(['target'])['imp2'].nlargest(1).reset_index(), how='left', on=['target']) max_imp2_by_rounds.plot.scatter(x='n_estimators', y='imp2', figsize=(16, 9)) plt.show() max_imp2_by_rounds.plot.hexbin(x='n_estimators', ...
_____no_output_____
BSD-3-Clause
notebooks/zeisel/Zeisel_SGBM_dup.ipynb
redst4r/arboreto
Plotting corrected feature importance (Arboreto SGBM default) vs. nr of boosting rounds
max_imp_by_rounds =\ meta_df.merge(network_df.groupby(['target'])['importance'].nlargest(1).reset_index(), how='left', on=['target']) max_imp_by_rounds.plot.scatter(x='n_estimators', y='importance', figsize=(16, 9)) plt.show() max_imp_by_rounds.plot.hexbin(x='n_estimators', ...
_____no_output_____
BSD-3-Clause
notebooks/zeisel/Zeisel_SGBM_dup.ipynb
redst4r/arboreto
Links in common with GENIE3
z_genie3 = pd.read_csv('/media/tmo/data/work/datasets/benchmarks/genie3/zeisel/zeisel.filtered.genie3.txt', header=None, sep='\t') z_genie3.columns=['TF', 'target', 'importance'] inner = z_genie3.merge(top_100k, how='inner', on=['TF', 'target']) len(inner) inner_50k = z_genie3[:50000].merge(top_100k[:50000], how='inner...
_____no_output_____
BSD-3-Clause
notebooks/zeisel/Zeisel_SGBM_dup.ipynb
redst4r/arboreto
Forecasting using spatio-temporal data with combined Graph Convolution + LSTM model Run the latest release of this notebook: The dynamics of many real-world phenomena are spatio-temporal in nature. Traffic forecasting is a quintessential example of spatio-temporal problems for which we present here a deep learning fra...
# install StellarGraph if running on Google Colab import sys if 'google.colab' in sys.modules: %pip install -q stellargraph[demos]==1.1.0b # verify that we're using the correct version of StellarGraph for this notebook import stellargraph as sg try: sg.utils.validate_notebook_version("1.1.0b") except AttributeEr...
_____no_output_____
Apache-2.0
demos/time-series/gcn-lstm-time-series.ipynb
lyubov888L/stellargraph
DataWe apply the gcn-lstm model to the **Los-loop** data. This traffic datasetcontains traffic information collected from loop detectors in the highway of Los Angeles County (Jagadishet al., 2014). There are several processed versions of this dataset used by the research community working in Traffic forecasting space...
import stellargraph as sg
_____no_output_____
Apache-2.0
demos/time-series/gcn-lstm-time-series.ipynb
lyubov888L/stellargraph
This demo is based on the pre-processed version of the dataset used by the TGCN paper.
dataset = sg.datasets.METR_LA()
_____no_output_____
Apache-2.0
demos/time-series/gcn-lstm-time-series.ipynb
lyubov888L/stellargraph
(See [the "Loading from Pandas" demo](../basics/loading-pandas.ipynb) for details on how data can be loaded.)
speed_data, sensor_dist_adj = dataset.load() num_nodes = speed_data.shape[1] time_len = speed_data.shape[0] print("No. of sensors:", num_nodes, "\nNo of timesteps:", time_len)
No. of sensors: 207 No of timesteps: 2016
Apache-2.0
demos/time-series/gcn-lstm-time-series.ipynb
lyubov888L/stellargraph
**Let's look at a sample of speed data.**
speed_data.head()
_____no_output_____
Apache-2.0
demos/time-series/gcn-lstm-time-series.ipynb
lyubov888L/stellargraph
As you can see above, there are 2016 observations (timesteps) of speed records over 207 sensors. Speeds are recorded every 5 minutes. This means that, for a single hour, you will have 12 observations. Similarly, a single day will contain 288 (12x24) observations. Overall, the data consists of speeds recorded every 5 m...
def train_test_split(data, train_portion): time_len = data.shape[0] train_size = int(time_len * train_portion) train_data = np.array(data[:train_size]) test_data = np.array(data[train_size:]) return train_data, test_data train_rate = 0.8 train_data, test_data = train_test_split(speed_data, train_rat...
Train data: (1612, 207) Test data: (404, 207)
Apache-2.0
demos/time-series/gcn-lstm-time-series.ipynb
lyubov888L/stellargraph
ScalingIt is generally a good practice to rescale the data from the original range so that all values are within the range of 0 and 1. Normalization can be useful and even necessary when your time series data has input values with differing scales. In the following we normalize the speed timeseries by the maximum an...
def scale_data(train_data, test_data): max_speed = train_data.max() min_speed = train_data.min() train_scaled = (train_data - min_speed) / (max_speed - min_speed) test_scaled = (test_data - min_speed) / (max_speed - min_speed) return train_scaled, test_scaled train_scaled, test_scaled = scale_data(t...
_____no_output_____
Apache-2.0
demos/time-series/gcn-lstm-time-series.ipynb
lyubov888L/stellargraph
Sequence data preparation for LSTMWe first need to prepare the data to be fed into an LSTM. The LSTM model learns a function that maps a sequence of past observations as input to an output observation. As such, the sequence of observations must be transformed into multiple examples from which the LSTM can learn.To mak...
seq_len = 10 pre_len = 12 def sequence_data_preparation(seq_len, pre_len, train_data, test_data): trainX, trainY, testX, testY = [], [], [], [] for i in range(len(train_data) - int(seq_len + pre_len - 1)): a = train_data[ i : i + seq_len + pre_len, ] trainX.append(a[:seq_len...
(1591, 10, 207) (1591, 207) (383, 10, 207) (383, 207)
Apache-2.0
demos/time-series/gcn-lstm-time-series.ipynb
lyubov888L/stellargraph
StellarGraph Graph Convolution and LSTM model
from stellargraph.layer import GraphConvolutionLSTM gcn_lstm = GraphConvolutionLSTM( seq_len=seq_len, adj=sensor_dist_adj, gc_layers=2, gc_activations=["relu", "relu"], lstm_layer_size=[200], lstm_activations=["tanh"], ) x_input, x_output = gcn_lstm.in_out_tensors() model = Model(inputs=x_input,...
_____no_output_____
Apache-2.0
demos/time-series/gcn-lstm-time-series.ipynb
lyubov888L/stellargraph
Rescale valuesRecale the predicted values to the original value range of the timeseries.
## Rescale values max_speed = train_data.max() min_speed = train_data.min() ## actual train and test values train_rescref = np.array(trainY * max_speed) test_rescref = np.array(testY * max_speed) ## Rescale model predicted values train_rescpred = np.array((ythat) * max_speed) test_rescpred = np.array((yhat) * max_spee...
_____no_output_____
Apache-2.0
demos/time-series/gcn-lstm-time-series.ipynb
lyubov888L/stellargraph
Measuring the performance of the modelTo understand how well the model is performing, we compare it against a naive benchmark.1. Naive prediction: using the most recently **observed** value as the predicted value. Note, that albeit being **naive** this is a very strong baseline to beat. Especially, when speeds are rec...
## Naive prediction benchmark (using previous observed value) testnpred = np.array(testX).transpose(1, 0, 2)[ -1 ] # picking the last speed of the 10 sequence for each segment in each sample testnpredc = (testnpred) * max_speed ## Performance measures seg_mael = [] seg_masel = [] seg_nmael = [] for j in range(t...
_____no_output_____
Apache-2.0
demos/time-series/gcn-lstm-time-series.ipynb
lyubov888L/stellargraph
Plot of actual and predicted speeds on a sample sensor
##all test result visualization fig1 = plt.figure(figsize=(15, 8)) # ax1 = fig1.add_subplot(1,1,1) a_pred = test_rescpred[:, 1] a_true = test_rescref[:, 1] plt.plot(a_pred, "r-", label="prediction") plt.plot(a_true, "b-", label="true") plt.xlabel("time") plt.ylabel("speed") plt.legend(loc="best", fontsize=10) plt.sh...
_____no_output_____
Apache-2.0
demos/time-series/gcn-lstm-time-series.ipynb
lyubov888L/stellargraph
jupyterplot> Create real-time plots in Jupyter Notebooks.
# hide from nbdev.showdoc import * # export import IPython import matplotlib.pyplot as plt try: from lrcurve.plot_learning_curve import PlotLearningCurve except: from lrcurve.plot_learning_curve import PlotLearningCurve # so sorry for this hack :( the first import goes through # the lrcurve __init__ which trig...
_____no_output_____
Apache-2.0
notebooks/00_jupyterplot.ipynb
lvwerra/jupyterplot
Example
from jupyterplot import ProgressPlot pp = ProgressPlot() for i in range(100): pp.update(1 / (i + 1)) pp.finalize() import numpy as np pp = ProgressPlot(x_iterator=False, x_lim=[-1, 1], y_lim=[-1, 1]) for i in range(1001): pp.update(np.sin(2 * np.pi * i / 1000), np.cos(2 * np.pi * i / 1000)) pp.finalize()
_____no_output_____
Apache-2.0
notebooks/00_jupyterplot.ipynb
lvwerra/jupyterplot
100 numpy exercisesThis is a collection of exercises that have been collected in the numpy mailing list, on stack overflow and in the numpy documentation. The goal of this collection is to offer a quick reference for both old and new users but also to provide a set of exercises for those who teach.If you find an error...
import numpy as np
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ShuoGH/numpy-100
2. Print the numpy version and the configuration (β˜…β˜†β˜†)
print(np.__version__) np.show_config()
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ShuoGH/numpy-100
3. Create a null vector of size 10 (β˜…β˜†β˜†)
Z = np.zeros(10) print(Z)
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ShuoGH/numpy-100
4. How to find the memory size of any array (β˜…β˜†β˜†)
Z = np.zeros((10,10)) print("%d bytes" % (Z.size * Z.itemsize))
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ShuoGH/numpy-100
5. How to get the documentation of the numpy add function from the command line? (β˜…β˜†β˜†)
%run `python -c "import numpy; numpy.info(numpy.add)"`
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ShuoGH/numpy-100
6. Create a null vector of size 10 but the fifth value which is 1 (β˜…β˜†β˜†)
Z = np.zeros(10) Z[4] = 1 print(Z)
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ShuoGH/numpy-100
7. Create a vector with values ranging from 10 to 49 (β˜…β˜†β˜†)
Z = np.arange(10,50) print(Z)
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ShuoGH/numpy-100
8. Reverse a vector (first element becomes last) (β˜…β˜†β˜†)
Z = np.arange(50) Z = Z[::-1] print(Z)
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ShuoGH/numpy-100
9. Create a 3x3 matrix with values ranging from 0 to 8 (β˜…β˜†β˜†)
Z = np.arange(9).reshape(3,3) print(Z)
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ShuoGH/numpy-100
10. Find indices of non-zero elements from \[1,2,0,0,4,0\] (β˜…β˜†β˜†)
nz = np.nonzero([1,2,0,0,4,0]) print(nz)
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ShuoGH/numpy-100
11. Create a 3x3 identity matrix (β˜…β˜†β˜†)
Z = np.eye(3) print(Z)
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ShuoGH/numpy-100
12. Create a 3x3x3 array with random values (β˜…β˜†β˜†)
Z = np.random.random((3,3,3)) print(Z)
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ShuoGH/numpy-100
13. Create a 10x10 array with random values and find the minimum and maximum values (β˜…β˜†β˜†)
Z = np.random.random((10,10)) Zmin, Zmax = Z.min(), Z.max() print(Zmin, Zmax)
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ShuoGH/numpy-100
14. Create a random vector of size 30 and find the mean value (β˜…β˜†β˜†)
Z = np.random.random(30) m = Z.mean() print(m)
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ShuoGH/numpy-100
15. Create a 2d array with 1 on the border and 0 inside (β˜…β˜†β˜†)
Z = np.ones((10,10)) Z[1:-1,1:-1] = 0 print(Z)
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ShuoGH/numpy-100
16. How to add a border (filled with 0's) around an existing array? (β˜…β˜†β˜†)
Z = np.ones((5,5)) Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0) print(Z)
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ShuoGH/numpy-100
17. What is the result of the following expression? (β˜…β˜†β˜†)
print(0 * np.nan) print(np.nan == np.nan) print(np.inf > np.nan) print(np.nan - np.nan) print(0.3 == 3 * 0.1)
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ShuoGH/numpy-100
18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (β˜…β˜†β˜†)
Z = np.diag(1+np.arange(4),k=-1) print(Z)
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ShuoGH/numpy-100
19. Create a 8x8 matrix and fill it with a checkerboard pattern (β˜…β˜†β˜†)
Z = np.zeros((8,8),dtype=int) Z[1::2,::2] = 1 Z[::2,1::2] = 1 print(Z)
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ShuoGH/numpy-100
20. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element?
print(np.unravel_index(100,(6,7,8)))
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ShuoGH/numpy-100