hexsha
stringlengths 40
40
| size
int64 6
14.9M
| ext
stringclasses 1
value | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 6
260
| max_stars_repo_name
stringlengths 6
119
| max_stars_repo_head_hexsha
stringlengths 40
41
| max_stars_repo_licenses
sequence | max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 6
260
| max_issues_repo_name
stringlengths 6
119
| max_issues_repo_head_hexsha
stringlengths 40
41
| max_issues_repo_licenses
sequence | max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 6
260
| max_forks_repo_name
stringlengths 6
119
| max_forks_repo_head_hexsha
stringlengths 40
41
| max_forks_repo_licenses
sequence | max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | avg_line_length
float64 2
1.04M
| max_line_length
int64 2
11.2M
| alphanum_fraction
float64 0
1
| cells
sequence | cell_types
sequence | cell_type_groups
sequence |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e779edc6802176e92f0c965be37762d5f8a5e8ef | 253,749 | ipynb | Jupyter Notebook | 1_get_regions_eof_reofs.ipynb | zzheng93/code_DSI_India_AutoML | a95fe541bd2e93376116254dc774d8a552d335a6 | [
"MIT"
] | null | null | null | 1_get_regions_eof_reofs.ipynb | zzheng93/code_DSI_India_AutoML | a95fe541bd2e93376116254dc774d8a552d335a6 | [
"MIT"
] | null | null | null | 1_get_regions_eof_reofs.ipynb | zzheng93/code_DSI_India_AutoML | a95fe541bd2e93376116254dc774d8a552d335a6 | [
"MIT"
] | null | null | null | 258.663609 | 34,776 | 0.908725 | [
[
[
"**Note: Please use the [pyEOF](https://pyeof.readthedocs.io/en/latest/installation.html) environment for this script**",
"_____no_output_____"
],
[
"This script is used to implement EOF, REOF and k-means clustering to get regions",
"_____no_output_____"
]
],
[
[
"from pyEOF import *\nimport numpy as np\nimport pandas as pd\nimport xarray as xr\nimport matplotlib.pyplot as plt\nimport gc\nimport warnings\nimport pickle\nfrom matplotlib.ticker import MaxNLocator\nfrom tqdm import tqdm\nfrom sklearn.cluster import KMeans\nimport cartopy.crs as ccrs\nimport cartopy.feature as cfeature\n\nwarnings.filterwarnings('ignore')\n\n# select region\ndef sel_extent(ds):\n return ds.sel(lat=slice(6,36),lon=slice(68,98))\n\n# path\nds_path = \"./data/daily_surface_pm25_RH50.nc\"\nmask_path = \"./data/land_mask.nc\"",
"_____no_output_____"
]
],
[
[
"## plot the time series of the mean PM2.5 \nWe decided to use April and August as the testing data",
"_____no_output_____"
]
],
[
[
"mask = xr.open_dataset(mask_path)\nds = sel_extent(xr.open_dataset(ds_path)).where(mask[\"mask\"])\n\nds[\"PM25\"].groupby('time.month').mean(dim=[\"lon\",\"lat\",\"time\"]).plot()\nplt.show()",
"_____no_output_____"
]
],
[
[
"## get the data and implement EOFs\nBased on the results, we will select 4 PCs (n=4) and implemented varimax rotated EOFs (REOFs)",
"_____no_output_____"
]
],
[
[
"n=28\n\n# remove months \"4\" (April) and \"8\" (August), to be consistant with training data\nds = ds.sel(time=ds.time.dt.month.isin([1,2,3,\n 5,6,7,\n 9,10,11,12]))\ndf = ds[\"PM25\"].to_dataframe().reset_index() # get df from ds\n\n# process the data for implementing pyEOF\ndf_data = get_time_space(df, time_dim = \"time\", lumped_space_dims = [\"lat\",\"lon\"])\n\n# implement PCA/EOF\npca = df_eof(df_data)\neofs = pca.eofs(s=2, n=n)\neofs_ds = eofs.stack([\"lat\",\"lon\"], dropna=False).to_xarray()\npcs = pca.pcs(s=2, n=n)\nevf = pca.evf(n=n)\n\n# show the results\ndf = pd.DataFrame({\"n\":np.arange(1,n+1),\n \"evf\":pca.evf(n)*100.0,\n \"accum\":pca.evf(n).cumsum()*100.0\n })\n\nplt.scatter(df[\"n\"],df[\"accum\"], s=8)\nplt.axhline(y=50,c=\"r\",ls=\"-.\")\nplt.xlabel(\"# of PCs\")\nplt.ylabel(\"acc. explained variance [%]\")\nplt.show()\n\ndisplay(df.transpose())",
"_____no_output_____"
]
],
[
[
"## implement REOFs",
"_____no_output_____"
]
],
[
[
"n=4\n\n# implement REOF\npca = df_eof(df_data,pca_type=\"varimax\",n_components=n)\neofs = pca.eofs(s=2, n=n)\neofs_ds = eofs.stack([\"lat\",\"lon\"], dropna=False).to_xarray()\npcs = pca.pcs(s=2, n=n)\nevf = pca.evf(n=n)\n\ndf = pd.DataFrame({\"n\":np.arange(1,n+1),\n \"evf\":pca.evf(n)*100.0,\n \"accum\":pca.evf(n).cumsum()*100.0\n })\n\n# show the reults\nfig = plt.figure(figsize=(6,2))\n\nax = fig.add_subplot(121)\nax.scatter(df[\"n\"],df[\"evf\"], s=8)\nax.set_ylim(0,20)\nax.set_ylabel(\"explained variance [%]\")\nax.set_xlabel(\"PC\")\n\nax = fig.add_subplot(122)\nax.scatter(df[\"n\"],df[\"accum\"], s=8)\nax.set_ylim(0,60)\nax.set_ylabel(\"acc. explained variance [%]\")\nax.set_xlabel(\"PC\")\nax.axhline(y=50,c=\"r\",ls=\"-.\")\n\nplt.tight_layout()\nplt.show()\n\nprint(\"explained variance and acc. explained variance\")\ndisplay(df.transpose())\n\nprint(\"EOFs loading\")\neofs.transpose().describe().loc[[\"max\",\"min\"]].transpose()\n\neofs_ds = eofs.stack([\"lat\",\"lon\"], dropna=False).to_xarray()\nfig = plt.figure(figsize=(10,2))\nfor i in range(1,n+1):\n ax = fig.add_subplot(1,4,i)\n eofs_ds[\"PM25\"].sel(EOF=i).plot(ax=ax,vmax=1.0,vmin=-1.0,cbar_kwargs={'label': \"\"},cmap=\"bwr\")\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"## weighted EOFs loading",
"_____no_output_____"
]
],
[
[
"eofs_w = pd.DataFrame(data = (eofs.values * evf.reshape(n,1)),\n index = eofs.index,\n columns = eofs.columns)\n\neofs_w_ds = eofs_w.stack([\"lat\",\"lon\"], dropna=False).to_xarray()\nfig = plt.figure(figsize=(10,2))\nfor i in range(1,n+1):\n ax = fig.add_subplot(1,4,i)\n eofs_w_ds[\"PM25\"].sel(EOF=i).plot(ax=ax,cmap=\"bwr\",\n vmax=1.0*evf[i-1],\n vmin=-1.0*evf[i-1],\n cbar_kwargs={'label': \"\"})\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"## implement k-Means",
"_____no_output_____"
]
],
[
[
"# get the index which is not \"nan\"\nplaceholder_idx = np.argwhere(~np.isnan((eofs_w.values)[0])).reshape(-1)\n# get the matrix without missing values: locations (row) * EOFs (columns)\nm = eofs_w.values[:,placeholder_idx].transpose()\n# clustering and calculate the Sum_of_squared_distances\nSum_of_squared_distances = []\n\nK = range(2,15)\nfor n_clusters in tqdm(K):\n kmeans = KMeans(n_clusters=n_clusters, random_state=66).fit(m)\n Sum_of_squared_distances.append(kmeans.inertia_)\n \nssd = Sum_of_squared_distances\nresidual_x = K[1:]\nresidual = [(x - y) for x,y in zip(ssd,ssd[1:])]\npd.DataFrame({\"n_clusters\":K, \"ssd\":Sum_of_squared_distances}).transpose()",
"100%|██████████| 13/13 [00:01<00:00, 6.59it/s]\n"
],
[
"fig = plt.figure(figsize=(8,4))\ncluster_list = [3,4,5,6,7,8]\nfor i in range(len(cluster_list)):\n n_cluster = cluster_list[i]\n ax = fig.add_subplot(2,3,i+1)\n clusters = KMeans(n_clusters=n_cluster, random_state=66).fit_predict(m)\n\n df_f = eofs.copy()\n df_f.loc[str(n+1),:] = np.nan\n df_f.iloc[n,placeholder_idx] = clusters\n\n df_fs = df_f.stack([\"lat\",\"lon\"], dropna=False).to_xarray()\n df_fs.sel(EOF=str(n+1))[\"PM25\"].plot(ax=ax, cbar_kwargs={\"label\":\"cluster\"})\n ax.set_title(f\"clusters={n_cluster}\")\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"## we select n_cluster = 6 to further the analysis",
"_____no_output_____"
]
],
[
[
"n_cluster = 6\n\nfig = plt.figure(figsize=(8,3))\n\nax = fig.add_subplot(121)\nax.plot(K, Sum_of_squared_distances, 'bx-')\nax.plot(n_cluster,Sum_of_squared_distances[n_cluster-2],\"rx\")\nax.set_xlabel('number of clusters')\nax.set_ylabel('sum of squared distances')\n# ax.set_title('Elbow method for optimal number of clusters')\n\nax = fig.add_subplot(122)\nax.plot(residual_x, residual, 'bx-')\nax.set_xlabel('number of clusters')\nax.set_ylabel('diff. in ssd')\nax.plot(n_cluster,residual[n_cluster-3],\"rx\")\n# ax.set_title('difference in sum of squared distances')\nax.xaxis.set_major_locator(MaxNLocator(integer=True))\n\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"## use n_cluster = 6 to implement the clusters",
"_____no_output_____"
]
],
[
[
"clusters = KMeans(n_clusters=n_cluster, random_state=66).fit_predict(m)\n\ndf_f = eofs.copy()\ndf_f.loc[str(n+1),:] = np.nan\ndf_f.iloc[n,placeholder_idx] = clusters\n\nds_f = df_f.stack([\"lat\",\"lon\"], dropna=False).to_xarray()",
"_____no_output_____"
],
[
"fig = plt.figure(figsize=(3,3))\nax = fig.add_subplot(111, projection=ccrs.PlateCarree())\nax.set_extent([68,98,6,36],crs=ccrs.PlateCarree())\nds_regions = ds_f.sel(EOF=str(n+1))[\"PM25\"].drop(\"EOF\")\nds_regions.plot(ax=ax,cbar_kwargs={\"label\":\"cluster\"})\n# ax.add_feature(cfeature.STATES.with_scale('10m'),\n# facecolor='none',\n# edgecolor='black')\n# ax.add_feature(cfeature.BORDERS,edgecolor='red')\nplt.show()",
"_____no_output_____"
]
],
[
[
"## save the clusters masks",
"_____no_output_____"
]
],
[
[
"fig = plt.figure(figsize=(2*n_cluster,2))\nfor i in range(n_cluster):\n ax = fig.add_subplot(1,n_cluster,i+1)\n ds_f[\"mask_\"+str(i)] = ds_regions.where(ds_regions==i).notnull().squeeze()\n ds_f[\"mask_\"+str(i)].plot(ax=ax,cbar_kwargs={\"label\":\"\"})\n ax.set_title(\"mask_\"+str(i))\nplt.tight_layout()\nplt.show()\n\nmask_ls = [\"mask_\"+str(i) for i in range(n_cluster)]\nds_f[mask_ls].to_netcdf(\"./data/cluster_mask_\"+str(n_cluster)+\".nc\",engine=\"scipy\")",
"_____no_output_____"
]
],
[
[
"## save the regional masks",
"_____no_output_____"
]
],
[
[
"cluster_mask = xr.open_dataset(\"./data/cluster_mask_\"+str(n_cluster)+\".nc\",engine=\"scipy\")\nfig = plt.figure(figsize=(2*n_cluster,2))\nfor i in range(n_cluster):\n ax = fig.add_subplot(1,n_cluster,i+1)\n ds.mean(dim=\"time\").where(cluster_mask[\"mask_\"+str(i)])[\"PM25\"].plot(ax=ax,cbar_kwargs={\"label\":\"\"})\n ax.set_title(\"mask_\"+str(i))\n ax.set_xlabel(\"\")\n ax.set_ylabel(\"\")\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
],
[
"# process\ncluster_mask[\"mask_\"+str(0)] = cluster_mask.where((cluster_mask.lon>=90) & (cluster_mask.lat>=15),0)[\"mask_\"+str(0)]\ncluster_mask[\"mask_\"+str(3)] = cluster_mask.where((cluster_mask.lat>=12) & (cluster_mask.lat<=30),0)[\"mask_\"+str(3)]\ncluster_mask[\"mask_\"+str(4)] = cluster_mask.where((cluster_mask.lat<=20.5) & (cluster_mask.lat>=8),0)[\"mask_\"+str(4)]\n\n# rename\ncluster_mask = cluster_mask[[\"mask_0\",\"mask_1\",\"mask_3\",\"mask_4\"]]\\\n .rename({\"mask_0\":\"E\",\"mask_1\":\"W\",\"mask_3\":\"N\",\"mask_4\":\"S\"})\nloc_name = list(cluster_mask)\n\nfig = plt.figure(figsize=(n_cluster*2,2))\nfor i in range(len(loc_name)):\n ax = fig.add_subplot(1,n_cluster,i+1)\n ds.mean(dim=\"time\").where(cluster_mask[loc_name[i]])[\"PM25\"].plot(ax=ax,cbar_kwargs={\"label\":\"\"})\n ax.set_title(loc_name[i])\n ax.set_xlabel(\"\")\n ax.set_ylabel(\"\")\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"## save and load the regional mask",
"_____no_output_____"
]
],
[
[
"# save the regional mask\ncluster_mask.to_netcdf(\"./data/r_mask.nc\",engine=\"scipy\")\n\n# load the regional mask\ntest = xr.open_dataset(\"./data/r_mask.nc\",engine=\"scipy\")\nfig = plt.figure(figsize=(n_cluster*2,2))\nfor i in range(len(loc_name)):\n ax = fig.add_subplot(1,n_cluster,i+1)\n ds.mean(dim=\"time\").where(test[loc_name[i]])[\"PM25\"].plot(ax=ax,cbar_kwargs={\"label\":\"\"})\n ax.set_title(loc_name[i])\n ax.set_xlabel(\"\")\n ax.set_ylabel(\"\")\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
e77a06e9b2f1e46f5891ae9d2514a4dcb70a8b00 | 213,540 | ipynb | Jupyter Notebook | src/graph_notebook/notebooks/04-Machine-Learning/Neptune-ML-03-Introduction-to-Link-Prediction-Gremlin.ipynb | zacharyrs/graph-notebook | 410722dc579013dc1e9fb747807570a7e7035387 | [
"ISC",
"Apache-2.0",
"CC0-1.0"
] | 1 | 2022-03-12T14:41:59.000Z | 2022-03-12T14:41:59.000Z | src/graph_notebook/notebooks/04-Machine-Learning/Neptune-ML-03-Introduction-to-Link-Prediction-Gremlin.ipynb | zacharyrs/graph-notebook | 410722dc579013dc1e9fb747807570a7e7035387 | [
"ISC",
"Apache-2.0",
"CC0-1.0"
] | null | null | null | src/graph_notebook/notebooks/04-Machine-Learning/Neptune-ML-03-Introduction-to-Link-Prediction-Gremlin.ipynb | zacharyrs/graph-notebook | 410722dc579013dc1e9fb747807570a7e7035387 | [
"ISC",
"Apache-2.0",
"CC0-1.0"
] | 2 | 2022-02-09T15:41:33.000Z | 2022-02-11T07:47:40.000Z | 343.864734 | 112,636 | 0.922581 | [
[
[
"",
"_____no_output_____"
],
[
"# Link Prediction - Introduction\nIn this Notebook we are going to examine the process of using Amazon Neptune ML feature to perform link prediction in a property graph. \n\n<div style=\"background-color:#eeeeee; padding:10px; text-align:left; border-radius:10px; margin-top:10px; margin-bottom:10px; \"><b>Note</b>: This notebook take approximately 1 hour to complete</div>\n\n[Neptune ML](https://docs.aws.amazon.com/neptune/latest/userguide/machine-learning.html#machine-learning-overview) is a feature of Amazon Neptune that enables users to automate the creation, management, and usage of Graph Neural Network (GNN) machine learning models within Amazon Neptune. Neptune ML is built using [Amazon SageMaker](https://aws.amazon.com/sagemaker/) and [Deep Graph Library](https://www.dgl.ai/) and provides a simple and easy to use mechanism to build/train/maintain these models and then use the predictive capabilities of these models within a Gremlin query to predict elements or property values in the graph. \n\nFor this notebook we are going to show how to perform a common machine learning task known as **link prediction**. Link prediction is a unsupervised machine learning task where a model built using nodes and edges in the graph to predict whether an edge exists between two particular nodes. Link prediction is not unique to GNN based models (look at DeepWalk or node2vec) but the GNN based models in Neptune ML provide additional context to the predictions by combining the connectivity and features of the local neighborhood of a node to create a more predictive model.\n\nLink prediction is commonly used to solve many common buisness problems such as:\n\n* Predicting group membership in a social or identity network\n* [Entity Resolution in an identity graph](https://github.com/awslabs/sagemaker-graph-entity-resolution/blob/master/source/sagemaker/dgl-entity-resolution.ipynb)\n* Knowledge graph completion\n* Product recommendation\n\nNeptune ML uses a four step process to automate the process of creating production ready GNN models:\n\n1. **Load Data** - Data is loaded into a Neptune cluster using any of the normal methods such as the Gremlin drivers or using the Neptune Bulk Loader.\n2. **Export Data** - A service call is made specifying the machine learning model type and model configuration parameters. The data and model configuration parameters are then exported from a Neptune cluster to an S3 bucket.\n3. **Model Training** - A set of service calls are made to pre-process the exported data, train the machine learning model, and then generate an Amazon SageMaker endpoint that exposes the model.\n4. **Run Queries** - The final step is to use this inference endpoint within our Gremlin queries to infer data using the machine learning model.\n\n",
"_____no_output_____"
],
[
"For this notebook we'll use the [MovieLens 100k dataset](https://grouplens.org/datasets/movielens/100k/) provided by [GroupLens Research](https://grouplens.org/datasets/movielens/). This dataset consists of movies, users, and ratings of those movies by users. \n\n\n\nFor this notebook we'll walk through how Neptune ML can predict product recommendations in a product knowledge graph. To demonstrate this we'll predict the movies a user would be most likely to rate as well as which users are most likely to rate a given movie. We'll walk through each step of loading and exporting the data, configuring and training the model, and finally we'll show how to use that model to infer the genre of movies using Gremlin traversals. ",
"_____no_output_____"
],
[
"## Checking that we are ready to run Neptune ML \nRun the code below to check that this cluster is configured to run Neptune ML.",
"_____no_output_____"
]
],
[
[
"import neptune_ml_utils as neptune_ml\nneptune_ml.check_ml_enabled()",
"_____no_output_____"
]
],
[
[
"If the check above did not say that this cluster is ready to run Neptune ML jobs then please check that the cluster meets all the pre-requisites defined [here](https://docs.aws.amazon.com/neptune/latest/userguide/machine-learning.html#machine-learning-overview).\n\n# Load the data\nThe first step in building a Neptune ML model is to load data into the Neptune cluster. Loading data for Neptune ML follows the standard process of ingesting data into Amazon Neptune, for this example we'll be using the Bulk Loader. \n\nWe have written a script that automates the process of downloading the data from the MovieLens websites and formatting it to load into Neptune. All you need to provide is an S3 bucket URI that is located in the same region as the cluster.\n\n<div style=\"background-color:#eeeeee; padding:10px; text-align:left; border-radius:10px; margin-top:10px; margin-bottom:10px; \"><b>Note</b>: This is the only step that requires any specific input from the user, all remaining cells will automatically propogate the required values.</div>",
"_____no_output_____"
]
],
[
[
"s3_bucket_uri=\"s3://<INSERT S3 BUCKET OR PATH>\"\n# remove trailing slashes\ns3_bucket_uri = s3_bucket_uri[:-1] if s3_bucket_uri.endswith('/') else s3_bucket_uri",
"_____no_output_____"
]
],
[
[
"Now that you have provided an S3 bucket, run the cell below which will download and format the MovieLens data into a format compatible with Neptune's bulk loader.",
"_____no_output_____"
]
],
[
[
"response = neptune_ml.prepare_movielens_data(s3_bucket_uri)",
"_____no_output_____"
]
],
[
[
"This process only takes a few minutes and once it has completed you can load the data using the `%load` command in the cell below.",
"_____no_output_____"
]
],
[
[
"%load -s {response} -f csv -p OVERSUBSCRIBE --run",
"_____no_output_____"
]
],
[
[
"## Check to make sure the data is loaded\n\nOnce the cell has completed, the data has been loaded into the cluster. We verify the data loaded correctly by running the traversals below to see the count of nodes by label: \n\n<div style=\"background-color:#eeeeee; padding:10px; text-align:left; border-radius:10px; margin-top:10px; margin-bottom:10px; \"><b>Note</b>: The numbers below assume no other data is in the cluster</div>",
"_____no_output_____"
]
],
[
[
"%%gremlin\ng.V().groupCount().by(label).unfold()",
"_____no_output_____"
]
],
[
[
"If our nodes loaded correctly then the output is:\n\n* 19 genres\n* 1682 movies\n* 100000 rating\n* 943 users\n\nTo check that our edges loaded correctly we check the edge counts:",
"_____no_output_____"
]
],
[
[
"%%gremlin\ng.E().groupCount().by(label).unfold()",
"_____no_output_____"
]
],
[
[
"If our edges loaded correctly then the output is:\n\n* 100000 about\n* 2893 included_in\n* 100000 rated\n* 100000 wrote\n\n\n## Preparing for export\n\nWith our data validated let's remove a few `rated` vertices so that we can build a model that predicts these missing connections. In a normal scenario, the data you would like to predict is most likely missing from the data being loaded so removing these values prior to building our machine learning model simulates that situation.\n\nSpecifically, let's remove the `rated` edgesfor `user_1`, to provide us with a few candidate vertices to run our link prediction tasks. Let's start by taking a look at what `rated` edges currently exist.",
"_____no_output_____"
]
],
[
[
"%%gremlin\n\ng.V('user_1').outE('rated')",
"_____no_output_____"
]
],
[
[
"Now let's remove these edges to simulate them missing from our data.",
"_____no_output_____"
]
],
[
[
"%%gremlin\ng.V('user_1').outE('rated').drop()",
"_____no_output_____"
]
],
[
[
"Checking our data again we see that the edges have now been removed.",
"_____no_output_____"
]
],
[
[
"%%gremlin\ng.V('user_1').outE('rated')",
"_____no_output_____"
]
],
[
[
"# Export the data and model configuration\n\n**Note:** Before exporting data ensure that Neptune Export has been configured as described here: [Neptune Export Service](https://docs.aws.amazon.com/neptune/latest/userguide/machine-learning-data-export-service.html#machine-learning-data-export-service-run-export)",
"_____no_output_____"
],
[
"With our product knowledge graph loaded we are ready to export the data and configuration which will be used to train the ML model. \n\nThe export process is triggered by calling to the [Neptune Export service endpoint](https://docs.aws.amazon.com/neptune/latest/userguide/machine-learning-data-export-service.html). This call contains a configuration object which specifies the type of machine learning model to build, in this example node classification, as well as any feature configurations required. \n\n<div style=\"background-color:#eeeeee; padding:10px; text-align:left; border-radius:10px; margin-top:10px; margin-bottom:10px; \"><b>Note</b>: The configuration used in this notebook specifies only a minimal set of configuration options meaning that our model's predictions are not as accurate as they could be. The parameters included in this configuration are one of a couple of sets of options available to the end user to tune the model and optimize the accuracy of the resulting predictions.</div>\n\nThe configuration options provided to the export service are broken into two main sections, selecting the target and configuring features. \n\n## Selecting the target\n\nIn the first section, selecting the target, we specify what type of machine learning task will be run. To run a link prediction mdoel do not specify any `targets` in the `additionalParams` value. Unlike node classification or node regression, link prediction can be used to predict any edge type that exists in the graph between any two vertices. Becasue of this, there is no need to define a target set of values.\n\n\n## Configuring features\nThe second section of the configuration, configuring features, is where we specify details about the types of data stored in our graph and how the machine learning model should interpret that data. In machine learning, each property is known as a feature and these features are used by the model to make predictions. \n\nIn machine learning, each property is known as a feature and these features are used by the model to make predictions. When data is exported from Neptune all properties of all vertices are included. Each property is treated as a separate feature for the ML model. Neptune ML does its best to infer the correct type of feature for a property, in many cases, the accuracy of the model can be improved by specifying information about the property used for a feature. By default Neptune ML puts features into one of two categories:\n\n* If the feature represents a numerical property (float, double, int) then it is treated as a `numerical` feature type. In this feature type data is represented as a continuous set of numbers. In our example, the `age` of a `user` would best be represented as a numerical feature as the age of a user is best represented as a continuous set of values.\n* All other property types are represented as `category` features. In this feature type, each unique value of data is represented as a unique value in the set of classifications used by the model. In our MovieLens example the `occupation` of a `user` would represent a good example of a `category` feature as we want to group users that all have the same job.\n\nIf all of the properties fit into these two feature types then no configuration changes are needed at the time of export. However, in many scenarios these defaults are not always the best choice. In these cases, additional configuration options should be specified to better define how the property should be represented as a feature. \n\nOne common feature that needs additional configuration is numerical data, and specifically properties of numerical data that represent chunks or groups of items instead of a continuous stream.\n\nLet's say that instead of wanting `age` to be represented as a set of continuous values we want to represent it as a set of discrete buckets of values (e.g. 18-25, 26-24, 35-44, etc.). In this scenario we want to specify some additional attributes of that feature to bucket this attribute into certain known sets. We achieve this by specifying this feature as a `numerical_bucket`. This feature type takes a range of expected values, as well as a number of buckets, and groups data into buckets during the training process.\n\nAnother common feature that needs additional attributes are text features such as names, titles, or descriptions. While Neptune ML will treat these as categorical features by default the reality of these features is that they will likely be unique for each node. For example, since the `title` property of a `movie` node does not fit into a category grouping our model would be better served by representing this type of feature as a `text_word2vec` feature. A `text_word2vec` feature uses techniques from natural language processing to create a vector of data that represents a string of text. \n\nIn our export example below we have specified that the `title` property of our `movie` should be exported and trained as a `text_word2vec` feature and that our `age` field should range from 0-100 and that data should be bucketed into 10 distinct groups. \n\n<div style=\"background-color:#eeeeee; padding:10px; text-align:left; border-radius:10px; margin-top:10px; margin-bottom:10px; \"><b>Important</b>: The example below is an example of a minimal amount of the features of the model configuration parameters and will not create the most accurate model possible. Additional options are available for tuning this configuration to produce an optimal model are described here: <a href=\"https://docs.aws.amazon.com/neptune/latest/userguide/machine-learning-data-export-parameters.html\">Neptune Export Process Parameters</a></div>\n\nRunning the cell below we set the export configuration and run the export process. Neptune export is capable of automatically creating a clone of the cluster by setting `cloneCluster=True` which takes about 20 minutes to complete and will incur additional costs while the cloned cluster is running. Exporting from the existing cluster takes about 5 minutes but requires that the `neptune_query_timeout` parameter in the [parameter group](https://docs.aws.amazon.com/neptune/latest/userguide/parameters.html) is set to a large enough value (>72000) to prevent timeout errors.",
"_____no_output_____"
]
],
[
[
"export_params={ \n\"command\": \"export-pg\", \n\"params\": { \"endpoint\": neptune_ml.get_host(),\n \"profile\": \"neptune_ml\",\n \"cloneCluster\": False\n }, \n\"outputS3Path\": f'{s3_bucket_uri}/neptune-export',\n\"additionalParams\": {\n \"neptune_ml\": {\n \"version\": \"v2.0\",\n \"features\": [\n {\n \"node\": \"movie\",\n \"property\": \"title\",\n \"type\": \"word2vec\"\n },\n {\n \"node\": \"user\",\n \"property\": \"age\",\n \"type\": \"bucket_numerical\",\n \"range\" : [1, 100],\n \"num_buckets\": 10\n }\n ]\n }\n },\n\"jobSize\": \"medium\"}",
"_____no_output_____"
],
[
"%%neptune_ml export start --export-url {neptune_ml.get_export_service_host()} --export-iam --wait --store-to export_results\n${export_params}",
"_____no_output_____"
]
],
[
[
"# ML data processing, model training, and endpoint creation\n\nOnce the export job is completed we are now ready to train our machine learning model and create the inference endpoint. Training our Neptune ML model requires three steps. \n \n<div style=\"background-color:#eeeeee; padding:10px; text-align:left; border-radius:10px; margin-top:10px; margin-bottom:10px; \"><b>Note</b>: The cells below only configure a minimal set of parameters required to run a model training.</div>\n\n## Data processing\nThe first step (data processing) processes the exported graph dataset using standard feature preprocessing techniques to prepare it for use by DGL. This step performs functions such as feature normalization for numeric data and encoding text features using word2vec. At the conclusion of this step the dataset is formatted for model training. \n\nThis step is implemented using a SageMaker Processing Job and data artifacts are stored in a pre-specified S3 location once the job is complete.\n\nAdditional options and configuration parameters for the data processing job can be found using the links below:\n\n* [Data Processing](https://docs.aws.amazon.com/neptune/latest/userguide/machine-learning-on-graphs-processing.html)\n* [dataprocessing command](https://docs.aws.amazon.com/neptune/latest/userguide/machine-learning-api-dataprocessing.html)\n\nRun the cells below to create the data processing configuration and to begin the processing job.",
"_____no_output_____"
]
],
[
[
"# The training_job_name can be set to a unique value below, otherwise one will be auto generated\ntraining_job_name=neptune_ml.get_training_job_name('link-prediction')\n\nprocessing_params = f\"\"\"\n--config-file-name training-data-configuration.json\n--job-id {training_job_name} \n--s3-input-uri {export_results['outputS3Uri']} \n--s3-processed-uri {str(s3_bucket_uri)}/preloading \"\"\"",
"_____no_output_____"
],
[
"%neptune_ml dataprocessing start --wait --store-to processing_results {processing_params}",
"_____no_output_____"
]
],
[
[
"## Model training\nThe second step (model training) trains the ML model that will be used for predictions. The model training is done in two stages. The first stage uses a SageMaker Processing job to generate a model training strategy. A model training strategy is a configuration set that specifies what type of model and model hyperparameter ranges will be used for the model training. Once the first stage is complete, the SageMaker Processing job launches a SageMaker Hyperparameter tuning job. The SageMaker Hyperparameter tuning job runs a pre-specified number of model training job trials on the processed data, and stores the model artifacts generated by the training in the output S3 location. Once all the training jobs are complete, the Hyperparameter tuning job also notes the training job that produced the best performing model.\n\nAdditional options and configuration parameters for the data processing job can be found using the links below:\n\n* [Model Training](https://docs.aws.amazon.com/neptune/latest/userguide/machine-learning-on-graphs-model-training.html)\n* [modeltraining command](https://docs.aws.amazon.com/neptune/latest/userguide/machine-learning-api-modeltraining.html)\n\n<div style=\"background-color:#eeeeee; padding:10px; text-align:left; border-radius:10px; margin-top:10px; margin-bottom:10px; \"><b>Information</b>: Link prediction is a more computationally complex model than classification or regression so training this model will take 2-3 hours</div>",
"_____no_output_____"
]
],
[
[
"training_params=f\"\"\"\n--job-id {training_job_name} \n--data-processing-id {training_job_name} \n--instance-type ml.p3.2xlarge\n--s3-output-uri {str(s3_bucket_uri)}/training\n--max-hpo-number 2\n--max-hpo-parallel 2 \"\"\"",
"_____no_output_____"
],
[
"%neptune_ml training start --wait --store-to training_results {training_params}",
"_____no_output_____"
]
],
[
[
"## Endpoint creation\nThe final step is to create the inference endpoint which is an Amazon SageMaker endpoint instance that is launched with the model artifacts produced by the best training job. This endpoint will be used by our graph queries to return the model predictions for the inputs in the request. The endpoint once created stays active until it is manually deleted. Each model is tied to a single endpoint.\n\nAdditional options and configuration parameters for the data processing job can be found using the links below:\n\n* [Inference Endpoint](https://docs.aws.amazon.com/neptune/latest/userguide/machine-learning-on-graphs-inference-endpoint.html)\n* [Endpoint command](https://docs.aws.amazon.com/neptune/latest/userguide/machine-learning-api-endpoints.html)\n\n<div style=\"background-color:#eeeeee; padding:10px; text-align:left; border-radius:10px; margin-top:10px; margin-bottom:10px; \"><b>Information</b>: The endpoint creation process takes ~5-10 minutes</div>",
"_____no_output_____"
]
],
[
[
"endpoint_params=f\"\"\"\n--id {training_job_name}\n--model-training-job-id {training_job_name}\"\"\"",
"_____no_output_____"
],
[
"%neptune_ml endpoint create --wait --store-to endpoint_results {endpoint_params}",
"_____no_output_____"
]
],
[
[
"Once this has completed we get the endpoint name for our newly created inference endpoint. The cell below will set the endpoint name which will be used in the Gremlin queries below. ",
"_____no_output_____"
]
],
[
[
"endpoint=endpoint_results['endpoint']['name']",
"_____no_output_____"
]
],
[
[
"# Querying using Gremlin\n\nNow that we have our inference endpoint setup let's query our product knowledge graph to show how to predict how likely it is that a user will rate a movie. The need to predict the likelyhood of connections in a product knowledge graph is commonly used to provide recommendations for products that a customer might purchase.\n\nUnlike node classification and node regression, link prediction can infer any of the edge labels that existed in our graph when the model was created. In our model this means we could infer the probability that a `wrote`, `about`, `rated`, or `included_in` edge exists between any two vertices. However for this example we are going to focus on inferring the `rated` edges between the `user` and `movie` vertices. \n\n## Predicting what movies a user will rate\n\nBefore we predict what movies `user_1` is most likely to rate let's verify that our graph does not contain any `rated` edges for `user_1`.\n",
"_____no_output_____"
]
],
[
[
"%%gremlin\ng.V('user_1').out('rated').hasLabel('movie').valueMap()",
"_____no_output_____"
]
],
[
[
"As expected, their are not any `rated` edges for `user_1`. Maybe `user_1` is a new user in our system and we want to provide them some product recommendations. Let's modify the query to predict what movies `user_1` is most likely to rate. \n\nFirst, we add the `with()` step to specify the inference endpoint we want to use with our Gremlin query like this\n`g.with(\"Neptune#ml.endpoint\",\"<INSERT ENDPOINT NAME>\")`. \n\n<div style=\"background-color:#eeeeee; padding:10px; text-align:left; border-radius:10px; margin-top:10px; margin-bottom:10px; \"><b>Note</b>: The endpoint values are automatically passed into the queries below</div>\n\nSecond, when we ask for the link within our query we use the `out()` step to predict the target node or the `in()` step to predict the source node. For each of these steps we need to specify the type of model being used with a with() step (`with(\"Neptune#ml.prediction\")`).\n\nPutting these items together we get the query below, which returns the movies that` user_1` is likely to rate.",
"_____no_output_____"
]
],
[
[
"%%gremlin\ng.with(\"Neptune#ml.endpoint\",\"${endpoint}\").\n V('user_1').out('rated').with(\"Neptune#ml.prediction\").hasLabel('movie').valueMap('title')",
"_____no_output_____"
]
],
[
[
"Great, we can now see that we are predicted edges showing that `Sleepers` is the movie that `user_1` is most likely to rate. In the example above we predicted the target node but we can also use the same mechanism to predict the source node. \n\nLet's turn that question around and say that we had a product and we wanted to find the people most likely to rate this product.\n\n## Predicting the top 10 users most likely to rate a movie\nTo accomplish this we would want to start at the movie vertex and predict the rated edge back to the user. Since we want to return the top 10 recommended users we need to use the `.with(\"Neptune#ml.limit\",10)` configuration option. Combining these together we get the query below which finds the top 10 users most likely to rate `Apollo 13`.",
"_____no_output_____"
]
],
[
[
"%%gremlin\ng.with(\"Neptune#ml.endpoint\",\"${endpoint}\").\n with(\"Neptune#ml.limit\",10).\n V().has('title', 'Apollo 13 (1995)').\n in('rated').with(\"Neptune#ml.prediction\").hasLabel('user').id()",
"_____no_output_____"
]
],
[
[
"With that we have sucessfully been able to show how you can use link prediction to predict edges starting at either end.",
"_____no_output_____"
],
[
"From the examples we have shown here you can begin to see how the ability to infer unknown connections within a graph starts to enable many interesting and unique use cases within Amazon Neptune. ",
"_____no_output_____"
],
[
"# Cleaning Up \nNow that you have completed this walkthrough you have created a Sagemaker endpoint which is currently running and will incur the standard charges. If you are done trying out Neptune ML and would like to avoid these recurring costs, run the cell below to delete the inference endpoint.",
"_____no_output_____"
]
],
[
[
"neptune_ml.delete_endpoint(training_job_name)",
"_____no_output_____"
]
],
[
[
"In addition to the inference endpoint the CloudFormation script that you used has setup several additional resources. If you are finished then we suggest you delete the CloudFormation stack to avoid any recurring charges. For instructions, see Deleting a Stack on the [Deleting a Stack on the Amazon Web Services CloudFormation Console](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-delete-stack.html). Be sure to delete the root stack (the stack you created earlier). Deleting the root stack deletes any nested stacks.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e77a0b8749fbdb6fc602ac50a6d55d8afd4342a7 | 192,402 | ipynb | Jupyter Notebook | 3_moo/2_NSGAII.ipynb | benstyle11/evolution | 8ded697dc3e34b785471a66b7438e78ceec7da83 | [
"Apache-2.0"
] | null | null | null | 3_moo/2_NSGAII.ipynb | benstyle11/evolution | 8ded697dc3e34b785471a66b7438e78ceec7da83 | [
"Apache-2.0"
] | null | null | null | 3_moo/2_NSGAII.ipynb | benstyle11/evolution | 8ded697dc3e34b785471a66b7438e78ceec7da83 | [
"Apache-2.0"
] | null | null | null | 77.706785 | 497 | 0.582276 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
e77a17c5d5de6e48810ae13a736ae23c716407cb | 7,685 | ipynb | Jupyter Notebook | docs/src/notebooks/1_pubmed_search_and_save.ipynb | UnofficialJuliaMirrorSnapshots/BioMedQuery.jl-e96904bf-1073-5077-9b57-b0ce0ff5555a | 427d5144852cff0cc1394ab8c3ffe8770bda0632 | [
"MIT"
] | 10 | 2016-07-16T20:05:25.000Z | 2019-11-27T06:41:32.000Z | docs/src/notebooks/1_pubmed_search_and_save.ipynb | UnofficialJuliaMirrorSnapshots/BioMedQuery.jl-e96904bf-1073-5077-9b57-b0ce0ff5555a | 427d5144852cff0cc1394ab8c3ffe8770bda0632 | [
"MIT"
] | 58 | 2016-09-13T16:21:30.000Z | 2020-04-19T16:41:02.000Z | docs/src/notebooks/1_pubmed_search_and_save.ipynb | UnofficialJuliaMirrorSnapshots/BioMedQuery.jl-e96904bf-1073-5077-9b57-b0ce0ff5555a | 427d5144852cff0cc1394ab8c3ffe8770bda0632 | [
"MIT"
] | 16 | 2016-08-10T06:37:14.000Z | 2020-02-08T11:22:53.000Z | 20.940054 | 129 | 0.534548 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
e77a289f3bf68559ce04e442fc04b201390f0e33 | 250,976 | ipynb | Jupyter Notebook | Alura/imersaoDados02/aula 2/ImersaoDados02Aula02.ipynb | W8jonas/estudos | b8f07bfd1890d94ff74c77adba1e033b4f0edd54 | [
"MIT"
] | 11 | 2021-01-26T03:13:16.000Z | 2021-08-14T01:28:07.000Z | Alura/imersaoDados02/aula 2/ImersaoDados02Aula02.ipynb | W8jonas/estudos | b8f07bfd1890d94ff74c77adba1e033b4f0edd54 | [
"MIT"
] | 4 | 2021-01-26T07:27:37.000Z | 2021-01-26T07:31:18.000Z | Alura/imersaoDados02/aula 2/ImersaoDados02Aula02.ipynb | W8jonas/estudos | b8f07bfd1890d94ff74c77adba1e033b4f0edd54 | [
"MIT"
] | null | null | null | 128.837782 | 52,382 | 0.78576 | [
[
[
"import pandas as pd\n\nfonte = \"https://github.com/alura-cursos/imersao-dados-2-2020/blob/master/MICRODADOS_ENEM_2019_SAMPLE_43278.csv?raw=true\"\n\n# Lendo banco de dados do ENEM 2019 (Amostra)\ndados = pd.read_csv(fonte)\ndados.shape",
"_____no_output_____"
],
[
"dados.head()",
"_____no_output_____"
],
[
"dados.columns.values",
"_____no_output_____"
],
[
"# Mostrando a 10 primeiras idades e seus totais de participantes em ordem crescente\ndados[ \"NU_IDADE\"].value_counts().sort_index().head(10)",
"_____no_output_____"
]
],
[
[
"Desafio01: Encontrar os valores relativos para as idades dos incritos\n\nDesafio02: Descobrir de quais estados são os inscritos com 13 anos.",
"_____no_output_____"
],
[
"Desafio03: Colocar título no gráfico",
"_____no_output_____"
]
],
[
[
"# Mostrando histograma das idades dos participantes\ndados[ \"NU_IDADE\"].hist(bins = 50, figsize = (16, 7))",
"_____no_output_____"
],
[
"# Fazendo query no bando de dados para pegar somente observacoes de treineiros, depois mostrando o total das idades em ordem crescente\ndados.query(\"IN_TREINEIRO == 1\")[\"NU_IDADE\"].value_counts().sort_index().head(5)",
"_____no_output_____"
]
],
[
[
"Desafio04: Plotar os histogramas das idades dos treineiros e não treineiros",
"_____no_output_____"
]
],
[
[
"# Plotando histograma das notas da redacao\ndados[\"NU_NOTA_REDACAO\"].hist(bins = 50, figsize=(19, 7))",
"_____no_output_____"
],
[
"# Plotando histograma das notas da prova de Ciências Humanas\ndados[\"NU_NOTA_CH\"].hist(bins = 50, figsize=(19, 7))",
"_____no_output_____"
],
[
"# Fazendo query no bando de dados para pegar somente observacoes do Estado de Minas\n# Depois separando somente as notas das provas \n# Por fim mostrando dados estatísticos\n\nprovas = [\"NU_NOTA_LC\", \"NU_NOTA_CH\", \"NU_NOTA_MT\", \"NU_NOTA_CN\", \"NU_NOTA_REDACAO\"]\ndados.query(\"SG_UF_RESIDENCIA == 'MG'\")[provas].describe()",
"_____no_output_____"
],
[
"# Fazendo query no bando de dados para pegar somente observacoes do Estado de Minas\n# Depois separando somente as notas das provas \n# Por fim plotando grafico boxplot contendo as notas das provas\n\nprovas = [\"NU_NOTA_LC\", \"NU_NOTA_CH\", \"NU_NOTA_MT\", \"NU_NOTA_CN\", \"NU_NOTA_REDACAO\"]\ndados.query(\"SG_UF_RESIDENCIA == 'MG'\")[provas].boxplot(grid = 1, figsize=(18,8))",
"_____no_output_____"
]
],
[
[
"Desafio05: Comparar as distribuições das provas em inglês e espanhol nas provas de LC",
"_____no_output_____"
]
],
[
[
"\n#Resolvendo desafio 01\n\ndados.query(\"NU_IDADE <= 14\")[\"SG_UF_RESIDENCIA\"].value_counts(normalize=True)",
"_____no_output_____"
],
[
"renda_ordenada = dados[\"Q006\"].unique()\nrenda_ordenada.sort()\nprint(renda_ordenada)\n",
"['A' 'B' 'C' 'D' 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' 'P' 'Q']\n"
],
[
"import seaborn as sns\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(18, 8))\nsns.boxplot(x=\"Q006\", y = \"NU_NOTA_REDACAO\", data = dados, order = renda_ordenada)\nplt.title(\"Boxplot das notas de matemática pela renda\")",
"_____no_output_____"
],
[
"total_notas_por_aluno = dados[provas].sum(axis=1)\ndados[\"NU_NOTA_TOTAL\"] = total_notas_por_aluno\ndados.head()",
"_____no_output_____"
],
[
"plt.figure(figsize=(18, 8))\ndados_sem_zeros = dados.query(\"NU_NOTA_TOTAL != 0\")\nsns.boxplot(x=\"Q006\", y = \"NU_NOTA_TOTAL\", data = dados_sem_zeros, order = renda_ordenada)\nplt.title(\"Boxplot das notas todais pela renda\")",
"_____no_output_____"
],
[
"sns.displot(dados, x = \"NU_NOTA_TOTAL\")",
"_____no_output_____"
],
[
"plt.figure(figsize=(18, 8))\nsns.boxplot(x=\"Q006\", y = \"NU_NOTA_TOTAL\", data = dados_sem_zeros, order = renda_ordenada, hue= \"IN_TREINEIRO\")\nplt.title(\"Boxplot das notas todais pela renda\")",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e77a2b1ad68028a8e127ce3c2442d43f60c9d2be | 24,316 | ipynb | Jupyter Notebook | notebooks/nessie-iceberg-flink-demo-nba.ipynb | sandhyasun/nessie-demos | 40e4926d17fcec9a25bac105ab7dcc015b052cb9 | [
"Apache-2.0"
] | 5 | 2021-05-20T10:54:26.000Z | 2022-03-26T21:28:23.000Z | notebooks/nessie-iceberg-flink-demo-nba.ipynb | sandhyasun/nessie-demos | 40e4926d17fcec9a25bac105ab7dcc015b052cb9 | [
"Apache-2.0"
] | 153 | 2021-05-07T12:38:16.000Z | 2022-03-25T11:38:41.000Z | notebooks/nessie-iceberg-flink-demo-nba.ipynb | AlexRogalskiy/nessie-demos | ca1db554e0df055a533ee7fa0828e9a082886717 | [
"Apache-2.0"
] | 11 | 2021-05-11T12:49:33.000Z | 2022-03-16T04:58:21.000Z | 33.585635 | 308 | 0.576164 | [
[
[
"Nessie Iceberg/Flink SQL Demo with NBA Dataset\n============================\nThis demo showcases how to use Nessie Python API along with Flink from Iceberg\n\nInitialize PyFlink\n----------------------------------------------\nTo get started, we will first have to do a few setup steps that give us everything we need\nto get started with Nessie. In case you're interested in the detailed setup steps for Flink, you can check out the [docs](https://projectnessie.org/tools/flink/)\n\nThe Binder server has downloaded flink and some data for us as well as started a Nessie server in the background. All we have to do is start Flink\n\nThe below cell starts a local Flink session with parameters needed to configure Nessie. Each config option is followed by a comment explaining its purpose.\n",
"_____no_output_____"
]
],
[
[
"import os\nfrom pyflink.datastream import StreamExecutionEnvironment\nfrom pyflink.table import StreamTableEnvironment\nfrom pyflink.table.expressions import lit\nfrom pynessie import init\n\n# where we will store our data\nwarehouse = os.path.join(os.getcwd(), \"flink-warehouse\")\n# this was downloaded when Binder started, its available on maven central\niceberg_flink_runtime_jar = os.path.join(os.getcwd(), \"../iceberg-flink-runtime-0.12.0.jar\")\n\nenv = StreamExecutionEnvironment.get_execution_environment()\nenv.add_jars(\"file://{}\".format(iceberg_flink_runtime_jar))\ntable_env = StreamTableEnvironment.create(env)\n\nnessie_client = init()\n\ndef create_ref_catalog(ref):\n \"\"\"\n Create a flink catalog that is tied to a specific ref.\n\n In order to create the catalog we have to first create the branch\n \"\"\"\n hash_ = nessie_client.get_reference(nessie_client.get_default_branch()).hash_\n try:\n nessie_client.create_branch(ref, hash_)\n except:\n pass # already created\n # The important args below are:\n # type: tell Flink to use Iceberg as the catalog\n # catalog-impl: which Iceberg catalog to use, in this case we want Nessie\n # uri: the location of the nessie server.\n # ref: the Nessie ref/branch we want to use (defaults to main)\n # warehouse: the location this catalog should store its data\n table_env.execute_sql(\n f\"\"\"CREATE CATALOG {ref}_catalog WITH (\n 'type'='iceberg',\n 'catalog-impl'='org.apache.iceberg.nessie.NessieCatalog',\n 'uri'='http://localhost:19120/api/v1',\n 'ref'='{ref}',\n 'warehouse' = '{warehouse}')\"\"\"\n )\ncreate_ref_catalog(nessie_client.get_default_branch())\nprint(\"\\n\\n\\nFlink running\\n\\n\\n\")",
"_____no_output_____"
]
],
[
[
"Solving Data Engineering problems with Nessie\n============================\n\nIn this Demo we are a data engineer working at a fictional sports analytics blog. In order for the authors to write articles they have to have access to the relevant data. They need to be able to retrieve data quickly and be able to create charts with it.\n\nWe have been asked to collect and expose some information about basketball players. We have located some data sources and are now ready to start ingesting data into our data lakehouse. We will perform the ingestion steps on a Nessie branch to test and validate the data before exposing to the analysts.",
"_____no_output_____"
],
[
"Set up Nessie branches (via Nessie CLI)\n----------------------------\nOnce all dependencies are configured, we can get started with ingesting our basketball data into `Nessie` with the following steps:\n\n- Create a new branch named `dev`\n- List all branches\n\nIt is worth mentioning that we don't have to explicitly create a `main` branch, since it's the default branch.",
"_____no_output_____"
]
],
[
[
"create_ref_catalog(\"dev\")",
"_____no_output_____"
]
],
[
[
"We have created the branch `dev` and we can see the branch with the Nessie `hash` its currently pointing to.\n\nBelow we list all branches. Note that the auto created `main` branch already exists and both branches point at the same `hash`",
"_____no_output_____"
]
],
[
[
"!nessie --verbose branch",
"_____no_output_____"
]
],
[
[
"Create tables under dev branch\n-------------------------------------\nOnce we created the `dev` branch and verified that it exists, we can create some tables and add some data.\n\nWe create two tables under the `dev` branch:\n- `salaries`\n- `totals_stats`\n\nThese tables list the salaries per player per year and their stats per year.\n\nTo create the data we:\n\n1. switch our branch context to dev\n2. create the table\n3. insert the data from an existing csv file. This csv file is already stored locally on the demo machine. A production use case would likely take feeds from official data sources\n",
"_____no_output_____"
]
],
[
[
"# Load the dataset\nfrom pyflink.table import DataTypes\nfrom pyflink.table.descriptors import Schema, OldCsv, FileSystem\n\n# Creating `salaries` table\n(table_env.connect(FileSystem().path('../datasets/nba/salaries.csv'))\n .with_format(OldCsv()\n .field('Season', DataTypes.STRING()).field(\"Team\", DataTypes.STRING())\n .field(\"Salary\", DataTypes.STRING()).field(\"Player\", DataTypes.STRING()))\n .with_schema(Schema()\n .field('Season', DataTypes.STRING()).field(\"Team\", DataTypes.STRING())\n .field(\"Salary\", DataTypes.STRING()).field(\"Player\", DataTypes.STRING()))\n .create_temporary_table('dev_catalog.nba.salaries_temp'))\n\ntable_env.execute_sql(\"\"\"CREATE TABLE IF NOT EXISTS dev_catalog.nba.salaries\n (Season STRING, Team STRING, Salary STRING, Player STRING)\"\"\").wait()\n\ntab = table_env.from_path('dev_catalog.nba.salaries_temp')\ntab.execute_insert('dev_catalog.nba.salaries').wait()\n\n# Creating `totals_stats` table\n(table_env.connect(FileSystem().path('../datasets/nba/totals_stats.csv'))\n .with_format(OldCsv()\n .field('Season', DataTypes.STRING()).field(\"Age\", DataTypes.STRING()).field(\"Team\", DataTypes.STRING())\n .field(\"ORB\", DataTypes.STRING()).field(\"DRB\", DataTypes.STRING()).field(\"TRB\", DataTypes.STRING())\n .field(\"AST\", DataTypes.STRING()).field(\"STL\", DataTypes.STRING()).field(\"BLK\", DataTypes.STRING())\n .field(\"TOV\", DataTypes.STRING()).field(\"PTS\", DataTypes.STRING()).field(\"Player\", DataTypes.STRING())\n .field(\"RSorPO\", DataTypes.STRING()))\n .with_schema(Schema()\n .field('Season', DataTypes.STRING()).field(\"Age\", DataTypes.STRING()).field(\"Team\", DataTypes.STRING())\n .field(\"ORB\", DataTypes.STRING()).field(\"DRB\", DataTypes.STRING()).field(\"TRB\", DataTypes.STRING())\n .field(\"AST\", DataTypes.STRING()).field(\"STL\", DataTypes.STRING()).field(\"BLK\", DataTypes.STRING())\n .field(\"TOV\", DataTypes.STRING()).field(\"PTS\", DataTypes.STRING()).field(\"Player\", DataTypes.STRING())\n .field(\"RSorPO\", DataTypes.STRING()))\n .create_temporary_table('dev_catalog.nba.totals_stats_temp'))\n\ntable_env.execute_sql(\n \"\"\"CREATE TABLE IF NOT EXISTS dev_catalog.nba.totals_stats (Season STRING, Age STRING, Team STRING,\n ORB STRING, DRB STRING, TRB STRING, AST STRING, STL STRING, BLK STRING, TOV STRING, PTS STRING,\n Player STRING, RSorPO STRING)\"\"\").wait()\n\ntab = table_env.from_path('dev_catalog.nba.totals_stats_temp')\ntab.execute_insert('dev_catalog.nba.totals_stats').wait()\n\nsalaries = table_env.from_path('main_catalog.nba.`salaries@dev`').select(lit(1).count).to_pandas().values[0][0]\ntotals_stats = table_env.from_path('main_catalog.nba.`totals_stats@dev`').select(lit(1).count).to_pandas().values[0][0]\nprint(f\"\\n\\n\\nAdded {salaries} rows to the salaries table and {totals_stats} rows to the total_stats table.\\n\\n\\n\")",
"_____no_output_____"
]
],
[
[
"Now we count the rows in our tables to ensure they are the same number as the csv files. Note we use the `table@branch` notation which overrides the context set by the catalog.",
"_____no_output_____"
]
],
[
[
"table_count = table_env.from_path('dev_catalog.nba.`salaries@dev`').select('Season.count').to_pandas().values[0][0]\ncsv_count = table_env.from_path('dev_catalog.nba.salaries_temp').select('Season.count').to_pandas().values[0][0]\nassert table_count == csv_count\nprint(table_count)\n\ntable_count = table_env.from_path('dev_catalog.nba.`totals_stats@dev`').select('Season.count').to_pandas().values[0][0]\ncsv_count = table_env.from_path('dev_catalog.nba.totals_stats_temp').select('Season.count').to_pandas().values[0][0]\nassert table_count == csv_count\nprint(table_count)",
"_____no_output_____"
]
],
[
[
"Check generated tables\n----------------------------\nSince we have been working solely on the `dev` branch, where we created 2 tables and added some data,\nlet's verify that the `main` branch was not altered by our changes.",
"_____no_output_____"
]
],
[
[
"!nessie contents --list",
"_____no_output_____"
]
],
[
[
"And on the `dev` branch we expect to see two tables",
"_____no_output_____"
]
],
[
[
"!nessie contents --list --ref dev",
"_____no_output_____"
]
],
[
[
"We can also verify that the `dev` and `main` branches point to different commits",
"_____no_output_____"
]
],
[
[
"!nessie --verbose branch",
"_____no_output_____"
]
],
[
[
"Dev promotion into main\n-----------------------\nOnce we are done with our changes on the `dev` branch, we would like to merge those changes into `main`.\nWe merge `dev` into `main` via the command line `merge` command.\nBoth branches should be at the same revision after merging/promotion.",
"_____no_output_____"
]
],
[
[
"!nessie merge dev -b main --force",
"_____no_output_____"
]
],
[
[
"We can verify the branches are at the same hash and that the `main` branch now contains the expected tables and row counts.\n\nThe tables are now on `main` and ready for consumtion by our blog authors and analysts!",
"_____no_output_____"
]
],
[
[
"!nessie --verbose branch",
"_____no_output_____"
],
[
"!nessie contents --list",
"_____no_output_____"
],
[
"table_count = table_env.from_path('main_catalog.nba.salaries').select('Season.count').to_pandas().values[0][0]\ncsv_count = table_env.from_path('dev_catalog.nba.salaries_temp').select('Season.count').to_pandas().values[0][0]\nassert table_count == csv_count\n\ntable_count = table_env.from_path('main_catalog.nba.totals_stats').select('Season.count').to_pandas().values[0][0]\ncsv_count = table_env.from_path('dev_catalog.nba.totals_stats_temp').select('Season.count').to_pandas().values[0][0]\nassert table_count == csv_count",
"_____no_output_____"
]
],
[
[
"Perform regular ETL on the new tables\n-------------------\nOur analysts are happy with the data and we want to now regularly ingest data to keep things up to date. Our first ETL job consists of the following:\n\n1. Update the salaries table to add new data\n2. We have decided the `Age` column isn't required in the `total_stats` table so we will drop the column\n3. We create a new table to hold information about the players appearances in all star games\n\nAs always we will do this work on a branch and verify the results. This ETL job can then be set up to run nightly with new stats and salary information.",
"_____no_output_____"
]
],
[
[
"create_ref_catalog(\"etl\")",
"_____no_output_____"
],
[
"# add some salaries for Kevin Durant\ntable_env.execute_sql(\"\"\"INSERT INTO etl_catalog.nba.salaries\n VALUES ('2017-18', 'Golden State Warriors', '$25000000', 'Kevin Durant'),\n ('2018-19', 'Golden State Warriors', '$30000000', 'Kevin Durant'),\n ('2019-20', 'Brooklyn Nets', '$37199000', 'Kevin Durant'),\n ('2020-21', 'Brooklyn Nets', '$39058950', 'Kevin Durant')\"\"\").wait()",
"_____no_output_____"
],
[
"# Rename the table `totals_stats` to `new_total_stats`\ntable_env.execute_sql(\"ALTER TABLE etl_catalog.nba.totals_stats RENAME TO etl_catalog.nba.new_total_stats\").wait()",
"_____no_output_____"
],
[
"# Creating `allstar_games_stats` table\n(table_env.connect(FileSystem().path('../datasets/nba/allstar_games_stats.csv'))\n .with_format(OldCsv()\n .field('Season', DataTypes.STRING()).field(\"Age\", DataTypes.STRING()).field(\"Team\", DataTypes.STRING())\n .field(\"ORB\", DataTypes.STRING()).field(\"TRB\", DataTypes.STRING()).field(\"AST\", DataTypes.STRING())\n .field(\"STL\", DataTypes.STRING()).field(\"BLK\", DataTypes.STRING()).field(\"TOV\", DataTypes.STRING())\n .field(\"PF\", DataTypes.STRING()).field(\"PTS\", DataTypes.STRING()).field(\"Player\", DataTypes.STRING()))\n .with_schema(Schema()\n .field('Season', DataTypes.STRING()).field(\"Age\", DataTypes.STRING()).field(\"Team\", DataTypes.STRING())\n .field(\"ORB\", DataTypes.STRING()).field(\"TRB\", DataTypes.STRING()).field(\"AST\", DataTypes.STRING())\n .field(\"STL\", DataTypes.STRING()).field(\"BLK\", DataTypes.STRING()).field(\"TOV\", DataTypes.STRING())\n .field(\"PF\", DataTypes.STRING()).field(\"PTS\", DataTypes.STRING()).field(\"Player\", DataTypes.STRING()))\n .create_temporary_table('etl_catalog.nba.allstar_games_stats_temp'))\n\ntable_env.execute_sql(\n \"\"\"CREATE TABLE IF NOT EXISTS etl_catalog.nba.allstar_games_stats (Season STRING, Age STRING,\n Team STRING, ORB STRING, TRB STRING, AST STRING, STL STRING, BLK STRING, TOV STRING,\n PF STRING, PTS STRING, Player STRING)\"\"\").wait()\n\ntab = table_env.from_path('etl_catalog.nba.allstar_games_stats_temp')\ntab.execute_insert('etl_catalog.nba.allstar_games_stats').wait()\n\n# Notice how we view the data on the etl branch via @etl\ntable_env.from_path('etl_catalog.nba.`allstar_games_stats@etl`').to_pandas()",
"_____no_output_____"
]
],
[
[
"We can verify that the new table isn't on the `main` branch but is present on the etl branch",
"_____no_output_____"
]
],
[
[
"# Since we have been working on the `etl` branch, the `allstar_games_stats` table is not on the `main` branch\n!nessie contents --list",
"_____no_output_____"
],
[
"# We should see `allstar_games_stats` and the `new_total_stats` on the `etl` branch\n!nessie contents --list --ref etl",
"_____no_output_____"
]
],
[
[
"Now that we are happy with the data we can again merge it into `main`",
"_____no_output_____"
]
],
[
[
"!nessie merge etl -b main --force",
"_____no_output_____"
]
],
[
[
"Now lets verify that the changes exist on the `main` branch and that the `main` and `etl` branches have the same `hash`",
"_____no_output_____"
]
],
[
[
"!nessie contents --list",
"_____no_output_____"
],
[
"!nessie --verbose branch",
"_____no_output_____"
],
[
"table_count = table_env.from_path('main_catalog.nba.allstar_games_stats').select('Season.count').to_pandas().values[0][0]\ncsv_count = table_env.from_path('etl_catalog.nba.allstar_games_stats_temp').select('Season.count').to_pandas().values[0][0]\nassert table_count == csv_count",
"_____no_output_____"
]
],
[
[
"Create `experiment` branch\n--------------------------------\nAs a data analyst we might want to carry out some experiments with some data, without affecting `main` in any way.\nAs in the previous examples, we can just get started by creating an `experiment` branch off of `main`\nand carry out our experiment, which could consist of the following steps:\n- drop `totals_stats` table\n- add data to `salaries` table\n- compare `experiment` and `main` tables",
"_____no_output_____"
]
],
[
[
"create_ref_catalog(\"experiment\")",
"_____no_output_____"
],
[
"# Drop the `totals_stats` table on the `experiment` branch\ntable_env.execute_sql(\"DROP TABLE IF EXISTS experiment_catalog.nba.new_total_stats\")",
"_____no_output_____"
],
[
"# add some salaries for Dirk Nowitzki\ntable_env.execute_sql(\"\"\"INSERT INTO experiment_catalog.nba.salaries VALUES\n ('2015-16', 'Dallas Mavericks', '$8333333', 'Dirk Nowitzki'),\n ('2016-17', 'Dallas Mavericks', '$25000000', 'Dirk Nowitzki'),\n ('2017-18', 'Dallas Mavericks', '$5000000', 'Dirk Nowitzki'),\n ('2018-19', 'Dallas Mavericks', '$5000000', 'Dirk Nowitzki')\"\"\").wait()",
"_____no_output_____"
],
[
"# We should see the `salaries` and `allstar_games_stats` tables only (since we just dropped `new_total_stats`)\n!nessie contents --list --ref experiment",
"_____no_output_____"
],
[
"# `main` hasn't changed been changed and still has the `new_total_stats` table\n!nessie contents --list",
"_____no_output_____"
]
],
[
[
"Let's take a look at the contents of the `salaries` table on the `experiment` branch.\nNotice the use of the `nessie` catalog and the use of `@experiment` to view data on the `experiment` branch",
"_____no_output_____"
]
],
[
[
"table_env.from_path('main_catalog.nba.`salaries@experiment`').select(lit(1).count).to_pandas()",
"_____no_output_____"
]
],
[
[
"and compare to the contents of the `salaries` table on the `main` branch. Notice that we didn't have to specify `@branchName` as it defaulted\nto the `main` branch",
"_____no_output_____"
]
],
[
[
"table_env.from_path('main_catalog.nba.`salaries@main`').select(lit(1).count).to_pandas()\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e77a2fb47784b4a2c69028984da93041a7f91dfc | 68,950 | ipynb | Jupyter Notebook | reuter_LSTM.ipynb | tecktonik08/test_deeplearning | 30edbb642ba0eb8688fc5af3a3c63c71b4045e4f | [
"Apache-2.0"
] | null | null | null | reuter_LSTM.ipynb | tecktonik08/test_deeplearning | 30edbb642ba0eb8688fc5af3a3c63c71b4045e4f | [
"Apache-2.0"
] | null | null | null | reuter_LSTM.ipynb | tecktonik08/test_deeplearning | 30edbb642ba0eb8688fc5af3a3c63c71b4045e4f | [
"Apache-2.0"
] | null | null | null | 68.402778 | 13,202 | 0.608006 | [
[
[
"import tensorflow as tf",
"_____no_output_____"
],
[
"(x_train, y_train), (x_test, y_test) = tf.keras.datasets.reuters.load_data(num_words=10000)\nx_train.shape, y_train.shape, x_test.shape, y_test.shape",
"Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/reuters.npz\n2113536/2110848 [==============================] - 0s 0us/step\n"
],
[
"print(y_train[50], x_train[50])",
"4 [1, 1479, 1197, 71, 8, 25, 1479, 1197, 640, 71, 304, 471, 80, 9, 1379, 1901, 4530, 6797, 79, 5, 8144, 71, 175, 80, 58, 4, 1279, 5, 63, 32, 20, 5, 4, 326, 175, 80, 335, 7, 10, 845, 31, 4, 221, 9, 108, 259, 1479, 1197, 640, 8, 16, 600, 69, 68, 11, 15, 6, 8144, 21, 397, 321, 6, 438, 1761, 3072, 79, 5, 8144, 1040, 894, 1051, 617, 80, 4, 617, 80, 23, 1051, 172, 3814, 3206, 8144, 175, 79, 9, 1379, 6, 264, 395, 3814, 3206, 79, 1479, 1197, 9, 25, 323, 8, 4, 8144, 80, 23, 381, 43, 42, 205, 50, 77, 33, 909, 9, 3509, 22, 216, 6, 216, 17, 12]\n"
],
[
"len(x_train[50]), len(x_train[400])",
"_____no_output_____"
],
[
"pad_x_train = tf.keras.preprocessing.sequence.pad_sequences(x_train, maxlen=500)\nlen(pad_x_train[50])",
"_____no_output_____"
],
[
"import numpy as np\nnp.unique(y_train)",
"_____no_output_____"
]
],
[
[
"# Make model",
"_____no_output_____"
]
],
[
[
"model = tf.keras.models.Sequential()",
"_____no_output_____"
],
[
"model.add(tf.keras.layers.Embedding(input_length=500, input_dim=10000, output_dim=24)) # input layer\nmodel.add(tf.keras.layers.LSTM(24, return_sequences=True, activation='tanh')) # LSTM을 하나 더 쓸 때\nmodel.add(tf.keras.layers.LSTM(12, activation='tanh'))\n# model.add(tf.keras.layers.Flatten()) # hidden layer\nmodel.add(tf.keras.layers.Dense(46, activation='softmax')) # output layer\n\nmodel.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['acc']) # gadget",
"_____no_output_____"
],
[
"# hist = model.fit(pad_x_train, y_train, epochs=5, validation_split=0.3, batch_size=128)\nhist = model.fit(pad_x_train, y_train, epochs=100, validation_split=0.3, batch_size=256)",
"Epoch 1/100\n25/25 [==============================] - 20s 658ms/step - loss: 3.7195 - acc: 0.2704 - val_loss: 3.4674 - val_acc: 0.0479\nEpoch 2/100\n25/25 [==============================] - 16s 627ms/step - loss: 3.2134 - acc: 0.2591 - val_loss: 2.9466 - val_acc: 0.3532\nEpoch 3/100\n25/25 [==============================] - 16s 638ms/step - loss: 2.7723 - acc: 0.3510 - val_loss: 2.5808 - val_acc: 0.3532\nEpoch 4/100\n25/25 [==============================] - 16s 629ms/step - loss: 2.5263 - acc: 0.3510 - val_loss: 2.4439 - val_acc: 0.3532\nEpoch 5/100\n25/25 [==============================] - 16s 624ms/step - loss: 2.4537 - acc: 0.3510 - val_loss: 2.4077 - val_acc: 0.3532\nEpoch 6/100\n25/25 [==============================] - 16s 635ms/step - loss: 2.4323 - acc: 0.3510 - val_loss: 2.3950 - val_acc: 0.3532\nEpoch 7/100\n25/25 [==============================] - 16s 638ms/step - loss: 2.4233 - acc: 0.3510 - val_loss: 2.3891 - val_acc: 0.3532\nEpoch 8/100\n25/25 [==============================] - 16s 642ms/step - loss: 2.4190 - acc: 0.3510 - val_loss: 2.3863 - val_acc: 0.3532\nEpoch 9/100\n25/25 [==============================] - 16s 642ms/step - loss: 2.4164 - acc: 0.3510 - val_loss: 2.3847 - val_acc: 0.3532\nEpoch 10/100\n25/25 [==============================] - 16s 639ms/step - loss: 2.4149 - acc: 0.3510 - val_loss: 2.3839 - val_acc: 0.3532\nEpoch 11/100\n25/25 [==============================] - 16s 636ms/step - loss: 2.4139 - acc: 0.3510 - val_loss: 2.3833 - val_acc: 0.3532\nEpoch 12/100\n25/25 [==============================] - 16s 636ms/step - loss: 2.4133 - acc: 0.3510 - val_loss: 2.3826 - val_acc: 0.3532\nEpoch 13/100\n25/25 [==============================] - 16s 649ms/step - loss: 2.4129 - acc: 0.3510 - val_loss: 2.3823 - val_acc: 0.3532\nEpoch 14/100\n25/25 [==============================] - 16s 635ms/step - loss: 2.4126 - acc: 0.3510 - val_loss: 2.3825 - val_acc: 0.3532\nEpoch 15/100\n25/25 [==============================] - 16s 641ms/step - loss: 2.4122 - acc: 0.3510 - val_loss: 2.3821 - val_acc: 0.3532\nEpoch 16/100\n25/25 [==============================] - 16s 644ms/step - loss: 2.4123 - acc: 0.3510 - val_loss: 2.3820 - val_acc: 0.3532\nEpoch 17/100\n25/25 [==============================] - 16s 641ms/step - loss: 2.4119 - acc: 0.3510 - val_loss: 2.3822 - val_acc: 0.3532\nEpoch 18/100\n25/25 [==============================] - 16s 636ms/step - loss: 2.4120 - acc: 0.3510 - val_loss: 2.3825 - val_acc: 0.3532\nEpoch 19/100\n25/25 [==============================] - 16s 633ms/step - loss: 2.4120 - acc: 0.3510 - val_loss: 2.3822 - val_acc: 0.3532\nEpoch 20/100\n25/25 [==============================] - 16s 644ms/step - loss: 2.4117 - acc: 0.3510 - val_loss: 2.3823 - val_acc: 0.3532\nEpoch 21/100\n25/25 [==============================] - 16s 634ms/step - loss: 2.4119 - acc: 0.3510 - val_loss: 2.3819 - val_acc: 0.3532\nEpoch 22/100\n25/25 [==============================] - 16s 632ms/step - loss: 2.4115 - acc: 0.3510 - val_loss: 2.3821 - val_acc: 0.3532\nEpoch 23/100\n25/25 [==============================] - 16s 635ms/step - loss: 2.4119 - acc: 0.3510 - val_loss: 2.3825 - val_acc: 0.3532\nEpoch 24/100\n25/25 [==============================] - 16s 641ms/step - loss: 2.4115 - acc: 0.3510 - val_loss: 2.3819 - val_acc: 0.3532\nEpoch 25/100\n25/25 [==============================] - 16s 642ms/step - loss: 2.4029 - acc: 0.3510 - val_loss: 2.4550 - val_acc: 0.3532\nEpoch 26/100\n25/25 [==============================] - 16s 651ms/step - loss: 2.4105 - acc: 0.3510 - val_loss: 2.3819 - val_acc: 0.3532\nEpoch 27/100\n25/25 [==============================] - 16s 641ms/step - loss: 2.4118 - acc: 0.3510 - val_loss: 2.3822 - val_acc: 0.3532\nEpoch 28/100\n25/25 [==============================] - 16s 635ms/step - loss: 2.4118 - acc: 0.3510 - val_loss: 2.3823 - val_acc: 0.3532\nEpoch 29/100\n25/25 [==============================] - 16s 639ms/step - loss: 2.4116 - acc: 0.3510 - val_loss: 2.3823 - val_acc: 0.3532\nEpoch 30/100\n25/25 [==============================] - 16s 642ms/step - loss: 2.4114 - acc: 0.3510 - val_loss: 2.3824 - val_acc: 0.3532\nEpoch 31/100\n25/25 [==============================] - 16s 644ms/step - loss: 2.4117 - acc: 0.3510 - val_loss: 2.3823 - val_acc: 0.3532\nEpoch 32/100\n25/25 [==============================] - 16s 641ms/step - loss: 2.4118 - acc: 0.3510 - val_loss: 2.3824 - val_acc: 0.3532\nEpoch 33/100\n25/25 [==============================] - 16s 648ms/step - loss: 2.4116 - acc: 0.3510 - val_loss: 2.3824 - val_acc: 0.3532\nEpoch 34/100\n25/25 [==============================] - 16s 643ms/step - loss: 2.4115 - acc: 0.3510 - val_loss: 2.3821 - val_acc: 0.3532\nEpoch 35/100\n25/25 [==============================] - 16s 641ms/step - loss: 2.4116 - acc: 0.3510 - val_loss: 2.3825 - val_acc: 0.3532\nEpoch 36/100\n25/25 [==============================] - 16s 640ms/step - loss: 2.4116 - acc: 0.3510 - val_loss: 2.3824 - val_acc: 0.3532\nEpoch 37/100\n25/25 [==============================] - 16s 644ms/step - loss: 2.4117 - acc: 0.3510 - val_loss: 2.3824 - val_acc: 0.3532\nEpoch 38/100\n25/25 [==============================] - 16s 647ms/step - loss: 2.4117 - acc: 0.3510 - val_loss: 2.3825 - val_acc: 0.3532\nEpoch 39/100\n25/25 [==============================] - 16s 633ms/step - loss: 2.4116 - acc: 0.3510 - val_loss: 2.3826 - val_acc: 0.3532\nEpoch 40/100\n25/25 [==============================] - 16s 636ms/step - loss: 2.4116 - acc: 0.3510 - val_loss: 2.3822 - val_acc: 0.3532\nEpoch 41/100\n25/25 [==============================] - 16s 639ms/step - loss: 2.4115 - acc: 0.3510 - val_loss: 2.3820 - val_acc: 0.3532\nEpoch 42/100\n25/25 [==============================] - 16s 640ms/step - loss: 2.4122 - acc: 0.3510 - val_loss: 2.3825 - val_acc: 0.3532\nEpoch 43/100\n25/25 [==============================] - 16s 643ms/step - loss: 2.4118 - acc: 0.3510 - val_loss: 2.3822 - val_acc: 0.3532\nEpoch 44/100\n25/25 [==============================] - 16s 638ms/step - loss: 2.4118 - acc: 0.3510 - val_loss: 2.3825 - val_acc: 0.3532\nEpoch 45/100\n25/25 [==============================] - 16s 638ms/step - loss: 2.4116 - acc: 0.3510 - val_loss: 2.3825 - val_acc: 0.3532\nEpoch 46/100\n25/25 [==============================] - 16s 636ms/step - loss: 2.4118 - acc: 0.3510 - val_loss: 2.3823 - val_acc: 0.3532\nEpoch 47/100\n25/25 [==============================] - 16s 643ms/step - loss: 2.4116 - acc: 0.3510 - val_loss: 2.3824 - val_acc: 0.3532\nEpoch 48/100\n25/25 [==============================] - 16s 638ms/step - loss: 2.4119 - acc: 0.3510 - val_loss: 2.3823 - val_acc: 0.3532\nEpoch 49/100\n25/25 [==============================] - 16s 638ms/step - loss: 2.4117 - acc: 0.3510 - val_loss: 2.3824 - val_acc: 0.3532\nEpoch 50/100\n25/25 [==============================] - 16s 641ms/step - loss: 2.4115 - acc: 0.3510 - val_loss: 2.3824 - val_acc: 0.3532\nEpoch 51/100\n25/25 [==============================] - 16s 637ms/step - loss: 2.4115 - acc: 0.3510 - val_loss: 2.3820 - val_acc: 0.3532\nEpoch 52/100\n25/25 [==============================] - 16s 634ms/step - loss: 2.4115 - acc: 0.3510 - val_loss: 2.3822 - val_acc: 0.3532\nEpoch 53/100\n25/25 [==============================] - 16s 642ms/step - loss: 2.4104 - acc: 0.3510 - val_loss: 2.3803 - val_acc: 0.3532\nEpoch 54/100\n25/25 [==============================] - 16s 645ms/step - loss: 2.4060 - acc: 0.3510 - val_loss: 2.3665 - val_acc: 0.3532\nEpoch 55/100\n25/25 [==============================] - 16s 639ms/step - loss: 2.3382 - acc: 0.3755 - val_loss: 2.2555 - val_acc: 0.4764\nEpoch 56/100\n25/25 [==============================] - 16s 648ms/step - loss: 2.2553 - acc: 0.3689 - val_loss: 2.1948 - val_acc: 0.4553\nEpoch 57/100\n25/25 [==============================] - 16s 644ms/step - loss: 2.1991 - acc: 0.4641 - val_loss: 2.1491 - val_acc: 0.4842\nEpoch 58/100\n25/25 [==============================] - 16s 644ms/step - loss: 2.1441 - acc: 0.5096 - val_loss: 2.0970 - val_acc: 0.5239\nEpoch 59/100\n25/25 [==============================] - 16s 644ms/step - loss: 2.0953 - acc: 0.5254 - val_loss: 2.0584 - val_acc: 0.5288\nEpoch 60/100\n25/25 [==============================] - 16s 639ms/step - loss: 2.0709 - acc: 0.5160 - val_loss: 2.0558 - val_acc: 0.5006\nEpoch 61/100\n25/25 [==============================] - 16s 642ms/step - loss: 2.0219 - acc: 0.5340 - val_loss: 2.0104 - val_acc: 0.5276\nEpoch 62/100\n25/25 [==============================] - 16s 641ms/step - loss: 1.9885 - acc: 0.5398 - val_loss: 1.9924 - val_acc: 0.5187\nEpoch 63/100\n25/25 [==============================] - 16s 632ms/step - loss: 1.9596 - acc: 0.5397 - val_loss: 1.9764 - val_acc: 0.5165\nEpoch 64/100\n25/25 [==============================] - 16s 631ms/step - loss: 1.9213 - acc: 0.5418 - val_loss: 1.9706 - val_acc: 0.5132\nEpoch 65/100\n25/25 [==============================] - 16s 629ms/step - loss: 1.8728 - acc: 0.5379 - val_loss: 1.9073 - val_acc: 0.4994\nEpoch 66/100\n25/25 [==============================] - 16s 643ms/step - loss: 1.7927 - acc: 0.5683 - val_loss: 1.8431 - val_acc: 0.5299\nEpoch 67/100\n25/25 [==============================] - 16s 640ms/step - loss: 1.7446 - acc: 0.5780 - val_loss: 1.8360 - val_acc: 0.5273\nEpoch 68/100\n25/25 [==============================] - 16s 642ms/step - loss: 1.6942 - acc: 0.5825 - val_loss: 1.8078 - val_acc: 0.5351\nEpoch 69/100\n25/25 [==============================] - 16s 636ms/step - loss: 1.6616 - acc: 0.5858 - val_loss: 1.8114 - val_acc: 0.5310\nEpoch 70/100\n25/25 [==============================] - 16s 647ms/step - loss: 1.6356 - acc: 0.5925 - val_loss: 1.7646 - val_acc: 0.5432\nEpoch 71/100\n25/25 [==============================] - 16s 652ms/step - loss: 1.5982 - acc: 0.6039 - val_loss: 1.7583 - val_acc: 0.5518\nEpoch 72/100\n25/25 [==============================] - 16s 648ms/step - loss: 1.5679 - acc: 0.6122 - val_loss: 1.7503 - val_acc: 0.5570\nEpoch 73/100\n25/25 [==============================] - 16s 653ms/step - loss: 1.5409 - acc: 0.6176 - val_loss: 1.7591 - val_acc: 0.5518\nEpoch 74/100\n25/25 [==============================] - 16s 652ms/step - loss: 1.5137 - acc: 0.6218 - val_loss: 1.7479 - val_acc: 0.5555\nEpoch 75/100\n25/25 [==============================] - 16s 646ms/step - loss: 1.4868 - acc: 0.6268 - val_loss: 1.7797 - val_acc: 0.5466\nEpoch 76/100\n25/25 [==============================] - 16s 643ms/step - loss: 1.4703 - acc: 0.6267 - val_loss: 1.7516 - val_acc: 0.5525\nEpoch 77/100\n25/25 [==============================] - 16s 649ms/step - loss: 1.4460 - acc: 0.6275 - val_loss: 1.7809 - val_acc: 0.5391\nEpoch 78/100\n25/25 [==============================] - 16s 648ms/step - loss: 1.4209 - acc: 0.6310 - val_loss: 1.7754 - val_acc: 0.5484\nEpoch 79/100\n25/25 [==============================] - 16s 652ms/step - loss: 1.4056 - acc: 0.6289 - val_loss: 1.7807 - val_acc: 0.5451\nEpoch 80/100\n25/25 [==============================] - 16s 648ms/step - loss: 1.3871 - acc: 0.6350 - val_loss: 1.7988 - val_acc: 0.5406\nEpoch 81/100\n25/25 [==============================] - 16s 650ms/step - loss: 1.3677 - acc: 0.6361 - val_loss: 1.7908 - val_acc: 0.5488\nEpoch 82/100\n25/25 [==============================] - 16s 651ms/step - loss: 1.3643 - acc: 0.6350 - val_loss: 1.8382 - val_acc: 0.5317\nEpoch 83/100\n25/25 [==============================] - 16s 643ms/step - loss: 1.3414 - acc: 0.6434 - val_loss: 1.7929 - val_acc: 0.5492\nEpoch 84/100\n25/25 [==============================] - 16s 646ms/step - loss: 1.3253 - acc: 0.6472 - val_loss: 1.8259 - val_acc: 0.5440\nEpoch 85/100\n25/25 [==============================] - 16s 654ms/step - loss: 1.3071 - acc: 0.6485 - val_loss: 1.8041 - val_acc: 0.5462\nEpoch 86/100\n25/25 [==============================] - 16s 644ms/step - loss: 1.2946 - acc: 0.6626 - val_loss: 1.8500 - val_acc: 0.5310\nEpoch 87/100\n25/25 [==============================] - 16s 644ms/step - loss: 1.2779 - acc: 0.6706 - val_loss: 1.8331 - val_acc: 0.5347\nEpoch 88/100\n25/25 [==============================] - 16s 640ms/step - loss: 1.2590 - acc: 0.6841 - val_loss: 1.8651 - val_acc: 0.5291\nEpoch 89/100\n25/25 [==============================] - 16s 639ms/step - loss: 1.2441 - acc: 0.6909 - val_loss: 1.8525 - val_acc: 0.5358\nEpoch 90/100\n25/25 [==============================] - 16s 645ms/step - loss: 1.2360 - acc: 0.6811 - val_loss: 1.8554 - val_acc: 0.5380\nEpoch 91/100\n25/25 [==============================] - 16s 634ms/step - loss: 1.2183 - acc: 0.6847 - val_loss: 1.8912 - val_acc: 0.5295\nEpoch 92/100\n25/25 [==============================] - 16s 640ms/step - loss: 1.2373 - acc: 0.6703 - val_loss: 1.8739 - val_acc: 0.5336\nEpoch 93/100\n25/25 [==============================] - 16s 643ms/step - loss: 1.1995 - acc: 0.6854 - val_loss: 1.9008 - val_acc: 0.5302\nEpoch 94/100\n25/25 [==============================] - 16s 636ms/step - loss: 1.1730 - acc: 0.6878 - val_loss: 1.8738 - val_acc: 0.5362\nEpoch 95/100\n25/25 [==============================] - 16s 640ms/step - loss: 1.1558 - acc: 0.6911 - val_loss: 1.9222 - val_acc: 0.5147\nEpoch 96/100\n25/25 [==============================] - 16s 638ms/step - loss: 1.1452 - acc: 0.6917 - val_loss: 1.9129 - val_acc: 0.5280\nEpoch 97/100\n25/25 [==============================] - 16s 640ms/step - loss: 1.1313 - acc: 0.6954 - val_loss: 1.8829 - val_acc: 0.5384\nEpoch 98/100\n25/25 [==============================] - 16s 641ms/step - loss: 1.1093 - acc: 0.6975 - val_loss: 1.9224 - val_acc: 0.5250\nEpoch 99/100\n25/25 [==============================] - 16s 640ms/step - loss: 1.0904 - acc: 0.7040 - val_loss: 1.9198 - val_acc: 0.5310\nEpoch 100/100\n25/25 [==============================] - 16s 641ms/step - loss: 1.0828 - acc: 0.7040 - val_loss: 1.9060 - val_acc: 0.5380\n"
]
],
[
[
"# Evaluation",
"_____no_output_____"
]
],
[
[
"# 학습시켰던 데이터\nmodel.evaluate(pad_x_train, y_train)",
"281/281 [==============================] - 16s 56ms/step - loss: 1.3192 - acc: 0.6544\n"
]
],
[
[
"x_test 데이터 전처리",
"_____no_output_____"
]
],
[
[
"pad_x_test = tf.keras.preprocessing.sequence.pad_sequences(x_test, maxlen=500)",
"_____no_output_____"
],
[
"def pad_make(x_data):\n pad_x = tf.keras.preprocessing.sequence.pad_sequences(x_data, maxlen=500)\n return pad_x",
"_____no_output_____"
],
[
"pad_make_x = pad_make(x_test)",
"_____no_output_____"
],
[
"model.evaluate(pad_make_x, y_test)",
"71/71 [==============================] - 4s 56ms/step - loss: 1.9766 - acc: 0.5419\n"
],
[
"model.evaluate(pad_x_test, y_test)",
"71/71 [==============================] - 4s 57ms/step - loss: 1.9766 - acc: 0.5419\n"
]
],
[
[
"train과 test의 acc 유사하기 때문에 학습이 잘 됨을 볼 수 있음",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"plt.plot(hist.history['loss'])\nplt.plot(hist.history['val_loss'])\nplt.show()",
"_____no_output_____"
],
[
"plt.plot(hist.history['acc'])\nplt.plot(hist.history['val_acc'])\nplt.show()",
"_____no_output_____"
],
[
"from sklearn.metrics import classification_report",
"_____no_output_____"
],
[
"y_train_pred = model.predict(pad_x_train)\ny_train_pred[0]",
"_____no_output_____"
],
[
"y_pred = np.argmax(y_train_pred, axis=1)\ny_pred.shape",
"_____no_output_____"
],
[
"len(y_train)",
"_____no_output_____"
],
[
"print(classification_report(y_train, y_pred))",
" precision recall f1-score support\n\n 0 0.00 0.00 0.00 55\n 1 0.30 0.80 0.44 432\n 2 0.00 0.00 0.00 74\n 3 0.95 0.95 0.95 3159\n 4 0.88 0.89 0.89 1949\n 5 0.00 0.00 0.00 17\n 6 0.00 0.00 0.00 48\n 7 0.00 0.00 0.00 16\n 8 0.00 0.00 0.00 139\n 9 0.00 0.00 0.00 101\n 10 0.09 0.61 0.15 124\n 11 0.00 0.00 0.00 390\n 12 0.00 0.00 0.00 49\n 13 0.00 0.00 0.00 172\n 14 0.00 0.00 0.00 26\n 15 0.00 0.00 0.00 20\n 16 0.42 0.66 0.51 444\n 17 0.00 0.00 0.00 39\n 18 0.00 0.00 0.00 66\n 19 0.38 0.76 0.51 549\n 20 0.14 0.00 0.01 269\n 21 0.00 0.00 0.00 100\n 22 0.00 0.00 0.00 15\n 23 0.00 0.00 0.00 41\n 24 0.00 0.00 0.00 62\n 25 0.00 0.00 0.00 92\n 26 0.00 0.00 0.00 24\n 27 0.00 0.00 0.00 15\n 28 0.00 0.00 0.00 48\n 29 0.00 0.00 0.00 19\n 30 0.00 0.00 0.00 45\n 31 0.00 0.00 0.00 39\n 32 0.00 0.00 0.00 32\n 33 0.00 0.00 0.00 11\n 34 0.00 0.00 0.00 50\n 35 0.00 0.00 0.00 10\n 36 0.00 0.00 0.00 49\n 37 0.00 0.00 0.00 19\n 38 0.00 0.00 0.00 19\n 39 0.00 0.00 0.00 24\n 40 0.00 0.00 0.00 36\n 41 0.00 0.00 0.00 30\n 42 0.00 0.00 0.00 13\n 43 0.00 0.00 0.00 21\n 44 0.00 0.00 0.00 12\n 45 0.00 0.00 0.00 18\n\n accuracy 0.65 8982\n macro avg 0.07 0.10 0.08 8982\nweighted avg 0.59 0.65 0.61 8982\n\n"
],
[
"y_test_pred = model.predict(pad_x_test)",
"_____no_output_____"
],
[
"y_pred = np.argmax(y_test_pred, axis=1)",
"_____no_output_____"
],
[
"print(classification_report(y_test, y_pred))",
" precision recall f1-score support\n\n 0 0.00 0.00 0.00 12\n 1 0.17 0.53 0.26 105\n 2 0.00 0.00 0.00 20\n 3 0.93 0.89 0.91 813\n 4 0.70 0.72 0.71 474\n 5 0.00 0.00 0.00 5\n 6 0.00 0.00 0.00 14\n 7 0.00 0.00 0.00 3\n 8 0.00 0.00 0.00 38\n 9 0.00 0.00 0.00 25\n 10 0.07 0.37 0.11 30\n 11 0.00 0.00 0.00 83\n 12 0.00 0.00 0.00 13\n 13 0.00 0.00 0.00 37\n 14 0.00 0.00 0.00 2\n 15 0.00 0.00 0.00 9\n 16 0.11 0.22 0.15 99\n 17 0.00 0.00 0.00 12\n 18 0.00 0.00 0.00 20\n 19 0.23 0.47 0.31 133\n 20 0.33 0.04 0.08 70\n 21 0.00 0.00 0.00 27\n 22 0.00 0.00 0.00 7\n 23 0.00 0.00 0.00 12\n 24 0.00 0.00 0.00 19\n 25 0.00 0.00 0.00 31\n 26 0.00 0.00 0.00 8\n 27 0.00 0.00 0.00 4\n 28 0.00 0.00 0.00 10\n 29 0.00 0.00 0.00 4\n 30 0.00 0.00 0.00 12\n 31 0.00 0.00 0.00 13\n 32 0.00 0.00 0.00 10\n 33 0.00 0.00 0.00 5\n 34 0.00 0.00 0.00 7\n 35 0.00 0.00 0.00 6\n 36 0.00 0.00 0.00 11\n 37 0.00 0.00 0.00 2\n 38 0.00 0.00 0.00 3\n 39 0.00 0.00 0.00 5\n 40 0.00 0.00 0.00 10\n 41 0.00 0.00 0.00 8\n 42 0.00 0.00 0.00 3\n 43 0.00 0.00 0.00 6\n 44 0.00 0.00 0.00 5\n 45 0.00 0.00 0.00 1\n\n accuracy 0.54 2246\n macro avg 0.06 0.07 0.05 2246\nweighted avg 0.52 0.54 0.52 2246\n\n"
]
],
[
[
"비슷한 부분끼리 0임을 확인 -> words=10000 제한 때문에 0이 발생",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
e77a331cce225f56e0c2b7b4b98ac2234d21bc36 | 18,183 | ipynb | Jupyter Notebook | latestv1.ipynb | bxck75/Python_Helpers | 80a8f25e2469ae06bf8437c29ea736fecfed9290 | [
"BSD-2-Clause"
] | 1 | 2019-10-12T04:42:48.000Z | 2019-10-12T04:42:48.000Z | latestv1.ipynb | bxck75/Python_Helpers | 80a8f25e2469ae06bf8437c29ea736fecfed9290 | [
"BSD-2-Clause"
] | null | null | null | latestv1.ipynb | bxck75/Python_Helpers | 80a8f25e2469ae06bf8437c29ea736fecfed9290 | [
"BSD-2-Clause"
] | null | null | null | 33.54797 | 228 | 0.457075 | [
[
[
"<a href=\"https://colab.research.google.com/github/bxck75/Python_Helpers/blob/master/latestv1.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"''' install 3dparty sheit '''\nfrom IPython.display import clear_output as cle\nfrom pprint import pprint as print\nfrom PIL import Image\nimport os\nimport sys\nimport json\nimport IPython\n\n''' default sample data delete '''\nos.system('rm -r sample_data')\n\n''' set root paths '''\nroot = '/content'\ngdrive_root = '/content/drive/My Drive'\nhelpers_root = root + '/installed_repos/Python_Helpers'\n\n''' setup install the Helpers module '''\nos.system('git clone https://github.com/bxck75/Python_Helpers.git ' + helpers_root) \nos.system('python ' + helpers_root + 'setup.py install')\n\n''' import helpers '''\nos.chdir(helpers_root)\nimport main as main_core\nMainCore = main_core.main()\nHelpCore = MainCore.Helpers_Core\nFScrape = HelpCore.flickr_scrape\nfromGdrive = HelpCore.GdriveD\ntoGdrive = HelpCore.ZipUp.ZipUp\n\ncle()",
"_____no_output_____"
],
[
"dir(HelpCore)\nFScrape(['Ork','Troll','Dragon'], 25, '/content/images')\nimgs_path_list = HelpCore.GlobX(img_dir,'*.*g')\nprint(imgs_path_list)",
"_____no_output_____"
],
[
"dir(HelpCore)",
"_____no_output_____"
],
[
"print(MainCore.Helpers_Core.cloner('/content/images'))",
"_____no_output_____"
],
[
"# def LandMarks(img_dir,out_dir):\n# ''' Folder glob and Landmark all found imgs '''\n# imgs_path_list = HelpCore.GlobX(img_dir,'*.*g')\n# imgs_path_list.sort()\n \n# i=0\n# for i in range(len(imgs_path_list)):\n# ''' make folders '''\n\n# img_pathAr = imgs_path_list[i]\n# # img_pathAr.Split(Path.DirectorySeparatorChar) # returns array of the path\n# # img_pathAr.Lenth - 2\n# # print(img_pathAr[2])\n \n# os.system('mkdir -p '+os.path.join(out_dir,'/org'))\n# os.system('mkdir -p '+os.path.join(out_dir,'/marked'))\n# ''' backup original '''\n# os.system('cp imgs_path_list[i] '+out_dir + '/org')\n# ''' loop over images '''\n# img = cv.imread(imgs_path_list[i])\n# for c, w, h in img.shape:\n# print(3, w, h)\n# if img is None:\n# print('Failed to load image file:', fname)\n# sys.exit(1)\n# fork_img = img\n# ''' Mark the image '''\n# gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n# lsd = cv.line_descriptor_LSDDetector.createLSDDetector()\n# lines = lsd.detect(gray, 1, 1)\n# for kl in lines:\n# if kl.octave == 0:\n# pt1 = (int(kl.startPointX), int(kl.startPointY))\n# pt2 = (int(kl.endPointX), int(kl.endPointY))\n# cv.line(fork_img, pt1, pt2, [255, 0, 0], 2)\n\n\n# cv.waitKey(0)\n# cv.destroyAllWindows()\n# cv.imwrite('nice.jpg',img)\n# # marked\n# cv.imwrite('nice.jpg',img)\n# i += 1",
"_____no_output_____"
],
[
"# def org_n_marked_clone(img_path,id=0):\n# ''' backup the originals '''\n# drive, path_and_file = os.path.splitdrive(img_path)\n# path, file = os.path.split(path_and_file)\n# fi, ex = file.split(.)\n# fi.rstrip(string.digits)\n\n# ''' compose the new paths '''\n# org_path = path + '/org/' + fi + '_%d' % id\n# marked_path = path + '/marked/' + fi + '_%d' % id\n# ''' return the list '''\n# return [org_path,marked_path]\n\n\n# org_n_marked_clone('/content/images/img_1.jpg')",
"_____no_output_____"
],
[
"os.path.join( path+'/org', file )",
"_____no_output_____"
],
[
"import sys\nimport cv2 as cv\n\nif __name__ == '__main__':\n print(__doc__)\n\n fname = '/content/images/img_1.jpg'\n\n img = cv.imread(fname)\n\n if img is None:\n print('Failed to load image file:', fname)\n sys.exit(1)\n\n gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n\n lsd = cv.line_descriptor_LSDDetector.createLSDDetector()\n\n lines = lsd.detect(gray, 1, 1)\n for kl in lines:\n if kl.octave == 0:\n # cv.line only accepts integer coordinate\n pt1 = (int(kl.startPointX), int(kl.startPointY))\n pt2 = (int(kl.endPointX), int(kl.endPointY))\n cv.line(img, pt1, pt2, [255, 0, 0], 2)\n\n # plt.imshow('output', img)\n cv.waitKey(0)\n cv.destroyAllWindows()\n cv.imwrite('nice.jpg',img)",
"_____no_output_____"
],
[
"from google.colab import drive\ndrive.mount('/content/drive')",
"_____no_output_____"
],
[
"help(HelpCore)",
"_____no_output_____"
],
[
"help(FScrape)\n# search_list,img_dir,qty = ['zombie'], 'images', 21\n# FScrape(search_list,qty,img_dir)\nfuncs=[\n 'BigHelp',\n 'Colab_root',\n 'ColorPrint',\n 'FileView',\n 'FlickrS',\n 'GdriveD',\n 'Gdrive_root',\n 'GlobX',\n 'GooScrape',\n 'ImgCrawler',\n 'ImgTools',\n 'LogGER',\n 'Logger',\n 'MethHelp',\n 'Ops',\n 'Repo_List',\n 'Resize',\n 'Sys_Cmd',\n 'Sys_Exec',\n 'ZipUp',\n ]\n\ndef img_show_folder(folder):\n # fname = '/content/images/img_1.jpg'\n folder_path = Path(folder)\n GlobX(folder_path,'*.*g')\n for base, dirs, files in os.walk('/content/images'):\n files.sort()\n for i in range(len(files)):\n print(base+'/'+files[i])\n img = cv.imread(base+'/'+files[i])\n plt.imshow(img,cmap=dark2)\n plt.show()\n\nHelpCore.GlobX('/content/images','*.*g')\n# search_list, img_dir, qty = ['zombie'], 'images', 200\n\n# FScrape(search_list, qty, img_dir)",
"_____no_output_____"
],
[
"# toGdrive('cv2_samples','/content/drive/My Drive','/content/installed_repos/opencv/samples')\n# Load zipper\n# Zipper = toGdrive.GdriveD\n# Zip folder\n# images_set_name, gdrive_folder, folder_to_zip = 'cv2_samples', '/content/drive/My Drive', '/content/installed_repos/opencv/samples'\n# result=Zipper(images_set_name,gdrive_folder,folder_to_zip).ZipUp\n# Print Resulting hash\nprint(result)\ndir(toGdrive)\n# HelpCore.GlobX('/content', '*.py')",
"_____no_output_____"
],
[
"!python /content/installed_repos/opencv/samples/dnn/segmentation.py --zoo --input --framework 'tensorflow'",
"_____no_output_____"
],
[
"%cd /content/installed_repos/opencv/samples/dnn\n!cat segmentation.py",
"_____no_output_____"
]
],
[
[
"parser = argparse.ArgumentParser(add_help=False)\nparser.add_argument('--zoo', default=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'models.yml'),\n help='An optional path to file with preprocessing parameters.')\nparser.add_argument('--input', help='Path to input image or video file. Skip this argument to capture frames from a camera.')\nparser.add_argument('--framework', choices=['caffe', 'tensorflow', 'torch', 'darknet'],\n help='Optional name of an origin framework of the model. '\n 'Detect it automatically if it does not set.')\nparser.add_argument('--colors', help='Optional path to a text file with colors for an every class. '\n 'An every color is represented with three values from 0 to 255 in BGR channels order.')\nparser.add_argument('--backend', choices=backends, default=cv.dnn.DNN_BACKEND_DEFAULT, type=int,\n help=\"Choose one of computation backends: \"\n \"%d: automatically (by default), \"\n \"%d: Halide language (http://halide-lang.org/), \"\n \"%d: Intel's Deep Learning Inference Engine (https://software.intel.com/openvino-toolkit), \"\n \"%d: OpenCV implementation\" % backends)\nparser.add_argument('--target', choices=targets, default=cv.dnn.DNN_TARGET_CPU, type=int,\n help='Choose one of target computation devices: '\n '%d: CPU target (by default), '\n '%d: OpenCL, '\n '%d: OpenCL fp16 (half-float precision), '\n '%d: VPU' % targets)\nargs, _ = parser.parse_known_args()\n",
"_____no_output_____"
]
],
[
[
"# !wget https://drive.google.com/open?id=1KNfN-ktxbPJMtmdiL-I1WW0IO1B_2EG2\n# landmarks_file=['1KNfN-ktxbPJMtmdiL-I1WW0IO1B_2EG2','/content/shape_predictor_68_face_landmarks.dat']\n# fromGdrive.GdriveD(landmarks_file[0],landmarks_file[1])\nimport cv2\nimport numpy\nimport dlib\nimport matplotlib.pyplot as plt\n\n# cap = cv2.VideoCapture(0)\n\ndetector = dlib.get_frontal_face_detector()\npredictor = dlib.shape_predictor(\"/content/shape_predictor_68_face_landmarks.dat\")\n\nwhile True:\n _, frame = cap.read()\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n faces = detector(gray)\n for face in faces:\n x1 = face.left()\n y1 = face.top()\n x2 = face.right()\n y2 = face.bottom()\n #cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 3)\n\n landmarks = predictor(gray, face)\n\n for n in range(0, 68):\n x = landmarks.part(n).x\n y = landmarks.part(n).y\n cv2.circle(frame, (x, y), 4, (255, 0, 0), -1)\n\n\n plt.imshow(\"Frame\", frame)\n\n key = cv2.waitKey(1)\n if key == 27:\n break\ncap.release()\ncv2.destroyAllWindows()\n",
"_____no_output_____"
],
[
"''' install 3dparty sheit '''\nfrom IPython.display import clear_output as cle\nfrom pprint import pprint as print\nfrom PIL import Image\nimport os\nimport sys\nimport json\nimport IPython\n\n''' default sample data delete '''\nos.system('rm -r sample_data')\n\n''' set root paths '''\nroot = '/content'\ngdrive_root = '/content/drive/My Drive'\nhelpers_root = root + '/installed_repos/Python_Helpers'\n\n''' setup install the Helpers module '''\nos.system('git clone https://github.com/bxck75/Python_Helpers.git ' + helpers_root) \nos.system('python ' + helpers_root + 'setup.py install')\n",
"_____no_output_____"
],
[
"os.chdir(helpers_root)\nfrom main import main\nlandmarks_68_file = '1KNfN-ktxbPJMtmdiL-I1WW0IO1B_2EG2'\nlandmarks_194_file = '1fMOT_0f5clPbZXsphZyrGcLXkIhSDl3o'",
"_____no_output_____"
],
[
"os.chdir(root)\n\nimages_set_name, gdrive_folder, folder_to_zip = 'cv2_samples', '/content/installed_repos/opencv/samples/dnn/*', '/content/drive/My Drive'\nresults=HelpCore.ZipUp.ZipUp(images_set_name,gdrive_folder,folder_to_zip).ZipUp\nprint(results)",
"_____no_output_____"
],
[
"!zip -r cv2_examples.zip /content/installed_repos/opencv/samples/dnn /content/installed_repos/opencv/samples/python",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
e77a47d68625200afa2ada8974daa960d83f77ec | 313,341 | ipynb | Jupyter Notebook | 1-Splay-Trees.ipynb | jakobn-ai/SplayPy-Paper | 953c26b0d0d8a3189eebe360ad02838eed2a1ed9 | [
"MIT"
] | null | null | null | 1-Splay-Trees.ipynb | jakobn-ai/SplayPy-Paper | 953c26b0d0d8a3189eebe360ad02838eed2a1ed9 | [
"MIT"
] | null | null | null | 1-Splay-Trees.ipynb | jakobn-ai/SplayPy-Paper | 953c26b0d0d8a3189eebe360ad02838eed2a1ed9 | [
"MIT"
] | null | null | null | 56.346161 | 1,345 | 0.529548 | [
[
[
"Dieser Block erzeugt eine Darstellung, die die ganze Breite des Fensters ausnutzt.",
"_____no_output_____"
]
],
[
[
"%%HTML\n<style>.container{width:100%;}</style>",
"_____no_output_____"
]
],
[
[
"Dieser Block schaltet die Überprüfung auf Schönheitsfehler ein. Wir ignorieren die Konvention, dass zwischen Definitionen zwei Leerzeilen stehen sollen, um die Lesbarkeit zu erhöhen. Wir erlauben auch mehrere Leerzeichen vor einem Operator, um sequenzielle Zuweisungen am `=` ausrichten zu können.",
"_____no_output_____"
]
],
[
[
"%load_ext pycodestyle_magic\n%flake8_on --ignore E302,E305,E221",
"_____no_output_____"
]
],
[
[
"Wir benötigen außerdem *Graphviz* zur Visualisierung.",
"_____no_output_____"
]
],
[
[
"import graphviz",
"_____no_output_____"
]
],
[
[
"# Splay Trees\n\nIn diesem Notebook wird eine bestimmte Art von selbstbalancierenden Bäumen gezeigt, die *Splay Trees*. Diese Datenstruktur wurde [1985 von Sleator und Tarjan eingeführt](http://www.cs.cmu.edu/~sleator/papers/self-adjusting.pdf \"D. D. Sleator, R. E. Tarjan (1985): Self-Adjusting Binary Search Trees. Journal of the ACM, 32(3) 652-686\"). Im Gegensatz zu anderen selbstbalancierenden Bäumen wie AVL-Bäumen wird bei Splay Trees nicht gefordert, dass der Baum zu allen Zeiten so gut wie möglich balanciert ist. Stattdessen wird der Baum dahingehend optimiert, dass häufig verwendete Elemente nahe an der Wurzel sind.\n\nAuf Basis dieser Bäume soll später eine alternative Implementierung von Mengen in der Programmiersprache Python entstehen. In der Referenzimplementierung *CPython* sind [Mengen auf Basis von *Hashtabellen* implementiert](https://github.com/python/cpython/blob/3.7/Objects/setobject.c \"R. D. Hettinger et al. (2019): cpython/Objects/setobject.c, GitHub\"). Viele andere weit verbreitete Implementierungen anderer Programmiersprachen benutzen für Mengen ebenfalls Hashtabellen oder haben dies zumindest als Option, wie in [Java](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Set.html \"Oracle Corporation (2019): Set (Java SE 13 & JDK 13)\"), [.NET (C#)](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.iset-1?view=netframework-4.8, \"Microsoft Corporation (2020): ISet<T> Interface (System.Collections.Generic), Microsoft Docs\"), [JavaScript](https://v8.dev/blog/hash-code \"S. Gunasekaran (2018): Optimizing hash tables: hiding the hash code, V8 Blog\") oder [PHP](https://www.php.net/manual/en/class.ds-set.php \"The PHP Group (2020): PHP: Set, Manual\"). Jedoch sind mit der Verwendung von Bäumen für Mengen einige mengenlastige Programmierprobleme einfacher zu lösen, da diese Mengen *geordnet* sind und somit beispielsweise ein einfach zu bestimmendes Minimum und ein Maximum haben.\n\nGeordnete binäre Bäume eignen sich, um Mengen zu implementieren, da insbesondere in beiden keine doppelten Elemente vorkommen. Wir müssen für geordnete Mengen außerdem fordern, dass alle Elemente geordnet werden können. Wir behandeln später, wie wir beliebigen Nutzlasten in Python eine Ordnung geben können.\n\nDie reine Datenstruktur – ohne Operationen – ist bei Splay Trees genauso wie bei regulären geordneten binären Bäumen definiert: $\\mathrm{Node}(p, l, r)$ ist ein Baum, wobei\n- $p$ eine Nutzlast (payload) ist,\n- $l$ der linke Teilbaum ist und\n- $r$ der rechte Teilbaum ist.",
"_____no_output_____"
]
],
[
[
"class Node:\n def __init__(self, payload, left, right):\n self.payload = payload\n self.left = left\n self.right = right",
"_____no_output_____"
]
],
[
[
"Wir verlangen dabei:\n\n- Für alle Nutzlasten aus dem linken Teilbaum $l$ gilt, dass sie kleiner als die Nutzlast $p$ sind.\n- Für alle Nutzlasten aus dem rechten Teilbaum $r$ gilt, dass sie größer als die Nutzlast $p$ sind.\n\nDiese Aussagen können auch als $l < p < r$ formuliert werden.\n\n## Visualisierung\n\nWir wollen, um die Splay Trees besser erklären zu können, zuerst ihre Visualisierung implementieren. Bäume, die eine Untermenge der Graphen sind, können wir mit dem [Python-Interface](https://github.com/xflr6/graphviz \"S. Bank (2019): graphviz, GitHub\") zu [*Graphviz*](https://graphviz.org/ \"J. Ellson et al. (2019): Graphviz\") visualisieren.\n\nWir definieren dazu zuerst die interne Methode `_graph` der Klasse `Node`, die einem bestehenden Graphen `dot` die eigene Struktur hinzufügt. Wir müssen uns dabei merken, welche Namen wir schon für Knoten im Graph benutzt haben, wofür `_graph` noch die Menge `used` übergeben bekommt. Als Namen benutzen wir immer die `id` des Knotens, außer, wenn wir leere Knoten markieren, für die wir kein `Node`-Objekt halten. In diesem Fall benutzen wir einen Zähler `key`, den `_graph` ebenfalls übergeben bekommt. Den geänderten Zähler gibt `_graph` zurück, `used` brauchen wir nicht zurückgeben, da Mengen per Referenz weitergegeben werden.",
"_____no_output_____"
]
],
[
[
"def _graph(self, dot, used, key):\n used.add(id(self))\n dot.node(str(id(self)), label=str(self.payload))\n if not (self.left is None and self.right is None):\n for node in self.left, self.right:\n if node is not None:\n dot.edge(str(id(self)), str(id(node)))\n key = node._graph(dot, used, key)\n else:\n while True:\n key += 1\n if key not in used:\n break\n used.add(key)\n dot.node(str(key), shape=\"point\")\n dot.edge(str(id(self)), str(key))\n return key\n\nNode._graph = _graph\ndel _graph",
"_____no_output_____"
]
],
[
[
"Die nach außen offenstehende Methode `graph` (ohne Unterstrich) der Klasse `Node` leistet nur die Vorarbeit für `_graph` und ruft diese Methode dann auf. `graph` unterstützt allerdings beliebig viele `additionals`, also `Node`s, die in dieser Reihenfolge ebenfalls in den Graphen eingefügt werden. So können wir mehrere Bäume in einem Schaubild sehen und insbesondere Schritte besser nachvollziehen.",
"_____no_output_____"
]
],
[
[
"def graph(self, *additionals):\n dot = graphviz.Digraph()\n used = set()\n key = self._graph(dot, used, 0)\n for el in additionals:\n key = el._graph(dot, used, key)\n return dot\n\nNode.graph = graph\ndel graph",
"_____no_output_____"
]
],
[
[
"Um bei solchen Schritten anmerken zu können, was geschieht, definieren wir die Klasse `Method`, die sich auch mit `_graph` visualisieren lassen kann. Solche Knoten werden dann als Rechtecke angezeigt.",
"_____no_output_____"
]
],
[
[
"class Method:\n def __init__(self, name):\n self.name = name\n\n def _graph(self, dot, used, key):\n used.add(id(self))\n dot.node(str(id(self)), label=str(self.name) + \" ⇒\",\n shape=\"rectangle\", style=\"dotted\")\n return key",
"_____no_output_____"
]
],
[
[
"Zuletzt definieren wir `TempTree`, dessen Verbindung zu seinem einzigen (links oder rechts sitzenden) Kind an der Seite statt unten sitzt und gestrichelt gezeichnet wird. Der Baum selbst wird als Dreieck gezeichnet. Wir werden damit später Bäume visualisieren, bei denen wir nur die äußersten Knoten zeichnen und dazwischen Knoten in der Darstellung auslassen.",
"_____no_output_____"
]
],
[
[
"class TempTree:\n def __init__(self, name, child, left):\n self.name = name\n self.child = child\n self.left = left\n\n def _graph(self, dot, used, key):\n used.add(id(self))\n dot.node(str(id(self)), label=str(self.name), shape=\"triangle\")\n if self.child is not None:\n dot.edge(str(id(self)), str(id(self.child)), style=\"dashed\",\n tailport=\"w\" if self.left else \"e\")\n key = self.child._graph(dot, used, key)\n else:\n while True:\n key += 1\n if key not in used:\n break\n used.add(key)\n dot.node(str(key), shape=\"point\")\n dot.edge(str(id(self)), str(key), style=\"dashed\",\n tailport=\"w\" if self.left else \"e\")\n return key\n\nTempTree.graph = Node.graph",
"_____no_output_____"
]
],
[
[
"## Splaying\n\nDie Besonderheit von Splay Trees ist, dass mit allen Baumoperationen, die ein Element im Baum lokalisieren, eine besondere Operation, der *Splay*, durchgeführt wird. Mit Baumoperationen, die ein Element im Baum lokalisieren, sind alle Operationen auf den Baum gemeint, die den Baum auf der Suche nach einem Element oder auf der Suche nach dem richtigen Ort für ein Element durchsuchen. Dazu gehören das Einfügen, Löschen und Finden von Elementen.\n\nDer Splay ist eine Funktion, die einen Baum dahingehend modifiziert, dass eine Nutzlast, die schon im Baum enthalten ist, die neue Wurzel des Baums wird.\n\n$$\\mathrm{Node}.\\mathrm{splay}: \\mathrm{Payload} \\to \\mathrm{Node}$$\n\nIst die angegebene Nutzlast im Baum, so ist gerade der Knoten, der sie enthält, die neue Wurzel.\n\nWir arbeiten mit dem *Top-Down*-Ansatz, bei dem wir von der Wurzel aus so lange Knoten beiseite legen, bis der zu splayende Knoten die Wurzel darstellt, und diese beiseite gelegten Knoten wieder unterordnen. Dieser Ansatz wurde in der ursprünglichen Veröffentlichung von Sleator und Tarjan bereits beschrieben (S. 667ff.), aber erst [1987 von Mäkinen als in Komplexität etwas begrenzter analysiert](https://link.springer.com/article/10.1007%2FBF01933728 \"E. Mäkinen (1987): On top-down splaying. BIT Numerical Mathematics, 27 330-339 (SpringerLink)\").\n\nBeim Top-Down-Splaying werden zusätzlich zum Baum, der bearbeitet wird, die zwei Bäume $L, R$ betrachtet. Wenn Knoten beiseite gelegt werden, so werden sie in $L$ und $R$ abgelegt. In $L$ kommen die Elemente, die kleiner als der zu splayende Knoten sind, in $R$ die, die größer sind. Dabei bleiben der rechteste Knoten von $L$ und der linkeste Knoten von $R$ immer frei, sodass dort leicht angefügt werden kann. Wir definieren dafür zunächst $\\mathrm{insert\\_left}$ und $\\mathrm{insert\\_right}$, die keine neuen Nutzlasten, sondern existierende Knoten ganz links (für $R$) bzw. rechts (für $L$) außen an den Baum anfügen. Dabei ist der Baum selbst der erste Parameter, der neue Knoten der zweite. Die formale Definition ist rekursiv.\n\n$$\\mathrm{insert\\_left}: \\mathrm{Node} \\times \\mathrm{Node} \\to \\mathrm{Node}$$\n$$\\begin{aligned}\n\\mathrm{Nil}.\\mathrm{insert\\_left}(\\mathrm{Node}(a, b, c)) &= \\mathrm{Node}(a, b, c) \\\\\n\\mathrm{Node}(x, y, z).\\mathrm{insert\\_left}(\\mathrm{Nil}) &= \\mathrm{Node}(x, y, z) \\\\\n\\mathrm{Node}(x, y, z).\\mathrm{insert\\_left}(\\mathrm{Node}(a, b, c)) &= \\mathrm{Node}(x, y.\\mathrm{insert\\_left}(\\mathrm{Node}(a, b, c)), z)\n\\end{aligned}$$\n\n$$\\mathrm{insert\\_right}: \\mathrm{Node} \\times \\mathrm{Node} \\to \\mathrm{Node}$$\n$$\\begin{aligned}\n\\mathrm{Nil}.\\mathrm{insert\\_right}(\\mathrm{Node}(a, b, c)) &= \\mathrm{Node}(a, b, c) \\\\\n\\mathrm{Node}(x, y, z).\\mathrm{insert\\_right}(\\mathrm{Nil}) &= \\mathrm{Node}(x, y, z) \\\\\n\\mathrm{Node}(x, y, z).\\mathrm{insert\\_right}(\\mathrm{Node}(a, b, c)) &= \\mathrm{Node}(x, y, z.\\mathrm{insert\\_right}(\\mathrm{Node}(a, b, c)))\n\\end{aligned}$$\n\nUm das Splayen im Kontext dieser temporären Bäume definieren zu können, definieren wir die Funktion $\\mathrm{splay\\_step}$, die einen Splay-Schritt für eine Nutzlast durchführt, und dabei auf einem Tripel aus $L$, dem Baum selbst, und $R$ operiert, und dieses Tripel i. A. modifiziert zurückgibt.\n\n$$\\langle\\mathrm{Node}, \\mathrm{Node}, \\mathrm{Node}\\rangle.\\mathrm{splay\\_step}: \\mathrm{Payload} \\to \\langle\\mathrm{Node}, \\mathrm{Node}, \\mathrm{Node}\\rangle$$\n\nDie $\\mathrm{splay}$-Funktion muss nur leere Bäume $L, R$ konstruieren und den ersten $\\mathrm{splay\\_step}$ starten. Die übrigen Schritte werden von dort aus rekursiv aufgerufen. Sind alle $\\mathrm{splay\\_step}$s getan, gibt sie den mittleren Baum zurück.\n\n$$\\langle\\mathrm{Nil}, \\mathrm{Node}(x, y, z), \\mathrm{Nil}\\rangle.\\mathrm{splay\\_step}(k) = \\langle\\mathrm{Nil}, \\mathrm{Node}(a, b, c), \\mathrm{Nil}\\rangle \\Rightarrow \\mathrm{Node}(x, y, z).\\mathrm{splay}(k) = \\mathrm{Node}(a, b, c)$$\n\nIn jedem Schritt werden zwei Knoten beiseite gelegt. Sollte der Knoten mit der gesuchten Nutzlast auf der zweitobersten Ebene sein, so wird natürlich nur noch ein Knoten beiseite gelegt. Diesen Schritt behandeln wir zuerst. Ist der Knoten dabei das linke Kind seines Elternknotens, so bezeichnen wir diesen Schritt als *Zig*.\n\n### Zig und Zag\n\nDie folgende Grafik illustriert den Schritt. Die Dreiecke $L, R$ stehen hier für ganze Bäume, und die ausgehenden Pfeile stehen für die rechteste bzw. linkeste Stelle in diesen Bäumen.",
"_____no_output_____"
]
],
[
[
"# flake8: noqa\n# blocks solely for drawing are exempt because I consider\n# semicolons and longer lines more beneficial to the reading flow there\nx1 = Node(\"x\", None, None); y1 = Node(\"y\", None, None); z1 = Node(\"z\", None, None)\na1 = Node(\"a\", x1, y1); b1 = Node(\"b\", a1, z1)\nl1 = TempTree(\"L\", None, False); r1 = TempTree(\"R\", None, True)\n\nx2 = Node(\"x\", None, None); y2 = Node(\"y\", None, None); z2 = Node(\"z\", None, None)\na2 = Node(\"a\", x2, y2); b2 = Node(\"b\", None, z2)\nl2 = TempTree(\"L\", None, False); r2 = TempTree(\"R\", b2, True)\n\ndot = l1.graph(b1, r1, Method(\"zig()\"), l2, a2, r2)\nfor subtree in x1, y1, z1, x2, y2, z2:\n dot.node(str(id(subtree)), shape=\"triangle\")\ndot",
"_____no_output_____"
]
],
[
[
"Wir bewegen den Knoten $a$ an die Wurzel, wobei $b$ gemeinsam mit seinem rechten Teilbaum $z$ links unten an $R$ angefügt wird. Die Ordnung bleibt erhalten, da $b > a$ ist, und da alle Elemente, die zuvor schon in $R$ waren, auch größer als $b$ sind.\n\nFormal definieren wir\n\n$$\\langle L, \\mathrm{Node}(b, \\mathrm{Node}(a, x, y), z), R\\rangle.\\mathrm{splay\\_step}(a) = \\langle L, \\mathrm{Node}(a, x, y), R.\\mathrm{insert\\_left}(\\mathrm{Node}(b, \\mathrm{Nil}, z)\\rangle.\\mathrm{splay\\_step}(a)$$\n\nZu beachten ist, dass wir dabei auf das Ergebnis wieder einen Splayschritt durchführen. Wir haben zwar jetzt schon die gesuchte Nutzlast an der Wurzel, wollen aber das, was nach dem letzten regulären Schritt zu tun ist, nur einmal definieren. Hinzu kommt, dass dies für die anderen Optionen, Splay-Schritte durchzuführen, im Allgemeinen nicht der Fall ist, dann wird der Knoten noch nicht an der Wurzel sein. In der Implementierung wird später immerzu überprüft werden, ob noch ein Schritt benötigt wird, und dann der richtige Schritt ausgeführt.\n\nDie Implementierung in Python handhaben wir ein wenig anders. Die als intern markierte Methode `_zig` bekommt Zeiger auf die momentanen Extrema in $L$ und $R$, schreibt das Objekt selbst in $R$ fest, und überschreibt die Referenz auf sich selbst dann mit dem linken Knoten unter sich. So vermeiden wir das teure Konstruieren neuer Objekte. Die neuen Extrema sowie der neue Zeiger auf den betrachteten Knoten werden zurückgegeben (erst $L$, dann der Hauptbaum, dann $R$).",
"_____no_output_____"
]
],
[
[
"def _zig(self, max_less, min_greater):\n # self = Node(b, Node(a, x, y), z)\n min_greater.left = self\n new_min_greater = self\n # new_min_greater = Node(b, Node(a, x, y), z)\n new_self = self.left\n # new_self = Node(a, x, y)\n new_min_greater.left = None\n # new_min_greater = Node(b, Nil, z)\n return max_less, new_self, new_min_greater\n\nNode._zig = _zig\ndel _zig",
"_____no_output_____"
]
],
[
[
"Bei *Zag* ist der zu splayende Knoten das rechte Kind der Wurzel:",
"_____no_output_____"
]
],
[
[
"# flake8: noqa\nx1 = Node(\"x\", None, None); y1 = Node(\"y\", None, None); z1 = Node(\"z\", None, None)\na1 = Node(\"a\", y1, z1); b1 = Node(\"b\", x1, a1)\nl1 = TempTree(\"L\", None, False); r1 = TempTree(\"R\", None, True)\n\nx2 = Node(\"x\", None, None); y2 = Node(\"y\", None, None); z2 = Node(\"z\", None, None)\na2 = Node(\"a\", y2, z2); b2 = Node(\"b\", x2, None)\nl2 = TempTree(\"L\", b2, False); r2 = TempTree(\"R\", None, True)\n\ndot = l1.graph(b1, r1, Method(\"zag()\"), l2, a2, r2)\nfor subtree in x1, y1, z1, x2, y2, z2:\n dot.node(str(id(subtree)), shape=\"triangle\")\ndot",
"_____no_output_____"
]
],
[
[
"Formale Definition und Implementierung sind ähnlich.\n\n$$\\langle L, \\mathrm{Node}(b, x, \\mathrm{Node}(a, y, z)), R\\rangle.\\mathrm{splay\\_step}(a) = \\langle L.\\mathrm{insert\\_right}(\\mathrm{Node}(b, x, \\mathrm{Nil})), \\mathrm{Node}(a, y, z), R\\rangle.\\mathrm{splay\\_step}(a)$$",
"_____no_output_____"
]
],
[
[
"def _zag(self, max_less, min_greater):\n # self = Node(b, x, Node(a, y, z))\n max_less.right = self\n new_max_less = self\n # new_min_greater = Node(b, x, Node(a, y, z))\n new_self = self.right\n # new_self = Node(a, y, z)\n new_max_less.right = None\n # new_min_greater = Node(b, x, Nil)\n return new_max_less, new_self, min_greater\n\nNode._zag = _zag\ndel _zag",
"_____no_output_____"
]
],
[
[
"### Zig-Zig und Zag-Zag\n\nAls nächstes behandeln wir den Fall, dass der Knoten wenigstens zwei Ebenen von der Wurzel entfernt ist, und sowohl der Knoten als auch sein Elternknoten ein linkes Kind sind. Die Operation, die auf diese Ausgangssituation anzuwenden ist, bezeichnen wir als *Zig-Zig*. Diese Operation sieht so aus:",
"_____no_output_____"
]
],
[
[
"# flake8: noqa\nw1 = Node(\"w\", None, None); x1 = Node(\"x\", None, None); y1 = Node(\"y\", None, None); z1 = Node(\"z\", None, None)\na1 = Node(\"a\", w1, x1); b1 = Node(\"b\", a1, y1); c1 = Node(\"c\", b1, z1)\nl1 = TempTree(\"L\", None, False); r1 = TempTree(\"R\", None, True)\n\nw2 = Node(\"w\", None, None); x2 = Node(\"x\", None, None); y2 = Node(\"y\", None, None); z2 = Node(\"z\", None, None)\na2 = Node(\"a\", w2, x2); c2 = Node(\"c\", y2, z2); b2 = Node(\"b\", None, c2)\nl2 = TempTree(\"L\", None, False); r2 = TempTree(\"R\", b2, True)\n\ndot = l1.graph(c1, r1, Method(\"zig_zig()\"), l2, a2, r2)\nfor subtree in w1, x1, y1, z1, w2, x2, y2, z2:\n dot.node(str(id(subtree)), shape=\"triangle\")\ndot",
"_____no_output_____"
]
],
[
[
"Wir bewegen den Knoten $a$ an die Wurzel. $b$ wird mit $c$ als rechtes Kind an $R$ angefügt, wobei $c$ als seinen linken Teilbaum $y$ hat. Die Ordnungsbedingung bleibt erhalten, da $c > b > a$ und $y > c > b$ ist.\n\nWir definieren\n\n$$k < b \\Rightarrow \\langle L, \\mathrm{Node}(c, \\mathrm{Node}(b, \\mathrm{Node}(a, w, x), y), z), R\\rangle.\\mathrm{splay\\_step}(k) =$$\n$$= \\langle L, \\mathrm{Node}(a, w, x), R.\\mathrm{insert\\_left}(\\mathrm{Node}(b, \\mathrm{Node}(c, y, z)))\\rangle.\\mathrm{splay\\_step}(k)$$\n\nWir schreiben in der Implementierung wieder nur die nötigen Referenzen um. Dies sind einfach einige zusätzliche Schritte im Vergleich zu `_zig` und `_zag`.",
"_____no_output_____"
]
],
[
[
"def _zig_zig(self, max_less, min_greater):\n # self = Node(c, Node(b, Node(a, w, x), y), z)\n min_greater.left = self.left\n new_min_greater = self.left\n # new min_greater = Node(b, Node(a, w, x), y)\n new_self = new_min_greater.left\n # new_self = Node(a, w, x)\n self.left = new_min_greater.right\n # self = Node(c, y, z)\n new_min_greater.left = None\n # new_min_greater = Node(b, Nil, y)\n new_min_greater.right = self\n # new_min_greater = Node(b, Nil, Node(c, y, z))\n return max_less, new_self, new_min_greater\n\nNode._zig_zig = _zig_zig\ndel _zig_zig",
"_____no_output_____"
]
],
[
[
"Wir bezeichnen die gleiche Situation mit rechtem Kind und rechtem Enkel als *Zag-Zag*:",
"_____no_output_____"
]
],
[
[
"# flake8: noqa\nw1 = Node(\"w\", None, None); x1 = Node(\"x\", None, None); y1 = Node(\"y\", None, None); z1 = Node(\"z\", None, None)\na1 = Node(\"a\", y1, z1); b1 = Node(\"b\", x1, a1); c1 = Node(\"c\", w1, b1)\nl1 = TempTree(\"L\", None, False); r1 = TempTree(\"R\", None, True)\n\nw2 = Node(\"w\", None, None); x2 = Node(\"x\", None, None); y2 = Node(\"y\", None, None); z2 = Node(\"z\", None, None)\na2 = Node(\"a\", y2, z2); c2 = Node(\"c\", w2, x2); b2 = Node(\"b\", c2, None)\nl2 = TempTree(\"L\", b2, False); r2 = TempTree(\"R\", None, True)\n\ndot = l1.graph(c1, r1, Method(\"zag_zag()\"), l2, a2, r2)\nfor subtree in w1, x1, y1, z1, w2, x2, y2, z2:\n dot.node(str(id(subtree)), shape=\"triangle\")\ndot",
"_____no_output_____"
]
],
[
[
"Der Splay-Schritt ist ähnlich definiert und implementiert.\n\n$$k > b \\Rightarrow \\langle L, \\mathrm{Node}(c, w, \\mathrm{Node}(b, x, \\mathrm{Node}(a, y, z))), R\\rangle.\\mathrm{splay\\_step}(k) = $$\n$$= \\langle L.\\mathrm{insert\\_right}(\\mathrm{Node}(b, \\mathrm{Node}(c, w, x), \\mathrm{Nil})), \\mathrm{Node}(a, y, z), R\\rangle.\\mathrm{splay\\_step}(k)$$",
"_____no_output_____"
]
],
[
[
"def _zag_zag(self, max_less, min_greater):\n # self = Node(c, w, Node(b, x, Node(a, y, z)))\n max_less.right = self.right\n new_max_less = self.right\n # new_max_less = Node(b, x, Node(a, y, z))\n new_self = new_max_less.right\n # new_self = Node(a, y, z)\n self.right = new_max_less.left\n # self = Node(c, w, x)\n new_max_less.right = None\n # new_max_less = Node(b, x, Nil)\n new_max_less.left = self\n # new_max_less = Node(b, Node(c, w, x), Nil)\n return new_max_less, new_self, min_greater\n\nNode._zag_zag = _zag_zag\ndel _zag_zag",
"_____no_output_____"
]
],
[
[
"### Zig-Zag und Zag-Zig\n\nZuletzt behandeln wir den Fall, dass der Elternknoten ein linkes Kind, der Knoten selbst aber ein rechtes Kind ist. Die Operation auf diese Situation nennen wir *Zig-Zag*. Für diese Operation brauchen wir erstmalig sowohl $L$ als auch $R$:",
"_____no_output_____"
]
],
[
[
"# flake8: noqa\nw1 = Node(\"w\", None, None); x1 = Node(\"x\", None, None)\ny1 = Node(\"y\", None, None); z1 = Node(\"z\", None, None)\na1 = Node(\"a\", x1, y1); b1 = Node(\"b\", w1, a1); c1 = Node(\"c\", b1, z1)\nl1 = TempTree(\"L\", None, False); r1 = TempTree(\"R\", None, True)\n\nw2 = Node(\"w\", None, None); x2 = Node(\"x\", None, None)\ny2 = Node(\"y\", None, None); z2 = Node(\"z\", None, None)\na2 = Node(\"a\", x2, y2); b2 = Node(\"b\", w2, None); c2 = Node(\"c\", None, z2)\nl2 = TempTree(\"L\", b2, False); r2 = TempTree(\"R\", c2, True)\n\ndot = l1.graph(c1, r1, Method(\"zig_zag()\"), l2, a2, r2)\nfor subtree in w1, x1, y1, z1, w2, x2, y2, z2:\n dot.node(str(id(subtree)), shape=\"triangle\")\ndot",
"_____no_output_____"
]
],
[
[
"Wir bewegen den Knoten $a$ an die Stelle von $c$, dabei werden $b$ und $c$ respektive an $L$ und $R$ angefügt, die ja jeweils kleiner bzw. größer als $a$ sind.\n\nWir definieren\n\n$$b < k < c \\Rightarrow \\langle L, \\mathrm{Node}(c, \\mathrm{Node}(b, w, \\mathrm{Node}(a, x, y)), z), R\\rangle.\\mathrm{splay\\_step}(k) =$$\n$$= \\langle L.\\mathrm{insert\\_right}(\\mathrm{Node}(b, w, \\mathrm{Nil})), \\mathrm{Node}(a, x, y), R.\\mathrm{insert\\_left}(\\mathrm{Node}(c, \\mathrm{Nil}, z))\\rangle.\\mathrm{splay\\_step}(k)$$\n\nIn Code haben wir",
"_____no_output_____"
]
],
[
[
"def _zig_zag(self, max_less, min_greater):\n # self = Node(c, Node(b, w, Node(a, x, y)), z)\n max_less.right = self.left\n new_max_less = self.left\n # new_max_less = Node(b, w, Node(a, x, y))\n min_greater.left = self\n new_min_greater = self\n # new_min_greater = Node(c, Node(b, w, Node(a, x, y)), z)\n new_self = self.left.right\n # new_self = Node(a, x, y)\n new_max_less.right = None\n # new_max_less = Node(b, w, Nil)\n new_min_greater.left = None\n # new_min_greater = Node(c, Nil, z)\n return new_max_less, new_self, new_min_greater\n\nNode._zig_zag = _zig_zag\ndel _zig_zag",
"_____no_output_____"
]
],
[
[
"In umgekehrter Reihenfolge, d.h. der Elternknoten ist das rechte Kind, der Knoten das linke Kind, haben wir die Operation *Zag-Zig* mit",
"_____no_output_____"
]
],
[
[
"# flake8: noqa\nw1 = Node(\"w\", None, None); x1 = Node(\"x\", None, None)\ny1 = Node(\"y\", None, None); z1 = Node(\"z\", None, None)\na1 = Node(\"a\", x1, y1); b1 = Node(\"b\", a1, z1); c1 = Node(\"c\", w1, b1)\nl1 = TempTree(\"L\", None, False); r1 = TempTree(\"R\", None, True)\n\nw2 = Node(\"w\", None, None); x2 = Node(\"x\", None, None)\ny2 = Node(\"y\", None, None); z2 = Node(\"z\", None, None)\na2 = Node(\"a\", x2, y2); b2 = Node(\"b\", None, z2); c2 = Node(\"c\", w2, None)\nl2 = TempTree(\"L\", c2, False); r2 = TempTree(\"R\", b2, True)\n\ndot = l1.graph(c1, r1, Method(\"zag_zig()\"), l2, a2, r2)\nfor subtree in w1, x1, y1, z1, w2, x2, y2, z2:\n dot.node(str(id(subtree)), shape=\"triangle\")\ndot",
"_____no_output_____"
]
],
[
[
"Formal schreiben wir\n\n$$c < k < b \\Rightarrow \\langle L, \\mathrm{Node}(c, w, \\mathrm{Node}(b, \\mathrm{Node}(a, x, y), z)), R\\rangle.\\mathrm{splay\\_step}(k) =$$\n$$= \\langle L.\\mathrm{insert\\_right}(\\mathrm{Node}(c, w, \\mathrm{Nil})), \\mathrm{Node}(a, x, y), R.\\mathrm{insert\\_left}(\\mathrm{Node}(b, \\mathrm{Nil}, z))\\rangle.\\mathrm{splay\\_step}(k)$$\n\nund in Code",
"_____no_output_____"
]
],
[
[
"def _zag_zig(self, max_less, min_greater):\n # self = Node(c, w, Node(b, Node(a, x, y), z))\n max_less.right = self\n new_max_less = self\n # new_max_less = Node(c, w, Node(b, Node(a, x, y), z))\n min_greater.left = self.right\n new_min_greater = self.right\n # new_min_greater = Node(b, Node(a, x, y), z)\n new_self = self.right.left\n # new_self = Node(a, x, y)\n new_max_less.right = None\n # new_max_less = Node(c, w, Nil)\n new_min_greater.left = None\n # new_min_greater = Node(b, Nil, z)\n return new_max_less, new_self, new_min_greater\n\nNode._zag_zig = _zag_zig\ndel _zag_zig",
"_____no_output_____"
]
],
[
[
"### Vergleich beliebiger Nutzlasten\n\nWir müssen, um später Mengen, die Elemente unterschiedlicher Typen enthalten, zu unterstützen, dazu in der Lage sein, beliebige Nutzlasten zu vergleichen. Dazu versuchen wir den direkten Vergleich, und vergleichen, wenn das nicht funktioniert, am Klassennamen. So kommen wertgleiche Fließkomma- und Ganzzahlen nur einmal in die Menge (dies ist auch bei Python-Mengen so). Die Methoden, die wir dazu schreiben, geben wir der Klasse `Node` mit, um so wenig wie möglich in den Namespace zu laden, und somit die Einsetzbarkeit zu erhöhen. `_arb_gt(x, y)` überprüft, ob im Sinne dieses Vergleichs `x` $>$ `y` ist.",
"_____no_output_____"
]
],
[
[
"def _arb_gt(self, x, y):\n try:\n return y < x\n except TypeError:\n return type(x).__name__ > type(y).__name__\n\nNode._arb_gt = _arb_gt\ndel _arb_gt",
"_____no_output_____"
]
],
[
[
"`_arb_lt(x, y)` überprüft `x` $<$ `y`…",
"_____no_output_____"
]
],
[
[
"def _arb_lt(self, x, y):\n try:\n return x < y\n except TypeError:\n return type(x).__name__ < type(y).__name__\n\nNode._arb_lt = _arb_lt\ndel _arb_lt",
"_____no_output_____"
]
],
[
[
"…und `_arb_eq(x, y)` überprüft `x == y`.",
"_____no_output_____"
]
],
[
[
"def _arb_eq(self, x, y):\n try:\n return x == y\n except TypeError:\n return False\n\nNode._arb_eq = _arb_eq\ndel _arb_eq",
"_____no_output_____"
]
],
[
[
"### Verkettung der Schritte\n\nDer formalen Definition fehlt noch der Basisfall, wenn die Wurzel die zu splayende Nutzlast enthält. Wir fügen dann $L$ und $R$ an die neue Wurzel an – die Knoten in $L$ und $R$ waren ja gerade eben kleiner bzw. größer als die Wurzel. Wir fügen dabei die Teilbäume, die die Wurzel jetzt noch hat, in $L$ und $R$ ein; links von der Wurzel sind alle Nutzlasten, die größer als $L$ sind, und rechts sind alle, die kleiner als $R$ sind.",
"_____no_output_____"
]
],
[
[
"# flake8: noqa\nx1 = Node(\"x\", None, None); y1 = Node(\"y\", None, None); a1 = Node(\"a\", x1, y1)\nl1 = TempTree(\"L\", None, False); r1 = TempTree(\"R\", None, True)\n\nx2 = Node(\"x\", None, None); y2 = Node(\"y\", None, None)\nl2 = TempTree(\"L\", x2, False); r2 = TempTree(\"R\", y2, True)\na2 = Node(\"a\", l2, r2)\n\ndot = l1.graph(a1, r1, Method(\"finish()\"), a2)\nfor subtree in x1, y1, x2, y2:\n dot.node(str(id(subtree)), shape=\"triangle\")\ndot",
"_____no_output_____"
]
],
[
[
"Wir definieren:\n\n$$\\langle L, \\mathrm{Node}(a, x, y), R\\rangle.\\mathrm{splay\\_step}(a) = \\langle\\mathrm{Nil}, \\mathrm{Node}(a, L.\\mathrm{insert\\_right}(x), R.\\mathrm{insert\\_left}(y)), \\mathrm{Nil}\\rangle$$\n\nWir müssen allerdings auch den Basisfall betrachten, dass wir feststellen, dass der Knoten nicht vorhanden ist, weil da, wo der Knoten stünde, keine Knoten mehr sind. In diesem Fall müssen wir nur noch den anderen Teilbaum anfügen.\n\n$$\\begin{aligned}\nk < a &\\Rightarrow \\langle L, \\mathrm{Node}(a, \\mathrm{Nil}, y), R\\rangle.\\mathrm{splay\\_step}(k) = \\langle\\mathrm{Nil}, \\mathrm{Node}(a, L, R.\\mathrm{insert\\_left}(y)), \\mathrm{Nil}\\rangle \\\\\nk > a &\\Rightarrow \\langle L, \\mathrm{Node}(a, x, \\mathrm{Nil}), R\\rangle.\\mathrm{splay\\_step}(k) = \\langle\\mathrm{Nil}, \\mathrm{Node}(a, L.\\mathrm{insert\\_right}(x), R), \\mathrm{Nil}\\rangle\n\\end{aligned}$$\n\nIn der Implementierung wählen wir so lange den angemessenen Schritt aus und führen ihn durch, bis wir an den gesuchten Knoten kommen oder erfolglos an ein Blatt stoßen. So vermeiden wir Funktionsaufrufe und die Grenzen von Rekursionstiefe. Falls der gesuchte Knoten noch genau eine Ebene entfernt ist, so führen wir Zig bzw. Zag durch. In diesem Fall unterscheiden wir:\n\n|Linkes Kind|Rechtes Kind|\n|:----------|:-----------|\n|Zig |Zag |\n\nFalls er noch mindestens zwei Ebenen entfernt ist, so unterscheiden wir:\n\n|Kind vs. Enkel |Linkes Kind|Rechtes Kind|\n|----------------:|:----------|:-----------|\n|**Linker Enkel** |Zig-Zig |Zag-Zig |\n|**Rechter Enkel**|Zig-Zag |Zag-Zag |\n\nUm diese Implementierung später besser mit anderen rekursiv implementierten Datenstrukturen vergleichen zu können, implementieren wir den `_splay_step` jetzt auch rekursiv:",
"_____no_output_____"
]
],
[
[
"def _splay_step(self, max_less, min_greater, payload):\n if self._arb_lt(payload, self.payload):\n if self.left is None:\n return max_less, self, min_greater\n if self._arb_lt(payload, self.left.payload) \\\n and self.left.left is not None:\n new_max_less, new_self, new_min_greater = \\\n self._zig_zig(max_less, min_greater)\n return new_self._splay_step(new_max_less, new_min_greater, payload)\n if self._arb_gt(payload, self.left.payload) \\\n and self.left.right is not None:\n new_max_less, new_self, new_min_greater = \\\n self._zig_zag(max_less, min_greater)\n return new_self._splay_step(new_max_less, new_min_greater, payload)\n return self._zig(max_less, min_greater)\n if self._arb_gt(payload, self.payload):\n if self.right is None:\n return max_less, self, min_greater\n if self._arb_gt(payload, self.right.payload) \\\n and self.right.right is not None:\n new_max_less, new_self, new_min_greater = \\\n self._zag_zag(max_less, min_greater)\n return new_self._splay_step(new_max_less, new_min_greater, payload)\n if self._arb_lt(payload, self.right.payload) \\\n and self.right.left is not None:\n new_max_less, new_self, new_min_greater = \\\n self._zag_zig(max_less, min_greater)\n return new_self._splay_step(new_max_less, new_min_greater, payload)\n return self._zag(max_less, min_greater)\n return max_less, self, min_greater\n\nNode._splay_step = _splay_step\ndel _splay_step",
"_____no_output_____"
]
],
[
[
"In der Zusammensetzung `_splay` fügen wir noch die Teilbäume von der neuen Wurzel an $L, R$ an und setzen $L, R$ als Teilbäume dieser neuen Wurzel. Wir benutzen statt $L, R$ nur einen Baum `set_aside`, bei dem wir auf der entsprechenden Seite anfügen.",
"_____no_output_____"
]
],
[
[
"def _splay(self, payload):\n set_aside = Node(None, None, None)\n max_less, new_self, min_greater = \\\n self._splay_step(set_aside, set_aside, payload)\n max_less.right = new_self.left\n min_greater.left = new_self.right\n new_self.left = set_aside.right\n new_self.right = set_aside.left\n return new_self\n\nNode._splay = _splay\ndel _splay",
"_____no_output_____"
]
],
[
[
"Das nächste Beispiel zeigt, wie ein Splay aus einem schlechtestmöglich balancierten Baum einen deutlich besser balancierten Baum machen kann:",
"_____no_output_____"
]
],
[
[
"# flake8: noqa\na1 = Node(\"a\", None, None); c1 = Node(\"c\", None, None); e1 = Node(\"e\", None, None); g1 = Node(\"g\", None, None)\nj1 = Node(\"j\", None, None); l1 = Node(\"l\", None, None); n1 = Node(\"n\", None, None); p1 = Node(\"p\", None, None)\nb1 = Node(\"b\", a1, c1); d1 = Node(\"d\", b1, e1); f1 = Node(\"f\", d1, g1); h1 = Node(\"h\", f1, j1)\nk1 = Node(\"k\", h1, l1); m1 = Node(\"m\", k1, n1); o1 = Node(\"o\", m1, p1)\n\na2 = Node(\"a\", None, None); c2 = Node(\"c\", None, None); e2 = Node(\"e\", None, None); g2 = Node(\"g\", None, None)\nj2 = Node(\"j\", None, None); l2 = Node(\"l\", None, None); n2 = Node(\"n\", None, None); p2 = Node(\"p\", None, None)\nb2 = Node(\"b\", a2, c2); d2 = Node(\"d\", b2, e2); f2 = Node(\"f\", d2, g2); h2 = Node(\"h\", f2, j2)\nk2 = Node(\"k\", h2, l2); m2 = Node(\"m\", k2, n2); o2 = Node(\"o\", m2, p2)\n\ndot = o1.graph(Method(\"splay()\"), o2._splay(\"b\"))\nfor subtree in a1, c1, e1, g1, j1, l1, n1, p1, a2, c2, e2, g2, j2, l2, n2, p2:\n dot.node(str(id(subtree)), shape=\"triangle\")\ndot",
"_____no_output_____"
]
],
[
[
"Ein anderes Beispiel enthält alle Schritte außer Zag:",
"_____no_output_____"
]
],
[
[
"# flake8: noqa\nj1 = Node(\"j\", None, None); l1 = Node(\"l\", None, None); n1 = Node(\"n\", None, None); p1 = Node(\"p\", None, None)\ng1 = Node(\"g\", None, None); e1 = Node(\"e\", None, None); r1 = Node(\"r\", None, None); c1 = Node(\"c\", None, None)\na1 = Node(\"a\", None, None); t1 = Node(\"t\", None, None); v1 = Node(\"v\", None, None)\nk1 = Node(\"k\", j1, l1); m1 = Node(\"m\", k1, n1); o1 = Node(\"o\", m1, p1); h1 = Node(\"h\", g1, o1)\nf1 = Node(\"f\", e1, h1); q1 = Node(\"q\", f1, r1); d1 = Node(\"d\", c1, q1); b1 = Node(\"b\", a1, d1)\ns1 = Node(\"s\", b1, t1); u1 = Node(\"u\", s1, v1)\n\nj2 = Node(\"j\", None, None); l2 = Node(\"l\", None, None); n2 = Node(\"n\", None, None); p2 = Node(\"p\", None, None)\ng2 = Node(\"g\", None, None); e2 = Node(\"e\", None, None); r2 = Node(\"r\", None, None); c2 = Node(\"c\", None, None)\na2 = Node(\"a\", None, None); t2 = Node(\"t\", None, None); v2 = Node(\"v\", None, None)\nk2 = Node(\"k\", j2, l2); m2 = Node(\"m\", k2, n2); o2 = Node(\"o\", m2, p2); h2 = Node(\"h\", g2, o2)\nf2 = Node(\"f\", e2, h2); q2 = Node(\"q\", f2, r2); d2 = Node(\"d\", c2, q2); b2 = Node(\"b\", a2, d2)\ns2 = Node(\"s\", b2, t2); u2 = Node(\"u\", s2, v2)\n\ndot = u1.graph(Method(\"splay()\"), u2._splay(\"k\"))\nfor subtree in a1, c1, e1, g1, j1, l1, n1, p1, r1, t1, v1, a2, c2, e2, g2, j2, l2, n2, p2, r2, t2, u2:\n dot.node(str(id(subtree)), shape=\"triangle\")\ndot",
"_____no_output_____"
]
],
[
[
"Wir betrachten zuletzt das folgende Beispiel, um Zag abgedeckt zu haben:",
"_____no_output_____"
]
],
[
[
"# flake8: noqa\na1 = Node(\"a\", None, None); c1 = Node(\"c\", None, None); e1 = Node(\"e\", None, None)\nd1 = Node(\"d\", c1, e1); b1 = Node(\"b\", a1, d1)\n\na2 = Node(\"a\", None, None); c2 = Node(\"c\", None, None); e2 = Node(\"e\", None, None)\nd2 = Node(\"d\", c2, e2); b2 = Node(\"b\", a2, d2)\n\ndot = b1.graph(Method(\"splay()\"), b2._splay(\"d\"))\nfor subtree in a1, c1, e1, a2, c2, e2:\n dot.node(str(id(subtree)), shape=\"triangle\")\ndot",
"_____no_output_____"
]
],
[
[
"## Standardoperationen\n\nWir definieren für den Splay Tree als nächstes die grundlegenden Operationen auf Bäume: Einfügen, Löschen, auf das Vorhandensein eines Elements überprüfen, und auf das Leersein überprüfen.\n\n### Einfügen\n\nWir definieren das Einfügen eines Elementes, bei dem in einen bestehenden Baum eine neue Nutzlast eingefügt wird, wodurch sich der Baum i.A. verändert.\n\n$$\\mathrm{Node}.\\mathrm{insert}: \\mathrm{Payload} \\to \\mathrm{Node}$$\n\nBeim Einfügen traversieren wir nicht, wie bei den meisten Bäumen und auch bei der Verwendung des Bottom-Up-Splaying-Ansatzes, den Baum hinunter, sondern splayen an dem Element, das wir einfügen wollen. Es kann sein, dass die Wurzel des gesplayten Baums schon das einzufügende Element ist, in diesem Fall sind wir fertig. Wir bezeichnen den Baum mit $B$ und das neue Element mit $k$. Ist der Baum noch leer, so brauchen wir nur die Wurzel setzen:\n\n$$\\begin{aligned}\nB = \\mathrm{Nil} &\\Rightarrow B.\\mathrm{insert}(k) = \\mathrm{Node}(k, \\mathrm{Nil}, \\mathrm{Nil}) \\\\\nB.\\mathrm{splay}(k) = \\mathrm{Node}(k, x, y) &\\Rightarrow B.\\mathrm{insert}(k) = B.\\mathrm{splay}(k)\n\\end{aligned}$$\n\nAndernfalls ist die neue Wurzel genau das Element, das im ganzen Baum das nächstgrößere oder nächstkleinere als das einzufügende Element ist, oder formaler:\n\n$$B.\\mathrm{splay}(k) = \\mathrm{Node}(x, y, z) \\Rightarrow x = k \\lor x = \\max(\\{\\kappa \\in B: \\kappa < k\\}) \\lor x = \\min(\\{\\kappa \\in B: \\kappa > k\\})$$\n\nIn diesen beiden Fällen setzen wir das einzufügende Element $k$ als Wurzel. Im Fall, dass $k$ kleiner als die Wurzel des gesplayten existierenden Baums $B' = \\mathrm{Node}(x, y, z)$ ist, sind trotzdem alle Elemente im linken Teilbaum $y$ von $B'$ kleiner als $k$ und wir setzen diesen als linken Teilbaum von $k$. Wir setzen die Wurzel $x$ von $B'$ als rechten Teilbaum, da sie, wie auch alle Elemente des rechten Teilbaums $z$ von $B'$ größer als $k$ sind. Dabei setzen wir den linken Teilbaum von $x$ auf $\\mathrm{Nil}$.\n\n$$B.\\mathrm{splay}(k) = \\mathrm{Node}(x, y, z) \\land k < x \\Rightarrow B.\\mathrm{insert}(k) = \\mathrm{Node}(k, y, \\mathrm{Node}(x, \\mathrm{Nil}, z))$$\n\noder graphisch:",
"_____no_output_____"
]
],
[
[
"# flake8: noqa\nB = Node(\"B\", None, None); k1 = Node(\"k\", None, None)\ny2 = Node(\"y\", None, None); z2 = Node(\"z\", None, None); x2 = Node(\"x\", y2, z2); k2 = Node(\"k\", None, None)\ny3 = Node(\"y\", None, None); z3 = Node(\"z\", None, None); x3 = Node(\"x\", None, z3); k3 = Node(\"k\", y3, x3)\n\ndot = k1.graph(B, Method(\"B.splay(k)\"), k2, x2, Method(\"x.insert(k) where y < k < x\"), k3)\nfor subtree in B, y2, z2, y3, z3:\n dot.node(str(id(subtree)), shape=\"triangle\")\ndot",
"_____no_output_____"
]
],
[
[
"Im Fall, dass $k$ größer als die Wurzel $x$ des gesplayten Baums $B' = \\mathrm{Node}(x, y, z)$ ist, sind umgekehrt alle Elemente in dessen rechten Teilbaum $z$ größer als $k$, und wir setzen die Wurzel dieses Baumes $x$ als linken Teilbaum des neuen Elements $k$, wobei dieser Knoten dann als linken Teilbaum $y$ hat, als rechten Teilbaum $\\mathrm{Nil}$.\n\n$$B.\\mathrm{splay}(k) = \\mathrm{Node}(x, y, z) \\land k > x \\Rightarrow B.\\mathrm{insert}(k) = \\mathrm{Node}(k, \\mathrm{Node}(x, y, \\mathrm{Nil}), z)$$\n\nund graphisch:",
"_____no_output_____"
]
],
[
[
"# flake8: noqa\nB = Node(\"B\", None, None); k1 = Node(\"k\", None, None)\ny2 = Node(\"y\", None, None); z2 = Node(\"z\", None, None); x2 = Node(\"x\", y2, z2); k2 = Node(\"k\", None, None)\ny3 = Node(\"y\", None, None); z3 = Node(\"z\", None, None); x3 = Node(\"x\", y3, None); k3 = Node(\"k\", x3, z3)\n\ndot = B.graph(k1, Method(\"B.splay(k)\"), x2, k2, Method(\"x.insert(k) where y < k < x\"), k3)\nfor subtree in B, y2, z2, y3, z3:\n dot.node(str(id(subtree)), shape=\"triangle\")\ndot",
"_____no_output_____"
],
[
"def insert(self, payload):\n self = self._splay(payload)\n if self._arb_eq(payload, self.payload):\n return self\n if self._arb_lt(payload, self.payload):\n tmp = self.left\n self.left = None\n return Node(payload, tmp, self)\n tmp = self.right\n self.right = None\n return Node(payload, self, tmp)\n\nNode.insert = insert\ndel insert",
"_____no_output_____"
]
],
[
[
"Für den leeren Baum brauchen wir nur das Element in einen neuen Knoten setzen. Wir definieren – unter anderem zur Betrachtung des Falls des leeren Baumes – die Klasse `SplayTree`, die das Management des leeren Baums wie auch der Tatsache, dass sich bei einem Splay die Wurzel ändert, nach außen vereinfacht.",
"_____no_output_____"
]
],
[
[
"class SplayTree:\n def __init__(self):\n self.tree = None\n\n def insert(self, payload):\n if self.tree is None:\n self.tree = Node(payload, None, None)\n else:\n self.tree = self.tree.insert(payload)",
"_____no_output_____"
]
],
[
[
"Für den `SplayTree` definieren wir außerdem `graph`, um `Node.graph` zu exponieren.",
"_____no_output_____"
]
],
[
[
"def graph(self):\n if self.tree is None:\n return graphviz.Digraph()\n return self.tree.graph()\n\nSplayTree.graph = graph\ndel graph",
"_____no_output_____"
]
],
[
[
"Einige Beispiele zeigen das Einsetzen von Knoten in Splay Trees:",
"_____no_output_____"
]
],
[
[
"my_splay = SplayTree()\nmy_splay.insert(\"a\")\nmy_splay.graph()",
"_____no_output_____"
],
[
"my_splay.insert(\"c\")\nmy_splay.graph()",
"_____no_output_____"
],
[
"my_splay.insert(\"b\")\nmy_splay.graph()",
"_____no_output_____"
]
],
[
[
"### Entfernen\n\nWir definieren als nächstes das Entfernen eines Elementes, bei dem ebenfalls eine Nutzlast aus einem bestehenden Baum entfernt wird, wobei sich der Baum i.A. verändert.\n\n$$\\mathrm{Node}.\\mathrm{remove}: \\mathrm{Payload} \\to \\mathrm{Node}$$\n\nWir splayen wieder am zu entfernenden Element und haben dann einen Baum, der das zu entfernende Element als Wurzel hat. Sollte sich nach dem Splayen herausstellen, dass das Element nicht vorhanden ist, werfen wir einen `KeyError`, [da sich so auch die Mengen in Python verhalten](https://docs.python.org/3.7/library/stdtypes.html#set \"Python Software Foundation (2020): The Python Standard Library/Built-in Types/set, Python Documentation\"). In der Definition schreiben wir $\\downarrow$ für das Undefinierte. Dies tritt auch ein, wenn der Baum leer ist:\n\n$$\\begin{aligned}\nB = \\mathrm{Nil} &\\Rightarrow B.\\mathrm{remove}(k)\\downarrow \\\\\nB.\\mathrm{splay}(k) \\neq \\mathrm{Node}(k, x, y) &\\Rightarrow B.\\mathrm{remove}(k)\\downarrow\n\\end{aligned}$$\n\nAndernfalls überprüfen wir, ob ein Teilbaum des gesplayten Baums leer ist. In diesem Fall ist der neue Baum einfach der andere Teilbaum.\n\n$$\\begin{aligned}\nB.\\mathrm{splay}(k) = \\mathrm{Node}(k, \\mathrm{Nil}, x) &\\Rightarrow B.\\mathrm{remove}(k) = x \\\\\nB.\\mathrm{splay}(k) = \\mathrm{Node}(k, x, \\mathrm{Nil}) &\\Rightarrow B.\\mathrm{remove}(k) = x\n\\end{aligned}$$\n\nIst das nicht der Fall, so sorgen wir dafür, dass der rechte Teilbaum des gesplayten Baums keinen linken Teilbaum mehr hat, sodass wir den linken Teilbaum des gesplayten Baums anfügen können. Eine Grafik illustriert, was gemeint ist:",
"_____no_output_____"
]
],
[
[
"# flake8: noqa\nB = Node(\"B\", None, None)\nv1 = Node(\"v\", None, None); w1 = Node(\"w\", None, None); y1 = Node(\"y\", None, None); x1 = Node(\"x\", w1, y1); k1 = Node(\"k\", v1, x1)\nv2 = Node(\"v\", None, None); y2 = Node(\"y'\", None, None); x2 = Node(\"x'\", None, y2); k2 = Node(\"k\", v2, x2)\nv3 = Node(\"v\", None, None); y3 = Node(\"y'\", None, None); x3 = Node(\"x'\", v3, y3)\n\ndot = B.graph(Method(\"B.splay(k)\"), k1, Method(\"x.splay(k)\"), k2, Method(\"k.remove(k)\"), x3)\nfor subtree in B, v1, w1, y1, v2, y2, v3, y3:\n dot.node(str(id(subtree)), shape=\"triangle\")\ndot",
"_____no_output_____"
]
],
[
[
"Wir machen aus dem Baum $\\mathrm{Node}(x, w, y)$ den Baum $\\mathrm{Node}(x', \\mathrm{Nil}, y')$, indem wir an $k$ splayen. Da das Minimum aus $\\mathrm{Node}(x, w, y)$ größer $k$ ist, muss dann gerade dieses Minimum die Wurzel ($x'$) werden und kann keinen linken Teilbaum mehr haben.\n\n$$B.\\mathrm{splay}(k) = \\mathrm{Node}(k, v, \\mathrm{Node}(x, w, y)) \\land \\mathrm{Node}(x, w, y).\\mathrm{splay}(k) = \\mathrm{Node}(x', \\mathrm{Nil}, y') \\Rightarrow B.\\mathrm{remove}(k) = \\mathrm{Node}(x', v, y')$$\n\nFür `Node` implementieren wir:",
"_____no_output_____"
]
],
[
[
"def remove(self, payload):\n self = self._splay(payload)\n if not self._arb_eq(payload, self.payload):\n return False, self\n if self.left is None:\n return True, self.right\n if self.right is None:\n return True, self.left\n tmp = self.left\n self = self.right._splay(payload)\n self.left = tmp\n return True, self\n\nNode.remove = remove\ndel remove",
"_____no_output_____"
]
],
[
[
"Wir werfen in der Implementierung erst auf Ebene von `SplayTree` den `KeyError`, um im Baum noch aufräumen zu können. Der Nutzer könnte ja im Falle eines `KeyError`s diesen auffangen wollen und die Menge trotzdem noch benutzen wollen.",
"_____no_output_____"
]
],
[
[
"def remove(self, payload):\n if self.tree is None:\n raise KeyError(payload)\n rc, self.tree = self.tree.remove(payload)\n if not rc:\n raise KeyError(payload)\n\nSplayTree.remove = remove\ndel remove",
"_____no_output_____"
]
],
[
[
"Einige Beispiele zeigen das Entfernen von Elementen.",
"_____no_output_____"
]
],
[
[
"my_splay = SplayTree()\nfor letter in [\"a\", \"c\", \"b\"]:\n my_splay.insert(letter)\nmy_splay.graph()",
"_____no_output_____"
],
[
"my_splay.remove(\"b\")\nmy_splay.graph()",
"_____no_output_____"
],
[
"my_splay.remove(\"a\")\nmy_splay.graph()",
"_____no_output_____"
]
],
[
[
"### Finden\n\nWir definieren als nächstes das Überprüfen eines Baumes auf ein Element. In unserer Definition wird ein Tupel aus dem Vorhandensein und der neuen Wurzel zurückgegeben.\n\n$$\\mathrm{Node}.\\mathrm{contains}: \\mathrm{Payload} \\to \\langle\\mathbb{B}, \\mathrm{Node}\\rangle$$\n\nWir splayen am gesuchten Element und können schon an der Wurzel erkennen, ob das Element vorhanden ist. Noch einfacher haben wir es, wenn keine Elemente im Baum sind:\n\n$$\\begin{aligned}\nB = \\mathrm{Nil} &\\Rightarrow B.\\mathrm{contains}(k) = (\\mathrm{false}, \\mathrm{Nil}) \\\\\nB.\\mathrm{splay}(k) = \\mathrm{Node}(k, y, z) &\\Rightarrow B.\\mathrm{contains}(k) = (\\mathrm{true}, \\mathrm{Node}(k, y, z)) \\\\\nB.\\mathrm{splay}(k) = \\mathrm{Node}(x, y, z) \\land k \\neq x &\\Rightarrow B.\\mathrm{contains}(k) = (\\mathrm{false}, \\mathrm{Node}(x, y, z))\n\\end{aligned}$$\n\nWir haben für `Node`",
"_____no_output_____"
]
],
[
[
"def contains(self, payload):\n self = self._splay(payload)\n return self._arb_eq(payload, self.payload), self\n\nNode.contains = contains\ndel contains",
"_____no_output_____"
]
],
[
[
"und für den `SplayTree`",
"_____no_output_____"
]
],
[
[
"def contains(self, payload):\n if self.tree is None:\n return False\n contains, self.tree = self.tree.contains(payload)\n return contains\n\nSplayTree.contains = contains\ndel contains",
"_____no_output_____"
]
],
[
[
"Beispiele zeigen uns:",
"_____no_output_____"
]
],
[
[
"my_splay = SplayTree()\nfor letter in [\"a\", \"c\", \"b\"]:\n my_splay.insert(letter)\nmy_splay.graph()",
"_____no_output_____"
],
[
"my_splay.contains(\"a\")",
"_____no_output_____"
],
[
"my_splay.graph()",
"_____no_output_____"
],
[
"my_splay.contains(\"d\")",
"_____no_output_____"
],
[
"my_splay.graph()",
"_____no_output_____"
]
],
[
[
"### Leerüberprüfung\n\nWir definieren zuletzt, wie wir überprüfen, ob der Baum leer ist.\n\n$$\\mathrm{Node}.\\mathrm{is\\_empty}: \\langle\\rangle \\to \\mathbb{B}$$\n$$\\mathrm{Node}.\\mathrm{is\\_empty}() = (\\mathrm{Node} = \\mathrm{Nil})$$\n\nDie Implementierung findet von `SplayTree` aus statt.",
"_____no_output_____"
]
],
[
[
"def is_empty(self):\n return self.tree is None\n\nSplayTree.is_empty = is_empty\ndel is_empty",
"_____no_output_____"
],
[
"my_splay = SplayTree()\nmy_splay.is_empty()",
"_____no_output_____"
],
[
"my_splay.insert(\"a\")\nmy_splay.is_empty()",
"_____no_output_____"
]
],
[
[
"## Demonstration\n\nAls kleine Demonstration von `SplayTree` implementieren wir damit die Ermittlung aller Primzahlen bis zu einer Zahl `n` mit dem *Sieb des Eratosthenes*:",
"_____no_output_____"
]
],
[
[
"def primes(n):\n primes = SplayTree()\n for i in range(2, n + 1):\n primes.insert(i)\n for i in range(2, n + 1):\n for j in range(2 * i, n + 1, i):\n try:\n primes.remove(j)\n except KeyError:\n pass\n return primes",
"_____no_output_____"
]
],
[
[
"Da die Zahlen sequenziell betrachtet wurden, ist der Baum zunächst maximal unbalanciert:",
"_____no_output_____"
]
],
[
[
"tree = primes(25)\ntree.graph()",
"_____no_output_____"
]
],
[
[
"Wir sehen aber zum Beispiel, dass schon durch einen Splay ein deutlich besser balancierter Baum entsteht:",
"_____no_output_____"
]
],
[
[
"tree.tree = tree.tree._splay(7)\ntree.graph()",
"_____no_output_____"
]
],
[
[
"Da wir dieses Notebook noch wiederverwenden, entfernen wir irrelevante Namen aus dem Namespace.",
"_____no_output_____"
]
],
[
[
"del B, a1, a2, b1, b2, c1, c2, d1, d2, dot, e1, e2, f1, f2, g1, g2, h1, h2, \\\n j1, j2, k1, k2, k3, l1, l2, letter, m1, m2, my_splay, n1, n2, o1, o2, p1, \\\n p2, primes, q1, q2, r1, r2, s1, s2, subtree, t1, t2, tree, v1, v2, v3, \\\n w1, w2, x1, x2, x3, y1, y2, y3, z1, z2, z3",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e77a598a5691d9429b1e70da16925a452173840b | 353,466 | ipynb | Jupyter Notebook | analysis/mnist/train_scrambler_mnist_binary_predictor_2_vs_4_target_lum_var_occlusion_higher_entropy_penalty_epochs_50.ipynb | willshi88/scrambler | fd77c05824fc99e6965d204c4f5baa1e3b0c4fb3 | [
"MIT"
] | 19 | 2021-04-30T04:12:58.000Z | 2022-03-07T19:09:32.000Z | analysis/mnist/train_scrambler_mnist_binary_predictor_2_vs_4_target_lum_var_occlusion_higher_entropy_penalty_epochs_50.ipynb | willshi88/scrambler | fd77c05824fc99e6965d204c4f5baa1e3b0c4fb3 | [
"MIT"
] | 4 | 2021-07-02T15:07:27.000Z | 2021-08-01T12:41:28.000Z | analysis/mnist/train_scrambler_mnist_binary_predictor_2_vs_4_target_lum_var_occlusion_higher_entropy_penalty_epochs_50.ipynb | willshi88/scrambler | fd77c05824fc99e6965d204c4f5baa1e3b0c4fb3 | [
"MIT"
] | 4 | 2021-06-28T09:41:01.000Z | 2022-02-28T09:13:29.000Z | 124.416051 | 43,840 | 0.808547 | [
[
[
"import keras\nfrom keras.models import Sequential, Model, load_model\n\nfrom keras.layers import Dense, Dropout, Activation, Flatten, Input, Lambda\nfrom keras.layers import Conv2D, MaxPooling2D, AveragePooling2D, Conv1D, MaxPooling1D, LSTM, ConvLSTM2D, GRU, CuDNNLSTM, CuDNNGRU, BatchNormalization, LocallyConnected2D, Permute, TimeDistributed, Bidirectional\nfrom keras.layers import Concatenate, Reshape, Softmax, Conv2DTranspose, Embedding, Multiply\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, Callback\nfrom keras import regularizers\nfrom keras import backend as K\nfrom keras.utils.generic_utils import Progbar\nfrom keras.layers.merge import _Merge\nimport keras.losses\nfrom keras.datasets import mnist\n\nfrom functools import partial\n\nfrom collections import defaultdict\n\nimport tensorflow as tf\nfrom tensorflow.python.framework import ops\n\nimport isolearn.keras as iso\n\nimport numpy as np\n\nimport tensorflow as tf\nimport logging\nlogging.getLogger('tensorflow').setLevel(logging.ERROR)\n\nimport os\nimport pickle\nimport numpy as np\n\nimport scipy.sparse as sp\nimport scipy.io as spio\n\nimport matplotlib.pyplot as plt\n\nfrom keras.backend.tensorflow_backend import set_session\n\ndef contain_tf_gpu_mem_usage() :\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n sess = tf.Session(config=config)\n set_session(sess)\n\ncontain_tf_gpu_mem_usage()\n\nclass EpochVariableCallback(Callback) :\n \n def __init__(self, my_variable, my_func) :\n self.my_variable = my_variable \n self.my_func = my_func\n \n def on_epoch_begin(self, epoch, logs={}) :\n K.set_value(self.my_variable, self.my_func(K.get_value(self.my_variable), epoch))\n",
"Using TensorFlow backend.\n"
],
[
"#Load MNIST data\n\ndataset_name = \"mnist_2_vs_4_binary_predictor\"\n\nimg_rows, img_cols = 28, 28\n\nnum_classes = 10\nbatch_size = 32\n\nincluded_classes = [ 2, 4 ]\n\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\nkeep_index_train = []\nfor i in range(y_train.shape[0]) :\n if y_train[i] in included_classes :\n keep_index_train.append(i)\n\nkeep_index_test = []\nfor i in range(y_test.shape[0]) :\n if y_test[i] in included_classes :\n keep_index_test.append(i)\n\nx_train = x_train[keep_index_train]\nx_test = x_test[keep_index_test]\ny_train = y_train[keep_index_train]\ny_test = y_test[keep_index_test]\n\nn_train = int((x_train.shape[0] // batch_size) * batch_size)\nn_test = int((x_test.shape[0] // batch_size) * batch_size)\nx_train = x_train[:n_train]\nx_test = x_test[:n_test]\ny_train = y_train[:n_train]\ny_test = y_test[:n_test]\n\nx_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)\nx_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)\n\ninput_shape = (img_rows, img_cols, 1)\n\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\nx_train /= 255\nx_test /= 255\n\nprint(\"x_train.shape = \" + str(x_train.shape))\n\nprint(\"n train samples = \" + str(x_train.shape[0]))\nprint(\"n test samples = \" + str(x_test.shape[0]))\n\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\n#Binarize images\n\ndef _binarize_images(x, val_thresh=0.5) :\n \n x_bin = np.zeros(x.shape)\n x_bin[x >= val_thresh] = 1.\n \n return x_bin\n\nx_train = _binarize_images(x_train, val_thresh=0.5)\nx_test = _binarize_images(x_test, val_thresh=0.5)\n",
"x_train.shape = (11776, 28, 28, 1)\nn train samples = 11776\nn test samples = 1984\n"
],
[
"#Make binary labels\n\ndigit_train = np.argmax(y_train, axis=-1)\ndigit_test = np.argmax(y_test, axis=-1)\n\ny_train = np.zeros((digit_train.shape[0], 1))\ny_train[digit_train == included_classes[0], 0] = 0\ny_train[digit_train == included_classes[1], 0] = 1\n\ny_test = np.zeros((digit_test.shape[0], 1))\ny_test[digit_test == included_classes[0], 0] = 0\ny_test[digit_test == included_classes[1], 0] = 1\n",
"_____no_output_____"
],
[
"#Visualize background image distribution\n\npseudo_count = 1.0\n\nx_mean = (np.sum(x_train, axis=(0, 3)) + pseudo_count) / (x_train.shape[0] + pseudo_count)\nx_mean_logits = np.log(x_mean / (1. - x_mean))\n\nf = plt.figure(figsize=(4, 4))\n\nplot_ix = 0\n\nplt.imshow(x_mean, cmap=\"Greys\", vmin=0.0, vmax=1.0, aspect='equal')\n\nplt.xticks([], [])\nplt.yticks([], [])\n\nplt.tight_layout()\nplt.show()\n",
"_____no_output_____"
],
[
"#Calculate mean training set conservation\n\nentropy = (x_mean * -np.log(x_mean) + (1. - x_mean) * -np.log(1. - x_mean)) / np.log(2.0)\nconservation = 1.0 - entropy\n\nx_mean_conservation = np.mean(conservation)\n\nprint(\"Mean conservation (bits) = \" + str(x_mean_conservation))\n",
"Mean conservation (bits) = 0.6241306924499999\n"
],
[
"#Calculate mean training set kl-divergence against background\n\nx_train_clipped = np.clip(np.copy(x_train[:, :, :, 0]), 1e-8, 1. - 1e-8)\n\nx_mean_broadcasted = np.tile(np.expand_dims(x_mean, axis=0), (x_train_clipped.shape[0], 1, 1))\n\nkl_divs = (x_train_clipped * np.log(x_train_clipped / x_mean_broadcasted) + (1. - x_train_clipped) * np.log((1. - x_train_clipped) / (1. - x_mean_broadcasted))) / np.log(2.0)\n\nx_mean_kl_divs = np.mean(kl_divs, axis=(1, 2))\nx_mean_kl_div = np.mean(x_mean_kl_divs)\n\nprint(\"Mean KL Div against background (bits) = \" + str(x_mean_kl_div))\n",
"Mean KL Div against background (bits) = 0.3753392663167618\n"
],
[
"from tensorflow.python.framework import ops\n\n#Stochastic Binarized Neuron helper functions (Tensorflow)\n#ST Estimator code adopted from https://r2rt.com/binary-stochastic-neurons-in-tensorflow.html\n#See Github https://github.com/spitis/\n\ndef bernoulli_sample(x):\n g = tf.get_default_graph()\n with ops.name_scope(\"BernoulliSample\") as name:\n with g.gradient_override_map({\"Ceil\": \"Identity\",\"Sub\": \"BernoulliSample_ST\"}):\n return tf.ceil(x - tf.random_uniform(tf.shape(x)), name=name)\n\[email protected](\"BernoulliSample_ST\")\ndef bernoulliSample_ST(op, grad):\n return [grad, tf.zeros(tf.shape(op.inputs[1]))]\n",
"_____no_output_____"
],
[
"#Masking and Sampling helper functions\n\ndef sample_image_st(x) :\n p = tf.sigmoid(x)\n\n return bernoulli_sample(p)\n\n#Generator helper functions\ndef initialize_templates(generator, background_matrices) :\n\n embedding_backgrounds = []\n\n for k in range(len(background_matrices)) :\n embedding_backgrounds.append(background_matrices[k].reshape(1, -1))\n\n embedding_backgrounds = np.concatenate(embedding_backgrounds, axis=0)\n\n generator.get_layer('background_dense').set_weights([embedding_backgrounds])\n generator.get_layer('background_dense').trainable = False\n\n#Generator construction function\ndef build_sampler(batch_size, n_rows, n_cols, n_classes=1, n_samples=1) :\n\n #Initialize Reshape layer\n reshape_layer = Reshape((n_rows, n_cols, 1))\n \n #Initialize background matrix\n background_dense = Embedding(n_classes, n_rows * n_cols, embeddings_initializer='zeros', name='background_dense')\n\n #Initialize Templating and Masking Lambda layer\n background_layer = Lambda(lambda x: x[0] + x[1], name='background_layer')\n \n #Initialize Sigmoid layer\n image_layer = Lambda(lambda x: K.sigmoid(x), name='image')\n \n #Initialize Sampling layers\n upsampling_layer = Lambda(lambda x: K.tile(x, [n_samples, 1, 1, 1]), name='upsampling_layer')\n sampling_layer = Lambda(sample_image_st, name='image_sampler')\n permute_layer = Lambda(lambda x: K.permute_dimensions(K.reshape(x, (n_samples, batch_size, n_rows, n_cols, 1)), (1, 0, 2, 3, 4)), name='permute_layer')\n \n def _sampler_func(class_input, raw_logits) :\n \n #Get Template and Mask\n background = reshape_layer(background_dense(class_input))\n \n #Add Template and Multiply Mask\n image_logits = background_layer([raw_logits, background])\n \n #Compute Image (Sigmoids from logits)\n image = image_layer(image_logits)\n \n #Tile each image to sample from and create sample axis\n image_logits_upsampled = upsampling_layer(image_logits)\n sampled_image = sampling_layer(image_logits_upsampled)\n sampled_image = permute_layer(sampled_image)\n \n return image_logits, image, sampled_image\n \n return _sampler_func\n",
"_____no_output_____"
],
[
"#Scrambler network definition\n\ndef make_resblock(n_channels=64, window_size=8, dilation_rate=1, group_ix=0, layer_ix=0, drop_rate=0.0) :\n\n #Initialize res block layers\n batch_norm_0 = BatchNormalization(name='scrambler_resblock_' + str(group_ix) + '_' + str(layer_ix) + '_batch_norm_0')\n\n relu_0 = Lambda(lambda x: K.relu(x, alpha=0.0))\n\n conv_0 = Conv2D(n_channels, (window_size, window_size), dilation_rate=dilation_rate, strides=(1, 1), padding='same', activation='linear', kernel_initializer='glorot_normal', name='scrambler_resblock_' + str(group_ix) + '_' + str(layer_ix) + '_conv_0')\n\n batch_norm_1 = BatchNormalization(name='scrambler_resblock_' + str(group_ix) + '_' + str(layer_ix) + '_batch_norm_1')\n\n relu_1 = Lambda(lambda x: K.relu(x, alpha=0.0))\n\n conv_1 = Conv2D(n_channels, (window_size, window_size), dilation_rate=dilation_rate, strides=(1, 1), padding='same', activation='linear', kernel_initializer='glorot_normal', name='scrambler_resblock_' + str(group_ix) + '_' + str(layer_ix) + '_conv_1')\n\n skip_1 = Lambda(lambda x: x[0] + x[1], name='scrambler_resblock_' + str(group_ix) + '_' + str(layer_ix) + '_skip_1')\n\n drop_1 = None\n if drop_rate > 0.0 :\n drop_1 = Dropout(drop_rate)\n \n #Execute res block\n def _resblock_func(input_tensor) :\n batch_norm_0_out = batch_norm_0(input_tensor)\n relu_0_out = relu_0(batch_norm_0_out)\n conv_0_out = conv_0(relu_0_out)\n\n batch_norm_1_out = batch_norm_1(conv_0_out)\n relu_1_out = relu_1(batch_norm_1_out)\n \n if drop_rate > 0.0 :\n conv_1_out = drop_1(conv_1(relu_1_out))\n else :\n conv_1_out = conv_1(relu_1_out)\n\n skip_1_out = skip_1([conv_1_out, input_tensor])\n \n return skip_1_out\n\n return _resblock_func\n\ndef get_rand_lum(lum, x, min_lum=0.1, max_lum=0.5) :\n \n rand_lum = K.random_uniform(shape=K.shape(lum), minval=min_lum, maxval=max_lum)\n \n return K.switch(K.learning_phase(), rand_lum, lum)\n\ndef load_scrambler_network(n_groups=1, n_resblocks_per_group=4, n_channels=32, window_size=8, dilation_rates=[1], drop_rate=0.0, feature_min_lum=0.1, feature_max_lum=0.5) :\n\n #Discriminator network definition\n conv_0 = Conv2D(n_channels, (1, 1), strides=(1, 1), padding='same', activation='linear', kernel_initializer='glorot_normal', name='scrambler_conv_0')\n \n rand_lum = Lambda(lambda x: get_rand_lum(x[0], x[1], min_lum=feature_min_lum, max_lum=feature_max_lum))\n lum_concat = Lambda(lambda x: K.concatenate([x[0], K.tile(K.expand_dims(K.expand_dims(x[1], axis=1), axis=1), (1, K.shape(x[0])[1], K.shape(x[0])[2], 1))], axis=-1))\n \n skip_convs = []\n resblock_groups = []\n for group_ix in range(n_groups) :\n \n skip_convs.append(Conv2D(n_channels, (1, 1), strides=(1, 1), padding='same', activation='linear', kernel_initializer='glorot_normal', name='scrambler_skip_conv_' + str(group_ix)))\n \n resblocks = []\n for layer_ix in range(n_resblocks_per_group) :\n resblocks.append(make_resblock(n_channels=n_channels, window_size=window_size, dilation_rate=dilation_rates[group_ix], group_ix=group_ix, layer_ix=layer_ix, drop_rate=drop_rate))\n \n resblock_groups.append(resblocks)\n\n last_block_conv = Conv2D(n_channels, (1, 1), strides=(1, 1), padding='same', activation='linear', kernel_initializer='glorot_normal', name='scrambler_last_block_conv')\n \n skip_add = Lambda(lambda x: x[0] + x[1], name='scrambler_skip_add')\n \n final_conv = Conv2D(1, (1, 1), strides=(1, 1), padding='same', activation='softplus', kernel_initializer='glorot_normal', name='scrambler_final_conv')\n \n image_to_logits = Lambda(lambda x: 2. * x - 1., name='scrambler_image_to_logits')\n \n scale_logits = Lambda(lambda x: x[1] / K.maximum(x[0], K.epsilon()), name='scrambler_logit_scale')\n \n def _scrambler_func(image_input, lum_input) :\n \n rand_lum_out = rand_lum([lum_input, image_input])\n conv_0_out = conv_0(lum_concat([image_input, rand_lum_out]))\n\n #Connect group of res blocks\n output_tensor = conv_0_out\n\n #Res block group execution\n skip_conv_outs = []\n for group_ix in range(n_groups) :\n skip_conv_out = skip_convs[group_ix](output_tensor)\n skip_conv_outs.append(skip_conv_out)\n\n for layer_ix in range(n_resblocks_per_group) :\n output_tensor = resblock_groups[group_ix][layer_ix](output_tensor)\n \n #Last res block extr conv\n last_block_conv_out = last_block_conv(output_tensor)\n\n skip_add_out = last_block_conv_out\n for group_ix in range(n_groups) :\n skip_add_out = skip_add([skip_add_out, skip_conv_outs[group_ix]])\n\n #Final conv out\n final_conv_out = final_conv(skip_add_out)\n \n #Scale logits by importance scores\n scaled_logits = scale_logits([final_conv_out, image_to_logits(image_input)])\n \n return scaled_logits, final_conv_out, rand_lum_out\n\n return _scrambler_func\n",
"_____no_output_____"
],
[
"#Keras loss functions\n\ndef get_sigmoid_kl_divergence() :\n\n def _sigmoid_kl_divergence(y_true, y_pred) :\n\n y_pred = K.clip(y_pred, K.epsilon(), 1.0 - K.epsilon())\n y_true = K.clip(y_true, K.epsilon(), 1.0 - K.epsilon())\n \n mean_kl = K.mean(y_true * K.log(y_true / y_pred) + (1.0 - y_true) * K.log((1.0 - y_true) / (1.0 - y_pred)), axis=-1)\n \n return mean_kl\n \n return _sigmoid_kl_divergence\n\ndef get_margin_lum_ame() :\n \n def _margin_lum_ame(importance_scores, max_lum) :\n \n p_ons = 2. * K.sigmoid(importance_scores[..., 0]) - 1.\n \n mean_p_on = K.mean(p_ons, axis=(1, 2))\n\n margin_p_on = K.switch(mean_p_on > max_lum[:, 0], mean_p_on - max_lum[:, 0], K.zeros_like(mean_p_on))\n \n return margin_p_on\n \n return _margin_lum_ame\n\ndef get_target_lum_sme() :\n \n def _target_lum_sme(importance_scores, target_lum) :\n \n p_ons = 2. * K.sigmoid(importance_scores[..., 0]) - 1.\n \n mean_p_on = K.mean(p_ons, axis=(1, 2))\n \n return (mean_p_on - target_lum[:, 0])**2\n \n return _target_lum_sme\n\ndef get_weighted_loss(loss_coeff=1.) :\n \n def _min_pred(y_true, y_pred) :\n return loss_coeff * y_pred\n \n return _min_pred\n",
"_____no_output_____"
],
[
"#Initialize Encoder and Decoder networks\nbatch_size = 32\nn_rows = 28\nn_cols = 28\nn_samples = 32\n\n#Resnet parameters\nresnet_n_groups = 5\nresnet_n_resblocks_per_group = 4\nresnet_n_channels = 32\nresnet_window_size = 3\nresnet_dilation_rates = [1, 2, 4, 2, 1]\nresnet_drop_rate = 0.0\nresnet_feature_min_lum = 0.025\nresnet_feature_max_lum = 0.95\n\n#Load scrambler\nscrambler = load_scrambler_network(\n n_groups=resnet_n_groups,\n n_resblocks_per_group=resnet_n_resblocks_per_group,\n n_channels=resnet_n_channels, window_size=resnet_window_size,\n dilation_rates=resnet_dilation_rates,\n drop_rate=resnet_drop_rate,\n feature_min_lum=resnet_feature_min_lum,\n feature_max_lum=resnet_feature_max_lum\n)\n\n#Load sampler\nsampler = build_sampler(batch_size, n_rows, n_cols, n_classes=1, n_samples=n_samples)\n",
"_____no_output_____"
],
[
"#Load Predictor\npredictor_path = 'saved_models/mnist_binarized_cnn_digit_2_vs_4.h5'\n\npredictor = load_model(predictor_path)\n\npredictor.trainable = False\npredictor.compile(optimizer=keras.optimizers.SGD(lr=0.1), loss='mean_squared_error')\n",
"_____no_output_____"
],
[
"#Create inverted labels\n\ny_train_inv = 1. - y_train\ny_test_inv = 1. - y_test\n",
"_____no_output_____"
],
[
"#Build scrambler model\nscrambler_class = Input(shape=(1,), name='scrambler_class')\nscrambler_input = Input(shape=(n_rows, n_cols, 1), name='scrambler_input')\nscrambler_lum = Input(shape=(1,), name='scrambler_lum')\n\nscrambled_logits, importance_scores, _ = scrambler(scrambler_input, scrambler_lum)\n\nimage_logits, image, sampled_image = sampler(scrambler_class, scrambled_logits)\n\nscrambler_model = Model([scrambler_input, scrambler_class, scrambler_lum], [image_logits, image, sampled_image, importance_scores])\n\n#Initialize Templates and Masks\ninitialize_templates(scrambler_model, [x_mean_logits])\n\nscrambler_model.compile(\n optimizer=keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999),\n loss='mean_squared_error'\n)\n",
"_____no_output_____"
],
[
"#Build Auto-scrambler pipeline\n\n#Define model inputs\nae_scrambler_class = Input(shape=(1,), name='ae_scrambler_class')\nae_scrambler_input = Input(shape=(n_rows, n_cols, 1), name='ae_scrambler_input')\nae_scrambler_lum = Input(shape=(1,), name='ae_scrambler_lum')\nae_label_input = Input(shape=(1,), name='ae_label_input')\n\nscrambled_logits, importance_scores, target_lum = scrambler(ae_scrambler_input, ae_scrambler_lum)\n\n#Run encoder and decoder\n_, scrambled_image, scrambled_sample = sampler(ae_scrambler_class, scrambled_logits)\n\n#Define layer to deflate sample axis\ndeflate_scrambled_sample = Lambda(lambda x: K.reshape(x, (batch_size * n_samples, n_rows, n_cols, 1)), name='deflate_scrambled_sample')\n\n#Deflate sample axis\nscrambled_sample_deflated = deflate_scrambled_sample(scrambled_sample)\n\n#Make reference prediction on non-scrambled input sequence\ny_pred_non_scrambled_deflated = ae_label_input#predictor([ae_scrambler_input])\n\n#Make prediction on scrambled sequence samples\ny_pred_scrambled_deflated = predictor([scrambled_sample_deflated])\n\n#Define layer to inflate sample axis\ninflate_non_scrambled_prediction = Lambda(lambda x: K.tile(x, (1, n_samples)), name='inflate_non_scrambled_prediction')\ninflate_scrambled_prediction = Lambda(lambda x: K.reshape(x, (batch_size, n_samples)), name='inflate_scrambled_prediction')\n\n#Inflate sample axis\ny_pred_non_scrambled = inflate_non_scrambled_prediction(y_pred_non_scrambled_deflated)\ny_pred_scrambled = inflate_scrambled_prediction(y_pred_scrambled_deflated)\n\n#NLL cost\nnll_loss_func = get_sigmoid_kl_divergence()\n\n#Conservation cost\nconservation_loss_func = get_target_lum_sme()\n\n#Entropy cost\nentropy_loss_func = get_target_lum_sme()\n#entropy_loss_func = get_margin_lum_ame()\n\n#Define annealing coefficient\nanneal_coeff = K.variable(1.0)\n\n#Execute NLL cost\nnll_loss = Lambda(lambda x: nll_loss_func(x[0], x[1]), name='nll')([y_pred_non_scrambled, y_pred_scrambled])\n\n#Execute conservation cost\nconservation_loss = Lambda(lambda x: anneal_coeff * conservation_loss_func(x[0], x[1]), name='conservation')([importance_scores, target_lum])\n\n#Execute entropy cost\nentropy_loss = Lambda(lambda x: (1. - anneal_coeff) * entropy_loss_func(x[0], x[1]), name='entropy')([importance_scores, target_lum])\n\nloss_model = Model(\n [ae_scrambler_class, ae_scrambler_input, ae_scrambler_lum, ae_label_input],\n [nll_loss, conservation_loss, entropy_loss]\n)\n\n#Initialize Templates and Masks\ninitialize_templates(loss_model, [x_mean_logits])\n\nloss_model.compile(\n optimizer=keras.optimizers.Adam(lr=0.0001, beta_1=0.5, beta_2=0.9),\n loss={\n 'nll' : get_weighted_loss(loss_coeff=1.0),\n 'conservation' : get_weighted_loss(loss_coeff=1.0),\n 'entropy' : get_weighted_loss(loss_coeff=1200.0)\n }\n)\n",
"_____no_output_____"
],
[
"scrambler_model.summary()",
"__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\nscrambler_input (InputLayer) (None, 28, 28, 1) 0 \n__________________________________________________________________________________________________\nscrambler_lum (InputLayer) (None, 1) 0 \n__________________________________________________________________________________________________\nlambda_1 (Lambda) (None, 1) 0 scrambler_lum[0][0] \n scrambler_input[0][0] \n__________________________________________________________________________________________________\nlambda_2 (Lambda) (None, 28, 28, 2) 0 scrambler_input[0][0] \n lambda_1[0][0] \n__________________________________________________________________________________________________\nscrambler_conv_0 (Conv2D) (None, 28, 28, 32) 96 lambda_2[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_0_0_batch_no (None, 28, 28, 32) 128 scrambler_conv_0[0][0] \n__________________________________________________________________________________________________\nlambda_3 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_0_0_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_0_0_conv_0 ( (None, 28, 28, 32) 9248 lambda_3[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_0_0_batch_no (None, 28, 28, 32) 128 scrambler_resblock_0_0_conv_0[0][\n__________________________________________________________________________________________________\nlambda_4 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_0_0_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_0_0_conv_1 ( (None, 28, 28, 32) 9248 lambda_4[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_0_0_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_0_0_conv_1[0][\n scrambler_conv_0[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_0_1_batch_no (None, 28, 28, 32) 128 scrambler_resblock_0_0_skip_1[0][\n__________________________________________________________________________________________________\nlambda_5 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_0_1_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_0_1_conv_0 ( (None, 28, 28, 32) 9248 lambda_5[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_0_1_batch_no (None, 28, 28, 32) 128 scrambler_resblock_0_1_conv_0[0][\n__________________________________________________________________________________________________\nlambda_6 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_0_1_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_0_1_conv_1 ( (None, 28, 28, 32) 9248 lambda_6[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_0_1_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_0_1_conv_1[0][\n scrambler_resblock_0_0_skip_1[0][\n__________________________________________________________________________________________________\nscrambler_resblock_0_2_batch_no (None, 28, 28, 32) 128 scrambler_resblock_0_1_skip_1[0][\n__________________________________________________________________________________________________\nlambda_7 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_0_2_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_0_2_conv_0 ( (None, 28, 28, 32) 9248 lambda_7[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_0_2_batch_no (None, 28, 28, 32) 128 scrambler_resblock_0_2_conv_0[0][\n__________________________________________________________________________________________________\nlambda_8 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_0_2_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_0_2_conv_1 ( (None, 28, 28, 32) 9248 lambda_8[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_0_2_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_0_2_conv_1[0][\n scrambler_resblock_0_1_skip_1[0][\n__________________________________________________________________________________________________\nscrambler_resblock_0_3_batch_no (None, 28, 28, 32) 128 scrambler_resblock_0_2_skip_1[0][\n__________________________________________________________________________________________________\nlambda_9 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_0_3_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_0_3_conv_0 ( (None, 28, 28, 32) 9248 lambda_9[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_0_3_batch_no (None, 28, 28, 32) 128 scrambler_resblock_0_3_conv_0[0][\n__________________________________________________________________________________________________\nlambda_10 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_0_3_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_0_3_conv_1 ( (None, 28, 28, 32) 9248 lambda_10[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_0_3_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_0_3_conv_1[0][\n scrambler_resblock_0_2_skip_1[0][\n__________________________________________________________________________________________________\nscrambler_resblock_1_0_batch_no (None, 28, 28, 32) 128 scrambler_resblock_0_3_skip_1[0][\n__________________________________________________________________________________________________\nlambda_11 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_1_0_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_1_0_conv_0 ( (None, 28, 28, 32) 9248 lambda_11[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_1_0_batch_no (None, 28, 28, 32) 128 scrambler_resblock_1_0_conv_0[0][\n__________________________________________________________________________________________________\nlambda_12 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_1_0_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_1_0_conv_1 ( (None, 28, 28, 32) 9248 lambda_12[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_1_0_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_1_0_conv_1[0][\n scrambler_resblock_0_3_skip_1[0][\n__________________________________________________________________________________________________\nscrambler_resblock_1_1_batch_no (None, 28, 28, 32) 128 scrambler_resblock_1_0_skip_1[0][\n__________________________________________________________________________________________________\nlambda_13 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_1_1_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_1_1_conv_0 ( (None, 28, 28, 32) 9248 lambda_13[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_1_1_batch_no (None, 28, 28, 32) 128 scrambler_resblock_1_1_conv_0[0][\n__________________________________________________________________________________________________\nlambda_14 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_1_1_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_1_1_conv_1 ( (None, 28, 28, 32) 9248 lambda_14[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_1_1_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_1_1_conv_1[0][\n scrambler_resblock_1_0_skip_1[0][\n__________________________________________________________________________________________________\nscrambler_resblock_1_2_batch_no (None, 28, 28, 32) 128 scrambler_resblock_1_1_skip_1[0][\n__________________________________________________________________________________________________\nlambda_15 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_1_2_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_1_2_conv_0 ( (None, 28, 28, 32) 9248 lambda_15[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_1_2_batch_no (None, 28, 28, 32) 128 scrambler_resblock_1_2_conv_0[0][\n__________________________________________________________________________________________________\nlambda_16 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_1_2_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_1_2_conv_1 ( (None, 28, 28, 32) 9248 lambda_16[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_1_2_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_1_2_conv_1[0][\n scrambler_resblock_1_1_skip_1[0][\n__________________________________________________________________________________________________\nscrambler_resblock_1_3_batch_no (None, 28, 28, 32) 128 scrambler_resblock_1_2_skip_1[0][\n__________________________________________________________________________________________________\nlambda_17 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_1_3_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_1_3_conv_0 ( (None, 28, 28, 32) 9248 lambda_17[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_1_3_batch_no (None, 28, 28, 32) 128 scrambler_resblock_1_3_conv_0[0][\n__________________________________________________________________________________________________\nlambda_18 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_1_3_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_1_3_conv_1 ( (None, 28, 28, 32) 9248 lambda_18[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_1_3_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_1_3_conv_1[0][\n scrambler_resblock_1_2_skip_1[0][\n__________________________________________________________________________________________________\nscrambler_resblock_2_0_batch_no (None, 28, 28, 32) 128 scrambler_resblock_1_3_skip_1[0][\n__________________________________________________________________________________________________\nlambda_19 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_2_0_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_2_0_conv_0 ( (None, 28, 28, 32) 9248 lambda_19[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_2_0_batch_no (None, 28, 28, 32) 128 scrambler_resblock_2_0_conv_0[0][\n__________________________________________________________________________________________________\nlambda_20 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_2_0_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_2_0_conv_1 ( (None, 28, 28, 32) 9248 lambda_20[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_2_0_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_2_0_conv_1[0][\n scrambler_resblock_1_3_skip_1[0][\n__________________________________________________________________________________________________\nscrambler_resblock_2_1_batch_no (None, 28, 28, 32) 128 scrambler_resblock_2_0_skip_1[0][\n__________________________________________________________________________________________________\nlambda_21 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_2_1_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_2_1_conv_0 ( (None, 28, 28, 32) 9248 lambda_21[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_2_1_batch_no (None, 28, 28, 32) 128 scrambler_resblock_2_1_conv_0[0][\n__________________________________________________________________________________________________\nlambda_22 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_2_1_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_2_1_conv_1 ( (None, 28, 28, 32) 9248 lambda_22[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_2_1_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_2_1_conv_1[0][\n scrambler_resblock_2_0_skip_1[0][\n__________________________________________________________________________________________________\nscrambler_resblock_2_2_batch_no (None, 28, 28, 32) 128 scrambler_resblock_2_1_skip_1[0][\n__________________________________________________________________________________________________\nlambda_23 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_2_2_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_2_2_conv_0 ( (None, 28, 28, 32) 9248 lambda_23[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_2_2_batch_no (None, 28, 28, 32) 128 scrambler_resblock_2_2_conv_0[0][\n__________________________________________________________________________________________________\nlambda_24 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_2_2_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_2_2_conv_1 ( (None, 28, 28, 32) 9248 lambda_24[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_2_2_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_2_2_conv_1[0][\n scrambler_resblock_2_1_skip_1[0][\n__________________________________________________________________________________________________\nscrambler_resblock_2_3_batch_no (None, 28, 28, 32) 128 scrambler_resblock_2_2_skip_1[0][\n__________________________________________________________________________________________________\nlambda_25 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_2_3_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_2_3_conv_0 ( (None, 28, 28, 32) 9248 lambda_25[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_2_3_batch_no (None, 28, 28, 32) 128 scrambler_resblock_2_3_conv_0[0][\n__________________________________________________________________________________________________\nlambda_26 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_2_3_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_2_3_conv_1 ( (None, 28, 28, 32) 9248 lambda_26[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_2_3_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_2_3_conv_1[0][\n scrambler_resblock_2_2_skip_1[0][\n__________________________________________________________________________________________________\nscrambler_resblock_3_0_batch_no (None, 28, 28, 32) 128 scrambler_resblock_2_3_skip_1[0][\n__________________________________________________________________________________________________\nlambda_27 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_3_0_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_3_0_conv_0 ( (None, 28, 28, 32) 9248 lambda_27[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_3_0_batch_no (None, 28, 28, 32) 128 scrambler_resblock_3_0_conv_0[0][\n__________________________________________________________________________________________________\nlambda_28 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_3_0_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_3_0_conv_1 ( (None, 28, 28, 32) 9248 lambda_28[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_3_0_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_3_0_conv_1[0][\n scrambler_resblock_2_3_skip_1[0][\n__________________________________________________________________________________________________\nscrambler_resblock_3_1_batch_no (None, 28, 28, 32) 128 scrambler_resblock_3_0_skip_1[0][\n__________________________________________________________________________________________________\nlambda_29 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_3_1_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_3_1_conv_0 ( (None, 28, 28, 32) 9248 lambda_29[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_3_1_batch_no (None, 28, 28, 32) 128 scrambler_resblock_3_1_conv_0[0][\n__________________________________________________________________________________________________\nlambda_30 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_3_1_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_3_1_conv_1 ( (None, 28, 28, 32) 9248 lambda_30[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_3_1_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_3_1_conv_1[0][\n scrambler_resblock_3_0_skip_1[0][\n__________________________________________________________________________________________________\nscrambler_resblock_3_2_batch_no (None, 28, 28, 32) 128 scrambler_resblock_3_1_skip_1[0][\n__________________________________________________________________________________________________\nlambda_31 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_3_2_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_3_2_conv_0 ( (None, 28, 28, 32) 9248 lambda_31[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_3_2_batch_no (None, 28, 28, 32) 128 scrambler_resblock_3_2_conv_0[0][\n__________________________________________________________________________________________________\nlambda_32 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_3_2_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_3_2_conv_1 ( (None, 28, 28, 32) 9248 lambda_32[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_3_2_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_3_2_conv_1[0][\n scrambler_resblock_3_1_skip_1[0][\n__________________________________________________________________________________________________\nscrambler_resblock_3_3_batch_no (None, 28, 28, 32) 128 scrambler_resblock_3_2_skip_1[0][\n__________________________________________________________________________________________________\nlambda_33 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_3_3_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_3_3_conv_0 ( (None, 28, 28, 32) 9248 lambda_33[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_3_3_batch_no (None, 28, 28, 32) 128 scrambler_resblock_3_3_conv_0[0][\n__________________________________________________________________________________________________\nlambda_34 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_3_3_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_3_3_conv_1 ( (None, 28, 28, 32) 9248 lambda_34[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_3_3_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_3_3_conv_1[0][\n scrambler_resblock_3_2_skip_1[0][\n__________________________________________________________________________________________________\nscrambler_resblock_4_0_batch_no (None, 28, 28, 32) 128 scrambler_resblock_3_3_skip_1[0][\n__________________________________________________________________________________________________\nlambda_35 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_4_0_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_4_0_conv_0 ( (None, 28, 28, 32) 9248 lambda_35[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_4_0_batch_no (None, 28, 28, 32) 128 scrambler_resblock_4_0_conv_0[0][\n__________________________________________________________________________________________________\nlambda_36 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_4_0_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_4_0_conv_1 ( (None, 28, 28, 32) 9248 lambda_36[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_4_0_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_4_0_conv_1[0][\n scrambler_resblock_3_3_skip_1[0][\n__________________________________________________________________________________________________\nscrambler_resblock_4_1_batch_no (None, 28, 28, 32) 128 scrambler_resblock_4_0_skip_1[0][\n__________________________________________________________________________________________________\nlambda_37 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_4_1_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_4_1_conv_0 ( (None, 28, 28, 32) 9248 lambda_37[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_4_1_batch_no (None, 28, 28, 32) 128 scrambler_resblock_4_1_conv_0[0][\n__________________________________________________________________________________________________\nlambda_38 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_4_1_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_4_1_conv_1 ( (None, 28, 28, 32) 9248 lambda_38[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_4_1_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_4_1_conv_1[0][\n scrambler_resblock_4_0_skip_1[0][\n__________________________________________________________________________________________________\nscrambler_resblock_4_2_batch_no (None, 28, 28, 32) 128 scrambler_resblock_4_1_skip_1[0][\n__________________________________________________________________________________________________\nlambda_39 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_4_2_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_4_2_conv_0 ( (None, 28, 28, 32) 9248 lambda_39[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_4_2_batch_no (None, 28, 28, 32) 128 scrambler_resblock_4_2_conv_0[0][\n__________________________________________________________________________________________________\nlambda_40 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_4_2_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_4_2_conv_1 ( (None, 28, 28, 32) 9248 lambda_40[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_4_2_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_4_2_conv_1[0][\n scrambler_resblock_4_1_skip_1[0][\n__________________________________________________________________________________________________\nscrambler_resblock_4_3_batch_no (None, 28, 28, 32) 128 scrambler_resblock_4_2_skip_1[0][\n__________________________________________________________________________________________________\nlambda_41 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_4_3_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_4_3_conv_0 ( (None, 28, 28, 32) 9248 lambda_41[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_4_3_batch_no (None, 28, 28, 32) 128 scrambler_resblock_4_3_conv_0[0][\n__________________________________________________________________________________________________\nlambda_42 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_4_3_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_4_3_conv_1 ( (None, 28, 28, 32) 9248 lambda_42[0][0] \n__________________________________________________________________________________________________\nscrambler_resblock_4_3_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_4_3_conv_1[0][\n scrambler_resblock_4_2_skip_1[0][\n__________________________________________________________________________________________________\nscrambler_last_block_conv (Conv (None, 28, 28, 32) 1056 scrambler_resblock_4_3_skip_1[0][\n__________________________________________________________________________________________________\nscrambler_skip_conv_0 (Conv2D) (None, 28, 28, 32) 1056 scrambler_conv_0[0][0] \n__________________________________________________________________________________________________\nscrambler_skip_add (Lambda) (None, 28, 28, 32) 0 scrambler_last_block_conv[0][0] \n scrambler_skip_conv_0[0][0] \n scrambler_skip_add[0][0] \n scrambler_skip_conv_1[0][0] \n scrambler_skip_add[1][0] \n scrambler_skip_conv_2[0][0] \n scrambler_skip_add[2][0] \n scrambler_skip_conv_3[0][0] \n scrambler_skip_add[3][0] \n scrambler_skip_conv_4[0][0] \n__________________________________________________________________________________________________\nscrambler_skip_conv_1 (Conv2D) (None, 28, 28, 32) 1056 scrambler_resblock_0_3_skip_1[0][\n__________________________________________________________________________________________________\nscrambler_skip_conv_2 (Conv2D) (None, 28, 28, 32) 1056 scrambler_resblock_1_3_skip_1[0][\n__________________________________________________________________________________________________\nscrambler_skip_conv_3 (Conv2D) (None, 28, 28, 32) 1056 scrambler_resblock_2_3_skip_1[0][\n__________________________________________________________________________________________________\nscrambler_skip_conv_4 (Conv2D) (None, 28, 28, 32) 1056 scrambler_resblock_3_3_skip_1[0][\n__________________________________________________________________________________________________\nscrambler_class (InputLayer) (None, 1) 0 \n__________________________________________________________________________________________________\nscrambler_final_conv (Conv2D) (None, 28, 28, 1) 33 scrambler_skip_add[4][0] \n__________________________________________________________________________________________________\nscrambler_image_to_logits (Lamb (None, 28, 28, 1) 0 scrambler_input[0][0] \n__________________________________________________________________________________________________\nbackground_dense (Embedding) (None, 1, 784) 784 scrambler_class[0][0] \n__________________________________________________________________________________________________\nscrambler_logit_scale (Lambda) (None, 28, 28, 1) 0 scrambler_final_conv[0][0] \n scrambler_image_to_logits[0][0] \n__________________________________________________________________________________________________\nreshape_1 (Reshape) (None, 28, 28, 1) 0 background_dense[0][0] \n__________________________________________________________________________________________________\nbackground_layer (Lambda) (None, 28, 28, 1) 0 scrambler_logit_scale[0][0] \n reshape_1[0][0] \n__________________________________________________________________________________________________\nupsampling_layer (Lambda) (None, 28, 28, 1) 0 background_layer[0][0] \n__________________________________________________________________________________________________\nimage_sampler (Lambda) (None, 28, 28, 1) 0 upsampling_layer[0][0] \n__________________________________________________________________________________________________\nimage (Lambda) (None, 28, 28, 1) 0 background_layer[0][0] \n__________________________________________________________________________________________________\npermute_layer (Lambda) (32, 32, 28, 28, 1) 0 image_sampler[0][0] \n==================================================================================================\nTotal params: 382,289\nTrainable params: 378,945\nNon-trainable params: 3,344\n__________________________________________________________________________________________________\n"
],
[
"loss_model.summary()",
"__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\nae_scrambler_input (InputLayer) (None, 28, 28, 1) 0 \n__________________________________________________________________________________________________\nae_scrambler_lum (InputLayer) (None, 1) 0 \n__________________________________________________________________________________________________\nlambda_1 (Lambda) (None, 1) 0 ae_scrambler_lum[0][0] \n ae_scrambler_input[0][0] \n__________________________________________________________________________________________________\nlambda_2 (Lambda) (None, 28, 28, 2) 0 ae_scrambler_input[0][0] \n lambda_1[1][0] \n__________________________________________________________________________________________________\nscrambler_conv_0 (Conv2D) (None, 28, 28, 32) 96 lambda_2[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_0_0_batch_no (None, 28, 28, 32) 128 scrambler_conv_0[1][0] \n__________________________________________________________________________________________________\nlambda_3 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_0_0_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_0_0_conv_0 ( (None, 28, 28, 32) 9248 lambda_3[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_0_0_batch_no (None, 28, 28, 32) 128 scrambler_resblock_0_0_conv_0[1][\n__________________________________________________________________________________________________\nlambda_4 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_0_0_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_0_0_conv_1 ( (None, 28, 28, 32) 9248 lambda_4[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_0_0_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_0_0_conv_1[1][\n scrambler_conv_0[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_0_1_batch_no (None, 28, 28, 32) 128 scrambler_resblock_0_0_skip_1[1][\n__________________________________________________________________________________________________\nlambda_5 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_0_1_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_0_1_conv_0 ( (None, 28, 28, 32) 9248 lambda_5[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_0_1_batch_no (None, 28, 28, 32) 128 scrambler_resblock_0_1_conv_0[1][\n__________________________________________________________________________________________________\nlambda_6 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_0_1_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_0_1_conv_1 ( (None, 28, 28, 32) 9248 lambda_6[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_0_1_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_0_1_conv_1[1][\n scrambler_resblock_0_0_skip_1[1][\n__________________________________________________________________________________________________\nscrambler_resblock_0_2_batch_no (None, 28, 28, 32) 128 scrambler_resblock_0_1_skip_1[1][\n__________________________________________________________________________________________________\nlambda_7 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_0_2_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_0_2_conv_0 ( (None, 28, 28, 32) 9248 lambda_7[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_0_2_batch_no (None, 28, 28, 32) 128 scrambler_resblock_0_2_conv_0[1][\n__________________________________________________________________________________________________\nlambda_8 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_0_2_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_0_2_conv_1 ( (None, 28, 28, 32) 9248 lambda_8[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_0_2_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_0_2_conv_1[1][\n scrambler_resblock_0_1_skip_1[1][\n__________________________________________________________________________________________________\nscrambler_resblock_0_3_batch_no (None, 28, 28, 32) 128 scrambler_resblock_0_2_skip_1[1][\n__________________________________________________________________________________________________\nlambda_9 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_0_3_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_0_3_conv_0 ( (None, 28, 28, 32) 9248 lambda_9[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_0_3_batch_no (None, 28, 28, 32) 128 scrambler_resblock_0_3_conv_0[1][\n__________________________________________________________________________________________________\nlambda_10 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_0_3_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_0_3_conv_1 ( (None, 28, 28, 32) 9248 lambda_10[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_0_3_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_0_3_conv_1[1][\n scrambler_resblock_0_2_skip_1[1][\n__________________________________________________________________________________________________\nscrambler_resblock_1_0_batch_no (None, 28, 28, 32) 128 scrambler_resblock_0_3_skip_1[1][\n__________________________________________________________________________________________________\nlambda_11 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_1_0_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_1_0_conv_0 ( (None, 28, 28, 32) 9248 lambda_11[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_1_0_batch_no (None, 28, 28, 32) 128 scrambler_resblock_1_0_conv_0[1][\n__________________________________________________________________________________________________\nlambda_12 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_1_0_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_1_0_conv_1 ( (None, 28, 28, 32) 9248 lambda_12[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_1_0_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_1_0_conv_1[1][\n scrambler_resblock_0_3_skip_1[1][\n__________________________________________________________________________________________________\nscrambler_resblock_1_1_batch_no (None, 28, 28, 32) 128 scrambler_resblock_1_0_skip_1[1][\n__________________________________________________________________________________________________\nlambda_13 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_1_1_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_1_1_conv_0 ( (None, 28, 28, 32) 9248 lambda_13[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_1_1_batch_no (None, 28, 28, 32) 128 scrambler_resblock_1_1_conv_0[1][\n__________________________________________________________________________________________________\nlambda_14 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_1_1_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_1_1_conv_1 ( (None, 28, 28, 32) 9248 lambda_14[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_1_1_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_1_1_conv_1[1][\n scrambler_resblock_1_0_skip_1[1][\n__________________________________________________________________________________________________\nscrambler_resblock_1_2_batch_no (None, 28, 28, 32) 128 scrambler_resblock_1_1_skip_1[1][\n__________________________________________________________________________________________________\nlambda_15 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_1_2_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_1_2_conv_0 ( (None, 28, 28, 32) 9248 lambda_15[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_1_2_batch_no (None, 28, 28, 32) 128 scrambler_resblock_1_2_conv_0[1][\n__________________________________________________________________________________________________\nlambda_16 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_1_2_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_1_2_conv_1 ( (None, 28, 28, 32) 9248 lambda_16[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_1_2_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_1_2_conv_1[1][\n scrambler_resblock_1_1_skip_1[1][\n__________________________________________________________________________________________________\nscrambler_resblock_1_3_batch_no (None, 28, 28, 32) 128 scrambler_resblock_1_2_skip_1[1][\n__________________________________________________________________________________________________\nlambda_17 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_1_3_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_1_3_conv_0 ( (None, 28, 28, 32) 9248 lambda_17[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_1_3_batch_no (None, 28, 28, 32) 128 scrambler_resblock_1_3_conv_0[1][\n__________________________________________________________________________________________________\nlambda_18 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_1_3_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_1_3_conv_1 ( (None, 28, 28, 32) 9248 lambda_18[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_1_3_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_1_3_conv_1[1][\n scrambler_resblock_1_2_skip_1[1][\n__________________________________________________________________________________________________\nscrambler_resblock_2_0_batch_no (None, 28, 28, 32) 128 scrambler_resblock_1_3_skip_1[1][\n__________________________________________________________________________________________________\nlambda_19 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_2_0_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_2_0_conv_0 ( (None, 28, 28, 32) 9248 lambda_19[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_2_0_batch_no (None, 28, 28, 32) 128 scrambler_resblock_2_0_conv_0[1][\n__________________________________________________________________________________________________\nlambda_20 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_2_0_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_2_0_conv_1 ( (None, 28, 28, 32) 9248 lambda_20[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_2_0_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_2_0_conv_1[1][\n scrambler_resblock_1_3_skip_1[1][\n__________________________________________________________________________________________________\nscrambler_resblock_2_1_batch_no (None, 28, 28, 32) 128 scrambler_resblock_2_0_skip_1[1][\n__________________________________________________________________________________________________\nlambda_21 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_2_1_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_2_1_conv_0 ( (None, 28, 28, 32) 9248 lambda_21[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_2_1_batch_no (None, 28, 28, 32) 128 scrambler_resblock_2_1_conv_0[1][\n__________________________________________________________________________________________________\nlambda_22 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_2_1_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_2_1_conv_1 ( (None, 28, 28, 32) 9248 lambda_22[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_2_1_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_2_1_conv_1[1][\n scrambler_resblock_2_0_skip_1[1][\n__________________________________________________________________________________________________\nscrambler_resblock_2_2_batch_no (None, 28, 28, 32) 128 scrambler_resblock_2_1_skip_1[1][\n__________________________________________________________________________________________________\nlambda_23 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_2_2_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_2_2_conv_0 ( (None, 28, 28, 32) 9248 lambda_23[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_2_2_batch_no (None, 28, 28, 32) 128 scrambler_resblock_2_2_conv_0[1][\n__________________________________________________________________________________________________\nlambda_24 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_2_2_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_2_2_conv_1 ( (None, 28, 28, 32) 9248 lambda_24[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_2_2_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_2_2_conv_1[1][\n scrambler_resblock_2_1_skip_1[1][\n__________________________________________________________________________________________________\nscrambler_resblock_2_3_batch_no (None, 28, 28, 32) 128 scrambler_resblock_2_2_skip_1[1][\n__________________________________________________________________________________________________\nlambda_25 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_2_3_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_2_3_conv_0 ( (None, 28, 28, 32) 9248 lambda_25[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_2_3_batch_no (None, 28, 28, 32) 128 scrambler_resblock_2_3_conv_0[1][\n__________________________________________________________________________________________________\nlambda_26 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_2_3_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_2_3_conv_1 ( (None, 28, 28, 32) 9248 lambda_26[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_2_3_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_2_3_conv_1[1][\n scrambler_resblock_2_2_skip_1[1][\n__________________________________________________________________________________________________\nscrambler_resblock_3_0_batch_no (None, 28, 28, 32) 128 scrambler_resblock_2_3_skip_1[1][\n__________________________________________________________________________________________________\nlambda_27 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_3_0_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_3_0_conv_0 ( (None, 28, 28, 32) 9248 lambda_27[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_3_0_batch_no (None, 28, 28, 32) 128 scrambler_resblock_3_0_conv_0[1][\n__________________________________________________________________________________________________\nlambda_28 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_3_0_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_3_0_conv_1 ( (None, 28, 28, 32) 9248 lambda_28[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_3_0_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_3_0_conv_1[1][\n scrambler_resblock_2_3_skip_1[1][\n__________________________________________________________________________________________________\nscrambler_resblock_3_1_batch_no (None, 28, 28, 32) 128 scrambler_resblock_3_0_skip_1[1][\n__________________________________________________________________________________________________\nlambda_29 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_3_1_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_3_1_conv_0 ( (None, 28, 28, 32) 9248 lambda_29[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_3_1_batch_no (None, 28, 28, 32) 128 scrambler_resblock_3_1_conv_0[1][\n__________________________________________________________________________________________________\nlambda_30 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_3_1_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_3_1_conv_1 ( (None, 28, 28, 32) 9248 lambda_30[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_3_1_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_3_1_conv_1[1][\n scrambler_resblock_3_0_skip_1[1][\n__________________________________________________________________________________________________\nscrambler_resblock_3_2_batch_no (None, 28, 28, 32) 128 scrambler_resblock_3_1_skip_1[1][\n__________________________________________________________________________________________________\nlambda_31 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_3_2_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_3_2_conv_0 ( (None, 28, 28, 32) 9248 lambda_31[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_3_2_batch_no (None, 28, 28, 32) 128 scrambler_resblock_3_2_conv_0[1][\n__________________________________________________________________________________________________\nlambda_32 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_3_2_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_3_2_conv_1 ( (None, 28, 28, 32) 9248 lambda_32[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_3_2_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_3_2_conv_1[1][\n scrambler_resblock_3_1_skip_1[1][\n__________________________________________________________________________________________________\nscrambler_resblock_3_3_batch_no (None, 28, 28, 32) 128 scrambler_resblock_3_2_skip_1[1][\n__________________________________________________________________________________________________\nlambda_33 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_3_3_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_3_3_conv_0 ( (None, 28, 28, 32) 9248 lambda_33[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_3_3_batch_no (None, 28, 28, 32) 128 scrambler_resblock_3_3_conv_0[1][\n__________________________________________________________________________________________________\nlambda_34 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_3_3_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_3_3_conv_1 ( (None, 28, 28, 32) 9248 lambda_34[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_3_3_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_3_3_conv_1[1][\n scrambler_resblock_3_2_skip_1[1][\n__________________________________________________________________________________________________\nscrambler_resblock_4_0_batch_no (None, 28, 28, 32) 128 scrambler_resblock_3_3_skip_1[1][\n__________________________________________________________________________________________________\nlambda_35 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_4_0_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_4_0_conv_0 ( (None, 28, 28, 32) 9248 lambda_35[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_4_0_batch_no (None, 28, 28, 32) 128 scrambler_resblock_4_0_conv_0[1][\n__________________________________________________________________________________________________\nlambda_36 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_4_0_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_4_0_conv_1 ( (None, 28, 28, 32) 9248 lambda_36[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_4_0_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_4_0_conv_1[1][\n scrambler_resblock_3_3_skip_1[1][\n__________________________________________________________________________________________________\nscrambler_resblock_4_1_batch_no (None, 28, 28, 32) 128 scrambler_resblock_4_0_skip_1[1][\n__________________________________________________________________________________________________\nlambda_37 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_4_1_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_4_1_conv_0 ( (None, 28, 28, 32) 9248 lambda_37[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_4_1_batch_no (None, 28, 28, 32) 128 scrambler_resblock_4_1_conv_0[1][\n__________________________________________________________________________________________________\nlambda_38 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_4_1_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_4_1_conv_1 ( (None, 28, 28, 32) 9248 lambda_38[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_4_1_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_4_1_conv_1[1][\n scrambler_resblock_4_0_skip_1[1][\n__________________________________________________________________________________________________\nscrambler_resblock_4_2_batch_no (None, 28, 28, 32) 128 scrambler_resblock_4_1_skip_1[1][\n__________________________________________________________________________________________________\nlambda_39 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_4_2_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_4_2_conv_0 ( (None, 28, 28, 32) 9248 lambda_39[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_4_2_batch_no (None, 28, 28, 32) 128 scrambler_resblock_4_2_conv_0[1][\n__________________________________________________________________________________________________\nlambda_40 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_4_2_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_4_2_conv_1 ( (None, 28, 28, 32) 9248 lambda_40[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_4_2_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_4_2_conv_1[1][\n scrambler_resblock_4_1_skip_1[1][\n__________________________________________________________________________________________________\nscrambler_resblock_4_3_batch_no (None, 28, 28, 32) 128 scrambler_resblock_4_2_skip_1[1][\n__________________________________________________________________________________________________\nlambda_41 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_4_3_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_4_3_conv_0 ( (None, 28, 28, 32) 9248 lambda_41[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_4_3_batch_no (None, 28, 28, 32) 128 scrambler_resblock_4_3_conv_0[1][\n__________________________________________________________________________________________________\nlambda_42 (Lambda) (None, 28, 28, 32) 0 scrambler_resblock_4_3_batch_norm\n__________________________________________________________________________________________________\nscrambler_resblock_4_3_conv_1 ( (None, 28, 28, 32) 9248 lambda_42[1][0] \n__________________________________________________________________________________________________\nscrambler_resblock_4_3_skip_1 ( (None, 28, 28, 32) 0 scrambler_resblock_4_3_conv_1[1][\n scrambler_resblock_4_2_skip_1[1][\n__________________________________________________________________________________________________\nscrambler_last_block_conv (Conv (None, 28, 28, 32) 1056 scrambler_resblock_4_3_skip_1[1][\n__________________________________________________________________________________________________\nscrambler_skip_conv_0 (Conv2D) (None, 28, 28, 32) 1056 scrambler_conv_0[1][0] \n__________________________________________________________________________________________________\nscrambler_skip_add (Lambda) (None, 28, 28, 32) 0 scrambler_last_block_conv[1][0] \n scrambler_skip_conv_0[1][0] \n scrambler_skip_add[5][0] \n scrambler_skip_conv_1[1][0] \n scrambler_skip_add[6][0] \n scrambler_skip_conv_2[1][0] \n scrambler_skip_add[7][0] \n scrambler_skip_conv_3[1][0] \n scrambler_skip_add[8][0] \n scrambler_skip_conv_4[1][0] \n__________________________________________________________________________________________________\nscrambler_skip_conv_1 (Conv2D) (None, 28, 28, 32) 1056 scrambler_resblock_0_3_skip_1[1][\n__________________________________________________________________________________________________\nscrambler_skip_conv_2 (Conv2D) (None, 28, 28, 32) 1056 scrambler_resblock_1_3_skip_1[1][\n__________________________________________________________________________________________________\nscrambler_skip_conv_3 (Conv2D) (None, 28, 28, 32) 1056 scrambler_resblock_2_3_skip_1[1][\n__________________________________________________________________________________________________\nscrambler_skip_conv_4 (Conv2D) (None, 28, 28, 32) 1056 scrambler_resblock_3_3_skip_1[1][\n__________________________________________________________________________________________________\nae_scrambler_class (InputLayer) (None, 1) 0 \n__________________________________________________________________________________________________\nscrambler_final_conv (Conv2D) (None, 28, 28, 1) 33 scrambler_skip_add[9][0] \n__________________________________________________________________________________________________\nscrambler_image_to_logits (Lamb (None, 28, 28, 1) 0 ae_scrambler_input[0][0] \n__________________________________________________________________________________________________\nbackground_dense (Embedding) (None, 1, 784) 784 ae_scrambler_class[0][0] \n__________________________________________________________________________________________________\nscrambler_logit_scale (Lambda) (None, 28, 28, 1) 0 scrambler_final_conv[1][0] \n scrambler_image_to_logits[1][0] \n__________________________________________________________________________________________________\nreshape_1 (Reshape) (None, 28, 28, 1) 0 background_dense[1][0] \n__________________________________________________________________________________________________\nbackground_layer (Lambda) (None, 28, 28, 1) 0 scrambler_logit_scale[1][0] \n reshape_1[1][0] \n__________________________________________________________________________________________________\nupsampling_layer (Lambda) (None, 28, 28, 1) 0 background_layer[1][0] \n__________________________________________________________________________________________________\nimage_sampler (Lambda) (None, 28, 28, 1) 0 upsampling_layer[1][0] \n__________________________________________________________________________________________________\npermute_layer (Lambda) (32, 32, 28, 28, 1) 0 image_sampler[1][0] \n__________________________________________________________________________________________________\ndeflate_scrambled_sample (Lambd (1024, 28, 28, 1) 0 permute_layer[1][0] \n__________________________________________________________________________________________________\nae_label_input (InputLayer) (None, 1) 0 \n__________________________________________________________________________________________________\nsequential_1 (Sequential) multiple 608769 deflate_scrambled_sample[0][0] \n__________________________________________________________________________________________________\ninflate_non_scrambled_predictio (None, 32) 0 ae_label_input[0][0] \n__________________________________________________________________________________________________\ninflate_scrambled_prediction (L (32, 32) 0 sequential_1[1][0] \n__________________________________________________________________________________________________\nnll (Lambda) (32,) 0 inflate_non_scrambled_prediction[\n inflate_scrambled_prediction[0][0\n__________________________________________________________________________________________________\nconservation (Lambda) (None,) 0 scrambler_final_conv[1][0] \n lambda_1[1][0] \n__________________________________________________________________________________________________\nentropy (Lambda) (None,) 0 scrambler_final_conv[1][0] \n lambda_1[1][0] \n==================================================================================================\nTotal params: 991,058\nTrainable params: 378,945\nNon-trainable params: 612,113\n__________________________________________________________________________________________________\n"
],
[
"#Training configuration\n\n#Define number of training epochs\nn_epochs = 50\n\n#Define experiment suffix (optional)\nexperiment_suffix = \"_kl_divergence_var_lum_higher_entropy_penalty\"\n\n#Define anneal function\ndef _anneal_func(val, epoch, n_epochs=n_epochs) :\n if epoch in [0] :\n return 1.0\n \n return 0.0\n\narchitecture_str = \"resnet_\" + str(resnet_n_groups) + \"_\" + str(resnet_n_resblocks_per_group) + \"_\" + str(resnet_n_channels) + \"_\" + str(resnet_window_size) + \"_\" + str(resnet_drop_rate).replace(\".\", \"\")\n\nmodel_name = \"autoscrambler_dataset_\" + dataset_name + \"_inverted_scores_n_samples_\" + str(n_samples) + \"_\" + architecture_str + \"_n_epochs_\" + str(n_epochs) + experiment_suffix\n\nprint(\"Model save name = \" + model_name)\n",
"Model save name = autoscrambler_dataset_mnist_2_vs_4_binary_predictor_inverted_scores_n_samples_32_resnet_5_4_32_3_00_n_epochs_50_kl_divergence_var_lum_higher_entropy_penalty\n"
],
[
"#Execute training procedure\n\ncallbacks =[\n #ModelCheckpoint(\"model_checkpoints/\" + model_name + \"_epoch_{epoch:02d}.hdf5\", monitor='val_loss', mode='min', period=10, save_weights_only=True),\n EpochVariableCallback(anneal_coeff, _anneal_func)\n]\n\ns_train = np.zeros((x_train.shape[0], 1))\ns_test = np.zeros((x_test.shape[0], 1))\n\nlum_train = np.ones((x_train.shape[0], 1)) * 0.05\nlum_test = np.ones((x_test.shape[0], 1)) * 0.05\n\n# train the autoencoder\ntrain_history = loss_model.fit(\n [s_train, x_train, lum_train, y_train_inv],\n [s_train, s_train, s_train],\n shuffle=True,\n epochs=n_epochs,\n batch_size=batch_size,\n validation_data=(\n [s_test, x_test, lum_test, y_test_inv],\n [s_test, s_test, s_test]\n ),\n callbacks=callbacks\n)\n",
"Train on 11776 samples, validate on 1984 samples\nEpoch 1/50\n11776/11776 [==============================] - 100s 8ms/step - loss: 2.3949 - nll_loss: 2.3567 - conservation_loss: 0.0383 - entropy_loss: 0.0000e+00 - val_loss: 1.8781 - val_nll_loss: 1.7650 - val_conservation_loss: 0.1131 - val_entropy_loss: 0.0000e+00\nEpoch 2/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 5.7371 - nll_loss: 2.7241 - conservation_loss: 0.0000e+00 - entropy_loss: 3.0130 - val_loss: 9.1147 - val_nll_loss: 8.5319 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 0.5828\nEpoch 3/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 4.3434 - nll_loss: 2.4682 - conservation_loss: 0.0000e+00 - entropy_loss: 1.8751 - val_loss: 8.1056 - val_nll_loss: 7.5064 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 0.5992\nEpoch 4/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 3.5382 - nll_loss: 2.0685 - conservation_loss: 0.0000e+00 - entropy_loss: 1.4697 - val_loss: 7.4120 - val_nll_loss: 5.9190 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 1.4931\nEpoch 5/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 3.4453 - nll_loss: 1.8984 - conservation_loss: 0.0000e+00 - entropy_loss: 1.5468 - val_loss: 7.2667 - val_nll_loss: 4.9890 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 2.2777\nEpoch 6/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 3.1345 - nll_loss: 1.8109 - conservation_loss: 0.0000e+00 - entropy_loss: 1.3237 - val_loss: 7.5711 - val_nll_loss: 7.0132 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 0.5579\nEpoch 7/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 2.9152 - nll_loss: 1.7046 - conservation_loss: 0.0000e+00 - entropy_loss: 1.2106 - val_loss: 6.6753 - val_nll_loss: 5.9665 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 0.7088\nEpoch 8/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 2.7632 - nll_loss: 1.6211 - conservation_loss: 0.0000e+00 - entropy_loss: 1.1421 - val_loss: 6.5547 - val_nll_loss: 4.9803 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 1.5745\nEpoch 9/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 2.7079 - nll_loss: 1.5491 - conservation_loss: 0.0000e+00 - entropy_loss: 1.1588 - val_loss: 6.3006 - val_nll_loss: 4.5752 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 1.7254\nEpoch 10/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 2.5664 - nll_loss: 1.4745 - conservation_loss: 0.0000e+00 - entropy_loss: 1.0919 - val_loss: 9.2609 - val_nll_loss: 9.0042 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 0.2567\nEpoch 11/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 2.4139 - nll_loss: 1.4451 - conservation_loss: 0.0000e+00 - entropy_loss: 0.9688 - val_loss: 5.9669 - val_nll_loss: 4.4266 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 1.5403\nEpoch 12/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 2.4371 - nll_loss: 1.3859 - conservation_loss: 0.0000e+00 - entropy_loss: 1.0512 - val_loss: 7.1698 - val_nll_loss: 6.9750 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 0.1947\nEpoch 13/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 2.4252 - nll_loss: 1.3519 - conservation_loss: 0.0000e+00 - entropy_loss: 1.0733 - val_loss: 5.6539 - val_nll_loss: 4.6225 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 1.0314\nEpoch 14/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 2.3000 - nll_loss: 1.2933 - conservation_loss: 0.0000e+00 - entropy_loss: 1.0067 - val_loss: 5.9034 - val_nll_loss: 3.6711 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 2.2323\nEpoch 15/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 2.1875 - nll_loss: 1.2361 - conservation_loss: 0.0000e+00 - entropy_loss: 0.9514 - val_loss: 5.5643 - val_nll_loss: 3.8309 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 1.7333\nEpoch 16/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 2.1893 - nll_loss: 1.2113 - conservation_loss: 0.0000e+00 - entropy_loss: 0.9780 - val_loss: 5.4836 - val_nll_loss: 4.3270 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 1.1566\nEpoch 17/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 2.2861 - nll_loss: 1.1888 - conservation_loss: 0.0000e+00 - entropy_loss: 1.0974 - val_loss: 5.5414 - val_nll_loss: 3.9561 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 1.5853\nEpoch 18/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 2.2348 - nll_loss: 1.1701 - conservation_loss: 0.0000e+00 - entropy_loss: 1.0647 - val_loss: 5.5860 - val_nll_loss: 5.1245 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 0.4614\nEpoch 19/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 2.0619 - nll_loss: 1.1332 - conservation_loss: 0.0000e+00 - entropy_loss: 0.9287 - val_loss: 5.3367 - val_nll_loss: 4.2434 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 1.0933\nEpoch 20/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 1.9318 - nll_loss: 1.0949 - conservation_loss: 0.0000e+00 - entropy_loss: 0.8369 - val_loss: 5.8792 - val_nll_loss: 5.6956 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 0.1837\nEpoch 21/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 2.0217 - nll_loss: 1.0562 - conservation_loss: 0.0000e+00 - entropy_loss: 0.9655 - val_loss: 5.0723 - val_nll_loss: 4.3117 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 0.7606\nEpoch 22/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 1.9114 - nll_loss: 1.0069 - conservation_loss: 0.0000e+00 - entropy_loss: 0.9045 - val_loss: 4.9424 - val_nll_loss: 4.0481 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 0.8942\nEpoch 23/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 1.8954 - nll_loss: 0.9874 - conservation_loss: 0.0000e+00 - entropy_loss: 0.9080 - val_loss: 4.8619 - val_nll_loss: 4.0795 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 0.7824\nEpoch 24/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 1.9802 - nll_loss: 0.9678 - conservation_loss: 0.0000e+00 - entropy_loss: 1.0124 - val_loss: 5.1990 - val_nll_loss: 4.1783 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 1.0207\nEpoch 25/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 1.8579 - nll_loss: 0.9292 - conservation_loss: 0.0000e+00 - entropy_loss: 0.9287 - val_loss: 4.9452 - val_nll_loss: 4.3863 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 0.5589\nEpoch 26/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 1.8917 - nll_loss: 0.9175 - conservation_loss: 0.0000e+00 - entropy_loss: 0.9741 - val_loss: 5.6314 - val_nll_loss: 2.4068 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 3.2246\nEpoch 27/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 1.9507 - nll_loss: 0.8728 - conservation_loss: 0.0000e+00 - entropy_loss: 1.0779 - val_loss: 4.8202 - val_nll_loss: 4.0396 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 0.7806\nEpoch 28/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 1.6793 - nll_loss: 0.8690 - conservation_loss: 0.0000e+00 - entropy_loss: 0.8102 - val_loss: 5.0866 - val_nll_loss: 3.0103 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 2.0762\nEpoch 29/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 1.7473 - nll_loss: 0.8274 - conservation_loss: 0.0000e+00 - entropy_loss: 0.9198 - val_loss: 4.5506 - val_nll_loss: 3.5554 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 0.9952\nEpoch 30/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 1.6530 - nll_loss: 0.8083 - conservation_loss: 0.0000e+00 - entropy_loss: 0.8447 - val_loss: 4.4216 - val_nll_loss: 3.7320 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 0.6896\nEpoch 31/50\n11776/11776 [==============================] - 84s 7ms/step - loss: 1.6820 - nll_loss: 0.8190 - conservation_loss: 0.0000e+00 - entropy_loss: 0.8630 - val_loss: 4.9226 - val_nll_loss: 2.4642 - val_conservation_loss: 0.0000e+00 - val_entropy_loss: 2.4584\n"
],
[
"\nf, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(3 * 4, 3))\n\nn_epochs_actual = len(train_history.history['nll_loss'])\n\nax1.plot(np.arange(1, n_epochs_actual + 1), train_history.history['nll_loss'], linewidth=3, color='green')\nax1.plot(np.arange(1, n_epochs_actual + 1), train_history.history['val_nll_loss'], linewidth=3, color='orange')\n\nplt.sca(ax1)\nplt.xlabel(\"Epochs\", fontsize=14)\nplt.ylabel(\"NLL\", fontsize=14)\nplt.xlim(1, n_epochs_actual)\nplt.xticks([1, n_epochs_actual], [1, n_epochs_actual], fontsize=12)\nplt.yticks(fontsize=12)\n\nax2.plot(np.arange(1, n_epochs_actual + 1), train_history.history['entropy_loss'], linewidth=3, color='green')\nax2.plot(np.arange(1, n_epochs_actual + 1), train_history.history['val_entropy_loss'], linewidth=3, color='orange')\n\nplt.sca(ax2)\nplt.xlabel(\"Epochs\", fontsize=14)\nplt.ylabel(\"Entropy Loss\", fontsize=14)\nplt.xlim(1, n_epochs_actual)\nplt.xticks([1, n_epochs_actual], [1, n_epochs_actual], fontsize=12)\nplt.yticks(fontsize=12)\n\nax3.plot(np.arange(1, n_epochs_actual + 1), train_history.history['conservation_loss'], linewidth=3, color='green')\nax3.plot(np.arange(1, n_epochs_actual + 1), train_history.history['val_conservation_loss'], linewidth=3, color='orange')\n\nplt.sca(ax3)\nplt.xlabel(\"Epochs\", fontsize=14)\nplt.ylabel(\"Conservation Loss\", fontsize=14)\nplt.xlim(1, n_epochs_actual)\nplt.xticks([1, n_epochs_actual], [1, n_epochs_actual], fontsize=12)\nplt.yticks(fontsize=12)\n\nplt.tight_layout()\n\nplt.show()\n",
"_____no_output_____"
],
[
"# Save model and weights\nsave_dir = 'saved_models'\n\nif not os.path.isdir(save_dir):\n os.makedirs(save_dir)\n\nmodel_path = os.path.join(save_dir, model_name + '.h5')\n\nscrambler_model.save(model_path)\nprint('Saved scrambler model at %s ' % (model_path))\n",
"Saved scrambler model at saved_models/autoscrambler_dataset_mnist_2_vs_4_binary_predictor_inverted_scores_n_samples_32_resnet_5_4_32_3_00_n_epochs_50_kl_divergence_var_lum_higher_entropy_penalty.h5 \n"
],
[
"#Load models\nsave_dir = 'saved_models'\n\nif not os.path.isdir(save_dir):\n os.makedirs(save_dir)\n\nmodel_path = os.path.join(save_dir, model_name + '.h5')\nscrambler_model = load_model(model_path, custom_objects={\n 'bernoulli_sample' : bernoulli_sample,\n 'tf' : tf,\n 'get_rand_lum' : get_rand_lum\n})\n\nprint('Loaded scrambler model %s ' % (model_path))\n",
"Loaded scrambler model saved_models/autoscrambler_dataset_mnist_2_vs_4_binary_predictor_inverted_scores_n_samples_32_resnet_5_4_32_3_00_n_epochs_50_kl_divergence_var_lum_higher_entropy_penalty.h5 \n"
],
[
"#Visualize a few reconstructed images\n\nfrom numpy.ma import masked_array\n\ns_test = np.zeros((x_test.shape[0], 1))\n\nlum_test = np.ones((x_test.shape[0], 1)) * 0.05\n\n_, image_test, sample_test, importance_scores_test = scrambler_model.predict_on_batch(x=[x_test[:32], s_test[:32], lum_test[:32]])\n\nfor plot_i in range(0, 20) :\n \n print(\"Test image \" + str(plot_i) + \":\")\n \n y_test_hat_ref = predictor.predict(x=[np.expand_dims(x_test[plot_i], axis=0)], batch_size=1)[0, 0]\n y_test_hat = predictor.predict(x=[sample_test[plot_i]], batch_size=32)[:10, 0].tolist()\n \n print(\" - Prediction (original) = \" + str(round(y_test_hat_ref, 2))[:4])\n print(\" - Predictions (scrambled) = \" + str([float(str(round(y_test_hat[i], 2))[:4]) for i in range(len(y_test_hat))]))\n \n f, (ax1, ax2, ax3, ax4) = plt.subplots(1, 4, figsize=(3 * 4, 3))\n\n ax1.imshow(x_test[plot_i, :, :, 0], cmap=\"Greys\", vmin=0.0, vmax=1.0, aspect='equal')\n\n plt.sca(ax1)\n plt.xticks([], [])\n plt.yticks([], [])\n \n ax2.imshow(image_test[plot_i, :, :, 0], cmap=\"Greys\", vmin=0.0, vmax=1.0, aspect='equal')\n\n plt.sca(ax2)\n plt.xticks([], [])\n plt.yticks([], [])\n \n ax3.imshow(importance_scores_test[plot_i, :, :, 0], cmap=\"hot\", vmin=0.0, vmax=np.max(importance_scores_test[plot_i, :, :, 0]), aspect='equal')\n\n plt.sca(ax3)\n plt.xticks([], [])\n plt.yticks([], [])\n \n ax4.imshow(x_test[plot_i, :, :, 0], cmap=\"Greys\", vmin=0.0, vmax=1.0, aspect='equal')\n\n plt.sca(ax4)\n plt.xticks([], [])\n plt.yticks([], [])\n \n ax4.imshow(importance_scores_test[plot_i, :, :, 0], alpha=0.75, cmap=\"hot\", vmin=0.0, vmax=np.max(importance_scores_test[plot_i, :, :, 0]), aspect='equal')\n\n plt.sca(ax4)\n plt.xticks([], [])\n plt.yticks([], [])\n\n plt.tight_layout()\n plt.show()\n",
"Test image 0:\n - Prediction (original) = 0.0\n - Predictions (scrambled) = [0.7, 0.84, 0.42, 0.02, 0.02, 0.0, 0.12, 0.03, 0.06, 0.56]\n"
],
[
"#Predict on test set\n\nsave_figs = True\n\ntest_ix = 0\n\nn_levels = 4\n\nimportance_thresh_qt = 0.0\n\nmin_importance_thresh = 10.\n\nlum_levels = [\n 0.05,\n 0.25,\n 0.45,\n 0.75\n]\n\nprint(\"Test image \" + str(test_ix) + \":\")\n \ny_test_hat_ref = predictor.predict(x=[np.expand_dims(x_test[test_ix], axis=0)], batch_size=1)[0, 0]\n\nprint(\" - Prediction (original) = \" + str(round(y_test_hat_ref, 2))[:4])\n\nimportance_scores_levels = []\ny_test_hat_levels = []\n\nfor level_ix in range(n_levels) :\n \n print(\"Depth = \" + str(level_ix))\n \n lum_test = np.ones((batch_size, 1)) * lum_levels[level_ix]\n \n _, image_test, sample_test, importance_scores_test = scrambler_model.predict_on_batch(x=[np.tile(np.expand_dims(x_test[test_ix], axis=0), (batch_size, 1, 1, 1)), np.tile(np.expand_dims(s_test[test_ix], axis=0), (batch_size, 1)), lum_test])\n\n y_test_hat = predictor.predict(x=[sample_test[0]], batch_size=32)[:, 0].tolist()\n \n y_test_hat_levels.append(y_test_hat)\n \n print(\" - Predictions (scrambled) = \" + str([float(str(round(y_test_hat[i], 2))[:4]) for i in range(len(y_test_hat[:10]))]))\n \n f, (ax1, ax2, ax3, ax4) = plt.subplots(1, 4, figsize=(3 * 4, 3))\n\n ax1.imshow(x_test[test_ix, :, :, 0], cmap=\"Greys\", vmin=0.0, vmax=1.0, aspect='equal')\n\n plt.sca(ax1)\n plt.xticks([], [])\n plt.yticks([], [])\n \n ax2.imshow(image_test[0, :, :, 0], cmap=\"Greys\", vmin=0.0, vmax=1.0, aspect='equal')\n\n plt.sca(ax2)\n plt.xticks([], [])\n plt.yticks([], [])\n \n ax3.imshow(importance_scores_test[0, :, :, 0], cmap=\"hot\", vmin=0.0, vmax=np.max(importance_scores_test[plot_i, :, :, 0]), aspect='equal')\n \n plt.sca(ax3)\n plt.xticks([], [])\n plt.yticks([], [])\n \n ax4.imshow(x_test[test_ix, :, :, 0], cmap=\"Greys\", vmin=0.0, vmax=1.0, aspect='equal')\n\n plt.sca(ax4)\n plt.xticks([], [])\n plt.yticks([], [])\n \n ax4.imshow(importance_scores_test[0, :, :, 0], alpha=0.75, cmap=\"hot\", vmin=0.0, vmax=np.max(importance_scores_test[0, :, :, 0]), aspect='equal')\n\n plt.sca(ax4)\n plt.xticks([], [])\n plt.yticks([], [])\n\n plt.tight_layout()\n \n if save_figs :\n plt.savefig(model_name + \"_test_example_\" + str(test_ix) + \"_level_\" + str(level_ix) + \".png\", transparent=True, dpi=300)\n plt.savefig(model_name + \"_test_example_\" + str(test_ix) + \"_level_\" + str(level_ix) + \".eps\")\n \n plt.show()\n \n importance_thresh = np.quantile(np.ravel(importance_scores_test[0, :, :, 0]), q=importance_thresh_qt)\n importance_thresh = max(importance_thresh, min_importance_thresh)\n \n importance_scores_test = importance_scores_test[:1]\n \n max_lum = np.max(importance_scores_test)\n total_lum = np.sum(importance_scores_test)\n mean_lum = np.mean(importance_scores_test)\n mean_p_on = np.mean(2. / (1. + np.exp(-importance_scores_test)) - 1.)\n \n print(\"Max Luminescence (logit) = \" + str(max_lum))\n print(\"Total Luminescence (logit) = \" + str(total_lum))\n print(\"Mean Luminescence (logit) = \" + str(mean_lum))\n print(\"Target P(On) = \" + str(lum_levels[level_ix]))\n print(\"Mean P(On) = \" + str(mean_p_on))\n \n importance_scores_test[importance_scores_test < importance_thresh] = 0.\n if level_ix > 0 :\n importance_scores_levels_above = np.expand_dims(np.sum(np.concatenate(importance_scores_levels[:level_ix], axis=0), axis=0), axis=0)\n importance_scores_test[importance_scores_levels_above > 0] = 0.\n \n importance_scores_levels.append(importance_scores_test)\n \n #Calculate mean kl-divergence against background\n\n image_test_clipped = np.clip(np.copy(image_test[0, :, :, 0]), 1e-6, 1. - 1e-6)\n x_test_clipped = np.clip(np.copy(x_test[test_ix, :, :, 0]), 1e-6, 1. - 1e-6)\n\n kl_divs = (image_test_clipped * np.log(image_test_clipped / x_mean) + (1. - image_test_clipped) * np.log((1. - image_test_clipped) / (1. - x_mean))) / np.log(2.0)\n x_mean_kl_div = np.mean(kl_divs)\n\n print(\"Mean KL Div against background (bits) = \" + str(x_mean_kl_div))\n \n ces = - x_test[test_ix, :, :, 0] * np.log(image_test_clipped) / np.log(2.) - (1. - x_test[test_ix, :, :, 0]) * np.log(1. - image_test_clipped) / np.log(2.)\n x_mean_ce = np.mean(ces)\n\n print(\"Mean Cross-Entropy against example (bits) = \" + str(x_mean_ce))\n \n x_kl_divs = (x_test_clipped * np.log(x_test_clipped / image_test_clipped) + (1. - x_test_clipped) * np.log((1. - x_test_clipped) / (1. - image_test_clipped))) / np.log(2.0)\n x_kl_div = np.mean(x_kl_divs)\n\n print(\"Mean KL Div against against example (bits) = \" + str(x_kl_div))\n\n\nimport numpy.ma as ma\n\nf = plt.figure(figsize=(3, 3))\n\nplt.imshow(1. - x_test[test_ix, :, :, 0], cmap=\"Greys\", vmin=-1.0, vmax=1.0, aspect='equal')\n\ncmap_vals = [\n 0,\n 4,\n 5,\n 2\n]\n\nfor level_ix in range(n_levels) :\n \n importance_scores = importance_scores_levels[level_ix][0, :, :, 0]\n \n importance_scores_masked = ma.array(np.ones(importance_scores.shape), mask = importance_scores <= 0)\n \n plt.imshow(importance_scores_masked * cmap_vals[level_ix], alpha=1.0, cmap='Set1', vmin=0, vmax=8, aspect='equal')\n\nplt.xticks([], [])\nplt.yticks([], [])\n\nplt.tight_layout()\n\nif save_figs :\n plt.savefig(model_name + \"_test_example_\" + str(test_ix) + \"_levelset.png\", transparent=True, dpi=300)\n plt.savefig(model_name + \"_test_example_\" + str(test_ix) + \"_levelset.eps\")\n\nplt.show()\n",
"Test image 0:\n - Prediction (original) = 0.0\nDepth = 0\n - Predictions (scrambled) = [0.28, 0.21, 0.16, 0.54, 0.01, 0.0, 0.06, 0.01, 0.02, 0.01]\n"
],
[
"#Predict on test set\n\nsave_figs = True\n\ntest_ix = 1\n\nn_levels = 4\n\nimportance_thresh_qt = 0.0\n\nmin_importance_thresh = 10.\n\nlum_levels = [\n 0.05,\n 0.25,\n 0.45,\n 0.75\n]\n\nprint(\"Test image \" + str(test_ix) + \":\")\n \ny_test_hat_ref = predictor.predict(x=[np.expand_dims(x_test[test_ix], axis=0)], batch_size=1)[0, 0]\n\nprint(\" - Prediction (original) = \" + str(round(y_test_hat_ref, 2))[:4])\n\nimportance_scores_levels = []\ny_test_hat_levels = []\n\nfor level_ix in range(n_levels) :\n \n print(\"Depth = \" + str(level_ix))\n \n lum_test = np.ones((batch_size, 1)) * lum_levels[level_ix]\n \n _, image_test, sample_test, importance_scores_test = scrambler_model.predict_on_batch(x=[np.tile(np.expand_dims(x_test[test_ix], axis=0), (batch_size, 1, 1, 1)), np.tile(np.expand_dims(s_test[test_ix], axis=0), (batch_size, 1)), lum_test])\n\n y_test_hat = predictor.predict(x=[sample_test[0]], batch_size=32)[:, 0].tolist()\n \n y_test_hat_levels.append(y_test_hat)\n \n print(\" - Predictions (scrambled) = \" + str([float(str(round(y_test_hat[i], 2))[:4]) for i in range(len(y_test_hat[:10]))]))\n \n f, (ax1, ax2, ax3, ax4) = plt.subplots(1, 4, figsize=(3 * 4, 3))\n\n ax1.imshow(x_test[test_ix, :, :, 0], cmap=\"Greys\", vmin=0.0, vmax=1.0, aspect='equal')\n\n plt.sca(ax1)\n plt.xticks([], [])\n plt.yticks([], [])\n \n ax2.imshow(image_test[0, :, :, 0], cmap=\"Greys\", vmin=0.0, vmax=1.0, aspect='equal')\n\n plt.sca(ax2)\n plt.xticks([], [])\n plt.yticks([], [])\n \n ax3.imshow(importance_scores_test[0, :, :, 0], cmap=\"hot\", vmin=0.0, vmax=np.max(importance_scores_test[plot_i, :, :, 0]), aspect='equal')\n \n plt.sca(ax3)\n plt.xticks([], [])\n plt.yticks([], [])\n \n ax4.imshow(x_test[test_ix, :, :, 0], cmap=\"Greys\", vmin=0.0, vmax=1.0, aspect='equal')\n\n plt.sca(ax4)\n plt.xticks([], [])\n plt.yticks([], [])\n \n ax4.imshow(importance_scores_test[0, :, :, 0], alpha=0.75, cmap=\"hot\", vmin=0.0, vmax=np.max(importance_scores_test[0, :, :, 0]), aspect='equal')\n\n plt.sca(ax4)\n plt.xticks([], [])\n plt.yticks([], [])\n\n plt.tight_layout()\n \n if save_figs :\n plt.savefig(model_name + \"_test_example_\" + str(test_ix) + \"_level_\" + str(level_ix) + \".png\", transparent=True, dpi=300)\n plt.savefig(model_name + \"_test_example_\" + str(test_ix) + \"_level_\" + str(level_ix) + \".eps\")\n \n plt.show()\n \n importance_thresh = np.quantile(np.ravel(importance_scores_test[0, :, :, 0]), q=importance_thresh_qt)\n importance_thresh = max(importance_thresh, min_importance_thresh)\n \n importance_scores_test = importance_scores_test[:1]\n \n max_lum = np.max(importance_scores_test)\n total_lum = np.sum(importance_scores_test)\n mean_lum = np.mean(importance_scores_test)\n mean_p_on = np.mean(2. / (1. + np.exp(-importance_scores_test)) - 1.)\n \n print(\"Max Luminescence (logit) = \" + str(max_lum))\n print(\"Total Luminescence (logit) = \" + str(total_lum))\n print(\"Mean Luminescence (logit) = \" + str(mean_lum))\n print(\"Target P(On) = \" + str(lum_levels[level_ix]))\n print(\"Mean P(On) = \" + str(mean_p_on))\n \n importance_scores_test[importance_scores_test < importance_thresh] = 0.\n if level_ix > 0 :\n importance_scores_levels_above = np.expand_dims(np.sum(np.concatenate(importance_scores_levels[:level_ix], axis=0), axis=0), axis=0)\n importance_scores_test[importance_scores_levels_above > 0] = 0.\n \n importance_scores_levels.append(importance_scores_test)\n \n #Calculate mean kl-divergence against background\n\n image_test_clipped = np.clip(np.copy(image_test[0, :, :, 0]), 1e-6, 1. - 1e-6)\n x_test_clipped = np.clip(np.copy(x_test[test_ix, :, :, 0]), 1e-6, 1. - 1e-6)\n\n kl_divs = (image_test_clipped * np.log(image_test_clipped / x_mean) + (1. - image_test_clipped) * np.log((1. - image_test_clipped) / (1. - x_mean))) / np.log(2.0)\n x_mean_kl_div = np.mean(kl_divs)\n\n print(\"Mean KL Div against background (bits) = \" + str(x_mean_kl_div))\n \n ces = - x_test[test_ix, :, :, 0] * np.log(image_test_clipped) / np.log(2.) - (1. - x_test[test_ix, :, :, 0]) * np.log(1. - image_test_clipped) / np.log(2.)\n x_mean_ce = np.mean(ces)\n\n print(\"Mean Cross-Entropy against example (bits) = \" + str(x_mean_ce))\n \n x_kl_divs = (x_test_clipped * np.log(x_test_clipped / image_test_clipped) + (1. - x_test_clipped) * np.log((1. - x_test_clipped) / (1. - image_test_clipped))) / np.log(2.0)\n x_kl_div = np.mean(x_kl_divs)\n\n print(\"Mean KL Div against against example (bits) = \" + str(x_kl_div))\n\n\nimport numpy.ma as ma\n\nf = plt.figure(figsize=(3, 3))\n\nplt.imshow(1. - x_test[test_ix, :, :, 0], cmap=\"Greys\", vmin=-1.0, vmax=1.0, aspect='equal')\n\ncmap_vals = [\n 0,\n 4,\n 5,\n 2\n]\n\nfor level_ix in range(n_levels) :\n \n importance_scores = importance_scores_levels[level_ix][0, :, :, 0]\n \n importance_scores_masked = ma.array(np.ones(importance_scores.shape), mask = importance_scores <= 0)\n \n plt.imshow(importance_scores_masked * cmap_vals[level_ix], alpha=1.0, cmap='Set1', vmin=0, vmax=8, aspect='equal')\n\nplt.xticks([], [])\nplt.yticks([], [])\n\nplt.tight_layout()\n\nif save_figs :\n plt.savefig(model_name + \"_test_example_\" + str(test_ix) + \"_levelset.png\", transparent=True, dpi=300)\n plt.savefig(model_name + \"_test_example_\" + str(test_ix) + \"_levelset.eps\")\n\nplt.show()\n",
"Test image 1:\n - Prediction (original) = 1.0\nDepth = 0\n - Predictions (scrambled) = [0.03, 0.0, 0.0, 0.0, 0.0, 0.0, 0.21, 0.0, 0.52, 0.02]\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e77a6727f6f4b3673cb92ddd211f29602e3d7efc | 102,890 | ipynb | Jupyter Notebook | Graphing.ipynb | nmattei/InterdependentSchedulingGames | acea13f989478f92548dada1db387f8eccddc20e | [
"BSD-3-Clause"
] | null | null | null | Graphing.ipynb | nmattei/InterdependentSchedulingGames | acea13f989478f92548dada1db387f8eccddc20e | [
"BSD-3-Clause"
] | null | null | null | Graphing.ipynb | nmattei/InterdependentSchedulingGames | acea13f989478f92548dada1db387f8eccddc20e | [
"BSD-3-Clause"
] | null | null | null | 524.94898 | 97,362 | 0.927738 | [
[
[
"Notebook to play with some graph forms...",
"_____no_output_____"
]
],
[
[
"### Standard Magic and startup initializers.\n\nimport math\nimport csv\nimport numpy as np\nimport random\nimport itertools\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n%matplotlib inline\nmatplotlib.style.use('seaborn-whitegrid')\n\nfont = {'family' :'serif',\n 'size' : 22}\n\nmatplotlib.rc('font', **font)\n\n### Load Datafiles..\n## Load some stuff from Pickle..\nimport pickle\n\n## Open an older file\nwith open(\"./1000_stepping_run.pickle\", 'rb') as input_file:\n results = pickle.load(input_file)\n\n## Open an older file\nwith open(\"./1000_stepping_run_uniform.pickle\", 'rb') as input_file:\n uniform_results = pickle.load(input_file)\n\n# Print the keys.\nprint(\"players, tasks, sample\")\nfor k,v in results.items():\n print(k)",
"players, tasks, sample\n(5, 30)\n(10, 5)\n(2, 70)\n(5, 10)\n(5, 5)\n(2, 50)\n(5, 70)\n(10, 70)\n(5, 50)\n(2, 10)\n(10, 30)\n(2, 30)\n(2, 5)\n(10, 50)\n(10, 10)\n"
],
[
"df = pd.DataFrame(results)\nm = df.mean().unstack().T\ne = df.std().unstack().T\nprint(m)\nprint(e)\n#print(df.max())\n\nuf = pd.DataFrame(uniform_results)\nmu = uf.mean().unstack().T\neu = uf.std().unstack().T\nprint(mu)\nprint(eu)\n\ncolor_list = plt.cm.Paired(np.linspace(0, 1, 3))\ncolor_list = color_list[:6]\n#a = m.plot(kind='line', yerr=e.values.T, marker='*',figsize=(10,8),linewidth=3, color=color_list)\na = m.plot(kind='line', marker='*',figsize=(10,8),linewidth=3, color=color_list)\n\nhandles, labels = a.get_legend_handles_labels()\nplt.legend(loc=\"upper left\", bbox_to_anchor=[0, 1], shadow=True, title=\"Players\", fancybox=True, handles=handles[::-1], labels=labels[::-1])\n#a.legend(handles[::-1], labels[::-1])\n\nmu.plot(kind='line', yerr=eu.values.T, marker='o', ax = a, color=color_list, linestyle='--',linewidth=3, legend=False)\n#mu.plot(kind='line', marker='o', ax = a, color=color_list, linestyle='--',linewidth=3, legend=False)\n\na.set_yscale(\"log\", nonposy='clip')\na.set_xlim([0,80])\na.set_ylim([0,1000])\n#plt.legend(bbox_to_anchor = (0,0.04,1,1), bbox_transform=plt.gcf().transFigure, loc='upper center', ncol=6, borderaxespad=0.)\na.set_xlabel(\"Services Per Player ($|T_i|$)\")\na.set_ylabel(\"Solve Time (log(s))\")\nplt.tight_layout()\nplt.savefig(\"test.pdf\",bbox_inches='tight')\nplt.show()\n",
" 2 5 10\n5 0.006819 0.016678 0.033212\n10 0.063348 0.178242 0.377655\n30 2.620236 9.073796 23.524422\n50 25.765830 89.238418 222.992741\n70 107.386757 379.349311 787.160301\n 2 5 10\n5 0.005216 0.010583 0.020155\n10 0.034577 0.135762 0.244456\n30 2.349703 10.141068 28.983025\n50 35.372481 118.425861 311.230165\n70 146.042514 769.699986 1004.326137\n 2 5 10\n5 0.004272 0.010473 0.020113\n10 0.029629 0.078207 0.162628\n30 0.634193 2.217992 6.046969\n50 3.111379 13.037105 46.203912\n70 9.442468 40.573399 158.673905\n 2 5 10\n5 0.001078 0.001731 0.003553\n10 0.004977 0.011571 0.028786\n30 0.093679 0.330223 0.887312\n50 0.444567 1.804271 17.048166\n70 1.382044 5.754932 62.828016\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
]
] |
e77a7186b19109f6e7801dd19142ba7a9de9702a | 102,707 | ipynb | Jupyter Notebook | notebooks/tf2/tf-dense-insurance-reg.ipynb | kmunve/ml-workshop | 96a42e663bb656e97231eff17ef4ca21e2a14b0e | [
"MIT"
] | 3 | 2020-02-17T13:35:56.000Z | 2020-10-22T13:15:28.000Z | notebooks/tf2/tf-dense-insurance-reg.ipynb | kmunve/ml-workshop | 96a42e663bb656e97231eff17ef4ca21e2a14b0e | [
"MIT"
] | 7 | 2020-02-09T17:52:44.000Z | 2020-02-09T17:52:53.000Z | notebooks/tf2/tf-dense-insurance-reg.ipynb | kmunve/ml-workshop | 96a42e663bb656e97231eff17ef4ca21e2a14b0e | [
"MIT"
] | 4 | 2019-07-22T17:05:52.000Z | 2020-01-23T12:17:59.000Z | 200.992172 | 36,078 | 0.463143 | [
[
[
"<a href=\"https://colab.research.google.com/github/DJCordhose/ml-workshop/blob/master/notebooks/tf2/tf-dense-insurance-reg.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"# Gives us a well defined version of tensorflow\n\ntry:\n # %tensorflow_version only exists in Colab.\n %tensorflow_version 2.x\nexcept Exception:\n pass\n\n# will also work, but nightly build might contain surprises\n\n# !pip install -q tf-nightly-gpu-2.0-preview",
"TensorFlow 2.x selected.\n"
],
[
"import tensorflow as tf\nprint(tf.__version__)",
"2.0.0-rc0\n"
],
[
"import matplotlib.pyplot as plt\nimport pandas as pd\nimport tensorflow as tf\nimport numpy as np\nfrom tensorflow import keras",
"_____no_output_____"
],
[
"import pandas as pd\n\ndf = pd.read_csv('https://raw.githubusercontent.com/DJCordhose/ml-workshop/master/data/insurance-customers-1500.csv', sep=';')",
"_____no_output_____"
],
[
"y = df['group'].values\nX = df.drop('group', axis='columns').values",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)",
"_____no_output_____"
]
],
[
[
"### An experimental approach:\n- keep adding regularization to make validation and train scores come closer to each other\n- this will come at the cost of train scores going down\n- if both values start going down you have gone too far\n- each experiment takes some time\n- for larger datasets and more complex models some people start by overfitting on a subsample of the data (because it trains much faster)\n - then you can be sure you have an architecture that at least has the capacity to solve the problem\n - then keep adding regularizations\n - eventually try using the complete data\n- if you want to use batch normalization place it between raw output of neuron and activation function ",
"_____no_output_____"
]
],
[
[
"from tensorflow.keras.layers import Input, Dense, Dropout, \\\n BatchNormalization, Activation\n\nnum_features = 3\nnum_categories = 3\n\ndropout = 0.6\nmodel = keras.Sequential()\n\nmodel.add(Input(name='input', shape=(num_features,)))\n\n# reduce capacity by decreasing number of neurons\nmodel.add(Dense(500, name='hidden1'))\nmodel.add(Activation('relu'))\n# model.add(BatchNormalization())\n# model.add(Dropout(dropout))\n\nmodel.add(Dense(500, name='hidden2'))\nmodel.add(Activation('relu'))\n# model.add(BatchNormalization())\n# model.add(Dropout(dropout))\n\nmodel.add(Dense(name='output', units=num_categories, activation='softmax'))\n\nmodel.compile(loss='sparse_categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\nmodel.summary()",
"Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nhidden1 (Dense) (None, 500) 2000 \n_________________________________________________________________\nactivation (Activation) (None, 500) 0 \n_________________________________________________________________\nhidden2 (Dense) (None, 500) 250500 \n_________________________________________________________________\nactivation_1 (Activation) (None, 500) 0 \n_________________________________________________________________\noutput (Dense) (None, 3) 1503 \n=================================================================\nTotal params: 254,003\nTrainable params: 254,003\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"%%time\n\n# reducing batch size might increase overfitting, \n# but might be necessary to reduce memory requirements \nBATCH_SIZE=1000\n\n# reduce this based on what you see in the training history\nEPOCHS = 10000\n\nmodel.compile(loss='sparse_categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\nhistory = model.fit(X_train, y_train, epochs=EPOCHS, batch_size=BATCH_SIZE, validation_split=0.2, verbose=0)",
"WARNING:tensorflow:Entity <function Function._initialize_uninitialized_variables.<locals>.initialize_variables at 0x7fac599677b8> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nWARNING: Entity <function Function._initialize_uninitialized_variables.<locals>.initialize_variables at 0x7fac599677b8> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'\nCPU times: user 3min 1s, sys: 18.6 s, total: 3min 20s\nWall time: 2min 55s\n"
],
[
"train_loss, train_accuracy = model.evaluate(X_train, y_train, batch_size=BATCH_SIZE)\ntrain_loss, train_accuracy",
"\r1200/1 [================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================] - 0s 10us/sample - loss: 1.2201 - accuracy: 0.8700\n"
],
[
"test_loss, test_accuracy = model.evaluate(X_test, y_test, batch_size=BATCH_SIZE)\ntest_loss, test_accuracy",
"\r300/1 [========================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================] - 0s 14us/sample - loss: 1.3659 - accuracy: 0.7067\n"
],
[
"plt.yscale('log')\n\nplt.ylabel(\"loss\")\nplt.xlabel(\"epochs\")\n\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\n\nplt.legend([\"Loss\", \"Valdation Loss\"])",
"_____no_output_____"
],
[
"plt.ylabel(\"accuracy\")\nplt.xlabel(\"epochs\")\n\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\n\nplt.legend([\"Accuracy\", \"Valdation Accuracy\"])",
"_____no_output_____"
],
[
"# category 1 should have the highest probability\nmodel.predict(np.array([[100, 48, 10]]))",
"_____no_output_____"
],
[
"assert model.predict(np.array([[100, 48, 10]])).argmax() == 1",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e77a74ac00569dacf071df621a92a3e66b61d8b5 | 4,043 | ipynb | Jupyter Notebook | notebooks/notebook-template.ipynb | knu2xs/white-pass-feature-selection | f67db3fb884b76b7e79db73745208de3d7a986f8 | [
"Apache-2.0"
] | null | null | null | notebooks/notebook-template.ipynb | knu2xs/white-pass-feature-selection | f67db3fb884b76b7e79db73745208de3d7a986f8 | [
"Apache-2.0"
] | null | null | null | notebooks/notebook-template.ipynb | knu2xs/white-pass-feature-selection | f67db3fb884b76b7e79db73745208de3d7a986f8 | [
"Apache-2.0"
] | null | null | null | 32.869919 | 342 | 0.621568 | [
[
[
"# Notebook Template\n\nThis Notebook is stubbed out with some project paths, loading of enviroment variables, and common package imports to speed up the process of starting a new project.\n\nIt is highly recommended you copy and rename this notebook following the naming convention outlined in the readme of naming notebooks with a double number such as `01-first-thing`, and `02-next-thing`. This way the order of notebooks is apparent, and each notebook does not need to be needlesssly long, complex, and difficult to follow.",
"_____no_output_____"
]
],
[
[
"import importlib\nimport os\nfrom pathlib import Path\nimport sys\n\nfrom arcgis.features import GeoAccessor, GeoSeriesAccessor\nfrom arcgis.gis import GIS\nfrom dotenv import load_dotenv, find_dotenv\nimport pandas as pd\n\n# import arcpy if available\nif importlib.util.find_spec(\"arcpy\") is not None:\n import arcpy",
"_____no_output_____"
],
[
"# paths to common data locations - NOTE: to convert any path to a raw string, simply use str(path_instance)\ndir_prj = Path.cwd().parent\n\ndir_data = dir_prj/'data'\n\ndir_raw = dir_data/'raw'\ndir_ext = dir_data/'external'\ndir_int = dir_data/'interim'\ndir_out = dir_data/'processed'\n\ngdb_raw = dir_raw/'raw.gdb'\ngdb_int = dir_int/'interim.gdb'\ngdb_out = dir_out/'processed.gdb'\n\n# import the project package from the project package path - only necessary if you are not using a unique environemnt for this project\nsys.path.append(str(dir_prj/'src'))\nimport white_pass_feature_selection\n\n# load the \"autoreload\" extension so that code can change, & always reload modules so that as you change code in src, it gets loaded\n%load_ext autoreload\n%autoreload 2\n\n# load environment variables from .env\nload_dotenv(find_dotenv())\n\n# create a GIS object instance; if you did not enter any information here, it defaults to anonymous access to ArcGIS Online\ngis = GIS(\n url=os.getenv('ESRI_GIS_URL'), \n username=os.getenv('ESRI_GIS_USERNAME'),\n password=None if len(os.getenv('ESRI_GIS_PASSWORD')) is 0 else os.getenv('ESRI_GIS_PASSWORD')\n)\n\ngis",
"_____no_output_____"
]
],
[
[
"Licensing\n\nCopyright 2020 Esri\n\nLicensed under the Apache License, Version 2.0 (the \"License\"); You\nmay not use this file except in compliance with the License. You may\nobtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\nimplied. See the License for the specific language governing\npermissions and limitations under the License.\n\nA copy of the license is available in the repository's\nLICENSE file.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
e77a787cedd94804e140df04d022b01af3b9c794 | 395,331 | ipynb | Jupyter Notebook | benchmarks/annotation_store.ipynb | adamshephard/tiatoolbox | 28c32648bc1f3e842c7b241637fd25af290386e6 | [
"BSD-3-Clause"
] | null | null | null | benchmarks/annotation_store.ipynb | adamshephard/tiatoolbox | 28c32648bc1f3e842c7b241637fd25af290386e6 | [
"BSD-3-Clause"
] | null | null | null | benchmarks/annotation_store.ipynb | adamshephard/tiatoolbox | 28c32648bc1f3e842c7b241637fd25af290386e6 | [
"BSD-3-Clause"
] | null | null | null | 163.495037 | 30,738 | 0.874745 | [
[
[
"# Benchmarking Annotation Storage\nClick to open in: [[GitHub](https://github.com/TissueImageAnalytics/tiatoolbox/tree/master/benchmarks/annotation_store.ipynb)][[Colab](https://colab.research.google.com/github/TissueImageAnalytics/tiatoolbox/blob/master/benchmarks/annotation_store.ipynb)][[Kaggle](https://kaggle.com/kernels/welcome?src=https://github.com/TissueImageAnalytics/tiatoolbox/blob/master/benchmarks/annotation_store.ipynb)]",
"_____no_output_____"
],
[
"_In order to run this notebook on a Kaggle platform, 1) click the Kaggle URL 2) click on Settings on the right of the Kaggle screen, 3) log in to your Kaggle account, 4) tick \"Internet\" checkbox under Settings, to enable necessary downloads._\n\n**NOTE:** Some parts of this notebook require a lot of memory. Part 2 in particular may not run on memory constrained systems. The notebook will run well on an MacBook Air (M1, 2020) but will use a lot of swap. It may require >64GB of memory for second half to avoid using swap.",
"_____no_output_____"
],
[
"## About This Notebook\n\nManaging annotation, either created by hand or from model output, is a\ncommon task in computational pathology. For a small number of\nannotations this may be trivial. However, for large numbers of\nannotations, it is often necessary to store the annotations in a more\nstructured format such as a database. This is because finding a desired\nsubset of annotations within a very large collection, for example over\none million cell boundary polygons derived from running HoVerNet on a\nWSI, may be very slow if performed in a naive manner. In the toolbox, we\nimplement two storage method to make handling annotations easier:\n`DictionaryStore` and `SQLiteStore`.\n\n### Storage Classes\n\nBoth stores act as a key-value store where the key is the annotation ID\n(as a string) and the value is the annotation. This follows the Python\n[`MutableMapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping)\ninterface meaning that the stores can be used in the same way as a\nregular Python dictionary (`dict`).\n\nThe `DictionaryStore` is implemented internally using a Python\ndictionary. It is a realtively simple class, operating with all\nannotations in memory and using a simple scan method to search for\nannotations. This works very well for a small number of annotations. In\ncontrast the `SQLiteStore` is implemented using a SQLite database\n(either in memory or on disk), it is a more complex class making use of\nan rtree index to efficiently spatially search for annotations. This is\nmuch more suited to a very large number of annotations. However, they\nboth follow the same interface and can be used interchangeably for\nalmost all methods (`SQLiteStore` has some additional methods).\n\n### Provided Functionality (Mini Tutorial)\n\nThe storage classes provide a lot of functionality including. This\nincludes all of the standard `MutableMapping` methods, as well as\nsome additional ones for querying the collection of annotations.\nBelow is a brief summary of the main functionality.\n\n#### Adding Annotations\n\n```python\nfrom tiatoolbox.annotation.storage import Annotation, DictionaryStore, SQliteStore\nfrom shapely.geometry import Polygon\n\n# Create a new store. If no path is given it is an in-memory store.\nstore = DictionaryStore()\n\n# An annotation is a shapely geometry and a JSON serializable dictionary\nannotation = Annotation(Polygon.from_bounds(0, 0, 1, 1), {'id': '1'})\n\n# Add the annotation to the store in the same way as a dictionary\nstore[\"foo\"] = annotation\n\n# Bulk append is also supported. This will be faster in some contexts\n# (e.g. for an SQLiteStore) than adding them one at a time.\n# Here we add 100 simple box annotations.\n# As we have not specified a set of keys to use, a new UUID is generated\n# for each. The respective generated keys are also returned.\nannotations = [\n Annotation(Polygon.from_bounds(n, n, n+1, n+1), {'id': n})\n for n in range(100)\n]\nkeys = store.append_many(annotations)\n```\n\n#### Removing Annotations\n\n```python\n# Remove an annotation by key\ndel store[\"foo\"]\n\n# Bulk removal\nkeys = [\"1234-5676....\", \"...\"] # etc.\nstore.remove_many(keys)\n```\n\n\n#### Querying Within a Region\n\n```python\n# Find all annotations which intersect a polygon\nsearch_region = Polygon.from_bounds(0, 0, 10, 10)\nresult = store.query(search_region)\n\n# Find all annotations which are contained within a polygon\nsearch_region = Polygon.from_bounds(0, 0, 10, 10)\nresult = store.query(search_region, geometry_predicate=\"contains\")\n```\n\n#### Querying Using A Predicate Statement\n\n```python\n# 'props' is a provided shorthand to access the 'properties' dictionary\nresults = store.query(where=\"propd['id'] == 1\")\n```\n\n#### Serializing and Deserializing\n\n```python\n# Serialize the store to a GeoJSON string\njson_string = store.to_geojson()\n\n# Serialize the store to a GeoJSON file\nstore.to_geojson(\"boxes.geojson\")\n\n# Deserialize a GeoJSON string into a store (even of a different type)\nsqlitestore = SqliteStore.from_geojson(\"boxes.geojson\")\n\n# The above is an in-memory store. We can also now write this to disk\n# as an SQLite database.\nsqlitestore.dump(\"boxes.db\")\n```\n\n### Benchmarking\n\nHere we evaluate the storage efficient and data querying performance of\nthe annotation store versus other common formats. We will evaluate some\ncommon situations and use cases including:\n\n- Disk I/O (tested with an SSD)\n- Querying the data for annotations within a box region\n- Querying the data for annotations within a polygon region\n- Querying the data with a predicate e.g. 'class=1'\n\nAll saved output is from running this notebook on a 2020 M1 MacBook Air with 16GB RAM.",
"_____no_output_____"
],
[
"## Imports",
"_____no_output_____"
]
],
[
[
"import sys\n\nsys.path.append(\"..\") # If running locally without pypi installed tiatoolbox\n\nimport copy\nimport pickle\nimport tempfile\nimport timeit\nimport uuid\nfrom numbers import Number\nfrom pathlib import Path\nfrom typing import Generator, List, Optional, Tuple\n\nimport numpy as np\nfrom IPython.display import display\nfrom matplotlib import pyplot as plt\nfrom shapely.geometry import MultiPolygon, Point, Polygon\nfrom tqdm.auto import tqdm\n\nfrom tiatoolbox.annotation.storage import Annotation\n\nplt.style.use(\"ggplot\")\n\nfrom tiatoolbox.annotation.storage import Annotation, DictionaryStore, SQLiteStore",
"_____no_output_____"
]
],
[
[
"## Data Generation & Utility Functions\n\nHere we define some useful functions to generate some artificial data\nand visualise results.",
"_____no_output_____"
]
],
[
[
"def cell_polygon(\n xy: Tuple[Number, Number],\n n_points: int = 20,\n radius: Number = 8,\n noise: Number = 0.01,\n eccentricity: Tuple[Number, Number] = (1, 3),\n repeat_first: bool = True,\n direction: str = \"CCW\",\n seed:int = 0,\n) -> Polygon:\n \"\"\"Generate a fake cell boundary polygon.\n\n Borrowed from tiatoolbox unit tests.\n\n Cell boundaries are generated an ellipsoids with randomised eccentricity,\n added noise, and a random rotation.\n\n Args:\n xy (tuple(int)): The x,y centre point to generate the cell boundary around.\n n_points (int): Number of points in the boundary. Defaults to 20.\n radius (float): Radius of the points from the centre. Defaults to 10.\n noise (float): Noise to add to the point locations. Defaults to 1.\n eccentricity (tuple(float)): Range of values (low, high) to use for\n randomised eccentricity. Defaults to (1, 3).\n repeat_first (bool): Enforce that the last point is equal to the first.\n direction (str): Ordering of the points. Defaults to \"CCW\". Valid options\n are: counter-clockwise \"CCW\", and clockwise \"CW\".\n seed: Seed for the random number generator. Defaults to 0.\n\n \"\"\"\n from shapely import affinity\n \n rand_state = np.random.get_state()\n np.random.seed(seed)\n if repeat_first:\n n_points -= 1\n\n # Generate points about an ellipse with random eccentricity\n x, y = xy\n alpha = np.linspace(0, 2 * np.pi - (2 * np.pi / n_points), n_points)\n rx = radius * (np.random.rand() + 0.5)\n ry = np.random.uniform(*eccentricity) * radius - 0.5 * rx\n x = rx * np.cos(alpha) + x + (np.random.rand(n_points) - 0.5) * noise\n y = ry * np.sin(alpha) + y + (np.random.rand(n_points) - 0.5) * noise\n boundary_coords = np.stack([x, y], axis=1).astype(int).tolist()\n\n # Copy first coordinate to the end if required\n if repeat_first:\n boundary_coords = boundary_coords + [boundary_coords[0]]\n\n # Swap direction\n if direction.strip().lower() == \"cw\":\n boundary_coords = boundary_coords[::-1]\n\n polygon = Polygon(boundary_coords)\n\n # Add random rotation\n angle = np.random.rand() * 360\n polygon = affinity.rotate(polygon, angle, origin=\"centroid\")\n\n\n # Restore the random state\n np.random.set_state(rand_state)\n \n return polygon",
"_____no_output_____"
],
[
"def cell_grid(\n size: Tuple[int, int] = (10, 10), spacing: Number = 25\n) -> Generator[Polygon, None, None]:\n \"\"\"Generate a grid of cell boundaries.\"\"\"\n return (\n cell_polygon(xy=np.multiply(ij, spacing), repeat_first=False, seed=n)\n for n, ij in enumerate(np.ndindex(size))\n )",
"_____no_output_____"
],
[
"def plot_results(\n experiments: List[List[Number]], title: str, capsize=5, **kwargs\n) -> None:\n \"\"\"Plot the results of a benchmark.\n\n Uses the min for the bar height (see See\n https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat),\n and plots a min-max error bar.\n \n \"\"\"\n import matplotlib.patheffects as PathEffects\n\n x = range(len(experiments))\n color = [f\"C{x_i}\" for x_i in x]\n plt.bar(\n x=x,\n height=[min(e) for e in experiments],\n color=color,\n yerr=[[0 for e in experiments], [max(e) - min(e) for e in experiments]],\n capsize=capsize,\n **kwargs,\n )\n for i, (runs, c) in enumerate(zip(experiments, color)):\n plt.text(\n i,\n min(runs),\n f\" {min(runs):.4f}s\",\n ha=\"left\",\n va=\"bottom\",\n color=c,\n zorder=10,\n fontweight=\"bold\",\n path_effects=[\n PathEffects.withStroke(linewidth=2, foreground=\"w\"),\n ],\n )\n plt.title(title)\n plt.hlines(\n 0.5,\n -0.5,\n len(experiments) - 0.5,\n linestyles=\"dashed\",\n colors=\"black\",\n alpha=0.5,\n )\n plt.yscale(\"log\")\n plt.xlabel(\"Store Type\")\n plt.ylabel(\"Time (s)\")",
"_____no_output_____"
]
],
[
[
"## Display Some Generated Data\n",
"_____no_output_____"
]
],
[
[
"for n in range(4):\n display(cell_polygon(xy=(0, 0), n_points=20, repeat_first=False, seed=n))",
"_____no_output_____"
]
],
[
[
"### Randomised Cell Boundaries\n\nHere we create a function to generate grid of cells for testing. It uses a fixed seed for reproducibility.\n",
"_____no_output_____"
],
[
"### A Sample 5×5 Grid\n",
"_____no_output_____"
]
],
[
[
"from shapely.geometry import MultiPolygon\n\nMultiPolygon(polygons=list(cell_grid(size=(5, 5), spacing=35)))",
"_____no_output_____"
]
],
[
[
"# Part 1: Small Scale Benchmarking of Annotation Storage\n\nUsing the already defined data generation functions (`cell_polygon` and\n`cell_grid`), we create some simple artificial cell boundaries by\ncreating a circle of points, adding some noise, scaling to introduce\neccentricity, and then rotating. We use 20 points per cell, which is a\nreasonably high value for cell annotation. However, this can be\nadjusted.\n",
"_____no_output_____"
],
[
"## 1.1) Appending Annotations (In-Memory & Disk I/O)\n\nHere we test:\n\n1. A python dictionary based in-memory store (`DictionaryStore`)\n2. An SQLite database based in-memory store (`SQLiteStore`)\n\nBoth of these stores may operate in memory. The `SQLiteStore` may also\nbe backed by an on-disk file for datasets which are too large to fit in\nmemory. The `DictionaryStore` class can serialise/deserialise itself\nto/from disk in a line delimited GeoJSON format (each line seperated\nby `\\n` is a valid GeoJSON object)",
"_____no_output_____"
]
],
[
[
"# Convert to annotations (a dataclass pairing a geometry and (optional)\n# key-value properties)\n# Run time: ~2s\nannotations = [\n Annotation(polygon) for polygon in cell_grid(size=(100, 100), spacing=35)\n]",
"_____no_output_____"
]
],
[
[
"### 1.1.1) In Memory Append",
"_____no_output_____"
]
],
[
[
"# Run time: ~5s\n\n# Time dictionary store\ndict_runs = timeit.repeat(\n \"dict_store.append_many(annotations)\",\n setup=\"dict_store = DictionaryStore()\",\n globals={\"DictionaryStore\": DictionaryStore, \"annotations\": annotations},\n number=1,\n repeat=3,\n)\n\n# Time SQLite store\nsqlite_runs = timeit.repeat(\n \"sql_store.append_many(annotations)\",\n setup=\"sql_store = SQLiteStore()\",\n globals={\"SQLiteStore\": SQLiteStore, \"annotations\": annotations},\n number=1,\n repeat=3,\n)\n\n# Plot the results\nplot_results(\n experiments=[dict_runs, sqlite_runs],\n title=\"Time to Append 10,000 Annotations In Memory\",\n tick_label=[\"DictionaryStore\", \"SQLiteStore\"],\n)\nplt.hlines(0.5, -0.5, 1.5, linestyles=\"dashed\", color=\"k\")\nplt.xlim([-0.5, 1.5])\nplt.show()",
"_____no_output_____"
]
],
[
[
"Note that inserting into the `SQLiteStore` is much slower than the\n`DictionaryStore`. Appending to a `Dictionary` store simply requires\nadding a memory reference to a dictionary. Therefore, this is a very\nfast operation. On the other hand, for the `SQLiteStore`, the insertion\nis slower because the data must be serialised for the database and the\nR-Tree spatial index must also be updated. Updating the index is a\nrelatively expensive operation. However, this spatial index allows for\nvery fast queries of a very large set of annotations within a set of\nspatial bounds.\n\nInsertion is typically only performed once for each\nannotation, whereas queries may be performed many times on the\nannotation set. Therefore, it makes sense to trade a more expensive\ninsertion for fast queries as the cost of insertion will be amortised\nover a number of queries on the data. Additionally, data may be written\nto the database from multiple threads or subprocesses (so long as a new\ninstance of `SQLiteStore` is created for each thread or subprocess to\nattach to a database on disk) thus freeing up the main thread.\n\nFor comparison, we also compare bulk insertion plus seralising to disk\nas line-delimited GeoJSON from the `DictionaryStore` as this is the\ndefault serialisation to disk method (`DictionaryStore.dump(file_path`).",
"_____no_output_____"
]
],
[
[
"# Run time: ~10s\n\nsetup = \"fp.truncate(0)\\n\" \"store = Store(fp)\" # Clear the file\n\n# Time dictionary store\nwith tempfile.NamedTemporaryFile(\"w+\") as fp:\n dict_runs = timeit.repeat(\n (\"store.append_many(annotations)\\n\" \"store.commit()\"),\n setup=setup,\n globals={\"Store\": DictionaryStore, \"annotations\": annotations, \"fp\": fp},\n number=1,\n repeat=3,\n )\n\n# Time SQLite store\nwith tempfile.NamedTemporaryFile(\"w+b\") as fp:\n sqlite_runs = timeit.repeat(\n (\"store.append_many(annotations)\\n\" \"store.commit()\"),\n setup=setup,\n globals={\"Store\": SQLiteStore, \"annotations\": annotations, \"fp\": fp},\n number=1,\n repeat=3,\n )\n\n# Plot the results\nplot_results(\n experiments=[dict_runs, sqlite_runs],\n title=\"Time to Append & Serialise 10,000 Annotations To Disk\",\n tick_label=[\"DictionaryStore\", \"SQLiteStore\"],\n)\nplt.hlines(0.5, -0.5, 1.5, linestyles=\"dashed\", color=\"k\")\nplt.xlim([-0.5, 1.5])\nplt.show()",
"_____no_output_____"
]
],
[
[
"Here we can see that when we include the serialisation to disk in the\nbenchmark, the time to insert is much more similar.",
"_____no_output_____"
],
[
"## 1.2) Box Query",
"_____no_output_____"
]
],
[
[
"# Run time: ~20s\n\n# One time Setup\ndict_store = DictionaryStore()\nsql_store = SQLiteStore()\ndict_store.append_many(annotations)\nsql_store.append_many(annotations)\n\nnp.random.seed(123)\nboxes = [\n Polygon.from_bounds(x, y, 128, 128)\n for x, y in np.random.randint(0, 1000, size=(100, 2))\n]\nstmt = \"for box in boxes:\\n\" \" _ = store.query(box)\"\n\n# Time dictionary store\ndict_runs = timeit.repeat(\n stmt,\n globals={\"store\": dict_store, \"boxes\": boxes},\n number=1,\n repeat=10,\n)\n\n# Time SQLite store\nsqlite_runs = timeit.repeat(\n stmt,\n globals={\"store\": sql_store, \"boxes\": boxes},\n number=1,\n repeat=10,\n)\n\n# Plot the results\nplot_results(\n experiments=[dict_runs, sqlite_runs],\n title=\"100 Box Queries\",\n tick_label=[\"DictionaryStore\", \"SQLiteStore\"],\n)\nplt.show()",
"_____no_output_____"
]
],
[
[
"Here we can see that the `SQLiteStore` is a bit faster. Addtionally,\ndifference in performance is more pronounced when there are more\nannotations (as we will see later in this notebook) in the store or when\njust returning keys:",
"_____no_output_____"
]
],
[
[
"# Run time: ~15s\n\n# One time Setup\ndict_store = DictionaryStore()\nsql_store = SQLiteStore()\ndict_store.append_many(annotations)\nsql_store.append_many(annotations)\n\nnp.random.seed(123)\nboxes = [\n Polygon.from_bounds(x, y, 128, 128)\n for x, y in np.random.randint(0, 1000, size=(100, 2))\n]\nstmt = \"for box in boxes:\\n\" \" _ = store.iquery(box)\" # Just return the keys (uuids)\n\n# Time dictionary store\ndict_runs = timeit.repeat(\n stmt,\n globals={\"store\": dict_store, \"boxes\": boxes},\n number=1,\n repeat=10,\n)\n\n# Time SQLite store\nsqlite_runs = timeit.repeat(\n stmt,\n globals={\"store\": sql_store, \"boxes\": boxes},\n number=1,\n repeat=10,\n)\n\n# Plot the results\nplot_results(\n experiments=[dict_runs, sqlite_runs],\n title=\"100 Box Queries (Key Lookup Only)\",\n tick_label=[\"DictionaryStore\", \"SQLiteStore\"],\n)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## 1.3) Polygon Query",
"_____no_output_____"
]
],
[
[
"# Run time: ~15s\n\n# One time Setup\ndict_store = DictionaryStore()\nsql_store = SQLiteStore()\ndict_store.append_many(annotations)\nsql_store.append_many(annotations)\n\nnp.random.seed(123)\nquery_polygons = [\n Polygon(\n [\n (x, y),\n (x + 128, y),\n (x + 128, y + 128),\n (x, y),\n ]\n )\n for x, y in np.random.randint(0, 1000, size=(100, 2))\n]\nstmt = \"for polygon in query_polygons:\\n\" \" _ = store.query(polygon)\"\n\n# Time dictionary store\ndict_runs = timeit.repeat(\n stmt,\n globals={\"store\": dict_store, \"query_polygons\": query_polygons},\n number=1,\n repeat=10,\n)\n\n# Time SQLite store\nsqlite_runs = timeit.repeat(\n stmt,\n globals={\"store\": sql_store, \"query_polygons\": query_polygons},\n number=1,\n repeat=10,\n)\n\n# Plot the results\nplot_results(\n experiments=[dict_runs, sqlite_runs],\n title=\"100 Polygon Queries\",\n tick_label=[\"DictionaryStore\", \"SQLiteStore\"],\n)\nplt.show()",
"_____no_output_____"
]
],
[
[
"Here we can see that performing queries within a polygon region is about\n10x faster with the `SQLiteStore` than with the `DictionaryStore`.",
"_____no_output_____"
],
[
"## 1.4) Predicate Query\n\nHere we query the whole annotation region but with a predicate to\nselect only annotations with the class label of 0. We also,\ndemonstrate how creating a database index can dramatically improve\nthe performance of queries.",
"_____no_output_____"
]
],
[
[
"# Run time: ~2m\n\n# Setup\nlabelled_annotations = copy.deepcopy(annotations)\nfor n, annotation in enumerate(labelled_annotations):\n annotation.properties[\"class\"] = n % 10\n annotation.properties[\"vector\"] = np.random.randint(1, 4, 10).tolist()\n\npredicate = \"(props['class'] == ?) & (3 in props['vector'])\"\nclasses = np.random.randint(0, 10, size=100)\nstmt = \"for n in classes:\\n\" \" store.query(where=predicate.replace('?', str(n)))\"\n\ndict_store = DictionaryStore()\nsql_store = SQLiteStore()\n\ndict_store.append_many(labelled_annotations)\nsql_store.append_many(labelled_annotations)\n\n\n# Time dictionary store\ndict_runs = timeit.repeat(\n stmt,\n globals={\"store\": dict_store, \"predicate\": predicate, \"classes\": classes},\n number=1,\n repeat=10,\n)\ndict_result = dict_store.query(where=predicate.replace(\"?\", \"0\"))\n\n# Time SQLite store\nsqlite_runs = timeit.repeat(\n stmt,\n globals={\"store\": sql_store, \"predicate\": predicate, \"classes\": classes},\n number=1,\n repeat=10,\n)\nsql_result = sql_store.query(where=predicate.replace(\"?\", \"0\"))\n\n\n# Add an index\n# Note: Indexes may not always speed up the query (sometimes they can\n# actually slow it down), test to make sure.\nsql_store.create_index(\"class_lookup\", \"props['class']\")\nsql_store.create_index(\"has_3\", \"3 in props['vector']\")\n\n# Time SQLite store again\nsqlite_index_runs = timeit.repeat(\n stmt,\n globals={\"store\": sql_store, \"predicate\": predicate, \"classes\": classes},\n number=1,\n repeat=10,\n)\nsql_index_result = sql_store.query(where=predicate.replace(\"?\", \"0\"))\n\n# # Validate the results against each other\n# for a, b, c in zip(dict_result, sql_result, sql_index_result):\n# assert a.geometry == b.geometry == c.geometry\n\n# Plot the results\nplot_results(\n experiments=[dict_runs, sqlite_runs, sqlite_index_runs],\n title=\"100 Queries with a Predicate\",\n tick_label=[\"DictionaryStore\", \"SQLiteStore\", \"SQLiteStore\\n(with index)\"],\n)\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Polygon & Predicate Query",
"_____no_output_____"
]
],
[
[
"# Run time: ~10s\n\n# Setup\nlabelled_annotations = copy.deepcopy(annotations)\nfor n, annotation in enumerate(labelled_annotations):\n annotation.properties[\"class\"] = n % 10\n\npredicate = \"props['class'] == \"\nclasses = np.random.randint(0, 10, size=50)\nquery_polygons = [\n Polygon(\n [\n (x, y),\n (x + 128, y),\n (x + 128, y + 128),\n (x, y),\n ]\n )\n for x, y in np.random.randint(0, 1000, size=(100, 2))\n]\nstmt = (\n \"for n, poly in zip(classes, query_polygons):\\n\"\n \" store.query(poly, where=predicate + str(n))\"\n)\n\ndict_store = DictionaryStore()\nsql_store = SQLiteStore()\n\ndict_store.append_many(labelled_annotations)\nsql_store.append_many(labelled_annotations)\n\n\n# Time dictionary store\ndict_runs = timeit.repeat(\n stmt,\n globals={\n \"store\": dict_store,\n \"predicate\": predicate,\n \"classes\": classes,\n \"query_polygons\": query_polygons,\n },\n number=1,\n repeat=10,\n)\ndict_result = dict_store.query(query_polygons[0], where=predicate + \"0\")\n\n# Time SQLite store\nsqlite_runs = timeit.repeat(\n stmt,\n globals={\n \"store\": sql_store,\n \"predicate\": predicate,\n \"classes\": classes,\n \"query_polygons\": query_polygons,\n },\n number=1,\n repeat=10,\n)\nsql_result = sql_store.query(query_polygons[0], where=predicate + \"0\")\n\n\n# Check that the set difference of bounding boxes is empty i.e. all sets\n# of results contain polygons which produce the same set of bounding\n# boxes. This avoids being tripped up by slight varations in order or\n# coordinate order between the results.\ndict_set = set(x.geometry.bounds for x in dict_result)\nsql_set = set(x.geometry.bounds for x in sql_result)\nassert len(dict_set.difference(sql_set)) == 0\n\n# Plot the results\nplot_results(\n experiments=[dict_runs, sqlite_runs],\n title=\"100 Queries with a Polygon and Predicate\",\n tick_label=[\"DictionaryStore\", \"SQLiteStore\"],\n)\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Complex Predicate Query\n\nHere we slightly increase the complexity of the predicate to show how\nthe complexity of a predicate can dramatically affect the performance\nwhen handling many annotations.",
"_____no_output_____"
]
],
[
[
"# Run time: ~1m\n\n# Setup\nbox = Polygon.from_bounds(0, 0, 1024, 1024)\nlabelled_annotations = copy.deepcopy(annotations)\nfor n, annotation in enumerate(labelled_annotations):\n annotation.properties[\"class\"] = n % 4\n annotation.properties[\"n\"] = n\n\npredicate = \"(props['n'] > 1000) & (props['n'] % 4 == 0) & (props['class'] == \"\ntargets = np.random.randint(0, 4, size=100)\nstmt = \"for n in targets:\\n\" \" store.query(box, where=predicate + str(n) + ')')\"\n\ndict_store = DictionaryStore()\nsql_store = SQLiteStore()\n\ndict_store.append_many(labelled_annotations)\nsql_store.append_many(labelled_annotations)\n\n\n# Time dictionary store\ndict_runs = timeit.repeat(\n stmt,\n globals={\n \"store\": dict_store,\n \"predicate\": predicate,\n \"targets\": targets,\n \"box\": box,\n },\n number=1,\n repeat=10,\n)\ndict_result = dict_store.query(box, where=predicate + \"0)\")\n\n# Time SQLite store\nsqlite_runs = timeit.repeat(\n stmt,\n globals={\n \"store\": sql_store,\n \"predicate\": predicate,\n \"targets\": targets,\n \"box\": box,\n },\n number=1,\n repeat=10,\n)\nsql_result = sql_store.query(box, where=predicate + \"0)\")\n\n\n# Check that the set difference of bounding boxes is empty i.e. all sets\n# of results contain polygons which produce the same set of bounding\n# boxes. This avoids being tripped up by slight varations in order or\n# coordinate order between the results.\ndict_set = set(x.geometry.bounds for x in dict_result.values())\nsql_set = set(x.geometry.bounds for x in sql_result.values())\n\nassert len(dict_set.difference(sql_set)) == 0\n\n# Plot the results\nplot_results(\n experiments=[dict_runs, sqlite_runs],\n title=\"100 Queries with a Complex Predicate\",\n tick_label=[\"DictionaryStore\", \"SQLiteStore\"],\n)\nplt.show()",
"_____no_output_____"
]
],
[
[
"# Part 2: Large Scale Dataset Benchmarking\n\nHere we generate some sets of anntations with five million items each\n(in a 2237 x 2237 grid). One is a set of points, the other a set of\ngenerated cell boundaries.\n\nThe code to generate and write out the annotations to various formats is\nincluded in the following cells. However, some of these take a very long\ntime to run. A pre-generated dataset is downloaded and then read from\ndisk instead to save time. However, you may uncomment the generation\ncode to replicate the original.\n",
"_____no_output_____"
],
[
"## 2.1) Points Dataset\n\nHere we generate a simple points data in a grid. The grid is 2237 x 2237\nand contains over 5 million points. We also write this to disk in\nvarious formats. Some formats take a long time and are commented out. A\nsummary of times for a consumer laptop are shown in a table at the end.",
"_____no_output_____"
]
],
[
[
"# Generate some points with a little noise\n# Run time: ~5s\npoints = np.array(\n [[x, y] for x in np.linspace(0, 75_000, 2237) for y in np.linspace(0, 75_000, 2237)]\n)\n# Add some noise between -1 and 1\nnp.random.seed(42)\npoints += np.random.uniform(-1, 1, size=(2237**2, 2))",
"_____no_output_____"
]
],
[
[
"### 2.1.1) Writing To Disk",
"_____no_output_____"
]
],
[
[
"# Save as a simple Numpy array (.npy)\n# Run time: <1s\nnp.save(\"points.npy\", points)",
"_____no_output_____"
],
[
"# Save as compressed NumPy archive (.npz)\n# Run time: ~5s\nnp.savez_compressed(\"points.npz\", points)",
"_____no_output_____"
]
],
[
[
"Note that the above numpy format is missing the keys (UUIDs) of each point.\nThis may not be required in all cases. However, for the sake of comparison\nwe also generate a NumPy archive with keys included. We store the UUIDs\nas integers to save space and for a fair comparison where the optimal\nstorage method is used in each case. Note however that UUIDs are too\nlarge to be a standard C type and therefore are stored as an object\narray.",
"_____no_output_____"
]
],
[
[
"# Generate UUIDs\n# Run time: ~10s\nkeys = np.array([uuid.uuid4().int for _ in range(len(points))])",
"_____no_output_____"
],
[
"# Generate some UUIDs as keys\n# Save in NumPy format (.npz)\n# Run time: <1s\nnp.savez(\"uuid_points.npz\", keys=keys, coords=points)",
"_____no_output_____"
],
[
"# Save in compressed (zip) NumPy format (.npz)\n# Run time: ~10s\nnp.savez_compressed(\"uuid_points_compressed.npz\", keys=keys, coords=points)",
"_____no_output_____"
],
[
"# Write to SQLite with SQLiteStore\n# Run time: ~10m\npoints_sqlite_store = SQLiteStore(\"points.db\")\n_ = points_sqlite_store.append_many(annotations=(Annotation(Point(x, y)) for x, y in points))",
"_____no_output_____"
],
[
"# Load a DictionaryStore into memory by copying from the SQLiteStore\n# Run time: ~1m 30s\npoints_dict_store = DictionaryStore(Path(\"points.ndjson\"))\nfor key, value in points_sqlite_store.items():\n points_dict_store[key] = value",
"_____no_output_____"
],
[
"# Save as GeoJSON\n# Run time: ~1m 30s\npoints_sqlite_store.to_geojson(\"points.geojson\")",
"_____no_output_____"
],
[
"# Save as ndjson\n# Run time: ~1m 30s\n# Spec: https://github.com/ndjson/ndjson-spec\npoints_sqlite_store.to_ndjson(\"points.ndjson\")",
"_____no_output_____"
]
],
[
[
"### 2.1.2) Points Dataset Statistics Summary\n\n| Format | Write Time | Size |\n|-------------------------------:|-----------:|-------:|\n| SQLiteStore (.db) | 6m 20s | 893MB |\n| ndjson | 1m 23s | 667 MB |\n| GeoJSON | 1m 42s | 500 MB |\n| NumPy + UUID (.npz) | 0.5s | 165 MB |\n| NumPy + UUID Compressed (.npz) | 31s | 136 MB |\n| NumPy (.npy) | 0.1s | 76 MB |\n| NumPy Compressed (.npz) | 3.3s | 66 MB |\n\n\nNote that the points SQLite database is significantly larger than the\nNumPy arrays on disk. The numpy array is much more storage efficient\npartly because there is no R Tree index or unique identifier (UUID)\nstored for each point. For a more fair comparison, another NumPy archive\n(.npz) is created where the keys are stored along with the coordinates.\n\nAlso note that although the compressed NumPy representation is much\nsmaller, it must be decompressed in memeory before it can be used. The\nuncompressed versions may be memory mapped if their size exceeds the\navailable memory.",
"_____no_output_____"
],
[
"### 2.1.3) Simple Box Query\n\nHere we evaluate the performance of performing a simple box query on the\ndata. All points which are in the area between 128 and 256 in the x and\ny coordinates are retrieved. It is assumed that the data is already in\nmemory for the NumPy formats. In reality this would not the be case for\nthe first query, all data would have to be read from disk, which is a\nsignifican overhead. However, this cost is amortised across many\nqueries. To ensure the fairest possible comparison, it is assumed that\nmany queries will be performed, and that this data loading cost in\nnegligable.",
"_____no_output_____"
]
],
[
[
"box = Polygon.from_bounds(128, 128, 256, 256)\n\n# Time numpy\nnumpy_runs = timeit.repeat(\n (\n \"where = np.all([\"\n \"points[:, 0] > 128,\"\n \"points[:, 0] < 256,\"\n \"points[:, 1] > 128,\"\n \"points[:, 1] < 256\"\n \"], 0)\\n\"\n \"uuids = keys[where]\\n\"\n \"result = points[where]\\n\"\n ),\n globals={\"keys\": keys, \"points\": points, \"np\": np},\n number=1,\n repeat=10,\n)\n\n# Time SQLiteStore\nsqlite_runs = timeit.repeat(\n \"store.query(box)\",\n globals={\"store\": points_sqlite_store, \"box\": box},\n number=1,\n repeat=10,\n)\n\n# Time DictionaryStore\ndict_runs = timeit.repeat(\n \"store.query(box)\",\n globals={\"store\": points_dict_store, \"box\": box},\n number=1,\n repeat=10,\n)",
"_____no_output_____"
],
[
"plot_results(\n experiments=[dict_runs, sqlite_runs, numpy_runs],\n title=\"Points Box Query (5 Million Points)\",\n tick_label=[\"DictionaryStore\", \"SQLiteStore\", \"NumPy Array\"],\n)\nplt.show()",
"_____no_output_____"
]
],
[
[
"Although the NumPy array is very space efficient on disk, it is not as\nfast to query as the `SQLiteStore`. The `SQLiteStore` is likely faster\ndue to the use of the R tree index. Furthermore, the method used to\nstore the points in a NumPy array is limited in that it does not use\nUUIDs, which makes merging two datasets more difficult as the indexes of\npoints no longer uniquely identify them. Additionally, only homogeneous\ndata such as two-dimentional coordinates can be practically stored in\nthis way. If the user would like to store variable length data\nstructures such as polygons, or even mix data types by storing both\npoints and polygons, then using raw NumPy arrays in this way can become\ncumbersome and begins to offer little benefit in terms of storage\nefficient or query performance.",
"_____no_output_____"
],
[
"### 2.1.4) Polygon Query",
"_____no_output_____"
]
],
[
[
"big_triangle = Polygon(\n shell=[\n (1024, 1024),\n (1024, 4096),\n (4096, 4096),\n (1024, 1024),\n ]\n)\n\n# Time SQLiteStore\nsqlite_runs = timeit.repeat(\n \"store.query(polygon)\",\n globals={\"store\": points_sqlite_store, \"polygon\": big_triangle},\n number=1,\n repeat=10,\n)\n\n# Time DictionaryStore\ndict_runs = timeit.repeat(\n \"store.query(polygon)\",\n globals={\"store\": points_dict_store, \"polygon\": big_triangle},\n number=1,\n repeat=10,\n)",
"_____no_output_____"
],
[
"plot_results(\n experiments=[dict_runs, sqlite_runs],\n title=\"Polygon Query (5 Million Points)\",\n tick_label=[\"DictionaryStore\", \"SQLiteStore\"],\n)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## 2.2) Cell Boundary Polygons Dataset\n\nHere we generate a much larger and more complex polygon dataset. This\nconsistes of a grid of over 5 million generated cell boundary like\npolygons.",
"_____no_output_____"
]
],
[
[
"# Generate a grid of 5 million cell boundary polygons (2237 x 2237)\n# Run time: ~10m\n\nimport random\nrandom.seed(42)\n\ncell_polygons = [\n Annotation(geometry=polygon, properties={\"class\": random.randint(0, 4)})\n for polygon\n in tqdm(cell_grid(size=(2237, 2237), spacing=35), total=2237**2)\n]",
"100%|██████████| 5004169/5004169 [10:04<00:00, 8277.35it/s] \n"
]
],
[
[
"### 2.2.1) Write To Formats For Comparison",
"_____no_output_____"
]
],
[
[
"# Write to an SQLiteStore on disk (SSD for recorded times here)\n# Run time: ~30m\ncell_sqlite_store = SQLiteStore(\"cells.db\")\n_ = cell_sqlite_store.append_many(annotations=cell_polygons)",
"_____no_output_____"
],
[
"# Create a copy as an in memory DictionaryStore\n# Run time: ~5m\ncell_dict_store = DictionaryStore()\nfor key, value in tqdm( # Show a nice progress bar\n cell_sqlite_store.items(),\n total=len(cell_sqlite_store),\n leave=False,\n position=0,\n):\n cell_dict_store[key] = value",
" \r"
],
[
"# Transform into a numpy array\n# Run Time: ~1m\ncell_polygons_np = np.array(\n [np.array(a.geometry.exterior.coords) for a in tqdm(cell_polygons)],\n dtype=object\n)",
"100%|██████████| 5004169/5004169 [01:26<00:00, 58002.74it/s]\n"
],
[
"# Create an Nx4 index of (xmin, ymin, xmax, ymax) as a simple spatial\n# index to speed up the numpy query.\n# Run time: ~1m\nmin_max_index = np.array(\n [(*np.min(coords, 0), *np.max(coords, 0)) for coords in cell_polygons_np]\n)",
"_____no_output_____"
],
[
"# Write to GeoJSON\n# Run time: ~10m\n\ncell_dict_store.to_geojson(\"cells.geojson\")",
"_____no_output_____"
],
[
"# Write to line delimited JSON (ndjson)\n# Run time: ~10m\n\ncell_dict_store.to_ndjson(\"cells.ndjson\")",
"_____no_output_____"
],
[
"# Zstandard compression of ndjson to demonstrate how well it compresses.\n# Gzip may also be used but is slower to compress.\n# Run time: ~1m\n! zstd -f -k cells.ndjson -o cells.ndjson.zstd",
"cells.ndjson : 40.82% ( 8.82 GiB => 3.60 GiB, cells.ndjson.zstd) \n"
],
[
"# Zstandard compression of sqlite to demonstrate how well it compresses.\n# Gzip may also be used but is slower to compress.\n# Run time: ~20s\n! zstd -f -k cells.db -o cells.db.zstd",
"cells.db : 75.87% ( 4.87 GiB => 3.69 GiB, cells.db.zstd) \n"
],
[
"# Write as a pickle (list)\n# Run time: ~2m\nwith open(\"cells.pickle\", \"wb\") as fh:\n pickle.dump(cell_polygons, fh)",
"_____no_output_____"
],
[
"# Write as a pickle (dict)\n# Run time: ~15m\nwith open(\"cells-dict.pickle\", \"wb\") as fh:\n pickle.dump(cell_dict_store._rows, fh)",
"_____no_output_____"
],
[
"# Write dictionary store to a pickle\n# Run time: ~20m\nwith open(\"cells.pickle\", \"wb\") as fh:\n pickle.dump(cell_dict_store, fh)",
"_____no_output_____"
],
[
"# Write as numpy object array (similar to writing out with pickle),\n# Numpy cannot handle ragged arrays and therefore dtype must be object.\n# Run time: ~30m\nnp.save(\"cells.npy\", np.asanyarray(cell_polygons_np, dtype=object))",
"_____no_output_____"
],
[
"# Create UUIDs, and get the class labels for each cell boundary\n# Run time: ~2m\n_uuids = [str(uuid.uuid4) for _ in cell_polygons]\n_cls = [x.properties[\"class\"] for x in cell_polygons]",
"_____no_output_____"
],
[
"# Write as NumPy archive (.npz) with uuid and min_max_index\n# Run time: ~40m\nnp.savez(\n \"cells.npz\",\n uuids=_uuids,\n polygons=cell_polygons_np,\n min_max_index=min_max_index,\n cls=_cls,\n)\n\ndel _uuids, _cls",
"_____no_output_____"
]
],
[
[
"### 2.2.2) Time To Write Summary Statistics\n\nThe following is a summary of the time required to write each format to\ndisk and the total disk space occupied by the final output.\n\nNote that some of these formats, such as GeoJSON compress well with\nschemes such as gzip and zstd, reducing the disk space by approximately\nhalf. Statistics for zstd compressed data is also reported below. It\nshould be noted that the data must be decompressed to be usable.\nHowever, for gzip and zstd, this may be done in a streaming fashion from\ndisk.\n\n| Format | Write Time | Size |\n|------------------:|------------:|--------:|\n| SQLiteStore (.db) |33m 48.4s | 4.9 GB |\n| GeoJSON |11m 32.9s | 8.9 GB |\n| ndjson |9m 0.9s | 8.8 GB |\n| pickle |1m 2.9s | 1.8 GB |\n| zstd (SQLite) |18.2s | 3.7 GB |\n| zstd (ndjson) |43.7s | 3.6 GB |\n| NumPy (.npy) |50.3s | 1.8 GB |\n| NumPy (.npz) |55.3s | 2.6 GB |\n",
"_____no_output_____"
],
[
"### 2.2.3) Box Query",
"_____no_output_____"
]
],
[
[
"# Run time: ~5m\n\n# Setup\nxmin, ymin, xmax, ymax = 128, 12, 256, 256\nbox = Polygon.from_bounds(xmin, ymin, xmax, ymax)\n\n\n# Time DictionaryStore\ndict_runs = timeit.repeat(\n \"store.query(box)\",\n globals={\"store\": cell_dict_store, \"box\": box},\n number=1,\n repeat=3,\n)\n\n# Time SQLite store\nsqlite_runs = timeit.repeat(\n \"store.query(box)\",\n globals={\"store\": cell_sqlite_store, \"box\": box},\n number=1,\n repeat=3,\n)",
"_____no_output_____"
],
[
"# Plot results\nplot_results(\n experiments=[dict_runs, sqlite_runs],\n title=\"Box Query (5 Million Polygons)\",\n tick_label=[\n \"DictionaryStore\",\n \"SQLiteStore\",\n ],\n)\nplt.show()",
"_____no_output_____"
]
],
[
[
"### 2.2.4) Polygon Query",
"_____no_output_____"
]
],
[
[
"# Run Time: 35s\n\n# Setup\nbig_triangle = Polygon(\n shell=[\n (1024, 1024),\n (1024, 4096),\n (4096, 4096),\n (1024, 1024),\n ]\n)\n\n\n# Time DictionaryStore\ndict_runs = timeit.repeat(\n \"store.query(polygon)\",\n globals={\"store\": cell_dict_store, \"polygon\": big_triangle},\n number=1,\n repeat=3,\n)\n\n# Time SQLite store\nsqlite_runs = timeit.repeat(\n \"store.query(polygon)\",\n globals={\"store\": cell_sqlite_store, \"polygon\": big_triangle},\n number=1,\n repeat=3,\n)",
"_____no_output_____"
],
[
"# Plot results\nplot_results(\n experiments=[dict_runs, sqlite_runs],\n title=\"Polygon Query (5 Million Polygons)\",\n tick_label=[\n \"DictionaryStore\",\n \"SQLiteStore\",\n ],\n)\nplt.show()",
"_____no_output_____"
]
],
[
[
"### 2.2.5) Predicate Query",
"_____no_output_____"
]
],
[
[
"# Run Time: ~10m\n\n# Setup\nxmin, ymin, xmax, ymax = 128, 12, 256, 256\nbox = Polygon.from_bounds(xmin, ymin, xmax, ymax)\npredicate = \"props['class'] == 0\"\n\n# Time DictionaryStore\ndict_runs = timeit.repeat(\n \"store.query(box, predicate)\",\n globals={\"store\": cell_dict_store, \"box\": box, \"predicate\": predicate},\n number=1,\n repeat=3,\n)\n\n# Time SQLiteStore\nsqlite_runs = timeit.repeat(\n \"store.query(box, where=predicate)\",\n globals={\"store\": cell_sqlite_store, \"box\": box, \"predicate\": predicate},\n number=1,\n repeat=3,\n)\n\nnp_stmt = f\"\"\"\npolygons = [\n polygon\n for polygon in tqdm(cell_polygons_np)\n if np.all([np.max(polygon, 0) >= ({xmin}, {ymin}), np.min(polygon, 0) <= ({xmax}, {ymax})])\n]\n\"\"\"\n\n# Time numpy\nnumpy_runs = timeit.repeat(\n np_stmt,\n globals={\"cell_polygons_np\": cell_polygons_np, \"np\": np, \"tqdm\": lambda x: x},\n number=1,\n repeat=3,\n)\n\n# Time shapely\nshapely_runs = timeit.repeat(\n \"polygons = [box.intersects(ann.geometry) for ann in cell_polygons]\",\n globals={\"box\": box, \"cell_polygons\": cell_polygons},\n number=1,\n repeat=3,\n)\n\n# Time box indexed numpy\nnumpy_index_runs = timeit.repeat(\n \"in_box = np.all(min_max_index[:, :2] <= (xmax, ymax), 1) & np.all(min_max_index[:, 2:] >= (xmin, ymin), 1)\\n\"\n \"polygons = [p for p, w in zip(cell_polygons, in_box) if w]\",\n globals={\n \"min_max_index\": min_max_index,\n \"xmin\": xmin,\n \"ymin\": ymin,\n \"xmax\": xmax,\n \"ymax\": ymax,\n \"np\": np,\n \"cell_polygons\": cell_polygons,\n },\n number=1,\n repeat=3,\n)",
"_____no_output_____"
],
[
"# Run Time: ~5s \n\n# Plot results\nplot_results(\n experiments=[dict_runs, sqlite_runs, numpy_runs, shapely_runs, numpy_index_runs],\n title=\"Box Query\",\n tick_label=[\n \"DictionaryStore\",\n \"SQLiteStore\",\n \"NumPy\\n(Simple Loop)\",\n \"Shapely\\n(Simple Loop)\",\n \"NumPy\\n(With Bounds Index)\",\n ],\n)\nplt.xticks(rotation=90)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## 2.3) Size vs Approximate Lower Bound\n\nHere we calculate an estimated lower bound on file size by finding the\nthe Shannon entropy of each file. This tells us the theoretical minimum\nnumber of bits per byte. The lowest lower bound is then used as an\nestimate of the minimum file size possible to store the annotation data.",
"_____no_output_____"
]
],
[
[
"# Run Time: ~5m\n\n\n# Files to consider containing keys, geometry, and properties.\n# Files which are missing keys e.g. cells.pickle are excluded\n# for a fair comparison.\nfile_names = [\n \"cells-dicionary-store.pickle\",\n \"cells-dict.pickle\",\n \"cells.db\",\n \"cells.db.zstd\",\n \"cells.geojson\",\n \"cells.ndjson\",\n \"cells.ndjson.zstd\",\n]\n\n\ndef human_readible_bytes(byte_count: int) -> Tuple[int, str]:\n \"\"\"Convert bytes to human readble size and suffix.\"\"\"\n for suffix in [\"B\", \"KB\", \"MB\", \"GB\", \"TB\"]:\n if byte_count < 1024:\n return byte_count, suffix\n byte_count /= 1024\n return byte_count, \"PB\"\n\n\ndef shannon_entropy(\n fp: Path,\n sample_size: int = 1e9, # 1GiB\n stride: int = 7,\n skip: int = 1e5, # 100KiB\n) -> float:\n \"\"\"Calculate the Shannon entropy of a file from a sample.\n\n The first `skip` bytes are skipped to avoid sampling low entropy\n (highly ordered) parts which commonly occur at the beginning e.g.\n headers.\n\n Args:\n fp: File path to calculate entropy of.\n sample_size: Number of bytes to sample from the file.\n stride: Number of bytes to skip between samples.\n skip: Number of bytes to skip before sampling.\n \"\"\"\n npmmap = np.memmap(Path(fp), dtype=np.uint8, mode=\"r\")\n values, counts = np.unique(\n npmmap[int(skip) : int(skip + (sample_size * stride)) : int(stride)],\n return_counts=True,\n )\n total = np.sum(counts)\n frequencies = {v: 0 for v in range(256)}\n for v, x in zip(values, counts):\n frequencies[v] = x / total\n frequency_array = np.array(list(frequencies.values()))\n epsilon = 1e-16\n return -np.sum(frequency_array * np.log2(frequency_array + epsilon))\n\n\n# Find the min across all of the representations for the lowest lower\n# bound.\nbytes_lower_bounds = {\n path: (\n shannon_entropy(Path(path)) / 8 * len(np.memmap(path, dtype=np.uint8, mode=\"r\"))\n )\n for path in tqdm([Path(\".\") / name for name in file_names], position=0, leave=False)\n}\n\nlowest_bytes_lower_bound = min(bytes_lower_bounds.values())\n\nsize, suffix = human_readible_bytes(lowest_bytes_lower_bound)\nprint(f\"Approximate Lower Bound Size: {size:.2f} {suffix}\")",
" "
]
],
[
[
"### Plot Results",
"_____no_output_____"
]
],
[
[
"# Get file sizes\nfile_sizes = {path: path.stat().st_size for path in [Path(\".\") / name for name in file_names]}\n\n# Sort by size\nfile_sizes = {k: v for k, v in sorted(file_sizes.items(), key=lambda x: x[1])}\n\n# Plot\nplt.bar(\n x=range(len(file_sizes)),\n height=file_sizes.values(),\n tick_label=[p.name for p in file_sizes],\n color=[f\"C{i}\" for i in range(len(file_sizes))],\n)\nplt.xlabel(\"File Name\")\nplt.ylabel(\"Bytes\")\nplt.xticks(rotation=90)\nplt.hlines(\n y=lowest_bytes_lower_bound,\n xmin=-0.5,\n xmax=len(file_sizes) - 0.5,\n linestyles=\"dashed\",\n color=\"black\",\n label=\"Approximate Bytes Lower Bound\",\n)\nplt.legend()\nplt.tight_layout()\nplt.title(\"Polygon Annotation File Sizes\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"The SQLite representation (4.9GB) appears to be quite compact compared\nwith GeoJSON and ndjson. Although not as compact as a dictionary pickle\nor Zstandard compressed ndjson, it offers a good compromise between\ncompactness and read performance.",
"_____no_output_____"
],
[
"# 3: Extra Bits\n\n## 3.1) Space Saving\n\nA lot of space can be saved by rounding the coordinates to the nearest\ninteger when storing them. Below we make a copy of the dataset with all\ncoordinates rounded.",
"_____no_output_____"
]
],
[
[
"# Run Time: ~50m\n! rm integer-cells.db\nint_cell_sqlite_store = SQLiteStore(\"integer-cells.db\")\n\n# We use batches of 1000 to speed up appending\nbatch = {}\nfor key, annotation in tqdm(cell_sqlite_store.items(), total=len(cell_sqlite_store)):\n geometry = Polygon(np.array(annotation.geometry.exterior.coords).round())\n rounded_annotation = Annotation(geometry, annotation.properties)\n batch[key] = rounded_annotation\n if len(batch) >= 1000:\n int_cell_sqlite_store.append_many(batch.values(), batch.keys())\n batch = {}\n_ = int_cell_sqlite_store.append_many(batch.values(), batch.keys())",
"100%|██████████| 10008338/10008338 [51:00<00:00, 3270.16it/s] \n"
]
],
[
[
"Here the database size is reduced to 2.9GB, down from 4.9GB.\nAdditionally, when using integer coordinates, the database compresses\nmuch better. Zstandard can compress to approximately 60% of the\noriginal size (and 35% of the floating point coordinate\ndatabase size). This may be done for archival purposes.",
"_____no_output_____"
]
],
[
[
"# Run time: ~15s\n! zstd -f -k integer-cells.db -o integer-cells.db.zstd",
"integer-cells.db : 60.58% ( 2.86 GiB => 1.73 GiB, integer-cells.db.zstd) \n"
]
],
[
[
"With higher (slower) compression settings the space can be further\nreduced for long term storage.",
"_____no_output_____"
]
],
[
[
"# Run time: ~20m\n! zstd -f -k -19 --long integer-cells.db -o integer-cells.db.19.zstd",
"integer-cells.db : 51.22% ( 2.86 GiB => 1.47 GiB, integer-cells.db.19.zstd) \n"
]
],
[
[
"## 3.2) Feature Comparison Summary\n\nHere we briefly summarise some of the positives and negatives of each format and construct a comparison matrix.\n\n**GeoJSON**\n\n*Positives*\n\n+ Simple, based JSON which is well known.\n+ Well defined with a public specification.\n+ Popular format for geometry, many tools which work with it.\n+ Fast to write.\n\n*Negatives*\n\n- Requires loading the whole file into memory for parsing. Some\n specialised parsers can, in some situations, reduce or avoid this but\n it is not possible in general.\n- Not a very compact representation.\n\n**ndjson (One GeoJSON Feature Per Line)**\n\n*Positives*\n\n+ Simple.\n+ Better to parse than JSON/GeoJSON. Each line can be parsed\n independently.\n+ Many tools to parse JSON lines.\n+ Fast to write.\n\n*Negatives*\n\n- Not a very compact representation.\n- Requires loading the whole dataset from disk before querying OR\n scanning through and reparsing each line for each query.\n- Amending annotations can be tricky. The easiest way is to blank out a\n line and append a modified copy each time. This could end up\n fragmenting the file and wasting a lot of space. More complex methods\n could be developed to reduce fragmenting the file.\n\n**pickle**\n\n*Positives*\n\n+ Fast to write.\n\n*Negatives*\n\n- Vulnerable to arbitrary code execution when loading from disk.\n- Requires loading the whole dataset into memory for querying.\n\n**SQLite (SQLiteStore Flavour)**\n\n*Positives*\n\n+ Very fast to query (uses an R-TREE index to accelerate\n spatial queries).\n+ Does not require loading data into memory before querying.\n+ Possible to index property lookups.\n\n*Negatives*\n\n- Not the most compact representation on disk.\n\n### Feature Matrix\n\n| Format | Size On-Disk | Size In-Memory | Partial Reads | Serialization | Query Performance |\n|----------------:|:---------------|:---------------|:--------------|:----------------|:------------------|\n| SQLiteStore | Medium | Small | Yes | Slow | Fast |\n| GeoJSON | Large | Large | No | Fast | Slow |\n| ndjson | Large | Large | Yes | Fast | Medium |\n| pickle | Small | Medium | No | Medium | Slow |\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e77a7d2679f8b3bab8b656c69980692c2a6c3a23 | 27,251 | ipynb | Jupyter Notebook | exercises/.ipynb_checkpoints/synthetic_features_and_outliers-checkpoint.ipynb | Kabongosalomon/Crash-Course-Machine-Learning- | ccbe645f892f5e70d06bfb497f9fb8217b895834 | [
"Apache-2.0"
] | 1 | 2019-04-03T21:20:48.000Z | 2019-04-03T21:20:48.000Z | exercises/.ipynb_checkpoints/synthetic_features_and_outliers-checkpoint.ipynb | Kabongosalomon/Crash-Course-Machine-Learning- | ccbe645f892f5e70d06bfb497f9fb8217b895834 | [
"Apache-2.0"
] | null | null | null | exercises/.ipynb_checkpoints/synthetic_features_and_outliers-checkpoint.ipynb | Kabongosalomon/Crash-Course-Machine-Learning- | ccbe645f892f5e70d06bfb497f9fb8217b895834 | [
"Apache-2.0"
] | null | null | null | 30.967045 | 250 | 0.493486 | [
[
[
"#### Copyright 2017 Google LLC.",
"_____no_output_____"
]
],
[
[
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.",
"_____no_output_____"
]
],
[
[
"# Synthetic Features and Outliers",
"_____no_output_____"
],
[
"**Learning Objectives:**\n * Create a synthetic feature that is the ratio of two other features\n * Use this new feature as an input to a linear regression model\n * Improve the effectiveness of the model by identifying and clipping (removing) outliers out of the input data",
"_____no_output_____"
],
[
"Let's revisit our model from the previous First Steps with TensorFlow exercise. \n\nFirst, we'll import the California housing data into a *pandas* `DataFrame`:",
"_____no_output_____"
],
[
"## Setup",
"_____no_output_____"
]
],
[
[
"from __future__ import print_function\n\nimport math\n\nfrom IPython import display\nfrom matplotlib import cm\nfrom matplotlib import gridspec\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport sklearn.metrics as metrics\nimport tensorflow as tf\nfrom tensorflow.python.data import Dataset\n\ntf.logging.set_verbosity(tf.logging.ERROR)\npd.options.display.max_rows = 10\npd.options.display.float_format = '{:.1f}'.format\n\ncalifornia_housing_dataframe = pd.read_csv(\"https://download.mlcc.google.com/mledu-datasets/california_housing_train.csv\", sep=\",\")\n\ncalifornia_housing_dataframe = california_housing_dataframe.reindex(\n np.random.permutation(california_housing_dataframe.index))\ncalifornia_housing_dataframe[\"median_house_value\"] /= 1000.0\ncalifornia_housing_dataframe",
"_____no_output_____"
]
],
[
[
"Next, we'll set up our input function, and define the function for model training:",
"_____no_output_____"
]
],
[
[
"def my_input_fn(features, targets, batch_size=1, shuffle=True, num_epochs=None):\n \"\"\"Trains a linear regression model of one feature.\n \n Args:\n features: pandas DataFrame of features\n targets: pandas DataFrame of targets\n batch_size: Size of batches to be passed to the model\n shuffle: True or False. Whether to shuffle the data.\n num_epochs: Number of epochs for which data should be repeated. None = repeat indefinitely\n Returns:\n Tuple of (features, labels) for next data batch\n \"\"\"\n \n # Convert pandas data into a dict of np arrays.\n features = {key:np.array(value) for key,value in dict(features).items()} \n \n # Construct a dataset, and configure batching/repeating.\n ds = Dataset.from_tensor_slices((features,targets)) # warning: 2GB limit\n ds = ds.batch(batch_size).repeat(num_epochs)\n \n # Shuffle the data, if specified.\n if shuffle:\n ds = ds.shuffle(buffer_size=10000)\n \n # Return the next batch of data.\n features, labels = ds.make_one_shot_iterator().get_next()\n return features, labels",
"_____no_output_____"
],
[
"def train_model(learning_rate, steps, batch_size, input_feature):\n \"\"\"Trains a linear regression model.\n \n Args:\n learning_rate: A `float`, the learning rate.\n steps: A non-zero `int`, the total number of training steps. A training step\n consists of a forward and backward pass using a single batch.\n batch_size: A non-zero `int`, the batch size.\n input_feature: A `string` specifying a column from `california_housing_dataframe`\n to use as input feature.\n \n Returns:\n A Pandas `DataFrame` containing targets and the corresponding predictions done\n after training the model.\n \"\"\"\n \n periods = 10\n steps_per_period = steps / periods\n\n my_feature = input_feature\n my_feature_data = california_housing_dataframe[[my_feature]].astype('float32')\n my_label = \"median_house_value\"\n targets = california_housing_dataframe[my_label].astype('float32')\n\n # Create input functions.\n training_input_fn = lambda: my_input_fn(my_feature_data, targets, batch_size=batch_size)\n predict_training_input_fn = lambda: my_input_fn(my_feature_data, targets, num_epochs=1, shuffle=False)\n \n # Create feature columns.\n feature_columns = [tf.feature_column.numeric_column(my_feature)]\n \n # Create a linear regressor object.\n my_optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)\n my_optimizer = tf.contrib.estimator.clip_gradients_by_norm(my_optimizer, 5.0)\n linear_regressor = tf.estimator.LinearRegressor(\n feature_columns=feature_columns,\n optimizer=my_optimizer\n )\n\n # Set up to plot the state of our model's line each period.\n plt.figure(figsize=(15, 6))\n plt.subplot(1, 2, 1)\n plt.title(\"Learned Line by Period\")\n plt.ylabel(my_label)\n plt.xlabel(my_feature)\n sample = california_housing_dataframe.sample(n=300)\n plt.scatter(sample[my_feature], sample[my_label])\n colors = [cm.coolwarm(x) for x in np.linspace(-1, 1, periods)]\n\n # Train the model, but do so inside a loop so that we can periodically assess\n # loss metrics.\n print(\"Training model...\")\n print(\"RMSE (on training data):\")\n root_mean_squared_errors = []\n for period in range (0, periods):\n # Train the model, starting from the prior state.\n linear_regressor.train(\n input_fn=training_input_fn,\n steps=steps_per_period,\n )\n # Take a break and compute predictions.\n predictions = linear_regressor.predict(input_fn=predict_training_input_fn)\n predictions = np.array([item['predictions'][0] for item in predictions])\n \n # Compute loss.\n root_mean_squared_error = math.sqrt(\n metrics.mean_squared_error(predictions, targets))\n # Occasionally print the current loss.\n print(\" period %02d : %0.2f\" % (period, root_mean_squared_error))\n # Add the loss metrics from this period to our list.\n root_mean_squared_errors.append(root_mean_squared_error)\n # Finally, track the weights and biases over time.\n # Apply some math to ensure that the data and line are plotted neatly.\n y_extents = np.array([0, sample[my_label].max()])\n \n weight = linear_regressor.get_variable_value('linear/linear_model/%s/weights' % input_feature)[0]\n bias = linear_regressor.get_variable_value('linear/linear_model/bias_weights')\n \n x_extents = (y_extents - bias) / weight\n x_extents = np.maximum(np.minimum(x_extents,\n sample[my_feature].max()),\n sample[my_feature].min())\n y_extents = weight * x_extents + bias\n plt.plot(x_extents, y_extents, color=colors[period]) \n print(\"Model training finished.\")\n\n # Output a graph of loss metrics over periods.\n plt.subplot(1, 2, 2)\n plt.ylabel('RMSE')\n plt.xlabel('Periods')\n plt.title(\"Root Mean Squared Error vs. Periods\")\n plt.tight_layout()\n plt.plot(root_mean_squared_errors)\n\n # Create a table with calibration data.\n calibration_data = pd.DataFrame()\n calibration_data[\"predictions\"] = pd.Series(predictions)\n calibration_data[\"targets\"] = pd.Series(targets)\n display.display(calibration_data.describe())\n\n print(\"Final RMSE (on training data): %0.2f\" % root_mean_squared_error)\n \n return calibration_data",
"_____no_output_____"
]
],
[
[
"## Task 1: Try a Synthetic Feature\n\nBoth the `total_rooms` and `population` features count totals for a given city block.\n\nBut what if one city block were more densely populated than another? We can explore how block density relates to median house value by creating a synthetic feature that's a ratio of `total_rooms` and `population`.\n\nIn the cell below, create a feature called `rooms_per_person`, and use that as the `input_feature` to `train_model()`.\n\nWhat's the best performance you can get with this single feature by tweaking the learning rate? (The better the performance, the better your regression line should fit the data, and the lower\nthe final RMSE should be.)",
"_____no_output_____"
],
[
"**NOTE**: You may find it helpful to add a few code cells below so you can try out several different learning rates and compare the results. To add a new code cell, hover your cursor directly below the center of this cell, and click **CODE**.",
"_____no_output_____"
]
],
[
[
"#\n# YOUR CODE HERE\n#\ncalifornia_housing_dataframe[\"rooms_per_person\"] =\n\ncalibration_data = train_model(\n learning_rate=0.00005,\n steps=500,\n batch_size=5,\n input_feature=\"rooms_per_person\"\n)",
"_____no_output_____"
]
],
[
[
"### Solution\n\nClick below for a solution.",
"_____no_output_____"
]
],
[
[
"california_housing_dataframe[\"rooms_per_person\"] = (\n california_housing_dataframe[\"total_rooms\"] / california_housing_dataframe[\"population\"])\n\ncalibration_data = train_model(\n learning_rate=0.05,\n steps=500,\n batch_size=5,\n input_feature=\"rooms_per_person\")",
"_____no_output_____"
]
],
[
[
"## Task 2: Identify Outliers\n\nWe can visualize the performance of our model by creating a scatter plot of predictions vs. target values. Ideally, these would lie on a perfectly correlated diagonal line.\n\nUse Pyplot's [`scatter()`](https://matplotlib.org/gallery/shapes_and_collections/scatter.html) to create a scatter plot of predictions vs. targets, using the rooms-per-person model you trained in Task 1.\n\nDo you see any oddities? Trace these back to the source data by looking at the distribution of values in `rooms_per_person`.",
"_____no_output_____"
]
],
[
[
"# YOUR CODE HERE",
"_____no_output_____"
]
],
[
[
"### Solution\n\nClick below for the solution.",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(15, 6))\nplt.subplot(1, 2, 1)\nplt.scatter(calibration_data[\"predictions\"], calibration_data[\"targets\"])",
"_____no_output_____"
]
],
[
[
"The calibration data shows most scatter points aligned to a line. The line is almost vertical, but we'll come back to that later. Right now let's focus on the ones that deviate from the line. We notice that they are relatively few in number.\n\nIf we plot a histogram of `rooms_per_person`, we find that we have a few outliers in our input data:",
"_____no_output_____"
]
],
[
[
"plt.subplot(1, 2, 2)\n_ = california_housing_dataframe[\"rooms_per_person\"].hist()",
"_____no_output_____"
]
],
[
[
"## Task 3: Clip Outliers\n\nSee if you can further improve the model fit by setting the outlier values of `rooms_per_person` to some reasonable minimum or maximum.\n\nFor reference, here's a quick example of how to apply a function to a Pandas `Series`:\n\n clipped_feature = my_dataframe[\"my_feature_name\"].apply(lambda x: max(x, 0))\n\nThe above `clipped_feature` will have no values less than `0`.",
"_____no_output_____"
]
],
[
[
"# YOUR CODE HERE",
"_____no_output_____"
]
],
[
[
"### Solution\n\nClick below for the solution.",
"_____no_output_____"
],
[
"The histogram we created in Task 2 shows that the majority of values are less than `5`. Let's clip `rooms_per_person` to 5, and plot a histogram to double-check the results.",
"_____no_output_____"
]
],
[
[
"california_housing_dataframe[\"rooms_per_person\"] = (\n california_housing_dataframe[\"rooms_per_person\"]).apply(lambda x: min(x, 5))\n\n_ = california_housing_dataframe[\"rooms_per_person\"].hist()",
"_____no_output_____"
]
],
[
[
"To verify that clipping worked, let's train again and print the calibration data once more:",
"_____no_output_____"
]
],
[
[
"calibration_data = train_model(\n learning_rate=0.05,\n steps=500,\n batch_size=5,\n input_feature=\"rooms_per_person\")",
"_____no_output_____"
],
[
"_ = plt.scatter(calibration_data[\"predictions\"], calibration_data[\"targets\"])",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e77a89abec4f4de26ea2eab8ca8624550e55095d | 443,392 | ipynb | Jupyter Notebook | HALEM Notebooks/Graduation Notebooks/Single route results/Total plot.ipynb | Pietervanhalem/Pieters-Personal-Repository | c31e3c86b1d42f29876455e8553f350d4d527ee5 | [
"MIT"
] | 2 | 2020-02-26T13:02:44.000Z | 2020-03-06T07:09:10.000Z | HALEM Notebooks/Graduation Notebooks/Single route results/Total plot.ipynb | Pietervanhalem/Pieters-Personal-Repository | c31e3c86b1d42f29876455e8553f350d4d527ee5 | [
"MIT"
] | 11 | 2020-03-06T07:17:10.000Z | 2022-02-26T22:32:59.000Z | HALEM Notebooks/Graduation Notebooks/Single route results/Total plot.ipynb | Pietervanhalem/Personal-Code-Examples | c31e3c86b1d42f29876455e8553f350d4d527ee5 | [
"MIT"
] | null | null | null | 1,084.08802 | 351,180 | 0.947067 | [
[
[
"import datetime, time\nimport platform\nimport simpy\nimport shapely.geometry\nfrom simplekml import Kml, Style\nimport numpy as np\n\nimport halem.Base_functions as halem\nimport halem.Mesh_maker as Mesh_maker\nimport halem.Functions as Functions\nimport halem.Calc_path as Calc_path\n\nimport pickle\nimport networkx as nx\n\nimport matplotlib.pyplot as plt\nplt.style.use('ggplot')\nfrom cartopy import config\nimport cartopy.crs as ccrs\nimport cartopy.feature as cfeature\nfrom matplotlib.collections import LineCollection\nfrom matplotlib.colors import ListedColormap, BoundaryNorm\nfrom scipy.interpolate import griddata\n\nimport netCDF4\nfrom netCDF4 import Dataset, num2date\nfrom scipy.spatial import Delaunay\nfrom shapely.geometry import Point\nfrom shapely.geometry.polygon import Polygon\n\ndef scale_bar_left(ax, bars=4, length=4, location=(0.1, 0.05), linewidth=3, col='black'):\n \"\"\"\n ax is the axes to draw the scalebar on.\n bars is the number of subdivisions of the bar (black and white chunks)\n length is the length of the scalebar in km.\n location is left side of the scalebar in axis coordinates.\n (ie. 0 is the left side of the plot)\n linewidth is the thickness of the scalebar.\n color is the color of the scale bar\n \"\"\"\n # Get the limits of the axis in lat long\n llx0, llx1, lly0, lly1 = ax.get_extent(ccrs.PlateCarree())\n # Make tmc aligned to the left of the map,\n # vertically at scale bar location\n sbllx = llx0 + (llx1 - llx0) * location[0]\n sblly = lly0 + (lly1 - lly0) * location[1]\n tmc = ccrs.TransverseMercator(sbllx, sblly)\n # Get the extent of the plotted area in coordinates in metres\n x0, x1, y0, y1 = ax.get_extent(tmc)\n # Turn the specified scalebar location into coordinates in metres\n sbx = x0 + (x1 - x0) * location[0]\n sby = y0 + (y1 - y0) * location[1]\n\n # Calculate a scale bar length if none has been given\n # (Theres probably a more pythonic way of rounding the number but this works)\n if not length:\n length = (x1 - x0) / 5000 # in km\n ndim = int(np.floor(np.log10(length))) # number of digits in number\n length = round(length, -ndim) # round to 1sf\n\n # Returns numbers starting with the list\n def scale_number(x):\n if str(x)[0] in ['1', '2', '5']:\n return int(x)\n else:\n return scale_number(x - 10 ** ndim)\n\n length = scale_number(length)\n\n # Generate the x coordinate for the ends of the scalebar\n bar_xs = [sbx, sbx + length * 1000 / bars]\n # Plot the scalebar chunks\n barcol = 'white'\n for i in range(0, bars):\n # plot the chunk\n ax.plot(bar_xs, [sby, sby], transform=tmc, color=barcol, linewidth=linewidth)\n # alternate the colour\n if barcol == 'white':\n barcol = 'dimgrey'\n else:\n barcol = 'white'\n # Generate the x coordinate for the number\n bar_xt = sbx + i * length * 1000 / bars\n # Plot the scalebar label for that chunk\n ax.text(bar_xt, sby, str(round(i * length / bars)), transform=tmc,\n horizontalalignment='center', verticalalignment='bottom',\n color=col)\n # work out the position of the next chunk of the bar\n bar_xs[0] = bar_xs[1]\n bar_xs[1] = bar_xs[1] + length * 1000 / bars\n # Generate the x coordinate for the last number\n bar_xt = sbx + length * 1000\n # Plot the last scalebar label\n ax.text(bar_xt, sby, str(round(length)), transform=tmc,\n horizontalalignment='center', verticalalignment='bottom',\n color=col)\n # Plot the unit label below the bar\n bar_xt = sbx + length * 1000 / 2\n bar_yt = y0 + (y1 - y0) * (location[1] / 4)\n ax.text(bar_xt, bar_yt, 'km', transform=tmc, horizontalalignment='center',\n verticalalignment='bottom', color=col)",
"_____no_output_____"
],
[
"coords_WGS = np.loadtxt('E:/Use_case_Schouwen/baty_WGS.csv') \n\nload_factor =np.array([0]) # Roadmap11\n \nstart = [3.674, 51.70969009] # Location of the koppelpunt (lon, lat)\nstop = [3.522637481591586,51.76880095558772] # Location of the dredging area (lon, lat)\nVolume = 425_500 # Total volume to be dregded (m^3)\n\nunloading_rate = 1.5\nloading_rate = 1.5\nukc = 1.0 # Under Keel clearance (m)\nWWL = 20 # Width on Water Line (m)\nLWL = 80 # Length on Water Line (m)\nhopper_capacity = 4000 # Maximal capacity of the hopper (m^3)\nV_full = 10*0.514444444 # Velocity in deep water when maximal loaded (m/s)\nV_emp = 12*0.514444444 # Maximal sailing velocity empty in deep water (m/s)\nT_full = 6.5 # Draft when maximal Loaded (m)\nT_emp = 3.5 # Draft When empty (m)\nWVPI_full = 10000 # Weight when maximal loaded (tf)\nWVPI_empt = 4000 # Weight empty (tf)\n\nvship = [[V_emp]]",
"_____no_output_____"
],
[
"files = [\n '01_DCSM-FM_100m/Roadmap11SIM',\n '02_DCSM-FM_100m NB3/Roadmap11SIM',\n '03_Zuno_real_data/Roadmap11SIM',\n '03_Zuno_real_data NB3/Roadmap11SIM'\n]\n\nPaths = []\ntime_paths = []\ndistances = []\n\nfor name_textfile_load in files:\n print('done')\n with open(name_textfile_load, 'rb') as input:\n Roadmap = pickle.load(input)\n\n\n\n ind = halem.Calc_path.Has_route.find_startstop(None, start[::-1], Roadmap.nodes)\n ind = np.argwhere(Roadmap.WD[ind,:] == Roadmap.WD[ind,75:125].max())[0][0]\n print(Roadmap.WD[ind,75:125].max(), name_textfile_load)\n t0 = datetime.datetime.fromtimestamp(Roadmap.t[ind]+12).strftime('%d/%m/%Y %H:%M:%S')\n\n Path, timePath, dist = halem.HALEM_time(start,\n stop,\n t0 ,\n vship[0][0],\n Roadmap\n )\n\n Paths.append(Path)\n time_paths.append(timePath)\n distances.append(dist)\n\n\n ind = halem.Calc_path.Has_route.find_startstop(None, start[::-1], Roadmap.nodes)\n ind = np.argwhere(Roadmap.WD[ind,:] == Roadmap.WD[ind,:].min())[0][0]\n print(Roadmap.WD[ind,75:125].min(), name_textfile_load)\n t1 = datetime.datetime.fromtimestamp(Roadmap.t[ind]).strftime('%d/%m/%Y %H:%M:%S')\n\n Path2, timePath2, dist2 = halem.HALEM_time(start, \n stop,\n t1 ,\n vship[0][0],\n Roadmap\n )\n Paths.append(Path2)\n time_paths.append(timePath2)\n distances.append(dist2)\n",
"done\n16.819456392313686 01_DCSM-FM_100m/Roadmap11SIM\n6.766525443656578 01_DCSM-FM_100m/Roadmap11SIM\ndone\n16.819456392313686 02_DCSM-FM_100m NB3/Roadmap11SIM\n6.766525443656578 02_DCSM-FM_100m NB3/Roadmap11SIM\ndone\n12.861028989796681 03_Zuno_real_data/Roadmap11SIM\n13.398964103121996 03_Zuno_real_data/Roadmap11SIM\ndone\n12.861028989796681 03_Zuno_real_data NB3/Roadmap11SIM\n13.398964103121996 03_Zuno_real_data NB3/Roadmap11SIM\n"
],
[
"# -----------------------------------------------------------------------------\n# -----------------------------------------------------------------------------\n# Plot Background\n# -----------------------------------------------------------------------------\n# -----------------------------------------------------------------------------\n\nD_emp = 4.0\nD_full = 8.0\nukc = 1.0\ntide = -1.3\n\nN = 100\nx_r = np.arange(coords_WGS[:,0].min(), coords_WGS[:,0].max(), (coords_WGS[:,0].max() - coords_WGS[:,0].min())/N)\ny_r = np.arange(coords_WGS[:,1].min(), coords_WGS[:,1].max(), (coords_WGS[:,1].max() - coords_WGS[:,1].min())/N)\ny_r, x_r = np.meshgrid(y_r,x_r)\n\nWD_r = tide - griddata(coords_WGS[:,:2], coords_WGS[:,2], (x_r, y_r), method= 'linear')\nWD_r[np.isnan(WD_r)] = 0\nWD_r[WD_r<-1000] = 0\ncval = [-1000,D_emp + ukc -3.3, D_emp +ukc, D_full+ukc, 100]\ncval2 = [D_emp + ukc - 3.3, D_emp +ukc, D_full+ukc]\n\nfig = plt.figure(figsize = (20,20))\n\nax = plt.subplot(projection=ccrs.Mercator())\nim = plt.contourf(x_r,y_r,WD_r,cval,\n transform=ccrs.PlateCarree(), \n colors = ('tab:red','sandybrown', 'cornflowerblue', 'darkblue'),\n alpha = 0.75\n )\nplt.contour(x_r,y_r,WD_r,cval2,transform=ccrs.PlateCarree(), colors = 'black')\nax.add_feature(cfeature.NaturalEarthFeature('physical', 'land', '10m', edgecolor='face', facecolor='palegoldenrod'))\nax.coastlines(resolution='10m', color='darkgoldenrod', linewidth=3)\nax.gridlines(color = 'grey', zorder = 3)\nax.set_extent([coords_WGS[:,0].min(),coords_WGS[:,0].max(),coords_WGS[:,1].min()*1.0015,coords_WGS[:,1].max()*0.998])\n\n# -----------------------------------------------------------------------------\n# -----------------------------------------------------------------------------\n# Calclate different routes \n# -----------------------------------------------------------------------------\n# Calculation at HHW and at LLW for a empty shipt from nourishment to dredging area\n# -----------------------------------------------------------------------------\n\nlabels = [\n 'FM model nb = 1 at HW',\n 'FM model nb = 1 at LW',\n 'FM model nb = 3 at HW',\n 'FM model nb = 3 at LW',\n 'Zuno model nb = 1 at HW',\n 'Zuno model nb = 1 at LW',\n 'Zuno model nb = 3 at HW',\n 'Zuno model nb = 3 at LW',\n \n]\n\ncolors = [\n 'k',\n 'tab:grey',\n 'lightgrey',\n 'darkgrey',\n \n 'tab:red',\n 'darkred',\n 'pink',\n 'coral'\n]\n\n\nfor i, Path in enumerate(Paths):\n plt.plot(Path[:,0],\n Path[:,1],\n transform=ccrs.PlateCarree(),\n linewidth =5,\n markersize = 3,\n label = labels[i],\n color = colors[i]\n )\n \n\nax.legend(prop={'size': 15})\n\nscale_bar_left(ax)\n\nplt.plot(start[0], \n start[1],\n 'o',\n color = 'tab:green',\n transform=ccrs.PlateCarree(), \n label = 'Nourishment location', \n markersize = 15\n )\n\nplt.plot(stop[0], \n stop[1], \n 'o',color = 'tab:purple',\n transform=ccrs.PlateCarree() , \n label = 'Mining location', \n markersize = 15\n )\n\nfig.savefig('Sinlge_route_optimisation.svg')\nfig.savefig('Sinlge_route_optimisation')\nplt.show()",
"_____no_output_____"
],
[
"fig = plt.figure(figsize=(10,10))\nfor i in range(8):\n plt.plot(\n (time_paths[i][:-1] - time_paths[i][0]) / 3600,\n distances[i]/1000, \n label = labels[i],\n color = colors[i]\n )\n\nplt.legend()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code"
]
] |
e77a90c738c61f1bf5e9de69780810a3cdbd5770 | 362,289 | ipynb | Jupyter Notebook | examples/notebooks/mednist_GAN_workflow.ipynb | BRAINSia/MONAI | 04e1c345fc840f5a1b6504ee5857d5a9feb27d84 | [
"Apache-2.0"
] | null | null | null | examples/notebooks/mednist_GAN_workflow.ipynb | BRAINSia/MONAI | 04e1c345fc840f5a1b6504ee5857d5a9feb27d84 | [
"Apache-2.0"
] | null | null | null | examples/notebooks/mednist_GAN_workflow.ipynb | BRAINSia/MONAI | 04e1c345fc840f5a1b6504ee5857d5a9feb27d84 | [
"Apache-2.0"
] | null | null | null | 555.657975 | 117,315 | 0.857953 | [
[
[
"# GAN Workflow Engine with the MedNIST Dataset\n\nThe MONAI framework can be used to easily design, train, and evaluate generative adversarial networks.\nThis notebook exemplifies using MONAI components to design and train a simple GAN model to reconstruct images of Hand CT scans.\n\nRead the [MONAI Mednist GAN Tutorial](https://github.com/Project-MONAI/MONAI/blob/master/examples/notebooks/mednist_GAN_tutorial.ipynb) for details about the network architecture and loss functions.\n\n**Table of Contents**\n\n1. Setup\n2. Initialize MONAI Components\n * Create image transform chain\n * Create dataset and dataloader\n * Define generator and discriminator\n * Create training handlers\n * Create GanTrainer\n3. Run Training\n4. Evaluate Results\n\n[](https://colab.research.google.com/github/Project-MONAI/MONAI/blob/master/examples/notebooks/mednist_GAN_workflow.ipynb)",
"_____no_output_____"
],
[
"## Step 1: Setup\n\n### Setup environment",
"_____no_output_____"
]
],
[
[
"%pip install -qU \"monai[ignite]\"",
"Note: you may need to restart the kernel to use updated packages.\n"
],
[
"# temporarily need this, FIXME remove when d93c0a6 released\n%pip install -qU git+https://github.com/Project-MONAI/MONAI#egg=MONAI",
"Note: you may need to restart the kernel to use updated packages.\n"
],
[
"%pip install -qU matplotlib\n%matplotlib inline",
"Note: you may need to restart the kernel to use updated packages.\n"
]
],
[
[
"### Setup imports",
"_____no_output_____"
]
],
[
[
"import logging\nimport os\nimport shutil\nimport sys\nimport tempfile\n\nimport IPython\nimport matplotlib.pyplot as plt\nimport torch\n\nfrom monai.apps import download_and_extract\nfrom monai.config import print_config\nfrom monai.data import CacheDataset, DataLoader\nfrom monai.engines import GanKeys, GanTrainer, default_make_latent\nfrom monai.handlers import CheckpointSaver, MetricLogger, StatsHandler\nfrom monai.networks import normal_init\nfrom monai.networks.nets import Discriminator, Generator\nfrom monai.transforms import (\n AddChannelD,\n Compose,\n LoadPNGD,\n RandFlipD,\n RandRotateD,\n RandZoomD,\n ScaleIntensityD,\n ToTensorD,\n)\nfrom monai.utils import set_determinism\n\nprint_config()",
"MONAI version: 0.2.0+74.g8e5a53e\nPython version: 3.7.5 (default, Nov 7 2019, 10:50:52) [GCC 8.3.0]\nNumpy version: 1.19.1\nPytorch version: 1.6.0\n\nOptional dependencies:\nPytorch Ignite version: 0.3.0\nNibabel version: NOT INSTALLED or UNKNOWN VERSION.\nscikit-image version: NOT INSTALLED or UNKNOWN VERSION.\nPillow version: 7.2.0\nTensorboard version: NOT INSTALLED or UNKNOWN VERSION.\n\nFor details about installing the optional dependencies, please visit:\n https://docs.monai.io/en/latest/installation.html#installing-the-recommended-dependencies\n\n"
]
],
[
[
"### Setup data directory\n\nYou can specify a directory with the `MONAI_DATA_DIRECTORY` environment variable. \nThis allows you to save results and reuse downloads. \nIf not specified a temporary directory will be used.",
"_____no_output_____"
]
],
[
[
"directory = os.environ.get(\"MONAI_DATA_DIRECTORY\")\nroot_dir = tempfile.mkdtemp() if directory is None else directory\nprint(root_dir)",
"/home/bengorman/notebooks/\n"
]
],
[
[
"### Download dataset\n\nDownloads and extracts the dataset.\n\nThe MedNIST dataset was gathered from several sets from [TCIA](https://wiki.cancerimagingarchive.net/display/Public/Data+Usage+Policies+and+Restrictions),\n[the RSNA Bone Age Challenge](http://rsnachallenges.cloudapp.net/competitions/4),\nand [the NIH Chest X-ray dataset](https://cloud.google.com/healthcare/docs/resources/public-datasets/nih-chest).\n\nThe dataset is kindly made available by [Dr. Bradley J. Erickson M.D., Ph.D.](https://www.mayo.edu/research/labs/radiology-informatics/overview) (Department of Radiology, Mayo Clinic)\nunder the Creative Commons [CC BY-SA 4.0 license](https://creativecommons.org/licenses/by-sa/4.0/).\n\n\nIf you use the MedNIST dataset, please acknowledge the source, e.g. \nhttps://github.com/Project-MONAI/MONAI/blob/master/examples/notebooks/mednist_tutorial.ipynb.",
"_____no_output_____"
]
],
[
[
"resource = \"https://www.dropbox.com/s/5wwskxctvcxiuea/MedNIST.tar.gz?dl=1\"\nmd5 = \"0bc7306e7427e00ad1c5526a6677552d\"\n\ncompressed_file = os.path.join(root_dir, \"MedNIST.tar.gz\")\ndata_dir = os.path.join(root_dir, \"MedNIST\")\n\ndownload_and_extract(resource, compressed_file, root_dir, md5)",
"file /home/bengorman/notebooks/MedNIST.tar.gz exists, skip downloading.\nextracted file /home/bengorman/notebooks/MedNIST exists, skip extracting.\n"
],
[
"hand_dir = os.path.join(data_dir, \"Hand\")\ntraining_datadict = [\n {\"hand\": os.path.join(hand_dir, filename)} for filename in os.listdir(hand_dir)\n]",
"_____no_output_____"
],
[
"print(training_datadict[:5])",
"[{'hand': '/home/bengorman/notebooks/MedNIST/Hand/003676.jpeg'}, {'hand': '/home/bengorman/notebooks/MedNIST/Hand/006548.jpeg'}, {'hand': '/home/bengorman/notebooks/MedNIST/Hand/002169.jpeg'}, {'hand': '/home/bengorman/notebooks/MedNIST/Hand/004081.jpeg'}, {'hand': '/home/bengorman/notebooks/MedNIST/Hand/004815.jpeg'}]\n"
]
],
[
[
"## Step 2: Initialize MONAI components",
"_____no_output_____"
]
],
[
[
"logging.basicConfig(stream=sys.stdout, level=logging.INFO)\nset_determinism(0)\ndevice = torch.device(\"cuda:0\")",
"_____no_output_____"
]
],
[
[
"### Create image transform chain\n\nDefine the processing pipeline to convert saved disk images into usable Tensors.",
"_____no_output_____"
]
],
[
[
"train_transforms = Compose(\n [\n LoadPNGD(keys=[\"hand\"]),\n AddChannelD(keys=[\"hand\"]),\n ScaleIntensityD(keys=[\"hand\"]),\n RandRotateD(keys=[\"hand\"], range_x=15, prob=0.5, keep_size=True),\n RandFlipD(keys=[\"hand\"], spatial_axis=0, prob=0.5),\n RandZoomD(keys=[\"hand\"], min_zoom=0.9, max_zoom=1.1, prob=0.5),\n ToTensorD(keys=[\"hand\"]),\n ]\n)",
"_____no_output_____"
]
],
[
[
"### Create dataset and dataloader\n\nHold data and present batches during training.",
"_____no_output_____"
]
],
[
[
"real_dataset = CacheDataset(training_datadict, train_transforms)",
"10000/10000 Load and cache transformed data: [==============================]\n"
],
[
"batch_size = 300\nreal_dataloader = DataLoader(real_dataset, batch_size=batch_size, shuffle=True, num_workers=10)\n\n\ndef prepare_batch(batchdata):\n return batchdata[\"hand\"]",
"_____no_output_____"
]
],
[
[
"### Define generator and discriminator\n\nLoad basic computer vision GAN networks from libraries.",
"_____no_output_____"
]
],
[
[
"# define networks\ndisc_net = Discriminator(\n in_shape=(1, 64, 64),\n channels=(8, 16, 32, 64, 1),\n strides=(2, 2, 2, 2, 1),\n num_res_units=1,\n kernel_size=5,\n).to(device)\n\nlatent_size = 64\ngen_net = Generator(\n latent_shape=latent_size,\n start_shape=(latent_size, 8, 8),\n channels=[32, 16, 8, 1],\n strides=[2, 2, 2, 1],\n)\ngen_net.conv.add_module(\"activation\", torch.nn.Sigmoid())\ngen_net = gen_net.to(device)\n\n# initialize both networks\ndisc_net.apply(normal_init)\ngen_net.apply(normal_init)\n\n# define optimizors\nlearning_rate = 2e-4\nbetas = (0.5, 0.999)\ndisc_opt = torch.optim.Adam(disc_net.parameters(), learning_rate, betas=betas)\ngen_opt = torch.optim.Adam(gen_net.parameters(), learning_rate, betas=betas)\n\n# define loss functions\ndisc_loss_criterion = torch.nn.BCELoss()\ngen_loss_criterion = torch.nn.BCELoss()\nreal_label = 1\nfake_label = 0\n\n\ndef discriminator_loss(gen_images, real_images):\n real = real_images.new_full((real_images.shape[0], 1), real_label)\n gen = gen_images.new_full((gen_images.shape[0], 1), fake_label)\n\n realloss = disc_loss_criterion(disc_net(real_images), real)\n genloss = disc_loss_criterion(disc_net(gen_images.detach()), gen)\n\n return (genloss + realloss) / 2\n\n\ndef generator_loss(gen_images):\n output = disc_net(gen_images)\n cats = output.new_full(output.shape, real_label)\n return gen_loss_criterion(output, cats)",
"_____no_output_____"
]
],
[
[
"### Create training handlers\n\nPerform operations during model training.",
"_____no_output_____"
]
],
[
[
"metric_logger = MetricLogger(\n loss_transform=lambda x: {GanKeys.GLOSS: x[GanKeys.GLOSS], GanKeys.DLOSS: x[GanKeys.DLOSS]},\n metric_transform=lambda x: x,\n)\n\nhandlers = [\n StatsHandler(\n name=\"batch_training_loss\",\n output_transform=lambda x: {\n GanKeys.GLOSS: x[GanKeys.GLOSS],\n GanKeys.DLOSS: x[GanKeys.DLOSS],\n },\n ),\n CheckpointSaver(\n save_dir=os.path.join(root_dir, \"hand-gan\"),\n save_dict={\"g_net\": gen_net, \"d_net\": disc_net},\n save_interval=10,\n save_final=True,\n epoch_level=True,\n ),\n metric_logger,\n]",
"_____no_output_____"
]
],
[
[
"### Create GanTrainer\n\nMONAI Workflow engine for adversarial learning. The components come together here with the GanTrainer.\n\nUses a training loop based on Goodfellow et al. 2014 https://arxiv.org/abs/1406.266. \n\n```\nTraining Loop: for each batch of data size m\n 1. Generate m fakes from random latent codes.\n 2. Update D with these fakes and current batch reals, repeated d_train_steps times.\n 3. Generate m fakes from new random latent codes.\n 4. Update generator with these fakes using discriminator feedback.\n```",
"_____no_output_____"
]
],
[
[
"disc_train_steps = 5\nnum_epochs = 50\n\ntrainer = GanTrainer(\n device,\n num_epochs,\n real_dataloader,\n gen_net,\n gen_opt,\n generator_loss,\n disc_net,\n disc_opt,\n discriminator_loss,\n d_prepare_batch=prepare_batch,\n d_train_steps=disc_train_steps,\n g_update_latents=True,\n latent_shape=latent_size,\n key_train_metric=None,\n train_handlers=handlers,\n)",
"_____no_output_____"
]
],
[
[
"## Step 3: Start Training",
"_____no_output_____"
]
],
[
[
"trainer.run()\nIPython.display.clear_output()",
"_____no_output_____"
]
],
[
[
"## Evaluate Results\n\nExamine G and D loss curves for collapse.",
"_____no_output_____"
]
],
[
[
"g_loss = [loss[GanKeys.GLOSS] for loss in metric_logger.loss]\nd_loss = [loss[GanKeys.DLOSS] for loss in metric_logger.loss]",
"_____no_output_____"
],
[
"plt.figure(figsize=(12, 5))\nplt.semilogy(g_loss, label=\"Generator Loss\")\nplt.semilogy(d_loss, label=\"Discriminator Loss\")\nplt.grid(True, \"both\", \"both\")\nplt.legend()\nplt.show()",
"_____no_output_____"
]
],
[
[
"### View image reconstructions\nWith random latent codes view trained generator output.",
"_____no_output_____"
]
],
[
[
"test_img_count = 10\ntest_latents = default_make_latent(test_img_count, latent_size).to(device)\nfakes = gen_net(test_latents)\n\nfig, axs = plt.subplots(2, (test_img_count // 2), figsize=(20, 8))\naxs = axs.flatten()\nfor i, ax in enumerate(axs):\n ax.axis(\"off\")\n ax.imshow(fakes[i, 0].cpu().data.numpy(), cmap=\"gray\")",
"_____no_output_____"
]
],
[
[
"### Cleanup data directory\n\nRemove directory if a temporary was used.",
"_____no_output_____"
]
],
[
[
"if directory is None:\n shutil.rmtree(root_dir)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e77ab15af5e7c6f21b0b5def5105ab51646e4142 | 52,651 | ipynb | Jupyter Notebook | notebooks/rewriting-grammar.ipynb | dimkart/discopy | cf3d7bd86bb78271e5c99a1735890d35cc1d2b29 | [
"BSD-3-Clause"
] | null | null | null | notebooks/rewriting-grammar.ipynb | dimkart/discopy | cf3d7bd86bb78271e5c99a1735890d35cc1d2b29 | [
"BSD-3-Clause"
] | null | null | null | notebooks/rewriting-grammar.ipynb | dimkart/discopy | cf3d7bd86bb78271e5c99a1735890d35cc1d2b29 | [
"BSD-3-Clause"
] | 1 | 2021-09-19T07:16:01.000Z | 2021-09-19T07:16:01.000Z | 192.156934 | 10,016 | 0.906554 | [
[
[
"We show how to translate from syntax trees, to pregroup parsing diagrams, to equivalent diagrams where all cups and caps are removed.",
"_____no_output_____"
]
],
[
[
"from discopy import Ty, Id, Box, Diagram, Word\n\n# POS TAGS:\ns, n, adj, v, vp = Ty('S'), Ty('N'), Ty('ADJ'), Ty('V'), Ty('VP')\n\n# WORDS:\nJane = Word('Jane', n)\nloves = Word('loves', v)\nfunny = Word('funny', adj)\nboys = Word('boys', n)\n\nvocab = [Jane, loves, funny, boys]",
"_____no_output_____"
]
],
[
[
"## Syntax trees",
"_____no_output_____"
]
],
[
[
"# The CFG's production rules are boxes.\n\nR0 = Box('R0', vp @ n, s)\nR1 = Box('R1', n @ vp, s)\nR2 = Box('R2', n @ v , vp)\nR3 = Box('R3', v @ n , vp)\nR4 = Box('R4', adj @ n, n)\n\n# A syntax tree is a diagram!\n\ntree0 = R2 @ R4 >> R0\ntree1 = Id(n @ v) @ R4 >> Id(n) @ R3 >> R1\nsentence0 = Jane @ loves @ funny @ boys >> tree0\nsentence1 = Jane @ loves @ funny @ boys >> tree1\nprint(\"Two syntax trees for sentence 'Jane loves funny boys':\")\nsentence0.draw(aspect='auto')\nsentence1.draw(aspect='auto')",
"Two syntax trees for sentence 'Jane loves funny boys':\n"
]
],
[
[
"## Pregroup parsing",
"_____no_output_____"
]
],
[
[
"from discopy.rigid import Cup, Cap, Functor\n\n# Dict from POS tags to Pregroup types:\nob = {n : n, s: s, adj: n @ n.l, v: n.r @ s @ n.l, vp: s @ n.l}\n\n_Jane = Word('Jane', n)\n_loves = Word('loves', n.r @ s @ n.l)\n_funny = Word('funny', n @ n.l)\n_boys = Word('boys', n)\n\n# Dict from CFG rules to Pregroup reductions: \nar = {R0: Id(s) @ Cup(n.l, n), \n R2: Cup(n, n.r) @ Id(s @ n.l),\n R4: Id(n) @ Cup(n.l, n),\n R3: Id(n.r @ s) @ Cup(n.l, n),\n R1: Cup(n, n.r) @ Id(s),\n Jane: _Jane, loves: _loves, funny: _funny, boys: _boys}\n \nT2P = Functor(ob, ar)\nprint(\"The syntax trees are mapped to pregroup diagrams, equivalent up to interchanger:\")\nT2P(sentence0).draw(aspect='auto')\nT2P(sentence1).draw(aspect='auto')",
"The syntax trees are mapped to pregroup diagrams, equivalent up to interchanger:\n"
],
[
"# Check that the two diagrams above are equal up to monoidal.normal_form()\n\nassert T2P(sentence0).normal_form() == T2P(sentence0).normal_form()",
"_____no_output_____"
]
],
[
[
"## Snake removal",
"_____no_output_____"
]
],
[
[
"# Define the Wiring functor that decomposes a word into monoidal boxes with inputs transposed:\n\nlove_box = Box('loves', n @ n, s)\nfunny_box = Box('funny', n, n)\n\nob = {n: n, s: s}\nar = {_Jane: _Jane, _boys: _boys,\n _loves: Cap(n.r, n) @ Cap(n, n.l) >> Diagram.id(n.r) @ love_box @ Diagram.id(n.l), \n _funny: Cap(n, n.l) >> funny_box @ Id(n.l)}\n\nW = Functor(ob, ar)\nprint('Image of the wiring functor:')\nW(T2P(sentence0)).draw(aspect='auto')",
"Image of the wiring functor:\n"
],
[
"rewrite_steps = W(T2P(sentence0)).normalize()\nprint(\"Equivalent diagram for 'Jane loves funny boys', after snake removal:\")\nT2P(sentence0).to_gif(*rewrite_steps, path='../docs/imgs/jane_boys.gif', aspect='auto')",
"Equivalent diagram for 'Jane loves funny boys', after snake removal:\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e77ab17a26bfe63a0729387beca3176038db4fc9 | 7,676 | ipynb | Jupyter Notebook | extra/KNN_demo.ipynb | Gan4x4/hse-cv2019 | 30abf105dcfd54099051b3ea4e3a960fed99fbe8 | [
"MIT"
] | null | null | null | extra/KNN_demo.ipynb | Gan4x4/hse-cv2019 | 30abf105dcfd54099051b3ea4e3a960fed99fbe8 | [
"MIT"
] | null | null | null | extra/KNN_demo.ipynb | Gan4x4/hse-cv2019 | 30abf105dcfd54099051b3ea4e3a960fed99fbe8 | [
"MIT"
] | 1 | 2020-04-10T17:27:25.000Z | 2020-04-10T17:27:25.000Z | 33.373913 | 224 | 0.484367 | [
[
[
"<a href=\"https://colab.research.google.com/github/Gan4x4/CV-HSE2019/blob/master/KNN_demo.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"# Download and unpack archive with CIFAR10 dataset to disk from official site: https://www.cs.toronto.edu/~kriz/cifar.html\n\n!wget https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz\n!tar -xzf cifar-10-python.tar.gz\n!ls -l",
"--2021-02-07 16:28:58-- https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz\nResolving www.cs.toronto.edu (www.cs.toronto.edu)... 128.100.3.30\nConnecting to www.cs.toronto.edu (www.cs.toronto.edu)|128.100.3.30|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 170498071 (163M) [application/x-gzip]\nSaving to: ‘cifar-10-python.tar.gz’\n\ncifar-10-python.tar 100%[===================>] 162.60M 31.2MB/s in 5.8s \n\n2021-02-07 16:29:05 (27.9 MB/s) - ‘cifar-10-python.tar.gz’ saved [170498071/170498071]\n\ntotal 166516\ndrwxr-xr-x 2 2156 1103 4096 Jun 4 2009 cifar-10-batches-py\n-rw-r--r-- 1 root root 170498071 Jun 4 2009 cifar-10-python.tar.gz\ndrwxr-xr-x 1 root root 4096 Feb 4 15:26 sample_data\n"
],
[
"# Loading CIFAR10 data using code from official site: https://www.cs.toronto.edu/~kriz/cifar.html\nimport numpy as np\nimport random\n\ndef unpickle(file,encoding = 'bytes'):\n import pickle\n with open(file, 'rb') as fo:\n dict = pickle.load(fo, encoding=encoding)\n return dict\n\ndef load_train_data():\n x = np.zeros((0,3072),dtype=int) # To avoid overflow \n y = np.array([],dtype=int)\n for i in range(1,6):\n raw = unpickle(f\"/content/cifar-10-batches-py/data_batch_{i}\")\n x = np.append(x,np.array(raw[b'data'],dtype=int),axis=0)\n y = np.append(y,np.array(raw[b'labels'],dtype=int),axis=0)\n return x,y\n\nx_train, y_train = load_train_data()\n\ntest = unpickle(\"/content/cifar-10-batches-py/test_batch\")\nx_test = np.array(test[b'data'])\ny_test = np.array(test[b'labels'])\n\n# Load label names. For for convenience only.\nmeta = unpickle(\"/content/cifar-10-batches-py/batches.meta\",'utf-8')\nlabels= meta['label_names']\n\n",
"_____no_output_____"
],
[
"class NearestNeighbor:\n def __init__(self):\n pass\n\n def train(self,x,y):\n self.train_data = x\n self.train_labels = y\n \n def predict(self,x):\n # To avoid overflow data must be int, not a byte!\n distances = np.sum(np.abs(self.train_data - x),axis = 1) # Axis 0 it's a row num in image list \n return self.train_labels[np.argmin(distances)]\n",
"_____no_output_____"
],
[
"# Function to check model accuracy\ndef validate(model,x_test,y_test):\n correct = 0\n for i, sample in enumerate(x_test):\n index = model.predict(sample)\n correct += 1 if index == y_test[i] else 0\n if i > 0 and i % 100 == 0:\n print (\"Accuracy {:.3f}\".format(correct/i))\n \n return correct/len(x_test) ",
"_____no_output_____"
],
[
"# Now test accuracy and speed of model\nimport time\n\nnn = NearestNeighbor()\nnn.train(x_train,y_train)\n\nstart = time.perf_counter()\naccuracy = validate(nn,x_test[:100],y_test[:100]) \ntm = time.perf_counter() - start\ntotal = x_test.shape[0]\nprint(\"Accuracy {:.2f} Train {:d} /test {:d} in {:.1f} sec. speed {:.2f} samples per second.\".format(accuracy,len(x_train),total,tm,total/tm,) )",
"Accuracy 0.34 Train 50000 /test 10000 in 46.4 sec. speed 215.56 samples per second.\n"
],
[
"# KNN \n\nfrom collections import Counter\n\nclass KNearestNeighbor(NearestNeighbor):\n def __init__(self,k):\n self.k = k\n pass\n \n def predict(self,x):\n distances = np.sum(np.abs(self.train_data - x),axis = 1) # L1\n sorted_distance_indexes = np.argsort(distances)\n k_nearest_images = sorted_distance_indexes[:self.k]\n most_common = Counter(self.train_labels[k_nearest_images]).most_common()\n return most_common[0][0]\n\nknn = KNearestNeighbor(11)\nknn.train( x_train,y_train)\nvalidate(knn,x_test[:1000],y_test[:1000]) \n",
"Accuracy 0.380\nAccuracy 0.410\nAccuracy 0.373\nAccuracy 0.375\nAccuracy 0.380\nAccuracy 0.383\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e77ac1ae4e43ae69530e0a2ba53245456ecbf640 | 225,977 | ipynb | Jupyter Notebook | TASK#1.ipynb | Umer86/IRIS_FLOWER_Classfication_ML_Project | 18b0ae5385cb23dff296b7b0fb1f3db6756deaac | [
"MIT"
] | null | null | null | TASK#1.ipynb | Umer86/IRIS_FLOWER_Classfication_ML_Project | 18b0ae5385cb23dff296b7b0fb1f3db6756deaac | [
"MIT"
] | null | null | null | TASK#1.ipynb | Umer86/IRIS_FLOWER_Classfication_ML_Project | 18b0ae5385cb23dff296b7b0fb1f3db6756deaac | [
"MIT"
] | null | null | null | 225,977 | 225,977 | 0.920952 | [
[
[
"# **LetsGrowMore**\n\n---\n\n\n\n---\n# ***Data Science Internship***\n\n---\n\n\n\n---\n\n## `Author: UMER FAROOQ`\n## `Task Level: Beginner Level`\n## `Task Number: 1`\n## `Task Title: Iris Flower Classification`\n\n\n## `Language: Python`\n## `IDE: Google Colab`\n",
"_____no_output_____"
],
[
"# **Steps**:\n",
"_____no_output_____"
],
[
"# **Step:1**\n***Importing Libraries***",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport seaborn as sns\nsns.set_palette('husl')\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC",
"_____no_output_____"
]
],
[
[
"# **Step:2**\n***Loading the Dataset:*** I have pick the dataset from the following link. You can download the dataset as well as you can use by URL.",
"_____no_output_____"
]
],
[
[
"url = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/iris.csv'",
"_____no_output_____"
],
[
"# Creating the list of column name:\n\ncolumn_name = ['sepal-lenght','sepal-width','petal-lenght','petal-width','class']\n\n# Pandas read_csv() is used for reading the csv file:\n\ndataset = pd.read_csv(url, names = column_name)",
"_____no_output_____"
]
],
[
[
"# **Step:3**\n***Dataset Summarizing:*** Check the structure/shape of data on which we have to work on.",
"_____no_output_____"
]
],
[
[
"dataset.shape",
"_____no_output_____"
]
],
[
[
"This shows that we have: \n\n1. 150 rows,\n2. 5 columns.\n\nThats enough for our Beginner Project.\n*Displaying the First 5 records:*\n\n\n",
"_____no_output_____"
]
],
[
[
"dataset.head()",
"_____no_output_____"
]
],
[
[
"Pandas info() method prints information about a DataFrame such as datatypes, cols, NAN values and usage of memory:",
"_____no_output_____"
]
],
[
[
"dataset.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 150 entries, 0 to 149\nData columns (total 5 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 sepal-lenght 150 non-null float64\n 1 sepal-width 150 non-null float64\n 2 petal-lenght 150 non-null float64\n 3 petal-width 150 non-null float64\n 4 class 150 non-null object \ndtypes: float64(4), object(1)\nmemory usage: 6.0+ KB\n"
],
[
"dataset.isnull()",
"_____no_output_____"
],
[
"# Returns no. of missing records/values\ndataset.isnull().sum() ",
"_____no_output_____"
],
[
"\"\"\" Pandas describe() is used to view some basic statistical details like percentile, mean, std etc. of a data frame or a series of numeric values: \"\"\"\n\ndataset.describe()",
"_____no_output_____"
]
],
[
[
"**Now let’s check the number of rows that belongs to each class:**",
"_____no_output_____"
]
],
[
[
"dataset['class'].value_counts() # No of records/samples in each class",
"_____no_output_____"
]
],
[
[
"The above outputs shows that each class of flowers has 50 rows.",
"_____no_output_____"
],
[
"# **Step: 4 Data Visualization**\n\n---\n\n\n\n---\n\nData visualization is the process of translating large data sets and metrics into charts, graphs and other visuals.\n\n---\n\n\n\n---\n\n**Violin Plot:** Plotting the violin plot to check the comparison of a variable distribution:",
"_____no_output_____"
]
],
[
[
"sns.violinplot(y='class', x='sepal-lenght', data=dataset, inner='quartile')\nplt.show()\nprint('\\n')\n\nsns.violinplot(y='class', x='sepal-width', data=dataset, inner='quartile')\nplt.show()\nprint('\\n')\n\nsns.violinplot(y='class', x='petal-lenght', data=dataset, inner='quartile')\nplt.show()\nprint('\\n')\n\nsns.violinplot(y='class', x='petal-width', data=dataset, inner='quartile')\nplt.show()\nprint('\\n')",
"_____no_output_____"
]
],
[
[
"Above-plotted violin plot says that Iris-Setosa class is having a smaller petal length and petal width as compared to other class.",
"_____no_output_____"
],
[
"**Pair Plot:** Plotting multiple pairwise bivariate distributions in a dataset using pairplot:",
"_____no_output_____"
]
],
[
[
"sns.pairplot(dataset, hue='class', markers='+')\nplt.show()",
"_____no_output_____"
]
],
[
[
"From the above, we can see that Iris-Setosa is separated from both other species in all the features.",
"_____no_output_____"
],
[
"**Heatmap:** Plotting the heatmap to check the correlation.\n**dataset.corr()** is used to find the pairwise correlation of all columns in the dataframe.",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(8,5))\nsns.heatmap(dataset.corr(), annot=True, cmap= 'PuOr')\nplt.show()",
"_____no_output_____"
]
],
[
[
"# **Step: 5 Model Construction (Splitting, Training and Model Creation)**\n\n---\n\n---\n\n\n**SPLITTING THE DATASET:**\nX have dependent variables.\nY have an independent variables.\n",
"_____no_output_____"
]
],
[
[
"x= dataset.drop(['class'], axis=1)\ny= dataset['class'] # Class is an independent variable\n\nprint('X shape: {}\\nY Shape: {}'.format(x.shape, y.shape))",
"X shape: (150, 4)\nY Shape: (150,)\n"
]
],
[
[
"The output shows that X has 150 records/rows and 4 cols, whereas, Y has 150 records and only 1 col.",
"_____no_output_____"
],
[
"**TRAINING THE TEST SPLIT:**\nSplitting our dataset into train and test using train_test_split(), what we are doing here is taking 80% of data to train our model, and 20% that we will hold back as a validation dataset:",
"_____no_output_____"
]
],
[
[
"x_train, x_test, y_train, y_test = train_test_split (x, y, test_size=0.20, random_state=1)",
"_____no_output_____"
]
],
[
[
"**MODEL CONSTRUCTION PART:1:**\nWe have no idea which algorithms might work best in this situation.\nLet's run each algorithm in a loop and print its accuracy so we can choose the best one. Following are the algorithms:\n\n1. Logistic Regression (LR)\n2. Linear Discriminant Analysis (LDA)\n\n1. K-Nearest Neighbors (KNN).\n2. Classification and Regression Trees (CART).\n\n1. Gaussian Naive Bayes (NB).\n2. Support Vector Machines (SVM).\n\n\n\n\n\n",
"_____no_output_____"
]
],
[
[
"models = []\nmodels.append(('LR', LogisticRegression()))\nmodels.append(('LDA', LinearDiscriminantAnalysis()))\nmodels.append(('KNN', KNeighborsClassifier()))\nmodels.append(('CART', DecisionTreeClassifier()))\nmodels.append(('NB', GaussianNB()))\nmodels.append(('SVC', SVC(gamma='auto')))\n# evaluate each model in turn\nresults = []\nmodel_names = []\nfor name, model in models:\n kfold = StratifiedKFold(n_splits=10, random_state=1, shuffle=True)\n cv_results = cross_val_score(model, x_train, y_train, cv=kfold, scoring='accuracy')\n results.append(cv_results)\n model_names.append(name)\n print('%s: %f (%f)' % (name, cv_results.mean(), cv_results.std()))",
"/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_logistic.py:940: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n extra_warning_msg=_LOGISTIC_SOLVER_CONVERGENCE_MSG)\n/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_logistic.py:940: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n extra_warning_msg=_LOGISTIC_SOLVER_CONVERGENCE_MSG)\n/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_logistic.py:940: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n extra_warning_msg=_LOGISTIC_SOLVER_CONVERGENCE_MSG)\n/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_logistic.py:940: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n extra_warning_msg=_LOGISTIC_SOLVER_CONVERGENCE_MSG)\n/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_logistic.py:940: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n extra_warning_msg=_LOGISTIC_SOLVER_CONVERGENCE_MSG)\n"
]
],
[
[
"***Support Vector Classifier (SVC) is performing better than other algorithms.\nLet’s train SVC model on our training set and predict on test set in the next step.***",
"_____no_output_____"
],
[
"**MODEL CONSTRUCTION PART:2**\n\nWe are defining our SVC model and passing gamma as auto.\n\nAfter that fitting/training the model on X_train and Y_train using .fit() method.\n\nThen we are predicting on X_test using .predict() method.",
"_____no_output_____"
]
],
[
[
"model = SVC(gamma='auto')\nmodel.fit(x_train, y_train)\nprediction = model.predict(x_test)",
"_____no_output_____"
]
],
[
[
"**Now checking the accuracy of the model using accuracy_score(y_test, prediction).**\n\ny_test is actually values of x_test\nprediction: it predicts values of x_test as mentioned earlier (*then we are predicting on X_test using .predict() method*).\n\n**Printing out the classfication report using:** classification_report(y_test, prediction)\n\n",
"_____no_output_____"
]
],
[
[
"print(f\"Test Accuracy: {accuracy_score(y_test, prediction)} \\n\")\nprint(f'Classification Report:\\n \\n {classification_report(y_test, prediction)}')",
"Test Accuracy: 0.9666666666666667 \n\nClassification Report:\n \n precision recall f1-score support\n\n Iris-setosa 1.00 1.00 1.00 11\nIris-versicolor 1.00 0.92 0.96 13\n Iris-virginica 0.86 1.00 0.92 6\n\n accuracy 0.97 30\n macro avg 0.95 0.97 0.96 30\n weighted avg 0.97 0.97 0.97 30\n\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e77adbb429514b79ef978b1ec8c9282c1bd18551 | 392,167 | ipynb | Jupyter Notebook | week3/day3/theory/statistics.ipynb | Marvxeles/mxrodvi | a1170ae44278e6b4013c5feab98408b4bb78b04d | [
"Apache-2.0"
] | 1 | 2020-11-19T10:28:26.000Z | 2020-11-19T10:28:26.000Z | week3/day3/theory/statistics.ipynb | Marvxeles/mxrodvi | a1170ae44278e6b4013c5feab98408b4bb78b04d | [
"Apache-2.0"
] | null | null | null | week3/day3/theory/statistics.ipynb | Marvxeles/mxrodvi | a1170ae44278e6b4013c5feab98408b4bb78b04d | [
"Apache-2.0"
] | null | null | null | 176.572265 | 30,089 | 0.715863 | [
[
[
"# Estadística",
"_____no_output_____"
],
[
"Es la rama de las matemáticas que estudia la variabilidad, así como el proceso aleatorio que la genera siguiendo leyes de probabilidad.\n\nLa estadística es útil para una amplia variedad de ciencias empíricas (la que entiende los hechos creando representaciones de la realidad), desde la física hasta las ciencias sociales, desde las ciencias de la salud hasta el control de calidad. Además, se usa en áreas de negocios o instituciones gubernamentales con el objetivo de describir el conjunto de datos obtenidos para la toma de decisiones, o bien para realizar generalizaciones sobre las características observadas.",
"_____no_output_____"
],
[
"La estadística se divide en dos grandes áreas:\n\n- **Estadística descriptiva**: Se dedica a la descripción, visualización y resumen de datos originados a partir de los fenómenos de estudio. Los datos pueden ser resumidos numérica o gráficamente. Su objetivo es organizar y describir las características sobre un conjunto de datos con el propósito de facilitar su aplicación, generalmente con el apoyo de gráficas, tablas o medidas numéricas.\n\n - Ejemplos básicos de parámetros estadísticos son: la media y la desviación estándar.\n - Ejemplos gráficos son: histograma, pirámide poblacional, gráfico circular, entre otros.\n\n- **Estadística inferencial**: Se dedica a la generación de los modelos, inferencias y predicciones asociadas a los fenómenos en cuestión teniendo en cuenta la aleatoriedad de las observaciones. Se usa para modelar patrones en los datos y extraer inferencias acerca de la población bajo estudio. Estas inferencias pueden tomar la forma de respuestas a preguntas sí/no (prueba de hipótesis), estimaciones de unas características numéricas (estimación), pronósticos de futuras observaciones, descripciones de asociación (correlación) o modelamiento de relaciones entre variables (análisis de regresión). Otras técnicas de modelamiento incluyen análisis de varianza, series de tiempo y minería de datos. Su objetivo es obtener conclusiones útiles para lograr hacer deducciones acerca de la totalidad de todas las observaciones hechas, basándose en la información numérica.",
"_____no_output_____"
],
[
"# Sampling\n\n\n\nOne reason we need statistics is because we'd like to make statements about a general population based only on a subset - a *sample* - of the data. This can be for practical reasons, to reduce costs, or can be inherently necessary because of the nature of the problem. For example, it's not possible to collect data on \"everyone who ever had a headache\", so people wanting to study headaches will have to somehow get a group of people and try to generalize based on that.\n\nWhat's the right way to build that group? If a drug company decides to only ask its employees if their headache drug works, does that have any problems?\n\n*Yes* - let's discuss!",
"_____no_output_____"
]
],
[
[
"import random\npopulation = range(100)\nsample = random.sample(population, 10) #sample crea una muestra aleatorio dentro del rango\nprint(sample)",
"[2, 78, 40, 59, 13, 31, 24, 43, 29, 68]\n"
]
],
[
[
"--> Tarea Crear población a partir de lista de alturas de alumnos y con clases",
"_____no_output_____"
],
[
"## Conceptos básicos de la estadística descriptiva\n\nEn *[estadística descriptiva](https://es.wikipedia.org/wiki/Estad%C3%ADstica_descriptiva)* se utilizan distintas medidas para intentar describir las propiedades de nuestros datos, algunos de los conceptos básicos, son:\n\n* **Media aritmética**: La [media aritmética](https://es.wikipedia.org/wiki/Media_aritm%C3%A9tica) es el valor obtenido al sumar todos los *[datos](https://es.wikipedia.org/wiki/Dato)* y dividir el resultado entre el número total elementos. Se suele representar con la letra griega $\\mu$. Si tenemos una [muestra](https://es.wikipedia.org/wiki/Muestra_estad%C3%ADstica) de $n$ valores, $x_i$, la *media aritmética*, $\\mu$, es la suma de los valores divididos por el numero de elementos; en otras palabras:\n$$\\mu = \\frac{1}{n} \\sum_{i}x_i$$\n\n\n* **Desviación respecto a la media**: La desviación respecto a la media es la diferencia en valor absoluto entre cada valor de la variable estadística y la media aritmética.\n$$D_i = |x_i - \\mu|$$\n\n\n* **Varianza**: La [varianza](https://es.wikipedia.org/wiki/Varianza) es la media aritmética del cuadrado de las desviaciones respecto a la media de una distribución estadística. La varianza intenta describir la dispersión de los *[datos](https://es.wikipedia.org/wiki/Dato). Básicamente representa lo que varían los datos.* Se representa como $\\sigma^2$. \n$$\\sigma^2 = \\frac{\\sum\\limits_{i=1}^n(x_i - \\mu)^2}{n} $$\n\n\n* **Desviación típica**: La [desviación típica](https://es.wikipedia.org/wiki/Desviaci%C3%B3n_t%C3%ADpica) es la raíz cuadrada de la varianza. Se representa con la letra griega $\\sigma$.\n$$\\sigma = \\sqrt{\\frac{\\sum\\limits_{i=1}^n(x_i - \\mu)^2}{n}} $$\n\n\n* **Moda**: La <a href=\"https://es.wikipedia.org/wiki/Moda_(estad%C3%ADstica)\">moda</a> es el valor que tiene mayor frecuencia absoluta. Se representa con $M_0$\n\n\n* **Mediana**: La <a href=\"https://es.wikipedia.org/wiki/Mediana_(estad%C3%ADstica)\">mediana</a> es el valor que ocupa el lugar central de todos los datos cuando éstos están ordenados de menor a mayor. Se representa con $\\widetilde{x}$.\n\n\n* **Correlación**: La [correlación](https://es.wikipedia.org/wiki/Correlaci%C3%B3n) trata de establecer la relación o dependencia que existe entre las dos variables que intervienen en una distribución bidimensional. Es decir, determinar si los cambios en una de las variables influyen en los cambios de la otra. En caso de que suceda, diremos que las variables están correlacionadas o que hay correlación entre ellas. La correlación es positiva cuando los valores de las variables aumenta juntos; y es negativa cuando un valor de una variable se reduce cuando el valor de la otra variable aumenta.\n\n\n* **Covarianza**: La [covarianza](https://es.wikipedia.org/wiki/Covarianza) es el equivalente de la varianza aplicado a una variable bidimensional. Es la media aritmética de los productos de las desviaciones de cada una de las variables respecto a sus medias respectivas.La covarianza indica el sentido de la correlación entre las variables; Si $\\sigma_{xy} > 0$ la correlación es directa; Si $\\sigma_{xy} < 0$ la correlación es inversa.\n\n$$\\sigma_{xy} = \\frac{\\sum\\limits_{i=1}^n(x_i - \\mu_x)(y_i -\\mu_y)}{n}$$\n\n\n* **Valor atípico (Outlier)**: Un [valor atípico](https://es.wikipedia.org/wiki/Valor_at%C3%ADpico) es una observación que se aleja demasiado de la moda; esta muy lejos de la tendencia principal del resto de los *[datos](https://es.wikipedia.org/wiki/Dato)*. Pueden ser causados por errores en la recolección de *[datos](https://es.wikipedia.org/wiki/Dato)* o medidas inusuales. Generalmente se recomienda eliminarlos del [conjunto de datos](https://es.wikipedia.org/wiki/Conjunto_de_datos).\n",
"_____no_output_____"
],
[
"1. https://towardsdatascience.com/a-quick-guide-on-descriptive-statistics-using-pandas-and-seaborn-2aadc7395f32\n\n2. https://www.tutorialspoint.com/python_pandas/python_pandas_descriptive_statistics.htm",
"_____no_output_____"
],
[
"### Ejemplos en Python\n\nCalcular los principales indicadores de la *[estadística descriptiva](https://es.wikipedia.org/wiki/Estad%C3%ADstica_descriptiva)* con [Python](http://python.org/) es muy fácil!.",
"_____no_output_____"
]
],
[
[
"import numpy as np #np y pd es un alias. son librerias de estadistica y tratamientos de datos\nimport pandas as pd\nimport matplotlib.pyplot as pyplot\n#se instalan en terminal \n#pip3 install numpy",
"_____no_output_____"
],
[
"from numpy import *\n#importo las funciones de numpy a jupiter y se puede usar sin np.\n#no se recomienda",
"_____no_output_____"
],
[
"lista = [2, 4, 6, 8]\nprint(type(lista))\nlista_array = np.asarray(lista) #numpy trabaja con arrays. cambio de lista a array con asarray(lista) ARRAY tiene sus propios metodos incluidos en np\n#el equivalente a max(lista) q nos da el numero mas alto es lista_array.argmax()\n#list(lista_array) paso de array a lista\nprint(type(lista_array))",
"<class 'list'>\n<class 'numpy.ndarray'>\n"
],
[
"np.arange()",
"_____no_output_____"
],
[
"from scipy import unique, stats",
"_____no_output_____"
],
[
"# Ejemplos de estadistica descriptiva con python\n\nimport numpy as np # importando numpy\nfrom scipy import stats # importando scipy.stats\nimport pandas as pd # importando pandas\n\nnp.random.seed(4) # para poder replicar el random. fichero semilla seed",
"_____no_output_____"
],
[
"lista = [2., 1.76, 1.8, 1.6]\na = np.array(lista)\na",
"_____no_output_____"
],
[
"datos = np.random.randn(5, 4) # datos normalmente distribuidos. 5 filas y 4 columnas\ndatos #ya es un array de numpy",
"_____no_output_____"
],
[
"# media arítmetica\ndatos.mean() # Calcula la media aritmetica de los datos. no le alado np pq es un array q ya es de numpy",
"_____no_output_____"
],
[
"x = np.mean(datos) # Mismo resultado desde la funcion de numpy\nx",
"_____no_output_____"
],
[
"datos",
"_____no_output_____"
],
[
"datos.mean(axis=1) # media aritmetica de cada fila",
"_____no_output_____"
],
[
"datos.mean(axis=0) # media aritmetica de cada columna",
"_____no_output_____"
],
[
"# mediana\nnp.median(datos) ",
"_____no_output_____"
],
[
"np.median(datos, axis=0) # media aritmetica de cada columna",
"_____no_output_____"
],
[
"import numpy as np",
"_____no_output_____"
],
[
" # Desviación típica\nnp.std(datos)",
"_____no_output_____"
],
[
"type(datos)",
"_____no_output_____"
],
[
"datos.std()",
"_____no_output_____"
],
[
"np.std(datos, 0) # Desviación típica de cada columna",
"_____no_output_____"
],
[
"lista = [1, 3, 5, 7]\n\nnp.mean(a=lista)",
"_____no_output_____"
],
[
"x = np.array(lista)\nx",
"_____no_output_____"
],
[
"x.mean()",
"_____no_output_____"
],
[
"# varianza\nnp.var(datos) ",
"_____no_output_____"
],
[
"datos.var()",
"_____no_output_____"
],
[
"np.var(datos, 0) # varianza de cada columna",
"_____no_output_____"
],
[
"# moda\nstats.mode(datos) # Calcula la moda de cada columna\n# el 2do array devuelve la frecuencia.",
"_____no_output_____"
],
[
"datos2 = np.array([1, 2, 3, 6, 6, 1, 2, 4, 2, 2, 6, 6, 8, 10, 6])\nfrom scipy import stats # importando scipy.stats\n\nstats.mode(datos2) # aqui la moda es el 6 porque aparece 5 veces en el vector.",
"_____no_output_____"
],
[
"# correlacion\nnp.corrcoef(datos) # Crea matriz de correlación.",
"_____no_output_____"
],
[
"# calculando la correlación entre dos vectores.\nnp.corrcoef(datos[0], datos[1])",
"_____no_output_____"
],
[
"# covarianza\nnp.cov(datos) # calcula matriz de covarianza",
"_____no_output_____"
],
[
"# covarianza de dos vectores\nnp.cov(datos[0], datos[1])",
"_____no_output_____"
],
[
"datos",
"_____no_output_____"
],
[
"import pandas as pd\n# usando pandas\ndataframe = pd.DataFrame(datos, index=['a', 'b', 'c', 'd', 'e'], \n columns=['col1', 'col2', 'col3', 'col4'])\ndataframe",
"_____no_output_____"
],
[
"dataframe[\"col1\"].values",
"_____no_output_____"
],
[
"# resumen estadistadistico con pandas\ndataframe.describe()",
"_____no_output_____"
],
[
"lista = [2., 1.76, 1.8, 1.6]\nlista_array = np.array(lista)\nprint(lista_array)\ndataframe2 = pd.DataFrame(lista_array, index=['a', 'b', 'c', 'd'], \n columns=['col1'])\n\ndataframe2",
"[2. 1.76 1.8 1.6 ]\n"
],
[
"dataframe",
"_____no_output_____"
],
[
"# sumando las columnas\ndataframe.sum()",
"_____no_output_____"
],
[
"# sumando filas\ndataframe.sum(axis=1)",
"_____no_output_____"
],
[
"dataframe.cumsum() # acumulados\n\n",
"_____no_output_____"
],
[
"# media aritmética de cada columna con pandas\ndataframe.mean()",
"_____no_output_____"
],
[
"# media aritmética de cada fila con pandas\ndataframe.mean(axis=1)",
"_____no_output_____"
],
[
"altura1 = [1.78, 1.63, 1.75, 1.68]\naltura2 = [2.00, 1.82, 1.76, 1.66]\naltura3 = [1.65, 1.73, 1.75, 1.76]\naltura4 = [1.72, 1.71, 1.71, 1.62]\n\nlista_alturas = [altura1, altura2, altura3, altura4]\n\nclass Humano():\n def __init__(self, altura):\n self.altura = altura\n\n def crece(self):\n self.altura = self.altura + 2.0\n\nlista_humanos = []\n\nfor col_alt in lista_alturas:\n for alt in col_alt: \n humano = Humano(altura=alt)\n lista_humanos.append(humano)\n",
"_____no_output_____"
],
[
"lista_humanos",
"_____no_output_____"
],
[
"for humano in lista_humanos:\n print(humano.altura)\n humano.crece()\n print(humano.altura)\n print(\"----------\")",
"1.78\n3.7800000000000002\n----------\n1.63\n3.63\n----------\n1.75\n3.75\n----------\n1.68\n3.6799999999999997\n----------\n2.0\n4.0\n----------\n1.82\n3.8200000000000003\n----------\n1.76\n3.76\n----------\n1.66\n3.66\n----------\n1.65\n3.65\n----------\n1.73\n3.73\n----------\n1.75\n3.75\n----------\n1.76\n3.76\n----------\n1.72\n3.7199999999999998\n----------\n1.71\n3.71\n----------\n1.71\n3.71\n----------\n1.62\n3.62\n----------\n"
],
[
"lista_alturas",
"_____no_output_____"
],
[
"x = np.arange(0, 15)\nx",
"_____no_output_____"
],
[
"lista = [2, 5, 7]\nprint(sum(lista))",
"14\n"
],
[
"import numpy as np\ndef axis_x(limit):\n return np.arange(0, limit)\n\ntotal_elements_x = axis_x(limit=sum([len(x) for x in lista_alturas]))\ntotal_elements_x",
"_____no_output_____"
],
[
"lista_alturas_total = []\nfor humano in lista_humanos:\n lista_alturas_total.append(humano.altura)\narray_alturas_completo = np.array(lista_alturas_total).T\narray_alturas_completo\n",
"_____no_output_____"
],
[
"array_alturas_completo.shape",
"_____no_output_____"
],
[
"import pandas as pd",
"_____no_output_____"
],
[
"df = pd.DataFrame({'Alturas':array_alturas_completo})\ndf",
"_____no_output_____"
],
[
"import numpy as np\nimport pandas as pd \nimport matplotlib.pyplot as plt\n\nplt.plot(lista_alturas_alumnos, linewidth=2, marker='o', color=\"g\", linestyle='dashed', markersize=12)\nplt.ylabel(\"Alturas\")\nplt.show()",
"_____no_output_____"
],
[
"import mi_libreria as ml\n\nml.grafica_verde(lista=lista_alturas_alumnos, ylabel=\"Alturas 2\")",
"_____no_output_____"
],
[
"def create_array_with_same_value(value, limit):\n return np.full(limit, value)\n\na = create_array_with_same_value(2, 80)\na",
"_____no_output_____"
],
[
"a = np.arange(4)\na",
"_____no_output_____"
],
[
"media = np.mean(lista_alturas_alumnos)\nmedia_graph = create_array_with_same_value(value=media, limit=len(lista_alturas_alumnos))\nprint(lista_alturas_alumnos)\nmedia_graph",
"[180, 180, 181, 173, 173, 175, 164, 189, 170, 167, 168, 160, 169, 176, 160, 175]\n"
],
[
"print(len(lista_alturas_alumnos))\nprint(len(media_graph))",
"16\n16\n"
],
[
"# Añadimos la media a la gráfica\nplt.plot(lista_alturas_alumnos, \"ro\")\nmedia = np.mean(lista_alturas_alumnos)\nprint(\"Media:\", media)\nmedia_graph = create_array_with_same_value(value=media, limit=len(lista_alturas_alumnos))\n\nplt.ylabel(\"Alturas\")\nplt.plot(media_graph, \"b--\")\nplt.show()",
"Media: 172.5\n"
],
[
"lista_alturas_total = np.array(lista_alturas_total)\nstd = np.std(lista_alturas_total)\nstd",
"_____no_output_____"
],
[
"std_superior = media + std\nstd_inferior = media - std\n",
"_____no_output_____"
],
[
"plt.plot(lista_alturas_total, \"ro\")\nmedia = np.mean(lista_alturas_total)\nprint(\"Media:\", media)\nstd_superior_total = create_array_with_same_value(value=std_superior, limit=numero_de_alturas)\n\nstd_inferior_total = create_array_with_same_value(value=std_inferior, limit=numero_de_alturas)\n\nplt.ylabel(\"Alturas\")\nplt.plot(std_superior_total, \"b--\")\nplt.plot(std_inferior_total, \"g--\")\nplt.show()",
"Media: 1.7331249999999998\n"
],
[
"lista = [[[[2,4,6,8], [5,6,7,8]]]]\nlista_array = np.array(lista)\n\nlista_array",
"_____no_output_____"
],
[
"lista_array.shape",
"_____no_output_____"
],
[
"arrays_alturas = np.array([np.array(x) for x in lista_alturas])\narrays_alturas",
"_____no_output_____"
],
[
"np.mean(arrays_alturas)",
"_____no_output_____"
],
[
"np.mean(arrays_alturas, 1) # Fila",
"_____no_output_____"
],
[
"np.mean(arrays_alturas, 0) # Columna",
"_____no_output_____"
],
[
"lista = [2, 2, 2, 4, 6, 10, 10]\n\n2 --> 3\n4 --> 1\n6 --> 1\n10 -> 2\n\n",
"_____no_output_____"
],
[
"import pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame({'Alturas':np.array(lista_alturas_alumnos)})\ndf\n\n",
"_____no_output_____"
],
[
"df.hist(bins=10)",
"_____no_output_____"
]
],
[
[
"## Histogramas y Distribuciones\n\nMuchas veces los indicadores de la *[estadística descriptiva](https://es.wikipedia.org/wiki/Estad%C3%ADstica_descriptiva)* no nos proporcionan una imagen clara de nuestros *[datos](https://es.wikipedia.org/wiki/Dato)*. Por esta razón, siempre es útil complementarlos con gráficos de las distribuciones de los *[datos](https://es.wikipedia.org/wiki/Dato)*, que describan con qué frecuencia aparece cada valor. La representación más común de una distribución es un [histograma](https://es.wikipedia.org/wiki/Histograma), que es un gráfico que muestra la frecuencia o probabilidad de cada valor. El [histograma](https://es.wikipedia.org/wiki/Histograma) muestra las frecuencias como un gráfico de barras que indica cuan frecuente un determinado valor ocurre en el [conjunto de datos](https://es.wikipedia.org/wiki/Conjunto_de_datos). El eje horizontal representa los valores del [conjunto de datos](https://es.wikipedia.org/wiki/Conjunto_de_datos) y el eje vertical representa la frecuencia con que esos valores ocurren.\n\nLas distribuciones se pueden clasificar en dos grandes grupos:\n\n1. Las **[distribuciones continuas](https://es.wikipedia.org/wiki/Distribuci%C3%B3n_de_probabilidad_continua)**, que son aquellas que presentan un número infinito de posibles soluciones. Dentro de este grupo vamos a encontrar a las distribuciones: \n * [normal](https://es.wikipedia.org/wiki/Distribuci%C3%B3n_normal),\n * [gamma](https://es.wikipedia.org/wiki/Distribuci%C3%B3n_gamma),\n * [chi cuadrado](https://es.wikipedia.org/wiki/Distribuci%C3%B3n_%CF%87%C2%B2), \n * [t de Student](https://es.wikipedia.org/wiki/Distribuci%C3%B3n_t_de_Student), \n * [pareto](https://es.wikipedia.org/wiki/Distribuci%C3%B3n_de_Pareto),\n * entre otras\n\n2. Las **distribuciones discretas**, que son aquellas en las que la variable puede pude tomar un número determinado de valores. Los principales exponenetes de este grupo son las distribuciones: \n * [poisson](https://es.wikipedia.org/wiki/Distribuci%C3%B3n_de_Poisson),\n * [binomial](https://es.wikipedia.org/wiki/Distribuci%C3%B3n_binomial),\n * [hipergeométrica](https://es.wikipedia.org/wiki/Distribuci%C3%B3n_hipergeom%C3%A9trica),\n * [bernoulli](https://es.wikipedia.org/wiki/Distribuci%C3%B3n_de_Bernoulli)\n * entre otras\n\nVeamos algunos ejemplos graficados con la ayuda de [Python](http://python.org/).",
"_____no_output_____"
]
],
[
[
"# Histogram\ndf.hist()",
"_____no_output_____"
]
],
[
[
"### Distribución normal\n\nLa [distribución normal](https://es.wikipedia.org/wiki/Distribuci%C3%B3n_normal) es una de las principales distribuciones, ya que es la que con más frecuencia aparece aproximada en los fenómenos reales. Tiene una forma acampanada y es simétrica respecto de un determinado parámetro estadístico. Con la ayuda de [Python](http://python.org/) la podemos graficar de la siguiente manera:",
"_____no_output_____"
]
],
[
[
"# Graficos embebidos.\n%matplotlib inline ",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt # importando matplotlib\nimport seaborn as sns # importando seaborn\n\n# parametros esteticos de seaborn\nsns.set_palette(\"deep\", desat=.6)\nsns.set_context(rc={\"figure.figsize\": (8, 4)})",
"_____no_output_____"
],
[
"mu, sigma = 0, 0.1 # media y desvio estandar\ns = np.random.normal(mu, sigma, 1000) #creando muestra de datos",
"_____no_output_____"
],
[
"# histograma de distribución normal.\ncuenta, cajas, ignorar = plt.hist(s, 30, normed=True)\nnormal = plt.plot(cajas, 1/(sigma * np.sqrt(2 * np.pi)) *\n np.exp( - (cajas - mu)**2 / (2 * sigma**2) ),\n linewidth=2, color='r')",
"_____no_output_____"
]
],
[
[
"### Distribuciones simétricas y asimétricas\n\nUna distribución es simétrica cuando moda, mediana y media coinciden aproximadamente en sus valores. Si una distribución es simétrica, existe el mismo número de valores a la derecha que a la izquierda de la media, por tanto, el mismo número de desviaciones con signo positivo que con signo negativo.\n\nUna distribución tiene [asimetria](https://es.wikipedia.org/wiki/Asimetr%C3%ADa_estad%C3%ADstica) positiva (o a la derecha) si la \"cola\" a la derecha de la media es más larga que la de la izquierda, es decir, si hay valores más separados de la media a la derecha. De la misma forma una distribución tiene [asimetria](https://es.wikipedia.org/wiki/Asimetr%C3%ADa_estad%C3%ADstica) negativa (o a la izquierda) si la \"cola\" a la izquierda de la media es más larga que la de la derecha, es decir, si hay valores más separados de la media a la izquierda.\n\nLas distribuciones asimétricas suelen ser problemáticas, ya que la mayoría de los métodos estadísticos suelen estar desarrollados para distribuciones del tipo [normal](https://es.wikipedia.org/wiki/Distribuci%C3%B3n_normal). Para salvar estos problemas se suelen realizar transformaciones a los datos para hacer a estas distribuciones más simétricas y acercarse a la [distribución normal](https://es.wikipedia.org/wiki/Distribuci%C3%B3n_normal). ",
"_____no_output_____"
]
],
[
[
"# Dibujando la distribucion Gamma\nx = stats.gamma(3).rvs(5000)\ngamma = plt.hist(x, 70, histtype=\"stepfilled\", alpha=.7)",
"_____no_output_____"
]
],
[
[
"En este ejemplo podemos ver que la [distribución gamma](https://es.wikipedia.org/wiki/Distribuci%C3%B3n_gamma) que dibujamos tiene una [asimetria](https://es.wikipedia.org/wiki/Asimetr%C3%ADa_estad%C3%ADstica) positiva. ",
"_____no_output_____"
]
],
[
[
"# Calculando la simetria con scipy\nstats.skew(x)",
"_____no_output_____"
]
],
[
[
"## Cuartiles y diagramas de cajas\n\nLos **[cuartiles](https://es.wikipedia.org/wiki/Cuartil)** son los tres valores de la variable estadística que dividen a un [conjunto de datos](https://es.wikipedia.org/wiki/Conjunto_de_datos) ordenados en cuatro partes iguales. Q1, Q2 y Q3 determinan los valores correspondientes al 25%, al 50% y al 75% de los datos. Q2 coincide con la <a href=\"https://es.wikipedia.org/wiki/Mediana_(estad%C3%ADstica)\">mediana</a>.\n\nLos [diagramas de cajas](https://es.wikipedia.org/wiki/Diagrama_de_caja) son una presentación visual que describe varias características importantes al mismo tiempo, tales como la dispersión y simetría. Para su realización se representan los tres cuartiles y los valores mínimo y máximo de los datos, sobre un rectángulo, alineado horizontal o verticalmente. Estos gráficos nos proporcionan abundante información y son sumamente útiles para encontrar [valores atípicos](https://es.wikipedia.org/wiki/Valor_at%C3%ADpico) y comparar dos [conjunto de datos](https://es.wikipedia.org/wiki/Conjunto_de_datos). \n\n\n<img alt=\"diagrama de cajas\" title=\"Diagrama de cajas\" src=\"http://relopezbriega.github.io/images/diagCajas.png\" width=\"600\">",
"_____no_output_____"
]
],
[
[
"lista = [2, 3, 4, 5,6,7,9,10,11, 1000]",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\n\n# Ejemplo de grafico de cajas en python\n\ndatos_1 = np.random.normal(100, 10, 200)\n#datos_2 = np.random.normal(80, 30, 200)\ndatos_3 = np.random.normal(90, 20, 200)\ndatos_4 = np.random.normal(70, 25, 200)\n\ndatos_graf = [datos_1, datos_2, datos_3, datos_4]\n\n# Creando el objeto figura\nfig = plt.figure(1, figsize=(9, 6))\n\n# Creando el subgrafico\nax = fig.add_subplot(111)\n\n# creando el grafico de cajas\nbp = ax.boxplot(datos_graf)\n\n# visualizar mas facile los atípicos\nfor flier in bp['fliers']:\n flier.set(marker='o', color='red', alpha=0.5)\n# los puntos aislados son valores atípicos",
"_____no_output_____"
],
[
"df = pd.DataFrame(datos_2)\ndf",
"_____no_output_____"
],
[
"es_menor_a_80 = 0\nfor value in datos_2:\n if value <= 80:\n es_menor_a_80 += 1\n\nprint(es_menor_a_80)",
"103\n"
],
[
"df.hist(bins=2)",
"_____no_output_____"
],
[
"x = list(datos_2)\nx.append(500)\ndatos_2 = np.array(x)\ndf = pd.DataFrame(datos_2)\ndf.hist()",
"_____no_output_____"
],
[
"# usando seaborn\nsns.boxplot(datos_graf, names=[\"grupo1\", \"grupo2\", \"grupo3\", \"grupo 4\"],\n color=\"PaleGreen\");",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e77af7ec0b66baccfae9cdae3e831709134c6b41 | 1,439 | ipynb | Jupyter Notebook | Array/1. Reverse an Array.ipynb | itzanuragsinghania/DSA-450-Series-in-Python | 27502e1b1a6c061a3549c47cff748ae26d1a6d58 | [
"MIT"
] | 1 | 2021-04-24T07:44:10.000Z | 2021-04-24T07:44:10.000Z | Array/1. Reverse an Array.ipynb | itzanuragsinghania/DSA-450-Series-in-Python | 27502e1b1a6c061a3549c47cff748ae26d1a6d58 | [
"MIT"
] | null | null | null | Array/1. Reverse an Array.ipynb | itzanuragsinghania/DSA-450-Series-in-Python | 27502e1b1a6c061a3549c47cff748ae26d1a6d58 | [
"MIT"
] | null | null | null | 17.765432 | 48 | 0.451008 | [
[
[
"list=[1,2,3,4,5]\nlist[::-1]",
"_____no_output_____"
],
[
"array=[1,2,3,4,5]\ndef revlist(A,start,end):\n while start<end:\n A[start],A[end]=A[end],A[start]\n start += 1\n end -= 1\n return A\nrevlist(array,0,len(array)-1)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code"
]
] |
e77b0b1f7111e522a263493213b0f3a2c88d1002 | 232,520 | ipynb | Jupyter Notebook | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney | 0fdf738426f1346347793724565972a58ee80efd | [
"MIT"
] | 1 | 2021-07-07T13:50:14.000Z | 2021-07-07T13:50:14.000Z | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney | 0fdf738426f1346347793724565972a58ee80efd | [
"MIT"
] | null | null | null | 10_Data Aggregation and Group Operations.ipynb | quangphu1912/Py-data-analysis-McKinney | 0fdf738426f1346347793724565972a58ee80efd | [
"MIT"
] | null | null | null | 30.386827 | 1,295 | 0.409401 | [
[
[
"# Data Aggregation and Group Operations",
"_____no_output_____"
]
],
[
[
"import numpy as np\r\nimport pandas as pd\r\nPREVIOUS_MAX_ROWS = pd.options.display.max_rows\r\npd.options.display.max_rows = 20\r\nnp.random.seed(12345)\r\nimport matplotlib.pyplot as plt\r\nplt.rc('figure', figsize=(10, 6))\r\nnp.set_printoptions(precision=4, suppress=True)",
"_____no_output_____"
]
],
[
[
"## 10.1. GroupBy Mechanics",
"_____no_output_____"
],
[
"### 10.1.0",
"_____no_output_____"
],
[
"To get started, here is a small tabular dataset as a DataFrame:",
"_____no_output_____"
]
],
[
[
"df = pd.DataFrame({'key1' : ['a', 'a', 'b', 'b', 'a'],\r\n 'key2' : ['one', 'two', 'one', 'two', 'one'],\r\n 'data1' : np.random.randn(5),\r\n 'data2' : np.random.randn(5)})\r\ndf",
"_____no_output_____"
]
],
[
[
"Suppose you wanted to *compute the mean of the data1 column* using the *labels from key1*.<br>\r\nThere are a number of ways to do this.<br>\r\n* One is to access data1 and call groupby with the column (a Series) at key1:",
"_____no_output_____"
]
],
[
[
"grouped = df['data1'].groupby(df['key1'])\r\ngrouped",
"_____no_output_____"
]
],
[
[
"This grouped variable is now a GroupBy object. It has not actually computed anything yet except for some intermediate data about the group key df['key1']. The idea is that this object has all of the information needed to then apply some operation to each of the groups.<br>\r\n\r\nFor example, to compute group means we can call the GroupBy’s mean method:",
"_____no_output_____"
]
],
[
[
"grouped.mean()",
"_____no_output_____"
]
],
[
[
"Later, I’ll explain more about what happens when you call .mean(). The important thing here is that `the data (a Series) has been aggregated according to the group key`, producing a new Series that is now indexed by the unique values in the key1 column. The result index has the name 'key1' because the DataFrame column df['key1'] did.<br>\r\n\r\nIf instead we had passed multiple arrays as a list, we’d get something different:",
"_____no_output_____"
]
],
[
[
"means = df['data1'].groupby([df['key1'], df['key2']]).mean()\r\nmeans",
"_____no_output_____"
]
],
[
[
"Here we grouped the data using two keys (@P:key 1 + key 2 above), and the resulting Series now has a hierarchical index consisting of the unique pairs of keys observed:",
"_____no_output_____"
]
],
[
[
"means.unstack()",
"_____no_output_____"
]
],
[
[
"In this example, the group keys are all Series, though they could be any arrays of the right length:",
"_____no_output_____"
]
],
[
[
"states = np.array(['Ohio', 'California', 'California', 'Ohio', 'Ohio'])\r\nyears = np.array([2005, 2005, 2006, 2005, 2006])\r\ndf['data1'].groupby([states, years]).mean()",
"_____no_output_____"
]
],
[
[
"Frequently the grouping information is found in the same DataFrame as the data you want to work on. In that case, you can pass column names (whether those are strings, numbers, or other Python objects) as the group keys:",
"_____no_output_____"
]
],
[
[
"df.groupby('key1').mean()",
"_____no_output_____"
],
[
"df.groupby(['key1', 'key2']).mean()",
"_____no_output_____"
]
],
[
[
"You may have noticed in the first case df.groupby('key1').mean() that there is no key2 column in the result. *Because df['key2'] is not numeric data*, it is said to be a `nuisance column`, which is therefore excluded from the result. `By default, all of the numeric columns are aggregated`, though it is possible to filter down to a subset, as you’ll see soon.<br>\r\nRegardless of the objective in using groupby, a generally useful GroupBy method is size, which returns a Series containing group sizes:",
"_____no_output_____"
]
],
[
[
"df.groupby(['key1', 'key2']).size()",
"_____no_output_____"
]
],
[
[
"Take note that any missing values in a group key will be excluded from the result.",
"_____no_output_____"
],
[
"### 10.1.1. Iterating Over Groups",
"_____no_output_____"
],
[
"The `GroupBy object supports iteration`, generating a sequence of 2-tuples containing the group name along with the chunk of data. Consider the following:",
"_____no_output_____"
]
],
[
[
"for name, group in df.groupby('key1'):\r\n print(name)\r\n print(group)",
"a\n key1 key2 data1 data2\n0 a one -0.204708 1.393406\n1 a two 0.478943 0.092908\n4 a one 1.965781 1.246435\nb\n key1 key2 data1 data2\n2 b one -0.519439 0.281746\n3 b two -0.555730 0.769023\n"
]
],
[
[
"In the case of multiple keys, the first element in the tuple will be a tuple of key values:",
"_____no_output_____"
]
],
[
[
"for (k1, k2), group in df.groupby(['key1', 'key2']):\r\n print((k1, k2))\r\n print(group)",
"('a', 'one')\n key1 key2 data1 data2\n0 a one -0.204708 1.393406\n4 a one 1.965781 1.246435\n('a', 'two')\n key1 key2 data1 data2\n1 a two 0.478943 0.092908\n('b', 'one')\n key1 key2 data1 data2\n2 b one -0.519439 0.281746\n('b', 'two')\n key1 key2 data1 data2\n3 b two -0.55573 0.769023\n"
]
],
[
[
"Of course, you can choose to do whatever you want with the pieces of data. *A recipe you may find useful* is `computing a dict of the data pieces as a one-liner`:",
"_____no_output_____"
]
],
[
[
"pieces = dict(list(df.groupby('key1')))\r\npieces\r\n# pieces['b']",
"_____no_output_____"
]
],
[
[
"By default groupby groups on `axis=0`, but you `can group on any of the other axes`. For example, we could group the columns of our example df here by dtype like so:",
"_____no_output_____"
]
],
[
[
"df.dtypes",
"_____no_output_____"
],
[
"grouped = df.groupby(df.dtypes, axis=1)\r\ngrouped",
"_____no_output_____"
],
[
"#We can print out the groups like so:\r\nfor dtype, group in grouped:\r\n print(dtype)\r\n print(group)",
"float64\n data1 data2\n0 -0.204708 1.393406\n1 0.478943 0.092908\n2 -0.519439 0.281746\n3 -0.555730 0.769023\n4 1.965781 1.246435\nobject\n key1 key2\n0 a one\n1 a two\n2 b one\n3 b two\n4 a one\n"
]
],
[
[
"### 10.1.2. Selecting a Column or Subset of Columns",
"_____no_output_____"
],
[
"Indexing a GroupBy object created from a DataFrame with a column name or array of column names has the effect of column subsetting for aggregation. This means that:",
"_____no_output_____"
]
],
[
[
"df.groupby('key1')['data1']\r\ndf.groupby('key1')[['data2']]",
"_____no_output_____"
]
],
[
[
"are `syntactic sugar` for:",
"_____no_output_____"
]
],
[
[
"df['data1'].groupby(df['key1'])\r\ndf[['data2']].groupby(df['key1'])",
"_____no_output_____"
]
],
[
[
"Especially for large datasets, it may be desirable to aggregate only a few columns.<br>\r\nFor example, in the preceding dataset, to *compute means for just the data2 column* and get the result as a DataFrame, we could write:",
"_____no_output_____"
]
],
[
[
"df.groupby(['key1', 'key2'])[['data2']].mean()",
"_____no_output_____"
]
],
[
[
"`The object returned by this indexing operation is a grouped DataFrame` if a *list or array* is passed or` a grouped Series` if only a *single column name is passed* as a scalar:",
"_____no_output_____"
]
],
[
[
"s_grouped = df.groupby(['key1', 'key2'])['data2']\r\ns_grouped",
"_____no_output_____"
],
[
"s_grouped.mean()",
"_____no_output_____"
]
],
[
[
"### 10.1.3. Grouping with Dicts and Series",
"_____no_output_____"
],
[
"Grouping information may exist in a form other than an array. Let’s consider another example DataFrame:",
"_____no_output_____"
]
],
[
[
"people = pd.DataFrame(np.random.randn(5, 5),\r\n columns=['a', 'b', 'c', 'd', 'e'],\r\n index=['Joe', 'Steve', 'Wes', 'Jim', 'Travis'])\r\npeople.iloc[2:3, [1, 2]] = np.nan # Add a few NA values\r\npeople",
"_____no_output_____"
]
],
[
[
"Now, suppose I have a group correspondence for the columns and want to sum together the columns by group:",
"_____no_output_____"
]
],
[
[
"mapping = {'a': 'red', 'b': 'red', 'c': 'blue',\r\n 'd': 'blue', 'e': 'red', 'f' : 'orange'}\r\nmapping",
"_____no_output_____"
]
],
[
[
"Now, you could construct an array from this dict to pass to groupby, but instead we can just pass the dict (I included the key 'f' to highlight that unused grouping keys are OK):",
"_____no_output_____"
]
],
[
[
"by_column = people.groupby(mapping, axis=1)\r\nby_column.sum()",
"_____no_output_____"
]
],
[
[
"`The same functionality holds for Series`, which can be viewed as a *fixedsize mapping*:",
"_____no_output_____"
]
],
[
[
"map_series = pd.Series(mapping)\r\nmap_series",
"_____no_output_____"
],
[
"people.groupby(map_series, axis=1).count()",
"_____no_output_____"
]
],
[
[
"### 10.1.4. Grouping with Functions",
"_____no_output_____"
],
[
"Using Python functions is a more generic way of defining a group mapping compared with a dict or Series. `Any function passed as a group key will be called once per index value, with the return values being used as the group names`.<br>\r\nMore concretely, consider the example DataFrame from the previous section, which has people’s first names as index values. Suppose you wanted to group by the length of the names; while you could compute an array of string lengths, it’s simpler to just pass the len function:",
"_____no_output_____"
]
],
[
[
"people.groupby(len).sum()",
"_____no_output_____"
]
],
[
[
"Mixing functions with arrays, dicts, or Series is not a problem as everything gets converted to arrays internally:",
"_____no_output_____"
]
],
[
[
"key_list = ['one', 'one', 'one', 'two', 'two']\r\npeople.groupby([len, key_list]).min()\r\n#@P 20210901: not understand how key_list function in this syntax",
"_____no_output_____"
]
],
[
[
"### 10.1.5. Grouping by Index Levels",
"_____no_output_____"
],
[
"A final convenience for hierarchically indexed datasets is the ability to aggregate using one of the levels of an axis index.<br>\r\nLet’s look at an example:",
"_____no_output_____"
]
],
[
[
"columns = pd.MultiIndex.from_arrays([['US', 'US', 'US', 'JP', 'JP'],\r\n [1, 3, 5, 1, 3]],\r\n names=['cty', 'tenor'])\r\nhier_df = pd.DataFrame(np.random.randn(4, 5), columns=columns)\r\nhier_df",
"_____no_output_____"
]
],
[
[
"* *To group by level*, pass the level number or name using the level keyword:",
"_____no_output_____"
]
],
[
[
"hier_df.groupby(level='cty', axis=1).count()",
"_____no_output_____"
]
],
[
[
"## 10.2. Data Aggregation",
"_____no_output_____"
],
[
"`Aggregations` refer to *any data transformation that produces scalar values from arrays*. The preceding examples have used several of them, including *mean, count, min, and sum*.",
"_____no_output_____"
],
[
"While `quantile` is not explicitly implemented for GroupBy, it is a Series method and thus available for use. Internally, *GroupBy efficiently slices up the Series*, *calls piece.quantile(0.9) for each piece*, and then *assembles those results together into the result object*:",
"_____no_output_____"
]
],
[
[
"df",
"_____no_output_____"
],
[
"grouped = df.groupby('key1')\r\ngrouped['data1'].quantile(0.9)",
"_____no_output_____"
]
],
[
[
"To use your own aggregation functions, pass any function that aggregates an array to the `aggregate` or `agg method`:",
"_____no_output_____"
]
],
[
[
"def peak_to_peak(arr):\r\n return arr.max() - arr.min()\r\ngrouped.agg(peak_to_peak)",
"D:\\Users\\phu.le2\\Anaconda3\\lib\\site-packages\\pandas\\core\\groupby\\generic.py:303: FutureWarning: Dropping invalid columns in SeriesGroupBy.agg is deprecated. In a future version, a TypeError will be raised. Before calling .agg, select only columns which should be valid for the aggregating function.\n results[key] = self.aggregate(func)\n"
],
[
"def peak_to_peak(arr):\r\n return arr.max() - arr.min()\r\ngrouped.aggregate(peak_to_peak)\r\n#@P 20210902: due to the warning that SeriesGroupBy.agg is deprecated -> change to this method but it seems to me that the results are not the same",
"D:\\Users\\phu.le2\\Anaconda3\\lib\\site-packages\\pandas\\core\\groupby\\generic.py:303: FutureWarning: Dropping invalid columns in SeriesGroupBy.agg is deprecated. In a future version, a TypeError will be raised. Before calling .agg, select only columns which should be valid for the aggregating function.\n results[key] = self.aggregate(func)\n"
]
],
[
[
"You may notice that some methods like `describe` also work, even though they are not aggregations, strictly speaking:",
"_____no_output_____"
]
],
[
[
"grouped.describe()",
"_____no_output_____"
]
],
[
[
"**NOTE**\r\n*Custom aggregation functions are generally much slower than the optimized functions found in Table 10-1* *(count, sum, mean, meadiam, std, var, min, max, prod, first, last)*. This is because there is some extra overhead (function calls, data rearrangement) in constructing the intermediate group data chunks.",
"_____no_output_____"
],
[
"### 10.2.1. Column-Wise and Multiple Function Application",
"_____no_output_____"
],
[
"Let’s return to the tipping dataset from earlier examples. After loading it with read_csv, we add a tipping percentage column tip_pct:",
"_____no_output_____"
]
],
[
[
"tips = pd.read_csv('examples/tips.csv')\r\ntips.head()",
"_____no_output_____"
],
[
"# Add tip percentage of total bill\r\ntips['tip_pct'] = tips['tip'] / tips['total_bill']\r\ntips[:6]",
"_____no_output_____"
]
],
[
[
"As you’ve already seen, aggregating a Series or all of the columns of a DataFrame is a matter of using `aggregate` with the desired function or calling a method like mean or std. However, you may want to aggregate using a different function depending on the column, or multiple functions at once. Fortunately, this is possible to do, which I’ll illustrate through a number of examples.<br>\r\nFirst, I’ll group the tips by day and smoker:",
"_____no_output_____"
]
],
[
[
"rouped = tips.groupby(['day', 'smoker'])\r\ngrouped",
"_____no_output_____"
]
],
[
[
"Note that for descriptive statistics like those in Table 10-1, you can pass the name of the function as a string:",
"_____no_output_____"
]
],
[
[
"grouped_pct = grouped['tip_pct']\r\ngrouped_pct",
"_____no_output_____"
],
[
"grouped_pct.agg('mean')",
"_____no_output_____"
]
],
[
[
"If you p*ass a list of functions or function names* instead, you get back a DataFrame with column names taken from the functions:",
"_____no_output_____"
]
],
[
[
"grouped_pct.agg(['mean', 'std', peak_to_peak])",
"_____no_output_____"
]
],
[
[
"Here we passed a list of aggregation functions to `agg` to evaluate indepedently on the data groups.",
"_____no_output_____"
],
[
"`You don’t need to accept the names that GroupBy gives to the columns`; notably, lambda functions have the name '<lambda>', which makes them hard to identify (you can see for yourself by looking at a function’s __name__ attribute). Thus, *if you pass a list of (name, function) tuples,* `the first element of each tuple will be used as the DataFrame column names` (you can think of a list of 2-tuples as an ordered mapping):",
"_____no_output_____"
]
],
[
[
"grouped_pct.agg([('foo', 'mean'), ('bar', np.std)])\r\n#@P: mean and std but are named as foo and bar",
"_____no_output_____"
]
],
[
[
"With a DataFrame you have more options, as you can specify a list of functions to apply to all of the columns or different functions per column.",
"_____no_output_____"
],
[
"To start, suppose we wanted to compute the same three statistics for the *tip_pct* and *total_bill* columns:",
"_____no_output_____"
]
],
[
[
"functions = ['count', 'mean', 'max']\r\nresult = grouped['tip_pct', 'total_bill'].agg(functions)\r\nresult",
"<ipython-input-274-f8119a6d3215>:2: FutureWarning: Indexing with multiple keys (implicitly converted to a tuple of keys) will be deprecated, use a list instead.\n result = grouped['tip_pct', 'total_bill'].agg(functions)\n"
],
[
"grouped",
"_____no_output_____"
],
[
"#to deal with FutureWarning: Indexing with multiple keys (implicitly converted to a tuple of keys) will be deprecated, use a list instead.\r\n#https://stackoverflow.com/questions/61634759/python-futurewarning-indexing-with-multiple-keys-implicitly-converted-to-a-tup -> extra bracket to solve it\r\nfunctions = ['count', 'mean', 'max']\r\nresult = grouped[['tip_pct', 'total_bill']].agg(functions)\r\nresult",
"_____no_output_____"
]
],
[
[
"As you can see, the resulting DataFrame has hierarchical columns, the same as you would get aggregating each column separately and using `concat` to glue the results together using the column names as the keys argument:",
"_____no_output_____"
]
],
[
[
"result['tip_pct']",
"_____no_output_____"
]
],
[
[
"As before, a list of tuples with custom names can be passed:",
"_____no_output_____"
]
],
[
[
"ftuples = [('Durchschnitt', 'mean'), ('Abweichung', np.var)] #@P: mean and var is named with different name as Durchschnitt and Abweichung)\r\ngrouped[['tip_pct', 'total_bill']].agg(ftuples)",
"_____no_output_____"
]
],
[
[
"Now, suppose you wanted to *apply potentially different functions* to one or more of the columns. To do this, `pass a dict to agg that contains a mapping of column names` to any of the function specifications listed so far:",
"_____no_output_____"
]
],
[
[
"grouped.agg({'tip' : np.max, 'size' : 'sum'})",
"_____no_output_____"
],
[
"grouped.agg({'tip_pct' : ['min', 'max', 'mean', 'std'],\r\n 'size' : 'sum'})",
"_____no_output_____"
]
],
[
[
"### 10.2.2. Returning Aggregated Data Without Row Indexes",
"_____no_output_____"
],
[
"In all of the examples up until now, `the aggregated data comes back with an index, potentially hierarchical, composed from the unique group key combinations`. Since this isn’t always desirable, *you can disable this behavior in most cases by passing* `as_index=False` to groupby:",
"_____no_output_____"
]
],
[
[
"tips.groupby(['day', 'smoker'], as_index=False).mean()",
"_____no_output_____"
]
],
[
[
"## 10.3. Apply: General split-apply-combine",
"_____no_output_____"
],
[
"#### 10.3.0",
"_____no_output_____"
],
[
"Returning to the tipping dataset from before, *suppose you wanted to select the top five tip_pct values by group*. \r\n* First, write a function that selects the rows with the largest values in a particular column:",
"_____no_output_____"
]
],
[
[
"def top(df, n=5, column='tip_pct'):\r\n return df.sort_values(by=column)[-n:]\r\ntop(tips, n=6)",
"_____no_output_____"
]
],
[
[
"Now, if we group by smoker, say, and call apply with this function, we get the following:",
"_____no_output_____"
]
],
[
[
"tips.groupby('smoker').apply(top)",
"_____no_output_____"
]
],
[
[
"What has happened here?<br>\r\n* The top function is called on each row group from the DataFrame, and then the results are glued together using `pandas.concat`, labeling the pieces with the group names.<br>\r\nThe result therefore has *a hierarchical index* whose inner level contains index values from the original DataFrame.",
"_____no_output_____"
],
[
"If you pass a function to `apply` that takes other arguments or keywords, you can pass these after the function:",
"_____no_output_____"
]
],
[
[
"tips.groupby(['smoker', 'day']).apply(top, n=1, column='total_bill')\r\n#@P: additional config to the function: n= 1 and apply the function on column total_bill, not the default n =5 and column='tip_pct'",
"_____no_output_____"
]
],
[
[
"**NOTE**<br>\r\nBeyond these basic usage mechanics, getting the most out of apply may require some creativity. What occurs inside the function passed is up to you; `it only needs to return a pandas object or a scalar value`. The rest of this chapter will mainly consist of examples showing you how to solve various problems using groupby.",
"_____no_output_____"
],
[
"You may recall that I earlier called `describe` on a GroupBy object:",
"_____no_output_____"
]
],
[
[
"result = tips.groupby('smoker')['tip_pct'].describe()\r\nresult",
"_____no_output_____"
],
[
"result.unstack('smoker')",
"_____no_output_____"
]
],
[
[
"Inside GroupBy, when you invoke a method like `describe`, *it is actually just a shortcut for*:",
"_____no_output_____"
]
],
[
[
"f = lambda x: x.describe()\r\ngrouped.apply(f)",
"_____no_output_____"
]
],
[
[
"### 10.3.1. Suppressing the Group Keys",
"_____no_output_____"
],
[
"In the preceding examples, you see that the *resulting object has a hierarchical index* formed from the group keys along with the indexes of each piece of the original object. You can *disable this by passing* `group_keys=False`to *groupby*:",
"_____no_output_____"
]
],
[
[
"tips.groupby('smoker', group_keys=False).apply(top)",
"_____no_output_____"
]
],
[
[
"### 10.3.2. Quantile and Bucket Analysis",
"_____no_output_____"
],
[
"As you may `recall from Chapter 8`, pandas has some tools, in particular `cut and qcut`, *for slicing data up into buckets with bins of your choosing or by sample quantiles*. `Combining these functions with groupby makes it convenient to perform bucket or quantile analysis on a dataset`.<br>\r\nConsider a simple random dataset and an equal-length bucket categorization using cut:",
"_____no_output_____"
]
],
[
[
"#@P checking syntax docstring\r\nnp.random.randn??",
"\u001b[1;31mDocstring:\u001b[0m\nrandn(d0, d1, ..., dn)\n\nReturn a sample (or samples) from the \"standard normal\" distribution.\n\n.. note::\n This is a convenience function for users porting code from Matlab,\n and wraps `standard_normal`. That function takes a\n tuple to specify the size of the output, which is consistent with\n other NumPy functions like `numpy.zeros` and `numpy.ones`.\n\n.. note::\n New code should use the ``standard_normal`` method of a ``default_rng()``\n instance instead; please see the :ref:`random-quick-start`.\n\nIf positive int_like arguments are provided, `randn` generates an array\nof shape ``(d0, d1, ..., dn)``, filled\nwith random floats sampled from a univariate \"normal\" (Gaussian)\ndistribution of mean 0 and variance 1. A single float randomly sampled\nfrom the distribution is returned if no argument is provided.\n\nParameters\n----------\nd0, d1, ..., dn : int, optional\n The dimensions of the returned array, must be non-negative.\n If no argument is given a single Python float is returned.\n\nReturns\n-------\nZ : ndarray or float\n A ``(d0, d1, ..., dn)``-shaped array of floating-point samples from\n the standard normal distribution, or a single such float if\n no parameters were supplied.\n\nSee Also\n--------\nstandard_normal : Similar, but takes a tuple as its argument.\nnormal : Also accepts mu and sigma arguments.\nGenerator.standard_normal: which should be used for new code.\n\nNotes\n-----\nFor random samples from :math:`N(\\mu, \\sigma^2)`, use:\n\n``sigma * np.random.randn(...) + mu``\n\nExamples\n--------\n>>> np.random.randn()\n2.1923875335537315 # random\n\nTwo-by-four array of samples from N(3, 6.25):\n\n>>> 3 + 2.5 * np.random.randn(2, 4)\narray([[-4.49401501, 4.00950034, -1.81814867, 7.29718677], # random\n [ 0.39924804, 4.68456316, 4.99394529, 4.84057254]]) # random\n\u001b[1;31mType:\u001b[0m builtin_function_or_method\n"
],
[
"#@P checking syntax docstring\r\npd.cut?",
"\u001b[1;31mSignature:\u001b[0m\n\u001b[0mpd\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mcut\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mx\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mbins\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mright\u001b[0m\u001b[1;33m:\u001b[0m \u001b[0mbool\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;32mTrue\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mlabels\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;32mNone\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mretbins\u001b[0m\u001b[1;33m:\u001b[0m \u001b[0mbool\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;32mFalse\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mprecision\u001b[0m\u001b[1;33m:\u001b[0m \u001b[0mint\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m3\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0minclude_lowest\u001b[0m\u001b[1;33m:\u001b[0m \u001b[0mbool\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;32mFalse\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mduplicates\u001b[0m\u001b[1;33m:\u001b[0m \u001b[0mstr\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;34m'raise'\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mordered\u001b[0m\u001b[1;33m:\u001b[0m \u001b[0mbool\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;32mTrue\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;31mDocstring:\u001b[0m\nBin values into discrete intervals.\n\nUse `cut` when you need to segment and sort data values into bins. This\nfunction is also useful for going from a continuous variable to a\ncategorical variable. For example, `cut` could convert ages to groups of\nage ranges. Supports binning into an equal number of bins, or a\npre-specified array of bins.\n\nParameters\n----------\nx : array-like\n The input array to be binned. Must be 1-dimensional.\nbins : int, sequence of scalars, or IntervalIndex\n The criteria to bin by.\n\n * int : Defines the number of equal-width bins in the range of `x`. The\n range of `x` is extended by .1% on each side to include the minimum\n and maximum values of `x`.\n * sequence of scalars : Defines the bin edges allowing for non-uniform\n width. No extension of the range of `x` is done.\n * IntervalIndex : Defines the exact bins to be used. Note that\n IntervalIndex for `bins` must be non-overlapping.\n\nright : bool, default True\n Indicates whether `bins` includes the rightmost edge or not. If\n ``right == True`` (the default), then the `bins` ``[1, 2, 3, 4]``\n indicate (1,2], (2,3], (3,4]. This argument is ignored when\n `bins` is an IntervalIndex.\nlabels : array or False, default None\n Specifies the labels for the returned bins. Must be the same length as\n the resulting bins. If False, returns only integer indicators of the\n bins. This affects the type of the output container (see below).\n This argument is ignored when `bins` is an IntervalIndex. If True,\n raises an error. When `ordered=False`, labels must be provided.\nretbins : bool, default False\n Whether to return the bins or not. Useful when bins is provided\n as a scalar.\nprecision : int, default 3\n The precision at which to store and display the bins labels.\ninclude_lowest : bool, default False\n Whether the first interval should be left-inclusive or not.\nduplicates : {default 'raise', 'drop'}, optional\n If bin edges are not unique, raise ValueError or drop non-uniques.\nordered : bool, default True\n Whether the labels are ordered or not. Applies to returned types\n Categorical and Series (with Categorical dtype). If True,\n the resulting categorical will be ordered. If False, the resulting\n categorical will be unordered (labels must be provided).\n\n .. versionadded:: 1.1.0\n\nReturns\n-------\nout : Categorical, Series, or ndarray\n An array-like object representing the respective bin for each value\n of `x`. The type depends on the value of `labels`.\n\n * True (default) : returns a Series for Series `x` or a\n Categorical for all other inputs. The values stored within\n are Interval dtype.\n\n * sequence of scalars : returns a Series for Series `x` or a\n Categorical for all other inputs. The values stored within\n are whatever the type in the sequence is.\n\n * False : returns an ndarray of integers.\n\nbins : numpy.ndarray or IntervalIndex.\n The computed or specified bins. Only returned when `retbins=True`.\n For scalar or sequence `bins`, this is an ndarray with the computed\n bins. If set `duplicates=drop`, `bins` will drop non-unique bin. For\n an IntervalIndex `bins`, this is equal to `bins`.\n\nSee Also\n--------\nqcut : Discretize variable into equal-sized buckets based on rank\n or based on sample quantiles.\nCategorical : Array type for storing data that come from a\n fixed set of values.\nSeries : One-dimensional array with axis labels (including time series).\nIntervalIndex : Immutable Index implementing an ordered, sliceable set.\n\nNotes\n-----\nAny NA values will be NA in the result. Out of bounds values will be NA in\nthe resulting Series or Categorical object.\n\nExamples\n--------\nDiscretize into three equal-sized bins.\n\n>>> pd.cut(np.array([1, 7, 5, 4, 6, 3]), 3)\n... # doctest: +ELLIPSIS\n[(0.994, 3.0], (5.0, 7.0], (3.0, 5.0], (3.0, 5.0], (5.0, 7.0], ...\nCategories (3, interval[float64, right]): [(0.994, 3.0] < (3.0, 5.0] ...\n\n>>> pd.cut(np.array([1, 7, 5, 4, 6, 3]), 3, retbins=True)\n... # doctest: +ELLIPSIS\n([(0.994, 3.0], (5.0, 7.0], (3.0, 5.0], (3.0, 5.0], (5.0, 7.0], ...\nCategories (3, interval[float64, right]): [(0.994, 3.0] < (3.0, 5.0] ...\narray([0.994, 3. , 5. , 7. ]))\n\nDiscovers the same bins, but assign them specific labels. Notice that\nthe returned Categorical's categories are `labels` and is ordered.\n\n>>> pd.cut(np.array([1, 7, 5, 4, 6, 3]),\n... 3, labels=[\"bad\", \"medium\", \"good\"])\n['bad', 'good', 'medium', 'medium', 'good', 'bad']\nCategories (3, object): ['bad' < 'medium' < 'good']\n\n``ordered=False`` will result in unordered categories when labels are passed.\nThis parameter can be used to allow non-unique labels:\n\n>>> pd.cut(np.array([1, 7, 5, 4, 6, 3]), 3,\n... labels=[\"B\", \"A\", \"B\"], ordered=False)\n['B', 'B', 'A', 'A', 'B', 'B']\nCategories (2, object): ['A', 'B']\n\n``labels=False`` implies you just want the bins back.\n\n>>> pd.cut([0, 1, 1, 2], bins=4, labels=False)\narray([0, 1, 1, 3])\n\nPassing a Series as an input returns a Series with categorical dtype:\n\n>>> s = pd.Series(np.array([2, 4, 6, 8, 10]),\n... index=['a', 'b', 'c', 'd', 'e'])\n>>> pd.cut(s, 3)\n... # doctest: +ELLIPSIS\na (1.992, 4.667]\nb (1.992, 4.667]\nc (4.667, 7.333]\nd (7.333, 10.0]\ne (7.333, 10.0]\ndtype: category\nCategories (3, interval[float64, right]): [(1.992, 4.667] < (4.667, ...\n\nPassing a Series as an input returns a Series with mapping value.\nIt is used to map numerically to intervals based on bins.\n\n>>> s = pd.Series(np.array([2, 4, 6, 8, 10]),\n... index=['a', 'b', 'c', 'd', 'e'])\n>>> pd.cut(s, [0, 2, 4, 6, 8, 10], labels=False, retbins=True, right=False)\n... # doctest: +ELLIPSIS\n(a 1.0\n b 2.0\n c 3.0\n d 4.0\n e NaN\n dtype: float64,\n array([ 0, 2, 4, 6, 8, 10]))\n\nUse `drop` optional when bins is not unique\n\n>>> pd.cut(s, [0, 2, 4, 6, 10, 10], labels=False, retbins=True,\n... right=False, duplicates='drop')\n... # doctest: +ELLIPSIS\n(a 1.0\n b 2.0\n c 3.0\n d 3.0\n e NaN\n dtype: float64,\n array([ 0, 2, 4, 6, 10]))\n\nPassing an IntervalIndex for `bins` results in those categories exactly.\nNotice that values not covered by the IntervalIndex are set to NaN. 0\nis to the left of the first bin (which is closed on the right), and 1.5\nfalls between two bins.\n\n>>> bins = pd.IntervalIndex.from_tuples([(0, 1), (2, 3), (4, 5)])\n>>> pd.cut([0, 0.5, 1.5, 2.5, 4.5], bins)\n[NaN, (0.0, 1.0], NaN, (2.0, 3.0], (4.0, 5.0]]\nCategories (3, interval[int64, right]): [(0, 1] < (2, 3] < (4, 5]]\n\u001b[1;31mFile:\u001b[0m d:\\users\\phu.le2\\anaconda3\\lib\\site-packages\\pandas\\core\\reshape\\tile.py\n\u001b[1;31mType:\u001b[0m function\n"
],
[
"frame = pd.DataFrame({'data1': np.random.randn(1000),\r\n 'data2': np.random.randn(1000)})\r\nquartiles = pd.cut(frame.data1, 4) #@P: cut the data1 to 4 group (not equal)\r\nquartiles[:10]",
"_____no_output_____"
]
],
[
[
"The `Categorical object` `returned by cut` can be passed directly to groupby. So we could compute a set of statistics for the data2 column like so:",
"_____no_output_____"
]
],
[
[
"#@P vietsub: get_stats is to obtain min, max, count, mean of the group\r\ndef get_stats(group):\r\n return {'min': group.min(), 'max': group.max(),\r\n 'count': group.count(), 'mean': group.mean()}\r\ngrouped = frame.data2.groupby(quartiles)\r\ngrouped.apply(get_stats).unstack()",
"_____no_output_____"
]
],
[
[
"These were equal-length buckets; to `compute equal-size buckets based on sample quantiles`, use `qcut`. I’ll pass labels=False to just get quantile numbers:",
"_____no_output_____"
]
],
[
[
"pd.qcut??",
"\u001b[1;31mSignature:\u001b[0m\n\u001b[0mpd\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mqcut\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mx\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mq\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mlabels\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;32mNone\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mretbins\u001b[0m\u001b[1;33m:\u001b[0m \u001b[0mbool\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;32mFalse\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mprecision\u001b[0m\u001b[1;33m:\u001b[0m \u001b[0mint\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m3\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mduplicates\u001b[0m\u001b[1;33m:\u001b[0m \u001b[0mstr\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;34m'raise'\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;31mSource:\u001b[0m \n\u001b[1;32mdef\u001b[0m \u001b[0mqcut\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mx\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mq\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mlabels\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;32mNone\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mretbins\u001b[0m\u001b[1;33m:\u001b[0m \u001b[0mbool\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;32mFalse\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mprecision\u001b[0m\u001b[1;33m:\u001b[0m \u001b[0mint\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m3\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mduplicates\u001b[0m\u001b[1;33m:\u001b[0m \u001b[0mstr\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;34m\"raise\"\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[1;34m\"\"\"\n Quantile-based discretization function.\n\n Discretize variable into equal-sized buckets based on rank or based\n on sample quantiles. For example 1000 values for 10 quantiles would\n produce a Categorical object indicating quantile membership for each data point.\n\n Parameters\n ----------\n x : 1d ndarray or Series\n q : int or list-like of float\n Number of quantiles. 10 for deciles, 4 for quartiles, etc. Alternately\n array of quantiles, e.g. [0, .25, .5, .75, 1.] for quartiles.\n labels : array or False, default None\n Used as labels for the resulting bins. Must be of the same length as\n the resulting bins. If False, return only integer indicators of the\n bins. If True, raises an error.\n retbins : bool, optional\n Whether to return the (bins, labels) or not. Can be useful if bins\n is given as a scalar.\n precision : int, optional\n The precision at which to store and display the bins labels.\n duplicates : {default 'raise', 'drop'}, optional\n If bin edges are not unique, raise ValueError or drop non-uniques.\n\n Returns\n -------\n out : Categorical or Series or array of integers if labels is False\n The return type (Categorical or Series) depends on the input: a Series\n of type category if input is a Series else Categorical. Bins are\n represented as categories when categorical data is returned.\n bins : ndarray of floats\n Returned only if `retbins` is True.\n\n Notes\n -----\n Out of bounds values will be NA in the resulting Categorical object\n\n Examples\n --------\n >>> pd.qcut(range(5), 4)\n ... # doctest: +ELLIPSIS\n [(-0.001, 1.0], (-0.001, 1.0], (1.0, 2.0], (2.0, 3.0], (3.0, 4.0]]\n Categories (4, interval[float64, right]): [(-0.001, 1.0] < (1.0, 2.0] ...\n\n >>> pd.qcut(range(5), 3, labels=[\"good\", \"medium\", \"bad\"])\n ... # doctest: +SKIP\n [good, good, medium, bad, bad]\n Categories (3, object): [good < medium < bad]\n\n >>> pd.qcut(range(5), 4, labels=False)\n array([0, 0, 1, 2, 3])\n \"\"\"\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0moriginal\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mx\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mx\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0m_preprocess_for_cut\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mx\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mx\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mdtype\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0m_coerce_to_type\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mx\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\n\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0mis_integer\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mq\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mquantiles\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mnp\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mlinspace\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m1\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mq\u001b[0m \u001b[1;33m+\u001b[0m \u001b[1;36m1\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mquantiles\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mq\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mbins\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0malgos\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mquantile\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mx\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mquantiles\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mfac\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mbins\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0m_bins_to_cuts\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mx\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mbins\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mlabels\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mlabels\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mprecision\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mprecision\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0minclude_lowest\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;32mTrue\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mdtype\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mdtype\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[0mduplicates\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mduplicates\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[1;33m)\u001b[0m\u001b[1;33m\n\u001b[0m\u001b[1;33m\n\u001b[0m \u001b[1;32mreturn\u001b[0m \u001b[0m_postprocess_for_cut\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mfac\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mbins\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mretbins\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mdtype\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0moriginal\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;31mFile:\u001b[0m d:\\users\\phu.le2\\anaconda3\\lib\\site-packages\\pandas\\core\\reshape\\tile.py\n\u001b[1;31mType:\u001b[0m function\n"
],
[
"# Return quantile numbers\r\ngrouping = pd.qcut(frame.data1, 10, labels=False) #cut data1 to 10 equal group\r\ngrouped = frame.data2.groupby(grouping)\r\ngrouped.apply(get_stats).unstack()",
"_____no_output_____"
]
],
[
[
"### 10.3.3. Example: Filling Missing Values with Group-Specific Values",
"_____no_output_____"
],
[
"When cleaning up missing data, in some cases you will replace data observations using dropna, but in others you may want to impute (fill in) the null (NA) values using a fixed value or some value derived from the data. `fillna is the right tool to use`;<br>\r\nfor example, here I fill in NA values with the mean:",
"_____no_output_____"
]
],
[
[
"s = pd.Series(np.random.randn(6))\r\ns[::2] = np.nan\r\ns\r\ns.fillna(s.mean())",
"_____no_output_____"
]
],
[
[
"`Suppose you need the fill value to vary by group`. One way to do this is to group the data and use apply with a function that calls fillna on each data chunk. Here is some sample data on US states divided into eastern and western regions:",
"_____no_output_____"
]
],
[
[
"states = ['Ohio', 'New York', 'Vermont', 'Florida',\r\n 'Oregon', 'Nevada', 'California', 'Idaho']\r\ngroup_key = ['East'] * 4 + ['West'] * 4\r\ndata = pd.Series(np.random.randn(8), index=states)\r\ndata",
"_____no_output_____"
]
],
[
[
"Note that the syntax ['East'] * 4 produces a list containing four copies of the elements in ['East']. Adding lists together concatenates them.<br>\r\nLet’s set some values in the data to be missing:",
"_____no_output_____"
]
],
[
[
"data[['Vermont', 'Nevada', 'Idaho']] = np.nan\r\ndata",
"_____no_output_____"
],
[
"data.groupby(group_key).mean()",
"_____no_output_____"
]
],
[
[
"We can fill the NA values using the group means like so:",
"_____no_output_____"
]
],
[
[
"fill_mean = lambda g: g.fillna(g.mean())\r\ndata.groupby(group_key).apply(fill_mean)",
"_____no_output_____"
]
],
[
[
"In another case, you might have predefined fill values in your code that vary by group. Since the groups have a `name` attribute set internally, we can use that:",
"_____no_output_____"
]
],
[
[
"fill_values = {'East': 0.5, 'West': -1}\r\nfill_func = lambda g: g.fillna(fill_values[g.name])\r\ndata.groupby(group_key).apply(fill_func)",
"_____no_output_____"
]
],
[
[
"### 10.3.4. Example: Random Sampling and Permutation",
"_____no_output_____"
],
[
"`Suppose you wanted to draw a random sample (with or without replacement) from a large dataset` for Monte Carlo simulation purposes or some other application. *There are a number of ways to perform the “draws”*; *here we use the sample method for Series*.",
"_____no_output_____"
],
[
"To demonstrate, here’s a way to construct a deck of English-style playing cards:",
"_____no_output_____"
]
],
[
[
"# Hearts, Spades, Clubs, Diamonds\r\nsuits = ['H', 'S', 'C', 'D']\r\ncard_val = (list(range(1, 11)) + [10] * 3) * 4 #@P: đoạn 10 *3 để thêm value cho J, K, Q = 10 như kết quả bên dưới\r\nbase_names = ['A'] + list(range(2, 11)) + ['J', 'K', 'Q']\r\ncards = []\r\nfor suit in ['H', 'S', 'C', 'D']:\r\n cards.extend(str(num) + suit for num in base_names)\r\n\r\ndeck = pd.Series(card_val, index=cards)\r\ndeck",
"_____no_output_____"
]
],
[
[
"So now we have a Series of length 52 whose index contains card names and values are the ones used in Blackjack and other games (to keep things simple, I just let the ace 'A' be 1):",
"_____no_output_____"
]
],
[
[
"deck[:20]",
"_____no_output_____"
]
],
[
[
"Now, based on what I said before, drawing a hand of five cards from the deck could be written as:",
"_____no_output_____"
]
],
[
[
"def draw(deck, n=5):\r\n return deck.sample(n)\r\ndraw(deck)",
"_____no_output_____"
]
],
[
[
"Suppose you wanted two random cards from each suit (@P: suits = ['H', 'S', 'C', 'D'] -- Hearts, Spades, Clubs, Diamonds). Because the suit is the last character of each card name, we can group based on this and use apply:",
"_____no_output_____"
]
],
[
[
"get_suit = lambda card: card[-1] # last letter is suit\r\ndeck.groupby(get_suit).apply(draw, n=2)",
"_____no_output_____"
]
],
[
[
"Alternatively, we could write:",
"_____no_output_____"
]
],
[
[
"deck.groupby(get_suit, group_keys=False).apply(draw, n=2)",
"_____no_output_____"
]
],
[
[
"### 10.3.5. Example: Group Weighted Average and Correlation",
"_____no_output_____"
],
[
"Under the split-apply-combine paradigm of `groupby`, operations between columns in a DataFrame or two Series, such as a group weighted average, are possible. As an example, take this dataset containing group keys, values, and some weights:",
"_____no_output_____"
]
],
[
[
"df = pd.DataFrame({'category': ['a', 'a', 'a', 'a',\r\n 'b', 'b', 'b', 'b'],\r\n 'data': np.random.randn(8),\r\n 'weights': np.random.rand(8)})\r\ndf",
"_____no_output_____"
]
],
[
[
"The group weighted average by `category` would then be:",
"_____no_output_____"
]
],
[
[
"grouped = df.groupby('category')\r\nget_wavg = lambda g: np.average(g['data'], weights=g['weights'])\r\ngrouped.apply(get_wavg)",
"_____no_output_____"
]
],
[
[
"As another example, consider a financial dataset originally obtained from Yahoo! Finance containing end-of-day prices for a few stocks and the S&P 500 index (the SPX symbol):",
"_____no_output_____"
]
],
[
[
"close_px = pd.read_csv('examples/stock_px_2.csv', parse_dates=True,\r\n index_col=0)\r\nclose_px.info()\r\nclose_px[-4:]",
"<class 'pandas.core.frame.DataFrame'>\nDatetimeIndex: 2214 entries, 2003-01-02 to 2011-10-14\nData columns (total 4 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 AAPL 2214 non-null float64\n 1 MSFT 2214 non-null float64\n 2 XOM 2214 non-null float64\n 3 SPX 2214 non-null float64\ndtypes: float64(4)\nmemory usage: 86.5 KB\n"
]
],
[
[
"One task of interest might be to compute a DataFrame consisting of the yearly correlations of daily returns (computed from percent changes) with SPX.<br> As one way to do this, we first create a function that computes the pairwise correlation of each column with the 'SPX' column:",
"_____no_output_____"
]
],
[
[
"spx_corr = lambda x: x.corrwith(x['SPX']) #@P 20210903: SPX: S&P500 Index",
"_____no_output_____"
]
],
[
[
"Next, we compute percent change on `close_px` using `pct_change`:",
"_____no_output_____"
]
],
[
[
"rets = close_px.pct_change().dropna()",
"_____no_output_____"
]
],
[
[
"Lastly, we group these percent changes by year, which can be extracted from each row label with a one-line function that returns the `year` attribute of each `datetime` label:",
"_____no_output_____"
]
],
[
[
"get_year = lambda x: x.year\r\nby_year = rets.groupby(get_year)\r\nby_year.apply(spx_corr)",
"_____no_output_____"
]
],
[
[
"You could also compute inter-column correlations. Here we compute the annual correlation between Apple and Microsoft:",
"_____no_output_____"
]
],
[
[
"by_year.apply(lambda g: g['AAPL'].corr(g['MSFT']))",
"_____no_output_____"
]
],
[
[
"### 10.3.6. Example: Group-Wise Linear Regression",
"_____no_output_____"
],
[
"In the same theme as the previous example, you can use `groupby` to perform more complex group-wise statistical analysis, as long as the function returns a pandas object or scalar value.<br>\r\nFor example, I can define the following `regress` function (using the `statsmodels` econometrics library), which executes an `ordinary least squares (OLS) regression` on each chunk of data:",
"_____no_output_____"
]
],
[
[
"import statsmodels.api as sm\r\ndef regress(data, yvar, xvars):\r\n Y = data[yvar]\r\n X = data[xvars]\r\n X['intercept'] = 1.\r\n result = sm.OLS(Y, X).fit()\r\n return result.params",
"_____no_output_____"
]
],
[
[
"Now, to run a yearly linear regression of *AAPL* on *SPX* returns, execute:",
"_____no_output_____"
]
],
[
[
"by_year.apply(regress, 'AAPL', ['SPX'])",
"_____no_output_____"
]
],
[
[
"## 10.4. Pivot Tables and Cross-Tabulation",
"_____no_output_____"
],
[
"A pivot table is a data summarization tool frequently found in spreadsheet programs and other data analysis software. It aggregates a table of data by one or more keys, arranging the data in a rectangle with some of the group keys along the rows and some along the columns. `Pivot tables in Python with pandas are made possible through the groupby facility described in this chapter combined with reshape operations utilizing hierarchical indexing`. DataFrame has a pivot_table method, and there is also a top-level pandas.pivot_table function. In addition to providing a convenience interface to groupby, pivot_table can add partial totals, also known as margins.",
"_____no_output_____"
],
[
"Returning to the *tipping dataset*, suppose you wanted to *compute a table of group means* (the default pivot_table aggregation type) arranged *by day and smoker* on the rows:",
"_____no_output_____"
]
],
[
[
"tips.pivot_table(index=['day', 'smoker'])",
"_____no_output_____"
]
],
[
[
"`This could have been produced with groupby directly`. Now, suppose we want to aggregate only *tip_pct* and *size*, and additionally group by time. I’ll put *smoker* in the table columns and *day* in the rows:",
"_____no_output_____"
]
],
[
[
"tips.pivot_table(['tip_pct', 'size'], index=['time', 'day'],\r\n columns='smoker')",
"_____no_output_____"
]
],
[
[
"We could augment this table to include partial totals by passing *margins=True*. This has the effect of *adding All row and column labels*, with corresponding values being the group statistics for all the data within a single tier:<br>\r\n#@P 20210903: it like a subtotal for each group in Excel pivotable? (P guess they use the term margin to indicate the subotal is put at the margin of the calculated table)",
"_____no_output_____"
]
],
[
[
"tips.pivot_table(['tip_pct', 'size'], index=['time', 'day'],\r\n columns='smoker', margins=True)",
"_____no_output_____"
]
],
[
[
"Here, the All values are means without taking into account smoker versus non-smoker (the All columns) or any of the two levels of grouping on the rows (the All row).",
"_____no_output_____"
],
[
"*To use a different aggregation function*, pass it to `aggfunc`. For example, *'count'* or *len* will give you a cross-tabulation (count or frequency) of group sizes:",
"_____no_output_____"
]
],
[
[
"tips.pivot_table('tip_pct', index=['time', 'smoker'], columns='day',\r\n aggfunc=len, margins=True)",
"_____no_output_____"
]
],
[
[
"If some combinations are empty (or otherwise NA), you may wish to pass a `fill_value`:",
"_____no_output_____"
]
],
[
[
"tips.pivot_table('tip_pct', index=['time', 'size', 'smoker'],\r\n columns='day', aggfunc='mean', fill_value=0)",
"_____no_output_____"
]
],
[
[
"### 10.4.1 Cross-Tabulations: Crosstab",
"_____no_output_____"
],
[
"A `cross-tabulation` (or `crosstab` for short) is *a special case* of a pivot table that computes group frequencies. Here is an example:",
"_____no_output_____"
]
],
[
[
"from io import StringIO\r\ndata = \"\"\"\\\r\nSample Nationality Handedness\r\n1 USA Right-handed\r\n2 Japan Left-handed\r\n3 USA Right-handed\r\n4 Japan Right-handed\r\n5 Japan Left-handed\r\n6 Japan Right-handed\r\n7 USA Right-handed\r\n8 USA Left-handed\r\n9 Japan Right-handed\r\n10 USA Right-handed\"\"\"\r\ndata = pd.read_table(StringIO(data), sep='\\s+')",
"_____no_output_____"
],
[
"data",
"_____no_output_____"
]
],
[
[
"As part of some survey analysis, we might want to summarize this data by nationality and handedness. *You could use pivot_table to do this*, but the `pandas.crosstab function` can be more convenient:",
"_____no_output_____"
]
],
[
[
"pd.crosstab(data.Nationality, data.Handedness, margins=True)",
"_____no_output_____"
]
],
[
[
"*The first two arguments to crosstab *can each either `be an array` or `Series` or `a list of arrays`. As in the tips data:",
"_____no_output_____"
]
],
[
[
"pd.crosstab([tips.time, tips.day], tips.smoker, margins=True)",
"_____no_output_____"
],
[
"pd.options.display.max_rows = PREVIOUS_MAX_ROWS",
"_____no_output_____"
]
],
[
[
"## 10.5. Conclusion",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
e77b19952955ee5f1812666ba4590719c97dae93 | 7,844 | ipynb | Jupyter Notebook | d2l/chapter_computer-vision/rcnn.ipynb | atlasbioinfo/myDLNotes_Pytorch | fada6ab56af340cd5ec6cc4dfd5e749af16a6ed4 | [
"MIT"
] | null | null | null | d2l/chapter_computer-vision/rcnn.ipynb | atlasbioinfo/myDLNotes_Pytorch | fada6ab56af340cd5ec6cc4dfd5e749af16a6ed4 | [
"MIT"
] | null | null | null | d2l/chapter_computer-vision/rcnn.ipynb | atlasbioinfo/myDLNotes_Pytorch | fada6ab56af340cd5ec6cc4dfd5e749af16a6ed4 | [
"MIT"
] | null | null | null | 32.683333 | 246 | 0.59434 | [
[
[
"# 区域卷积神经网络(R-CNN)系列\n:label:`sec_rcnn`\n\n除了 :numref:`sec_ssd` 中描述的单发多框检测之外,\n区域卷积神经网络(region-based CNN或regions with CNN features,R-CNN) :cite:`Girshick.Donahue.Darrell.ea.2014` 也是将深度模型应用于目标检测的开创性工作之一。\n在本节中,我们将介绍R-CNN及其一系列改进方法:快速的R-CNN(Fast R-CNN) :cite:`Girshick.2015` 、更快的R-CNN(Faster R-CNN) :cite:`Ren.He.Girshick.ea.2015` 和掩码R-CNN(Mask R-CNN) :cite:`He.Gkioxari.Dollar.ea.2017` 。\n限于篇幅,我们只着重介绍这些模型的设计思路。 \n\n## R-CNN\n\n*R-CNN* 首先从输入图像中选取若干(例如2000个)*提议区域*(如锚框也是一种选取方法),并标注它们的类别和边界框(如偏移量)。 :cite:`Girshick.Donahue.Darrell.ea.2014` 然后,用卷积神经网络对每个提议区域进行前向计算以抽取其特征。\n接下来,我们用每个提议区域的特征来预测类别和边界框。 \n\n\n:label:`fig_r-cnn`\n\n:numref:`fig_r-cnn` 展示了R-CNN模型。具体来说,R-CNN包括以下四个步骤: \n\n1. 对输入图像使用 *选择性搜索* 来选取多个高质量的提议区域 :cite:`Uijlings.Van-De-Sande.Gevers.ea.2013` 。这些提议区域通常是在多个尺度下选取的,并具有不同的形状和大小。每个提议区域都将被标注类别和真实边界框。\n1. 选择一个预训练的卷积神经网络,并将其在输出层之前截断。将每个提议区域变形为网络需要的输入尺寸,并通过前向计算输出抽取的提议区域特征。 \n1. 将每个提议区域的特征连同其标注的类别作为一个样本。训练多个支持向量机对目标分类,其中每个支持向量机用来判断样本是否属于某一个类别。\n1. 将每个提议区域的特征连同其标注的边界框作为一个样本,训练线性回归模型来预测真实边界框。\n\n尽管 R-CNN 模型通过预训练的卷积神经网络有效地抽取了图像特征,但它的速度很慢。\n想象一下,我们可能从一张图像中选出上千个提议区域,这需要上千次的卷积神经网络的前向计算来执行目标检测。\n这种庞大的计算量使得 R-CNN 在现实世界中难以被广泛应用。 \n\n## Fast R-CNN\n\nR-CNN 的主要性能瓶颈在于,对每个提议区域,卷积神经网络的前向计算是独立的,而没有共享计算。\n由于这些区域通常有重叠,独立的特征抽取会导致重复的计算。\n*Fast R-CNN* :cite:`Girshick.2015` 对 R-CNN 的主要改进之一,是仅在整张图象上执行卷积神经网络的前向计算。 \n\n\n:label:`fig_fast_r-cnn`\n\n:numref:`fig_fast_r-cnn` 中描述了 Fast R-CNN 模型。它的主要计算如下: \n\n1. 与 R-CNN 相比,Fast R-CNN 用来提取特征的卷积神经网络的输入是整个图像,而不是各个提议区域。此外,这个网络通常会参与训练。设输入为一张图像,将卷积神经网络的输出的形状记为 $1 \\times c \\times h_1 \\times w_1$。\n1. 假设选择性搜索生成了$n$个提议区域。这些形状各异的提议区域在卷积神经网络的输出上分别标出了形状各异的兴趣区域。然后,这些感兴趣的区域需要进一步抽取出形状相同的特征(比如指定高度$h_2$和宽度$w_2$),以便于连结后输出。为了实现这一目标,Fast R-CNN 引入了 *兴趣区域 (RoI) 池化* 层:将卷积神经网络的输出和提议区域作为输入,输出连结后的各个提议区域抽取的特征,形状为$n \\times c \\times h_2 \\times w_2$。\n1. 通过全连接层将输出形状变换为$n \\times d$,其中超参数$d$取决于模型设计。\n1. 预测$n$个提议区域中每个区域的类别和边界框。更具体地说,在预测类别和边界框时,将全连接层的输出分别转换为形状为 $n \\times q$($q$ 是类别的数量)的输出和形状为 $n \\times 4$ 的输出。其中预测类别时使用 softmax 回归。\n\n在Fast R-CNN 中提出的兴趣区域汇聚层与 :numref:`sec_pooling` 中介绍的汇聚层有所不同。在汇聚层中,我们通过设置池化窗口、填充和步幅的大小来间接控制输出形状。而兴趣区域汇聚层对每个区域的输出形状是可以直接指定的。 \n\n例如,指定每个区域输出的高和宽分别为 $h_2$ 和 $w_2$。\n对于任何形状为 $h \\times w$ 的兴趣区域窗口,该窗口将被划分为 $h_2 \\times w_2$ 子窗口网格,其中每个子窗口的大小约为$(h/h_2) \\times (w/w_2)$。\n在实践中,任何子窗口的高度和宽度都应向上取整,其中的最大元素作为该子窗口的输出。\n因此,兴趣区域汇聚层可从形状各异的兴趣区域中均抽取出形状相同的特征。\n\n作为说明性示例, :numref:`fig_roi` 中提到,在$4 \\times 4$的输入中,我们选取了左上角 $3\\times 3$ 的兴趣区域。\n对于该兴趣区域,我们通过 $2\\times 2$ 的兴趣区域汇聚层得到一个 $2\\times 2$ 的输出。\n请注意,四个划分后的子窗口中分别含有元素 0、1、4、5(5最大);2、6(6最大);8、9(9最大);以及10。 \n\n\n:label:`fig_roi`\n\n下面,我们演示了兴趣区域汇聚层的计算方法。\n假设卷积神经网络抽取的特征 `X` 的高度和宽度都是 4,且只有单通道。\n",
"_____no_output_____"
]
],
[
[
"import torch\nimport torchvision\n\nX = torch.arange(16.).reshape(1, 1, 4, 4)\nX",
"_____no_output_____"
]
],
[
[
"让我们进一步假设输入图像的高度和宽度都是40像素,且选择性搜索在此图像上生成了两个提议区域。\n每个区域由5个元素表示:区域目标类别、左上角和右下角的 $(x, y)$ 坐标。\n",
"_____no_output_____"
]
],
[
[
"rois = torch.Tensor([[0, 0, 0, 20, 20], [0, 0, 10, 30, 30]])",
"_____no_output_____"
]
],
[
[
"由于 `X` 的高和宽是输入图像高和宽的 $1/10$,因此,两个提议区域的坐标先按 `spatial_scale` 乘以 0.1。\n然后,在 `X` 上分别标出这两个兴趣区域 `X[:, :, 1:4, 0:4]` 和 `X[:, :, 1:4, 0:4]` 。\n最后,在 $2\\times 2$ 的兴趣区域汇聚层中,每个兴趣区域被划分为子窗口网格,并进一步抽取相同形状 $2\\times 2$ 的特征。\n",
"_____no_output_____"
]
],
[
[
"torchvision.ops.roi_pool(X, rois, output_size=(2, 2), spatial_scale=0.1)",
"_____no_output_____"
]
],
[
[
"## Faster R-CNN\n\n为了较精确地检测目标结果,Fast R-CNN 模型通常需要在选择性搜索中生成大量的提议区域。\n*Faster R-CNN* :cite:`Ren.He.Girshick.ea.2015` 提出将选择性搜索替换为 *区域提议网络*(region proposal network),从而减少提议区域的生成数量,并保证目标检测的精度。 \n\n\n:label:`fig_faster_r-cnn`\n\n:numref:`fig_faster_r-cnn` 描述了Faster R-CNN 模型。\n与Fast R-CNN 相比,Faster R-CNN 只将生成提议区域的方法从选择性搜索改为了区域提议网络,模型的其余部分保持不变。具体来说,区域提议网络的计算步骤如下: \n\n1. 使用填充为1的 $3\\times 3$ 的卷积层变换卷积神经网络的输出,并将输出通道数记为 $c$。这样,卷积神经网络为图像抽取的特征图中的每个单元均得到一个长度为 $c$ 的新特征。\n1. 以特征图的每个像素为中心,生成多个不同大小和宽高比的锚框并标注它们。\n1. 使用锚框中心单元长度为 $c$ 的特征,分别预测该锚框的二元类别(含目标还是背景)和边界框。\n1. 使用非极大值抑制,从预测类别为目标的预测边界框中移除相似的结果。最终输出的预测边界框即是兴趣区域汇聚层所需的提议区域。\n\n值得一提的是,区域提议网络作为 Faster R-CNN 模型的一部分,是和整个模型一起训练得到的。\n换句话说,Faster R-CNN 的目标函数不仅包括目标检测中的类别和边界框预测,还包括区域提议网络中锚框的二元类别和边界框预测。\n作为端到端训练的结果,区域提议网络能够学习到如何生成高质量的提议区域,从而在减少了从数据中学习的提议区域的数量的情况下,仍保持目标检测的精度。 \n\n## Mask R-CNN\n\n如果在训练集中还标注了每个目标在图像上的像素级位置,那么 *Mask R-CNN* :cite:`He.Gkioxari.Dollar.ea.2017` 能够有效地利用这些详尽的标注信息进一步提升目标检测的精度。 \n\n\n:label:`fig_mask_r-cnn`\n\n如 :numref:`fig_mask_r-cnn` 所示,Mask R-CNN 是基于 Faster R-CNN 修改而来的。\n具体来说,Mask R-CNN 将兴趣区域汇聚层替换为了\n*兴趣区域 (RoI) 对齐* 层,使用 *双线性插值*(bilinear interpolation)来保留特征图上的空间信息,从而更适于像素级预测。\n兴趣区域对齐层的输出包含了所有与兴趣区域的形状相同的特征图。\n它们不仅被用于预测每个兴趣区域的类别和边界框,还通过额外的全卷积网络预测目标的像素级位置。\n本章的后续章节将更详细地介绍如何使用全卷积网络预测图像中像素级的语义。 \n\n## 小结\n\n* R-CNN 对图像选取若干提议区域,使用卷积神经网络对每个提议区域执行前向计算以抽取其特征,然后再用这些特征来预测提议区域的类别和边界框。\n* Fast R-CNN 对 R-CNN 的一个主要改进:只对整个图像做卷积神经网络的前向计算。它还引入了兴趣区域汇聚层,从而为具有不同形状的兴趣区域抽取相同形状的特征。\n* Faster R-CNN 将 Fast R-CNN 中使用的选择性搜索替换为参与训练的区域提议网络,这样后者可以在减少提议区域数量的情况下仍保证目标检测的精度。\n* Mask R-CNN 在 Faster R-CNN 的基础上引入了一个全卷积网络,从而借助目标的像素级位置进一步提升目标检测的精度。\n\n## 练习\n\n1. 我们能否将目标检测视为回归问题(例如预测边界框和类别的概率)?你可以参考 YOLO 模型 :cite:`Redmon.Divvala.Girshick.ea.2016` 的设计。\n1. 将单发多框检测与本节介绍的方法进行比较。他们的主要区别是什么?你可以参考 :cite:`Zhao.Zheng.Xu.ea.2019` 中的图2。\n",
"_____no_output_____"
],
[
"[讨论区](https://discuss.d2l.ai/t/3207)\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
e77b1e91bf33fd036cbff4020bd1d1f50f35ffb5 | 2,100 | ipynb | Jupyter Notebook | docs/source/CLP/exercises/Blending Problem.ipynb | ffraile/operations-research | 3e143ac4ec7031f008505cc2695095ab8dfa2f28 | [
"MIT"
] | null | null | null | docs/source/CLP/exercises/Blending Problem.ipynb | ffraile/operations-research | 3e143ac4ec7031f008505cc2695095ab8dfa2f28 | [
"MIT"
] | null | null | null | docs/source/CLP/exercises/Blending Problem.ipynb | ffraile/operations-research | 3e143ac4ec7031f008505cc2695095ab8dfa2f28 | [
"MIT"
] | null | null | null | 26.582278 | 155 | 0.52 | [
[
[
"# Blending Problem\n## Problem definition",
"_____no_output_____"
],
[
"The Kahuna company manufactures sausages using three kinds of meat. The relevant information about the ingredients is provided in the table below:\n\n\n\n| Ingredient | Cost (€/kg) | Availability (kg) |\n|------------|--------------|-------------------|\n| Pork | 4.32 | 30 |\n| Wheat | 2.46 | 20 |\n| Starch | 1.86 | 17 |\n\nThe company makes two types of sausages:\n* Economy (>=40% Pork)\n* Premium (>=60% Pork)\n\nOne sausage is 50 grams (0.05 kg)\n\nAccording to government regulations, the most starch we can use in our sausages is 25%\n\nWe have a contract with a butcher, and have already purchased 23 kg pork, that will go bad if it's not used.\n\nWe have a demand for 350 economy sausages and 500 premium sausages.\n\n**Write a linear program to figure out the most cost effective recipe to manufacture our sausages.**\n\n\n## References ##\n[Introduction to Operations Research with Python](https://github.com/benalexkeen/Introduction-to-linear-programming)",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown",
"markdown"
]
] |
e77b1f04392afafd7391c151a9e87703848e3ade | 28,634 | ipynb | Jupyter Notebook | minihackathons/WF B.1a.ipynb | ranking-agent/robogallery | 48a5450cbad864d3569a5a8e94ca898338cb5a89 | [
"MIT"
] | null | null | null | minihackathons/WF B.1a.ipynb | ranking-agent/robogallery | 48a5450cbad864d3569a5a8e94ca898338cb5a89 | [
"MIT"
] | 1 | 2021-06-03T15:02:18.000Z | 2021-06-03T15:02:18.000Z | minihackathons/WF B.1a.ipynb | ranking-agent/robogallery | 48a5450cbad864d3569a5a8e94ca898338cb5a89 | [
"MIT"
] | 1 | 2021-05-26T17:17:17.000Z | 2021-05-26T17:17:17.000Z | 135.066038 | 1,775 | 0.663337 | [
[
[
"from use_translator import *",
"_____no_output_____"
],
[
"qname = 'workflowB/B.1a_DILI-three-hop-from-disease-or-phenotypic-feature_trapi.json'",
"_____no_output_____"
],
[
"qfile = '/Users/bizon/Projects/SRI/minihackathons/2021-12_demo/'+qname",
"_____no_output_____"
],
[
"with open(qfile,'r') as inf:\n query = json.load(inf)\nprintjson(query)",
"{\n \"message\": {\n \"query_graph\": {\n \"nodes\": {\n \"n0\": {\n \"ids\": [\n \"MONDO:0005359\"\n ],\n \"categories\": [\n \"biolink:DiseaseOrPhenotypicFeature\"\n ]\n },\n \"n1\": {\n \"categories\": [\n \"biolink:DiseaseOrPhenotypicFeature\"\n ]\n },\n \"n2\": {\n \"categories\": [\n \"biolink:Gene\"\n ]\n },\n \"n3\": {\n \"categories\": [\n \"biolink:ChemicalEntity\"\n ]\n }\n },\n \"edges\": {\n \"e01\": {\n \"subject\": \"n0\",\n \"object\": \"n1\",\n \"predicates\": [\n \"biolink:has_real_world_evidence_of_association_with\"\n ]\n },\n \"e02\": {\n \"subject\": \"n2\",\n \"object\": \"n1\",\n \"predicates\": [\n \"biolink:gene_associated_with_condition\"\n ]\n },\n \"e03\": {\n \"subject\": \"n2\",\n \"object\": \"n3\",\n \"predicates\": [\n \"biolink:related_to\"\n ]\n }\n }\n }\n }\n}\n"
],
[
"sr = strider(query) ",
"_____no_output_____"
],
[
"arp = aragorn(query)",
"_____no_output_____"
],
[
"local_strider(query)",
"_____no_output_____"
],
[
"local_aragorn(query)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e77b1f62cde743d899a4f1542de300eb22bed7fd | 25,553 | ipynb | Jupyter Notebook | notebooks/A3-parse-zoning.ipynb | CityOfLosAngeles/planning-entitlements | cf83b57063b4e55722cc640172b529611b263b3a | [
"Apache-2.0"
] | null | null | null | notebooks/A3-parse-zoning.ipynb | CityOfLosAngeles/planning-entitlements | cf83b57063b4e55722cc640172b529611b263b3a | [
"Apache-2.0"
] | 55 | 2020-01-08T17:50:17.000Z | 2021-01-13T21:45:31.000Z | notebooks/A3-parse-zoning.ipynb | CityOfLosAngeles/planning-entitlements | cf83b57063b4e55722cc640172b529611b263b3a | [
"Apache-2.0"
] | 2 | 2020-07-16T02:10:30.000Z | 2021-01-25T21:14:49.000Z | 31.469212 | 287 | 0.433139 | [
[
[
"# Clean ZIMAS / zoning file\n* Dissolve zoning file so they are multipolygons\n* Use parser in `laplan.zoning` to parse ZONE_CMPLT\n* Manually list the failed to parse observations and fix\n* Use this to build crosswalk of height, density, etc restrictions",
"_____no_output_____"
]
],
[
[
"import boto3\nimport geopandas as gpd\nimport intake\nimport numpy as np\nimport os\nimport pandas as pd\nimport laplan\nimport utils",
"_____no_output_____"
],
[
"catalog = intake.open_catalog(\"../catalogs/*.yml\")\n\ns3 = boto3.client('s3')\nbucket_name = 'city-planning-entitlements'",
"_____no_output_____"
],
[
"# Default value of display.max_rows is 10 i.e. at max 10 rows will be printed.\n# Set it None to display all rows in the dataframe\npd.set_option('display.max_rows', 25)",
"_____no_output_____"
],
[
"# Dissolve zoning to get multipolygons\n# File is large, but we only care about unique ZONE_CMPLT, which need to be parsed\nzones = catalog.zoning.read()\nzones = zones[['ZONE_CMPLT', 'ZONE_SMRY', 'geometry']].assign(\n zone2 = zones.ZONE_CMPLT\n)\n\ndf = zones.dissolve(by='zone2').reset_index(drop=True)\ndf.head()",
"_____no_output_____"
],
[
"print(f'# obs in zoning: {len(zones)}')\nprint(f'# unique types of zoning: {len(df)}')",
"# obs in zoning: 60588\n# unique types of zoning: 1934\n"
]
],
[
[
"## Parse zoning string",
"_____no_output_____"
]
],
[
[
"parsed_col_names = ['Q', 'T', 'zone_class', 'specific_plan', 'height_district', 'D', 'overlay']\n\ndef parse_zoning(row):\n try:\n z = laplan.zoning.ZoningInfo(row.ZONE_CMPLT)\n return pd.Series([z.Q, z.T, z.zone_class, z.specific_plan, z.height_district, z.D, z.overlay], \n index = parsed_col_names)\n except ValueError:\n return pd.Series(['failed', 'failed', 'failed', 'failed', 'failed', 'failed', ''], \n index = parsed_col_names)\n\n \nparsed = df.apply(parse_zoning, axis = 1)\n\ndf = pd.concat([df, parsed], axis = 1)\n\ndf.head()",
"_____no_output_____"
]
],
[
[
"## Fix parse fails",
"_____no_output_____"
]
],
[
[
"fails_crosswalk = pd.read_parquet(f's3://{bucket_name}/data/crosswalk_zone_parse_fails.parquet')\n\nprint(f'# obs in fails_crosswalk: {len(fails_crosswalk)}')",
"# obs in fails_crosswalk: 43\n"
],
[
"# Grab all obs in our df that shows up in the fails_crosswalk, even if it was parsed correctly\n# There were some other ones that were added because they weren't valid zone classes\nfails = df[df.ZONE_CMPLT.isin(fails_crosswalk.ZONE_CMPLT)]\nprint(f'# obs in fails: {len(fails)}')",
"# obs in fails: 43\n"
],
[
"# Convert the overlay column from string to list\nfails_crosswalk.overlay = fails_crosswalk.overlay.str[1:-1].str.split(',').tolist()\n\n# Fill in Nones with empty list\nfails_crosswalk['overlay'] = fails_crosswalk['overlay'].apply(lambda row: row if isinstance(row, list) else [])",
"_____no_output_____"
],
[
"df1 = df[~ df.ZONE_CMPLT.isin(fails_crosswalk.ZONE_CMPLT)]\n\n# Append the successfully parsed obs with the failed ones\ndf2 = df1.append(fails_crosswalk)",
"_____no_output_____"
],
[
"# Make sure cols are the same type again\nfor col in ['zone_class', 'specific_plan', 'height_district']:\n df2[col] = df2[col].astype(str)\n\nfor col in ['Q', 'T', 'D']:\n df2[col] = df2[col].astype(int)",
"_____no_output_____"
],
[
"print(f'# obs in df: {len(df)}')\nprint(f'# obs in df2: {len(df2)}')",
"# obs in df: 1934\n# obs in df2: 1934\n"
]
],
[
[
"## Need to do something about overlays and specific plans...\n* leave as list? -> then split (ZONE_CMPLT, geometry) from the rest, so we can save geojson and tabular separately\n* GeoJSON can't take lists. Convert to strings...later make it a list again?",
"_____no_output_____"
]
],
[
[
"# Fill in Nones, otherwise cannot do the apply to make the list a string\ndf2.overlay = df2.overlay.fillna('')\n\njust_overlay = df2[df2.overlay != ''][['ZONE_CMPLT', 'overlay']]\njust_overlay['no_brackets'] = just_overlay['overlay'].apply(', '.join)",
"_____no_output_____"
],
[
"split = just_overlay.no_brackets.str.split(',', expand = True).fillna('')\nsplit.rename(columns = {0: 'o1', 1: 'o2', 2: 'o3'}, inplace = True)\n\njust_overlay = pd.concat([just_overlay, split], axis = 1)",
"_____no_output_____"
],
[
"supplemental_use = pd.read_parquet(f's3://{bucket_name}/data/crosswalk_supplemental_use_overlay.parquet')\nspecific_plan = pd.read_parquet(f's3://{bucket_name}/data/crosswalk_specific_plan.parquet')",
"_____no_output_____"
],
[
"supplemental_use_dict = supplemental_use.set_index('supplemental_use').to_dict()['supplemental_use_description']\nspecific_plan_dict = specific_plan.set_index('specific_plan').to_dict()['specific_plan_description']",
"_____no_output_____"
],
[
"# Trouble mapping it across all columns\nfor col in ['o1', 'o2', 'o3']:\n just_overlay[col] = just_overlay[col].str.strip()\n new_col = f'{col}_descrip'\n just_overlay[new_col] = just_overlay[col].map(supplemental_use_dict)\n just_overlay[new_col] = just_overlay[new_col].fillna('')",
"_____no_output_____"
],
[
"# Put df back together\ndf3 = pd.merge(df2, just_overlay, on = 'ZONE_CMPLT', how = 'left', validate = '1:1')\ndf3.head()",
"_____no_output_____"
],
[
"# Invalid overlays\n# What is SP? Specific Plan?\n# Also, can't find H",
"_____no_output_____"
]
],
[
[
"## Merge and export",
"_____no_output_____"
]
],
[
[
"col_order = ['ZONE_CMPLT', 'ZONE_SMRY', \n 'Q', 'T', 'zone_class', 'height_district', 'D',\n 'specific_plan', 'no_brackets', 'geometry']\n\n# Geometry is messed up, so let's get it back from original dissolve\nfinal = (pd.merge(df[['ZONE_CMPLT', 'geometry']], df3.drop(columns = \"geometry\"), \n on = \"ZONE_CMPLT\", how = \"left\", validate = \"1:1\")\n [col_order]\n .rename(columns = {'no_brackets': 'overlay'})\n .sort_values(['ZONE_CMPLT', 'ZONE_SMRY'])\n .reset_index(drop=True) \n )\n\nfinal.head()\n\n# Fix CRS. It's EPSG:2229, not EPSG:4326\nfinal.crs = \"EPSG:2229\"",
"_____no_output_____"
],
[
"file_name = 'gis/raw/parsed_zoning'\nutils.make_zipped_shapefile(final, f'../{file_name}')\n\ns3.upload_file(f'../{file_name}.zip', bucket_name, f'{file_name}.zip')",
"Path name: ../gis/raw/parsed_zoning\nDirname (1st element of path): ../gis/raw/parsed_zoning\nShapefile name: parsed_zoning.shp\nShapefile component parts folder: ../gis/raw/parsed_zoning/parsed_zoning.shp\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e77b27de55b55c6e945f3347ac5f04314cbeda1f | 7,479 | ipynb | Jupyter Notebook | cv_explorer.ipynb | afry-south/mix-match-cv | 4718d087be7d197d1b725e24d1a2f42b7d316ea0 | [
"MIT"
] | null | null | null | cv_explorer.ipynb | afry-south/mix-match-cv | 4718d087be7d197d1b725e24d1a2f42b7d316ea0 | [
"MIT"
] | 4 | 2021-06-03T08:17:00.000Z | 2021-06-03T10:40:52.000Z | cv_explorer.ipynb | afry-south/mix-match-cv | 4718d087be7d197d1b725e24d1a2f42b7d316ea0 | [
"MIT"
] | 1 | 2021-06-03T07:54:34.000Z | 2021-06-03T07:54:34.000Z | 24.601974 | 535 | 0.573339 | [
[
[
"import pandas as pd\nimport flair\nfrom bpemb import BPEmb\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom scipy.spatial.distance import cdist\nfrom sklearn.decomposition import TruncatedSVD\n#import spacy",
"/home/londogard/miniconda3/envs/flair/lib/python3.9/site-packages/torch/cuda/__init__.py:52: UserWarning: CUDA initialization: Unexpected error from cudaGetDeviceCount(). Did you run some cuda functions before calling NumCudaDevices() that might have already set an error? Error 804: forward compatibility was attempted on non supported HW (Triggered internally at /opt/conda/conda-bld/pytorch_1607370151529/work/c10/cuda/CUDAFunctions.cpp:100.)\n return torch._C._cuda_getDeviceCount() > 0\n"
],
[
"full_files_assignment = [f\"data/assignment/{x}/assignment.txt\" for x in os.listdir('data/assignment')]\nfull_files_data_assignment = [open(x).read() for x in full_files_assignment if not 'annot' in x and not '.DS' in x]",
"_____no_output_____"
],
[
"full_files = [f\"data/resumes/{x}\" for x in os.listdir('data/resumes')]\nfull_files_data = [open(x).read() for x in full_files]\n\nfull_files_data[0][:500]",
"_____no_output_____"
],
[
"vectorizer = TfidfVectorizer(stop_words='english', max_df=0.50, min_df=10)\nX = vectorizer.fit_transform(full_files_data+full_files_data_assignment)",
"_____no_output_____"
],
[
"X_assignment = X[1037:]\nX_resume= X[:1037]",
"_____no_output_____"
],
[
"dists = cdist(X_assignment[0].toarray(), X_resume.toarray(), metric='cosine')[0]\nidx = dists.argpartition(5)[:5]",
"_____no_output_____"
],
[
"idx",
"_____no_output_____"
],
[
"full_files_data[564][:500]",
"_____no_output_____"
],
[
"svd = TruncatedSVD(n_components=100)",
"_____no_output_____"
],
[
"X2=svd.fit_transform(X)",
"_____no_output_____"
],
[
"X_assignment = X2[1037:]\nX_resume= X2[:1037]",
"_____no_output_____"
],
[
"X_assignment.shape",
"_____no_output_____"
],
[
"dists = cdist(X_assignment[:1], X_resume, metric='cosine')[0]\nidx = dists.argpartition(5)[:5]",
"_____no_output_____"
],
[
"idx",
"_____no_output_____"
],
[
"dists[idx]",
"_____no_output_____"
],
[
"full_files[485]",
"_____no_output_____"
],
[
"#full_files_data_assignment[0]",
"_____no_output_____"
],
[
"dists[1:10]",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e77b342a8b9a003804119a8f1f1d456dd995f6f7 | 44,903 | ipynb | Jupyter Notebook | docs/notebooks/flax_basics.ipynb | harry-stark/flax | 9d4505b7df0f8dd756e55bd89a97b793bb2cf914 | [
"Apache-2.0"
] | null | null | null | docs/notebooks/flax_basics.ipynb | harry-stark/flax | 9d4505b7df0f8dd756e55bd89a97b793bb2cf914 | [
"Apache-2.0"
] | null | null | null | docs/notebooks/flax_basics.ipynb | harry-stark/flax | 9d4505b7df0f8dd756e55bd89a97b793bb2cf914 | [
"Apache-2.0"
] | null | null | null | 40.199642 | 881 | 0.512727 | [
[
[
"# Flax Basics\n\nThis notebook will walk you through the following workflow:\n\n* Instantiating a model from Flax built-in layers or third-party models.\n* Initializing parameters of the model and manually written training.\n* Using optimizers provided by Flax to ease training.\n* Serialization of parameters and other objects.\n* Creating your own models and managing state.",
"_____no_output_____"
],
[
"## Setting up our environment\n\nHere we provide the code needed to set up the environment for our notebook.",
"_____no_output_____"
]
],
[
[
"# Install the latest JAXlib version.\n!pip install --upgrade -q pip jax jaxlib\n# Install Flax at head:\n!pip install --upgrade -q git+https://github.com/google/flax.git",
"\u001b[33mWARNING: Running pip as root will break packages and permissions. You should install packages reliably by using venv: https://pip.pypa.io/warnings/venv\u001b[0m\n\u001b[33mWARNING: Running pip as root will break packages and permissions. You should install packages reliably by using venv: https://pip.pypa.io/warnings/venv\u001b[0m\n"
],
[
"import jax\nfrom typing import Any, Callable, Sequence, Optional\nfrom jax import lax, random, numpy as jnp\nimport flax\nfrom flax.core import freeze, unfreeze\nfrom flax import linen as nn",
"_____no_output_____"
]
],
[
[
"## Linear regression with Flax\n\nIn the previous *JAX for the impatient* notebook, we finished up with a linear regression example. As we know, linear regression can also be written as a single dense neural network layer, which we will show in the following so that we can compare how it's done.\n\nA dense layer is a layer that has a kernel parameter $W\\in\\mathcal{M}_{m,n}(\\mathbb{R})$ where $m$ is the number of features as an output of the model, and $n$ the dimensionality of the input, and a bias parameter $b\\in\\mathbb{R}^m$. The dense layers returns $Wx+b$ from an input $x\\in\\mathbb{R}^n$.\n\nThis dense layer is already provided by Flax in the `flax.linen` module (here imported as `nn`).",
"_____no_output_____"
]
],
[
[
"# We create one dense layer instance (taking 'features' parameter as input)\nmodel = nn.Dense(features=5)",
"_____no_output_____"
]
],
[
[
"Layers (and models in general, we'll use that word from now on) are subclasses of the `linen.Module` class.\n\n### Model parameters & initialization\n\nParameters are not stored with the models themselves. You need to initialize parameters by calling the `init` function, using a PRNGKey and a dummy input parameter.",
"_____no_output_____"
]
],
[
[
"key1, key2 = random.split(random.PRNGKey(0))\nx = random.normal(key1, (10,)) # Dummy input\nparams = model.init(key2, x) # Initialization call\njax.tree_map(lambda x: x.shape, params) # Checking output shapes",
"WARNING:absl:No GPU/TPU found, falling back to CPU. (Set TF_CPP_MIN_LOG_LEVEL=0 and rerun for more info.)\n"
]
],
[
[
"*Note: JAX and Flax, like NumPy, are row-based systems, meaning that vectors are represented as row vectors and not column vectors. This can be seen in the shape of the kernel here.*\n\nThe result is what we expect: bias and kernel parameters of the correct size. Under the hood:\n\n* The dummy input variable `x` is used to trigger shape inference: we only declared the number of features we wanted in the output of the model, not the size of the input. Flax finds out by itself the correct size of the kernel.\n* The random PRNG key is used to trigger the initialization functions (those have default values provided by the module here).\n* Initialization functions are called to generate the initial set of parameters that the model will use. Those are functions that take as arguments `(PRNG Key, shape, dtype)` and return an Array of shape `shape`.\n* The init function returns the initialized set of parameters (you can also get the output of the evaluation on the dummy input with the same syntax but using the `init_with_output` method instead of `init`.",
"_____no_output_____"
],
[
"We see in the output that parameters are stored in a `FrozenDict` instance which helps deal with the functional nature of JAX by preventing any mutation of the underlying dict and making the user aware of it. Read more about it in the Flax docs. As a consequence, the following doesn't work:\n",
"_____no_output_____"
]
],
[
[
"try:\n params['new_key'] = jnp.ones((2,2))\nexcept ValueError as e:\n print(\"Error: \", e)",
"Error: FrozenDict is immutable.\n"
]
],
[
[
"To evaluate the model with a given set of parameters (never stored with the model), we just use the `apply` method by providing it the parameters to use as well as the input:",
"_____no_output_____"
]
],
[
[
"model.apply(params, x)",
"_____no_output_____"
]
],
[
[
"### Gradient descent\n\nIf you jumped here directly without going through the JAX part, here is the linear regression formulation we're going to use: from a set of data points $\\{(x_i,y_i), i\\in \\{1,\\ldots, k\\}, x_i\\in\\mathbb{R}^n,y_i\\in\\mathbb{R}^m\\}$, we try to find a set of parameters $W\\in \\mathcal{M}_{m,n}(\\mathbb{R}), b\\in\\mathbb{R}^m$ such that the function $f_{W,b}(x)=Wx+b$ minimizes the mean squared error:\n$$\\mathcal{L}(W,b)\\rightarrow\\frac{1}{k}\\sum_{i=1}^{k} \\frac{1}{2}\\|y_i-f_{W,b}(x_i)\\|^2_2$$\n\nHere, we see that the tuple $(W,b)$ matches the parameters of the Dense layer. We'll perform gradient descent using those. Let's first generate the fake data we'll use. The data is exactly the same as in the JAX part's linear regression pytree example.",
"_____no_output_____"
]
],
[
[
"# Set problem dimensions.\nn_samples = 20\nx_dim = 10\ny_dim = 5\n\n# Generate random ground truth W and b.\nkey = random.PRNGKey(0)\nk1, k2 = random.split(key)\nW = random.normal(k1, (x_dim, y_dim))\nb = random.normal(k2, (y_dim,))\n# Store the parameters in a pytree.\ntrue_params = freeze({'params': {'bias': b, 'kernel': W}})\n\n# Generate samples with additional noise.\nkey_sample, key_noise = random.split(k1)\nx_samples = random.normal(key_sample, (n_samples, x_dim))\ny_samples = jnp.dot(x_samples, W) + b + 0.1 * random.normal(key_noise,(n_samples, y_dim))\nprint('x shape:', x_samples.shape, '; y shape:', y_samples.shape)",
"x shape: (20, 10) ; y shape: (20, 5)\n"
]
],
[
[
"We copy the same training loop that we used in the JAX pytree linear regression example with `jax.value_and_grad()`, but here we can use `model.apply()` instead of having to define our own feed-forward function (`predict_pytree()` in the JAX example).",
"_____no_output_____"
]
],
[
[
"# Same as JAX version but using model.apply().\ndef mse(params, x_batched, y_batched):\n # Define the squared loss for a single pair (x,y)\n def squared_error(x, y):\n pred = model.apply(params, x)\n return jnp.inner(y-pred, y-pred) / 2.0\n # Vectorize the previous to compute the average of the loss on all samples.\n return jnp.mean(jax.vmap(squared_error)(x_batched,y_batched), axis=0)",
"_____no_output_____"
]
],
[
[
"And finally perform the gradient descent.",
"_____no_output_____"
]
],
[
[
"learning_rate = 0.3 # Gradient step size.\nprint('Loss for \"true\" W,b: ', mse(true_params, x_samples, y_samples))\nloss_grad_fn = jax.value_and_grad(mse)\n\[email protected]\ndef update_params(params, learning_rate, grads):\n params = jax.tree_map(\n lambda p, g: p - learning_rate * g, params, grads)\n return params\n\nfor i in range(101):\n # Perform one gradient update.\n loss_val, grads = loss_grad_fn(params, x_samples, y_samples)\n params = update_params(params, learning_rate, grads)\n if i % 10 == 0:\n print(f'Loss step {i}: ', loss_val)",
"Loss for \"true\" W,b: 0.023639778\nLoss step 0: 38.094772\nLoss step 10: 0.44692168\nLoss step 20: 0.10053458\nLoss step 30: 0.035822745\nLoss step 40: 0.018846875\nLoss step 50: 0.013864839\nLoss step 60: 0.012312559\nLoss step 70: 0.011812928\nLoss step 80: 0.011649306\nLoss step 90: 0.011595251\nLoss step 100: 0.0115773035\n"
]
],
[
[
"### Optimizing with Optax\n\nFlax used to use its own `flax.optim` package for optimization, but with\n[FLIP #1009](https://github.com/google/flax/blob/main/docs/flip/1009-optimizer-api.md)\nthis was deprecated in favor of\n[Optax](https://github.com/deepmind/optax).\n\nBasic usage of Optax is straightforward:\n\n1. Choose an optimization method (e.g. `optax.sgd`).\n2. Create optimizer state from parameters.\n3. Compute the gradients of your loss with `jax.value_and_grad()`.\n4. At every iteration, call the Optax `update` function to update the internal\n optimizer state and create an update to the parameters. Then add the update\n to the parameters with Optax's `apply_updates` method.\n\nNote that Optax can do a lot more: it's designed for composing simple gradient\ntransformations into more complex transformations that allows to implement a\nwide range of optimizers. There is also support for changing optimizer\nhyperparameters over time (\"schedules\"), applying different updates to different\nparts of the parameter tree (\"masking\") and much more. For details please refer\nto the\n[official documentation](https://optax.readthedocs.io/en/latest/).",
"_____no_output_____"
]
],
[
[
"import optax\ntx = optax.sgd(learning_rate=learning_rate)\nopt_state = tx.init(params)\nloss_grad_fn = jax.value_and_grad(mse)",
"_____no_output_____"
],
[
"for i in range(101):\n loss_val, grads = loss_grad_fn(params, x_samples, y_samples)\n updates, opt_state = tx.update(grads, opt_state)\n params = optax.apply_updates(params, updates)\n if i % 10 == 0:\n print('Loss step {}: '.format(i), loss_val)",
"Loss step 0: 0.011576377\nLoss step 10: 0.0115710115\nLoss step 20: 0.011569244\nLoss step 30: 0.011568661\nLoss step 40: 0.011568454\nLoss step 50: 0.011568379\nLoss step 60: 0.011568358\nLoss step 70: 0.01156836\nLoss step 80: 0.01156835\nLoss step 90: 0.011568353\nLoss step 100: 0.011568348\n"
]
],
[
[
"### Serializing the result\n\nNow that we're happy with the result of our training, we might want to save the model parameters to load them back later. Flax provides a serialization package to enable you to do that.",
"_____no_output_____"
]
],
[
[
"from flax import serialization\nbytes_output = serialization.to_bytes(params)\ndict_output = serialization.to_state_dict(params)\nprint('Dict output')\nprint(dict_output)\nprint('Bytes output')\nprint(bytes_output)",
"Dict output\n{'params': {'bias': DeviceArray([-1.4540135, -2.0262308, 2.0806582, 1.2201802, -0.9964547], dtype=float32), 'kernel': DeviceArray([[ 1.0106664 , 0.19014716, 0.04533899, -0.92722285,\n 0.34720102],\n [ 1.7320251 , 0.9901233 , 1.1662225 , 1.1027892 ,\n -0.10574618],\n [-1.2009128 , 0.28837162, 1.4176372 , 0.12073109,\n -1.3132601 ],\n [-1.1944956 , -0.18993308, 0.03379077, 1.3165942 ,\n 0.07996067],\n [ 0.14103189, 1.3737966 , -1.3162128 , 0.53401774,\n -2.239638 ],\n [ 0.5643044 , 0.813604 , 0.31888172, 0.5359193 ,\n 0.90352124],\n [-0.37948322, 1.7408353 , 1.0788013 , -0.5041964 ,\n 0.9286919 ],\n [ 0.9701384 , -1.3158673 , 0.33630812, 0.80941117,\n -1.202457 ],\n [ 1.0198247 , -0.6198277 , 1.0822718 , -1.8385581 ,\n -0.45790705],\n [-0.64384323, 0.4564892 , -1.1331053 , -0.68556863,\n 0.17010891]], dtype=float32)}}\nBytes output\nb'\\x81\\xa6params\\x82\\xa4bias\\xc7!\\x01\\x93\\x91\\x05\\xa7float32\\xc4\\x14\\x1d\\x1d\\xba\\xbf\\xc4\\xad\\x01\\xc0\\x81)\\x05@\\xdd.\\x9c?\\xa8\\x17\\x7f\\xbf\\xa6kernel\\xc7\\xd6\\x01\\x93\\x92\\n\\x05\\xa7float32\\xc4\\xc8\\x84]\\x81?\\xf0\\xb5B>`\\xb59=z^m\\xbfU\\xc4\\xb1>\\x00\\xb3\\xdd?\\xb8x}?\\xc7F\\x95?2(\\x8d?t\\x91\\xd8\\xbd\\x83\\xb7\\x99\\xbfr\\xa5\\x93>#u\\xb5?\\xdcA\\xf7=\\xe8\\x18\\xa8\\xbf;\\xe5\\x98\\xbf\\xd1}B\\xbe0h\\n=)\\x86\\xa8?k\\xc2\\xa3=\\xaaj\\x10>\\x91\\xd8\\xaf?\\xa9y\\xa8\\xbfc\\xb5\\x08?;V\\x0f\\xc0Av\\x10?ZHP?wD\\xa3>\\x022\\t?+Mg?\\xa0K\\xc2\\xbe\\xb1\\xd3\\xde?)\\x16\\x8a?\\x04\\x13\\x01\\xbf\\xc1\\xbem?\\xfdZx?Wn\\xa8\\xbf\\x940\\xac>\\x925O?\\x1c\\xea\\x99\\xbf\\x9e\\x89\\x82?\\x07\\xad\\x1e\\xbf\\xe2\\x87\\x8a?\\xdfU\\xeb\\xbf\\xcbr\\xea\\xbe\\xe9\\xd2$\\xbf\\xf4\\xb8\\xe9>\\x98\\t\\x91\\xbfm\\x81/\\xbf\\x081.>'\n"
]
],
[
[
"To load the model back, you'll need to use as a template the model parameter structure, like the one you would get from the model initialization. Here, we use the previously generated `params` as a template. Note that this will produce a new variable structure, and not mutate in-place.\n\n*The point of enforcing structure through template is to avoid users issues downstream, so you need to first have the right model that generates the parameters structure.*",
"_____no_output_____"
]
],
[
[
"serialization.from_bytes(params, bytes_output)",
"_____no_output_____"
]
],
[
[
"## Defining your own models\n\nFlax allows you to define your own models, which should be a bit more complicated than a linear regression. In this section, we'll show you how to build simple models. To do so, you'll need to create subclasses of the base `nn.Module` class.\n\n*Keep in mind that we imported* `linen as nn` *and this only works with the new linen API*",
"_____no_output_____"
],
[
"### Module basics\n\nThe base abstraction for models is the `nn.Module` class, and every type of predefined layers in Flax (like the previous `Dense`) is a subclass of `nn.Module`. Let's take a look and start by defining a simple but custom multi-layer perceptron i.e. a sequence of Dense layers interleaved with calls to a non-linear activation function.",
"_____no_output_____"
]
],
[
[
"class ExplicitMLP(nn.Module):\n features: Sequence[int]\n\n def setup(self):\n # we automatically know what to do with lists, dicts of submodules\n self.layers = [nn.Dense(feat) for feat in self.features]\n # for single submodules, we would just write:\n # self.layer1 = nn.Dense(feat1)\n\n def __call__(self, inputs):\n x = inputs\n for i, lyr in enumerate(self.layers):\n x = lyr(x)\n if i != len(self.layers) - 1:\n x = nn.relu(x)\n return x\n\nkey1, key2 = random.split(random.PRNGKey(0), 2)\nx = random.uniform(key1, (4,4))\n\nmodel = ExplicitMLP(features=[3,4,5])\nparams = model.init(key2, x)\ny = model.apply(params, x)\n\nprint('initialized parameter shapes:\\n', jax.tree_map(jnp.shape, unfreeze(params)))\nprint('output:\\n', y)",
"initialized parameter shapes:\n {'params': {'layers_0': {'bias': (3,), 'kernel': (4, 3)}, 'layers_1': {'bias': (4,), 'kernel': (3, 4)}, 'layers_2': {'bias': (5,), 'kernel': (4, 5)}}}\noutput:\n [[ 4.2292815e-02 -4.3807115e-02 2.9323792e-02 6.5492536e-03\n -1.7147182e-02]\n [ 1.2967806e-01 -1.4551792e-01 9.4432183e-02 1.2521387e-02\n -4.5417298e-02]\n [ 0.0000000e+00 0.0000000e+00 0.0000000e+00 0.0000000e+00\n 0.0000000e+00]\n [ 9.3024032e-04 2.7864395e-05 2.4478821e-04 8.1344310e-04\n -1.0110770e-03]]\n"
]
],
[
[
"As we can see, a `nn.Module` subclass is made of:\n\n* A collection of data fields (`nn.Module` are Python dataclasses) - here we only have the `features` field of type `Sequence[int]`.\n* A `setup()` method that is being called at the end of the `__postinit__` where you can register submodules, variables, parameters you will need in your model.\n* A `__call__` function that returns the output of the model from a given input.\n* The model structure defines a pytree of parameters following the same tree structure as the model: the params tree contains one `layers_n` sub dict per layer, and each of those contain the parameters of the associated Dense layer. The layout is very explicit.\n\n*Note: lists are mostly managed as you would expect (WIP), there are corner cases you should be aware of as pointed out* [here](https://github.com/google/flax/issues/524)\n\nSince the module structure and its parameters are not tied to each other, you can't directly call `model(x)` on a given input as it will return an error. The `__call__` function is being wrapped up in the `apply` one, which is the one to call on an input:",
"_____no_output_____"
]
],
[
[
"try:\n y = model(x) # Returns an error\nexcept AttributeError as e:\n print(e)",
"\"ExplicitMLP\" object has no attribute \"layers\"\n"
]
],
[
[
"Since here we have a very simple model, we could have used an alternative (but equivalent) way of declaring the submodules inline in the `__call__` using the `@nn.compact` annotation like so:",
"_____no_output_____"
]
],
[
[
"class SimpleMLP(nn.Module):\n features: Sequence[int]\n\n @nn.compact\n def __call__(self, inputs):\n x = inputs\n for i, feat in enumerate(self.features):\n x = nn.Dense(feat, name=f'layers_{i}')(x)\n if i != len(self.features) - 1:\n x = nn.relu(x)\n # providing a name is optional though!\n # the default autonames would be \"Dense_0\", \"Dense_1\", ...\n return x\n\nkey1, key2 = random.split(random.PRNGKey(0), 2)\nx = random.uniform(key1, (4,4))\n\nmodel = SimpleMLP(features=[3,4,5])\nparams = model.init(key2, x)\ny = model.apply(params, x)\n\nprint('initialized parameter shapes:\\n', jax.tree_map(jnp.shape, unfreeze(params)))\nprint('output:\\n', y)",
"initialized parameter shapes:\n {'params': {'layers_0': {'bias': (3,), 'kernel': (4, 3)}, 'layers_1': {'bias': (4,), 'kernel': (3, 4)}, 'layers_2': {'bias': (5,), 'kernel': (4, 5)}}}\noutput:\n [[ 4.2292815e-02 -4.3807115e-02 2.9323792e-02 6.5492536e-03\n -1.7147182e-02]\n [ 1.2967806e-01 -1.4551792e-01 9.4432183e-02 1.2521387e-02\n -4.5417298e-02]\n [ 0.0000000e+00 0.0000000e+00 0.0000000e+00 0.0000000e+00\n 0.0000000e+00]\n [ 9.3024032e-04 2.7864395e-05 2.4478821e-04 8.1344310e-04\n -1.0110770e-03]]\n"
]
],
[
[
"There are, however, a few differences you should be aware of between the two declaration modes:\n\n* In `setup`, you are able to name some sublayers and keep them around for further use (e.g. encoder/decoder methods in autoencoders).\n* If you want to have multiple methods, then you **need** to declare the module using `setup`, as the `@nn.compact` annotation only allows one method to be annotated.\n* The last initialization will be handled differently. See these notes for more details (TODO: add notes link).\n",
"_____no_output_____"
],
[
"### Module parameters\n\nIn the previous MLP example, we relied only on predefined layers and operators (`Dense`, `relu`). Let's imagine that you didn't have a Dense layer provided by Flax and you wanted to write it on your own. Here is what it would look like using the `@nn.compact` way to declare a new modules:",
"_____no_output_____"
]
],
[
[
"class SimpleDense(nn.Module):\n features: int\n kernel_init: Callable = nn.initializers.lecun_normal()\n bias_init: Callable = nn.initializers.zeros\n\n @nn.compact\n def __call__(self, inputs):\n kernel = self.param('kernel',\n self.kernel_init, # Initialization function\n (inputs.shape[-1], self.features)) # shape info.\n y = lax.dot_general(inputs, kernel,\n (((inputs.ndim - 1,), (0,)), ((), ())),) # TODO Why not jnp.dot?\n bias = self.param('bias', self.bias_init, (self.features,))\n y = y + bias\n return y\n\nkey1, key2 = random.split(random.PRNGKey(0), 2)\nx = random.uniform(key1, (4,4))\n\nmodel = SimpleDense(features=3)\nparams = model.init(key2, x)\ny = model.apply(params, x)\n\nprint('initialized parameters:\\n', params)\nprint('output:\\n', y)",
"initialized parameters:\n FrozenDict({\n params: {\n kernel: DeviceArray([[ 0.6503669 , 0.86789787, 0.4604268 ],\n [ 0.05673932, 0.9909285 , -0.63536596],\n [ 0.76134115, -0.3250529 , -0.65221626],\n [-0.82430327, 0.4150194 , 0.19405058]], dtype=float32),\n bias: DeviceArray([0., 0., 0.], dtype=float32),\n },\n})\noutput:\n [[ 0.5035518 1.8548558 -0.4270195 ]\n [ 0.0279097 0.5589246 -0.43061772]\n [ 0.3547128 1.5740999 -0.32865518]\n [ 0.5264864 1.2928858 0.10089308]]\n"
]
],
[
[
"Here, we see how to both declare and assign a parameter to the model using the `self.param` method. It takes as input `(name, init_fn, *init_args)` : \n\n* `name` is simply the name of the parameter that will end up in the parameter structure.\n* `init_fn` is a function with input `(PRNGKey, *init_args)` returning an Array, with `init_args` being the arguments needed to call the initialisation function.\n* `init_args` are the arguments to provide to the initialization function.\n\nSuch params can also be declared in the `setup` method; it won't be able to use shape inference because Flax is using lazy initialization at the first call site.",
"_____no_output_____"
],
[
"### Variables and collections of variables\n\nAs we've seen so far, working with models means working with:\n\n* A subclass of `nn.Module`;\n* A pytree of parameters for the model (typically from `model.init()`);\n\nHowever this is not enough to cover everything that we would need for machine learning, especially neural networks. In some cases, you might want your neural network to keep track of some internal state while it runs (e.g. batch normalization layers). There is a way to declare variables beyond the parameters of the model with the `variable` method.\n\nFor demonstration purposes, we'll implement a simplified but similar mechanism to batch normalization: we'll store running averages and subtract those to the input at training time. For proper batchnorm, you should use (and look at) the implementation [here](https://github.com/google/flax/blob/main/flax/linen/normalization.py).",
"_____no_output_____"
]
],
[
[
"class BiasAdderWithRunningMean(nn.Module):\n decay: float = 0.99\n\n @nn.compact\n def __call__(self, x):\n # easy pattern to detect if we're initializing via empty variable tree\n is_initialized = self.has_variable('batch_stats', 'mean')\n ra_mean = self.variable('batch_stats', 'mean',\n lambda s: jnp.zeros(s),\n x.shape[1:])\n mean = ra_mean.value # This will either get the value or trigger init\n bias = self.param('bias', lambda rng, shape: jnp.zeros(shape), x.shape[1:])\n if is_initialized:\n ra_mean.value = self.decay * ra_mean.value + (1.0 - self.decay) * jnp.mean(x, axis=0, keepdims=True)\n\n return x - ra_mean.value + bias\n\n\nkey1, key2 = random.split(random.PRNGKey(0), 2)\nx = jnp.ones((10,5))\nmodel = BiasAdderWithRunningMean()\nvariables = model.init(key1, x)\nprint('initialized variables:\\n', variables)\ny, updated_state = model.apply(variables, x, mutable=['batch_stats'])\nprint('updated state:\\n', updated_state)",
"initialized variables:\n FrozenDict({\n batch_stats: {\n mean: DeviceArray([0., 0., 0., 0., 0.], dtype=float32),\n },\n params: {\n bias: DeviceArray([0., 0., 0., 0., 0.], dtype=float32),\n },\n})\nupdated state:\n FrozenDict({\n batch_stats: {\n mean: DeviceArray([[0.01, 0.01, 0.01, 0.01, 0.01]], dtype=float32),\n },\n})\n"
]
],
[
[
"Here, `updated_state` returns only the state variables that are being mutated by the model while applying it on data. To update the variables and get the new parameters of the model, we can use the following pattern:",
"_____no_output_____"
]
],
[
[
"for val in [1.0, 2.0, 3.0]:\n x = val * jnp.ones((10,5))\n y, updated_state = model.apply(variables, x, mutable=['batch_stats'])\n old_state, params = variables.pop('params')\n variables = freeze({'params': params, **updated_state})\n print('updated state:\\n', updated_state) # Shows only the mutable part",
"updated state:\n FrozenDict({\n batch_stats: {\n mean: DeviceArray([[0.01, 0.01, 0.01, 0.01, 0.01]], dtype=float32),\n },\n})\nupdated state:\n FrozenDict({\n batch_stats: {\n mean: DeviceArray([[0.0299, 0.0299, 0.0299, 0.0299, 0.0299]], dtype=float32),\n },\n})\nupdated state:\n FrozenDict({\n batch_stats: {\n mean: DeviceArray([[0.059601, 0.059601, 0.059601, 0.059601, 0.059601]], dtype=float32),\n },\n})\n"
]
],
[
[
"From this simplified example, you should be able to derive a full BatchNorm implementation, or any layer involving a state. To finish, let's add an optimizer to see how to play with both parameters updated by an optimizer and state variables.\n\n*This example isn't doing anything and is only for demonstration purposes.*",
"_____no_output_____"
]
],
[
[
"def update_step(tx, apply_fn, x, opt_state, params, state):\n\n def loss(params):\n y, updated_state = apply_fn({'params': params, **state},\n x, mutable=list(state.keys()))\n l = ((x - y) ** 2).sum()\n return l, updated_state\n\n (l, state), grads = jax.value_and_grad(loss, has_aux=True)(params)\n updates, opt_state = tx.update(grads, opt_state)\n params = optax.apply_updates(params, updates)\n return opt_state, params, state\n\nx = jnp.ones((10,5))\nvariables = model.init(random.PRNGKey(0), x)\nstate, params = variables.pop('params')\ndel variables\ntx = optax.sgd(learning_rate=0.02)\nopt_state = tx.init(params)\n\nfor _ in range(3):\n opt_state, params, state = update_step(tx, model.apply, x, opt_state, params, state)\n print('Updated state: ', state)",
"Updated state: FrozenDict({\n batch_stats: {\n mean: DeviceArray([[0.01, 0.01, 0.01, 0.01, 0.01]], dtype=float32),\n },\n})\nUpdated state: FrozenDict({\n batch_stats: {\n mean: DeviceArray([[0.0199, 0.0199, 0.0199, 0.0199, 0.0199]], dtype=float32),\n },\n})\nUpdated state: FrozenDict({\n batch_stats: {\n mean: DeviceArray([[0.029701, 0.029701, 0.029701, 0.029701, 0.029701]], dtype=float32),\n },\n})\n"
]
],
[
[
"Note that the above function has a quite verbose signature and it would not actually\nwork with `jax.jit()` because the function arguments are not \"valid JAX types\".\n\nWe provide a handy wrapper that simplifies the above code, see:\n\nhttps://flax.readthedocs.io/en/latest/flax.training.html#train-state",
"_____no_output_____"
],
[
"### Exporting to Tensorflow's SavedModel with jax2tf\n\nJAX released an experimental converter called [jax2tf](https://github.com/google/jax/tree/main/jax/experimental/jax2tf), which allows converting trained Flax models into Tensorflow's SavedModel format (so it can be used for [TF Hub](https://www.tensorflow.org/hub), [TF.lite](https://www.tensorflow.org/lite), [TF.js](https://www.tensorflow.org/js), or other downstream applications). The repository contains more documentation and has various examples for Flax.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
e77b39e70186cfceec8d1fd55c78c675d90db389 | 3,522 | ipynb | Jupyter Notebook | Untitled.ipynb | bruce99kang/st-gcn | 2a98d84ef1ad0e5b03050fa85d17ada69c3aad96 | [
"BSD-2-Clause"
] | null | null | null | Untitled.ipynb | bruce99kang/st-gcn | 2a98d84ef1ad0e5b03050fa85d17ada69c3aad96 | [
"BSD-2-Clause"
] | null | null | null | Untitled.ipynb | bruce99kang/st-gcn | 2a98d84ef1ad0e5b03050fa85d17ada69c3aad96 | [
"BSD-2-Clause"
] | null | null | null | 25.708029 | 351 | 0.505963 | [
[
[
"import os\nimport argparse\nimport json\nimport shutil\n\nimport numpy as np\nimport torch\nimport skvideo.io\n\nfrom processor.io import IO\nimport tools\nimport tools.utils as utils\nimport tools.utils.visualization as visualization\nimport time",
"_____no_output_____"
],
[
"tt = time.time()\np = IO()",
"Init Start\nself.get_parser finish\n"
],
[
"p.model.eval()",
"_____no_output_____"
],
[
"%pwd",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code"
]
] |
e77b48130b57f8d919dcf07a16cd78ca0cd03987 | 515,835 | ipynb | Jupyter Notebook | demo_notebook.ipynb | mi-dai/sirahtargets-public | f9e7fcd39bd1d887fe2a48cc118b84608a9be0f1 | [
"MIT"
] | 1 | 2020-04-24T16:11:06.000Z | 2020-04-24T16:11:06.000Z | demo_notebook.ipynb | mi-dai/sirahtargets-public | f9e7fcd39bd1d887fe2a48cc118b84608a9be0f1 | [
"MIT"
] | null | null | null | demo_notebook.ipynb | mi-dai/sirahtargets-public | f9e7fcd39bd1d887fe2a48cc118b84608a9be0f1 | [
"MIT"
] | 2 | 2020-04-24T16:11:10.000Z | 2021-01-13T18:21:54.000Z | 455.282436 | 87,684 | 0.931054 | [
[
[
"# <b> SIRAH Candidate Pipeline Demo Notebook</b>\n<b>This notebook demostrates how to set up and run the SIRAH candidate pipeline and desribes its basic features</b> <br>\nby Mi Dai<br>\nApril 13, 2020<br>",
"_____no_output_____"
],
[
"## **0. prerequisites**",
"_____no_output_____"
],
[
"### **0.0 Before you start, follow the instructions under README [here](https://github.com/mi-dai/sirahtargets#pipeline-to-select-sirah-target) to set up conda enviroment and install other required packages**",
"_____no_output_____"
],
[
"### **0.1 Credentials**\nThe following credentials need to be obtained and set up in order to use all functions of the pipeline\n- **[alerce]**\n- **[lasair]** \n- **[TNS api key]**\n- **[SDSS CasJobs]** \n<br>\n\nIn the directory of this notebook\n`cp -r credentials_template/ credentials/` <br>\nThen fill in the credential info for each file.",
"_____no_output_____"
],
[
"### **0.2 local GLADE database**\nI have converted the downloaded GLADE catalogue into an sqlite3 database for easy query. <br>\nFor now you can grab the compiled database [here](https://www.dropbox.com/s/aib3ze9vaxmknp7/glade_v23.db?dl=0), and put it into a directory named `db/` in the directory of this notebook <br>\n(Later I will make sure the code that generates the db works so that you can make your own)",
"_____no_output_____"
],
[
"### **0.3 The following cells set up autoreload and import necessary packages for this notebook**",
"_____no_output_____"
]
],
[
[
"%load_ext autoreload\n%autoreload 2",
"_____no_output_____"
],
[
"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os",
"_____no_output_____"
]
],
[
[
"### **0.4 Define the follow environment variables if you haven't done so**",
"_____no_output_____"
]
],
[
[
"os.environ['SFD_DIR'] = '/home/mi/sfddata-master' #modify this to point to the dust map downloaded from https://github.com/kbarbary/sfddata\nos.environ['SIRAHPIPE_DIR'] = os.getcwd() #Or your sirah_target_pipe dir if you are running in other directories",
"_____no_output_____"
]
],
[
[
"## **1. Using the pipeline**\n### **1.1 import the SIRAHPipe module first**",
"_____no_output_____"
]
],
[
[
"from pipeline import SIRAHPipe",
"_____no_output_____"
]
],
[
[
"### **1.2 initialize the pipeline** <a id='init_pipe'></a>\nThis cell defines the pipeline and chooses the brokers, crossmatch calalogues, and the selection cuts <br>\n**Currently implemented brokers:** \n[alerce](http://alerce.science/), \n[lasair](https://lasair.roe.ac.uk/streams/#),\n[tns](https://wis-tns.weizmann.ac.il/) <br>\n**Crossmatch catalogues:** \n[sdss](https://skyserver.sdss.org/CasJobs/SubmitJob.aspx),\n[ned](https://ned.ipac.caltech.edu/forms/nnd.html),\n[glade](http://glade.elte.hu/) <br>\n**Selection cuts:**\nzcut,\nztflimcut,\nhostdistcut,\nolddetectioncut,\nmagzcut,\nrbcut \n(see <a href='#run_pipe'>1.4 running the pipeline</a> for descriptions on the cuts)<br>\nFor this demo we select all of the above options:",
"_____no_output_____"
]
],
[
[
"pipe = SIRAHPipe(brokers=['alerce','lasair','tns'],xmatch_catalogues=['sdss','ned','glade'],\n selection_cuts=['zcut','ztflimcut','hostdistcut','olddetectioncut','magzcut','rbcut'])",
"Setting up SkyServer...\nSetting up local db [db/glade_v23.db]\nBrokers to query: ['alerce', 'lasair', 'tns']\nCrossmatch catalogues: ['sdss', 'ned', 'glade']\nCuts to apply: ['zcut', 'ztflimcut', 'hostdistcut', 'olddetectioncut', 'magzcut', 'rbcut']\n"
]
],
[
[
"### **1.3 using the realtime mode**\nLet's record current date and time. <br>\nThe pipeline can run in realtime or non-realtime mode. <br>\nif `realtime==True`, the sql query includes conditions on the latest magnitude provided by the brokers; <br>\nif `realtime==False`, the latest magnitudes are calculated offline by querying all the detections before the specific date.<br> This is to mimic realtime query but can be used for an earlier date for testing and comparing. Note that this may not produce the exact results as the real time mode as the broker databases may change. <br>\nFor this demo we set `realtime = True`",
"_____no_output_____"
]
],
[
[
"from astropy.time import Time\nfrom datetime import datetime\nprint(Time(datetime.today()),'mjd=',Time(datetime.today()).mjd)\nrealtime = True",
"2020-04-22 18:13:58.102328 mjd= 58961.75970026116\n"
]
],
[
[
"### **1.4 running the pipeline** <a id='run_pipe'></a>\nThis is the main part of the pipeline that many options can be specified. <br>\nHere I list some useful ones (and their default values): <br>\n- **[query options]** <br>\n - **mjdstart, mjdend:** mjd range to query\n - **gmax(=20.), rmax(=20.), gmin(=16.), rmin(=16.):** max/min magnitude ranges to query (ZTF specifically, for objects on TNS that are not ZTF the bands are hard code to be g at the moment)\n - **qlim:** number of objects to query for brokers (this is a universal number set for all brokers but currently not applied to tns) \n - **skip_ztf(=True):** set to True to skip importing TNS objects that has internal ZTF names (since it's already in the Alerce/Lasair queries) \n - **use_sherlock(=True):** include Lasair's sherlock classification and crossmatch results in query, default is True. This can be set to False in case sherlock is not available or for testing purpose\n<br> \n- **[selection cut options]** \n - **[zcut] zlow(=0.016), zhigh(=0.08), zerrlim(=0.02):** limit on redshift and redshift error, for specz the zerr is currently set to 0.001. Increase the number to include photoz results\n - **[magzcut] dmag_min(=1.), dmag_max(=4.5), magabs=(-19.1):** cut on the mag difference from a given absolute magnitude (peak mag for example) - this can be translated as phase cut if the sedmodel is known (see mag/z plot below). \n - **[rbcut] rb(=0.5):** real/bogus score for ZTF objects (higher rb value is more likely to be real)\n - **[hostdistcut] dist_min(=2.), dist_max(=None):** distance to host (in arcsec) \n - **[ztflimcut] maglim(=19.8), nobs(=1):** set mag lim for objects that has <= nobs detections. This is used to cut on single detections closer to the (ZTF) limiting mag\n - **[olddetectioncut] dayslim(=5), fromday(=None):** Remove objects whose latest detection is > *dayslim* days from *fromday* (These are potentially too old)\n<br>\n- **[other options]**\n - **[magz plot options]**\n - **sedmodel=('salt2'):** sedmodel to generate the mag vs z lines. This can be any sncosmo model listed [here](https://sncosmo.readthedocs.io/en/v2.1.x/source-list.html)\n - **sedmodel_pardict=(None):** dictionary of parameters to set for the sedmodel\n\n`pipe.run()` **runs the pipeline and applies the selection cuts defined in <a href='#init_pipe'>1.2 initialize the pipeline</a>, and makes a mag/z plot for the objects that passed all cuts. This may take a while (a few minutes to about less than an hour) depending on how large the query is and how many objects to be crossmatched.**",
"_____no_output_____"
]
],
[
[
"import time\ntoday = Time(datetime.today()).mjd\n\nstart = time.time()\npipe.run(mjdstart=today-10,mjdend=today,qlim=100,zerrlim=0.01,dmag_max=4.5,gmax=22,rmax=22,realtime=realtime,skip_ztf=True,use_sherlock=True)\n# pipe.run(mjdstart=today-10,mjdend=today,qlim=100,zerrlim=0.01,dmag_max=4.5,gmax=22,rmax=22,realtime=realtime,\n# skip_ztf=True,use_sherlock=True,sedmodel='s11-2005hl',magabs=-18)\nend = time.time()\nprint(\"Time used: {:.2f} mins\".format((end - start)/60.))",
"queryresult size: 100\nqueryresult size: 100\nqueryresult size: 166\nTable [sncoor] uploaded successfully.\nQuery Job is submitted. JobID=47354091\nJob 47354091 is finished\nCross-matching GLADE catalog using astropy module search_around_sky\nDone. Time=0.021483612060546876 minutes\nCross match NED for 0.01 < sdss_photoz < 0.08, num = 2\nTable [sncoor] uploaded successfully.\nQuery Job is submitted. JobID=47354099\nJob 47354099 is finished\nCross-matching GLADE catalog using astropy module search_around_sky\nDone. Time=0.023793903986612956 minutes\nSelecting 0.016 < z < 0.080\n and zerr < 0.010\nNumber fails cut [flag_zcut]: 779/912\nCut on magnitude lim for nobs <= 1: maglim = 19.8\nNumber fails cut [flag_ztflimcut]: 14/912\nCut on distance to host: 2 < dist < None (Arcsec)\nNumber fails cut [flag_hostdistcut]: 113/912\nCut on days since last detection from 2020-04-22 18:16:02.215: dt < 5\nNumber fails cut [flag_olddetectioncut]: 459/912\n"
]
],
[
[
"### **1.5 Miscellaneous features**\nHere I describe some miscellaneous features that may be useful in analyzing the query results",
"_____no_output_____"
],
[
"#### 1.5.1 *SIRAHPipe.results*\nAfter the pipeline runs, all the query results, including the selection cut flags, are saved in `SIRAHPipe.results`",
"_____no_output_____"
]
],
[
[
"pipe.results.head()",
"_____no_output_____"
]
],
[
[
"#### 1.5.2 the *SIRAHPipe.MakeCuts* module\n- **(re)applying cuts using** ***SIRAHPipe.MakeCuts.[Cutname]*** <br>\nThe `SIRAHPipe.MakeCuts` module contains all the selection cut functions that can be reapplied after the pipeline runs to change the selection criteria. <br>\ne.g. We can reapply the redshift cut with narrower `zerrlim=0.005` or apply new cuts that are not selected in the initialization phase <br>\n- **make mag/z plot using** ***SIRAHPipe.MakeCuts.plot()***\n- **return a pandas DataFrame for objects that passed all cuts using** ***SIRAHPipe.MakeCuts.aftercuts()*** <br>\nNote that `SIRAHPipe.MakeCuts.aftercuts()` returns all entries passing the cuts so there can be multiple entries for the same object. \nYou may use `pd.DataFrame.sort_values()` and `pd.DataFrame.drop_duplicates()` to select unique results or define your own ranking",
"_____no_output_____"
]
],
[
[
"## apply additional cut here \npipe.MakeCuts.zcut(zerrlim=0.005)\n# pipe.MakeCuts.olddetectioncut()\npipe.MakeCuts.magzcut(dmag_max=3.,dmag_min=0.,magabs=-18)\n# pipe.MakeCuts.ztflimcut()\npipe.MakeCuts.plot(magabs=-18,magz_plot=True,sedmodel='snana-2004fe',phase=[-10,-5,0])\n# pipe.MakeCuts.plot(magabs=-19,magz_plot=True)\nplt.show()\ndf = pipe.MakeCuts.aftercuts()\n\ncols = ['xmatch_rank','xmatch_db','distance']\nsort_cols = [x for x in cols if x in df.columns]\ndf = df.sort_values(sort_cols).drop_duplicates('oid')\ncols = ['oid','nobs','firstmjd','lastmjd','gmaglatest','rmaglatest','classearly','classification','distance','separationArcsec','dmag_g','dmag_r',\n 'z','zerr','xmatch_rank','objID','xmatch_objid','xmatch_table_name']\ncols_exist = [x for x in cols if x in df.columns]\ndf[cols_exist].head()",
"Selecting 0.016 < z < 0.080\n and zerr < 0.005\nSelecting candidates based on mag vs z: 0.00 < dmag (from max) < 3.00\nPlotting MakeCuts...\n"
]
],
[
[
"## **2. Making plots for selected candidates**",
"_____no_output_____"
],
[
"The main function for making light curve and phase estimate plots is *utils.gen_plots* <br>\n`gen_plots()` requires a pandas DataFrame as input that comes from running the pipeline or a self-defined `pd.DataFrame` that has the required columns as the pipeline results <br>\n- set **interactive = True** to make interactive plots in jupyter notebook (this doesn't seem to work with jupyter lab) <br>\n if interactive=True, the image will be an interactive Aladin widget; otherwise the image will be retrieved from the PS1 image server\n- set **savepdf = True** to out pdfs <br>\n currently the pdfs are plotted in the order of decreasing phase estimation\n\n**Here are some useful *gen_plots* options:** <br>\n- **magabs(=-19.1):** For Ia, \n- **extra_lc(=False):** set to *True* is extra photometry is available. The photometry need to be placed in `data/extra_photometry` as `[objectname].txt`\n- **update_lc_prediction(=False):** replot the lc prediction\n- **last_detection_max(=5):** don't include objects with last detection that is >5 days old\n- **source(='ztf'):** provide correct photometry format ('ztf' or 'tns')\n- **broker(='alerce'):** for ztf objects only, broker to query for light curve points ('alerce' or 'lasair')\n- **plot_ylim(=(21,15)):** ylims for the light curve and mag/z plots\n- **ps1_image_size(=320):** image size for PS1 images (in pixels), actual image size is 0.25 arcsec/pixel\n",
"_____no_output_____"
]
],
[
[
"from utils import *\nimport matplotlib.pyplot as plt\nimport os\nfrom PyPDF2 import PdfFileMerger\n# %matplotlib inline\n\ninteractive = False\nsavepdf = True\nquerydate = date.today()\nif not os.path.isdir('demo'):\n os.mkdir('demo')\n\nif savepdf:\n pdf_file = 'demo/Candidates_{}.pdf'.format(querydate.strftime(\"%m-%d-%Y\"))\n folder = 'demo/{}'.format(querydate.strftime(\"%m-%d-%Y\"))\n if not os.path.isdir(folder):\n os.mkdir(folder)\n pdflist = []\n orderlist = []\n# display(target[target.oid=='ZTF20aamfpft'])\nfor i,row in df[0:2].iterrows():\n if savepdf:\n f = '{}/{}.pdf'.format(folder,row.oid)\n else:\n f = None\n source = 'tns' if row['Broker'] == 'tns' else 'ztf'\n res = gen_plots(row,interactive=interactive,pdf_file=f,source=source,plot_ylim=(22,15),broker='lasair',\n sedmodel='salt2',magabs=-19.1)\n if savepdf and not res['too_old']:\n pdflist.append(f) \n orderlist.append(res['phase_tuesday'])\nif savepdf:\n idx_ordered = np.argsort(orderlist)\n merger = PdfFileMerger()\n for pdf in np.array(pdflist)[idx_ordered]:\n merger.append(pdf)\n merger.write(pdf_file)\n merger.close()",
"ZTF20aaurfhs: z=0.0352 +/- 0.0010\nra = 17:01:22.507 dec = +20:18:58.35 mwebv=0.058\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
]
] |
e77b4cac1108e039dcd3b315b4acaa21487c7f00 | 15,259 | ipynb | Jupyter Notebook | serverless-inference/Serverless-Inference-Walkthrough.ipynb | jkroll-aws/amazon-sagemaker-examples | 4bbe7f31ef20f9db2f8a51dc5ddf02623ef747f2 | [
"Apache-2.0"
] | 3 | 2020-04-07T00:58:53.000Z | 2020-08-24T04:28:13.000Z | serverless-inference/Serverless-Inference-Walkthrough.ipynb | jkroll-aws/amazon-sagemaker-examples | 4bbe7f31ef20f9db2f8a51dc5ddf02623ef747f2 | [
"Apache-2.0"
] | null | null | null | serverless-inference/Serverless-Inference-Walkthrough.ipynb | jkroll-aws/amazon-sagemaker-examples | 4bbe7f31ef20f9db2f8a51dc5ddf02623ef747f2 | [
"Apache-2.0"
] | 1 | 2020-12-09T19:11:47.000Z | 2020-12-09T19:11:47.000Z | 30.037402 | 454 | 0.575398 | [
[
[
"# SageMaker Serverless Inference\n## XGBoost Regression Example\n\nAmazon SageMaker Serverless Inference is a purpose-built inference option that makes it easy for customers to deploy and scale ML models. Serverless Inference is ideal for workloads which have idle periods between traffic spurts and can tolerate cold starts. Serverless endpoints also automatically launch compute resources and scale them in and out depending on traffic, eliminating the need to choose instance types or manage scaling policies.\n\nFor this notebook we'll be working with the SageMaker XGBoost Algorithm to train a model and then deploy a serverless endpoint. We will be using the public S3 Abalone regression dataset for this example.\n\n<b>Notebook Setting</b>\n- <b>SageMaker Classic Notebook Instance</b>: ml.m5.xlarge Notebook Instance & conda_python3 Kernel\n- <b>SageMaker Studio</b>: Python 3 (Data Science)\n- <b>Regions Available</b>: SageMaker Serverless Inference is currently available in the following regions: US East (Northern Virginia), US East (Ohio), US West (Oregon), EU (Ireland), Asia Pacific (Tokyo) and Asia Pacific (Sydney)",
"_____no_output_____"
],
[
"## Table of Contents\n- Setup\n- Model Training\n- Deployment\n - Model Creation\n - Endpoint Configuration (Adjust for Serverless)\n - Serverless Endpoint Creation\n - Endpoint Invocation\n- Cleanup",
"_____no_output_____"
],
[
"## Setup\n\nFor testing you need to properly configure your Notebook Role to have <b>SageMaker Full Access</b>.",
"_____no_output_____"
],
[
"Let's start by installing preview wheels of the Python SDK, boto and aws cli",
"_____no_output_____"
]
],
[
[
"# Fallback in case wheels are unavailable\n! pip install sagemaker botocore boto3 awscli --upgrade",
"_____no_output_____"
],
[
"import subprocess\n\n\ndef execute_cmd(cmd):\n print(cmd)\n output = subprocess.getstatusoutput(cmd)\n return output\n\n\ndef _download_from_s3(_file_path):\n _path = f\"s3://reinvent21-sm-rc-wheels/{_file_path}\"\n print(f\"Path is {_path}\")\n ls_cmd = f\"aws s3 ls {_path}\"\n print(execute_cmd(ls_cmd))\n\n cmd = f\"aws s3 cp {_path} /tmp/\"\n print(\"Downloading: \", cmd)\n return execute_cmd(cmd)\n\n\ndef _install_wheel(wheel_name):\n cmd = f\"pip install --no-deps --log /tmp/output3.log /tmp/{wheel_name} --force-reinstall\"\n\n ret = execute_cmd(cmd)\n\n _name = wheel_name.split(\".\")[0]\n _, _version = execute_cmd(f\"python -c 'import {_name}; print({_name}.__version__)'\")\n\n for package in [\"botocore\", \"sagemaker\", \"boto3\", \"awscli\"]:\n print(execute_cmd(f\"python -c 'import {package}; print({package}.__version__)'\"))\n\n print(f\"Installed {_name}:{_version}\")\n\n return ret\n\n\ndef install_sm_py_sdk():\n pySDK_name = \"sagemaker.tar.gz\"\n\n exit_code, _ = _download_from_s3(\"dist/sagemaker.tar.gz\")\n\n if not exit_code:\n _install_wheel(pySDK_name)\n else:\n print(f\"'{pySDK_name}' is not present in S3 Bucket. Installing from public PyPi...\")\n execute_cmd(\"pip install sagemaker\")\n\n\ndef install_boto_wheels():\n WHEELS = [\"botocore.tar.gz\", \"boto3.tar.gz\", \"awscli.tar.gz\"]\n\n for wheel_name in WHEELS:\n _path = f\"boto3/{wheel_name}\"\n exit_code, _ = _download_from_s3(_path)\n\n if not exit_code:\n _install_wheel(wheel_name)\n else:\n print(f\"'{wheel_name}' is not present in S3 Bucket. Ignoring...\")\n\n\ninstall_boto_wheels()\ninstall_sm_py_sdk()",
"_____no_output_____"
],
[
"# Setup clients\nimport boto3\n\nclient = boto3.client(service_name=\"sagemaker\")\nruntime = boto3.client(service_name=\"sagemaker-runtime\")",
"_____no_output_____"
]
],
[
[
"### SageMaker Setup\nTo begin, we import the AWS SDK for Python (Boto3) and set up our environment, including an IAM role and an S3 bucket to store our data.",
"_____no_output_____"
]
],
[
[
"import boto3\nimport sagemaker\nfrom sagemaker.estimator import Estimator\n\nboto_session = boto3.session.Session()\nregion = boto_session.region_name\nprint(region)\n\nsagemaker_session = sagemaker.Session()\nbase_job_prefix = \"xgboost-example\"\nrole = sagemaker.get_execution_role()\nprint(role)\n\ndefault_bucket = sagemaker_session.default_bucket()\ns3_prefix = base_job_prefix\n\ntraining_instance_type = \"ml.m5.xlarge\"",
"_____no_output_____"
]
],
[
[
"Retrieve the Abalone dataset from a publicly hosted S3 bucket.",
"_____no_output_____"
]
],
[
[
"# retrieve data\n! curl https://sagemaker-sample-files.s3.amazonaws.com/datasets/tabular/uci_abalone/train_csv/abalone_dataset1_train.csv > abalone_dataset1_train.csv",
"_____no_output_____"
]
],
[
[
"Upload the Abalone dataset to the default S3 bucket.",
"_____no_output_____"
]
],
[
[
"# upload data to S3\n!aws s3 cp abalone_dataset1_train.csv s3://{default_bucket}/xgboost-regression/train.csv",
"_____no_output_____"
]
],
[
[
"## Model Training",
"_____no_output_____"
],
[
"Now, we train an ML model using the XGBoost Algorithm. In this example, we use a SageMaker-provided [XGBoost](https://docs.aws.amazon.com/sagemaker/latest/dg/xgboost.html) container image and configure an estimator to train our model.",
"_____no_output_____"
]
],
[
[
"from sagemaker.inputs import TrainingInput\n\ntraining_path = f\"s3://{default_bucket}/xgboost-regression/train.csv\"\ntrain_input = TrainingInput(training_path, content_type=\"text/csv\")",
"_____no_output_____"
],
[
"model_path = f\"s3://{default_bucket}/{s3_prefix}/xgb_model\"\n\n# retrieve xgboost image\nimage_uri = sagemaker.image_uris.retrieve(\n framework=\"xgboost\",\n region=region,\n version=\"1.0-1\",\n py_version=\"py3\",\n instance_type=training_instance_type,\n)\n\n# Configure Training Estimator\nxgb_train = Estimator(\n image_uri=image_uri,\n instance_type=training_instance_type,\n instance_count=1,\n output_path=model_path,\n sagemaker_session=sagemaker_session,\n role=role,\n)\n\n# Set Hyperparameters\nxgb_train.set_hyperparameters(\n objective=\"reg:linear\",\n num_round=50,\n max_depth=5,\n eta=0.2,\n gamma=4,\n min_child_weight=6,\n subsample=0.7,\n silent=0,\n)",
"_____no_output_____"
]
],
[
[
"Train the model on the Abalone dataset.",
"_____no_output_____"
]
],
[
[
"# Fit model\nxgb_train.fit({\"train\": train_input})",
"_____no_output_____"
]
],
[
[
"## Deployment",
"_____no_output_____"
],
[
"After training the model, retrieve the model artifacts so that we can deploy the model to an endpoint.",
"_____no_output_____"
]
],
[
[
"# Retrieve model data from training job\nmodel_artifacts = xgb_train.model_data\nmodel_artifacts",
"_____no_output_____"
]
],
[
[
"### Model Creation\nCreate a model by providing your model artifacts, the container image URI, environment variables for the container (if applicable), a model name, and the SageMaker IAM role.",
"_____no_output_____"
]
],
[
[
"from time import gmtime, strftime\n\nmodel_name = \"xgboost-serverless\" + strftime(\"%Y-%m-%d-%H-%M-%S\", gmtime())\nprint(\"Model name: \" + model_name)\n\n# dummy environment variables\nbyo_container_env_vars = {\"SAGEMAKER_CONTAINER_LOG_LEVEL\": \"20\", \"SOME_ENV_VAR\": \"myEnvVar\"}\n\ncreate_model_response = client.create_model(\n ModelName=model_name,\n Containers=[\n {\n \"Image\": image_uri,\n \"Mode\": \"SingleModel\",\n \"ModelDataUrl\": model_artifacts,\n \"Environment\": byo_container_env_vars,\n }\n ],\n ExecutionRoleArn=role,\n)\n\nprint(\"Model Arn: \" + create_model_response[\"ModelArn\"])",
"_____no_output_____"
]
],
[
[
"### Endpoint Configuration Creation\n\nThis is where you can adjust the <b>Serverless Configuration</b> for your endpoint. The current max concurrent invocations for a single endpoint, known as <b>MaxConcurrency</b>, can be any value from <b>1 to 50</b>, and <b>MemorySize</b> can be any of the following: <b>1024 MB, 2048 MB, 3072 MB, 4096 MB, 5120 MB, or 6144 MB</b>.",
"_____no_output_____"
]
],
[
[
"xgboost_epc_name = \"xgboost-serverless-epc\" + strftime(\"%Y-%m-%d-%H-%M-%S\", gmtime())\n\nendpoint_config_response = client.create_endpoint_config(\n EndpointConfigName=xgboost_epc_name,\n ProductionVariants=[\n {\n \"VariantName\": \"byoVariant\",\n \"ModelName\": model_name,\n \"ServerlessConfig\": {\n \"MemorySizeInMB\": 4096,\n \"MaxConcurrency\": 1,\n },\n },\n ],\n)\n\nprint(\"Endpoint Configuration Arn: \" + endpoint_config_response[\"EndpointConfigArn\"])",
"_____no_output_____"
]
],
[
[
"### Serverless Endpoint Creation\nNow that we have an endpoint configuration, we can create a serverless endpoint and deploy our model to it. When creating the endpoint, provide the name of your endpoint configuration and a name for the new endpoint.",
"_____no_output_____"
]
],
[
[
"endpoint_name = \"xgboost-serverless-ep\" + strftime(\"%Y-%m-%d-%H-%M-%S\", gmtime())\n\ncreate_endpoint_response = client.create_endpoint(\n EndpointName=endpoint_name,\n EndpointConfigName=xgboost_epc_name,\n)\n\nprint(\"Endpoint Arn: \" + create_endpoint_response[\"EndpointArn\"])",
"_____no_output_____"
]
],
[
[
"Wait until the endpoint status is InService before invoking the endpoint.",
"_____no_output_____"
]
],
[
[
"# wait for endpoint to reach a terminal state (InService) using describe endpoint\nimport time\n\ndescribe_endpoint_response = client.describe_endpoint(EndpointName=endpoint_name)\n\nwhile describe_endpoint_response[\"EndpointStatus\"] == \"Creating\":\n describe_endpoint_response = client.describe_endpoint(EndpointName=endpoint_name)\n print(describe_endpoint_response[\"EndpointStatus\"])\n time.sleep(15)\n\ndescribe_endpoint_response",
"_____no_output_____"
]
],
[
[
"### Endpoint Invocation\nInvoke the endpoint by sending a request to it. The following is a sample data point grabbed from the CSV file downloaded from the public Abalone dataset.",
"_____no_output_____"
]
],
[
[
"response = runtime.invoke_endpoint(\n EndpointName=endpoint_name,\n Body=b\".345,0.224414,.131102,0.042329,.279923,-0.110329,-0.099358,0.0\",\n ContentType=\"text/csv\",\n)\n\nprint(response[\"Body\"].read())",
"_____no_output_____"
]
],
[
[
"## Clean Up\nDelete any resources you created in this notebook that you no longer wish to use.",
"_____no_output_____"
]
],
[
[
"client.delete_model(ModelName=model_name)\nclient.delete_endpoint_config(EndpointConfigName=xgboost_epc_name)\nclient.delete_endpoint(EndpointName=endpoint_name)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e77b5464b66c5ba5812edf8d7aedfb4a8096a648 | 33,109 | ipynb | Jupyter Notebook | method5.ipynb | ancka019/ComputationsMethods6sem | e14576d5dfab19c686460a3b7d2f1b4709ef4adf | [
"Apache-2.0"
] | null | null | null | method5.ipynb | ancka019/ComputationsMethods6sem | e14576d5dfab19c686460a3b7d2f1b4709ef4adf | [
"Apache-2.0"
] | null | null | null | method5.ipynb | ancka019/ComputationsMethods6sem | e14576d5dfab19c686460a3b7d2f1b4709ef4adf | [
"Apache-2.0"
] | null | null | null | 43.336387 | 509 | 0.34027 | [
[
[
"<a href=\"https://colab.research.google.com/github/ancka019/ComputationsMethods6sem/blob/main/method5.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nfrom numpy.linalg import eig\nfrom scipy.linalg import hilbert\nfrom copy import copy",
"_____no_output_____"
]
],
[
[
"Степенной метод",
"_____no_output_____"
]
],
[
[
"def pow_method(a,eps,x0=None):\n if x0 is None:\n x0 = np.random.uniform(-1,1,size=a.shape[1])\n x1 = a@x0\n num_of_iters = 1\n lambda0 = x1[0]/x0[0]\n while True:\n x0,x1 = x1, a@x1\n lambda1 = x1[0]/x0[0]\n if abs(lambda1-lambda0)<eps or num_of_iters > 5000:\n break\n lambda0 = lambda1\n num_of_iters += 1\n return abs(lambda1),num_of_iters",
"_____no_output_____"
]
],
[
[
"метод скалярных произведений",
"_____no_output_____"
]
],
[
[
"def scal_method(a,eps,x0=None): \n if x0 is None:\n x0 = np.random.uniform(-1,1,size=a.shape[1])\n num_of_iters = 1\n x1 = a@x0\n y0 = copy(x0)\n a_T = np.transpose(a)\n y1 = a_T@x0\n lambda0 = np.dot(x1,y1)/np.dot(x0,y0)\n while True:\n x0,x1 = x1, a@x1\n y0,y1 = y1, a_T@y1\n lambda1 = np.dot(x1,y1)/np.dot(x0,y1)\n if abs(lambda1-lambda0)<eps or num_of_iters > 5000:\n break\n lambda0 = lambda1\n num_of_iters += 1\n return abs(lambda1),num_of_iters",
"_____no_output_____"
]
],
[
[
"Решение\n",
"_____no_output_____"
]
],
[
[
"result = []\nfor size in [3,5,11]:\n A = hilbert(size)\n data = []\n lambda_acc = max(abs(np.linalg.eig(A)[0]))\n for eps in range(-6, -1):\n eps = 10**eps\n data.append({\n 'eps': eps,\n 'Степенной метод (К-во итераций)':\n pow_method(A, eps)[1],\n 'Степенной метод |lambda_acc - lambda|' : \n abs(lambda_acc - abs(pow_method(A, eps)[0])),\n 'Метод скалярных произведений (К-во итераций)':\n scal_method(A, eps)[1],\n 'Метод скалярных произведений |lambda_acc - lambda|' : \n abs(lambda_acc - abs(scal_method(A, eps)[0]))\n })\n result.append(pd.DataFrame(data))",
"_____no_output_____"
],
[
"result[0]",
"_____no_output_____"
],
[
"result[1]",
"_____no_output_____"
],
[
"result[2]",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
e77b5e53ae104fd39ab2edf3cb6c7d8c4a0c2218 | 17,280 | ipynb | Jupyter Notebook | dev_swift/02_fully_connected.ipynb | rohitgr7/fastai_docs | 531139ac17dd2e0cf08a99b6f894dbca5028e436 | [
"Apache-2.0"
] | null | null | null | dev_swift/02_fully_connected.ipynb | rohitgr7/fastai_docs | 531139ac17dd2e0cf08a99b6f894dbca5028e436 | [
"Apache-2.0"
] | null | null | null | dev_swift/02_fully_connected.ipynb | rohitgr7/fastai_docs | 531139ac17dd2e0cf08a99b6f894dbca5028e436 | [
"Apache-2.0"
] | null | null | null | 24.40678 | 400 | 0.542419 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
e77b608fe23334d0d1bd3ff278caff6be589db02 | 129,429 | ipynb | Jupyter Notebook | el_nino.ipynb | nohitme/psu-daan888-project | 6abcd220bc74c2542a49eb7abdc055f8e20adc91 | [
"Apache-2.0"
] | null | null | null | el_nino.ipynb | nohitme/psu-daan888-project | 6abcd220bc74c2542a49eb7abdc055f8e20adc91 | [
"Apache-2.0"
] | null | null | null | el_nino.ipynb | nohitme/psu-daan888-project | 6abcd220bc74c2542a49eb7abdc055f8e20adc91 | [
"Apache-2.0"
] | null | null | null | 80.440646 | 46,888 | 0.690966 | [
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport os\nimport seaborn as sns\n\nelnino = pd.read_csv('tao-all2.dat', header=None, delimiter=' ')\noni = pd.read_csv('Data files/ONI.csv', header=0)\nelnino.columns = ['Observation', 'Year', 'Month', 'Day', 'Date', 'Latitude', 'Longitude', 'Zonal Winds',\n 'Meridional Winds', 'Humidity', 'Air Temp', 'Sea Surface Temp']",
"_____no_output_____"
]
],
[
[
"# Data Summary",
"_____no_output_____"
]
],
[
[
"elnino.head(20)",
"_____no_output_____"
],
[
"# Print statistical summary\nprint(\"Statistical summary for the 'Elnino' file: \\n\")\nprint(elnino.describe(), \"\\n \\n\")\n# display types for variables\nprint(\"The variable types are as follow: \\n\")\nprint(elnino.dtypes, \"\\n\")\n## get name of columns in dataset\nprint(\"The name of the columns in dataset are: \\n\")\nprint(elnino.columns, \"\\n\")\n## get number of rows and column in dataset\nprint(\"The dataset file is composed of the following number of rows and columns (rows, columns): \")\nprint(elnino.shape, \"\\n \\n\")\n# looking for null values\nprint(\"The total number of null/missing values before converting the variables is: \")\nprint(elnino.isnull().sum(), \"\\n\")\nprint(\"So, there is :\", elnino.isnull().values.sum(), \" value missing\")",
"Statistical summary for the 'Elnino' file: \n\n Observation Year Month Day \\\ncount 178080.000000 178080.000000 178080.000000 178080.000000 \nmean 89040.500000 93.302325 6.504869 15.720536 \nstd 51407.412306 3.393818 3.459657 8.800487 \nmin 1.000000 80.000000 1.000000 1.000000 \n25% 44520.750000 92.000000 4.000000 8.000000 \n50% 89040.500000 94.000000 6.000000 16.000000 \n75% 133560.250000 96.000000 10.000000 23.000000 \nmax 178080.000000 98.000000 12.000000 31.000000 \n\n Date Latitude Longitude \ncount 178080.000000 178080.000000 178080.000000 \nmean 933689.455374 0.473626 -54.025233 \nstd 33900.474320 4.583041 135.363994 \nmin 800307.000000 -8.810000 -180.000000 \n25% 920116.000000 -2.010000 -154.950000 \n50% 940601.000000 0.010000 -111.260000 \n75% 960617.000000 4.980000 147.010000 \nmax 980623.000000 9.050000 171.080000 \n \n\nThe variable types are as follow: \n\nObservation int64\nYear int64\nMonth int64\nDay int64\nDate int64\nLatitude float64\nLongitude float64\nZonal Winds object\nMeridional Winds object\nHumidity object\nAir Temp object\nSea Surface Temp object\ndtype: object \n\nThe name of the columns in dataset are: \n\nIndex(['Observation', 'Year', 'Month', 'Day', 'Date', 'Latitude', 'Longitude',\n 'Zonal Winds', 'Meridional Winds', 'Humidity', 'Air Temp',\n 'Sea Surface Temp'],\n dtype='object') \n\nThe dataset file is composed of the following number of rows and columns (rows, columns): \n(178080, 12) \n \n\nThe total number of null/missing values before converting the variables is: \nObservation 0\nYear 0\nMonth 0\nDay 0\nDate 0\nLatitude 0\nLongitude 0\nZonal Winds 0\nMeridional Winds 0\nHumidity 0\nAir Temp 0\nSea Surface Temp 0\ndtype: int64 \n\nSo, there is : 0 value missing\n"
],
[
"##\n# convert categorical variables to numeric\nelnino['Zonal Winds'] = pd.to_numeric(elnino['Zonal Winds'], errors='coerce')\nelnino['Meridional Winds'] = pd.to_numeric(elnino['Meridional Winds'], errors='coerce')\nelnino['Humidity'] = pd.to_numeric(elnino['Humidity'], errors='coerce')\nelnino['Air Temp'] = pd.to_numeric(elnino['Air Temp'], errors='coerce')\nelnino['Sea Surface Temp'] = pd.to_numeric(elnino['Sea Surface Temp'], errors='coerce')\n# display data types\nprint(\"After converting the variables, the new Data types are: \\n\", elnino.dtypes, \"\\n\")",
"After converting the variables, the new Data types are: \n Observation int64\nYear int64\nMonth int64\nDay int64\nDate int64\nLatitude float64\nLongitude float64\nZonal Winds float64\nMeridional Winds float64\nHumidity float64\nAir Temp float64\nSea Surface Temp float64\ndtype: object \n\n"
],
[
"elnino.describe().round(2)",
"_____no_output_____"
],
[
"# replace empty spaces with NAN values\nelnino.replace(r'^\\s*$', np.nan, regex=True)\nprint(\"The count of filled cells for each variable in the data set is: \\n\")\nprint(elnino.apply(lambda x: x.count(), axis=0), \"\\n \\n\")\nprint(\"The sum of filled cells in the data set is: \")\nprint(elnino.apply(lambda x: x.count(), axis=0).sum(), \"\\n \\n\")",
"The count of filled cells for each variable in the data set is: \n\nObservation 178080\nYear 178080\nMonth 178080\nDay 178080\nDate 178080\nLatitude 178080\nLongitude 178080\nZonal Winds 152917\nMeridional Winds 152918\nHumidity 112319\nAir Temp 159843\nSea Surface Temp 161073\ndtype: int64 \n \n\nThe sum of filled cells in the data set is: \n1985630 \n \n\n"
],
[
"elnino.apply(lambda x: x.count(), axis=0)",
"_____no_output_____"
],
[
"# print missing values per year\nelnino_Latitude = elnino['Latitude'].isnull().groupby(elnino['Year']).sum().astype(int).reset_index(name='Latitude')\nelnino_Longitude = elnino['Longitude'].isnull().groupby(elnino['Year']).sum().astype(int).reset_index(name='Longitude')\nelnino_Zonal_Winds = elnino['Zonal Winds'].isnull().groupby(elnino['Year']).sum().astype(int).reset_index(\n name='Zonal Winds')\nelnino_Meridional_Winds = elnino['Meridional Winds'].isnull().groupby(elnino['Year']).sum().astype(int).reset_index(\n name='Meridional Winds')\nelnino_Humidity = elnino['Humidity'].isnull().groupby(elnino['Year']).sum().astype(int).reset_index(name='Humidity')\nelnino_Air_Temp = elnino['Air Temp'].isnull().groupby(elnino['Year']).sum().astype(int).reset_index(name='Air Temp')\nelnino_Sea_Surface_Temp = elnino['Sea Surface Temp'].isnull().groupby(elnino['Year']).sum().astype(int).reset_index(\n name='Sea Surface Temp')\nelnino_1 = elnino_Latitude.join(elnino_Longitude.set_index('Year'), on='Year')\nelnino_2 = elnino_1.join(elnino_Zonal_Winds.set_index('Year'), on='Year')\nelnino_3 = elnino_2.join(elnino_Meridional_Winds.set_index('Year'), on='Year')\nelnino_4 = elnino_3.join(elnino_Humidity.set_index('Year'), on='Year')\nelnino_5 = elnino_4.join(elnino_Air_Temp.set_index('Year'), on='Year')\nelnino_6 = elnino_5.join(elnino_Sea_Surface_Temp.set_index('Year'), on='Year')\nprint(\"The total number of missing values per variable grouped by Year is: \", \"\\n\")\nelnino_6",
"The total number of missing values per variable grouped by Year is: \n\n"
],
[
"# looking for null values\nprint(\"The total number of null/missing values for each variable is: \", \"\\n\")\nprint(elnino.isnull().sum(), \"\\n\")\nprint(\"So, there is :\", elnino.isnull().values.sum(), \" value missing\", \"\\n \\n \\n \\n \\n\")\nprint(elnino.head(10))\nelnino_data_sum = elnino.apply(lambda x: x.count(), axis=0).sum()\nelnino_missing_sum = elnino.isnull().values.sum()\n# display percentage of missing data\nprint(\"The percentage of missing data is: \", \"\\n\")\nprint(str(round((elnino_missing_sum / elnino_data_sum) * 100, 2)), \"%\" \"\\n \\n \\n \\n\")\n# print correlation matrix\n# plt.figure(figsize=(12,12))\nplt.matshow(elnino.corr(), fignum=2)\nplt.title('Correlation Matrix El Nino')\nplt.colorbar()\nplt.gca().xaxis.tick_bottom()\nplt.xticks(range(12), list(elnino.columns), rotation='vertical')\nplt.yticks(range(12), list(elnino.columns))",
"The total number of null/missing values for each variable is: \n\nObservation 0\nYear 0\nMonth 0\nDay 0\nDate 0\nLatitude 0\nLongitude 0\nZonal Winds 25163\nMeridional Winds 25162\nHumidity 65761\nAir Temp 18237\nSea Surface Temp 17007\ndtype: int64 \n\nSo, there is : 151330 value missing \n \n \n \n \n\n Observation Year Month Day Date Latitude Longitude Zonal Winds \\\n0 1 80 3 7 800307 -0.02 -109.46 -6.8 \n1 2 80 3 8 800308 -0.02 -109.46 -4.9 \n2 3 80 3 9 800309 -0.02 -109.46 -4.5 \n3 4 80 3 10 800310 -0.02 -109.46 -3.8 \n4 5 80 3 11 800311 -0.02 -109.46 -4.2 \n5 6 80 3 12 800312 -0.02 -109.46 -4.4 \n6 7 80 3 13 800313 -0.02 -109.46 -3.2 \n7 8 80 3 14 800314 -0.02 -109.46 -3.1 \n8 9 80 3 15 800315 -0.02 -109.46 -3.0 \n9 10 80 3 16 800316 -0.02 -109.46 -1.2 \n\n Meridional Winds Humidity Air Temp Sea Surface Temp \n0 0.7 NaN 26.14 26.24 \n1 1.1 NaN 25.66 25.97 \n2 2.2 NaN 25.69 25.28 \n3 1.9 NaN 25.57 24.31 \n4 1.5 NaN 25.30 23.19 \n5 0.3 NaN 24.72 23.64 \n6 0.1 NaN 24.66 24.34 \n7 0.6 NaN 25.17 24.14 \n8 1.0 NaN 25.59 24.24 \n9 1.0 NaN 26.71 25.94 \nThe percentage of missing data is: \n\n7.62 %\n \n \n \n\n"
],
[
"elnino.drop(columns=['Observation']).corr().round(2)",
"_____no_output_____"
],
[
"elnino.hist(\n column=['Latitude', 'Longitude', 'Zonal Winds', 'Meridional Winds', 'Humidity', 'Air Temp', 'Sea Surface Temp'],\n figsize=(14, 14))",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e77b6272e0090fb5999e23ad8af23d1ea5876169 | 11,035 | ipynb | Jupyter Notebook | Naive_Bayes_&_SVM_tfidfVectorizer.ipynb | panayiotiska/Sentiment-Analysis-Reviews | 0c67cee5120fed74e2cb2897f0d57eeef66cff2a | [
"MIT"
] | null | null | null | Naive_Bayes_&_SVM_tfidfVectorizer.ipynb | panayiotiska/Sentiment-Analysis-Reviews | 0c67cee5120fed74e2cb2897f0d57eeef66cff2a | [
"MIT"
] | null | null | null | Naive_Bayes_&_SVM_tfidfVectorizer.ipynb | panayiotiska/Sentiment-Analysis-Reviews | 0c67cee5120fed74e2cb2897f0d57eeef66cff2a | [
"MIT"
] | null | null | null | 35.031746 | 541 | 0.56928 | [
[
[
"<table>\n <tr><td>\n <a href=\"https://nbviewer.jupyter.org/github/panayiotiska/Jupyter-Sentiment-Analysis-Video-games-reviews/blob/master/Vectorization.ipynb\">\n <img alt=\"start\" src=\"figures/button_previous.jpg\" width= 70% height= 70%>\n </td><td>\n <a href=\"https://nbviewer.jupyter.org/github/panayiotiska/Jupyter-Sentiment-Analysis-Video-games-reviews/blob/master/Index.ipynb\">\n <img alt=\"start\" src=\"figures/button_table-of-contents.jpg\" width= 70% height= 70%>\n </td><td>\n <a href=\"https://nbviewer.jupyter.org/github/panayiotiska/Jupyter-Sentiment-Analysis-Video-games-reviews/blob/master/Naive_Bayes_&_SVM_HashingVectorizer_Binary.ipynb\">\n <img alt=\"start\" src=\"figures/button_next.jpg\" width= 70% height= 70%>\n </td></tr>\n</table>",
"_____no_output_____"
],
[
"## Naive Bayes and Support vector machines using TF-IDF vectorizer\nIn this model both algorithms, Naive Bayes and Support Vector Machines are tested using the TF-IDF vectorizer, implemented in the scikit-learn's library. This vectorizer transforms a count matrix to a normalized tf-idf representation. Tf means term-frequency while tf-idf means term-frequency times inverse document-frequency. IDF is used to scale down the impact of tokens that occur very frequently in a given corpus and that are hence empirically less informative than features that occur in a small fraction of the training corpus.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom nltk.tokenize import word_tokenize\nfrom nltk import pos_tag\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer\nfrom sklearn.preprocessing import LabelEncoder\nfrom collections import defaultdict\nfrom nltk.corpus import wordnet as wn\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn import model_selection, naive_bayes, svm\nfrom sklearn.metrics import accuracy_score\nfrom collections import Counter\n\n#[1] Importing dataset\n\ndataset = pd.read_json(r\"C:\\Users\\Panos\\Desktop\\Dissert\\Code\\Video_Games_5.json\", lines=True, encoding='latin-1')\ndataset = dataset[['reviewText','overall']]\n\n#[2] Reduce number of classes\n\nratings = []\nfor index,entry in enumerate(dataset['overall']):\n if entry == 1.0 or entry == 2.0:\n ratings.append(-1)\n elif entry == 3.0:\n ratings.append(0)\n elif entry == 4.0 or entry == 5.0:\n ratings.append(1)",
"_____no_output_____"
],
[
"#[3] Cleaning the text\n\nimport re\nimport nltk\nnltk.download('stopwords')\nfrom nltk.corpus import stopwords\n\ncorpus = []\nfor i in range(0, len(dataset)):\n review = re.sub('[^a-zA-Z]', ' ', dataset['reviewText'][i])\n review = review.lower()\n review = review.split()\n review = [word for word in review if not word in set(stopwords.words('english'))]\n review = ' '.join(review)\n corpus.append(review)",
"[nltk_data] Downloading package stopwords to\n[nltk_data] C:\\Users\\Panos\\AppData\\Roaming\\nltk_data...\n[nltk_data] Package stopwords is already up-to-date!\n"
],
[
"#[4] Prepare Train and Test Data sets\n \nTrain_X, Test_X, Train_Y, Test_Y = model_selection.train_test_split(corpus,ratings,test_size=0.3)\n\nprint(Counter(Train_Y).values()) # counts the elements' frequency",
"dict_values([19749, 122618, 19879])\n"
],
[
"#[5] Encoding\n\nEncoder = LabelEncoder()\nTrain_Y = Encoder.fit_transform(Train_Y)\nTest_Y = Encoder.fit_transform(Test_Y)",
"_____no_output_____"
],
[
"#[6] Word Vectorization\n \nTfidf_vect = TfidfVectorizer(max_features=10000)\nTfidf_vect.fit(corpus)\nTrain_X_Tfidf = Tfidf_vect.transform(Train_X)\nTest_X_Tfidf = Tfidf_vect.transform(Test_X)\n\n# the vocabulary that it has learned from the corpus\n#print(Tfidf_vect.vocabulary_)\n\n# the vectorized data\n#print(Train_X_Tfidf)",
"_____no_output_____"
],
[
"#[7] Use the Naive Bayes Algorithms to Predict the outcome\n\n# fit the training dataset on the NB classifier\nNaive = naive_bayes.MultinomialNB()\nNaive.fit(Train_X_Tfidf,Train_Y)\n# predict the labels on validation dataset\npredictions_NB = Naive.predict(Test_X_Tfidf)\n\n# Use accuracy_score function to get the accuracy\nprint(\"-----------------------Naive Bayes------------------------\\n\")\nprint(\"Naive Bayes Accuracy Score -> \",accuracy_score(predictions_NB, Test_Y)*100)\n# Making the confusion matrix\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(Test_Y, predictions_NB)\nprint(\"\\n\",cm,\"\\n\")\n# Printing a classification report of different metrics\nfrom sklearn.metrics import classification_report\nmy_tags = ['Positive','Neutral','Negative']\nprint(classification_report(Test_Y, predictions_NB,target_names=my_tags))\n\n# Export reports to files for later visualizations\nreport_NB = classification_report(Test_Y, predictions_NB,target_names=my_tags, output_dict=True)\nreport_NB_df = pd.DataFrame(report_NB).transpose()\nreport_NB_df.to_csv(r'NB_report_TFIDFVect.csv', index = True, float_format=\"%.3f\")",
"-----------------------Naive Bayes------------------------\n\nNaive Bayes Accuracy Score -> 77.46282394224409\n\n [[ 1544 120 6973]\n [ 174 118 8234]\n [ 121 49 52201]] \n\n precision recall f1-score support\n\n Positive 0.84 0.18 0.29 8637\n Neutral 0.41 0.01 0.03 8526\n Negative 0.77 1.00 0.87 52371\n\n accuracy 0.77 69534\n macro avg 0.68 0.40 0.40 69534\nweighted avg 0.74 0.77 0.70 69534\n\n"
],
[
"#[8] Use the Support Vector Machine Algorithms to Predict the outcome\n\n# Classifier - Algorithm - SVM\n# fit the training dataset on the classifier\nSVM = svm.SVC(C=1.0, kernel='linear', degree=3, gamma='auto')\nSVM.fit(Train_X_Tfidf,Train_Y)\n# predict the labels on validation dataset\npredictions_SVM = SVM.predict(Test_X_Tfidf)\n\n# Use accuracy_score function to get the accuracy\nprint(\"-----------------Support Vector Machine CM------------------\\n\")\nprint(\"Accuracy Score -> \",accuracy_score(predictions_SVM, Test_Y)*100)\ncm = confusion_matrix(Test_Y, predictions_SVM)\n# Making the confusion matrix\nprint(\"\\n\",cm,\"\\n\")\n# Printing a classification report of different metrics\nprint(classification_report(Test_Y, predictions_SVM,target_names=my_tags))\n\n# Export reports to files for later visualizations\nreport_SVM = classification_report(Test_Y, predictions_SVM,target_names=my_tags, output_dict=True)\nreport_SVM_df = pd.DataFrame(report_SVM).transpose()\nreport_SVM_df.to_csv(r'SVM_report_TFIDFVect.csv', index = True, float_format=\"%.3f\")",
"-----------------Support Vector Machine CM------------------\n\nAccuracy Score -> 82.27485834268128\n\n [[ 4993 761 2883]\n [ 1365 1399 5762]\n [ 880 674 50817]] \n\n precision recall f1-score support\n\n Positive 0.69 0.58 0.63 8637\n Neutral 0.49 0.16 0.25 8526\n Negative 0.85 0.97 0.91 52371\n\n accuracy 0.82 69534\n macro avg 0.68 0.57 0.59 69534\nweighted avg 0.79 0.82 0.79 69534\n\n"
]
],
[
[
"<a href=\"https://nbviewer.jupyter.org/github/panayiotiska/Jupyter-Sentiment-Analysis-Video-games-reviews/blob/master/Naive_Bayes_&_SVM_HashingVectorizer_Binary.ipynb\">\n <img alt=\"start\" src=\"figures/button_next.jpg\">",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
e77b70c3174e8bb2c3551c94cd666252294c8627 | 350,619 | ipynb | Jupyter Notebook | 06-sdks/exercises/python_SDK/CARTO_Frames.ipynb | oss-spanish-geoserver/carto-workshop | a005afc1da6aa3f818e175b861519b789311b5e4 | [
"CC-BY-4.0"
] | 88 | 2017-01-23T12:29:54.000Z | 2022-01-09T12:24:01.000Z | 06-sdks/exercises/python_SDK/CARTO_Frames.ipynb | LarsMallien/carto-workshop | a005afc1da6aa3f818e175b861519b789311b5e4 | [
"CC-BY-4.0"
] | 45 | 2017-01-11T15:59:13.000Z | 2021-06-01T22:22:42.000Z | 06-sdks/exercises/python_SDK/CARTO_Frames.ipynb | LarsMallien/carto-workshop | a005afc1da6aa3f818e175b861519b789311b5e4 | [
"CC-BY-4.0"
] | 44 | 2017-01-25T13:35:45.000Z | 2021-12-30T03:32:57.000Z | 282.301932 | 279,726 | 0.888788 | [
[
[
"# CARTO frames workshop\n\nFull details at the [documentation](https://cartodb.github.io/cartoframes/) page. I'm using the `master` branch installed using\n\n```sh\npip install cartoframes jupyter seaborn\n```\n",
"_____no_output_____"
]
],
[
[
"import cartoframes\nfrom cartoframes import Credentials, CartoContext\nimport pandas as pd\nimport os",
"_____no_output_____"
]
],
[
[
"## Load the credentials",
"_____no_output_____"
]
],
[
[
"try:\n cc = cartoframes.CartoContext()\n print('Getting the credentials from a previous session')\nexcept Exception as e:\n print('Getting the credentials from your environment or here')\n BASEURL = os.environ.get('CARTO_API_URL','https://jsanz.carto.com') # <-- replace with your username or set up the envvar\n APIKEY = os.environ.get('CARTO_API_KEY',False) # <-- replace False with your CARTO API key or set up the envvar\n if BASEURL and APIKEY:\n creds = Credentials(base_url=BASEURL,key=APIKEY)\n creds.save()\n cc = cartoframes.CartoContext()\n else:\n print('Set up your environment!')\n ",
"Getting the credentials from a previous session\n"
]
],
[
[
"## Load the typical `Populated Places` dataset from CARTO",
"_____no_output_____"
],
[
"You can import this dataset from the Data Library",
"_____no_output_____"
]
],
[
[
"df = cc.read('populated_places')\ndf.head()",
"_____no_output_____"
]
],
[
[
"## It's a Pandas data frame\n\nYou can get the `featurecla` field counts",
"_____no_output_____"
]
],
[
[
"df.groupby('featurecla').featurecla.count()",
"_____no_output_____"
]
],
[
[
"## Run SQL queries",
"_____no_output_____"
]
],
[
[
"cc.query('''\nSELECT featurecla,count(*) as counts\nFROM populated_places\nGROUP BY featurecla\n''')",
"_____no_output_____"
]
],
[
[
"## Draw graphics using Seaborn\n\nMore about seaborn [here](https://seaborn.pydata.org/)",
"_____no_output_____"
]
],
[
[
"import seaborn as sns\nimport matplotlib.pyplot as plt\nimport warnings\nwarnings.filterwarnings('ignore')\n%matplotlib inline",
"_____no_output_____"
],
[
"f, ax = plt.subplots(figsize=(16, 6))\nsns.boxplot(x=\"featurecla\", y=\"pop_max\", data=df);",
"_____no_output_____"
]
],
[
[
"## Render your tables from CARTO",
"_____no_output_____"
]
],
[
[
"from cartoframes import Layer, styling\nl = Layer(\n 'populated_places', \n color={'column': 'featurecla','scheme': styling.prism(9)},\n size ={'column': 'pop_max','bin_method':'quantiles','bins' : 4, 'min': 3, 'max':10}\n)\ncc.map(layers=l, interactive=True)",
"_____no_output_____"
]
],
[
[
"## Render queries from CARTO",
"_____no_output_____"
]
],
[
[
"from cartoframes import QueryLayer\nlines = QueryLayer(\n '''\n WITH capitals as (\n select * \n from populated_places \n where featurecla like 'Admin-0 capital'\n )\n select pp.cartodb_id,\n pp.pop_max,\n ST_MakeLine(c.the_geom,pp.the_geom) as the_geom,\n ST_MakeLine(c.the_geom_webmercator,pp.the_geom_webmercator) as the_geom_webmercator\n from populated_places pp join capitals c on pp.adm0_a3 = c.adm0_a3\n where c.adm0_a3 = 'ESP'\n ''', \n color = {'column':'pop_max','scheme':styling.sunset(bins=3)},\n size ={'column': 'pop_max','bin_method':'quantiles','bins' : 4, 'min': 3, 'max':10}\n)\ncc.map(layers=lines, interactive=True,zoom=4, lat=36.19, lng=-6.79)",
"_____no_output_____"
],
[
"points = QueryLayer(\n '''\n select *\n from populated_places\n where adm0_a3 = 'ESP'\n ''', \n color = {'column':'pop_max','scheme':styling.sunset(bins=3)},\n size = {'column':'pop_max','bin_method':'quantiles','bins' : 4, 'min': 3, 'max':7}\n)\ncc.map(layers=[lines,points], interactive=True,zoom=4, lat=36.19, lng=-6.79)",
"_____no_output_____"
]
],
[
[
"## Crazy queries\n\nYou can render fancy queries, more details [here](https://gist.github.com/jsanz/8aeb48a274e3b787ca57)",
"_____no_output_____"
]
],
[
[
"query = '''\nwith -- first data\ndata as (\n SELECT * \n FROM jsanz.ne_10m_populated_places_simple_7 \n WHERE \n(megacity >= 0.5 AND megacity <= 1) AND featurecla IN ('Admin-0 capital','Admin-1 region capital','Admin-0 region capital','Admin-0 capital alt')\n), -- from dubai\norigin as (\n select *\n from jsanz.ne_10m_populated_places_simple_7\n where cartodb_id = 7263\n), -- cities closer to 14000 Km\ndests as (\n select d.*,\n ST_Distance(\n o.the_geom::geography,\n d.the_geom::geography\n )::int distance\n from data d, origin o\n where \n ST_DWithin( o.the_geom::geography, d.the_geom::geography, 14000000 ) \n),\ngeoms as (\n select \n dests.cartodb_id, dests.name, dests.adm0name, dests.distance,\n st_transform(\n st_segmentize(\n st_makeline(\n origin.the_geom,\n dests.the_geom\n )::geography,\n 10000\n )::geometry,\n 3857) the_geom_webmercator\n from origin,dests\n)\nselect *, st_transform(the_geom_webmercator,4326) as the_geom from geoms\n'''\ncc.map(QueryLayer(query), interactive=False, zoom=2, lat=19.9, lng=29.5)",
"_____no_output_____"
]
],
[
[
"## Create a new table on CARTO",
"_____no_output_____"
]
],
[
[
"df_spain = df[(df['adm0_a3'] == 'ESP')]\ndf_spain['name'].head()",
"_____no_output_____"
],
[
"cc.write(df_spain, 'places_spain', overwrite=True)",
"Table successfully written to CARTO: https://jsanz.carto.com/dataset/places_spain\n"
],
[
"cc.query('SELECT DISTINCT adm0_a3 FROM places_spain')",
"_____no_output_____"
]
],
[
[
"## Modify schema and data",
"_____no_output_____"
],
[
"Drop a column",
"_____no_output_____"
]
],
[
[
"df_spain = df[(df['adm0_a3'] == 'ESP')]\ndf_spain = df_spain.drop('adm0_a3', 1)\ncc.write(df_spain, 'places_spain', overwrite=True)",
"Table successfully written to CARTO: https://jsanz.carto.com/dataset/places_spain\n"
],
[
"try:\n cc.query('SELECT DISTINCT adm0_a3 FROM places_spain')\nexcept Exception as e:\n print(e)",
"['column \"adm0_a3\" does not exist']\n"
]
],
[
[
"Add `València` as an alternate name for the city of `Valencia`",
"_____no_output_____"
]
],
[
[
"vlc_id = df_spain[df.apply(lambda x: x['name'] == 'Valencia', axis=1)].index.values[0]\ndf_spain = df_spain.set_value(vlc_id,'cityalt','València')",
"_____no_output_____"
],
[
"# THE FUTURE\n# cc.sync(df_spain,'places_spain')\n\n# THE PRESENT\ncc.write(df_spain, 'places_spain', overwrite=True)",
"Table successfully written to CARTO: https://jsanz.carto.com/dataset/places_spain\n"
],
[
"cc.query('''SELECT name,cityalt from places_spain WHERE cartodb_id = {}'''.format(vlc_id))",
"_____no_output_____"
]
],
[
[
"## Delete the table",
"_____no_output_____"
]
],
[
[
"cc.delete('places_spain')",
"_____no_output_____"
]
],
[
[
"## But there's more\n\nTake a look into the documentation for other functions related with CARTO Data Observatory. All these features are is still under active development, things may change quickly.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e77b91ecacf41913d662e6fad718d00af239238d | 19,687 | ipynb | Jupyter Notebook | TrainGridSearch.ipynb | ibnuhajar/TrainingMachineLearning | a955f2364cffeea8abd6ff0acfbce92b712ab2d6 | [
"MIT"
] | null | null | null | TrainGridSearch.ipynb | ibnuhajar/TrainingMachineLearning | a955f2364cffeea8abd6ff0acfbce92b712ab2d6 | [
"MIT"
] | null | null | null | TrainGridSearch.ipynb | ibnuhajar/TrainingMachineLearning | a955f2364cffeea8abd6ff0acfbce92b712ab2d6 | [
"MIT"
] | null | null | null | 98.929648 | 13,850 | 0.813075 | [
[
[
"<a href=\"https://colab.research.google.com/github/ibnuhajar/TrainingMachineLearning/blob/main/TrainGridSearch.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport os \nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.svm import SVR\n\nos.listdir('sample_data')\n\ndata = pd.read_csv('sample_data/Salary_Data.csv')\n\nX = data['YearsExperience']\ny = data['Salary']\nX = X[:,np.newaxis]\n\nmodel = SVR()\n\nparameters = {\n 'kernel' : ['rbf'],\n 'C' : [1000,10000,100000],\n 'gamma' : [0.5,0.05,0.005]\n}\n\ngrid_search = GridSearchCV(model,parameters)\ngrid_search.fit(X,y)",
"/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:18: FutureWarning: Support for multi-dimensional indexing (e.g. `obj[:, None]`) is deprecated and will be removed in a future version. Convert to a numpy array before indexing instead.\n"
],
[
"print(grid_search.best_params_)",
"{'C': 100000, 'gamma': 0.005, 'kernel': 'rbf'}\n"
],
[
"model_baru = SVR(C=100000, gamma=0.005, kernel='rbf')\nmodel_baru.fit(X,y)",
"_____no_output_____"
],
[
"plt.scatter(X,y)\nplt.plot(X, model_baru.predict(X))",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
e77b9c752854e4697523d17e59e97015c92e5f9d | 158,029 | ipynb | Jupyter Notebook | week1/week1_MultilabelClassification.ipynb | Gurupradeep/Natural-Language-Processing | e032ca4fabf5cc0e0ccb2f8a5f1578b709e5b99f | [
"MIT"
] | 5 | 2019-05-07T15:51:16.000Z | 2021-02-08T21:06:52.000Z | week1/week1_MultilabelClassification.ipynb | Gurupradeep/Natural-Language-Processing | e032ca4fabf5cc0e0ccb2f8a5f1578b709e5b99f | [
"MIT"
] | 9 | 2020-01-28T22:29:39.000Z | 2022-02-09T23:57:24.000Z | week1/week1_MultilabelClassification.ipynb | Gurupradeep/Natural-Language-Processing | e032ca4fabf5cc0e0ccb2f8a5f1578b709e5b99f | [
"MIT"
] | 7 | 2020-02-07T18:04:20.000Z | 2021-12-16T13:09:30.000Z | 76.787658 | 46,484 | 0.756317 | [
[
[
"# Predict tags on StackOverflow with linear models",
"_____no_output_____"
],
[
"In this assignment you will learn how to predict tags for posts from [StackOverflow](https://stackoverflow.com). To solve this task you will use multilabel classification approach.\n\n### Libraries\n\nIn this task you will need the following libraries:\n- [Numpy](http://www.numpy.org) — a package for scientific computing.\n- [Pandas](https://pandas.pydata.org) — a library providing high-performance, easy-to-use data structures and data analysis tools for the Python\n- [scikit-learn](http://scikit-learn.org/stable/index.html) — a tool for data mining and data analysis.\n- [NLTK](http://www.nltk.org) — a platform to work with natural language.",
"_____no_output_____"
],
[
"### Data\n\nThe following cell will download all data required for this assignment into the folder `week1/data`.",
"_____no_output_____"
]
],
[
[
"! wget https://raw.githubusercontent.com/hse-aml/natural-language-processing/master/setup_google_colab.py -O setup_google_colab.py\nimport setup_google_colab\nsetup_google_colab.setup_week1()",
"\nRedirecting output to ‘wget-log’.\n"
],
[
"import sys\nsys.path.append(\"..\")\nfrom common.download_utils import download_week1_resources\n\ndownload_week1_resources()",
"**************************************************\ntrain.tsv\n**************************************************\nvalidation.tsv\n**************************************************\ntest.tsv\n**************************************************\ntext_prepare_tests.tsv\n"
],
[
"",
"_____no_output_____"
]
],
[
[
"### Grading\nWe will create a grader instance below and use it to collect your answers. Note that these outputs will be stored locally inside grader and will be uploaded to platform only after running submitting function in the last part of this assignment. If you want to make partial submission, you can run that cell any time you want.",
"_____no_output_____"
]
],
[
[
"from grader import Grader",
"_____no_output_____"
],
[
"grader = Grader()",
"_____no_output_____"
]
],
[
[
"### Text preprocessing",
"_____no_output_____"
],
[
"For this and most of the following assignments you will need to use a list of stop words. It can be downloaded from *nltk*:",
"_____no_output_____"
]
],
[
[
"import nltk\nnltk.download('stopwords')\nfrom nltk.corpus import stopwords",
"[nltk_data] Downloading package stopwords to /root/nltk_data...\n[nltk_data] Unzipping corpora/stopwords.zip.\n"
]
],
[
[
"In this task you will deal with a dataset of post titles from StackOverflow. You are provided a split to 3 sets: *train*, *validation* and *test*. All corpora (except for *test*) contain titles of the posts and corresponding tags (100 tags are available). The *test* set is provided for Coursera's grading and doesn't contain answers. Upload the corpora using *pandas* and look at the data:",
"_____no_output_____"
]
],
[
[
"from ast import literal_eval\nimport pandas as pd\nimport numpy as np",
"_____no_output_____"
],
[
"def read_data(filename):\n data = pd.read_csv(filename, sep='\\t')\n data['tags'] = data['tags'].apply(literal_eval)\n return data",
"_____no_output_____"
],
[
"train = read_data('data/train.tsv')\nvalidation = read_data('data/validation.tsv')\ntest = pd.read_csv('data/test.tsv', sep='\\t')",
"_____no_output_____"
],
[
"train.head()",
"_____no_output_____"
]
],
[
[
"As you can see, *title* column contains titles of the posts and *tags* column contains the tags. It could be noticed that a number of tags for a post is not fixed and could be as many as necessary.",
"_____no_output_____"
],
[
"For a more comfortable usage, initialize *X_train*, *X_val*, *X_test*, *y_train*, *y_val*.",
"_____no_output_____"
]
],
[
[
"X_train, y_train = train['title'].values, train['tags'].values\nX_val, y_val = validation['title'].values, validation['tags'].values\nX_test = test['title'].values",
"_____no_output_____"
]
],
[
[
"One of the most known difficulties when working with natural data is that it's unstructured. For example, if you use it \"as is\" and extract tokens just by splitting the titles by whitespaces, you will see that there are many \"weird\" tokens like *3.5?*, *\"Flip*, etc. To prevent the problems, it's usually useful to prepare the data somehow. In this task you'll write a function, which will be also used in the other assignments. \n\n**Task 1 (TextPrepare).** Implement the function *text_prepare* following the instructions. After that, run the function *test_test_prepare* to test it on tiny cases and submit it to Coursera.",
"_____no_output_____"
]
],
[
[
"import re",
"_____no_output_____"
],
[
"REPLACE_BY_SPACE_RE = re.compile('[/(){}\\[\\]\\|@,;]')\nBAD_SYMBOLS_RE = re.compile('[^0-9a-z #+_]')\nSTOPWORDS = set(stopwords.words('english'))\n\ndef text_prepare(text):\n \"\"\"\n text: a string\n \n return: modified initial string\n \"\"\"\n text = text.lower() # lowercase text\n text = re.sub(REPLACE_BY_SPACE_RE, \" \", text)# replace REPLACE_BY_SPACE_RE symbols by space in text\n text = re.sub(BAD_SYMBOLS_RE, \"\", text)# delete symbols which are in BAD_SYMBOLS_RE from text\n # print(text)\n text = ' '.join([word for word in text.split() if word not in STOPWORDS]) # Remove stopwords\n # print(text)\n text = text.strip()\n #text = re.sub(' +', ' ', text)\n # print(text)\n return text",
"_____no_output_____"
],
[
"def test_text_prepare():\n examples = [\"SQL Server - any equivalent of Excel's CHOOSE function?\",\n \"How to free c++ memory vector<int> * arr?\"]\n answers = [\"sql server equivalent excels choose function\", \n \"free c++ memory vectorint arr\"]\n for ex, ans in zip(examples, answers):\n if text_prepare(ex) != ans:\n return \"Wrong answer for the case: '%s'\" % ex\n return 'Basic tests are passed.'",
"_____no_output_____"
],
[
"print(test_text_prepare())",
"Basic tests are passed.\n"
]
],
[
[
"Run your implementation for questions from file *text_prepare_tests.tsv* to earn the points.",
"_____no_output_____"
]
],
[
[
"prepared_questions = []\nfor line in open('data/text_prepare_tests.tsv', encoding='utf-8'):\n line = text_prepare(line.strip())\n prepared_questions.append(line)\ntext_prepare_results = '\\n'.join(prepared_questions)\n\ngrader.submit_tag('TextPrepare', text_prepare_results)",
"Current answer for task TextPrepare is:\n sqlite php readonly\ncreating multiple textboxes dynamically\nself one prefer javascript\nsave php date...\n"
]
],
[
[
"Now we can preprocess the titles using function *text_prepare* and making sure that the headers don't have bad symbols:",
"_____no_output_____"
]
],
[
[
"X_train = [text_prepare(x) for x in X_train]\nX_val = [text_prepare(x) for x in X_val]\nX_test = [text_prepare(x) for x in X_test]",
"_____no_output_____"
],
[
"X_train[:3]",
"_____no_output_____"
]
],
[
[
"For each tag and for each word calculate how many times they occur in the train corpus. \n\n**Task 2 (WordsTagsCount).** Find 3 most popular tags and 3 most popular words in the train data and submit the results to earn the points.",
"_____no_output_____"
]
],
[
[
"from collections import Counter\n# Dictionary of all tags from train corpus with their counts.\ntags_counts = Counter() #{}\n# Dictionary of all words from train corpus with their counts.\nwords_counts = Counter() #{}\n\n######################################\n######### YOUR CODE HERE #############\n######################################\n# print(X_train[:3], y_train[:3])\nfor sentence in X_train:\n for word in sentence.split():\n # print(word)\n words_counts[word] += 1\n\nfor l in y_train:\n for tag in l:\n tags_counts[tag] += 1",
"_____no_output_____"
]
],
[
[
"We are assuming that *tags_counts* and *words_counts* are dictionaries like `{'some_word_or_tag': frequency}`. After applying the sorting procedure, results will be look like this: `[('most_popular_word_or_tag', frequency), ('less_popular_word_or_tag', frequency), ...]`. The grader gets the results in the following format (two comma-separated strings with line break):\n\n tag1,tag2,tag3\n word1,word2,word3\n\nPay attention that in this assignment you should not submit frequencies or some additional information.",
"_____no_output_____"
]
],
[
[
"most_common_tags = sorted(tags_counts.items(), key=lambda x: x[1], reverse=True)[:3]\nmost_common_words = sorted(words_counts.items(), key=lambda x: x[1], reverse=True)[:3]\n\ngrader.submit_tag('WordsTagsCount', '%s\\n%s' % (','.join(tag for tag, _ in most_common_tags), \n ','.join(word for word, _ in most_common_words)))",
"Current answer for task WordsTagsCount is:\n javascript,c#,java\nusing,php,java...\n"
]
],
[
[
"### Transforming text to a vector\n\nMachine Learning algorithms work with numeric data and we cannot use the provided text data \"as is\". There are many ways to transform text data to numeric vectors. In this task you will try to use two of them.\n\n#### Bag of words\n\nOne of the well-known approaches is a *bag-of-words* representation. To create this transformation, follow the steps:\n1. Find *N* most popular words in train corpus and numerate them. Now we have a dictionary of the most popular words.\n2. For each title in the corpora create a zero vector with the dimension equals to *N*.\n3. For each text in the corpora iterate over words which are in the dictionary and increase by 1 the corresponding coordinate.\n\nLet's try to do it for a toy example. Imagine that we have *N* = 4 and the list of the most popular words is \n\n ['hi', 'you', 'me', 'are']\n\nThen we need to numerate them, for example, like this: \n\n {'hi': 0, 'you': 1, 'me': 2, 'are': 3}\n\nAnd we have the text, which we want to transform to the vector:\n\n 'hi how are you'\n\nFor this text we create a corresponding zero vector \n\n [0, 0, 0, 0]\n \nAnd iterate over all words, and if the word is in the dictionary, we increase the value of the corresponding position in the vector:\n\n 'hi': [1, 0, 0, 0]\n 'how': [1, 0, 0, 0] # word 'how' is not in our dictionary\n 'are': [1, 0, 0, 1]\n 'you': [1, 1, 0, 1]\n\nThe resulting vector will be \n\n [1, 1, 0, 1]\n \nImplement the described encoding in the function *my_bag_of_words* with the size of the dictionary equals to 5000. To find the most common words use train data. You can test your code using the function *test_my_bag_of_words*.",
"_____no_output_____"
]
],
[
[
"most_common_words = sorted(words_counts.items(), key=lambda x: x[1], reverse=True)[:5002]",
"_____no_output_____"
],
[
"WORDS_TO_INDEX = {p[0]:i for i,p in enumerate(most_common_words[:5])}",
"_____no_output_____"
],
[
"print(WORDS_TO_INDEX)",
"{'using': 0, 'php': 1, 'java': 2, 'file': 3, 'javascript': 4}\n"
],
[
"DICT_SIZE = 5000\nWORDS_TO_INDEX = {p[0]:i for i,p in enumerate(most_common_words[:DICT_SIZE])}\nINDEX_TO_WORDS = {WORDS_TO_INDEX[k]:k for k in WORDS_TO_INDEX}\nALL_WORDS = WORDS_TO_INDEX.keys()\n\ndef my_bag_of_words(text, words_to_index, dict_size):\n \"\"\"\n text: a string\n dict_size: size of the dictionary\n \n return a vector which is a bag-of-words representation of 'text'\n \"\"\"\n result_vector = np.zeros(dict_size)\n ######################################\n ######### YOUR CODE HERE #############\n ######################################\n for word in text.split():\n if word in words_to_index :\n result_vector[words_to_index[word]] +=1\n return result_vector",
"_____no_output_____"
],
[
"def test_my_bag_of_words():\n words_to_index = {'hi': 0, 'you': 1, 'me': 2, 'are': 3}\n examples = ['hi how are you']\n answers = [[1, 1, 0, 1]]\n for ex, ans in zip(examples, answers):\n if (my_bag_of_words(ex, words_to_index, 4) != ans).any():\n return \"Wrong answer for the case: '%s'\" % ex\n return 'Basic tests are passed.'",
"_____no_output_____"
],
[
"print(test_my_bag_of_words())",
"Basic tests are passed.\n"
]
],
[
[
"Now apply the implemented function to all samples (this might take up to a minute):",
"_____no_output_____"
]
],
[
[
"from scipy import sparse as sp_sparse",
"_____no_output_____"
],
[
"X_train_mybag = sp_sparse.vstack([sp_sparse.csr_matrix(my_bag_of_words(text, WORDS_TO_INDEX, DICT_SIZE)) for text in X_train])\nX_val_mybag = sp_sparse.vstack([sp_sparse.csr_matrix(my_bag_of_words(text, WORDS_TO_INDEX, DICT_SIZE)) for text in X_val])\nX_test_mybag = sp_sparse.vstack([sp_sparse.csr_matrix(my_bag_of_words(text, WORDS_TO_INDEX, DICT_SIZE)) for text in X_test])\nprint('X_train shape ', X_train_mybag.shape)\nprint('X_val shape ', X_val_mybag.shape)\nprint('X_test shape ', X_test_mybag.shape)",
"X_train shape (100000, 5000)\nX_val shape (30000, 5000)\nX_test shape (20000, 5000)\n"
]
],
[
[
"As you might notice, we transform the data to sparse representation, to store the useful information efficiently. There are many [types](https://docs.scipy.org/doc/scipy/reference/sparse.html) of such representations, however sklearn algorithms can work only with [csr](https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html#scipy.sparse.csr_matrix) matrix, so we will use this one.",
"_____no_output_____"
],
[
"**Task 3 (BagOfWords).** For the 11th row in *X_train_mybag* find how many non-zero elements it has. In this task the answer (variable *non_zero_elements_count*) should be a number, e.g. 20.",
"_____no_output_____"
]
],
[
[
"row = X_train_mybag[10].toarray()[0]\nnon_zero_elements_count = np.count_nonzero(row)\n\ngrader.submit_tag('BagOfWords', str(non_zero_elements_count))",
"Current answer for task BagOfWords is:\n 7...\n"
],
[
"len(row)",
"_____no_output_____"
]
],
[
[
"#### TF-IDF\n\nThe second approach extends the bag-of-words framework by taking into account total frequencies of words in the corpora. It helps to penalize too frequent words and provide better features space. \n\nImplement function *tfidf_features* using class [TfidfVectorizer](http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html) from *scikit-learn*. Use *train* corpus to train a vectorizer. Don't forget to take a look into the arguments that you can pass to it. We suggest that you filter out too rare words (occur less than in 5 titles) and too frequent words (occur more than in 90% of the titles). Also, use bigrams along with unigrams in your vocabulary. ",
"_____no_output_____"
]
],
[
[
"from sklearn.feature_extraction.text import TfidfVectorizer",
"_____no_output_____"
],
[
"def tfidf_features(X_train, X_val, X_test):\n \"\"\"\n X_train, X_val, X_test — samples \n return TF-IDF vectorized representation of each sample and vocabulary\n \"\"\"\n # Create TF-IDF vectorizer with a proper parameters choice\n # Fit the vectorizer on the train set\n # Transform the train, test, and val sets and return the result\n \n \n tfidf_vectorizer = TfidfVectorizer(token_pattern='(\\S+)', min_df=5, max_df=0.9, ngram_range=(1,2))\n \n ######################################\n ######### YOUR CODE HERE #############\n ######################################\n \n tfidf_vectorizer.fit(X_train)\n X_train = tfidf_vectorizer.transform(X_train)\n X_val = tfidf_vectorizer.transform(X_val)\n X_test = tfidf_vectorizer.transform(X_test)\n \n return X_train, X_val, X_test, tfidf_vectorizer.vocabulary_",
"_____no_output_____"
]
],
[
[
"Once you have done text preprocessing, always have a look at the results. Be very careful at this step, because the performance of future models will drastically depend on it. \n\nIn this case, check whether you have c++ or c# in your vocabulary, as they are obviously important tokens in our tags prediction task:",
"_____no_output_____"
]
],
[
[
"X_train_tfidf, X_val_tfidf, X_test_tfidf, tfidf_vocab = tfidf_features(X_train, X_val, X_test)\ntfidf_reversed_vocab = {i:word for word,i in tfidf_vocab.items()}",
"_____no_output_____"
],
[
"print('c++' in tfidf_vocab)\nprint('c#' in tfidf_vocab)",
"True\nTrue\n"
]
],
[
[
"If you can't find it, we need to understand how did it happen that we lost them? It happened during the built-in tokenization of TfidfVectorizer. Luckily, we can influence on this process. Get back to the function above and use '(\\S+)' regexp as a *token_pattern* in the constructor of the vectorizer. ",
"_____no_output_____"
],
[
"Now, use this transormation for the data and check again.",
"_____no_output_____"
]
],
[
[
"######### YOUR CODE HERE #############\nprint('c++' in tfidf_vocab)\nprint('c#' in tfidf_vocab)",
"True\nTrue\n"
]
],
[
[
"### MultiLabel classifier\n\nAs we have noticed before, in this task each example can have multiple tags. To deal with such kind of prediction, we need to transform labels in a binary form and the prediction will be a mask of 0s and 1s. For this purpose it is convenient to use [MultiLabelBinarizer](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MultiLabelBinarizer.html) from *sklearn*.",
"_____no_output_____"
]
],
[
[
"from sklearn.preprocessing import MultiLabelBinarizer",
"_____no_output_____"
],
[
"mlb = MultiLabelBinarizer(classes=sorted(tags_counts.keys()))\ny_train = mlb.fit_transform(y_train)\ny_val = mlb.fit_transform(y_val)",
"_____no_output_____"
],
[
"y_train[0]",
"_____no_output_____"
]
],
[
[
"Implement the function *train_classifier* for training a classifier. In this task we suggest to use One-vs-Rest approach, which is implemented in [OneVsRestClassifier](http://scikit-learn.org/stable/modules/generated/sklearn.multiclass.OneVsRestClassifier.html) class. In this approach *k* classifiers (= number of tags) are trained. As a basic classifier, use [LogisticRegression](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html). It is one of the simplest methods, but often it performs good enough in text classification tasks. It might take some time, because a number of classifiers to train is large.",
"_____no_output_____"
]
],
[
[
"from sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.linear_model import LogisticRegression, RidgeClassifier",
"_____no_output_____"
],
[
"def train_classifier(X_train, y_train, C = 1.0, penalty = 'l2'):\n \"\"\"\n X_train, y_train — training data\n \n return: trained classifier\n \"\"\"\n \n # Create and fit LogisticRegression wraped into OneVsRestClassifier.\n\n ######################################\n ######### YOUR CODE HERE #############\n ######################################\n lr = LogisticRegression(C=C, penalty=penalty)\n oneVsRest = OneVsRestClassifier(lr)\n oneVsRest.fit(X_train, y_train)\n \n return oneVsRest\n ",
"_____no_output_____"
]
],
[
[
"Train the classifiers for different data transformations: *bag-of-words* and *tf-idf*.",
"_____no_output_____"
]
],
[
[
"classifier_mybag = train_classifier(X_train_mybag, y_train)\nclassifier_tfidf = train_classifier(X_train_tfidf, y_train)",
"_____no_output_____"
]
],
[
[
"Now you can create predictions for the data. You will need two types of predictions: labels and scores.",
"_____no_output_____"
]
],
[
[
"y_val_predicted_labels_mybag = classifier_mybag.predict(X_val_mybag)\ny_val_predicted_scores_mybag = classifier_mybag.decision_function(X_val_mybag)\n\ny_val_predicted_labels_tfidf = classifier_tfidf.predict(X_val_tfidf)\ny_val_predicted_scores_tfidf = classifier_tfidf.decision_function(X_val_tfidf)",
"_____no_output_____"
]
],
[
[
"Now take a look at how classifier, which uses TF-IDF, works for a few examples:",
"_____no_output_____"
]
],
[
[
"y_val_pred_inversed = mlb.inverse_transform(y_val_predicted_labels_tfidf)\ny_val_inversed = mlb.inverse_transform(y_val)\nfor i in range(3):\n print('Title:\\t{}\\nTrue labels:\\t{}\\nPredicted labels:\\t{}\\n\\n'.format(\n X_val[i],\n ','.join(y_val_inversed[i]),\n ','.join(y_val_pred_inversed[i])\n ))",
"Title:\todbc_exec always fail\nTrue labels:\tphp,sql\nPredicted labels:\t\n\n\nTitle:\taccess base classes variable within child class\nTrue labels:\tjavascript\nPredicted labels:\t\n\n\nTitle:\tcontenttype application json required rails\nTrue labels:\truby,ruby-on-rails\nPredicted labels:\tjson,ruby-on-rails\n\n\n"
]
],
[
[
"Now, we would need to compare the results of different predictions, e.g. to see whether TF-IDF transformation helps or to try different regularization techniques in logistic regression. For all these experiments, we need to setup evaluation procedure. ",
"_____no_output_____"
],
[
"### Evaluation\n\nTo evaluate the results we will use several classification metrics:\n - [Accuracy](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html)\n - [F1-score](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html)\n - [Area under ROC-curve](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_auc_score.html)\n - [Area under precision-recall curve](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.average_precision_score.html#sklearn.metrics.average_precision_score) \n \nMake sure you are familiar with all of them. How would you expect the things work for the multi-label scenario? Read about micro/macro/weighted averaging following the sklearn links provided above.",
"_____no_output_____"
]
],
[
[
"from sklearn.metrics import accuracy_score\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import roc_auc_score \nfrom sklearn.metrics import average_precision_score\nfrom sklearn.metrics import recall_score",
"_____no_output_____"
]
],
[
[
"Implement the function *print_evaluation_scores* which calculates and prints to stdout:\n - *accuracy*\n - *F1-score macro/micro/weighted*\n - *Precision macro/micro/weighted*",
"_____no_output_____"
]
],
[
[
"def print_evaluation_scores(y_val, predicted):\n \n ######################################\n ######### YOUR CODE HERE #############\n ######################################\n #print('accuracy')\n print(f1_score(y_val, predicted, average = 'weighted'))\n \"\"\"\n #print('f1_score_macro')\n print(f1_score(y_val,predicted, average = 'macro')\n #print('f1_score_micro')\n print(f1_score(y_val,predicted, average = 'micro')\n #print('f1_score_weighted')\n print(f1_score(y_val,predicted, average = 'weighted')\n \"\"\"",
"_____no_output_____"
],
[
"print('Bag-of-words')\nprint_evaluation_scores(y_val, y_val_predicted_labels_mybag)\nprint('Tfidf')\nprint_evaluation_scores(y_val, y_val_predicted_labels_tfidf)",
"Bag-of-words\n0.6486956090682869\nTfidf\n0.6143558163126149\n"
]
],
[
[
"You might also want to plot some generalization of the [ROC curve](http://scikit-learn.org/stable/modules/model_evaluation.html#receiver-operating-characteristic-roc) for the case of multi-label classification. Provided function *roc_auc* can make it for you. The input parameters of this function are:\n - true labels\n - decision functions scores\n - number of classes",
"_____no_output_____"
]
],
[
[
"from metrics import roc_auc\n%matplotlib inline",
"_____no_output_____"
],
[
"n_classes = len(tags_counts)\nroc_auc(y_val, y_val_predicted_scores_mybag, n_classes)",
"_____no_output_____"
],
[
"n_classes = len(tags_counts)\nroc_auc(y_val, y_val_predicted_scores_tfidf, n_classes)",
"_____no_output_____"
]
],
[
[
"**Task 4 (MultilabelClassification).** Once we have the evaluation set up, we suggest that you experiment a bit with training your classifiers. We will use *F1-score weighted* as an evaluation metric. Our recommendation:\n- compare the quality of the bag-of-words and TF-IDF approaches and chose one of them.\n- for the chosen one, try *L1* and *L2*-regularization techniques in Logistic Regression with different coefficients (e.g. C equal to 0.1, 1, 10, 100).\n\nYou also could try other improvements of the preprocessing / model, if you want. ",
"_____no_output_____"
]
],
[
[
" def EvaluateDifferentModel(C, penalty) :\n classifier_mybag = train_classifier(X_train_mybag, y_train, C, penalty)\n classifier_tfidf = train_classifier(X_train_tfidf, y_train, C, penalty)\n y_val_predicted_labels_mybag = classifier_mybag.predict(X_val_mybag)\n y_val_predicted_scores_mybag = classifier_mybag.decision_function(X_val_mybag)\n y_val_predicted_labels_tfidf = classifier_tfidf.predict(X_val_tfidf)\n y_val_predicted_scores_tfidf = classifier_tfidf.decision_function(X_val_tfidf)\n \n print('Bag-of-words')\n print_evaluation_scores(y_val, y_val_predicted_labels_mybag)\n print('Tfidf')\n print_evaluation_scores(y_val, y_val_predicted_labels_tfidf)",
"_____no_output_____"
],
[
"EvaluateDifferentModel(0.1,'l1')\nEvaluateDifferentModel(0.1,'l2')\nEvaluateDifferentModel(1,'l1')\nEvaluateDifferentModel(1,'l2')\nEvaluateDifferentModel(10,'l1')\nEvaluateDifferentModel(10,'l2')\nEvaluateDifferentModel(100,'l1')\nEvaluateDifferentModel(100,'l2')",
"Bag-of-words\n0.6116000654698222\nTfidf\n"
],
[
"######################################\n######### YOUR CODE HERE #############\n######################################\nclassifier_tfidf = train_classifier(X_train_tfidf, y_train, C=1.0, penalty='l1')\ny_test_predicted_labels_tfidf = classifier_tfidf.predict(X_test_tfidf)",
"_____no_output_____"
]
],
[
[
"When you are happy with the quality, create predictions for *test* set, which you will submit to Coursera.",
"_____no_output_____"
]
],
[
[
"test_predictions = y_test_predicted_labels_tfidf ######### YOUR CODE HERE #############\ntest_pred_inversed = mlb.inverse_transform(test_predictions)\n\ntest_predictions_for_submission = '\\n'.join('%i\\t%s' % (i, ','.join(row)) for i, row in enumerate(test_pred_inversed))\ngrader.submit_tag('MultilabelClassification', test_predictions_for_submission)",
"Current answer for task MultilabelClassification is:\n 0\tmysql,php\n1\tjavascript\n2\t\n3\tjavascript,jquery\n4\tandroid,java\n5\tphp,xml\n6\tjson\n7\tjava,swing\n8\tpytho...\n"
]
],
[
[
"### Analysis of the most important features",
"_____no_output_____"
],
[
"Finally, it is usually a good idea to look at the features (words or n-grams) that are used with the largest weigths in your logistic regression model.",
"_____no_output_____"
],
[
"Implement the function *print_words_for_tag* to find them. Get back to sklearn documentation on [OneVsRestClassifier](http://scikit-learn.org/stable/modules/generated/sklearn.multiclass.OneVsRestClassifier.html) and [LogisticRegression](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html) if needed.",
"_____no_output_____"
]
],
[
[
"def print_words_for_tag(classifier, tag, tags_classes, index_to_words, all_words):\n \"\"\"\n classifier: trained classifier\n tag: particular tag\n tags_classes: a list of classes names from MultiLabelBinarizer\n index_to_words: index_to_words transformation\n all_words: all words in the dictionary\n \n return nothing, just print top 5 positive and top 5 negative words for current tag\n \"\"\"\n print('Tag:\\t{}'.format(tag))\n \n # Extract an estimator from the classifier for the given tag.\n # Extract feature coefficients from the estimator. \n \n ######################################\n ######### YOUR CODE HERE #############\n ######################################\n idx = tags_classes.index(tag)\n coef=classifier_tfidf.coef_[idx]\n cd = {i:coef[i] for i in range(len(coef))}\n scd=sorted(cd.items(), key=lambda x: x[1], reverse=True)\n \n top_positive_words = [index_to_words[k[0]] for k in scd[:5]] # top-5 words sorted by the coefficiens.\n top_negative_words = [index_to_words[k[0]] for k in scd[-5:]] # bottom-5 words sorted by the coefficients.\n print('Top positive words:\\t{}'.format(', '.join(top_positive_words)))\n print('Top negative words:\\t{}\\n'.format(', '.join(top_negative_words)))",
"_____no_output_____"
],
[
"print_words_for_tag(classifier_tfidf, 'c', mlb.classes, tfidf_reversed_vocab, ALL_WORDS)\nprint_words_for_tag(classifier_tfidf, 'c++', mlb.classes, tfidf_reversed_vocab, ALL_WORDS)\nprint_words_for_tag(classifier_tfidf, 'linux', mlb.classes, tfidf_reversed_vocab, ALL_WORDS)",
"Tag:\tc\nTop positive words:\tc, malloc, scanf, printf, gcc\nTop negative words:\tc#, javascript, python, php, java\n\nTag:\tc++\nTop positive words:\tc++, qt, boost, mfc, opencv\nTop negative words:\tc#, javascript, python, php, java\n\nTag:\tlinux\nTop positive words:\tlinux, ubuntu, c, address, signal\nTop negative words:\tmethod, array, jquery, c#, javascript\n\n"
]
],
[
[
"### Authorization & Submission\nTo submit assignment parts to Cousera platform, please, enter your e-mail and token into variables below. You can generate token on this programming assignment page. <b>Note:</b> Token expires 30 minutes after generation.",
"_____no_output_____"
]
],
[
[
"grader.status()",
"You want to submit these parts:\nTask TextPrepare:\n sqlite php readonly\ncreating multiple textboxes dynamically\nself one prefer javascript\nsave php date...\nTask WordsTagsCount:\n javascript,c#,java\nusing,php,java...\nTask BagOfWords:\n 7...\nTask MultilabelClassification:\n 0\tphp\n1\tjavascript,jquery\n2\t\n3\tjavascript,jquery\n4\tandroid,java\n5\tphp,xml\n6\tjson\n7\tjava\n8\tpython\n9\th...\n"
],
[
"STUDENT_EMAIL = \"[email protected]\"# EMAIL \nSTUDENT_TOKEN = \"X6mGG4lxlszGyk9H\"# TOKEN \ngrader.status()",
"You want to submit these parts:\nTask TextPrepare:\n sqlite php readonly\ncreating multiple textboxes dynamically\nself one prefer javascript\nsave php date...\nTask WordsTagsCount:\n javascript,c#,java\nusing,php,java...\nTask BagOfWords:\n 7...\nTask MultilabelClassification:\n 0\tmysql,php\n1\tjavascript\n2\t\n3\tjavascript,jquery\n4\tandroid,java\n5\tphp,xml\n6\tjson\n7\tjava,swing\n8\tpytho...\n"
]
],
[
[
"If you want to submit these answers, run cell below",
"_____no_output_____"
]
],
[
[
"grader.submit(STUDENT_EMAIL, STUDENT_TOKEN)",
"Submitted to Coursera platform. See results on assignment page!\n"
],
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e77ba10eb828a64ecc448ef1fbfe6bf6d4daf8c6 | 139,747 | ipynb | Jupyter Notebook | examples/notebooks/mednist_tutorial.ipynb | erexhepa/MONAI | 98210a266db428a0769fde260dda0703b1c4ea95 | [
"Apache-2.0"
] | 1 | 2020-07-09T08:03:22.000Z | 2020-07-09T08:03:22.000Z | examples/notebooks/mednist_tutorial.ipynb | erexhepa/MONAI | 98210a266db428a0769fde260dda0703b1c4ea95 | [
"Apache-2.0"
] | null | null | null | examples/notebooks/mednist_tutorial.ipynb | erexhepa/MONAI | 98210a266db428a0769fde260dda0703b1c4ea95 | [
"Apache-2.0"
] | null | null | null | 258.790741 | 90,244 | 0.91212 | [
[
[
"# Medical Image Classification Tutorial with the MedNIST Dataset",
"_____no_output_____"
],
[
"## Introduction\n\nIn this tutorial, we introduce an end-to-end training and evaluation example based on the MedNIST dataset. \nWe'll go through the following steps:\n<ul>\n <li>Create a dataset for training and testing</li>\n <li>Use MONAI transforms to pre-process data</li>\n <li>Use the DenseNet from MONAI for classification</li>\n <li>Train the model with a PyTorch program</li>\n <li>Evaluate on test dataset</li>\n</ul>\n",
"_____no_output_____"
],
[
"### Get the dataset\n\nThe MedNIST dataset was gathered from several sets from [TCIA](https://wiki.cancerimagingarchive.net/display/Public/Data+Usage+Policies+and+Restrictions), [the RSNA Bone Age Challenge](http://rsnachallenges.cloudapp.net/competitions/4), and [the NIH Chest X-ray dataset](https://cloud.google.com/healthcare/docs/resources/public-datasets/nih-chest).\n\nThe dataset is kindly made available by [Dr. Bradley J. Erickson M.D., Ph.D.](https://www.mayo.edu/research/labs/radiology-informatics/overview) (Department of Radiology, Mayo Clinic)\nunder the Creative Commons [CC BY-SA 4.0 license](https://creativecommons.org/licenses/by-sa/4.0/).\nIf you use the MedNIST dataset, please acknowledge the source, e.g.\n\nhttps://github.com/Project-MONAI/MONAI/blob/master/examples/notebooks/mednist_tutorial.ipynb.\n\nThe following commands download and unzip the dataset (~60MB).",
"_____no_output_____"
]
],
[
[
"!wget https://www.dropbox.com/s/5wwskxctvcxiuea/MedNIST.tar.gz",
"--2020-07-08 08:50:05-- https://www.dropbox.com/s/5wwskxctvcxiuea/MedNIST.tar.gz\nResolving www.dropbox.com (www.dropbox.com)... 162.125.82.1, 2620:100:6032:1::a27d:5201\nConnecting to www.dropbox.com (www.dropbox.com)|162.125.82.1|:443... connected.\nHTTP request sent, awaiting response... 301 Moved Permanently\nLocation: /s/raw/5wwskxctvcxiuea/MedNIST.tar.gz [following]\n--2020-07-08 08:50:06-- https://www.dropbox.com/s/raw/5wwskxctvcxiuea/MedNIST.tar.gz\nReusing existing connection to www.dropbox.com:443.\nHTTP request sent, awaiting response... 302 Found\nLocation: https://ucf87fb94e4db4ff0b5ccc540922.dl.dropboxusercontent.com/cd/0/inline/A7HBOQSNhIryWngUdvVYJp10xl3-oBB6NC8AZiARn_xABLNWkN207TajHxk58Ip4H655VkH7ZyFPZ5RQLXhZeiYcTaFdedviIQwHthxlcyXlmETFkjkq33izoJNsfzMyxB4/file# [following]\n--2020-07-08 08:50:06-- https://ucf87fb94e4db4ff0b5ccc540922.dl.dropboxusercontent.com/cd/0/inline/A7HBOQSNhIryWngUdvVYJp10xl3-oBB6NC8AZiARn_xABLNWkN207TajHxk58Ip4H655VkH7ZyFPZ5RQLXhZeiYcTaFdedviIQwHthxlcyXlmETFkjkq33izoJNsfzMyxB4/file\nResolving ucf87fb94e4db4ff0b5ccc540922.dl.dropboxusercontent.com (ucf87fb94e4db4ff0b5ccc540922.dl.dropboxusercontent.com)... 162.125.82.15, 2620:100:6032:15::a27d:520f\nConnecting to ucf87fb94e4db4ff0b5ccc540922.dl.dropboxusercontent.com (ucf87fb94e4db4ff0b5ccc540922.dl.dropboxusercontent.com)|162.125.82.15|:443... connected.\nHTTP request sent, awaiting response... 302 Found\nLocation: /cd/0/inline2/A7GO7eRd3Z36tEsWL5q7uBPWWfH4XYskKV4J_cUOOvk20qhCJ7r5qqenLTjIbErbw_MKZsiYke9prAjXuzAkPf7VG0m_9cGwg9EuuicoXnVNM2-NRM-0S1Ht3CKp78eHKoFf1Pg279AwLF5U8IXQHWLIy9RxytnrvpNKYUdmU6z7wTV1msC3Gf5cMl_gDOOLfNlJWGKAYBOr-FppXC5OJ7vSdgAA4V7YHWXF_JkAA2xec5z5QbnFp6P5VVVKy0CybXlr6Wxhbuq9mNsSef-6_kXC40IRktZt2qOolxNzKqhTSPHNVGnvofwedtub8U8tFPLYikn4FbojtVSOmImlDzEtMgBVsBTnZT8lpnRY-e7yVA/file [following]\n--2020-07-08 08:50:07-- https://ucf87fb94e4db4ff0b5ccc540922.dl.dropboxusercontent.com/cd/0/inline2/A7GO7eRd3Z36tEsWL5q7uBPWWfH4XYskKV4J_cUOOvk20qhCJ7r5qqenLTjIbErbw_MKZsiYke9prAjXuzAkPf7VG0m_9cGwg9EuuicoXnVNM2-NRM-0S1Ht3CKp78eHKoFf1Pg279AwLF5U8IXQHWLIy9RxytnrvpNKYUdmU6z7wTV1msC3Gf5cMl_gDOOLfNlJWGKAYBOr-FppXC5OJ7vSdgAA4V7YHWXF_JkAA2xec5z5QbnFp6P5VVVKy0CybXlr6Wxhbuq9mNsSef-6_kXC40IRktZt2qOolxNzKqhTSPHNVGnvofwedtub8U8tFPLYikn4FbojtVSOmImlDzEtMgBVsBTnZT8lpnRY-e7yVA/file\nReusing existing connection to ucf87fb94e4db4ff0b5ccc540922.dl.dropboxusercontent.com:443.\nHTTP request sent, awaiting response... 200 OK\nLength: 61834679 (59M) [application/octet-stream]\nSaving to: ‘MedNIST.tar.gz’\n\nMedNIST.tar.gz 100%[===================>] 58.97M 12.4MB/s in 4.8s \n\n2020-07-08 08:50:13 (12.4 MB/s) - ‘MedNIST.tar.gz’ saved [61834679/61834679]\n\n"
],
[
"# unzip the '.tar.gz' file to the current directory\nimport tarfile\ndatafile = tarfile.open('MedNIST.tar.gz')\ndatafile.extractall()\ndatafile.close()",
"_____no_output_____"
],
[
"import os\nimport numpy as np\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\nimport torch\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader\n\nfrom monai.transforms import \\\n Compose, LoadPNG, AddChannel, ScaleIntensity, ToTensor, RandRotate, RandFlip, RandZoom\nfrom monai.networks.nets import densenet121\nfrom monai.metrics import compute_roc_auc\n\nnp.random.seed(0)",
"_____no_output_____"
]
],
[
[
"## Read image filenames from the dataset folders\nFirst of all, check the dataset files and show some statistics. \nThere are 6 folders in the dataset: Hand, AbdomenCT, CXR, ChestCT, BreastMRI, HeadCT, \nwhich should be used as the labels to train our classification model.",
"_____no_output_____"
]
],
[
[
"data_dir = './MedNIST/'\nclass_names = sorted([x for x in os.listdir(data_dir) if os.path.isdir(os.path.join(data_dir, x))])\nnum_class = len(class_names)\nimage_files = [[os.path.join(data_dir, class_names[i], x)\n for x in os.listdir(os.path.join(data_dir, class_names[i]))]\n for i in range(num_class)]\nnum_each = [len(image_files[i]) for i in range(num_class)]\nimage_files_list = []\nimage_class = []\nfor i in range(num_class):\n image_files_list.extend(image_files[i])\n image_class.extend([i] * num_each[i])\nnum_total = len(image_class)\nimage_width, image_height = Image.open(image_files_list[0]).size\n\nprint(f\"Total image count: {num_total}\")\nprint(f\"Image dimensions: {image_width} x {image_height}\")\nprint(f\"Label names: {class_names}\")\nprint(f\"Label counts: {num_each}\")",
"Total image count: 58954\nImage dimensions: 64 x 64\nLabel names: ['AbdomenCT', 'BreastMRI', 'CXR', 'ChestCT', 'Hand', 'HeadCT']\nLabel counts: [10000, 8954, 10000, 10000, 10000, 10000]\n"
]
],
[
[
"## Randomly pick images from the dataset to visualize and check",
"_____no_output_____"
]
],
[
[
"plt.subplots(3, 3, figsize=(8, 8))\nfor i,k in enumerate(np.random.randint(num_total, size=9)):\n im = Image.open(image_files_list[k])\n arr = np.array(im)\n plt.subplot(3, 3, i + 1)\n plt.xlabel(class_names[image_class[k]])\n plt.imshow(arr, cmap='gray', vmin=0, vmax=255)\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Prepare training, validation and test data lists\nRandomly select 10% of the dataset as validation and 10% as test.",
"_____no_output_____"
]
],
[
[
"val_frac = 0.1\ntest_frac = 0.1\ntrain_x = list()\ntrain_y = list()\nval_x = list()\nval_y = list()\ntest_x = list()\ntest_y = list()\n\nfor i in range(num_total):\n rann = np.random.random()\n if rann < val_frac:\n val_x.append(image_files_list[i])\n val_y.append(image_class[i])\n elif rann < test_frac + val_frac:\n test_x.append(image_files_list[i])\n test_y.append(image_class[i])\n else:\n train_x.append(image_files_list[i])\n train_y.append(image_class[i])\n\nprint(f\"Training count: {len(train_x)}, Validation count: {len(val_x)}, Test count: {len(test_x)}\")",
"Training count: 47156, Validation count: 5913, Test count: 5885\n"
]
],
[
[
"## Define MONAI transforms, Dataset and Dataloader to pre-process data",
"_____no_output_____"
]
],
[
[
"train_transforms = Compose([\n LoadPNG(image_only=True),\n AddChannel(),\n ScaleIntensity(),\n RandRotate(range_x=15, prob=0.5, keep_size=True),\n RandFlip(spatial_axis=0, prob=0.5),\n RandZoom(min_zoom=0.9, max_zoom=1.1, prob=0.5),\n ToTensor()\n])\n\nval_transforms = Compose([\n LoadPNG(image_only=True),\n AddChannel(),\n ScaleIntensity(),\n ToTensor()\n])",
"_____no_output_____"
],
[
"class MedNISTDataset(Dataset):\n\n def __init__(self, image_files, labels, transforms):\n self.image_files = image_files\n self.labels = labels\n self.transforms = transforms\n\n def __len__(self):\n return len(self.image_files)\n\n def __getitem__(self, index):\n return self.transforms(self.image_files[index]), self.labels[index]\n\ntrain_ds = MedNISTDataset(train_x, train_y, train_transforms)\ntrain_loader = DataLoader(train_ds, batch_size=300, shuffle=True, num_workers=10)\n\nval_ds = MedNISTDataset(val_x, val_y, val_transforms)\nval_loader = DataLoader(val_ds, batch_size=300, num_workers=10)\n\ntest_ds = MedNISTDataset(test_x, test_y, val_transforms)\ntest_loader = DataLoader(test_ds, batch_size=300, num_workers=10)",
"_____no_output_____"
]
],
[
[
"## Define network and optimizer\n1. Set learning rate for how much the model is updated per batch.\n2. Set total epoch number, as we have shuffle and random transforms, so the training data of every epoch is different. \n And as this is just a get start tutorial, let's just train 4 epochs. \n If train 10 epochs, the model can achieve 100% accuracy on test dataset.\n3. Use DenseNet from MONAI and move to GPU devide, this DenseNet can support both 2D and 3D classification tasks.\n4. Use Adam optimizer.",
"_____no_output_____"
]
],
[
[
"device = torch.device('cuda:0')\nmodel = densenet121(\n spatial_dims=2,\n in_channels=1,\n out_channels=num_class\n).to(device)\nloss_function = torch.nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.parameters(), 1e-5)\nepoch_num = 4\nval_interval = 1",
"_____no_output_____"
]
],
[
[
"## Model training\nExecute a typical PyTorch training that run epoch loop and step loop, and do validation after every epoch. \nWill save the model weights to file if got best validation accuracy.",
"_____no_output_____"
]
],
[
[
"best_metric = -1\nbest_metric_epoch = -1\nepoch_loss_values = list()\nmetric_values = list()\nfor epoch in range(epoch_num):\n print('-' * 10)\n print(f\"epoch {epoch + 1}/{epoch_num}\")\n model.train()\n epoch_loss = 0\n step = 0\n for batch_data in train_loader:\n step += 1\n inputs, labels = batch_data[0].to(device), batch_data[1].to(device)\n optimizer.zero_grad()\n outputs = model(inputs)\n loss = loss_function(outputs, labels)\n loss.backward()\n optimizer.step()\n epoch_loss += loss.item()\n print(f\"{step}/{len(train_ds) // train_loader.batch_size}, train_loss: {loss.item():.4f}\")\n epoch_len = len(train_ds) // train_loader.batch_size\n epoch_loss /= step\n epoch_loss_values.append(epoch_loss)\n print(f\"epoch {epoch + 1} average loss: {epoch_loss:.4f}\")\n\n if (epoch + 1) % val_interval == 0:\n model.eval()\n with torch.no_grad():\n y_pred = torch.tensor([], dtype=torch.float32, device=device)\n y = torch.tensor([], dtype=torch.long, device=device)\n for val_data in val_loader:\n val_images, val_labels = val_data[0].to(device), val_data[1].to(device)\n y_pred = torch.cat([y_pred, model(val_images)], dim=0)\n y = torch.cat([y, val_labels], dim=0)\n auc_metric = compute_roc_auc(y_pred, y, to_onehot_y=True, softmax=True)\n metric_values.append(auc_metric)\n acc_value = torch.eq(y_pred.argmax(dim=1), y)\n acc_metric = acc_value.sum().item() / len(acc_value)\n if auc_metric > best_metric:\n best_metric = auc_metric\n best_metric_epoch = epoch + 1\n torch.save(model.state_dict(), 'best_metric_model.pth')\n print('saved new best metric model')\n print(f\"current epoch: {epoch + 1} current AUC: {auc_metric:.4f}\"\n f\" current accuracy: {acc_metric:.4f} best AUC: {best_metric:.4f}\"\n f\" at epoch: {best_metric_epoch}\")\nprint(f\"train completed, best_metric: {best_metric:.4f} at epoch: {best_metric_epoch}\")",
"_____no_output_____"
]
],
[
[
"## Plot the loss and metric",
"_____no_output_____"
]
],
[
[
"plt.figure('train', (12, 6))\nplt.subplot(1, 2, 1)\nplt.title('Epoch Average Loss')\nx = [i + 1 for i in range(len(epoch_loss_values))]\ny = epoch_loss_values\nplt.xlabel('epoch')\nplt.plot(x, y)\nplt.subplot(1, 2, 2)\nplt.title('Val AUC')\nx = [val_interval * (i + 1) for i in range(len(metric_values))]\ny = metric_values\nplt.xlabel('epoch')\nplt.plot(x, y)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Evaluate the model on test dataset\nAfter training and validation, we already got the best model on validation test. \nWe need to evaluate the model on test dataset to check whether it's robust and not over-fitting. \nWe'll use these predictions to generate a classification report.",
"_____no_output_____"
]
],
[
[
"model.load_state_dict(torch.load('best_metric_model.pth'))\nmodel.eval()\ny_true = list()\ny_pred = list()\nwith torch.no_grad():\n for test_data in test_loader:\n test_images, test_labels = test_data[0].to(device), test_data[1].to(device)\n pred = model(test_images).argmax(dim=1)\n for i in range(len(pred)):\n y_true.append(test_labels[i].item())\n y_pred.append(pred[i].item())",
"_____no_output_____"
],
[
"! pip install -U sklearn",
"_____no_output_____"
],
[
"from sklearn.metrics import classification_report\nprint(classification_report(y_true, y_pred, target_names=class_names, digits=4))",
" precision recall f1-score support\n\n Hand 0.9969 0.9928 0.9948 969\n AbdomenCT 0.9839 0.9924 0.9881 1046\n CXR 0.9948 0.9969 0.9958 961\n ChestCT 0.9969 1.0000 0.9985 980\n BreastMRI 1.0000 0.9905 0.9952 944\n HeadCT 0.9929 0.9919 0.9924 985\n\n accuracy 0.9941 5885\n macro avg 0.9942 0.9941 0.9941 5885\nweighted avg 0.9941 0.9941 0.9941 5885\n\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
e77bb0fce7b550a205dac3b6c82703f9e56a7acf | 55,687 | ipynb | Jupyter Notebook | lab.ipynb | bhaveshwadhwani/CarND-TensorFlow-Lab | 02d15508030d474ffbf7f81fbe2a9842fd21cd94 | [
"MIT"
] | null | null | null | lab.ipynb | bhaveshwadhwani/CarND-TensorFlow-Lab | 02d15508030d474ffbf7f81fbe2a9842fd21cd94 | [
"MIT"
] | null | null | null | lab.ipynb | bhaveshwadhwani/CarND-TensorFlow-Lab | 02d15508030d474ffbf7f81fbe2a9842fd21cd94 | [
"MIT"
] | null | null | null | 69.783208 | 25,408 | 0.748182 | [
[
[
"<h1 align=\"center\">TensorFlow Neural Network Lab</h1>",
"_____no_output_____"
],
[
"<img src=\"image/notmnist.png\">\nIn this lab, you'll use all the tools you learned from *Introduction to TensorFlow* to label images of English letters! The data you are using, <a href=\"http://yaroslavvb.blogspot.com/2011/09/notmnist-dataset.html\">notMNIST</a>, consists of images of a letter from A to J in differents font.\n\nThe above images are a few examples of the data you'll be training on. After training the network, you will compare your prediction model against test data. Your goal, by the end of this lab, is to make predictions against that test set with at least an 80% accuracy. Let's jump in!",
"_____no_output_____"
],
[
"To start this lab, you first need to import all the necessary modules. Run the code below. If it runs successfully, it will print \"`All modules imported`\".",
"_____no_output_____"
]
],
[
[
"import hashlib\nimport os\nimport pickle\nfrom urllib.request import urlretrieve\n\nimport numpy as np\nfrom PIL import Image\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.utils import resample\nfrom tqdm import tqdm\nfrom zipfile import ZipFile\n\nprint('All modules imported.')",
"All modules imported.\n"
]
],
[
[
"The notMNIST dataset is too large for many computers to handle. It contains 500,000 images for just training. You'll be using a subset of this data, 15,000 images for each label (A-J).",
"_____no_output_____"
]
],
[
[
"def download(url, file):\n \"\"\"\n Download file from <url>\n :param url: URL to file\n :param file: Local file path\n \"\"\"\n if not os.path.isfile(file):\n print('Downloading ' + file + '...')\n urlretrieve(url, file)\n print('Download Finished')\n\n# Download the training and test dataset.\ndownload('https://s3.amazonaws.com/udacity-sdc/notMNIST_train.zip', 'notMNIST_train.zip')\ndownload('https://s3.amazonaws.com/udacity-sdc/notMNIST_test.zip', 'notMNIST_test.zip')\n\n# Make sure the files aren't corrupted\nassert hashlib.md5(open('notMNIST_train.zip', 'rb').read()).hexdigest() == 'c8673b3f28f489e9cdf3a3d74e2ac8fa',\\\n 'notMNIST_train.zip file is corrupted. Remove the file and try again.'\nassert hashlib.md5(open('notMNIST_test.zip', 'rb').read()).hexdigest() == '5d3c7e653e63471c88df796156a9dfa9',\\\n 'notMNIST_test.zip file is corrupted. Remove the file and try again.'\n\n# Wait until you see that all files have been downloaded.\nprint('All files downloaded.')",
"All files downloaded.\n"
],
[
"def uncompress_features_labels(file):\n \"\"\"\n Uncompress features and labels from a zip file\n :param file: The zip file to extract the data from\n \"\"\"\n features = []\n labels = []\n\n with ZipFile(file) as zipf:\n # Progress Bar\n filenames_pbar = tqdm(zipf.namelist(), unit='files')\n \n # Get features and labels from all files\n for filename in filenames_pbar:\n # Check if the file is a directory\n if not filename.endswith('/'):\n with zipf.open(filename) as image_file:\n image = Image.open(image_file)\n image.load()\n # Load image data as 1 dimensional array\n # We're using float32 to save on memory space\n feature = np.array(image, dtype=np.float32).flatten()\n\n # Get the the letter from the filename. This is the letter of the image.\n label = os.path.split(filename)[1][0]\n\n features.append(feature)\n labels.append(label)\n return np.array(features), np.array(labels)\n\n# Get the features and labels from the zip files\ntrain_features, train_labels = uncompress_features_labels('notMNIST_train.zip')\ntest_features, test_labels = uncompress_features_labels('notMNIST_test.zip')\n\n# Limit the amount of data to work with a docker container\ndocker_size_limit = 150000\ntrain_features, train_labels = resample(train_features, train_labels, n_samples=docker_size_limit)\n\n# Set flags for feature engineering. This will prevent you from skipping an important step.\nis_features_normal = False\nis_labels_encod = False\n\n# Wait until you see that all features and labels have been uncompressed.\nprint('All features and labels uncompressed.')",
"100%|██████████| 210001/210001 [00:49<00:00, 4284.12files/s]\n100%|██████████| 10001/10001 [00:02<00:00, 4503.60files/s]\n"
]
],
[
[
"<img src=\"image/mean_variance.png\" style=\"height: 75%;width: 75%; position: relative; right: 5%\">\n\n## Problem 1\nThe first problem involves normalizing the features for your training and test data.\n\nImplement Min-Max scaling in the `normalize()` function to a range of `a=0.1` and `b=0.9`. After scaling, the values of the pixels in the input data should range from 0.1 to 0.9.\n\nSince the raw notMNIST image data is in [grayscale](https://en.wikipedia.org/wiki/Grayscale), the current values range from a min of 0 to a max of 255.\n\nMin-Max Scaling:\n$\nX'=a+{\\frac {\\left(X-X_{\\min }\\right)\\left(b-a\\right)}{X_{\\max }-X_{\\min }}}\n$\n\n*If you're having trouble solving problem 1, you can view the solution [here](https://github.com/udacity/CarND-TensorFlow-Lab/blob/master/solutions.ipynb).*",
"_____no_output_____"
]
],
[
[
"from sklearn.preprocessing import MinMaxScaler\n\n# Problem 1 - Implement Min-Max scaling for grayscale image data\ndef normalize_grayscale(image_data):\n \"\"\"\n Normalize the image data with Min-Max scaling to a range of [0.1, 0.9]\n :param image_data: The image data to be normalized\n :return: Normalized image data\n \"\"\"\n # TODO: Implement Min-Max scaling for grayscale image data\n a = 0.1\n b = 0.9\n grayscale_min = 0\n grayscale_max = 255\n return a + ( ( (image_data - grayscale_min)*(b - a) )/( grayscale_max - grayscale_min ) )\n\n### DON'T MODIFY ANYTHING BELOW ###\n# Test Cases\nnp.testing.assert_array_almost_equal(\n normalize_grayscale(np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 255])),\n [0.1, 0.103137254902, 0.106274509804, 0.109411764706, 0.112549019608, 0.11568627451, 0.118823529412, 0.121960784314,\n 0.125098039216, 0.128235294118, 0.13137254902, 0.9],\n decimal=3)\nnp.testing.assert_array_almost_equal(\n normalize_grayscale(np.array([0, 1, 10, 20, 30, 40, 233, 244, 254,255])),\n [0.1, 0.103137254902, 0.13137254902, 0.162745098039, 0.194117647059, 0.225490196078, 0.830980392157, 0.865490196078,\n 0.896862745098, 0.9])\n\nif not is_features_normal:\n train_features = normalize_grayscale(train_features)\n test_features = normalize_grayscale(test_features)\n is_features_normal = True\n\nprint('Tests Passed!')",
"Tests Passed!\n"
],
[
"if not is_labels_encod:\n # Turn labels into numbers and apply One-Hot Encoding\n encoder = LabelBinarizer()\n encoder.fit(train_labels)\n train_labels = encoder.transform(train_labels)\n test_labels = encoder.transform(test_labels)\n\n # Change to float32, so it can be multiplied against the features in TensorFlow, which are float32\n train_labels = train_labels.astype(np.float32)\n test_labels = test_labels.astype(np.float32)\n is_labels_encod = True\n\nprint('Labels One-Hot Encoded')",
"Labels One-Hot Encoded\n"
],
[
"assert is_features_normal, 'You skipped the step to normalize the features'\nassert is_labels_encod, 'You skipped the step to One-Hot Encode the labels'\n\n# Get randomized datasets for training and validation\ntrain_features, valid_features, train_labels, valid_labels = train_test_split(\n train_features,\n train_labels,\n test_size=0.05,\n random_state=832289)\n\nprint('Training features and labels randomized and split.')",
"Training features and labels randomized and split.\n"
],
[
"# Save the data for easy access\npickle_file = 'notMNIST.pickle'\nif not os.path.isfile(pickle_file):\n print('Saving data to pickle file...')\n try:\n with open('notMNIST.pickle', 'wb') as pfile:\n pickle.dump(\n {\n 'train_dataset': train_features,\n 'train_labels': train_labels,\n 'valid_dataset': valid_features,\n 'valid_labels': valid_labels,\n 'test_dataset': test_features,\n 'test_labels': test_labels,\n },\n pfile, pickle.HIGHEST_PROTOCOL)\n except Exception as e:\n print('Unable to save data to', pickle_file, ':', e)\n raise\n\nprint('Data cached in pickle file.')",
"Data cached in pickle file.\n"
]
],
[
[
"# Checkpoint\nAll your progress is now saved to the pickle file. If you need to leave and comeback to this lab, you no longer have to start from the beginning. Just run the code block below and it will load all the data and modules required to proceed.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n\n# Load the modules\nimport pickle\nimport math\n\nimport numpy as np\nimport tensorflow as tf\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\n\n# Reload the data\npickle_file = 'notMNIST.pickle'\nwith open(pickle_file, 'rb') as f:\n pickle_data = pickle.load(f)\n train_features = pickle_data['train_dataset']\n train_labels = pickle_data['train_labels']\n valid_features = pickle_data['valid_dataset']\n valid_labels = pickle_data['valid_labels']\n test_features = pickle_data['test_dataset']\n test_labels = pickle_data['test_labels']\n del pickle_data # Free up memory\n\n\nprint('Data and modules loaded.')",
"_____no_output_____"
]
],
[
[
"<img src=\"image/weight_biases.png\" style=\"height: 60%;width: 60%; position: relative; right: 10%\">\n\n## Problem 2\nFor the neural network to train on your data, you need the following <a href=\"https://www.tensorflow.org/api_docs/python/tf/dtypes/DType\">float32</a> tensors:\n\n - `features`\n - Placeholder tensor for feature data (`train_features`/`valid_features`/`test_features`)\n - `labels`\n - Placeholder tensor for label data (`train_labels`/`valid_labels`/`test_labels`)\n - `weights`\n - Variable Tensor with random numbers from a truncated normal distribution.\n - See <a href=\"https://www.tensorflow.org/api_docs/python/tf/random/truncated_normal\">`tf.truncated_normal()` documentation</a> for help.\n - `biases`\n - Variable Tensor with all zeros.\n - See <a href=\"https://www.tensorflow.org/api_docs/python/tf/zeros\"> `tf.zeros()` documentation</a> for help.\n\n*If you're having trouble solving problem 2, review \"TensorFlow Linear Function\" section of the class. If that doesn't help, the solution for this problem is available [here](https://github.com/udacity/CarND-TensorFlow-Lab/blob/master/solutions.ipynb).*",
"_____no_output_____"
]
],
[
[
"features_count = 784\nlabels_count = 10\n\n# TODO: Set the features and labels tensors\nfeatures = tf.placeholder(tf.float32) \nlabels = tf.placeholder(tf.float32) \n\n# TODO: Set the weights and biases tensors\nweights = tf.Variable(tf.truncated_normal((features_count,labels_count)))\nbiases = tf.Variable(tf.zeros(labels_count))\n\n\n\n### DON'T MODIFY ANYTHING BELOW ###\n\n#Test Cases\nfrom tensorflow.python.ops.variables import Variable\n\nassert features._op.name.startswith('Placeholder'), 'features must be a placeholder'\nassert labels._op.name.startswith('Placeholder'), 'labels must be a placeholder'\nassert isinstance(weights, Variable), 'weights must be a TensorFlow variable'\nassert isinstance(biases, Variable), 'biases must be a TensorFlow variable'\n\nassert features._shape == None or (\\\n features._shape.dims[0].value is None and\\\n features._shape.dims[1].value in [None, 784]), 'The shape of features is incorrect'\nassert labels._shape == None or (\\\n labels._shape.dims[0].value is None and\\\n labels._shape.dims[1].value in [None, 10]), 'The shape of labels is incorrect'\nassert weights._variable._shape == (784, 10), 'The shape of weights is incorrect'\nassert biases._variable._shape == (10), 'The shape of biases is incorrect'\n\nassert features._dtype == tf.float32, 'features must be type float32'\nassert labels._dtype == tf.float32, 'labels must be type float32'\n\n# Feed dicts for training, validation, and test session\ntrain_feed_dict = {features: train_features, labels: train_labels}\nvalid_feed_dict = {features: valid_features, labels: valid_labels}\ntest_feed_dict = {features: test_features, labels: test_labels}\n\n# Linear Function WX + b\nlogits = tf.matmul(features, weights) + biases\n\nprediction = tf.nn.softmax(logits)\n\n# Cross entropy\ncross_entropy = -tf.reduce_sum(labels * tf.log(prediction), axis=1)\n\n# some students have encountered challenges using this function, and have resolved issues\n# using https://www.tensorflow.org/api_docs/python/tf/nn/softmax_cross_entropy_with_logits\n# please see this thread for more detail https://discussions.udacity.com/t/accuracy-0-10-in-the-intro-to-tensorflow-lab/272469/9\n\n# Training loss\nloss = tf.reduce_mean(cross_entropy)\n\n# Create an operation that initializes all variables\ninit = tf.global_variables_initializer()\n\n# Test Cases\nwith tf.Session() as session:\n session.run(init)\n session.run(loss, feed_dict=train_feed_dict)\n session.run(loss, feed_dict=valid_feed_dict)\n session.run(loss, feed_dict=test_feed_dict)\n biases_data = session.run(biases)\n\nassert not np.count_nonzero(biases_data), 'biases must be zeros'\n\nprint('Tests Passed!')",
"Tests Passed!\n"
],
[
"# Determine if the predictions are correct\nis_correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(labels, 1))\n# Calculate the accuracy of the predictions\naccuracy = tf.reduce_mean(tf.cast(is_correct_prediction, tf.float32))\n\nprint('Accuracy function created.')",
"Accuracy function created.\n"
]
],
[
[
"<img src=\"image/learn_rate_tune.png\" style=\"height: 60%;width: 60%\">\n\n## Problem 3\nBelow are 3 parameter configurations for training the neural network. In each configuration, one of the parameters has multiple options. For each configuration, choose the option that gives the best acccuracy.\n\nParameter configurations:\n\nConfiguration 1\n* **Epochs:** 1\n* **Batch Size:**\n * 2000\n * 1000\n * 500\n * 300\n * 50\n* **Learning Rate:** 0.01\n\nConfiguration 2\n* **Epochs:** 1\n* **Batch Size:** 100\n* **Learning Rate:**\n * 0.8\n * 0.5\n * 0.1\n * 0.05\n * 0.01\n\nConfiguration 3\n* **Epochs:**\n * 1\n * 2\n * 3\n * 4\n * 5\n* **Batch Size:** 100\n* **Learning Rate:** 0.2\n\nThe code will print out a Loss and Accuracy graph, so you can see how well the neural network performed.\n\n*If you're having trouble solving problem 3, you can view the solution [here](https://github.com/udacity/CarND-TensorFlow-Lab/blob/master/solutions.ipynb).*",
"_____no_output_____"
]
],
[
[
"# TODO: Find the best parameters for each configuration\nepochs = 30\nbatch_size = 100\nlearning_rate = 0.2\n\n\n\n### DON'T MODIFY ANYTHING BELOW ###\n# Gradient Descent\noptimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss) \n\n# The accuracy measured against the validation set\nvalidation_accuracy = 0.0\n\n# Measurements use for graphing loss and accuracy\nlog_batch_step = 50\nbatches = []\nloss_batch = []\ntrain_acc_batch = []\nvalid_acc_batch = []\n\nwith tf.Session() as session:\n session.run(init)\n batch_count = int(math.ceil(len(train_features)/batch_size))\n\n for epoch_i in range(epochs):\n \n # Progress bar\n batches_pbar = tqdm(range(batch_count), desc='Epoch {:>2}/{}'.format(epoch_i+1, epochs), unit='batches')\n \n # The training cycle\n for batch_i in batches_pbar:\n # Get a batch of training features and labels\n batch_start = batch_i*batch_size\n batch_features = train_features[batch_start:batch_start + batch_size]\n batch_labels = train_labels[batch_start:batch_start + batch_size]\n\n # Run optimizer and get loss\n _, l = session.run(\n [optimizer, loss],\n feed_dict={features: batch_features, labels: batch_labels})\n\n # Log every 50 batches\n if not batch_i % log_batch_step:\n # Calculate Training and Validation accuracy\n training_accuracy = session.run(accuracy, feed_dict=train_feed_dict)\n validation_accuracy = session.run(accuracy, feed_dict=valid_feed_dict)\n\n # Log batches\n previous_batch = batches[-1] if batches else 0\n batches.append(log_batch_step + previous_batch)\n loss_batch.append(l)\n train_acc_batch.append(training_accuracy)\n valid_acc_batch.append(validation_accuracy)\n\n # Check accuracy against Validation data\n validation_accuracy = session.run(accuracy, feed_dict=valid_feed_dict)\n\nloss_plot = plt.subplot(211)\nloss_plot.set_title('Loss')\nloss_plot.plot(batches, loss_batch, 'g')\nloss_plot.set_xlim([batches[0], batches[-1]])\nacc_plot = plt.subplot(212)\nacc_plot.set_title('Accuracy')\nacc_plot.plot(batches, train_acc_batch, 'r', label='Training Accuracy')\nacc_plot.plot(batches, valid_acc_batch, 'x', label='Validation Accuracy')\nacc_plot.set_ylim([0, 1.0])\nacc_plot.set_xlim([batches[0], batches[-1]])\nacc_plot.legend(loc=4)\nplt.tight_layout()\nplt.show()\n\nprint('Validation accuracy at {}'.format(validation_accuracy))",
"Epoch 1/30: 100%|██████████| 1425/1425 [00:05<00:00, 241.03batches/s]\nEpoch 2/30: 100%|██████████| 1425/1425 [00:05<00:00, 241.15batches/s]\nEpoch 3/30: 100%|██████████| 1425/1425 [00:05<00:00, 241.68batches/s]\nEpoch 4/30: 100%|██████████| 1425/1425 [00:06<00:00, 237.31batches/s]\nEpoch 5/30: 100%|██████████| 1425/1425 [00:05<00:00, 239.41batches/s]\nEpoch 6/30: 100%|██████████| 1425/1425 [00:06<00:00, 233.95batches/s]\nEpoch 7/30: 100%|██████████| 1425/1425 [00:05<00:00, 248.55batches/s]\nEpoch 8/30: 100%|██████████| 1425/1425 [00:05<00:00, 249.13batches/s]\nEpoch 9/30: 100%|██████████| 1425/1425 [00:05<00:00, 246.91batches/s]\nEpoch 10/30: 100%|██████████| 1425/1425 [00:05<00:00, 246.33batches/s]\nEpoch 11/30: 100%|██████████| 1425/1425 [00:06<00:00, 222.22batches/s]\nEpoch 12/30: 100%|██████████| 1425/1425 [00:05<00:00, 238.46batches/s]\nEpoch 13/30: 100%|██████████| 1425/1425 [00:05<00:00, 247.66batches/s]\nEpoch 14/30: 100%|██████████| 1425/1425 [00:05<00:00, 247.59batches/s]\nEpoch 15/30: 100%|██████████| 1425/1425 [00:05<00:00, 265.48batches/s]\nEpoch 16/30: 100%|██████████| 1425/1425 [00:05<00:00, 243.82batches/s]\nEpoch 17/30: 100%|██████████| 1425/1425 [00:06<00:00, 236.59batches/s]\nEpoch 18/30: 100%|██████████| 1425/1425 [00:05<00:00, 240.60batches/s]\nEpoch 19/30: 100%|██████████| 1425/1425 [00:05<00:00, 248.57batches/s]\nEpoch 20/30: 100%|██████████| 1425/1425 [00:05<00:00, 244.13batches/s]\nEpoch 21/30: 100%|██████████| 1425/1425 [00:05<00:00, 244.86batches/s]\nEpoch 22/30: 100%|██████████| 1425/1425 [00:05<00:00, 217.50batches/s]\nEpoch 23/30: 100%|██████████| 1425/1425 [00:05<00:00, 245.30batches/s]\nEpoch 24/30: 100%|██████████| 1425/1425 [00:05<00:00, 241.40batches/s]\nEpoch 25/30: 100%|██████████| 1425/1425 [00:05<00:00, 251.86batches/s]\nEpoch 26/30: 100%|██████████| 1425/1425 [00:05<00:00, 256.47batches/s]\nEpoch 27/30: 100%|██████████| 1425/1425 [00:06<00:00, 224.38batches/s]\nEpoch 28/30: 100%|██████████| 1425/1425 [00:05<00:00, 249.99batches/s]\nEpoch 29/30: 100%|██████████| 1425/1425 [00:05<00:00, 246.27batches/s]\nEpoch 30/30: 100%|██████████| 1425/1425 [00:05<00:00, 252.18batches/s]\n"
]
],
[
[
"## Test\nSet the epochs, batch_size, and learning_rate with the best learning parameters you discovered in problem 3. You're going to test your model against your hold out dataset/testing data. This will give you a good indicator of how well the model will do in the real world. You should have a test accuracy of at least 80%.",
"_____no_output_____"
]
],
[
[
"# TODO: Set the epochs, batch_size, and learning_rate with the best parameters from problem 3\nepochs = 30\nbatch_size = 100 \nlearning_rate = 0.2\n\n\n\n### DON'T MODIFY ANYTHING BELOW ###\n# The accuracy measured against the test set\ntest_accuracy = 0.0\n\nwith tf.Session() as session:\n \n session.run(init)\n batch_count = int(math.ceil(len(train_features)/batch_size))\n\n for epoch_i in range(epochs):\n \n # Progress bar\n batches_pbar = tqdm(range(batch_count), desc='Epoch {:>2}/{}'.format(epoch_i+1, epochs), unit='batches')\n \n # The training cycle\n for batch_i in batches_pbar:\n # Get a batch of training features and labels\n batch_start = batch_i*batch_size\n batch_features = train_features[batch_start:batch_start + batch_size]\n batch_labels = train_labels[batch_start:batch_start + batch_size]\n\n # Run optimizer\n _ = session.run(optimizer, feed_dict={features: batch_features, labels: batch_labels})\n\n # Check accuracy against Test data\n test_accuracy = session.run(accuracy, feed_dict=test_feed_dict)\n\n\nassert test_accuracy >= 0.80, 'Test accuracy at {}, should be equal to or greater than 0.80'.format(test_accuracy)\nprint('Nice Job! Test Accuracy is {}'.format(test_accuracy))",
"Epoch 1/25: 100%|██████████| 1425/1425 [00:02<00:00, 505.22batches/s]\nEpoch 2/25: 100%|██████████| 1425/1425 [00:02<00:00, 540.31batches/s]\nEpoch 3/25: 100%|██████████| 1425/1425 [00:02<00:00, 536.68batches/s]\nEpoch 4/25: 100%|██████████| 1425/1425 [00:02<00:00, 538.19batches/s]\nEpoch 5/25: 100%|██████████| 1425/1425 [00:02<00:00, 539.59batches/s]\nEpoch 6/25: 100%|██████████| 1425/1425 [00:02<00:00, 540.76batches/s]\nEpoch 7/25: 100%|██████████| 1425/1425 [00:02<00:00, 541.74batches/s]\nEpoch 8/25: 100%|██████████| 1425/1425 [00:02<00:00, 545.16batches/s]\nEpoch 9/25: 100%|██████████| 1425/1425 [00:02<00:00, 505.92batches/s]\nEpoch 10/25: 32%|███▏ | 452/1425 [00:00<00:01, 491.61batches/s]"
]
],
[
[
"# Multiple layers\nGood job! You built a one layer TensorFlow network! However, you want to build more than one layer. This is deep learning after all! In the next section, you will start to satisfy your need for more layers.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e77bc64b25174236ac524802d7ac2207f6498d90 | 5,932 | ipynb | Jupyter Notebook | tutorial/t06_TensorFilter_imbalanced_training.ipynb | fastestimator-util/test_nightly | d7db45b5b38c301aa4985d24f6ece960dd9b5fed | [
"Apache-2.0"
] | 7 | 2021-03-07T09:25:27.000Z | 2022-01-08T03:36:35.000Z | tutorial/t06_TensorFilter_imbalanced_training.ipynb | Hozhang77/fastestimator | 50393bcfa7b4e3c12ff1fa4cb0eeec0c23facd43 | [
"Apache-2.0"
] | null | null | null | tutorial/t06_TensorFilter_imbalanced_training.ipynb | Hozhang77/fastestimator | 50393bcfa7b4e3c12ff1fa4cb0eeec0c23facd43 | [
"Apache-2.0"
] | 5 | 2019-09-14T22:15:10.000Z | 2021-07-15T02:38:35.000Z | 33.139665 | 227 | 0.578557 | [
[
[
"# Tutorial 6: Dealing with imbalanced dataset using TensorFilter\n\nWhen your dataset is imbalanced, training data needs to maintain a certain distribution to make sure minority classes are not ommitted during the training. In FastEstimator, `TensorFilter` is designed for that purpose.\n\n`TensorFilter` is a Tensor Operator that is used in `Pipeline` along with other tensor operators such as `MinMax` and `Resize`.\n\nThere are only two differences between `TensorFilter` and `TensorOp`: \n1. `TensorFilter` does not have outputs.\n2. The forward function of `TensorFilter` produces a boolean value which indicates whether to keep the data or not.",
"_____no_output_____"
],
[
"## Step 0 - Data preparation *(same as tutorial 1)*",
"_____no_output_____"
]
],
[
[
"# Import libraries\nimport numpy as np\nimport tensorflow as tf\nimport fastestimator as fe\nfrom fastestimator.op.tensorop import Minmax\n\n# Load data and create dictionaries\n(x_train, y_train), (x_eval, y_eval) = tf.keras.datasets.mnist.load_data()\ntrain_data = {\"x\": np.expand_dims(x_train, -1), \"y\": y_train}\neval_data = {\"x\": np.expand_dims(x_eval, -1), \"y\": y_eval}\ndata = {\"train\": train_data, \"eval\": eval_data}",
"_____no_output_____"
]
],
[
[
"## Step 1 - Customize your own Filter...\nIn this example, we will get rid of all images that have a label smaller than 5.",
"_____no_output_____"
]
],
[
[
"from fastestimator.op.tensorop import TensorFilter\n\n# We create our filter in forward function, it's just our condition.\nclass MyFilter(TensorFilter):\n def forward(self, data, state):\n pass_filter = data >= 5\n return pass_filter\n\n# We specify the filter in Pipeline ops list.\npipeline = fe.Pipeline(batch_size=32, data=data, ops=[MyFilter(inputs=\"y\"), Minmax(inputs=\"x\", outputs=\"x\")])",
"_____no_output_____"
],
[
"# Let's check our pipeline ops results with show_results\nresults = pipeline.show_results()\nprint(\"filtering out all data with label less than 5, the labels of current batch are:\")\nprint(results[0][\"y\"])",
"filtering out all data with label less than 5, the labels of current batch are:\ntf.Tensor([5 9 6 9 8 8 9 6 5 8 9 6 8 9 5 9 6 7 5 8 7 5 7 5 6 6 9 8 6 5 6 5], shape=(32,), dtype=uint8)\n"
]
],
[
[
"## ... or use a pre-built ScalarFilter\n\nIn FastEstimator, if user needs to filter out scalar values with a certain probability, one can use pre-built filter `ScalarFilter`. \nLet's filter out even numbers labels with 50% probability:",
"_____no_output_____"
]
],
[
[
"from fastestimator.op.tensorop import ScalarFilter\n\n# We specify the list of scalars to filter out and the probability to keep these scalars\npipeline = fe.Pipeline(batch_size=32, \n data=data, \n ops=[ScalarFilter(inputs=\"y\", filter_value=[0, 2, 4, 6, 8], keep_prob=[0.5, 0.5, 0.5, 0.5, 0.5]), \n Minmax(inputs=\"x\", outputs=\"x\")])",
"_____no_output_____"
],
[
"# Let's check our pipeline ops results with show_results\nresults = pipeline.show_results(num_steps=10)\n\nfor idx in range(10):\n batch_label = results[idx][\"y\"].numpy()\n even_count = 0\n odd_count = 0\n for elem in batch_label:\n if elem % 2 == 0:\n even_count += 1\n else:\n odd_count += 1\n print(\"in batch number {}, there are {} odd labels and {} even labels\".format(idx, odd_count, even_count))",
"in batch number 0, there are 20 odd labels and 12 even labels\nin batch number 1, there are 21 odd labels and 11 even labels\nin batch number 2, there are 20 odd labels and 12 even labels\nin batch number 3, there are 22 odd labels and 10 even labels\nin batch number 4, there are 22 odd labels and 10 even labels\nin batch number 5, there are 22 odd labels and 10 even labels\nin batch number 6, there are 21 odd labels and 11 even labels\nin batch number 7, there are 20 odd labels and 12 even labels\nin batch number 8, there are 22 odd labels and 10 even labels\nin batch number 9, there are 25 odd labels and 7 even labels\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e77bcadf48e3248c6b8fb58826133aa9aa3c0a9a | 240,966 | ipynb | Jupyter Notebook | ml_prova_7.ipynb | titocaco/disciplina_ml | 51accb145cbc51d95033e3dd9d3732b0d60fc54d | [
"MIT"
] | null | null | null | ml_prova_7.ipynb | titocaco/disciplina_ml | 51accb145cbc51d95033e3dd9d3732b0d60fc54d | [
"MIT"
] | null | null | null | ml_prova_7.ipynb | titocaco/disciplina_ml | 51accb145cbc51d95033e3dd9d3732b0d60fc54d | [
"MIT"
] | null | null | null | 271.970655 | 41,824 | 0.916586 | [
[
[
"import matplotlib.pyplot as plt\nimport numpy as np\nimport random\nimport pandas as pd\nfrom os import listdir\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis, QuadraticDiscriminantAnalysis\nfrom mlxtend.evaluate import scoring",
"_____no_output_____"
],
[
"def importar_dados(arquivo):\n df = pd.read_csv(arquivo, sep=' ', names=['x1', 'x2', 'classe'])\n \n X = df[['x1', 'x2']].values\n y = df['classe'].values\n \n return X, y",
"_____no_output_____"
],
[
"def exibir_amostras(X, y, \n titulo=None, \n salvar=False, \n figsize=(10, 8), \n legend_fontsize=20, \n title_fontsize=24, \n labels_fontsize=24, \n ticks_fontsize=16):\n \n classes = list(set([classe for classe in y]))\n n_classes = len(classes)\n \n plt.figure(figsize=figsize)\n \n for classe in classes:\n plt.scatter(X[y == classe][:, 0], X[y == classe][:, 1], s=100, label='Classe ' + str(classe))\n \n plt.legend(fontsize=legend_fontsize)\n plt.grid(True, linestyle='-', alpha=0.5)\n \n plt.title(str(titulo), fontsize=title_fontsize)\n plt.xlabel(r'$x_{1}$', fontsize=labels_fontsize)\n plt.ylabel(r'$x_{2}$', fontsize=labels_fontsize)\n plt.xticks(fontsize=ticks_fontsize)\n plt.yticks(fontsize=ticks_fontsize)\n \n if salvar:\n plt.savefig(titulo + '.pdf', format='pdf', dpi=300, transparent=True, bbox_inches='tight')\n \n plt.show()",
"_____no_output_____"
],
[
"class AnaliseDiscriminante:\n def __init__ (self, tipo='LDA'):\n self.tipo = tipo\n \n def treinar (self, X, y):\n self.classes = list(set(y))\n self.n_classes = len(self.classes)\n self.n_amostras = len(X)\n self.n_amostras_classe = [len(X[y == c]) for c in self.classes]\n self.probs = [n / self.n_amostras for n in self.n_amostras_classe]\n self.mu = np.mean(X, axis=0)\n self.mu_classe = [np.mean(X[y == c], axis=0) for c in self.classes]\n \n if self.tipo == 'LDA':\n self.sigma = np.cov(X.T)\n self.sigma_inv = np.linalg.inv(self.sigma)\n \n elif self.tipo == 'QDA':\n self.sigma = np.array([np.cov(X[y == c].T) for c in self.classes])\n self.sigma_inv = np.array([np.linalg.inv(matriz) for matriz in self.sigma])\n \n else:\n print(\"O tipo deve ser 'LDA' ou 'QDA'. Escolha um dos dois!\")\n \n def __delta_LDA(self, X, mu, P):\n return (np.matrix(X) * np.matrix(self.sigma_inv).T * np.matrix(mu).T - 0.5 * np.matrix(mu) * np.matrix(self.sigma_inv) * np.matrix(mu).T + np.log(P)).A1[0]\n \n def __delta_QDA(self, X, mu, sigma, sigma_inv, P):\n return (-0.5 * np.log(np.linalg.det(sigma)) - 0.5 * np.matrix(X - mu) * np.matrix(sigma_inv).T * np.matrix(X - mu).T + np.log(P)).A1[0]\n \n def classificar (self, X):\n if self.tipo == 'LDA':\n self.deltas = np.array([[self.__delta_LDA(amostra, self.mu_classe[i], self.probs[i]) for i in range(len(self.classes))] for amostra in X])\n \n elif self.tipo == 'QDA':\n self.deltas = np.array([[self.__delta_QDA(amostra, self.mu_classe[i], self.sigma[i], self.sigma_inv[i], self.probs[i]) for i in range(len(self.classes))] for amostra in X])\n \n else:\n print(\"O tipo deve ser 'LDA' ou 'QDA'. Escolha um dos dois!\")\n \n return np.array([np.argmax(amostra)+1 for amostra in self.deltas])",
"_____no_output_____"
],
[
"def holdout(X, y, teste_parcela=0.30, aleatorio=True, semente=None):\n n_amostras = len(X)\n n_amostras_teste = int(teste_parcela * n_amostras)\n n_amostras_treino = n_amostras - n_amostras_teste\n\n if aleatorio:\n if semente == None:\n semente = random.randint(0, 1000)\n random.seed(semente)\n teste_idx = np.array(sorted(random.sample(range(n_amostras), n_amostras_teste)))\n\n else:\n teste_idx = np.arange(n_amostras - n_amostras_teste - 1, n_amostras)\n\n treino_idx = np.array(list(set(np.arange(n_amostras)) - set(teste_idx)))\n X_teste = np.array([X[idx] for idx in teste_idx])\n y_teste = np.array([y[idx] for idx in teste_idx])\n X_treino = np.array([X[idx] for idx in treino_idx])\n y_treino = np.array([y[idx] for idx in treino_idx])\n \n return X_treino, y_treino, X_teste, y_teste",
"_____no_output_____"
],
[
"def avaliar_desempenho(y_verdadeiro, y_obtido):\n return scoring(y_verdadeiro, y_obtido, metric='accuracy', )",
"_____no_output_____"
]
],
[
[
"### Dataset 1",
"_____no_output_____"
]
],
[
[
"X1, y1 = importar_dados('datasets/dataset1.txt')\nexibir_amostras(X=X1, y=y1)",
"_____no_output_____"
]
],
[
[
"**Classificador mais adequado**: para este caso, o LDA já é suficiente para atuar bem, mas nada impede que seja escolhido o QDA.",
"_____no_output_____"
]
],
[
[
"# Bootstrap\nn_repeticoes = 10\n\nSK_LDA_desempenho = []\nME_LDA_desempenho = []\nSK_QDA_desempenho = []\nME_QDA_desempenho = []\nfor execucao in range(n_repeticoes):\n \n # Holdout\n X_treino, y_treino, X_teste, y_teste = holdout(X=X1, y=y1, teste_parcela=0.30, aleatorio=True, semente=None)\n\n # LDA - Scikit-Learn\n SK_LDA = LinearDiscriminantAnalysis().fit(X=X_treino, y=y_treino)\n SK_LDA_y_predito = SK_LDA.predict(X=X_teste)\n SK_LDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=SK_LDA_y_predito))\n \n # LDA - Próprio\n ME_LDA = AnaliseDiscriminante(tipo='LDA')\n ME_LDA.treinar(X=X_treino, y=y_treino)\n ME_LDA_y_predito = ME_LDA.classificar(X=X_teste)\n ME_LDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=ME_LDA_y_predito))\n \n # QDA - Scikit-Learn\n SK_QDA = QuadraticDiscriminantAnalysis().fit(X=X_treino, y=y_treino)\n SK_QDA_y_predito = SK_QDA.predict(X=X_teste)\n SK_QDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=SK_QDA_y_predito))\n \n # QDA - Próprio\n ME_QDA = AnaliseDiscriminante(tipo='QDA')\n ME_QDA.treinar(X=X_treino, y=y_treino)\n ME_QDA_y_predito = ME_QDA.classificar(X=X_teste)\n ME_QDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=ME_QDA_y_predito))\n\nSK_LDA_desempenho = np.array(SK_LDA_desempenho)\nSK_LDA_desempenho_media = np.mean(SK_LDA_desempenho)\nSK_LDA_desempenho_std = np.std(SK_LDA_desempenho)\n\nME_LDA_desempenho = np.array(ME_LDA_desempenho)\nME_LDA_desempenho_media = np.mean(ME_LDA_desempenho)\nME_LDA_desempenho_std = np.std(ME_LDA_desempenho)\n\nSK_QDA_desempenho = np.array(SK_QDA_desempenho)\nSK_QDA_desempenho_media = np.mean(SK_QDA_desempenho)\nSK_QDA_desempenho_std = np.std(SK_QDA_desempenho)\n\nME_QDA_desempenho = np.array(ME_QDA_desempenho)\nME_QDA_desempenho_media = np.mean(ME_QDA_desempenho)\nME_QDA_desempenho_std = np.std(ME_QDA_desempenho)\n\n\nprint('DATASET 1')\nprint('------ Acurácias -----')\nprint('LDA - Scikit: \\t{0:3.4f}'.format(SK_LDA_desempenho_media))\nprint('LDA - Próprio: \\t{0:3.4f}'.format(ME_LDA_desempenho_media))\nprint('----------------------')\nprint('QDA - Scikit: \\t{0:3.4f}'.format(SK_QDA_desempenho_media))\nprint('QDA - Próprio: \\t{0:3.4f}'.format(ME_QDA_desempenho_media))",
"DATASET 1\n------ Acurácias -----\nLDA - Scikit: \t1.0000\nLDA - Próprio: \t1.0000\n----------------------\nQDA - Scikit: \t1.0000\nQDA - Próprio: \t1.0000\n"
]
],
[
[
"### Dataset 2",
"_____no_output_____"
]
],
[
[
"X2, y2 = importar_dados('datasets/dataset2.txt')\nexibir_amostras(X=X2, y=y2)",
"_____no_output_____"
]
],
[
[
"**Classificador mais adequado**: aqui não parece ser possível zerar a taxa de erros, mas é possível observar que o LDA satisfaz a classificação com uma taxa de erros relativamebte baixa.",
"_____no_output_____"
]
],
[
[
"# Bootstrap\nn_repeticoes = 10\n\nSK_LDA_desempenho = []\nME_LDA_desempenho = []\nSK_QDA_desempenho = []\nME_QDA_desempenho = []\nfor execucao in range(n_repeticoes):\n \n # Holdout\n X_treino, y_treino, X_teste, y_teste = holdout(X=X2, y=y2, teste_parcela=0.30, aleatorio=True, semente=None)\n\n # LDA - Scikit-Learn\n SK_LDA = LinearDiscriminantAnalysis().fit(X=X_treino, y=y_treino)\n SK_LDA_y_predito = SK_LDA.predict(X=X_teste)\n SK_LDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=SK_LDA_y_predito))\n \n # LDA - Próprio\n ME_LDA = AnaliseDiscriminante(tipo='LDA')\n ME_LDA.treinar(X=X_treino, y=y_treino)\n ME_LDA_y_predito = ME_LDA.classificar(X=X_teste)\n ME_LDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=ME_LDA_y_predito))\n \n # QDA - Scikit-Learn\n SK_QDA = QuadraticDiscriminantAnalysis().fit(X=X_treino, y=y_treino)\n SK_QDA_y_predito = SK_QDA.predict(X=X_teste)\n SK_QDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=SK_QDA_y_predito))\n \n # QDA - Próprio\n ME_QDA = AnaliseDiscriminante(tipo='QDA')\n ME_QDA.treinar(X=X_treino, y=y_treino)\n ME_QDA_y_predito = ME_QDA.classificar(X=X_teste)\n ME_QDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=ME_QDA_y_predito))\n\nSK_LDA_desempenho = np.array(SK_LDA_desempenho)\nSK_LDA_desempenho_media = np.mean(SK_LDA_desempenho)\nSK_LDA_desempenho_std = np.std(SK_LDA_desempenho)\n\nME_LDA_desempenho = np.array(ME_LDA_desempenho)\nME_LDA_desempenho_media = np.mean(ME_LDA_desempenho)\nME_LDA_desempenho_std = np.std(ME_LDA_desempenho)\n\nSK_QDA_desempenho = np.array(SK_QDA_desempenho)\nSK_QDA_desempenho_media = np.mean(SK_QDA_desempenho)\nSK_QDA_desempenho_std = np.std(SK_QDA_desempenho)\n\nME_QDA_desempenho = np.array(ME_QDA_desempenho)\nME_QDA_desempenho_media = np.mean(ME_QDA_desempenho)\nME_QDA_desempenho_std = np.std(ME_QDA_desempenho)\n\nprint('DATASET 2')\nprint('------ Acurácias -----')\nprint('LDA - Scikit: \\t{0:3.4f}'.format(SK_LDA_desempenho_media))\nprint('LDA - Próprio: \\t{0:3.4f}'.format(ME_LDA_desempenho_media))\nprint('----------------------')\nprint('QDA - Scikit: \\t{0:3.4f}'.format(SK_QDA_desempenho_media))\nprint('QDA - Próprio: \\t{0:3.4f}'.format(ME_QDA_desempenho_media))",
"DATASET 2\n------ Acurácias -----\nLDA - Scikit: \t0.7714\nLDA - Próprio: \t0.7429\n----------------------\nQDA - Scikit: \t0.7571\nQDA - Próprio: \t0.7571\n"
]
],
[
[
"### Dataset 3",
"_____no_output_____"
]
],
[
[
"X3, y3 = importar_dados('datasets/dataset3.txt')\nexibir_amostras(X=X3, y=y3)",
"_____no_output_____"
]
],
[
[
"**Classificador mais adequado**: neste dataset é bastante evidente que há uma intensa sobreposição entre os dados, e o QDA é bem mais conveniente.",
"_____no_output_____"
]
],
[
[
"# Bootstrap\nn_repeticoes = 10\n\nSK_LDA_desempenho = []\nME_LDA_desempenho = []\nSK_QDA_desempenho = []\nME_QDA_desempenho = []\nfor execucao in range(n_repeticoes):\n \n # Holdout\n X_treino, y_treino, X_teste, y_teste = holdout(X=X3, y=y3, teste_parcela=0.30, aleatorio=True, semente=None)\n\n # LDA - Scikit-Learn\n SK_LDA = LinearDiscriminantAnalysis().fit(X=X_treino, y=y_treino)\n SK_LDA_y_predito = SK_LDA.predict(X=X_teste)\n SK_LDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=SK_LDA_y_predito))\n \n # LDA - Próprio\n ME_LDA = AnaliseDiscriminante(tipo='LDA')\n ME_LDA.treinar(X=X_treino, y=y_treino)\n ME_LDA_y_predito = ME_LDA.classificar(X=X_teste)\n ME_LDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=ME_LDA_y_predito))\n \n # QDA - Scikit-Learn\n SK_QDA = QuadraticDiscriminantAnalysis().fit(X=X_treino, y=y_treino)\n SK_QDA_y_predito = SK_QDA.predict(X=X_teste)\n SK_QDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=SK_QDA_y_predito))\n \n # QDA - Próprio\n ME_QDA = AnaliseDiscriminante(tipo='QDA')\n ME_QDA.treinar(X=X_treino, y=y_treino)\n ME_QDA_y_predito = ME_QDA.classificar(X=X_teste)\n ME_QDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=ME_QDA_y_predito))\n\nSK_LDA_desempenho = np.array(SK_LDA_desempenho)\nSK_LDA_desempenho_media = np.mean(SK_LDA_desempenho)\nSK_LDA_desempenho_std = np.std(SK_LDA_desempenho)\n\nME_LDA_desempenho = np.array(ME_LDA_desempenho)\nME_LDA_desempenho_media = np.mean(ME_LDA_desempenho)\nME_LDA_desempenho_std = np.std(ME_LDA_desempenho)\n\nSK_QDA_desempenho = np.array(SK_QDA_desempenho)\nSK_QDA_desempenho_media = np.mean(SK_QDA_desempenho)\nSK_QDA_desempenho_std = np.std(SK_QDA_desempenho)\n\nME_QDA_desempenho = np.array(ME_QDA_desempenho)\nME_QDA_desempenho_media = np.mean(ME_QDA_desempenho)\nME_QDA_desempenho_std = np.std(ME_QDA_desempenho)\n\nprint('DATASET 3')\nprint('------ Acurácias -----')\nprint('LDA - Scikit: \\t{0:3.4f}'.format(SK_LDA_desempenho_media))\nprint('LDA - Próprio: \\t{0:3.4f}'.format(ME_LDA_desempenho_media))\nprint('----------------------')\nprint('QDA - Scikit: \\t{0:3.4f}'.format(SK_QDA_desempenho_media))\nprint('QDA - Próprio: \\t{0:3.4f}'.format(ME_QDA_desempenho_media))",
"DATASET 3\n------ Acurácias -----\nLDA - Scikit: \t0.4450\nLDA - Próprio: \t0.4450\n----------------------\nQDA - Scikit: \t0.8033\nQDA - Próprio: \t0.8033\n"
]
],
[
[
"### Dataset 4",
"_____no_output_____"
]
],
[
[
"X4, y4 = importar_dados('datasets/dataset4.txt')\nexibir_amostras(X=X4, y=y4)",
"_____no_output_____"
]
],
[
[
"**Classificador mais adequado**: aqui também á uma considerável sobreposição das amostras, mas é menos agressiva do que o observado no dataset anterior. Embora não aparente, LDA e QDA exibirão resultados bastante próximos.",
"_____no_output_____"
]
],
[
[
"# Bootstrap\nn_repeticoes = 10\n\nSK_LDA_desempenho = []\nME_LDA_desempenho = []\nSK_QDA_desempenho = []\nME_QDA_desempenho = []\nfor execucao in range(n_repeticoes):\n \n # Holdout\n X_treino, y_treino, X_teste, y_teste = holdout(X=X4, y=y4, teste_parcela=0.30, aleatorio=True, semente=None)\n\n # LDA - Scikit-Learn\n SK_LDA = LinearDiscriminantAnalysis().fit(X=X_treino, y=y_treino)\n SK_LDA_y_predito = SK_LDA.predict(X=X_teste)\n SK_LDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=SK_LDA_y_predito))\n \n # LDA - Próprio\n ME_LDA = AnaliseDiscriminante(tipo='LDA')\n ME_LDA.treinar(X=X_treino, y=y_treino)\n ME_LDA_y_predito = ME_LDA.classificar(X=X_teste)\n ME_LDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=ME_LDA_y_predito))\n \n # QDA - Scikit-Learn\n SK_QDA = QuadraticDiscriminantAnalysis().fit(X=X_treino, y=y_treino)\n SK_QDA_y_predito = SK_QDA.predict(X=X_teste)\n SK_QDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=SK_QDA_y_predito))\n \n # QDA - Próprio\n ME_QDA = AnaliseDiscriminante(tipo='QDA')\n ME_QDA.treinar(X=X_treino, y=y_treino)\n ME_QDA_y_predito = ME_QDA.classificar(X=X_teste)\n ME_QDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=ME_QDA_y_predito))\n\nSK_LDA_desempenho = np.array(SK_LDA_desempenho)\nSK_LDA_desempenho_media = np.mean(SK_LDA_desempenho)\nSK_LDA_desempenho_std = np.std(SK_LDA_desempenho)\n\nME_LDA_desempenho = np.array(ME_LDA_desempenho)\nME_LDA_desempenho_media = np.mean(ME_LDA_desempenho)\nME_LDA_desempenho_std = np.std(ME_LDA_desempenho)\n\nSK_QDA_desempenho = np.array(SK_QDA_desempenho)\nSK_QDA_desempenho_media = np.mean(SK_QDA_desempenho)\nSK_QDA_desempenho_std = np.std(SK_QDA_desempenho)\n\nME_QDA_desempenho = np.array(ME_QDA_desempenho)\nME_QDA_desempenho_media = np.mean(ME_QDA_desempenho)\nME_QDA_desempenho_std = np.std(ME_QDA_desempenho)\n\nprint('DATASET 4')\nprint('------ Acurácias -----')\nprint('LDA - Scikit: \\t{0:3.4f}'.format(SK_LDA_desempenho_media))\nprint('LDA - Próprio: \\t{0:3.4f}'.format(ME_LDA_desempenho_media))\nprint('----------------------')\nprint('QDA - Scikit: \\t{0:3.4f}'.format(SK_QDA_desempenho_media))\nprint('QDA - Próprio: \\t{0:3.4f}'.format(ME_QDA_desempenho_media))",
"DATASET 4\n------ Acurácias -----\nLDA - Scikit: \t0.7872\nLDA - Próprio: \t0.7872\n----------------------\nQDA - Scikit: \t0.7564\nQDA - Próprio: \t0.7564\n"
]
],
[
[
"### Dataset 5",
"_____no_output_____"
]
],
[
[
"X5, y5 = importar_dados('datasets/dataset5.txt')\nexibir_amostras(X=X5, y=y5)",
"_____no_output_____"
]
],
[
[
"**Classificador mais adequado**: este é um caso em que não há qualquer sobreposição. Embora não seja fácil, é possível realizar uma classificação perfeita, com zero erros, utilizando um classificador linear, portanto, o LDA já é suficiente para satisfazer o problema, mas nada impede que o QDA seja utilizado.",
"_____no_output_____"
]
],
[
[
"# Bootstrap\nn_repeticoes = 10\n\nSK_LDA_desempenho = []\nME_LDA_desempenho = []\nSK_QDA_desempenho = []\nME_QDA_desempenho = []\nfor execucao in range(n_repeticoes):\n \n # Holdout\n X_treino, y_treino, X_teste, y_teste = holdout(X=X5, y=y5, teste_parcela=0.30, aleatorio=True, semente=None)\n\n # LDA - Scikit-Learn\n SK_LDA = LinearDiscriminantAnalysis().fit(X=X_treino, y=y_treino)\n SK_LDA_y_predito = SK_LDA.predict(X=X_teste)\n SK_LDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=SK_LDA_y_predito))\n \n # LDA - Próprio\n ME_LDA = AnaliseDiscriminante(tipo='LDA')\n ME_LDA.treinar(X=X_treino, y=y_treino)\n ME_LDA_y_predito = ME_LDA.classificar(X=X_teste)\n ME_LDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=ME_LDA_y_predito))\n \n # QDA - Scikit-Learn\n SK_QDA = QuadraticDiscriminantAnalysis().fit(X=X_treino, y=y_treino)\n SK_QDA_y_predito = SK_QDA.predict(X=X_teste)\n SK_QDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=SK_QDA_y_predito))\n \n # QDA - Próprio\n ME_QDA = AnaliseDiscriminante(tipo='QDA')\n ME_QDA.treinar(X=X_treino, y=y_treino)\n ME_QDA_y_predito = ME_QDA.classificar(X=X_teste)\n ME_QDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=ME_QDA_y_predito))\n\nSK_LDA_desempenho = np.array(SK_LDA_desempenho)\nSK_LDA_desempenho_media = np.mean(SK_LDA_desempenho)\nSK_LDA_desempenho_std = np.std(SK_LDA_desempenho)\n\nME_LDA_desempenho = np.array(ME_LDA_desempenho)\nME_LDA_desempenho_media = np.mean(ME_LDA_desempenho)\nME_LDA_desempenho_std = np.std(ME_LDA_desempenho)\n\nSK_QDA_desempenho = np.array(SK_QDA_desempenho)\nSK_QDA_desempenho_media = np.mean(SK_QDA_desempenho)\nSK_QDA_desempenho_std = np.std(SK_QDA_desempenho)\n\nME_QDA_desempenho = np.array(ME_QDA_desempenho)\nME_QDA_desempenho_media = np.mean(ME_QDA_desempenho)\nME_QDA_desempenho_std = np.std(ME_QDA_desempenho)\n\nprint('DATASET 5')\nprint('------ Acurácias -----')\nprint('LDA - Scikit: \\t{0:3.4f}'.format(SK_LDA_desempenho_media))\nprint('LDA - Próprio: \\t{0:3.4f}'.format(ME_LDA_desempenho_media))\nprint('----------------------')\nprint('QDA - Scikit: \\t{0:3.4f}'.format(SK_QDA_desempenho_media))\nprint('QDA - Próprio: \\t{0:3.4f}'.format(ME_QDA_desempenho_media))",
"DATASET 5\n------ Acurácias -----\nLDA - Scikit: \t0.9889\nLDA - Próprio: \t0.9800\n----------------------\nQDA - Scikit: \t0.9844\nQDA - Próprio: \t0.9844\n"
]
],
[
[
"### Dataset 6",
"_____no_output_____"
]
],
[
[
"X6, y6 = importar_dados('datasets/dataset6.txt')\nexibir_amostras(X=X6, y=y6)",
"_____no_output_____"
]
],
[
[
"**Classificador mais adequado**: neste caso já há sobreposição, o que não permite uma classificação completamente isenta de erros, mas um bom desempenho pode ser alcançado por ambos os classificadores, sem que haja grandes diferenças entre eles.",
"_____no_output_____"
]
],
[
[
"# Bootstrap\nn_repeticoes = 10\n\nSK_LDA_desempenho = []\nME_LDA_desempenho = []\nSK_QDA_desempenho = []\nME_QDA_desempenho = []\nfor execucao in range(n_repeticoes):\n \n # Holdout\n X_treino, y_treino, X_teste, y_teste = holdout(X=X6, y=y6, teste_parcela=0.30, aleatorio=True, semente=None)\n\n # LDA - Scikit-Learn\n SK_LDA = LinearDiscriminantAnalysis().fit(X=X_treino, y=y_treino)\n SK_LDA_y_predito = SK_LDA.predict(X=X_teste)\n SK_LDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=SK_LDA_y_predito))\n \n # LDA - Próprio\n ME_LDA = AnaliseDiscriminante(tipo='LDA')\n ME_LDA.treinar(X=X_treino, y=y_treino)\n ME_LDA_y_predito = ME_LDA.classificar(X=X_teste)\n ME_LDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=ME_LDA_y_predito))\n \n # QDA - Scikit-Learn\n SK_QDA = QuadraticDiscriminantAnalysis().fit(X=X_treino, y=y_treino)\n SK_QDA_y_predito = SK_QDA.predict(X=X_teste)\n SK_QDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=SK_QDA_y_predito))\n \n # QDA - Próprio\n ME_QDA = AnaliseDiscriminante(tipo='QDA')\n ME_QDA.treinar(X=X_treino, y=y_treino)\n ME_QDA_y_predito = ME_QDA.classificar(X=X_teste)\n ME_QDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=ME_QDA_y_predito))\n\nSK_LDA_desempenho = np.array(SK_LDA_desempenho)\nSK_LDA_desempenho_media = np.mean(SK_LDA_desempenho)\nSK_LDA_desempenho_std = np.std(SK_LDA_desempenho)\n\nME_LDA_desempenho = np.array(ME_LDA_desempenho)\nME_LDA_desempenho_media = np.mean(ME_LDA_desempenho)\nME_LDA_desempenho_std = np.std(ME_LDA_desempenho)\n\nSK_QDA_desempenho = np.array(SK_QDA_desempenho)\nSK_QDA_desempenho_media = np.mean(SK_QDA_desempenho)\nSK_QDA_desempenho_std = np.std(SK_QDA_desempenho)\n\nME_QDA_desempenho = np.array(ME_QDA_desempenho)\nME_QDA_desempenho_media = np.mean(ME_QDA_desempenho)\nME_QDA_desempenho_std = np.std(ME_QDA_desempenho)\n\nprint('DATASET 6')\nprint('------ Acurácias -----')\nprint('LDA - Scikit: \\t{0:3.4f}'.format(SK_LDA_desempenho_media))\nprint('LDA - Próprio: \\t{0:3.4f}'.format(ME_LDA_desempenho_media))\nprint('----------------------')\nprint('QDA - Scikit: \\t{0:3.4f}'.format(SK_QDA_desempenho_media))\nprint('QDA - Próprio: \\t{0:3.4f}'.format(ME_QDA_desempenho_media))",
"DATASET 6\n------ Acurácias -----\nLDA - Scikit: \t0.8222\nLDA - Próprio: \t0.8089\n----------------------\nQDA - Scikit: \t0.8156\nQDA - Próprio: \t0.8156\n"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e77bd3de9aee2570e4651e00c6ab0b88ffc4453b | 8,880 | ipynb | Jupyter Notebook | 7Octubre_daa.ipynb | ibzan79/daa_2021_1 | 74585f5d2e0a742d63ea102f3d776dfe388daa9f | [
"MIT"
] | null | null | null | 7Octubre_daa.ipynb | ibzan79/daa_2021_1 | 74585f5d2e0a742d63ea102f3d776dfe388daa9f | [
"MIT"
] | null | null | null | 7Octubre_daa.ipynb | ibzan79/daa_2021_1 | 74585f5d2e0a742d63ea102f3d776dfe388daa9f | [
"MIT"
] | null | null | null | 51.32948 | 1,367 | 0.542342 | [
[
[
"<a href=\"https://colab.research.google.com/github/ibzan79/daa_2021_1/blob/master/7Octubre_daa.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Búsqueda lineal\n\nDada un conjunto de datos no ordenados, la búsqueda lineal consiste en recorrer el conjunto de datos desde el inicio al final, moviéndose uno en uno hasta encontrar el elemento o llegar al final del conjunto.\n\ndatos = [ 4,18,47,2,34,14,78,12,48,21,31,19,1,3,5 ]\n\n# Búsqueda binaria\nfunciona sobre un conjunto de datos lineal ordenado.\n\nConsiste en dividir el conjunto en mitades y buscar en esa mitad. Si el elemento buscado no está en la mitad, preguntas si el elemento está a la derecha o a la izquierda. Haces la lista igual a la mitad correspondiente y repites el proceso.\n\nPseudocódigo:\n\nL = [ 4,18,47,2,34,14,78,12,48,21,31,19,1,3,5]\n\nDER = longitud(L) - 1\n\nIZQ = 0\n\nMID: apuntará a la mitad del segmento de búsqueda \n\nbuscado: es el valos a buscar\n\n1. Hacer DER = longitud(L) - 1\n2. Hacer IZQ = 0\n3. Si IZQ > DER, significa que hay un error en los datos \n4. Calcular MID = int((IZQ + DER) / 2)\n5. Mientras L[MID] != buscado, hacer\n6. - preguntar si L[MID] > buscado \n - hacer DER = MID\n - de lo contrario\n - hacer IZQ = MID\n - preguntar si (DER - IZQ) % 2 == 0\n - MID = (IZQ + ((DER - IZQ) / 2)) + 1\n - de lo contrario\n - MID = IZQ + ((DER - IZQ) / 2)\n7. return MID",
"_____no_output_____"
]
],
[
[
"'''\nBusqueda lineal\nregresa la posición del elemento 'buscado' si se encuentra dentro de la lista.\nregresa -1 si el elemento buscado no existe dentro de la lista.\n'''\ndef busq_lineal(L, buscado):\n indice = -1\n contador = 0\n for idx in range(len(L)):\n contador += 1\n if L[idx] == buscado:\n indice = idx\n break\n print(f\"número de comparaciones realizadas = {contador}\")\n return indice\n\n'''\nBúsqueda binaria\n'''\n\ndef busqueda_binaria(L, buscado):\n IZQ = 0\n DER = len(L) - 1\n MID = int((IZQ + DER) / 2)\n if len(L) % 2 == 0:\n MID = (DER // 2) + 1\n else:\n MID = DER // 2\n while (L[MID] != buscado):\n if L[MID] > buscado:\n DER = MID\n else:\n IZQ = MID\n if (DER - IZQ) % 2 == 0:\n MID = (IZQ + ((DER - IZQ) // 2)) + 1\n else:\n MID = IZQ + ((DER - IZQ) // 2)\n return MID\n\ndef main():\n datos = [ 4,18,47,2,34,14,78,12,48,21,31,19,1,3,5]\n dato = int(input(\"Que valor quieres buscar: \"))\n resultado = busq_lineal(datos, dato)\n print(\"Resultado: \", resultado)\n\n print(\"Búsqueda lineal en una lista ordenada\")\n datos.sort() # Con esto se ordenan los datos\n print(datos)\n resultado = busq_lineal(datos, dato)\n print(\"Resultado: \", resultado)\n\n print(\"Búsqueda binaria\")\n posicion = busqueda_binaria(datos, dato)\n print(f\"El elemento dato está en la posición {posicion} de la lista\")\n\nmain()",
"Que valor quieres buscar: 47\nnúmero de comparaciones realizadas = 3\nResultado: 2\nBúsqueda lineal en una lista ordenada\n[1, 2, 3, 4, 5, 12, 14, 18, 19, 21, 31, 34, 47, 48, 78]\nnúmero de comparaciones realizadas = 13\nResultado: 12\nBúsqueda binaria\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
]
] |
e77bdfaf3507403482b53fc02e1441cae9cec991 | 2,158 | ipynb | Jupyter Notebook | notebooks/edfi/edfi.ipynb | xmarcosx/notebooks | d44fa044149106e5e0e031d786c502118de0aa49 | [
"Apache-2.0"
] | null | null | null | notebooks/edfi/edfi.ipynb | xmarcosx/notebooks | d44fa044149106e5e0e031d786c502118de0aa49 | [
"Apache-2.0"
] | null | null | null | notebooks/edfi/edfi.ipynb | xmarcosx/notebooks | d44fa044149106e5e0e031d786c502118de0aa49 | [
"Apache-2.0"
] | null | null | null | 22.957447 | 89 | 0.552827 | [
[
[
"\nimport base64\nimport json\nimport os\nimport requests\n\n\nBASE_URL = os.environ.get('BASE_URL')\nAPI_KEY = os.environ.get('API_KEY')\nAPI_SECRET = os.environ.get('API_SECRET')",
"_____no_output_____"
],
[
"credentials_concatenated = ':'.join((API_KEY, API_SECRET))\ncredentials_encoded = base64.b64encode(credentials_concatenated.encode('utf-8'))\naccess_url = f'{BASE_URL}/oauth/token'\n\naccess_headers = {\n 'Authorization': b'Basic ' + credentials_encoded\n}\n\naccess_params = {\n 'grant_type': 'client_credentials'\n}\n\nresponse = requests.post(access_url, headers=access_headers, data=access_params)\n\nif response.ok:\n response_json = response.json()\n print(response_json['access_token'])\nelse:\n raise Exception(\"Failed to retrieve access token\")\n",
"_____no_output_____"
],
[
"with open('nwea.json') as json_file:\n data = json.load(json_file)\n\n\ndata['Bootstraps']",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code"
]
] |
e77bedaa847eca7d3e1207ea25eb0b701f6b5290 | 19,606 | ipynb | Jupyter Notebook | numpy_fonctions.ipynb | Michel-Nassalang/python | 8c3b40d63c9930ac32120140db04fff6ec6c46bf | [
"Apache-2.0"
] | null | null | null | numpy_fonctions.ipynb | Michel-Nassalang/python | 8c3b40d63c9930ac32120140db04fff6ec6c46bf | [
"Apache-2.0"
] | null | null | null | numpy_fonctions.ipynb | Michel-Nassalang/python | 8c3b40d63c9930ac32120140db04fff6ec6c46bf | [
"Apache-2.0"
] | null | null | null | 18.636882 | 91 | 0.425533 | [
[
[
"import numpy as np\nimport pandas as pd",
"_____no_output_____"
],
[
"np.random.seed(0) # pour éviter le changement de la matrice à chaque recompilation\nA = np.random.randint(0,9, [5,4])\nA",
"_____no_output_____"
],
[
"A.mean()",
"_____no_output_____"
],
[
"A.std()",
"_____no_output_____"
],
[
"A.var()",
"_____no_output_____"
],
[
"A.shape",
"_____no_output_____"
],
[
"A.max()",
"_____no_output_____"
],
[
"A.min()",
"_____no_output_____"
],
[
"A.argmin()",
"_____no_output_____"
],
[
"A.argmax()",
"_____no_output_____"
],
[
"np.corrcoef(A)",
"_____no_output_____"
],
[
"A",
"_____no_output_____"
],
[
"np.unique(A, return_counts=True)",
"_____no_output_____"
],
[
"values, counts = np.unique(A,return_counts=True)",
"_____no_output_____"
],
[
"values",
"_____no_output_____"
],
[
"counts",
"_____no_output_____"
],
[
"counts.argsort()",
"_____no_output_____"
],
[
"C = counts[counts.argsort()]\nC",
"_____no_output_____"
],
[
"D =values[counts.argsort()]\nD",
"_____no_output_____"
],
[
"for i, j in zip(C, D) :\n print(f'L\\'élement {j} apparait {i} fois dans la matrice A')",
"L'élement 0 apparait 1 fois dans la matrice A\nL'élement 2 apparait 1 fois dans la matrice A\nL'élement 4 apparait 1 fois dans la matrice A\nL'élement 1 apparait 2 fois dans la matrice A\nL'élement 6 apparait 2 fois dans la matrice A\nL'élement 3 apparait 3 fois dans la matrice A\nL'élement 5 apparait 3 fois dans la matrice A\nL'élement 8 apparait 3 fois dans la matrice A\nL'élement 7 apparait 4 fois dans la matrice A\n"
],
[
"# counts.sort()\n# counts",
"_____no_output_____"
],
[
"[A>4]",
"_____no_output_____"
],
[
"E = np.random.randn(4,3)\nE",
"_____no_output_____"
],
[
"E[E>0.5] = np.nan\nE",
"_____no_output_____"
],
[
"E.mean()",
"_____no_output_____"
],
[
"np.nanmean(E)",
"_____no_output_____"
],
[
"np.nanstd(E)",
"_____no_output_____"
],
[
"np.nanvar(E)",
"_____no_output_____"
],
[
"np.isnan(E)",
"_____no_output_____"
],
[
"l = np.isnan(E).sum()\nl",
"_____no_output_____"
],
[
"l/E.size",
"_____no_output_____"
],
[
"E.shape",
"_____no_output_____"
],
[
"E.size",
"_____no_output_____"
],
[
"E[np.isnan(E)] = 0",
"_____no_output_____"
],
[
"E",
"_____no_output_____"
]
],
[
[
"# Algèbre linéaire",
"_____no_output_____"
]
],
[
[
"M = np.random.randint(0,9, [4,3])\nprint(M) \nprint('\\n')\nN =np.random.randint(0,9, [3,4])\nprint(N)",
"[[8 4 6]\n [5 8 2]\n [3 7 5]\n [3 4 5]]\n\n\n[[3 3 7 7]\n [3 2 3 7]\n [7 5 1 2]]\n"
],
[
"M.dot(N)",
"_____no_output_____"
],
[
"N.dot(M)",
"_____no_output_____"
],
[
"M.T",
"_____no_output_____"
],
[
"G = np.random.randint(0,9,[3,3])",
"_____no_output_____"
],
[
"np.linalg.det(G)",
"_____no_output_____"
],
[
"np.linalg.inv(G)",
"_____no_output_____"
],
[
"np.linalg.pinv(G)",
"_____no_output_____"
],
[
"np.linalg.pinv(M)",
"_____no_output_____"
],
[
"np.linalg.eig(G)",
"_____no_output_____"
]
],
[
[
"# TP Standardisation (important)",
"_____no_output_____"
]
],
[
[
"M",
"_____no_output_____"
],
[
"M.mean(axis=0)",
"_____no_output_____"
],
[
"P= M - M.mean(axis=0)\nP",
"_____no_output_____"
],
[
"S = P/M.std(axis=0)\nS # standardisation",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
e77c02027fbdc1e1544e482c0242f6f46262a2fb | 146,455 | ipynb | Jupyter Notebook | 12. FIR Filter -Windowed-Sinc Filters/.ipynb_checkpoints/FIR Filter - 2.Spectral Reversal_Solution-checkpoint.ipynb | mriosrivas/DSP_Student_2021 | 7d978d5a538e2eb198dfbe073b4d8dcbf1aa756f | [
"MIT"
] | 2 | 2022-01-25T04:58:58.000Z | 2022-03-24T23:00:13.000Z | 12. FIR Filter -Windowed-Sinc Filters/.ipynb_checkpoints/FIR Filter - 2.Spectral Reversal_Solution-checkpoint.ipynb | mriosrivas/DSP_Student_2021 | 7d978d5a538e2eb198dfbe073b4d8dcbf1aa756f | [
"MIT"
] | 1 | 2021-11-25T00:39:40.000Z | 2021-11-25T00:39:40.000Z | 12. FIR Filter -Windowed-Sinc Filters/.ipynb_checkpoints/FIR Filter - 2.Spectral Reversal_Solution-checkpoint.ipynb | mriosrivas/DSP_Student_2021 | 7d978d5a538e2eb198dfbe073b4d8dcbf1aa756f | [
"MIT"
] | null | null | null | 554.753788 | 90,640 | 0.945731 | [
[
[
"# High Pass Filter Using the Spectral Reversal Technique\nWe can create a high pass filter by using as reference a low pass filter and a technique called **Spectral Reversal**. For this notebook we will use the *Windowed-Sinc Filters* Notebook results, which are pickled in an serialized object called `save_data.pickle`.",
"_____no_output_____"
]
],
[
[
"import sys\nsys.path.insert(0, '../')",
"_____no_output_____"
],
[
"from Common import common_plots\nfrom Common import fourier_transform\n\ncplots = common_plots.Plot()",
"_____no_output_____"
],
[
"import pickle\nimport numpy as np\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"def get_fourier(x):\n \"\"\"\n Function that performs the Fourier calculation of a signal x and returns its magnitude and frequency range.\n \n Parameters:\n x (numpy array): Signal to be transformed into Fourier domain.\n \n Returns:\n mag (numpy array): Magnitude of the signal's Fourier transform.\n freq (numpy array): Frequency domain of the signal's Fourier transform.\n \"\"\"\n signal = x.reshape(-1,1)\n fourier = fourier_transform.FourierTransform(signal)\n mag = fourier.dft_magnitude()\n freq = fourier.frequency_domain()\n return mag, freq",
"_____no_output_____"
]
],
[
[
"We load the low pass data from the *Windowed-Sinc Filters* Notebook",
"_____no_output_____"
]
],
[
[
"with open('save_data.pickle', 'rb') as f:\n data = pickle.load(f)\n \necg = np.array(data['ecg'])\nlow_pass = np.array(data['low_pass'])\nlow_pass = low_pass/np.sum(low_pass)\nfft_low_pass = np.array(data['fft_low_pass'])",
"_____no_output_____"
]
],
[
[
"To generate the high pass filter, we use the Sprectral Reversal methond, which consist of multiplying the low pass filter response $h_{lp}[n]$ with $(-1)^{-n}$. Therefore the high pass filter response is given by:\n$$h_{hp}[n] = h_{lp}[n](-1)^{-n}$$",
"_____no_output_____"
]
],
[
[
"N = low_pass.shape[0]\nhigh_pass = low_pass * ((-1) ** np.arange(N))",
"_____no_output_____"
],
[
"dft_low_pass_magnitude, dft_low_pass_freq = get_fourier(low_pass)\ndft_high_pass_magnitude, dft_high_pass_freq = get_fourier(high_pass)",
"_____no_output_____"
],
[
"plt.rcParams[\"figure.figsize\"] = (15,10)\n\nplt.subplot(2,2,1)\nplt.stem(low_pass, markerfmt='.', use_line_collection=True)\nplt.title('Low Pass Filter')\nplt.grid('on')\n\nplt.subplot(2,2,2)\nplt.stem(high_pass, markerfmt='.', use_line_collection=True)\nplt.title('High Pass Filter')\nplt.grid('on')\n\nplt.subplot(2,2,3)\ncplots.plot_frequency_response(dft_low_pass_magnitude, \n dft_low_pass_freq, \n title='Low Pass Filter Response')\n\nplt.subplot(2,2,4)\ncplots.plot_frequency_response(dft_high_pass_magnitude, \n dft_high_pass_freq, \n title='High Pass Filter Response');",
"_____no_output_____"
]
],
[
[
"**This frequency response is a “left-right flipped” version of the frequency response of the low-pass filter.**",
"_____no_output_____"
]
],
[
[
"low_pass_ecg = np.convolve(ecg,low_pass)\nhigh_pass_ecg = np.convolve(ecg,high_pass)\n\n\nplt.rcParams[\"figure.figsize\"] = (15,10)\n\nplt.subplot(2,2,1)\nplt.plot(low_pass_ecg)\nplt.title('Low Pass ECG')\nplt.grid('on')\nplt.xlabel('Samples')\nplt.ylabel('Amplitude')\n\nplt.subplot(2,2,2)\nplt.plot(high_pass_ecg)\nplt.title('High Pass ECG')\nplt.grid('on')\nplt.xlabel('Samples')\nplt.ylabel('Amplitude')\n\nplt.subplot(2,1,2)\nplt.plot(ecg)\nplt.title('ECG Signal')\nplt.grid('on')\nplt.xlabel('Samples')\nplt.ylabel('Amplitude');",
"_____no_output_____"
]
],
[
[
"## Why Does Spectral Reversal Work?\n\nThe spectral reversal technique is based on the so-called shift theorem of the Fourier transform. Formulated for the discrete case, the shift theorem says that, for a Fourier transform pair $x[n]⟷X[k]$, a shift by $s$ samples in the frequency domain is equivalent with multiplying by a complex exponential in the time domain, as\n\n$$x[n]e^{j2πns/N}⟷X[k−s]$$\n\nIn general, the result of doing this will be complex. This is not a problem, but let’s investigate in which circumstances the result is not complex. This is may be easiest to see with the complex exponential rewritten using Euler’s Identity,\n\n$$e^{j2πns/N}=\\cos{(2πns/N)}+j\\sin{(2πns/N)}$$\n\nThis expression is real if the sine term is zero, which is the case if the angle is zero or $\\pi$\n\nWe get this result if we shift by $s=N/2$ samples, because then the angles become $2πns/N=nπ$. Of course, in that case the complete expression becomes $\\cos{(nπ)}$, which is exactly the sequence $1,−1,1,−1,…$.",
"_____no_output_____"
],
[
"#### Reference:\n[1] https://tomroelandts.com/articles/spectral-reversal-to-create-a-high-pass-filter",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
e77c05d928b8af111843624697f966f8f3e06d64 | 663 | ipynb | Jupyter Notebook | pset_challenging_ext/exercises/nb/p43.ipynb | mottaquikarim/pydev-psets | 9749e0d216ee0a5c586d0d3013ef481cc21dee27 | [
"MIT"
] | 5 | 2019-04-08T20:05:37.000Z | 2019-12-04T20:48:45.000Z | pset_challenging_ext/exercises/nb/p43.ipynb | mottaquikarim/pydev-psets | 9749e0d216ee0a5c586d0d3013ef481cc21dee27 | [
"MIT"
] | 8 | 2019-04-15T15:16:05.000Z | 2022-02-12T10:33:32.000Z | pset_challenging_ext/exercises/nb/p43.ipynb | mottaquikarim/pydev-psets | 9749e0d216ee0a5c586d0d3013ef481cc21dee27 | [
"MIT"
] | 2 | 2019-04-10T00:14:42.000Z | 2020-02-26T20:35:21.000Z | 24.555556 | 134 | 0.538462 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
e77c127b3e765d9588a45bd70424627d0fa40ab2 | 1,349 | ipynb | Jupyter Notebook | First_try.ipynb | kpflugshaupt/colab | 7e7c08af0f82e33ae99fa1954016202818039eec | [
"MIT"
] | null | null | null | First_try.ipynb | kpflugshaupt/colab | 7e7c08af0f82e33ae99fa1954016202818039eec | [
"MIT"
] | null | null | null | First_try.ipynb | kpflugshaupt/colab | 7e7c08af0f82e33ae99fa1954016202818039eec | [
"MIT"
] | null | null | null | 21.078125 | 226 | 0.445515 | [
[
[
"<a href=\"https://colab.research.google.com/github/kpflugshaupt/colab/blob/master/First_try.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"import pandas as pd\n",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
e77c18e54c1fb1aac0f9afb3b61a094f887742c4 | 137,171 | ipynb | Jupyter Notebook | predict-social-media-ad-purchased.ipynb | scarlledo/predict-social-media-ad-purchased | 59bb949c59f7c243ebc671bff0d6604274c1173a | [
"MIT"
] | null | null | null | predict-social-media-ad-purchased.ipynb | scarlledo/predict-social-media-ad-purchased | 59bb949c59f7c243ebc671bff0d6604274c1173a | [
"MIT"
] | null | null | null | predict-social-media-ad-purchased.ipynb | scarlledo/predict-social-media-ad-purchased | 59bb949c59f7c243ebc671bff0d6604274c1173a | [
"MIT"
] | null | null | null | 214.329688 | 100,260 | 0.895532 | [
[
[
"import pandas as pd",
"_____no_output_____"
],
[
"data=pd.read_csv('data.csv')",
"_____no_output_____"
],
[
"data.isnull().sum()",
"_____no_output_____"
],
[
"data.head()",
"_____no_output_____"
],
[
"data = data.drop('User ID', axis=1)",
"_____no_output_____"
],
[
"data.head()",
"_____no_output_____"
],
[
"from sklearn.preprocessing import LabelEncoder",
"_____no_output_____"
],
[
"le= LabelEncoder()",
"_____no_output_____"
],
[
"data['Gender']=le.fit_transform(data['Gender'])",
"_____no_output_____"
],
[
"data.head()",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\nimport seaborn as sns\n",
"_____no_output_____"
],
[
"sns.pairplot(data)",
"_____no_output_____"
],
[
"x=data.drop('Purchased',axis=1).values\ny=data['Purchased'].values",
"_____no_output_____"
],
[
"x.shape,y.shape",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split",
"_____no_output_____"
],
[
"x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,shuffle=True)",
"_____no_output_____"
],
[
"x_train.shape,y_train.shape,x_test.shape,y_test.shape",
"_____no_output_____"
],
[
"from sklearn.linear_model import LogisticRegression",
"_____no_output_____"
],
[
"log=LogisticRegression()",
"_____no_output_____"
],
[
"log.fit(x_train,y_train)",
"_____no_output_____"
],
[
"pred = log.predict(x_test)",
"_____no_output_____"
],
[
"from sklearn.metrics import accuracy_score",
"_____no_output_____"
],
[
"accuracy_score(y_test,pred)",
"_____no_output_____"
],
[
"plt.plot(pred, '--r')\nplt.plot(y_test, '-b')\nplt.title('Pur vs Act')\nplt.show()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e77c1aba8f891be05a6f80c31fe5dbc1aa3439c1 | 48,718 | ipynb | Jupyter Notebook | Bubble_Dissolution_Acquisition.ipynb | bsaintmichel/bubbledynamics | 314960b8e83d60c5f8afb73153131a87418fb4a2 | [
"CC0-1.0"
] | null | null | null | Bubble_Dissolution_Acquisition.ipynb | bsaintmichel/bubbledynamics | 314960b8e83d60c5f8afb73153131a87418fb4a2 | [
"CC0-1.0"
] | null | null | null | Bubble_Dissolution_Acquisition.ipynb | bsaintmichel/bubbledynamics | 314960b8e83d60c5f8afb73153131a87418fb4a2 | [
"CC0-1.0"
] | null | null | null | 76.121875 | 9,950 | 0.600045 | [
[
[
"# Bubble dissolution : Realtime Acquisition + Preprocessing + Saving Data / Snapshots\n\nBrice : [email protected]",
"_____no_output_____"
],
[
"## Step 1 : Definitions / Initialisations / Automatic thresholding\n\n#### Subroutines : \n\n* `analyse_bubble` : checks one bubble (any bubble) for shape and threshold detection\n * `padding` : pads an image with values from the edge (useful to avoid issues with bubbles close to the border)\n * `proj_fourier` : fits the bubble shape with Fourier series (produces coefficients)\n * `build_fourier` : rebuilds the Fourier fit based on projection coefficients\n* `write_csvheader` : helps me build a nice header for the data file based on \n* `write_logheader`: helps doing the same with the log file (saving lots of acquisition-related parameters)\n* `format_logstr` : bunches together some numbers to track your experiment (in log file & in stdout)\n* `init_figure` : initialises the (somewhat live) figure of the bubble and its interface\n* `init_camera` : (re)starts the camera with the proper acquisition parameters\n\n#### Note : \n\nIf the camera is not accessible, try before re-running the cells : \n\n* camera.Close() \n* closing vscode and restarting it\n* Closing Pylon :-)\n\n\n ",
"_____no_output_____"
]
],
[
[
"from pypylon import pylon\nfrom bokeh.plotting import show, row, figure, column\nfrom bokeh.models import ColumnDataSource, LinearColorMapper\nfrom jupyter_bokeh.widgets import BokehModel\nfrom bokeh.io import output_notebook\nimport numpy as np\nimport pandas as pd\nimport time\nimport codecs\nimport os\nfrom PIL import Image\nimport skimage.transform as sktr\nimport skimage.measure as skms\nimport skimage.filters as skfi\nimport skimage.morphology as skmph\n\n##### YOUR PARAMETERS HERE #############\n\nzoom = 3 # Check on the lens\n## ZOOM VALUES z = {'zoom': [0.7, 1, 1.5, 2, 3, 4, 4.5], 'one_mm_in_px': [62, 91, 137, 184, 281, 361, 405]}\n## Leads to 90.4 mm/px for a zoom of 1\nexposure = 100 # in ms\nimagesize = [512,512] # width x height\nfilter_size = 1 # To smooth images\nfolder_location = 'C:\\\\Users\\\\saint-michel\\\\Documents\\\\Acquisitions\\\\Bubbles_20211216'\npixel_format = \"Mono12\" # Image values are then from 0 to 4095 (and not 255). NOTE : SOME THINGS WILL BREAK IF YOU CHANGE THIS (including image saving)\nthreshold = None # From 0 to 4096, leave to 'None' if you want auto threshold ...\nchunk_size = 100 # We save snapshots every chunk_size frames \n\n### FUNCTIONS THAT YOU MAY CALL TO DO THINGS ##################################################################\ndef analyse_frame(img, myinfo, time=0):\n # Finds a nice threshold, etc. \n # Myinfo : dict with at least 'pixel_format' and 'threshold' (which can be None)\n # Time : timestamp given by camera.grabFrame\n # Subroutines ... \n def img_padding(img, pad=16):\n img_pad = np.zeros((np.shape(img)[0] + 2*pad, np.shape(img)[1] + 2*pad))\n img_pad[pad:-pad, pad:-pad] = img\n img_pad[:pad, pad:-pad] = img[0,:]\n img_pad[-pad:, pad:-pad] = img[-1,:]\n img_pad[:, :pad] = img_pad[:,pad, np.newaxis]\n img_pad[:, -pad:] = img_pad[:, -pad-1, np.newaxis]\n return img_pad, pad\n def proj_fourier(signal, thetas):\n nmodes = 10\n proj_cos, proj_sin = np.zeros(nmodes), np.zeros(nmodes)\n for mno in range(nmodes):\n proj_cos[mno] = np.trapz(signal*np.cos(mno*thetas), x=thetas)*1/np.pi\n proj_sin[mno] = np.trapz(signal*np.sin(mno*thetas), x=thetas)*1/np.pi\n proj_amp = np.sqrt(proj_cos**2 + proj_sin**2)\n proj_phs = np.arctan2(-proj_sin, proj_cos) # It works with a (-) ... so be it.\n return proj_amp, proj_phs\n def build_fourier(proj_amp, proj_phs, thetas):\n nmodes = 10\n rebuild = np.zeros(np.shape(thetas))\n for mno in range(nmodes):\n rebuild = rebuild + proj_amp[mno]*np.cos(mno*thetas + proj_phs[mno])\n return rebuild\n def local_minimum(signal, size=150):\n x = np.linspace(-3,3,size+1)\n kernel = np.diff(np.exp(-x**2))/np.sum(np.exp(-x**2))\n signal_dfilt = np.convolve(signal, kernel, mode='same')\n slope_left, slope_right = signal_dfilt[:-1], signal_dfilt[1:]\n the_maxima = np.where(np.logical_and(slope_left > 0, slope_right < 0))[0]\n if the_maxima.size == 2:\n the_minimum = np.round(0.5*np.sum(the_maxima)).astype(int)\n print('> local_minimum : Found two maxima at : ' + str(the_maxima) + ' / minimum around : ' + str(the_minimum))\n return the_minimum\n else:\n print(\"> Cannot locate a minimum between : \" + str(np.size(the_maxima)) + ' maxima :(' )\n return 0 \n\n # fill holes & filter image\n img_seed = np.copy(img)\n img_seed[1:-1,1:-1] = img.min()\n img_filled = skmph.reconstruction(img_seed, img, method='dilation')\n img_pad, padsize = img_padding(img_filled, pad=16)\n img_filt = skfi.gaussian(img_pad, sigma=myinfo['smoothing'], preserve_range=True)\n myinfo['padsize'] = padsize\n\n # Find threshold from histogram, then threshold image and analyse it\n [hist, bins] = np.histogram(img_filt.ravel(), bins=np.linspace(-0.5,myinfo['max_lum']+0.5, 361)) # NOTE: bin number must mach length of theta (for bokeh CDS to be happy)\n if myinfo['threshold'] is None:\n myinfo['threshold'] = bins[local_minimum(hist)]\n img_th = img_pad < myinfo['threshold']\n labelled_img = skms.label(img_th)\n props = skms.regionprops_table(labelled_img, properties=('label', 'centroid', 'area', 'eccentricity', 'coords'))\n big = props['area'] > 100\n\n # Fill in small objects, clean up a bit\n x_toclean, y_toclean = np.array([], dtype=int), np.array([], dtype=int)\n for elno, xy in enumerate(props['coords']):\n if not big[elno]:\n x_toclean, y_toclean = np.append(x_toclean, xy[:,1]), np.append(y_toclean, xy[:,0])\n img_th[y_toclean, x_toclean] = 0\n props = pd.DataFrame.from_dict(props).drop(columns='coords')\n props = props[big].sort_values(by='area', ascending=False, ignore_index=True)\n props['label'] = np.arange(1,props.shape[0]+1)\n\n # If no objects, we can't analyse interface (== project on polar coordinates + do fourier modes)\n th_rebuild = np.linspace(-np.pi, np.pi, 360)\n nbubbles = np.size(props['area'])\n adapter = np.atleast_1d(np.ones(np.shape(props['area']))) # matching shape of rad, ecc, ... with scalar frameno & time\n local_time = (time - myinfo['reftime'])*1e-9\n\n if nbubbles > 0:\n # These will be saved later\n xctr, yctr = np.atleast_1d(props['centroid-1']), np.atleast_1d(props['centroid-0'])\n rad, ecc, label = np.atleast_1d(np.sqrt(props['area']/np.pi)), np.atleast_1d(props['eccentricity']), np.atleast_1d(props['label'])\n frameno, time = adapter*idx, adapter*local_time\n\n # This is not saved later, just used to check interface of the largest bubble (and verify threshold)\n bub0 = np.argmax(rad) \n img_pad_warp = sktr.warp_polar(img_pad, (yctr[bub0], xctr[bub0]), radius=1.4*rad[bub0]).T\n img_th_warp = sktr.warp_polar(img_th, (yctr[bub0], xctr[bub0]), radius=1.4*rad[bub0]).T\n coords = skms.find_contours(img_th)\n longest_contour = np.argmax([elem.shape[0] for elem in coords])\n coords = np.array(coords[longest_contour]) # I expect the longest contour to match the largest object ...\n coords = (coords - [yctr[bub0], xctr[bub0]])/rad[bub0] # Normally : only one contour\n th, r = np.arctan2(coords[:,0], coords[:,1]), np.sqrt(coords[:,0]**2 + coords[:,1]**2) - 1\n reorder = np.argsort(th)\n th, r = th[reorder], r[reorder]\n r_amps, r_phs = proj_fourier(r, th)\n img_pad_diff = skfi.gaussian(np.diff(img_pad_warp, axis=0), sigma=1)\n r_fit = 1 + build_fourier(r_amps, r_phs, th_rebuild)\n r_maxgrad = (np.argmax(img_pad_diff, axis=0) + 0.5)*1.4/np.shape(img_pad_warp)[0]\n else:\n img_pad_warp, img_th_warp = np.zeros((200, 360)), np.zeros((200, 360))\n r_fit, r_maxgrad = np.zeros(360), np.zeros(360)\n xctr, yctr, rad, ecc, = np.array([np.nan]), np.array([np.nan]), np.array([np.nan]), np.array([np.nan]) \n label, time, frameno = np.array([0]), np.array([local_time]), np.array([idx])\n\n # Putting everything in two dicts because there is a bug in Bokeh if singleton and 1d objects are mixed\n img_data = {'img': [img_pad], 'img_th': [img_th], 'img_polar': [img_pad_warp], 'img_th_polar': [img_th_warp], \n 'frame': frameno, 'time': time, 'label': label, 'x_px':xctr, 'y_px':yctr, 'rad':rad, 'ecc':ecc, 'padsize':[padsize]}\n line_data = {'theta': th_rebuild, 'r_fourier': r_fit, 'r_gradient': r_maxgrad, 'lum_hist': hist, 'lum_bins': bins[1:]}\n\n return img_data, line_data\n\n### WRITE HEADER OF FILES OR DATA #################################################\ndef write_csvheader(myfile, mylist):\n mystr = ''\n for elem in mylist:\n mystr += elem + ',' \n myfile.write(mystr[:-1] + '\\n')\n return 0\n\ndef write_logheader(myfile, mydict):\n for k, v in zip(mydict.keys(), mydict.values()):\n info_str = str(k) + ':' + str(v) + '\\n'\n myfile.write(info_str)\n print(info_str,end='')\n return 0\n\ndef format_data(data_dict, myinfo): # Data_dict is essentially img_data (or CDS_img.data)\n nrows, ncols = np.shape(data_dict['x_px'])[0], 8\n is_spurious = np.any(np.sum(data_dict['img'], axis=1) == 0) # Spurious == strange horizontal black lines\n data = np.zeros((nrows, ncols))\n\n if nrows > 0:\n data[:,0] = data_dict['frame']\n data[:,1] = data_dict['time']\n data[:,2] = data_dict['label']\n data[:,3] = data_dict['x_px']*myinfo['pixsize']\n data[:,4] = data_dict['y_px']*myinfo['pixsize']\n data[:,5] = data_dict['rad']*myinfo['pixsize']\n data[:,6] = data_dict['ecc']\n data[:,7] = is_spurious \n return data\n\ndef format_logstr(data_dict):\n is_spurious = np.any(np.sum(data_dict['img'], axis=1) == 0) # Spurious == strange horizontal black lines\n nstr = 'Frame=' + '{:06.0f}'.format(data_dict['frame'][0]) + ','\n tstr = 't=' + '{:.2f}'.format(data_dict['time'][0]) + ','\n labstr = 'n=' + '{:.0f}'.format(data_dict['label'][-1]) + ','\n xstr = 'x0=' + '{:.2f}'.format(data_dict['x_px'][0]) + ','\n ystr = 'y0=' + '{:.2f}'.format(data_dict['y_px'][0]) + ','\n rstr = 'r=' + '{:.2f}'.format(data_dict['rad'][0]) + ','\n spstr = 'spu=' + '{:d}'.format(is_spurious)\n return nstr + tstr + labstr + xstr + ystr + rstr + spstr\n\ndef save_snapshot(folder_location, img, pix_fmt=\"Mono12\", idx=0):\n rescaling = 1 + (pix_fmt==\"Mono12\")*(4095/255-1)\n img = (img[0].astype(np.int32)/rescaling).astype(np.uint8) # The [0] is some compatibility thing with Bokeh\n pilimg = Image.fromarray(img)\n pilimg.save(folder_location + '\\\\frame_' + '{:06d}'.format(idx) + '.png')\n \ndef init_figure(): \n # Essentially needs the CDS_img and CDS_line objects (from analyse_frame)\n # And myinfo object. Returns Bokeh figure objects\n\n mapper_bw = LinearColorMapper(palette=\"Greys256\")\n mapper_th = LinearColorMapper(palette=['rgba(0,0,0,0)', 'lime'], high=1, low=0)\n\n plotint = figure(title=\"Threshold : orange and pink closer is better\", height=300, width=800, tools=\"\")\n plotint.image(\"img_polar\", x=-np.pi, y=0, dw=2*np.pi, dh=1.4, color_mapper=mapper_bw, global_alpha=1, source=CDS_img)\n plotint.image(\"img_th_polar\", x=-np.pi, y=0, dw=2*np.pi, dh=1.4, color_mapper=mapper_th, global_alpha=0.15, source=CDS_img)\n plotint.line(x='theta', y='r_fourier', line_color='hotpink', line_width=2, line_dash='dashed', source=CDS_line)\n plotint.line(x='theta', y='r_gradient', line_color='orange', line_width=2, line_dash='dotted', source=CDS_line)\n plotint.y_range.start, plotint.y_range.end = 0.85, 1.15\n plotint.x_range.start, plotint.x_range.end = -np.pi, np.pi\n plotint.xaxis.axis_label, plotint.yaxis.axis_label = 'θ', 'r/R'\n\n f_height, f_width = np.shape(CDS_img.data['img'][0]) # Affected by img_padding (used in analyse_frame) \n hist_max = np.max(CDS_line.data['lum_hist'])\n\n plotimg = figure(height=400, width=400, title='Raw Reference Frame', tools=\"\", match_aspect=True)\n plotpdf = figure(height=400, width=400, title='Histogram', tools=\"\")\n plotimg.image(\"img\", dw=f_width, dh=f_height, x=0, y=0, color_mapper=mapper_bw, source=CDS_img)\n # plotimg.image(\"img_th\", dw=f_width, dh=f_height, x=0, y=0, color_mapper=mapper_th, global_alpha=0.25, source=CDS_img)\n plotimg.cross(x=\"x_px\", y=\"y_px\", size=10, line_color='lime', source=CDS_img)\n plotpdf.line([myinfo['threshold'],myinfo['threshold']], [0, hist_max], line_dash='dashed')\n plotpdf.line(x=\"lum_bins\", y='lum_hist', source=CDS_line)\n\n return plotint, plotimg, plotpdf\n\n##### SAY HI TO THE CAMERA and set some parameters\ndef init_camera(myinfo):\n camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice())\n camera.Close()\n camera.Open()\n myinfo['cameraname'] = camera.GetDeviceInfo().GetModelName()\n camera.AcquisitionFrameRateEnable.SetValue(True), camera.AcquisitionFrameRateAbs.SetValue(5) # Setting fps to 5\n camera.BinningModeVertical.SetValue('Averaging'), camera.BinningModeHorizontal.SetValue('Averaging') # Activating binning in x & y\n camera.BinningHorizontal.SetValue(2), camera.BinningVertical.SetValue(2) # Using 2^1 (3 would be 2^2 I guess) binning \n camera.Width.SetValue(imagesize[0]), camera.Height.SetValue(imagesize[1]) \n camera.CenterX.SetValue(True), camera.CenterY.SetValue(True)\n camera.ExposureTimeAbs.SetValue(myinfo['exposure'])\n camera.PixelFormat.SetValue(myinfo['pixel_format'])\n camera.GevTimestampControlReset()\n return camera\n\n# # Emulate with a PNG file \n# img = Image.open('C:\\\\Users\\\\saint-michel\\\\Documents\\\\Python\\\\Bubbles_20211109\\\\frame_00000.png')\n# img = np.array(img)\n# time_ref = 0\n# pixel_format='Mono8'\n# cameraname = 'None'\n\n# Preparing acquisition information for later \nglobal_time_ref = time.gmtime()\ngt_str = time.strftime('%Y/%m/%d %H:%M:%S', global_time_ref)\npixsize = 1000/zoom/90.4 # in UM per PX\nmyinfo = {'time_ref': gt_str, 'zoom': zoom, 'pixsize': pixsize, 'pixel_format': pixel_format,\n 'threshold': threshold, 'width':imagesize[1], 'height':imagesize[0], 'smoothing':filter_size, 'exposure':exposure,\n 'pixel_fmt': pixel_format}\nif myinfo[\"pixel_format\"] == 'Mono12':\n myinfo['max_lum'] = 4095\nelse: \n myinfo['max_lum'] = 255\nmycolumns = ['frame', 'time', 'label', 'x', 'y', 'radius', 'eccentricity', 'spurious']\nmyunits = ['1', 's', '1', 'um', 'um', 'um', '1', '1']\nmyfmt = '%05d,%07.1f,%1d,%03.2f,%03.2f,%03.2f,%1.2f,%1d'\nidx = 0\n\n# Analysing image\ncamera = init_camera(myinfo)\nrawframe = camera.GrabOne(5000)\ncamera.Close()\n\nmyinfo['reftime'] = rawframe.TimeStamp\nref_imgdata, ref_linedata = analyse_frame(rawframe.Array, myinfo, time=rawframe.TimeStamp)\ndata_array = format_data(ref_imgdata, myinfo)\nlog_str = format_logstr(ref_imgdata)\nCDS_img, CDS_line = ColumnDataSource(data=ref_imgdata), ColumnDataSource(data=ref_linedata)\n\n#### DISPLAYING / LOGGING INFO \nos.makedirs(folder_location, exist_ok=True)\nlog_file = codecs.open(folder_location + \"\\\\log.txt\", mode='w', encoding=\"utf-8\")\ndata_file = codecs.open(folder_location + \"\\\\data.csv\", mode='w', encoding=\"utf-8\")\nwrite_logheader(log_file, myinfo)\nwrite_csvheader(data_file, myunits)\nwrite_csvheader(data_file, mycolumns)\nnp.savetxt(data_file, data_array, fmt=myfmt, delimiter=',')\nlog_file.write(log_str + '\\n')\nsave_snapshot(folder_location, ref_imgdata['img'])\nlog_file.close()\ndata_file.close()\n\n#### PLOTTING RESULTS #########\noutput_notebook()\nplotint, plotimg, plotpdf = init_figure()\nBokehModel(column(row(plotimg, plotpdf), plotint))",
"> local_minimum : Found two maxima at : [101 327] / minimum around : 214\ntime_ref:2021/12/16 11:42:58\nzoom:3\npixsize:3.6873156342182885\npixel_format:Mono12\nthreshold:2434.3444444444444\nwidth:512\nheight:512\nsmoothing:10\nexposure:100\npixel_fmt:Mono12\nmax_lum:4095\ncameraname:acA1300-60gm\nreftime:228432030\npadsize:16\n"
]
],
[
[
"## Step 2 : FRAME GRABBING LOOP \n\nSome bits have been initialised in Step 1, so please run it at least once\n\n* Spurious image detection with `spurious` or `spu`\n* Provide time stamps for each image\n* Can be restarted if stopped\n* Handles events (bubble disappearing, appearing, moving, ...)\n* Try an extra `camera.Close()` if you interrupted the program",
"_____no_output_____"
]
],
[
[
"import traceback\nfrom IPython.display import clear_output\n\n############# (Bad) event management routine #########################\"\"\n\ndef bubble_event(now_data, ref_data):\n event_str = ''\n nbubble_change = np.size(now_data['label']) != np.size(ref_data['label'])\n chunk_timeout = now_data['frame'][0] - ref_data['frame'][0] > chunk_size\n xy_change, r_change = False, False\n\n if not nbubble_change: \n \n r_change = np.abs(now_data['rad'] - ref_data['rad'])\n x_change = np.abs(now_data['x_px'] - ref_data['x_px'])\n y_change = np.abs(now_data['y_px'] - ref_data['y_px'])\n\n r_change = any(r_change > 1)\n xy_change = any(x_change > 3) or any(y_change > 3)\n\n if r_change:\n event_str = ' | Event ! One (or more) bubbles have changed radius ... Refreshing & Saving'\n if xy_change:\n event_str = ' | Event ! One (or more) bubbles have changed location ... Refreshing & Saving'\n if chunk_timeout:\n event_str = ' | Event ! There has been : ' + str(chunk_size) + ' frames with no event ... Refreshing & Saving'\n if nbubble_change:\n event_str = ' | Event ! One (or several) bubbles have appeared or disappeared ... Refreshing & Saving'\n \n any_change = xy_change or r_change or nbubble_change or chunk_timeout\n\n return any_change, event_str\n\n########################## MAIN SEQUENCE #####################################\n\ncamera.Open()\n\nif not camera.IsGrabbing():\n camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly)\n\ntry:\n while True:\n data_file = open(folder_location + '\\\\data.csv', 'a', encoding='utf-8')\n log_file = open(folder_location + '\\\\log.txt', 'a', encoding='utf-8')\n grab = camera.RetrieveResult(5000, pylon.TimeoutHandling_ThrowException) # I don't really mind if image comes late, I just want to know when it arrives\n\n if grab.GrabSucceeded(): # We could fail for any other reason \n idx += 1\n now_imgdata, now_linedata = analyse_frame(grab.Array, myinfo, grab.TimeStamp)\n data_array = np.append(data_array, format_data(now_imgdata, myinfo), axis=0)\n grab.Release()\n is_event, event_str = bubble_event(now_imgdata, ref_imgdata)\n log_str = format_logstr(now_imgdata)\n print(log_str + event_str)\n\n if is_event:\n np.savetxt(data_file, data_array, fmt=myfmt, delimiter=',')\n data_file.flush()\n save_snapshot(folder_location, now_imgdata['img'], pix_fmt=\"Mono12\", idx=idx)\n data_array = np.zeros((0,8))\n ref_imgdata = now_imgdata\n CDS_img.data = now_imgdata\n CDS_line.data = now_linedata\n log_file.write(log_str + event_str + '\\n')\n\n # Clear display from time to time\n if np.mod(idx,10) == 0:\n clear_output() \n\n time.sleep(1)\n\n################################################################################################\n## HANDLING ERRORS SECTION HERE ... #############################################################\n#################################################################################################\nexcept pylon.TimeoutException:\n timeout_str = ' /!\\\\ Timeout ... ! '\n log_file.write(log_str + timeout_str + '\\n')\n print(timeout_str)\n pass\n\nexcept SystemError as e:\n ## I KNOW IT IS SUPER UGLY, HATE ME ALL YOU WANT\n if \"KeyboardInterrupt\" in traceback.format_exc():\n interrupt_str = ' /!\\\\ Keyboard Interrupted ... ! '\n log_file.write(log_str + interrupt_str + '\\n')\n print(interrupt_str)\n grab.Release()\n camera.StopGrabbing()\n camera.Close()\n data_file.close()\n log_file.close()\n else:\n err_str = 'N°' + str(idx) + e\n log_file.write(err_str)\n print(err_str)\n pass\n\nexcept KeyboardInterrupt:\n interrupt_str = ' /!\\\\ Keyboard Interrupted ... ! '\n log_file.write(log_str + interrupt_str + '\\n')\n print(interrupt_str)\n grab.Release()\n camera.StopGrabbing()\n camera.Close() \n data_file.close()\n log_file.close()",
"Frame=089611,t=108301.80,n=1,x0=18.83,y0=125.36,r=5.78,spu=0\nFrame=089612,t=108303.00,n=1,x0=18.83,y0=125.36,r=5.78,spu=0\nFrame=089613,t=108304.20,n=1,x0=18.83,y0=125.36,r=5.78,spu=0\nFrame=089614,t=108305.40,n=1,x0=18.93,y0=125.27,r=5.81,spu=0\nFrame=089615,t=108306.60,n=1,x0=18.83,y0=125.36,r=5.78,spu=0\nFrame=089616,t=108308.00,n=1,x0=18.93,y0=125.27,r=5.81,spu=0\nFrame=089617,t=108309.20,n=1,x0=18.83,y0=125.36,r=5.78,spu=0\nFrame=089618,t=108310.40,n=1,x0=18.74,y0=125.29,r=5.73,spu=0\n"
],
[
"import skimage.filters as skfi\nfrom skimage.data import astronaut\nfrom bokeh.plotting import figure, show, row\nfrom bokeh.models import LinearColorMapper\nfrom bokeh.palettes import Greys256\nimport numpy as np\n\n\nast = astronaut()[:,:,0]/255\nheight, width = np.shape(ast)\nastf = skfi.gaussian(ast, sigma=1)\ncmapper = LinearColorMapper(palette=Greys256, low=0, high=1)\nf1 = figure(width=300, height=300, match_aspect=True)\nf2 = figure(width=300, height=300, match_aspect=True)\nf1.image([ast], x=0, y=0, dw=height, dh=width, color_mapper=cmapper)\nf2.image([astf], x=0, y=0, dw=height, dh=width, color_mapper=cmapper)\nshow(row(f1,f2))\n",
"_____no_output_____"
],
[
"ast",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
e77c1bea7a445255492c3a4ee3c1dbd9ff4bc7e3 | 252,730 | ipynb | Jupyter Notebook | rl-basics/temporal-difference/Temporal_Difference.ipynb | AmrMKayid/udacity-drl | 13755b2304f87563f5480198065f4d4e56d73c6f | [
"MIT"
] | null | null | null | rl-basics/temporal-difference/Temporal_Difference.ipynb | AmrMKayid/udacity-drl | 13755b2304f87563f5480198065f4d4e56d73c6f | [
"MIT"
] | null | null | null | rl-basics/temporal-difference/Temporal_Difference.ipynb | AmrMKayid/udacity-drl | 13755b2304f87563f5480198065f4d4e56d73c6f | [
"MIT"
] | null | null | null | 314.732254 | 48,408 | 0.913366 | [
[
[
"# Temporal-Difference Methods\n\nIn this notebook, you will write your own implementations of many Temporal-Difference (TD) methods.\n\nWhile we have provided some starter code, you are welcome to erase these hints and write your code from scratch.\n\n---\n\n### Part 0: Explore CliffWalkingEnv\n\nWe begin by importing the necessary packages.",
"_____no_output_____"
]
],
[
[
"import sys\nimport gym\nimport random\nimport numpy as np\nfrom collections import defaultdict, deque\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nimport check_test\nfrom plot_utils import plot_values",
"_____no_output_____"
]
],
[
[
"Use the code cell below to create an instance of the [CliffWalking](https://github.com/openai/gym/blob/master/gym/envs/toy_text/cliffwalking.py) environment.",
"_____no_output_____"
]
],
[
[
"env = gym.make('CliffWalking-v0')",
"_____no_output_____"
]
],
[
[
"The agent moves through a $4\\times 12$ gridworld, with states numbered as follows:\n```\n[[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],\n [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23],\n [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35],\n [36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47]]\n```\nAt the start of any episode, state `36` is the initial state. State `47` is the only terminal state, and the cliff corresponds to states `37` through `46`.\n\nThe agent has 4 potential actions:\n```\nUP = 0\nRIGHT = 1\nDOWN = 2\nLEFT = 3\n```\n\nThus, $\\mathcal{S}^+=\\{0, 1, \\ldots, 47\\}$, and $\\mathcal{A} =\\{0, 1, 2, 3\\}$. Verify this by running the code cell below.",
"_____no_output_____"
]
],
[
[
"print(env.action_space)\nprint(env.observation_space)",
"Discrete(4)\nDiscrete(48)\n"
]
],
[
[
"In this mini-project, we will build towards finding the optimal policy for the CliffWalking environment. The optimal state-value function is visualized below. Please take the time now to make sure that you understand _why_ this is the optimal state-value function.\n\n_**Note**: You can safely ignore the values of the cliff \"states\" as these are not true states from which the agent can make decisions. For the cliff \"states\", the state-value function is not well-defined._",
"_____no_output_____"
]
],
[
[
"# define the optimal state-value function\nV_opt = np.zeros((4,12))\nV_opt[0:13][0] = -np.arange(3, 15)[::-1]\nV_opt[0:13][1] = -np.arange(3, 15)[::-1] + 1\nV_opt[0:13][2] = -np.arange(3, 15)[::-1] + 2\nV_opt[3][0] = -13\n\nplot_values(V_opt)",
"/Users/amrmkayid/anaconda3/envs/kayddrl/lib/python3.7/site-packages/matplotlib/cbook/__init__.py:424: MatplotlibDeprecationWarning: \nPassing one of 'on', 'true', 'off', 'false' as a boolean is deprecated; use an actual boolean (True/False) instead.\n warn_deprecated(\"2.2\", \"Passing one of 'on', 'true', 'off', 'false' as a \"\n/Users/amrmkayid/anaconda3/envs/kayddrl/lib/python3.7/site-packages/matplotlib/cbook/__init__.py:424: MatplotlibDeprecationWarning: \nPassing one of 'on', 'true', 'off', 'false' as a boolean is deprecated; use an actual boolean (True/False) instead.\n warn_deprecated(\"2.2\", \"Passing one of 'on', 'true', 'off', 'false' as a \"\n/Users/amrmkayid/anaconda3/envs/kayddrl/lib/python3.7/site-packages/matplotlib/cbook/__init__.py:424: MatplotlibDeprecationWarning: \nPassing one of 'on', 'true', 'off', 'false' as a boolean is deprecated; use an actual boolean (True/False) instead.\n warn_deprecated(\"2.2\", \"Passing one of 'on', 'true', 'off', 'false' as a \"\n/Users/amrmkayid/anaconda3/envs/kayddrl/lib/python3.7/site-packages/matplotlib/cbook/__init__.py:424: MatplotlibDeprecationWarning: \nPassing one of 'on', 'true', 'off', 'false' as a boolean is deprecated; use an actual boolean (True/False) instead.\n warn_deprecated(\"2.2\", \"Passing one of 'on', 'true', 'off', 'false' as a \"\n"
]
],
[
[
"### Part 1: TD Control: Sarsa\n\nIn this section, you will write your own implementation of the Sarsa control algorithm.\n\nYour algorithm has four arguments:\n- `env`: This is an instance of an OpenAI Gym environment.\n- `num_episodes`: This is the number of episodes that are generated through agent-environment interaction.\n- `alpha`: This is the step-size parameter for the update step.\n- `gamma`: This is the discount rate. It must be a value between 0 and 1, inclusive (default value: `1`).\n\nThe algorithm returns as output:\n- `Q`: This is a dictionary (of one-dimensional arrays) where `Q[s][a]` is the estimated action value corresponding to state `s` and action `a`.\n\nPlease complete the function in the code cell below.\n\n(_Feel free to define additional functions to help you to organize your code._)",
"_____no_output_____"
]
],
[
[
"def update_Q_sarsa(alpha, gamma, Q, state, action, reward, next_state=None, next_action=None):\n current = Q[state][action]\n Qsa_next = Q[next_state][next_action] if next_state is not None else 0 \n \n target = reward + (gamma * Qsa_next) \n new_value = current + (alpha * (target - current))\n\n return new_value",
"_____no_output_____"
],
[
"def epsilon_greedy(Q, state, nA, eps):\n \n if random.random() > eps:\n return np.argmax(Q[state])\n else:\n return random.choice(np.arange(env.action_space.n))",
"_____no_output_____"
],
[
"def sarsa(env, num_episodes, alpha, gamma=1.0, plot_every=100):\n nA = env.action_space.n\n Q = defaultdict(lambda: np.zeros(env.nA))\n\n # initialize performance monitor\n tmp_scores = deque(maxlen=plot_every) # deque for keeping track of scores\n avg_scores = deque(maxlen=num_episodes) # average scores over every plot_every episodes\n \n # loop over episodes\n for i_episode in range(1, num_episodes+1):\n # monitor progress\n if i_episode % 100 == 0:\n print(\"\\rEpisode {}/{}\".format(i_episode, num_episodes), end=\"\")\n sys.stdout.flush() \n \n ## TODO: complete the function\n score = 0\n state = env.reset()\n \n eps = 1.0 / i_episode\n action = epsilon_greedy(Q, state, nA, eps)\n \n while True:\n next_state, reward, done, info = env.step(action)\n score += reward\n \n if not done:\n next_action = epsilon_greedy(Q, next_state, nA, eps)\n Q[state][action] = update_Q_sarsa(alpha, gamma, Q, \\\n state, action, reward, next_state, next_action)\n \n state = next_state\n action = next_action\n\n if done:\n Q[state][action] = update_Q_sarsa(alpha, gamma, Q, \\\n state, action, reward)\n\n tmp_scores.append(score)\n break\n \n if (i_episode % plot_every == 0):\n avg_scores.append(np.mean(tmp_scores))\n \n \n plt.plot(np.linspace(0,num_episodes,len(avg_scores),endpoint=False), np.asarray(avg_scores))\n plt.xlabel('Episode Number')\n plt.ylabel('Average Reward (Over Next %d Episodes)' % plot_every)\n plt.show()\n # print best 100-episode performance\n print(('Best Average Reward over %d Episodes: ' % plot_every), np.max(avg_scores)) \n \n return Q",
"_____no_output_____"
]
],
[
[
"Use the next code cell to visualize the **_estimated_** optimal policy and the corresponding state-value function. \n\nIf the code cell returns **PASSED**, then you have implemented the function correctly! Feel free to change the `num_episodes` and `alpha` parameters that are supplied to the function. However, if you'd like to ensure the accuracy of the unit test, please do not change the value of `gamma` from the default.",
"_____no_output_____"
]
],
[
[
"# obtain the estimated optimal policy and corresponding action-value function\nQ_sarsa = sarsa(env, 5000, .01)\n\n# print the estimated optimal policy\npolicy_sarsa = np.array([np.argmax(Q_sarsa[key]) if key in Q_sarsa else -1 for key in np.arange(48)]).reshape(4,12)\ncheck_test.run_check('td_control_check', policy_sarsa)\nprint(\"\\nEstimated Optimal Policy (UP = 0, RIGHT = 1, DOWN = 2, LEFT = 3, N/A = -1):\")\nprint(policy_sarsa)\n\n# plot the estimated optimal state-value function\nV_sarsa = ([np.max(Q_sarsa[key]) if key in Q_sarsa else 0 for key in np.arange(48)])\nplot_values(V_sarsa)",
"Episode 5000/5000"
]
],
[
[
"### Part 2: TD Control: Q-learning\n\nIn this section, you will write your own implementation of the Q-learning control algorithm.\n\nYour algorithm has four arguments:\n- `env`: This is an instance of an OpenAI Gym environment.\n- `num_episodes`: This is the number of episodes that are generated through agent-environment interaction.\n- `alpha`: This is the step-size parameter for the update step.\n- `gamma`: This is the discount rate. It must be a value between 0 and 1, inclusive (default value: `1`).\n\nThe algorithm returns as output:\n- `Q`: This is a dictionary (of one-dimensional arrays) where `Q[s][a]` is the estimated action value corresponding to state `s` and action `a`.\n\nPlease complete the function in the code cell below.\n\n(_Feel free to define additional functions to help you to organize your code._)",
"_____no_output_____"
]
],
[
[
"def update_Q_learning(alpha, gamma, Q, state, action, reward, next_state=None):\n current = Q[state][action]\n Qsa_next = np.max(Q[next_state]) if next_state is not None else 0 \n \n target = reward + (gamma * Qsa_next)\n new_value = current + (alpha * (target - current))\n return new_value",
"_____no_output_____"
],
[
"def q_learning(env, num_episodes, alpha, gamma=1.0, plot_every=100):\n nA = env.action_space.n\n Q = defaultdict(lambda: np.zeros(env.nA))\n\n # initialize performance monitor\n tmp_scores = deque(maxlen=plot_every)\n avg_scores = deque(maxlen=num_episodes)\n \n # loop over episodes\n for i_episode in range(1, num_episodes+1):\n # monitor progress\n if i_episode % 100 == 0:\n print(\"\\rEpisode {}/{}\".format(i_episode, num_episodes), end=\"\")\n sys.stdout.flush()\n \n ## TODO: complete the function\n score = 0\n state = env.reset()\n \n eps = 1.0 / i_episode\n action = epsilon_greedy(Q, state, nA, eps)\n \n while True:\n next_state, reward, done, info = env.step(action)\n score += reward\n \n if not done:\n next_action = epsilon_greedy(Q, next_state, nA, eps)\n Q[state][action] = update_Q_learning(alpha, gamma, Q, \\\n state, action, reward, next_state)\n \n state = next_state\n\n if done:\n tmp_scores.append(score)\n break\n \n if (i_episode % plot_every == 0):\n avg_scores.append(np.mean(tmp_scores))\n \n \n plt.plot(np.linspace(0,num_episodes,len(avg_scores),endpoint=False), np.asarray(avg_scores))\n plt.xlabel('Episode Number')\n plt.ylabel('Average Reward (Over Next %d Episodes)' % plot_every)\n plt.show()\n # print best 100-episode performance\n print(('Best Average Reward over %d Episodes: ' % plot_every), np.max(avg_scores)) \n \n return Q",
"_____no_output_____"
]
],
[
[
"Use the next code cell to visualize the **_estimated_** optimal policy and the corresponding state-value function. \n\nIf the code cell returns **PASSED**, then you have implemented the function correctly! Feel free to change the `num_episodes` and `alpha` parameters that are supplied to the function. However, if you'd like to ensure the accuracy of the unit test, please do not change the value of `gamma` from the default.",
"_____no_output_____"
]
],
[
[
"# obtain the estimated optimal policy and corresponding action-value function\nQ_sarsamax = q_learning(env, 5000, .01)\n\n# print the estimated optimal policy\npolicy_sarsamax = np.array([np.argmax(Q_sarsamax[key]) if key in Q_sarsamax else -1 for key in np.arange(48)]).reshape((4,12))\ncheck_test.run_check('td_control_check', policy_sarsamax)\nprint(\"\\nEstimated Optimal Policy (UP = 0, RIGHT = 1, DOWN = 2, LEFT = 3, N/A = -1):\")\nprint(policy_sarsamax)\n\n# plot the estimated optimal state-value function\nplot_values([np.max(Q_sarsamax[key]) if key in Q_sarsamax else 0 for key in np.arange(48)])",
"Episode 5000/5000"
]
],
[
[
"### Part 3: TD Control: Expected Sarsa\n\nIn this section, you will write your own implementation of the Expected Sarsa control algorithm.\n\nYour algorithm has four arguments:\n- `env`: This is an instance of an OpenAI Gym environment.\n- `num_episodes`: This is the number of episodes that are generated through agent-environment interaction.\n- `alpha`: This is the step-size parameter for the update step.\n- `gamma`: This is the discount rate. It must be a value between 0 and 1, inclusive (default value: `1`).\n\nThe algorithm returns as output:\n- `Q`: This is a dictionary (of one-dimensional arrays) where `Q[s][a]` is the estimated action value corresponding to state `s` and action `a`.\n\nPlease complete the function in the code cell below.\n\n(_Feel free to define additional functions to help you to organize your code._)",
"_____no_output_____"
]
],
[
[
"def update_Q_expected_sarsa(alpha, gamma, nA, eps, Q, state, action, reward, next_state=None):\n current = Q[state][action] \n policy_s = np.ones(nA) * eps / nA \n policy_s[np.argmax(Q[next_state])] = 1 - eps + (eps / nA)\n Qsa_next = np.dot(Q[next_state], policy_s) \n target = reward + (gamma * Qsa_next) \n new_value = current + (alpha * (target - current))\n return new_value",
"_____no_output_____"
],
[
"def expected_sarsa(env, num_episodes, alpha, gamma=1.0, plot_every=100):\n nA = env.action_space.n\n Q = defaultdict(lambda: np.zeros(env.nA))\n\n # initialize performance monitor\n tmp_scores = deque(maxlen=plot_every)\n avg_scores = deque(maxlen=num_episodes)\n \n # loop over episodes\n for i_episode in range(1, num_episodes+1):\n # monitor progress\n if i_episode % 100 == 0:\n print(\"\\rEpisode {}/{}\".format(i_episode, num_episodes), end=\"\")\n sys.stdout.flush()\n \n ## TODO: complete the function\n score = 0\n state = env.reset()\n eps = 0.005\n \n while True:\n action = epsilon_greedy(Q, state, nA, eps)\n next_state, reward, done, info = env.step(action)\n score += reward\n\n Q[state][action] = update_Q_expected_sarsa(alpha, gamma, nA, eps, Q, \\\n state, action, reward, next_state)\n\n state = next_state\n\n if done:\n tmp_scores.append(score)\n break\n \n if (i_episode % plot_every == 0):\n avg_scores.append(np.mean(tmp_scores))\n \n \n plt.plot(np.linspace(0,num_episodes,len(avg_scores),endpoint=False), np.asarray(avg_scores))\n plt.xlabel('Episode Number')\n plt.ylabel('Average Reward (Over Next %d Episodes)' % plot_every)\n plt.show()\n # print best 100-episode performance\n print(('Best Average Reward over %d Episodes: ' % plot_every), np.max(avg_scores)) \n \n return Q",
"_____no_output_____"
]
],
[
[
"Use the next code cell to visualize the **_estimated_** optimal policy and the corresponding state-value function. \n\nIf the code cell returns **PASSED**, then you have implemented the function correctly! Feel free to change the `num_episodes` and `alpha` parameters that are supplied to the function. However, if you'd like to ensure the accuracy of the unit test, please do not change the value of `gamma` from the default.",
"_____no_output_____"
]
],
[
[
"# obtain the estimated optimal policy and corresponding action-value function\nQ_expsarsa = expected_sarsa(env, 10000, 1)\n\n# print the estimated optimal policy\npolicy_expsarsa = np.array([np.argmax(Q_expsarsa[key]) if key in Q_expsarsa else -1 for key in np.arange(48)]).reshape(4,12)\ncheck_test.run_check('td_control_check', policy_expsarsa)\nprint(\"\\nEstimated Optimal Policy (UP = 0, RIGHT = 1, DOWN = 2, LEFT = 3, N/A = -1):\")\nprint(policy_expsarsa)\n\n# plot the estimated optimal state-value function\nplot_values([np.max(Q_expsarsa[key]) if key in Q_expsarsa else 0 for key in np.arange(48)])",
"Episode 10000/10000"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
e77c2d9b0ca9c8a5571127067fc53b5533041e72 | 9,911 | ipynb | Jupyter Notebook | hw 18_11_2021.ipynb | yuraMovsesyan/msu_hw | e7a558690a19f059173752be862c1b9141297416 | [
"MIT"
] | null | null | null | hw 18_11_2021.ipynb | yuraMovsesyan/msu_hw | e7a558690a19f059173752be862c1b9141297416 | [
"MIT"
] | null | null | null | hw 18_11_2021.ipynb | yuraMovsesyan/msu_hw | e7a558690a19f059173752be862c1b9141297416 | [
"MIT"
] | null | null | null | 29.673653 | 134 | 0.503885 | [
[
[
"Hw 18_11_2021",
"_____no_output_____"
]
],
[
[
"# Проверка целостности матрицы, т.е. количество элементов в строках\n# должны совпадать, тип матрицы должен быть список\ndef CheckMatrixCompletness(matrix):\n # проверяем тип всей матрицы\n if type(matrix) is not list:\n return False\n if type(matrix[0]) is not list:\n return False\n # определим количество столбцов\n column_num = len(matrix[0])\n # проверяем целостность всех строк\n for row in matrix:\n if type(row) is not list:\n return False\n if len(row) != column_num:\n return False\n # Проверка, что все элементы матрицы - числа\n for element in row:\n if type(element) is not int and type(element) is not float:\n return False\n return True",
"_____no_output_____"
],
[
"def AddVectors(vector_a, vector_b):\n if len(vector_a) != len(vector_b):\n return \"Vector lengths aren't equal!\"\n sum_vector = []\n for i in range(len(vector_a)):\n sum_vector.append(vector_a[i] + vector_b[i])\n return sum_vector",
"_____no_output_____"
],
[
"def MultiplyToScalar(vector, scalar):\n res_vector = []\n for elem in vector:\n res_vector.append(scalar * elem)\n return res_vector",
"_____no_output_____"
],
[
"def GetColumn(matrix, column):\n result = []\n \n for i in range(0, len(matrix)):\n result += [matrix[i][column]]\n return result",
"_____no_output_____"
],
[
"def TranspouseMatrix(matrix):\n if not CheckMatrixCompletness(matrix):\n return \"Matrix is incorrect\"\n result = []\n for i in range(len(matrix[0])):\n result += [[]]\n for j in range(len(matrix)):\n result[i] += [matrix[j][i]]\n return result",
"_____no_output_____"
],
[
"'''\n [1 2] [1 2 3] = [9 12 15]\n [3 4] [4 5 6] = [19 26 33]\n \n 1 * [1 3]' + 4 * [2 4]' = [1 3]' + [8 16]' = [9 19]'\n 2 * [1 3]' + 5 * [2 4]' = [2 6]' + [10 20]' = [12 26]'\n 3 * [1 3]' + 6 * [2 4]' = [3 9]' + [12 24]' = [15 33]'\n'''\ndef MatrixMultiplation(matrix_a, matrix_b):\n # Проверка соответствия на размеров матриц на произведение\n matrix_a_shape = CalculateMatrixShape(matrix_a)\n matrix_b_shape = CalculateMatrixShape(matrix_b)\n \n if type(matrix_a_shape) is str:\n return \"Matrix_a is incorrect\"\n if type(matrix_b_shape) is str:\n return \"Matrix_b is incorrect\"\n if matrix_a_shape[1] != matrix_b_shape[0]:\n return \"Matrices shapes are not insufficient.\"\n # --------------------------------------------------------\n \n #return \"Ok\"\n \n result = []\n \n for matrix_b_column_id in range(0, len(matrix_b[0])):\n #print(GetColumn(matrix_b, matrix_b_column_id))\n matrix_b_column = GetColumn(matrix_b, matrix_b_column_id)\n vec_res = [0] * len(matrix_a)\n for matrix_a_column_id in range(0, len(matrix_a[0])):\n vec = MultiplyToScalar(GetColumn(matrix_a, matrix_a_column_id), matrix_b_column[matrix_a_column_id])\n vec_res = AddVectors(vec_res, vec)\n #print(\"--\", GetColumn(matrix_a, matrix_a_column_id), \"--\", matrix_b_column[matrix_a_column_id], \"--\", vec)\n #print (\"!!!\", vec_res)\n result += [vec_res]\n return TranspouseMatrix(result)",
"_____no_output_____"
],
[
"# Вычисление размеров матрицы\ndef CalculateMatrixShape(matrix):\n if not CheckMatrixCompletness(matrix):\n return \"Matrix is incorrect\"\n # Количетсво строк\n row_num = len(matrix)\n # Количетсво столбцов\n col_num = len(matrix[0])\n return (row_num, col_num)",
"_____no_output_____"
],
[
"def MatrixMultiplyToScalar(matrix_a, scalar):\n # Проверка\n matrix_a_shape = CalculateMatrixShape(matrix_a)\n \n if type(matrix_a_shape) is str:\n return \"Matrix_a is incorrect\"\n # --------------------------------------------------------\n \n matrix_a = [] + matrix_a\n for i in range(matrix_a_shape[0]):\n for j in range(matrix_a_shape[1]):\n matrix_a[i][j] *= scalar\n return matrix_a",
"_____no_output_____"
],
[
"from copy import deepcopy\n\ndef det(arr):\n size_arr = len(arr)\n if size_arr == 1: return arr[0][0]\n result = 0\n for index_x in range(size_arr):\n arr_deepcopy = deepcopy(arr)\n del (arr_deepcopy[0])\n for i in range(len(arr_deepcopy)):\n del (arr_deepcopy[i][index_x])\n result += arr[0][index_x] * (-1 if index_x & 1 else 1 ) * det(arr_deepcopy)\n return result",
"_____no_output_____"
],
[
"from copy import deepcopy\n\n#Дополнительный Минор \ndef AdditionalMinor(matrix, row, col):\n if not CheckMatrixCompletness(matrix):\n return \"Matrix is incorrect\"\n \n row_num, _ = CalculateMatrixShape(matrix)\n \n matrix = deepcopy(matrix)\n \n del (matrix[row])\n \n for i in range(row_num - 1):\n del (matrix[i][col])\n \n return det(matrix)",
"_____no_output_____"
],
[
"#Алгебраическое дополнение\ndef AlgebraiComplement(matrix, row, col):\n if not CheckMatrixCompletness(matrix):\n return \"Matrix is incorrect\"\n return (-1)**(row + col) * AdditionalMinor(matrix, row, col)",
"_____no_output_____"
],
[
"def MatrixInverse(matrix):\n if not CheckMatrixCompletness(matrix):\n return \"Matrix is incorrect\"\n \n matrixDet = det(matrix)\n \n if matrixDet == 0:\n return \"Det = 0\"\n \n row_num, col_num = CalculateMatrixShape(matrix)\n\n result = []\n \n for i in range(row_num):\n result += [[]]\n for j in range(col_num):\n result[i] += [AlgebraiComplement(matrix, j, i)]\n \n \n\n return MatrixMultiplyToScalar(result, 1 / matrixDet)",
"_____no_output_____"
],
[
"a = [[-1, 2, -2],\n [2, -1, 5],\n [3, -2, 4]]\n\nprint (MatrixInverse(a))",
"[[0.6000000000000001, -0.4, 0.8], [0.7000000000000001, 0.2, 0.1], [-0.1, 0.4, -0.30000000000000004]]\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e77c344ae9396a97b80bffe504d9cb2fd1e96366 | 573,185 | ipynb | Jupyter Notebook | transfer-learning/Transfer_Learning.ipynb | sergio-lira/deep-learning101 | 56807565a04a306ad725a77ecce97d4d6859a088 | [
"MIT"
] | null | null | null | transfer-learning/Transfer_Learning.ipynb | sergio-lira/deep-learning101 | 56807565a04a306ad725a77ecce97d4d6859a088 | [
"MIT"
] | null | null | null | transfer-learning/Transfer_Learning.ipynb | sergio-lira/deep-learning101 | 56807565a04a306ad725a77ecce97d4d6859a088 | [
"MIT"
] | null | null | null | 459.651163 | 260,686 | 0.926847 | [
[
[
"# Transfer Learning\n\nMost of the time you won't want to train a whole convolutional network yourself. Modern ConvNets training on huge datasets like ImageNet take weeks on multiple GPUs. Instead, most people use a pretrained network either as a fixed feature extractor, or as an initial network to fine tune. In this notebook, you'll be using [VGGNet](https://arxiv.org/pdf/1409.1556.pdf) trained on the [ImageNet dataset](http://www.image-net.org/) as a feature extractor. Below is a diagram of the VGGNet architecture.\n\n<img src=\"assets/cnnarchitecture.jpg\" width=700px>\n\nVGGNet is great because it's simple and has great performance, coming in second in the ImageNet competition. The idea here is that we keep all the convolutional layers, but replace the final fully connected layers with our own classifier. This way we can use VGGNet as a feature extractor for our images then easily train a simple classifier on top of that. What we'll do is take the first fully connected layer with 4096 units, including thresholding with ReLUs. We can use those values as a code for each image, then build a classifier on top of those codes.\n\nYou can read more about transfer learning from [the CS231n course notes](http://cs231n.github.io/transfer-learning/#tf).\n\n## Pretrained VGGNet\n\nWe'll be using a pretrained network from https://github.com/machrisaa/tensorflow-vgg. This code is already included in 'tensorflow_vgg' directory, sdo you don't have to clone it.\n\nThis is a really nice implementation of VGGNet, quite easy to work with. The network has already been trained and the parameters are available from this link. **You'll need to clone the repo into the folder containing this notebook.** Then download the parameter file using the next cell.",
"_____no_output_____"
]
],
[
[
"from urllib.request import urlretrieve\nfrom os.path import isfile, isdir\nfrom tqdm import tqdm\n\nvgg_dir = 'tensorflow_vgg/'\n# Make sure vgg exists\nif not isdir(vgg_dir):\n raise Exception(\"VGG directory doesn't exist!\")\n\nclass DLProgress(tqdm):\n last_block = 0\n\n def hook(self, block_num=1, block_size=1, total_size=None):\n self.total = total_size\n self.update((block_num - self.last_block) * block_size)\n self.last_block = block_num\n\nif not isfile(vgg_dir + \"vgg16.npy\"):\n with DLProgress(unit='B', unit_scale=True, miniters=1, desc='VGG16 Parameters') as pbar:\n urlretrieve(\n 'https://s3.amazonaws.com/content.udacity-data.com/nd101/vgg16.npy',\n vgg_dir + 'vgg16.npy',\n pbar.hook)\nelse:\n print(\"Parameter file already exists!\")",
"VGG16 Parameters: 553MB [00:31, 17.6MB/s] \n"
]
],
[
[
"## Flower power\n\nHere we'll be using VGGNet to classify images of flowers. To get the flower dataset, run the cell below. This dataset comes from the [TensorFlow inception tutorial](https://www.tensorflow.org/tutorials/image_retraining).",
"_____no_output_____"
]
],
[
[
"import tarfile\n\ndataset_folder_path = 'flower_photos'\n\nclass DLProgress(tqdm):\n last_block = 0\n\n def hook(self, block_num=1, block_size=1, total_size=None):\n self.total = total_size\n self.update((block_num - self.last_block) * block_size)\n self.last_block = block_num\n\nif not isfile('flower_photos.tar.gz'):\n with DLProgress(unit='B', unit_scale=True, miniters=1, desc='Flowers Dataset') as pbar:\n urlretrieve(\n 'http://download.tensorflow.org/example_images/flower_photos.tgz',\n 'flower_photos.tar.gz',\n pbar.hook)\n\nif not isdir(dataset_folder_path):\n with tarfile.open('flower_photos.tar.gz') as tar:\n tar.extractall()\n tar.close()",
"Flowers Dataset: 229MB [00:02, 83.5MB/s] \n"
]
],
[
[
"## ConvNet Codes\n\nBelow, we'll run through all the images in our dataset and get codes for each of them. That is, we'll run the images through the VGGNet convolutional layers and record the values of the first fully connected layer. We can then write these to a file for later when we build our own classifier.\n\nHere we're using the `vgg16` module from `tensorflow_vgg`. The network takes images of size $224 \\times 224 \\times 3$ as input. Then it has 5 sets of convolutional layers. The network implemented here has this structure (copied from [the source code](https://github.com/machrisaa/tensorflow-vgg/blob/master/vgg16.py)):\n\n```\nself.conv1_1 = self.conv_layer(bgr, \"conv1_1\")\nself.conv1_2 = self.conv_layer(self.conv1_1, \"conv1_2\")\nself.pool1 = self.max_pool(self.conv1_2, 'pool1')\n\nself.conv2_1 = self.conv_layer(self.pool1, \"conv2_1\")\nself.conv2_2 = self.conv_layer(self.conv2_1, \"conv2_2\")\nself.pool2 = self.max_pool(self.conv2_2, 'pool2')\n\nself.conv3_1 = self.conv_layer(self.pool2, \"conv3_1\")\nself.conv3_2 = self.conv_layer(self.conv3_1, \"conv3_2\")\nself.conv3_3 = self.conv_layer(self.conv3_2, \"conv3_3\")\nself.pool3 = self.max_pool(self.conv3_3, 'pool3')\n\nself.conv4_1 = self.conv_layer(self.pool3, \"conv4_1\")\nself.conv4_2 = self.conv_layer(self.conv4_1, \"conv4_2\")\nself.conv4_3 = self.conv_layer(self.conv4_2, \"conv4_3\")\nself.pool4 = self.max_pool(self.conv4_3, 'pool4')\n\nself.conv5_1 = self.conv_layer(self.pool4, \"conv5_1\")\nself.conv5_2 = self.conv_layer(self.conv5_1, \"conv5_2\")\nself.conv5_3 = self.conv_layer(self.conv5_2, \"conv5_3\")\nself.pool5 = self.max_pool(self.conv5_3, 'pool5')\n\nself.fc6 = self.fc_layer(self.pool5, \"fc6\")\nself.relu6 = tf.nn.relu(self.fc6)\n```\n\nSo what we want are the values of the first fully connected layer, after being ReLUd (`self.relu6`). To build the network, we use\n\n```\nwith tf.Session() as sess:\n vgg = vgg16.Vgg16()\n input_ = tf.placeholder(tf.float32, [None, 224, 224, 3])\n with tf.name_scope(\"content_vgg\"):\n vgg.build(input_)\n```\n\nThis creates the `vgg` object, then builds the graph with `vgg.build(input_)`. Then to get the values from the layer,\n\n```\nfeed_dict = {input_: images}\ncodes = sess.run(vgg.relu6, feed_dict=feed_dict)\n```",
"_____no_output_____"
]
],
[
[
"import os\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow_vgg import vgg16\nfrom tensorflow_vgg import utils",
"_____no_output_____"
],
[
"data_dir = 'flower_photos/'\ncontents = os.listdir(data_dir)\nclasses = [each for each in contents if os.path.isdir(data_dir + each)]",
"_____no_output_____"
]
],
[
[
"Below I'm running images through the VGG network in batches.\n\n> **Exercise:** Below, build the VGG network. Also get the codes from the first fully connected layer (make sure you get the ReLUd values).",
"_____no_output_____"
]
],
[
[
"# Set the batch size higher if you can fit in in your GPU memory\nbatch_size = 10\ncodes_list = []\nlabels = []\nbatch = []\n\ncodes = None\n\nwith tf.Session() as sess:\n \n # TODO: Build the vgg network here\n vgg = vgg16.Vgg16()\n input_ = tf.placeholder(tf.float32, [None, 224, 224, 3])\n with tf.name_scope(\"content_vgg\"):\n vgg.build(input_)\n\n for each in classes:\n print(\"Starting {} images\".format(each))\n class_path = data_dir + each\n files = os.listdir(class_path)\n for ii, file in enumerate(files, 1):\n # Add images to the current batch\n # utils.load_image crops the input images for us, from the center\n img = utils.load_image(os.path.join(class_path, file))\n batch.append(img.reshape((1, 224, 224, 3)))\n labels.append(each)\n \n # Running the batch through the network to get the codes\n if ii % batch_size == 0 or ii == len(files):\n \n # Image batch to pass to VGG network\n images = np.concatenate(batch)\n \n # TODO: Get the values from the relu6 layer of the VGG network \n codes_batch = sess.run(vgg.relu6, feed_dict={input_: images})\n \n # Here I'm building an array of the codes\n if codes is None:\n codes = codes_batch\n else:\n codes = np.concatenate((codes, codes_batch))\n \n # Reset to start building the next batch\n batch = []\n print('{} images processed'.format(ii))",
"/home/ubuntu/deep-learning/transfer-learning/tensorflow_vgg/vgg16.npy\nnpy file loaded\nbuild model started\nbuild model finished: 0s\nStarting roses images\n10 images processed\n20 images processed\n30 images processed\n40 images processed\n50 images processed\n60 images processed\n70 images processed\n80 images processed\n90 images processed\n100 images processed\n110 images processed\n120 images processed\n130 images processed\n140 images processed\n150 images processed\n160 images processed\n170 images processed\n180 images processed\n190 images processed\n200 images processed\n210 images processed\n220 images processed\n230 images processed\n240 images processed\n250 images processed\n260 images processed\n270 images processed\n280 images processed\n290 images processed\n300 images processed\n310 images processed\n320 images processed\n330 images processed\n340 images processed\n350 images processed\n360 images processed\n370 images processed\n380 images processed\n390 images processed\n400 images processed\n410 images processed\n420 images processed\n430 images processed\n440 images processed\n450 images processed\n460 images processed\n470 images processed\n480 images processed\n490 images processed\n500 images processed\n510 images processed\n520 images processed\n530 images processed\n540 images processed\n550 images processed\n560 images processed\n570 images processed\n580 images processed\n590 images processed\n600 images processed\n610 images processed\n620 images processed\n630 images processed\n640 images processed\n641 images processed\nStarting daisy images\n10 images processed\n20 images processed\n30 images processed\n40 images processed\n50 images processed\n60 images processed\n70 images processed\n80 images processed\n90 images processed\n100 images processed\n110 images processed\n120 images processed\n130 images processed\n140 images processed\n150 images processed\n160 images processed\n170 images processed\n180 images processed\n190 images processed\n200 images processed\n210 images processed\n220 images processed\n230 images processed\n240 images processed\n250 images processed\n260 images processed\n270 images processed\n280 images processed\n290 images processed\n300 images processed\n310 images processed\n320 images processed\n330 images processed\n340 images processed\n350 images processed\n360 images processed\n370 images processed\n380 images processed\n390 images processed\n400 images processed\n410 images processed\n420 images processed\n430 images processed\n440 images processed\n450 images processed\n460 images processed\n470 images processed\n480 images processed\n490 images processed\n500 images processed\n510 images processed\n520 images processed\n530 images processed\n540 images processed\n550 images processed\n560 images processed\n570 images processed\n580 images processed\n590 images processed\n600 images processed\n610 images processed\n620 images processed\n630 images processed\n633 images processed\nStarting tulips images\n10 images processed\n20 images processed\n30 images processed\n40 images processed\n50 images processed\n60 images processed\n70 images processed\n80 images processed\n90 images processed\n100 images processed\n110 images processed\n120 images processed\n130 images processed\n140 images processed\n150 images processed\n160 images processed\n170 images processed\n180 images processed\n190 images processed\n200 images processed\n210 images processed\n220 images processed\n230 images processed\n240 images processed\n250 images processed\n260 images processed\n270 images processed\n280 images processed\n290 images processed\n300 images processed\n310 images processed\n320 images processed\n330 images processed\n340 images processed\n350 images processed\n360 images processed\n370 images processed\n380 images processed\n390 images processed\n400 images processed\n410 images processed\n420 images processed\n430 images processed\n440 images processed\n450 images processed\n460 images processed\n470 images processed\n480 images processed\n490 images processed\n500 images processed\n510 images processed\n520 images processed\n530 images processed\n540 images processed\n550 images processed\n560 images processed\n570 images processed\n580 images processed\n590 images processed\n600 images processed\n610 images processed\n620 images processed\n630 images processed\n640 images processed\n650 images processed\n660 images processed\n670 images processed\n680 images processed\n690 images processed\n700 images processed\n710 images processed\n720 images processed\n730 images processed\n740 images processed\n750 images processed\n760 images processed\n770 images processed\n780 images processed\n790 images processed\n799 images processed\nStarting sunflowers images\n10 images processed\n20 images processed\n30 images processed\n40 images processed\n50 images processed\n60 images processed\n70 images processed\n80 images processed\n90 images processed\n100 images processed\n110 images processed\n120 images processed\n130 images processed\n140 images processed\n150 images processed\n160 images processed\n170 images processed\n180 images processed\n190 images processed\n200 images processed\n210 images processed\n220 images processed\n230 images processed\n240 images processed\n250 images processed\n260 images processed\n270 images processed\n280 images processed\n290 images processed\n300 images processed\n310 images processed\n320 images processed\n330 images processed\n340 images processed\n350 images processed\n360 images processed\n370 images processed\n380 images processed\n390 images processed\n400 images processed\n410 images processed\n420 images processed\n430 images processed\n440 images processed\n450 images processed\n460 images processed\n470 images processed\n480 images processed\n490 images processed\n500 images processed\n510 images processed\n520 images processed\n530 images processed\n540 images processed\n550 images processed\n560 images processed\n570 images processed\n580 images processed\n590 images processed\n600 images processed\n610 images processed\n620 images processed\n630 images processed\n640 images processed\n650 images processed\n660 images processed\n670 images processed\n680 images processed\n690 images processed\n699 images processed\nStarting dandelion images\n10 images processed\n20 images processed\n30 images processed\n40 images processed\n50 images processed\n60 images processed\n70 images processed\n80 images processed\n90 images processed\n100 images processed\n110 images processed\n120 images processed\n130 images processed\n140 images processed\n150 images processed\n160 images processed\n170 images processed\n180 images processed\n190 images processed\n200 images processed\n210 images processed\n220 images processed\n230 images processed\n240 images processed\n250 images processed\n260 images processed\n270 images processed\n280 images processed\n290 images processed\n300 images processed\n310 images processed\n320 images processed\n330 images processed\n340 images processed\n350 images processed\n360 images processed\n370 images processed\n380 images processed\n390 images processed\n400 images processed\n410 images processed\n420 images processed\n430 images processed\n440 images processed\n450 images processed\n460 images processed\n470 images processed\n480 images processed\n490 images processed\n500 images processed\n510 images processed\n520 images processed\n530 images processed\n540 images processed\n550 images processed\n560 images processed\n570 images processed\n580 images processed\n590 images processed\n600 images processed\n610 images processed\n620 images processed\n630 images processed\n640 images processed\n650 images processed\n660 images processed\n670 images processed\n680 images processed\n690 images processed\n700 images processed\n710 images processed\n720 images processed\n730 images processed\n740 images processed\n750 images processed\n760 images processed\n770 images processed\n780 images processed\n790 images processed\n800 images processed\n810 images processed\n820 images processed\n830 images processed\n840 images processed\n850 images processed\n860 images processed\n870 images processed\n880 images processed\n890 images processed\n898 images processed\n"
],
[
"# write codes to file\nwith open('codes', 'w') as f:\n codes.tofile(f)\n \n# write labels to file\nimport csv\nwith open('labels', 'w') as f:\n writer = csv.writer(f, delimiter='\\n')\n writer.writerow(labels)",
"_____no_output_____"
]
],
[
[
"## Building the Classifier\n\nNow that we have codes for all the images, we can build a simple classifier on top of them. The codes behave just like normal input into a simple neural network. Below I'm going to have you do most of the work.",
"_____no_output_____"
]
],
[
[
"# read codes and labels from file\nimport csv\n\nwith open('labels') as f:\n reader = csv.reader(f, delimiter='\\n')\n labels = np.array([each for each in reader if len(each) > 0]).squeeze()\nwith open('codes') as f:\n codes = np.fromfile(f, dtype=np.float32)\n codes = codes.reshape((len(labels), -1))",
"_____no_output_____"
]
],
[
[
"### Data prep\n\nAs usual, now we need to one-hot encode our labels and create validation/test sets. First up, creating our labels!\n\n> **Exercise:** From scikit-learn, use [LabelBinarizer](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelBinarizer.html) to create one-hot encoded vectors from the labels. ",
"_____no_output_____"
]
],
[
[
"from sklearn import preprocessing\nlb = preprocessing.LabelBinarizer()\nlb.fit(labels)",
"_____no_output_____"
],
[
"labels_vecs = lb.transform(labels)",
"_____no_output_____"
]
],
[
[
"Now you'll want to create your training, validation, and test sets. An important thing to note here is that our labels and data aren't randomized yet. We'll want to shuffle our data so the validation and test sets contain data from all classes. Otherwise, you could end up with testing sets that are all one class. Typically, you'll also want to make sure that each smaller set has the same the distribution of classes as it is for the whole data set. The easiest way to accomplish both these goals is to use [`StratifiedShuffleSplit`](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedShuffleSplit.html) from scikit-learn.\n\nYou can create the splitter like so:\n```\nss = StratifiedShuffleSplit(n_splits=1, test_size=0.2)\n```\nThen split the data with \n```\nsplitter = ss.split(x, y)\n```\n\n`ss.split` returns a generator of indices. You can pass the indices into the arrays to get the split sets. The fact that it's a generator means you either need to iterate over it, or use `next(splitter)` to get the indices. Be sure to read the [documentation](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedShuffleSplit.html) and the [user guide](http://scikit-learn.org/stable/modules/cross_validation.html#random-permutations-cross-validation-a-k-a-shuffle-split).\n\n> **Exercise:** Use StratifiedShuffleSplit to split the codes and labels into training, validation, and test sets.",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import StratifiedShuffleSplit\nss = StratifiedShuffleSplit(n_splits=1, test_size=0.2)\n\ntrain_i, test_i = next(ss.split(codes, labels_vecs))\n\nsplit_val_i = len(test_i)//2\ntest_split, val_split = test_i[:split_val_i], test_i[split_val_i:]\n\ntrain_x, train_y = codes[train_i], labels_vecs[train_i]\nval_x, val_y = codes[val_split], labels_vecs[val_split]\ntest_x, test_y = codes[test_split], labels_vecs[test_split]",
"_____no_output_____"
],
[
"print(\"Train shapes (x, y):\", train_x.shape, train_y.shape)\nprint(\"Validation shapes (x, y):\", val_x.shape, val_y.shape)\nprint(\"Test shapes (x, y):\", test_x.shape, test_y.shape)",
"Train shapes (x, y): (2936, 4096) (2936, 5)\nValidation shapes (x, y): (367, 4096) (367, 5)\nTest shapes (x, y): (367, 4096) (367, 5)\n"
]
],
[
[
"If you did it right, you should see these sizes for the training sets:\n\n```\nTrain shapes (x, y): (2936, 4096) (2936, 5)\nValidation shapes (x, y): (367, 4096) (367, 5)\nTest shapes (x, y): (367, 4096) (367, 5)\n```",
"_____no_output_____"
],
[
"### Classifier layers\n\nOnce you have the convolutional codes, you just need to build a classfier from some fully connected layers. You use the codes as the inputs and the image labels as targets. Otherwise the classifier is a typical neural network.\n\n> **Exercise:** With the codes and labels loaded, build the classifier. Consider the codes as your inputs, each of them are 4096D vectors. You'll want to use a hidden layer and an output layer as your classifier. Remember that the output layer needs to have one unit for each class and a softmax activation function. Use the cross entropy to calculate the cost.",
"_____no_output_____"
]
],
[
[
"inputs_ = tf.placeholder(tf.float32, shape=[None, codes.shape[1]])\nlabels_ = tf.placeholder(tf.int64, shape=[None, labels_vecs.shape[1]])\n\n# TODO: Classifier layers and operations\nfc1 = tf.contrib.layers.fully_connected(inputs_, 1024)\nfc2 = tf.contrib.layers.fully_connected(fc1, 1024)\n\nlogits = tf.contrib.layers.fully_connected(fc2, labels_vecs.shape[1], activation_fn=None)\ncross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=labels_, logits=logits)\ncost = tf.reduce_mean(cross_entropy)\n\noptimizer = tf.train.AdamOptimizer().minimize(cost)\n\n# Operations for validation/test accuracy\npredicted = tf.nn.softmax(logits)\ncorrect_pred = tf.equal(tf.argmax(predicted, 1), tf.argmax(labels_, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))",
"_____no_output_____"
]
],
[
[
"### Batches!\n\nHere is just a simple way to do batches. I've written it so that it includes all the data. Sometimes you'll throw out some data at the end to make sure you have full batches. Here I just extend the last batch to include the remaining data.",
"_____no_output_____"
]
],
[
[
"def get_batches(x, y, n_batches=10):\n \"\"\" Return a generator that yields batches from arrays x and y. \"\"\"\n batch_size = len(x)//n_batches\n \n for ii in range(0, n_batches*batch_size, batch_size):\n # If we're not on the last batch, grab data with size batch_size\n if ii != (n_batches-1)*batch_size:\n X, Y = x[ii: ii+batch_size], y[ii: ii+batch_size] \n # On the last batch, grab the rest of the data\n else:\n X, Y = x[ii:], y[ii:]\n # I love generators\n yield X, Y",
"_____no_output_____"
]
],
[
[
"### Training\n\nHere, we'll train the network.\n\n> **Exercise:** So far we've been providing the training code for you. Here, I'm going to give you a bit more of a challenge and have you write the code to train the network. Of course, you'll be able to see my solution if you need help. Use the `get_batches` function I wrote before to get your batches like `for x, y in get_batches(train_x, train_y)`. Or write your own!",
"_____no_output_____"
]
],
[
[
"saver = tf.train.Saver()\nepochs = 10\niteration = 0\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n \n for e in range(epochs): \n for x, y in get_batches(train_x, train_y):\n feed = {inputs_: x, labels_: y}\n loss, _ = sess.run([cost, optimizer], feed)\n print('Epoch: {}/{}'.format(e+1, epochs),\n 'Iterations: {}'.format(iteration),\n \"Loss: {}\".format(loss))\n iteration+=1\n \n if iteration%5 == 0:\n feed = {inputs_: val_x, labels_: val_y}\n loss, _ = sess.run([cost, optimizer], feed)\n print('Epoch: {}/{}'.format(e+1, epochs),\n 'Iterations: {}'.format(iteration),\n \"Val loss: {}\".format(loss))\n \n saver.save(sess, \"checkpoints/flowers.ckpt\")",
"Epoch: 1/10 Iterations: 0 Loss: 4.672918796539307\nEpoch: 1/10 Iterations: 1 Loss: 29.755029678344727\nEpoch: 1/10 Iterations: 2 Loss: 45.8921012878418\nEpoch: 1/10 Iterations: 3 Loss: 25.696012496948242\nEpoch: 1/10 Iterations: 4 Loss: 28.859224319458008\nEpoch: 1/10 Iterations: 5 Val loss: 10.552411079406738\nEpoch: 1/10 Iterations: 5 Loss: 3.189404249191284\nEpoch: 1/10 Iterations: 6 Loss: 2.639348268508911\nEpoch: 1/10 Iterations: 7 Loss: 2.9115426540374756\nEpoch: 1/10 Iterations: 8 Loss: 2.798640251159668\nEpoch: 1/10 Iterations: 9 Loss: 2.4628725051879883\nEpoch: 1/10 Iterations: 10 Val loss: 1.82681405544281\nEpoch: 2/10 Iterations: 10 Loss: 1.1171455383300781\nEpoch: 2/10 Iterations: 11 Loss: 1.0355298519134521\nEpoch: 2/10 Iterations: 12 Loss: 0.47368577122688293\nEpoch: 2/10 Iterations: 13 Loss: 0.5847135782241821\nEpoch: 2/10 Iterations: 14 Loss: 0.8828096389770508\nEpoch: 2/10 Iterations: 15 Val loss: 0.8436155319213867\nEpoch: 2/10 Iterations: 15 Loss: 0.6585701704025269\nEpoch: 2/10 Iterations: 16 Loss: 0.556399941444397\nEpoch: 2/10 Iterations: 17 Loss: 0.487338125705719\nEpoch: 2/10 Iterations: 18 Loss: 0.4912504553794861\nEpoch: 2/10 Iterations: 19 Loss: 0.4451310634613037\nEpoch: 2/10 Iterations: 20 Val loss: 0.4065427780151367\nEpoch: 3/10 Iterations: 20 Loss: 0.34170132875442505\nEpoch: 3/10 Iterations: 21 Loss: 0.4052823781967163\nEpoch: 3/10 Iterations: 22 Loss: 0.2879161238670349\nEpoch: 3/10 Iterations: 23 Loss: 0.3895888924598694\nEpoch: 3/10 Iterations: 24 Loss: 0.3391869366168976\nEpoch: 3/10 Iterations: 25 Val loss: 0.2961403727531433\nEpoch: 3/10 Iterations: 25 Loss: 0.30506736040115356\nEpoch: 3/10 Iterations: 26 Loss: 0.25008511543273926\nEpoch: 3/10 Iterations: 27 Loss: 0.22011327743530273\nEpoch: 3/10 Iterations: 28 Loss: 0.24098922312259674\nEpoch: 3/10 Iterations: 29 Loss: 0.26284387707710266\nEpoch: 3/10 Iterations: 30 Val loss: 0.22571401298046112\nEpoch: 4/10 Iterations: 30 Loss: 0.21583987772464752\nEpoch: 4/10 Iterations: 31 Loss: 0.22172130644321442\nEpoch: 4/10 Iterations: 32 Loss: 0.161707803606987\nEpoch: 4/10 Iterations: 33 Loss: 0.1930975317955017\nEpoch: 4/10 Iterations: 34 Loss: 0.17036172747612\nEpoch: 4/10 Iterations: 35 Val loss: 0.16700726747512817\nEpoch: 4/10 Iterations: 35 Loss: 0.17953141033649445\nEpoch: 4/10 Iterations: 36 Loss: 0.1555631011724472\nEpoch: 4/10 Iterations: 37 Loss: 0.12652190029621124\nEpoch: 4/10 Iterations: 38 Loss: 0.12226159125566483\nEpoch: 4/10 Iterations: 39 Loss: 0.16163228452205658\nEpoch: 4/10 Iterations: 40 Val loss: 0.11334959417581558\nEpoch: 5/10 Iterations: 40 Loss: 0.11021738499403\nEpoch: 5/10 Iterations: 41 Loss: 0.12303079664707184\nEpoch: 5/10 Iterations: 42 Loss: 0.08418866246938705\nEpoch: 5/10 Iterations: 43 Loss: 0.11311700195074081\nEpoch: 5/10 Iterations: 44 Loss: 0.08980914205312729\nEpoch: 5/10 Iterations: 45 Val loss: 0.07618114352226257\nEpoch: 5/10 Iterations: 45 Loss: 0.09904886037111282\nEpoch: 5/10 Iterations: 46 Loss: 0.0816163569688797\nEpoch: 5/10 Iterations: 47 Loss: 0.06527123600244522\nEpoch: 5/10 Iterations: 48 Loss: 0.07217283546924591\nEpoch: 5/10 Iterations: 49 Loss: 0.0818411335349083\nEpoch: 5/10 Iterations: 50 Val loss: 0.050673067569732666\nEpoch: 6/10 Iterations: 50 Loss: 0.055724550038576126\nEpoch: 6/10 Iterations: 51 Loss: 0.056342266499996185\nEpoch: 6/10 Iterations: 52 Loss: 0.04057794064283371\nEpoch: 6/10 Iterations: 53 Loss: 0.07455720007419586\nEpoch: 6/10 Iterations: 54 Loss: 0.05536913871765137\nEpoch: 6/10 Iterations: 55 Val loss: 0.032396264374256134\nEpoch: 6/10 Iterations: 55 Loss: 0.05769611522555351\nEpoch: 6/10 Iterations: 56 Loss: 0.04174236208200455\nEpoch: 6/10 Iterations: 57 Loss: 0.03454503044486046\nEpoch: 6/10 Iterations: 58 Loss: 0.03190534561872482\nEpoch: 6/10 Iterations: 59 Loss: 0.039301518350839615\nEpoch: 6/10 Iterations: 60 Val loss: 0.027403196319937706\nEpoch: 7/10 Iterations: 60 Loss: 0.03119419328868389\nEpoch: 7/10 Iterations: 61 Loss: 0.03252197429537773\nEpoch: 7/10 Iterations: 62 Loss: 0.02040104568004608\nEpoch: 7/10 Iterations: 63 Loss: 0.02649182826280594\nEpoch: 7/10 Iterations: 64 Loss: 0.02423202432692051\nEpoch: 7/10 Iterations: 65 Val loss: 0.01874398998916149\nEpoch: 7/10 Iterations: 65 Loss: 0.04282507300376892\nEpoch: 7/10 Iterations: 66 Loss: 0.035250939428806305\nEpoch: 7/10 Iterations: 67 Loss: 0.020883135497570038\nEpoch: 7/10 Iterations: 68 Loss: 0.01988316886126995\nEpoch: 7/10 Iterations: 69 Loss: 0.01939186453819275\nEpoch: 7/10 Iterations: 70 Val loss: 0.013688798993825912\nEpoch: 8/10 Iterations: 70 Loss: 0.02058236673474312\nEpoch: 8/10 Iterations: 71 Loss: 0.025333741679787636\nEpoch: 8/10 Iterations: 72 Loss: 0.02040153741836548\nEpoch: 8/10 Iterations: 73 Loss: 0.03184022754430771\nEpoch: 8/10 Iterations: 74 Loss: 0.012570078484714031\nEpoch: 8/10 Iterations: 75 Val loss: 0.006841983646154404\nEpoch: 8/10 Iterations: 75 Loss: 0.015580104663968086\nEpoch: 8/10 Iterations: 76 Loss: 0.014343924820423126\nEpoch: 8/10 Iterations: 77 Loss: 0.018154548481106758\nEpoch: 8/10 Iterations: 78 Loss: 0.025013182312250137\nEpoch: 8/10 Iterations: 79 Loss: 0.028149407356977463\nEpoch: 8/10 Iterations: 80 Val loss: 0.006597414147108793\nEpoch: 9/10 Iterations: 80 Loss: 0.00860650185495615\nEpoch: 9/10 Iterations: 81 Loss: 0.00733830314129591\nEpoch: 9/10 Iterations: 82 Loss: 0.00633214833214879\nEpoch: 9/10 Iterations: 83 Loss: 0.014129566960036755\nEpoch: 9/10 Iterations: 84 Loss: 0.008173373527824879\nEpoch: 9/10 Iterations: 85 Val loss: 0.007537458091974258\nEpoch: 9/10 Iterations: 85 Loss: 0.01679036393761635\nEpoch: 9/10 Iterations: 86 Loss: 0.00960800051689148\nEpoch: 9/10 Iterations: 87 Loss: 0.005559608340263367\nEpoch: 9/10 Iterations: 88 Loss: 0.005612092092633247\nEpoch: 9/10 Iterations: 89 Loss: 0.010039210319519043\nEpoch: 9/10 Iterations: 90 Val loss: 0.002736186608672142\nEpoch: 10/10 Iterations: 90 Loss: 0.005322793032974005\nEpoch: 10/10 Iterations: 91 Loss: 0.0052515072748064995\nEpoch: 10/10 Iterations: 92 Loss: 0.013230983167886734\nEpoch: 10/10 Iterations: 93 Loss: 0.01197117194533348\nEpoch: 10/10 Iterations: 94 Loss: 0.0041971355676651\nEpoch: 10/10 Iterations: 95 Val loss: 0.0022358843125402927\nEpoch: 10/10 Iterations: 95 Loss: 0.004806811455637217\nEpoch: 10/10 Iterations: 96 Loss: 0.0033794238697737455\nEpoch: 10/10 Iterations: 97 Loss: 0.0032531919423490763\nEpoch: 10/10 Iterations: 98 Loss: 0.0034035572316497564\nEpoch: 10/10 Iterations: 99 Loss: 0.009972398169338703\nEpoch: 10/10 Iterations: 100 Val loss: 0.0017780129564926028\n"
]
],
[
[
"### Testing\n\nBelow you see the test accuracy. You can also see the predictions returned for images.",
"_____no_output_____"
]
],
[
[
"with tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('checkpoints'))\n \n feed = {inputs_: test_x,\n labels_: test_y}\n test_acc = sess.run(accuracy, feed_dict=feed)\n print(\"Test accuracy: {:.4f}\".format(test_acc))",
"Test accuracy: 0.9591\n"
],
[
"%matplotlib inline\n\nimport matplotlib.pyplot as plt\nfrom scipy.ndimage import imread",
"_____no_output_____"
]
],
[
[
"Below, feel free to choose images and see how the trained classifier predicts the flowers in them.",
"_____no_output_____"
]
],
[
[
"test_img_path = 'flower_photos/roses/10894627425_ec76bbc757_n.jpg'\ntest_img = imread(test_img_path)\nplt.imshow(test_img)",
"_____no_output_____"
],
[
"# Run this cell if you don't have a vgg graph built\nif 'vgg' in globals():\n print('\"vgg\" object already exists. Will not create again.')\nelse:\n #create vgg\n with tf.Session() as sess:\n input_ = tf.placeholder(tf.float32, [None, 224, 224, 3])\n vgg = vgg16.Vgg16()\n vgg.build(input_)",
"\"vgg\" object already exists. Will not create again.\n"
],
[
"with tf.Session() as sess:\n img = utils.load_image(test_img_path)\n img = img.reshape((1, 224, 224, 3))\n\n feed_dict = {input_: img}\n code = sess.run(vgg.relu6, feed_dict=feed_dict)\n \nsaver = tf.train.Saver()\nwith tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('checkpoints'))\n \n feed = {inputs_: code}\n prediction = sess.run(predicted, feed_dict=feed).squeeze()",
"_____no_output_____"
],
[
"plt.imshow(test_img)",
"_____no_output_____"
],
[
"plt.barh(np.arange(5), prediction)\n_ = plt.yticks(np.arange(5), lb.classes_)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
e77c3475bb47a9f77f0373bf940323c179620634 | 44,681 | ipynb | Jupyter Notebook | notebooks/eda-caged.ipynb | equipepontozip/coronathon | 9ea401888322192da94afcf84a3d3a40edfede8b | [
"MIT"
] | null | null | null | notebooks/eda-caged.ipynb | equipepontozip/coronathon | 9ea401888322192da94afcf84a3d3a40edfede8b | [
"MIT"
] | null | null | null | notebooks/eda-caged.ipynb | equipepontozip/coronathon | 9ea401888322192da94afcf84a3d3a40edfede8b | [
"MIT"
] | null | null | null | 121.746594 | 18,112 | 0.804995 | [
[
[
"import pandas as pd",
"_____no_output_____"
],
[
"df_caged = pd.read_csv(\"data/CAGEDEST_102019.txt\", sep=';', encoding='iso8859-1')",
"/home/chris/anaconda3/lib/python3.7/site-packages/IPython/core/interactiveshell.py:3049: DtypeWarning: Columns (32,33,34,35,36,37,38,39) have mixed types. Specify dtype option on import or set low_memory=False.\n interactivity=interactivity, compiler=compiler, result=result)\n"
],
[
"print(df_caged.shape)\ndf_caged.head()",
"(2659256, 42)\n"
],
[
"df_caged.columns",
"_____no_output_____"
],
[
"df_caged['CNAE 2.0 Subclas'].value_counts()[:15].plot.bar(figsize=(20,10));",
"_____no_output_____"
],
[
"df_caged.UF.value_counts()[:15].plot.bar(figsize=(20,10));",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e77c3477d574222ba2a9f92adf5947263042e9ba | 90,703 | ipynb | Jupyter Notebook | solution.ipynb | ezhilvendhan/dermatogist-ai-solution | 69c281fb25644d6a039d40b09707717ee5e0b335 | [
"MIT"
] | null | null | null | solution.ipynb | ezhilvendhan/dermatogist-ai-solution | 69c281fb25644d6a039d40b09707717ee5e0b335 | [
"MIT"
] | null | null | null | solution.ipynb | ezhilvendhan/dermatogist-ai-solution | 69c281fb25644d6a039d40b09707717ee5e0b335 | [
"MIT"
] | null | null | null | 147.484553 | 73,586 | 0.869784 | [
[
[
"# Melanoma Diagnoses",
"_____no_output_____"
]
],
[
[
"import os\nimport keras\nimport pandas as pd\nimport numpy as np\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nfrom keras import applications\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.preprocessing import image\nfrom keras import optimizers\nfrom keras.models import Sequential, Model \nfrom keras.layers import Dropout, Flatten, Dense, GlobalAveragePooling2D\nfrom keras import backend as k \nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler, TensorBoard, EarlyStopping\nfrom keras.models import load_model\n\nfrom sklearn.metrics import roc_curve, auc\n\nimport get_results\n",
"Using TensorFlow backend.\n"
]
],
[
[
"### Import Images",
"_____no_output_____"
]
],
[
[
"def load_image( infilename ) :\n img = Image.open( infilename )\n img.load()\n data = np.asarray( img, dtype=\"float32\" )\n return data\n\ndata_dir = 'data'\ntrain_dir = data_dir + '/train'\nvalid_dir = data_dir + '/valid'\ntest_dir = data_dir + '/test'",
"_____no_output_____"
],
[
"fig = plt.figure(figsize=(20,5))\ntrain_files = os.listdir(train_dir+\"/melanoma\")[:5]\nfor i in range(5):\n ax = fig.add_subplot(3, 12, i + 1, xticks=[], yticks=[])\n ax.imshow(load_image(train_dir + \"/melanoma/\" +train_files[i]))",
"_____no_output_____"
]
],
[
[
"### Image Data transformation",
"_____no_output_____"
]
],
[
[
"img_width, img_height = 256, 256\nbatch_size = 16\nepochs = 10\n\ntrain_datagen = ImageDataGenerator(\n rescale = 1./255,\n horizontal_flip = True,\n# fill_mode = \"nearest\",\n zoom_range = 0.2,\n# width_shift_range = 0.3,\n# height_shift_range=0.3,\n shear_range=0.2,\n# rotation_range=30\n)\n\ntest_datagen = ImageDataGenerator(rescale = 1./255)\n\ntrain_generator = train_datagen.flow_from_directory(\n train_dir,\n target_size = (img_height, img_width),\n batch_size = batch_size, \n class_mode = \"categorical\")\n\nvalidation_generator = test_datagen.flow_from_directory(\n valid_dir,\n target_size = (img_height, img_width),\n class_mode = \"categorical\")\n\ntest_generator = test_datagen.flow_from_directory(\n test_dir,\n target_size = (img_height, img_width),\n class_mode = \"categorical\")",
"Found 0 images belonging to 0 classes.\nFound 0 images belonging to 0 classes.\nFound 600 images belonging to 3 classes.\n"
],
[
"train_generator.image_shape",
"_____no_output_____"
]
],
[
[
"### Fine-tune Model",
"_____no_output_____"
]
],
[
[
"# create the base pre-trained model\nvgg_model = applications.VGG19(weights = \"imagenet\", \n include_top=False, \n input_shape = (img_width, img_height, 3))\nfor layer in vgg_model.layers[:5]:\n layer.trainable = False\n\n#Adding custom Layers \nx = vgg_model.output\nx = GlobalAveragePooling2D()(x)\n# add fully-connected layer\nx = Dense(512, activation='relu')(x)\nx = Dropout(0.5)(x)\n\n# add output layer\npredictions = Dense(3, activation='softmax')(x)\n\nmodel_final = Model(inputs=vgg_model.input, outputs=predictions)\n\n# freeze pre-trained model area's layer\nfor layer in vgg_model.layers:\n layer.trainable = False\n\n# update the weight that are added\nmodel_final.compile(optimizer='rmsprop', loss='categorical_crossentropy')",
"_____no_output_____"
],
[
"model_final.fit_generator(\n train_generator,\n steps_per_epoch=train_generator.samples/train_generator.batch_size,\n epochs = 3,\n validation_data = validation_generator,\n validation_steps = validation_generator.samples/validation_generator.batch_size)",
"Epoch 1/3\n125/125 [==============================] - 325s - loss: 0.8962 - val_loss: 1.2098\nEpoch 2/3\n125/125 [==============================] - 309s - loss: 0.8286 - val_loss: 1.2344\nEpoch 3/3\n125/125 [==============================] - 302s - loss: 0.8126 - val_loss: 1.1027\n"
]
],
[
[
"### Train Model",
"_____no_output_____"
]
],
[
[
"# Save the model according to the conditions \ncheckpoint = ModelCheckpoint(\"cancer_vgg19_wt.h5\", \n monitor='val_acc', verbose=2, \n save_best_only=True, save_weights_only=False, \n mode='auto', period=1)\nearly = EarlyStopping(monitor='val_acc', \n min_delta=0, patience=3, \n verbose=2, mode='auto')\n\n# choose the layers which are updated by training\nlayer_num = len(model_final.layers)\nfor layer in model_final.layers[:21]:\n layer.trainable = False\n\nfor layer in model_final.layers[21:]:\n layer.trainable = True\n\n# training\nmodel_final.compile(optimizer=optimizers.SGD(lr=0.001, momentum=0.9), \n loss='categorical_crossentropy', metrics=['accuracy'])\n\n# Train the model \nmodel_final.fit_generator(\n train_generator,\n steps_per_epoch = train_generator.samples/train_generator.batch_size,\n epochs = epochs,\n validation_data = validation_generator,\n validation_steps = validation_generator.samples/validation_generator.batch_size,\n callbacks = [checkpoint, early])",
"Epoch 1/10\n124/125 [============================>.] - ETA: 2s - loss: 0.7818 - acc: 0.6885Epoch 00000: val_acc improved from -inf to 0.52000, saving model to cancer_vgg19_wt.h5\n125/125 [==============================] - 332s - loss: 0.7812 - acc: 0.6895 - val_loss: 1.0943 - val_acc: 0.5200\nEpoch 2/10\n124/125 [============================>.] - ETA: 2s - loss: 0.7781 - acc: 0.6910Epoch 00001: val_acc did not improve\n125/125 [==============================] - 303s - loss: 0.7773 - acc: 0.6915 - val_loss: 1.1254 - val_acc: 0.5133\nEpoch 3/10\n124/125 [============================>.] - ETA: 2s - loss: 0.7872 - acc: 0.6799Epoch 00002: val_acc did not improve\n125/125 [==============================] - 302s - loss: 0.7872 - acc: 0.6800 - val_loss: 0.9755 - val_acc: 0.5200\nEpoch 4/10\n124/125 [============================>.] - ETA: 2s - loss: 0.7709 - acc: 0.6835Epoch 00003: val_acc did not improve\n125/125 [==============================] - 306s - loss: 0.7718 - acc: 0.6830 - val_loss: 1.0606 - val_acc: 0.5200\nEpoch 5/10\n124/125 [============================>.] - ETA: 2s - loss: 0.7698 - acc: 0.6920Epoch 00004: val_acc did not improve\n125/125 [==============================] - 306s - loss: 0.7703 - acc: 0.6915 - val_loss: 1.0909 - val_acc: 0.4867\nEpoch 00004: early stopping\n"
],
[
"model_final.save('cancer_vgg19_model.h5')",
"_____no_output_____"
],
[
"model_final = load_model('cancer_vgg19_model.h5')",
"_____no_output_____"
],
[
"img_path = 'data/test/nevus/ISIC_0012803.jpg'\nimg = image.load_img(img_path, target_size=(256, 256))\nx = image.img_to_array(img)\nx = np.expand_dims(x, axis=0)\nx = test_datagen.standardize(x)\nmodel_final.predict(x, verbose=2)",
"_____no_output_____"
],
[
"img_path = 'data/test/melanoma/ISIC_0012989.jpg'\nimg = image.load_img(img_path, target_size=(256, 256))\nx = image.img_to_array(img)\nx = np.expand_dims(x, axis=0)\nx = test_datagen.standardize(x)\nmodel_final.predict(x, verbose=2)",
"_____no_output_____"
],
[
"img_path = 'data/test/seborrheic_keratosis/ISIC_0012323.jpg'\nimg = image.load_img(img_path, target_size=(256, 256))\nx = image.img_to_array(img)\nx = np.expand_dims(x, axis=0)\nx = test_datagen.standardize(x)\nmodel_final.predict(x, verbose=2)",
"_____no_output_____"
],
[
"model_final.evaluate_generator(test_generator, \n steps = test_generator.samples/test_generator.batch_size)",
"_____no_output_____"
],
[
"y_hat = model_final.predict_generator(test_generator, \n steps = test_generator.samples/test_generator.batch_size)",
"_____no_output_____"
],
[
"def get_pred(img_path):\n img = image.load_img(img_path, target_size=(256, 256))\n x = image.img_to_array(img)\n x = np.expand_dims(x, axis=0)\n x = test_datagen.standardize(x)\n return model_final.predict(x)\n\ntest_files = pd.read_csv('sample_predictions.csv')\nfor index, row in test_files.iterrows():\n pred = get_pred(row['Id'])\n test_files.loc[index, 'task_1'] = pred[0][0]\n test_files.loc[index, 'task_2'] = pred[0][2]\n \ntest_files.head()",
"_____no_output_____"
],
[
"test_files.to_csv('submission_predictions.csv')",
"_____no_output_____"
]
],
[
[
"Category 1 Score: 0.554<br>\nCategory 2 Score: 0.659<br>\nCategory 3 Score: 0.607",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
e77c4045cbf961223620cf0eb1e1e6112d083d69 | 1,249 | ipynb | Jupyter Notebook | i2i/fspmaps/Phase-6-newData.ipynb | Vizzuality/notebooks | 88369cc20509b99483ae95ab68ec575ffe6f11f5 | [
"MIT"
] | null | null | null | i2i/fspmaps/Phase-6-newData.ipynb | Vizzuality/notebooks | 88369cc20509b99483ae95ab68ec575ffe6f11f5 | [
"MIT"
] | null | null | null | i2i/fspmaps/Phase-6-newData.ipynb | Vizzuality/notebooks | 88369cc20509b99483ae95ab68ec575ffe6f11f5 | [
"MIT"
] | null | null | null | 18.924242 | 66 | 0.534027 | [
[
[
"<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"></ul></div>",
"_____no_output_____"
]
],
[
[
"import geopandas\nimport plotly",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
]
] |
e77c49dc07bc07d6100d6842c2baa9fa37dbe95a | 20,465 | ipynb | Jupyter Notebook | regular-expressions-in-python/4. Advanced Regular Expression Concepts/notebook_section_4.ipynb | nhutnamhcmus/datacamp-playground | 25457e813b1145e1d335562286715eeddd1c1a7b | [
"MIT"
] | 1 | 2021-05-08T11:09:27.000Z | 2021-05-08T11:09:27.000Z | regular-expressions-in-python/4. Advanced Regular Expression Concepts/notebook_section_4.ipynb | nhutnamhcmus/datacamp-playground | 25457e813b1145e1d335562286715eeddd1c1a7b | [
"MIT"
] | 1 | 2022-03-12T15:42:14.000Z | 2022-03-12T15:42:14.000Z | regular-expressions-in-python/4. Advanced Regular Expression Concepts/notebook_section_4.ipynb | nhutnamhcmus/datacamp-playground | 25457e813b1145e1d335562286715eeddd1c1a7b | [
"MIT"
] | 1 | 2021-04-30T18:24:19.000Z | 2021-04-30T18:24:19.000Z | 35.903509 | 471 | 0.611776 | [
[
[
"# Section 4",
"_____no_output_____"
],
[
"# Try another name\nYou are still working on your Twitter sentiment analysis. You analyze now some things that caught your attention. You noticed that there are email addresses inserted in some tweets. Now, you are curious to find out which is the most common name.\n\nYou want to extract the first part of the email. E.g. if you have the email [email protected], you are only interested in marysmith90.\nYou need to match the entire expression. So you make sure to extract only names present in emails. Also, you are only interested in names containing upper (e.g. A,B, Z) or lowercase letters (e.g. a, d, z) and numbers.\n\nThe list sentiment_analysis containing the text of three tweets as well as the re module were loaded in your session. You can use print() to view it in the IPython Shell.",
"_____no_output_____"
]
],
[
[
"sentiment_analysis = ['Just got ur newsletter, those fares really are unbelievable. Write to [email protected] or [email protected]. They have amazing prices',\n 'I should have paid more attention when we covered photoshop in my webpage design class in undergrad. Contact me [email protected].',\n 'hey missed ya at the meeting. Read your email! [email protected]']",
"_____no_output_____"
],
[
"import re\n\n# Write a regex that matches email\nregex_email = r\"([A-Za-z0-9]+)@\\S+\"\n\nfor tweet in sentiment_analysis:\n # Find all matches of regex in each tweet\n email_matched = re.findall(regex_email, tweet)\n\n # Complete the format method to print the results\n print(\"Lists of users found in this tweet: {}\".format(email_matched))",
"Lists of users found in this tweet: ['statravelAU', 'statravelpo']\nLists of users found in this tweet: ['Hollywoodheat34']\nLists of users found in this tweet: ['msdrama098']\n"
]
],
[
[
"# Flying home\nYour boss assigned you to a small project. They are performing an analysis of the travels people made to attend business meetings. You are given a dataset with only the email subjects for each of the people traveling.\n\nYou learn that the text followed a pattern. Here is an example:\n\nHere you have your boarding pass LA4214 AER-CDB 06NOV.\n\nYou need to extract the information about the flight:\n\n- The two letters indicate the airline (e.g LA),\n- The 4 numbers are the flight number (e.g. 4214).\n- The three letters correspond to the departure (e.g AER),\n- The destination (CDB),\n- The date (06NOV) of the flight.\n- All letters are always uppercase.\n\nThe variable flight containing one email subject was loaded in your session. You can use print() to view it in the IPython Shell.",
"_____no_output_____"
]
],
[
[
"# Import re\nimport re",
"_____no_output_____"
],
[
"# Write regex to capture information of the flight\nregex = r\"([A-Z]{2})(\\d{4})\\s([A-Z]{3})-([A-Z]{3})\\s(\\d{2}[A-Z]{3})\"",
"_____no_output_____"
],
[
"flight = 'Subject: You are now ready to fly. Here you have your boarding pass IB3723 AMS-MAD 06OCT'\n# Find all matches of the flight information\nflight_matches = re.findall(regex, flight)",
"_____no_output_____"
],
[
"#Print the matches\nprint(\"Airline: {} Flight number: {}\".format(flight_matches[0][0], flight_matches[0][1]))\nprint(\"Departure: {} Destination: {}\".format(flight_matches[0][2], flight_matches[0][3]))\nprint(\"Date: {}\".format(flight_matches[0][4]))",
"Airline: IB Flight number: 3723\nDeparture: AMS Destination: MAD\nDate: 06OCT\n"
]
],
[
[
"# Love it!\nYou are still working on the Twitter sentiment analysis project. First, you want to identify positive tweets about movies and concerts.\n\nYou plan to find all the sentences that contain the words love, like, or enjoy and capture that word. You will limit the tweets by focusing on those that contain the words movie or concert by keeping the word in another group. You will also save the movie or concert name.\n\nFor example, if you have the sentence: I love the movie Avengers. You match and capture love. You need to match and capture movie. Afterwards, you match and capture anything until the dot.\n\nThe list sentiment_analysis containing the text of three tweets and the re module are loaded in your session. You can use print() to view the data in the IPython Shell.",
"_____no_output_____"
]
],
[
[
"sentiment_analysis = ['I totally love the concert The Book of Souls World Tour. It kinda amazing!',\n 'I enjoy the movie Wreck-It Ralph. I watched with my boyfriend.',\n \"I still like the movie Wish Upon a Star. Too bad Disney doesn't show it anymore.\"]",
"_____no_output_____"
],
[
"# Write a regex that matches sentences with the optional words\nregex_positive = r\"(love|like|enjoy).+?(movie|concert)\\s(.+?)\\.\"\n\nfor tweet in sentiment_analysis:\n\t# Find all matches of regex in tweet\n positive_matches = re.findall(regex_positive, tweet)\n \n # Complete format to print out the results\n print(\"Positive comments found {}\".format(positive_matches))",
"Positive comments found [('love', 'concert', 'The Book of Souls World Tour')]\nPositive comments found [('enjoy', 'movie', 'Wreck-It Ralph')]\nPositive comments found [('like', 'movie', 'Wish Upon a Star')]\n"
]
],
[
[
"# Ugh! Not for me!\nAfter finding positive tweets, you want to do it for negative tweets. Your plan now is to find sentences that contain the words hate, dislike or disapprove. You will again save the movie or concert name. You will get the tweet containing the words movie or concert but this time, you don't plan to save the word.\n\nFor example, if you have the sentence: I dislike the movie Avengers a lot.. You match and capture dislike. You will match but not capture the word movie. Afterwards, you match and capture anything until the dot.\n\nThe list sentiment_analysis containing the text of three tweets as well as the re module are loaded in your session. You can use print() to view the data in the IPython Shell.",
"_____no_output_____"
]
],
[
[
"sentiment_analysis = ['That was horrible! I really dislike the movie The cabin and the ant. So boring.',\n \"I disapprove the movie Honest with you. It's full of cliches.\",\n 'I dislike very much the concert After twelve Tour. The sound was horrible.']",
"_____no_output_____"
],
[
"# Write a regex that matches sentences with the optional words\nregex_negative = r\"(hate|dislike|disapprove).+?(?:movie|concert)\\s(.+?)\\.\"\n\nfor tweet in sentiment_analysis:\n\t# Find all matches of regex in tweet\n negative_matches = re.findall(regex_negative, tweet)\n \n # Complete format to print out the results\n print(\"Negative comments found {}\".format(negative_matches))",
"Negative comments found [('dislike', 'The cabin and the ant')]\nNegative comments found [('disapprove', 'Honest with you')]\nNegative comments found [('dislike', 'After twelve Tour')]\n"
]
],
[
[
"# Parsing PDF files\nYou now need to work on another small project you have been delaying. Your company gave you some PDF files of signed contracts. The goal of the project is to create a database with the information you parse from them. Three of these columns should correspond to the day, month, and year when the contract was signed.\nThe dates appear as Signed on 05/24/2016 (05 indicating the month, 24 the day). You decide to use capturing groups to extract this information. Also, you would like to retrieve that information so you can store it separately in different variables.\n\nYou decide to do a proof of concept.\n\nThe variable contract containing the text of one contract and the re module are already loaded in your session. You can use print() to view the data in the IPython Shell.",
"_____no_output_____"
]
],
[
[
"contract = 'Provider will invoice Client for Services performed within 30 days of performance. Client will pay Provider as set forth in each Statement of Work within 30 days of receipt and acceptance of such invoice. It is understood that payments to Provider for services rendered shall be made in full as agreed, without any deductions for taxes of any kind whatsoever, in conformity with Provider’s status as an independent contractor. Signed on 03/25/2001.'\n# Write regex and scan contract to capture the dates described\nregex_dates = r\"Signed\\son\\s(\\d{2})/(\\d{2})/(\\d{4})\"\ndates = re.search(regex_dates, contract)",
"_____no_output_____"
],
[
"# Assign to each key the corresponding match\nsignature = {\n\t\"day\": dates.group(2),\n\t\"month\": dates.group(1),\n\t\"year\": dates.group(3)\n}",
"_____no_output_____"
],
[
"# Complete the format method to print-out\nprint(\"Our first contract is dated back to {data[year]}. Particularly, the day {data[day]} of the month {data[month]}.\".format(data=signature))",
"Our first contract is dated back to 2001. Particularly, the day 25 of the month 03.\n"
]
],
[
[
"# Close the tag, please!\nIn the meantime, you are working on one of your other projects. The company is going to develop a new product. It will help developers automatically check the code they are writing. You need to write a short script for checking that every HTML tag that is open has its proper closure.\n\nYou have an example of a string containing HTML tags:\n\n<title>The Data Science Company</title>\n\nYou learn that an opening HTML tag is always at the beginning of the string. It appears inside <>. A closing tag also appears inside <>, but it is preceded by /.\n\nYou also remember that capturing groups can be referenced using numbers, e.g \\4.\n\nThe list html_tags, containing three strings with HTML tags, and there module are loaded in your session. You can use print() to view the data in the IPython Shell.",
"_____no_output_____"
]
],
[
[
"html_tags = ['<body>Welcome to our course! It would be an awesome experience</body>',\n '<article>To be a data scientist, you need to have knowledge in statistics and mathematics</article>',\n '<nav>About me Links Contact me!']",
"_____no_output_____"
],
[
"for string in html_tags:\n # Complete the regex and find if it matches a closed HTML tags\n match_tag = re.match(r\"<(\\w+)>.*?</\\1>\", string)\n \n if match_tag:\n # If it matches print the first group capture\n print(\"Your tag {} is closed\".format(match_tag.group(1))) \n else:\n # If it doesn't match capture only the tag \n notmatch_tag = re.match(r\"<(\\w+)>\", string)\n # Print the first group capture\n print(\"Close your {} tag!\".format(notmatch_tag.group(1)))",
"Your tag body is closed\nYour tag article is closed\nClose your nav tag!\n"
]
],
[
[
"# Reeepeated characters\nBack to your sentiment analysis! Your next task is to replace elongated words that appear in the tweets. We define an elongated word as a word that contains a repeating character twice or more times. e.g. \"Awesoooome\".\n\nReplacing those words is very important since a classifier will treat them as a different term from the source words lowering their frequency.\n\nTo find them, you will use capturing groups and reference them back using numbers. E.g \\4.\n\nIf you want to find a match for Awesoooome. You first need to capture Awes. Then, match o and reference the same character back, and then, me.\n\nThe list sentiment_analysis, containing the text of three tweets, and the re module are loaded in your session. You can use print() to view the data in the IPython Shell.",
"_____no_output_____"
]
],
[
[
"sentiment_analysis = ['@marykatherine_q i know! I heard it this morning and wondered the same thing. Moscooooooow is so behind the times',\n 'Staying at a friends house...neighborrrrrrrs are so loud-having a party',\n 'Just woke up an already have read some e-mail']",
"_____no_output_____"
],
[
"# Complete the regex to match an elongated word\nregex_elongated = r\"\\w*(\\w)\\1\\w*\"\n\nfor tweet in sentiment_analysis:\n\t# Find if there is a match in each tweet \n\tmatch_elongated = re.search(regex_elongated, tweet)\n \n\tif match_elongated:\n\t\t# Assign the captured group zero \n\t\telongated_word = match_elongated.group(0)\n \n\t\t# Complete the format method to print the word\n\t\tprint(\"Elongated word found: {word}\".format(word=elongated_word))\n\telse:\n\t\tprint(\"No elongated word found\")",
"Elongated word found: Moscooooooow\nElongated word found: neighborrrrrrrs\nNo elongated word found\n"
]
],
[
[
"# Surrounding words\nNow, you want to perform some visualizations with your sentiment_analysis dataset. You are interested in the words surrounding python. You want to count how many times a specific words appears right before and after it.\n\nPositive lookahead (?=) makes sure that first part of the expression is followed by the lookahead expression. Positive lookbehind (?<=) returns all matches that are preceded by the specified pattern.\n\nThe variable sentiment_analysis, containing the text of one tweet, and the re module are loaded in your session. You can use print() to view the data in the IPython Shell.",
"_____no_output_____"
]
],
[
[
"sentiment_analysis = 'You need excellent python skills to be a data scientist. Must be! Excellent python'",
"_____no_output_____"
],
[
"# Positive lookahead\nlook_ahead = re.findall(r\"\\w+(?=\\spython)\", sentiment_analysis)\n\n# Print out\nprint(look_ahead)",
"['excellent', 'Excellent']\n"
],
[
"# Positive lookbehind\nlook_behind = re.findall(r\"(?<=[Pp]ython\\s)\\w+\", sentiment_analysis)\n\n# Print out\nprint(look_behind)",
"['skills']\n"
]
],
[
[
"# Filtering phone numbers\nNow, you need to write a script for a cell-phone searcher. It should scan a list of phone numbers and return those that meet certain characteristics.\n\nThe phone numbers in the list have the structure:\n\n- Optional area code: 3 numbers\n- Prefix: 4 numbers\n- Line number: 6 numbers\n- Optional extension: 2 numbers\n\nE.g. 654-8764-439434-01.\n\nYou decide to use .findall() and the non-capturing group's negative lookahead (?!) and negative lookbehind (?<!).\n\nThe list cellphones, containing three phone numbers, and the re module are loaded in your session. You can use print() to view the data in the IPython Shell.",
"_____no_output_____"
]
],
[
[
"cellphones = ['4564-646464-01', '345-5785-544245', '6476-579052-01']",
"_____no_output_____"
],
[
"for phone in cellphones:\n\t# Get all phone numbers not preceded by area code\n\tnumber = re.findall(r\"(?<!\\d{3}-)\\d{4}-\\d{6}-\\d{2}\", phone)\n\tprint(number)",
"['4564-646464-01']\n[]\n['6476-579052-01']\n"
],
[
"for phone in cellphones:\n\t# Get all phone numbers not followed by optional extension\n\tnumber = re.findall(r\"\\d{3}-\\d{4}-\\d{6}(?!-\\d{2})\", phone)\n\tprint(number)",
"[]\n['345-5785-544245']\n[]\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
e77c54766898ca0400c1fd7f8c2b62ae4bdf579b | 576,462 | ipynb | Jupyter Notebook | batch-norm/Batch_Normalization_Lesson.ipynb | JJINDAHOUSE/deep-learning | dcfcef325a257da9fb090909d73d129d3416a402 | [
"MIT"
] | null | null | null | batch-norm/Batch_Normalization_Lesson.ipynb | JJINDAHOUSE/deep-learning | dcfcef325a257da9fb090909d73d129d3416a402 | [
"MIT"
] | null | null | null | batch-norm/Batch_Normalization_Lesson.ipynb | JJINDAHOUSE/deep-learning | dcfcef325a257da9fb090909d73d129d3416a402 | [
"MIT"
] | null | null | null | 274.114123 | 33,390 | 0.895048 | [
[
[
"# Batch Normalization – Lesson\n\n1. [What is it?](#theory)\n2. [What are it's benefits?](#benefits)\n3. [How do we add it to a network?](#implementation_1)\n4. [Let's see it work!](#demos)\n5. [What are you hiding?](#implementation_2)\n\n# What is Batch Normalization?<a id='theory'></a>\n\nBatch normalization was introduced in Sergey Ioffe's and Christian Szegedy's 2015 paper [Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift](https://arxiv.org/pdf/1502.03167.pdf). The idea is that, instead of just normalizing the inputs to the network, we normalize the inputs to _layers within_ the network. It's called \"batch\" normalization because during training, we normalize each layer's inputs by using the mean and variance of the values in the current mini-batch.\n\nWhy might this help? Well, we know that normalizing the inputs to a _network_ helps the network learn. But a network is a series of layers, where the output of one layer becomes the input to another. That means we can think of any layer in a neural network as the _first_ layer of a smaller network.\n\nFor example, imagine a 3 layer network. Instead of just thinking of it as a single network with inputs, layers, and outputs, think of the output of layer 1 as the input to a two layer network. This two layer network would consist of layers 2 and 3 in our original network. \n\nLikewise, the output of layer 2 can be thought of as the input to a single layer network, consisting only of layer 3.\n\nWhen you think of it like that - as a series of neural networks feeding into each other - then it's easy to imagine how normalizing the inputs to each layer would help. It's just like normalizing the inputs to any other neural network, but you're doing it at every layer (sub-network).\n\nBeyond the intuitive reasons, there are good mathematical reasons why it helps the network learn better, too. It helps combat what the authors call _internal covariate shift_. This discussion is best handled [in the paper](https://arxiv.org/pdf/1502.03167.pdf) and in [Deep Learning](http://www.deeplearningbook.org) a book you can read online written by Ian Goodfellow, Yoshua Bengio, and Aaron Courville. Specifically, check out the batch normalization section of [Chapter 8: Optimization for Training Deep Models](http://www.deeplearningbook.org/contents/optimization.html).",
"_____no_output_____"
],
[
"# Benefits of Batch Normalization<a id=\"benefits\"></a>\n\nBatch normalization optimizes network training. It has been shown to have several benefits:\n1. **Networks train faster** – Each training _iteration_ will actually be slower because of the extra calculations during the forward pass and the additional hyperparameters to train during back propagation. However, it should converge much more quickly, so training should be faster overall. \n2. **Allows higher learning rates** – Gradient descent usually requires small learning rates for the network to converge. And as networks get deeper, their gradients get smaller during back propagation so they require even more iterations. Using batch normalization allows us to use much higher learning rates, which further increases the speed at which networks train. \n3. **Makes weights easier to initialize** – Weight initialization can be difficult, and it's even more difficult when creating deeper networks. Batch normalization seems to allow us to be much less careful about choosing our initial starting weights. \n4. **Makes more activation functions viable** – Some activation functions do not work well in some situations. Sigmoids lose their gradient pretty quickly, which means they can't be used in deep networks. And ReLUs often die out during training, where they stop learning completely, so we need to be careful about the range of values fed into them. Because batch normalization regulates the values going into each activation function, non-linearlities that don't seem to work well in deep networks actually become viable again. \n5. **Simplifies the creation of deeper networks** – Because of the first 4 items listed above, it is easier to build and faster to train deeper neural networks when using batch normalization. And it's been shown that deeper networks generally produce better results, so that's great.\n6. **Provides a bit of regularlization** – Batch normalization adds a little noise to your network. In some cases, such as in Inception modules, batch normalization has been shown to work as well as dropout. But in general, consider batch normalization as a bit of extra regularization, possibly allowing you to reduce some of the dropout you might add to a network. \n7. **May give better results overall** – Some tests seem to show batch normalization actually improves the training results. However, it's really an optimization to help train faster, so you shouldn't think of it as a way to make your network better. But since it lets you train networks faster, that means you can iterate over more designs more quickly. It also lets you build deeper networks, which are usually better. So when you factor in everything, you're probably going to end up with better results if you build your networks with batch normalization.",
"_____no_output_____"
],
[
"# Batch Normalization in TensorFlow<a id=\"implementation_1\"></a>\n\nThis section of the notebook shows you one way to add batch normalization to a neural network built in TensorFlow. \n\nThe following cell imports the packages we need in the notebook and loads the MNIST dataset to use in our experiments. However, the `tensorflow` package contains all the code you'll actually need for batch normalization.",
"_____no_output_____"
]
],
[
[
"# Import necessary packages\nimport tensorflow as tf\nimport tqdm\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n# Import MNIST data so we have something for our experiments\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)",
"Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes.\nExtracting MNIST_data/train-images-idx3-ubyte.gz\nSuccessfully downloaded train-labels-idx1-ubyte.gz 28881 bytes.\nExtracting MNIST_data/train-labels-idx1-ubyte.gz\nSuccessfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes.\nExtracting MNIST_data/t10k-images-idx3-ubyte.gz\nSuccessfully downloaded t10k-labels-idx1-ubyte.gz 4542 bytes.\nExtracting MNIST_data/t10k-labels-idx1-ubyte.gz\n"
]
],
[
[
"### Neural network classes for testing\n\nThe following class, `NeuralNet`, allows us to create identical neural networks with and without batch normalization. The code is heavily documented, but there is also some additional discussion later. You do not need to read through it all before going through the rest of the notebook, but the comments within the code blocks may answer some of your questions.\n\n*About the code:*\n>This class is not meant to represent TensorFlow best practices – the design choices made here are to support the discussion related to batch normalization.\n\n>It's also important to note that we use the well-known MNIST data for these examples, but the networks we create are not meant to be good for performing handwritten character recognition. We chose this network architecture because it is similar to the one used in the original paper, which is complex enough to demonstrate some of the benefits of batch normalization while still being fast to train.",
"_____no_output_____"
]
],
[
[
"class NeuralNet:\n def __init__(self, initial_weights, activation_fn, use_batch_norm):\n \"\"\"\n Initializes this object, creating a TensorFlow graph using the given parameters.\n \n :param initial_weights: list of NumPy arrays or Tensors\n Initial values for the weights for every layer in the network. We pass these in\n so we can create multiple networks with the same starting weights to eliminate\n training differences caused by random initialization differences.\n The number of items in the list defines the number of layers in the network,\n and the shapes of the items in the list define the number of nodes in each layer.\n e.g. Passing in 3 matrices of shape (784, 256), (256, 100), and (100, 10) would \n create a network with 784 inputs going into a hidden layer with 256 nodes,\n followed by a hidden layer with 100 nodes, followed by an output layer with 10 nodes.\n :param activation_fn: Callable\n The function used for the output of each hidden layer. The network will use the same\n activation function on every hidden layer and no activate function on the output layer.\n e.g. Pass tf.nn.relu to use ReLU activations on your hidden layers.\n :param use_batch_norm: bool\n Pass True to create a network that uses batch normalization; False otherwise\n Note: this network will not use batch normalization on layers that do not have an\n activation function.\n \"\"\"\n # Keep track of whether or not this network uses batch normalization.\n self.use_batch_norm = use_batch_norm\n self.name = \"With Batch Norm\" if use_batch_norm else \"Without Batch Norm\"\n\n # Batch normalization needs to do different calculations during training and inference,\n # so we use this placeholder to tell the graph which behavior to use.\n self.is_training = tf.placeholder(tf.bool, name=\"is_training\")\n\n # This list is just for keeping track of data we want to plot later.\n # It doesn't actually have anything to do with neural nets or batch normalization.\n self.training_accuracies = []\n\n # Create the network graph, but it will not actually have any real values until after you\n # call train or test\n self.build_network(initial_weights, activation_fn)\n \n def build_network(self, initial_weights, activation_fn):\n \"\"\"\n Build the graph. The graph still needs to be trained via the `train` method.\n \n :param initial_weights: list of NumPy arrays or Tensors\n See __init__ for description. \n :param activation_fn: Callable\n See __init__ for description. \n \"\"\"\n self.input_layer = tf.placeholder(tf.float32, [None, initial_weights[0].shape[0]])\n layer_in = self.input_layer\n for weights in initial_weights[:-1]:\n layer_in = self.fully_connected(layer_in, weights, activation_fn) \n self.output_layer = self.fully_connected(layer_in, initial_weights[-1])\n \n def fully_connected(self, layer_in, initial_weights, activation_fn=None):\n \"\"\"\n Creates a standard, fully connected layer. Its number of inputs and outputs will be\n defined by the shape of `initial_weights`, and its starting weight values will be\n taken directly from that same parameter. If `self.use_batch_norm` is True, this\n layer will include batch normalization, otherwise it will not. \n \n :param layer_in: Tensor\n The Tensor that feeds into this layer. It's either the input to the network or the output\n of a previous layer.\n :param initial_weights: NumPy array or Tensor\n Initial values for this layer's weights. The shape defines the number of nodes in the layer.\n e.g. Passing in 3 matrix of shape (784, 256) would create a layer with 784 inputs and 256 \n outputs. \n :param activation_fn: Callable or None (default None)\n The non-linearity used for the output of the layer. If None, this layer will not include \n batch normalization, regardless of the value of `self.use_batch_norm`. \n e.g. Pass tf.nn.relu to use ReLU activations on your hidden layers.\n \"\"\"\n # Since this class supports both options, only use batch normalization when\n # requested. However, do not use it on the final layer, which we identify\n # by its lack of an activation function.\n if self.use_batch_norm and activation_fn:\n # Batch normalization uses weights as usual, but does NOT add a bias term. This is because \n # its calculations include gamma and beta variables that make the bias term unnecessary.\n # (See later in the notebook for more details.)\n weights = tf.Variable(initial_weights)\n linear_output = tf.matmul(layer_in, weights)\n\n # Apply batch normalization to the linear combination of the inputs and weights\n batch_normalized_output = tf.layers.batch_normalization(linear_output, training=self.is_training)\n\n # Now apply the activation function, *after* the normalization.\n return activation_fn(batch_normalized_output)\n else:\n # When not using batch normalization, create a standard layer that multiplies\n # the inputs and weights, adds a bias, and optionally passes the result \n # through an activation function. \n weights = tf.Variable(initial_weights)\n biases = tf.Variable(tf.zeros([initial_weights.shape[-1]]))\n linear_output = tf.add(tf.matmul(layer_in, weights), biases)\n return linear_output if not activation_fn else activation_fn(linear_output)\n\n def train(self, session, learning_rate, training_batches, batches_per_sample, save_model_as=None):\n \"\"\"\n Trains the model on the MNIST training dataset.\n \n :param session: Session\n Used to run training graph operations.\n :param learning_rate: float\n Learning rate used during gradient descent.\n :param training_batches: int\n Number of batches to train.\n :param batches_per_sample: int\n How many batches to train before sampling the validation accuracy.\n :param save_model_as: string or None (default None)\n Name to use if you want to save the trained model.\n \"\"\"\n # This placeholder will store the target labels for each mini batch\n labels = tf.placeholder(tf.float32, [None, 10])\n\n # Define loss and optimizer\n cross_entropy = tf.reduce_mean(\n tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=self.output_layer))\n \n # Define operations for testing\n correct_prediction = tf.equal(tf.argmax(self.output_layer, 1), tf.argmax(labels, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n if self.use_batch_norm:\n # If we don't include the update ops as dependencies on the train step, the \n # tf.layers.batch_normalization layers won't update their population statistics,\n # which will cause the model to fail at inference time\n with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):\n train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy)\n else:\n train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy)\n \n # Train for the appropriate number of batches. (tqdm is only for a nice timing display)\n for i in tqdm.tqdm(range(training_batches)):\n # We use batches of 60 just because the original paper did. You can use any size batch you like.\n batch_xs, batch_ys = mnist.train.next_batch(60)\n session.run(train_step, feed_dict={self.input_layer: batch_xs, \n labels: batch_ys, \n self.is_training: True})\n \n # Periodically test accuracy against the 5k validation images and store it for plotting later.\n if i % batches_per_sample == 0:\n test_accuracy = session.run(accuracy, feed_dict={self.input_layer: mnist.validation.images,\n labels: mnist.validation.labels,\n self.is_training: False})\n self.training_accuracies.append(test_accuracy)\n\n # After training, report accuracy against test data\n test_accuracy = session.run(accuracy, feed_dict={self.input_layer: mnist.validation.images,\n labels: mnist.validation.labels,\n self.is_training: False})\n print('{}: After training, final accuracy on validation set = {}'.format(self.name, test_accuracy))\n\n # If you want to use this model later for inference instead of having to retrain it,\n # just construct it with the same parameters and then pass this file to the 'test' function\n if save_model_as:\n tf.train.Saver().save(session, save_model_as)\n\n def test(self, session, test_training_accuracy=False, include_individual_predictions=False, restore_from=None):\n \"\"\"\n Trains a trained model on the MNIST testing dataset.\n\n :param session: Session\n Used to run the testing graph operations.\n :param test_training_accuracy: bool (default False)\n If True, perform inference with batch normalization using batch mean and variance;\n if False, perform inference with batch normalization using estimated population mean and variance.\n Note: in real life, *always* perform inference using the population mean and variance.\n This parameter exists just to support demonstrating what happens if you don't.\n :param include_individual_predictions: bool (default True)\n This function always performs an accuracy test against the entire test set. But if this parameter\n is True, it performs an extra test, doing 200 predictions one at a time, and displays the results\n and accuracy.\n :param restore_from: string or None (default None)\n Name of a saved model if you want to test with previously saved weights.\n \"\"\"\n # This placeholder will store the true labels for each mini batch\n labels = tf.placeholder(tf.float32, [None, 10])\n\n # Define operations for testing\n correct_prediction = tf.equal(tf.argmax(self.output_layer, 1), tf.argmax(labels, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n # If provided, restore from a previously saved model\n if restore_from:\n tf.train.Saver().restore(session, restore_from)\n\n # Test against all of the MNIST test data\n test_accuracy = session.run(accuracy, feed_dict={self.input_layer: mnist.test.images,\n labels: mnist.test.labels,\n self.is_training: test_training_accuracy})\n print('-'*75)\n print('{}: Accuracy on full test set = {}'.format(self.name, test_accuracy))\n\n # If requested, perform tests predicting individual values rather than batches\n if include_individual_predictions:\n predictions = []\n correct = 0\n\n # Do 200 predictions, 1 at a time\n for i in range(200):\n # This is a normal prediction using an individual test case. However, notice\n # we pass `test_training_accuracy` to `feed_dict` as the value for `self.is_training`.\n # Remember that will tell it whether it should use the batch mean & variance or\n # the population estimates that were calucated while training the model.\n pred, corr = session.run([tf.arg_max(self.output_layer,1), accuracy],\n feed_dict={self.input_layer: [mnist.test.images[i]],\n labels: [mnist.test.labels[i]],\n self.is_training: test_training_accuracy})\n correct += corr\n\n predictions.append(pred[0])\n\n print(\"200 Predictions:\", predictions)\n print(\"Accuracy on 200 samples:\", correct/200)\n",
"_____no_output_____"
]
],
[
[
"There are quite a few comments in the code, so those should answer most of your questions. However, let's take a look at the most important lines.\n\nWe add batch normalization to layers inside the `fully_connected` function. Here are some important points about that code:\n1. Layers with batch normalization do not include a bias term.\n2. We use TensorFlow's [`tf.layers.batch_normalization`](https://www.tensorflow.org/api_docs/python/tf/layers/batch_normalization) function to handle the math. (We show lower-level ways to do this [later in the notebook](#implementation_2).)\n3. We tell `tf.layers.batch_normalization` whether or not the network is training. This is an important step we'll talk about later.\n4. We add the normalization **before** calling the activation function.\n\nIn addition to that code, the training step is wrapped in the following `with` statement:\n```python\nwith tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):\n```\nThis line actually works in conjunction with the `training` parameter we pass to `tf.layers.batch_normalization`. Without it, TensorFlow's batch normalization layer will not operate correctly during inference.\n\nFinally, whenever we train the network or perform inference, we use the `feed_dict` to set `self.is_training` to `True` or `False`, respectively, like in the following line:\n```python\nsession.run(train_step, feed_dict={self.input_layer: batch_xs, \n labels: batch_ys, \n self.is_training: True})\n```\nWe'll go into more details later, but next we want to show some experiments that use this code and test networks with and without batch normalization.",
"_____no_output_____"
],
[
"# Batch Normalization Demos<a id='demos'></a>\nThis section of the notebook trains various networks with and without batch normalization to demonstrate some of the benefits mentioned earlier. \n\nWe'd like to thank the author of this blog post [Implementing Batch Normalization in TensorFlow](http://r2rt.com/implementing-batch-normalization-in-tensorflow.html). That post provided the idea of - and some of the code for - plotting the differences in accuracy during training, along with the idea for comparing multiple networks using the same initial weights.",
"_____no_output_____"
],
[
"## Code to support testing\n\nThe following two functions support the demos we run in the notebook. \n\nThe first function, `plot_training_accuracies`, simply plots the values found in the `training_accuracies` lists of the `NeuralNet` objects passed to it. If you look at the `train` function in `NeuralNet`, you'll see it that while it's training the network, it periodically measures validation accuracy and stores the results in that list. It does that just to support these plots.\n\nThe second function, `train_and_test`, creates two neural nets - one with and one without batch normalization. It then trains them both and tests them, calling `plot_training_accuracies` to plot how their accuracies changed over the course of training. The really imporant thing about this function is that it initializes the starting weights for the networks _outside_ of the networks and then passes them in. This lets it train both networks from the exact same starting weights, which eliminates performance differences that might result from (un)lucky initial weights.",
"_____no_output_____"
]
],
[
[
"def plot_training_accuracies(*args, **kwargs):\n \"\"\"\n Displays a plot of the accuracies calculated during training to demonstrate\n how many iterations it took for the model(s) to converge.\n \n :param args: One or more NeuralNet objects\n You can supply any number of NeuralNet objects as unnamed arguments \n and this will display their training accuracies. Be sure to call `train` \n the NeuralNets before calling this function.\n :param kwargs: \n You can supply any named parameters here, but `batches_per_sample` is the only\n one we look for. It should match the `batches_per_sample` value you passed\n to the `train` function.\n \"\"\"\n fig, ax = plt.subplots()\n\n batches_per_sample = kwargs['batches_per_sample']\n \n for nn in args:\n ax.plot(range(0,len(nn.training_accuracies)*batches_per_sample,batches_per_sample),\n nn.training_accuracies, label=nn.name)\n ax.set_xlabel('Training steps')\n ax.set_ylabel('Accuracy')\n ax.set_title('Validation Accuracy During Training')\n ax.legend(loc=4)\n ax.set_ylim([0,1])\n plt.yticks(np.arange(0, 1.1, 0.1))\n plt.grid(True)\n plt.show()\n\ndef train_and_test(use_bad_weights, learning_rate, activation_fn, training_batches=50000, batches_per_sample=500):\n \"\"\"\n Creates two networks, one with and one without batch normalization, then trains them\n with identical starting weights, layers, batches, etc. Finally tests and plots their accuracies.\n \n :param use_bad_weights: bool\n If True, initialize the weights of both networks to wildly inappropriate weights;\n if False, use reasonable starting weights.\n :param learning_rate: float\n Learning rate used during gradient descent.\n :param activation_fn: Callable\n The function used for the output of each hidden layer. The network will use the same\n activation function on every hidden layer and no activate function on the output layer.\n e.g. Pass tf.nn.relu to use ReLU activations on your hidden layers.\n :param training_batches: (default 50000)\n Number of batches to train.\n :param batches_per_sample: (default 500)\n How many batches to train before sampling the validation accuracy.\n \"\"\"\n # Use identical starting weights for each network to eliminate differences in\n # weight initialization as a cause for differences seen in training performance\n #\n # Note: The networks will use these weights to define the number of and shapes of\n # its layers. The original batch normalization paper used 3 hidden layers\n # with 100 nodes in each, followed by a 10 node output layer. These values\n # build such a network, but feel free to experiment with different choices.\n # However, the input size should always be 784 and the final output should be 10.\n if use_bad_weights:\n # These weights should be horrible because they have such a large standard deviation\n weights = [np.random.normal(size=(784,100), scale=5.0).astype(np.float32),\n np.random.normal(size=(100,100), scale=5.0).astype(np.float32),\n np.random.normal(size=(100,100), scale=5.0).astype(np.float32),\n np.random.normal(size=(100,10), scale=5.0).astype(np.float32)\n ]\n else:\n # These weights should be good because they have such a small standard deviation\n weights = [np.random.normal(size=(784,100), scale=0.05).astype(np.float32),\n np.random.normal(size=(100,100), scale=0.05).astype(np.float32),\n np.random.normal(size=(100,100), scale=0.05).astype(np.float32),\n np.random.normal(size=(100,10), scale=0.05).astype(np.float32)\n ]\n\n # Just to make sure the TensorFlow's default graph is empty before we start another\n # test, because we don't bother using different graphs or scoping and naming \n # elements carefully in this sample code.\n tf.reset_default_graph()\n\n # build two versions of same network, 1 without and 1 with batch normalization\n nn = NeuralNet(weights, activation_fn, False)\n bn = NeuralNet(weights, activation_fn, True)\n \n # train and test the two models\n with tf.Session() as sess:\n tf.global_variables_initializer().run()\n\n nn.train(sess, learning_rate, training_batches, batches_per_sample)\n bn.train(sess, learning_rate, training_batches, batches_per_sample)\n \n nn.test(sess)\n bn.test(sess)\n \n # Display a graph of how validation accuracies changed during training\n # so we can compare how the models trained and when they converged\n plot_training_accuracies(nn, bn, batches_per_sample=batches_per_sample)\n",
"_____no_output_____"
]
],
[
[
"## Comparisons between identical networks, with and without batch normalization\n\nThe next series of cells train networks with various settings to show the differences with and without batch normalization. They are meant to clearly demonstrate the effects of batch normalization. We include a deeper discussion of batch normalization later in the notebook.",
"_____no_output_____"
],
[
"**The following creates two networks using a ReLU activation function, a learning rate of 0.01, and reasonable starting weights.**",
"_____no_output_____"
]
],
[
[
"train_and_test(False, 0.01, tf.nn.relu)",
"100%|██████████| 50000/50000 [00:42<00:00, 1183.34it/s]\n"
]
],
[
[
"As expected, both networks train well and eventually reach similar test accuracies. However, notice that the model with batch normalization converges slightly faster than the other network, reaching accuracies over 90% almost immediately and nearing its max acuracy in 10 or 15 thousand iterations. The other network takes about 3 thousand iterations to reach 90% and doesn't near its best accuracy until 30 thousand or more iterations.\n\nIf you look at the raw speed, you can see that without batch normalization we were computing over 1100 batches per second, whereas with batch normalization that goes down to just over 500. However, batch normalization allows us to perform fewer iterations and converge in less time over all. (We only trained for 50 thousand batches here so we could plot the comparison.)",
"_____no_output_____"
],
[
"**The following creates two networks with the same hyperparameters used in the previous example, but only trains for 2000 iterations.**",
"_____no_output_____"
]
],
[
[
"train_and_test(False, 0.01, tf.nn.relu, 2000, 50)",
"100%|██████████| 2000/2000 [00:01<00:00, 1069.17it/s]\n"
]
],
[
[
"As you can see, using batch normalization produces a model with over 95% accuracy in only 2000 batches, and it was above 90% at somewhere around 500 batches. Without batch normalization, the model takes 1750 iterations just to hit 80% – the network with batch normalization hits that mark after around 200 iterations! (Note: if you run the code yourself, you'll see slightly different results each time because the starting weights - while the same for each model - are different for each run.)\n\nIn the above example, you should also notice that the networks trained fewer batches per second then what you saw in the previous example. That's because much of the time we're tracking is actually spent periodically performing inference to collect data for the plots. In this example we perform that inference every 50 batches instead of every 500, so generating the plot for this example requires 10 times the overhead for the same 2000 iterations.",
"_____no_output_____"
],
[
"**The following creates two networks using a sigmoid activation function, a learning rate of 0.01, and reasonable starting weights.**",
"_____no_output_____"
]
],
[
[
"train_and_test(False, 0.01, tf.nn.sigmoid)",
"100%|██████████| 50000/50000 [00:43<00:00, 1153.97it/s]\n"
]
],
[
[
"With the number of layers we're using and this small learning rate, using a sigmoid activation function takes a long time to start learning. It eventually starts making progress, but it took over 45 thousand batches just to get over 80% accuracy. Using batch normalization gets to 90% in around one thousand batches. ",
"_____no_output_____"
],
[
"**The following creates two networks using a ReLU activation function, a learning rate of 1, and reasonable starting weights.**",
"_____no_output_____"
]
],
[
[
"train_and_test(False, 1, tf.nn.relu)",
"100%|██████████| 50000/50000 [00:35<00:00, 1397.55it/s]\n"
]
],
[
[
"Now we're using ReLUs again, but with a larger learning rate. The plot shows how training started out pretty normally, with the network with batch normalization starting out faster than the other. But the higher learning rate bounces the accuracy around a bit more, and at some point the accuracy in the network without batch normalization just completely crashes. It's likely that too many ReLUs died off at this point because of the high learning rate.\n\nThe next cell shows the same test again. The network with batch normalization performs the same way, and the other suffers from the same problem again, but it manages to train longer before it happens.",
"_____no_output_____"
]
],
[
[
"train_and_test(False, 1, tf.nn.relu)",
"100%|██████████| 50000/50000 [00:36<00:00, 1379.92it/s]\n"
]
],
[
[
"In both of the previous examples, the network with batch normalization manages to gets over 98% accuracy, and get near that result almost immediately. The higher learning rate allows the network to train extremely fast.",
"_____no_output_____"
],
[
"**The following creates two networks using a sigmoid activation function, a learning rate of 1, and reasonable starting weights.**",
"_____no_output_____"
]
],
[
[
"train_and_test(False, 1, tf.nn.sigmoid)",
"100%|██████████| 50000/50000 [00:36<00:00, 1382.38it/s]\n"
]
],
[
[
"In this example, we switched to a sigmoid activation function. It appears to hande the higher learning rate well, with both networks achieving high accuracy.\n\nThe cell below shows a similar pair of networks trained for only 2000 iterations.",
"_____no_output_____"
]
],
[
[
"train_and_test(False, 1, tf.nn.sigmoid, 2000, 50)",
"100%|██████████| 2000/2000 [00:01<00:00, 1167.28it/s]\n"
]
],
[
[
"As you can see, even though these parameters work well for both networks, the one with batch normalization gets over 90% in 400 or so batches, whereas the other takes over 1700. When training larger networks, these sorts of differences become more pronounced.",
"_____no_output_____"
],
[
"**The following creates two networks using a ReLU activation function, a learning rate of 2, and reasonable starting weights.**",
"_____no_output_____"
]
],
[
[
"train_and_test(False, 2, tf.nn.relu)",
"100%|██████████| 50000/50000 [00:35<00:00, 1412.09it/s]\n"
]
],
[
[
"With this very large learning rate, the network with batch normalization trains fine and almost immediately manages 98% accuracy. However, the network without normalization doesn't learn at all.",
"_____no_output_____"
],
[
"**The following creates two networks using a sigmoid activation function, a learning rate of 2, and reasonable starting weights.**",
"_____no_output_____"
]
],
[
[
"train_and_test(False, 2, tf.nn.sigmoid)",
"100%|██████████| 50000/50000 [00:35<00:00, 1395.37it/s]\n"
]
],
[
[
"Once again, using a sigmoid activation function with the larger learning rate works well both with and without batch normalization.\n\nHowever, look at the plot below where we train models with the same parameters but only 2000 iterations. As usual, batch normalization lets it train faster. ",
"_____no_output_____"
]
],
[
[
"train_and_test(False, 2, tf.nn.sigmoid, 2000, 50)",
"100%|██████████| 2000/2000 [00:01<00:00, 1170.27it/s]\n"
]
],
[
[
"In the rest of the examples, we use really bad starting weights. That is, normally we would use very small values close to zero. However, in these examples we choose random values with a standard deviation of 5. If you were really training a neural network, you would **not** want to do this. But these examples demonstrate how batch normalization makes your network much more resilient. ",
"_____no_output_____"
],
[
"**The following creates two networks using a ReLU activation function, a learning rate of 0.01, and bad starting weights.**",
"_____no_output_____"
]
],
[
[
"train_and_test(True, 0.01, tf.nn.relu)",
"100%|██████████| 50000/50000 [00:43<00:00, 1147.21it/s]\n"
]
],
[
[
"As the plot shows, without batch normalization the network never learns anything at all. But with batch normalization, it actually learns pretty well and gets to almost 80% accuracy. The starting weights obviously hurt the network, but you can see how well batch normalization does in overcoming them. ",
"_____no_output_____"
],
[
"**The following creates two networks using a sigmoid activation function, a learning rate of 0.01, and bad starting weights.**",
"_____no_output_____"
]
],
[
[
"train_and_test(True, 0.01, tf.nn.sigmoid)",
"100%|██████████| 50000/50000 [00:45<00:00, 1108.50it/s]\n"
]
],
[
[
"Using a sigmoid activation function works better than the ReLU in the previous example, but without batch normalization it would take a tremendously long time to train the network, if it ever trained at all. ",
"_____no_output_____"
],
[
"**The following creates two networks using a ReLU activation function, a learning rate of 1, and bad starting weights.**<a id=\"successful_example_lr_1\"></a>",
"_____no_output_____"
]
],
[
[
"train_and_test(True, 1, tf.nn.relu)",
"100%|██████████| 50000/50000 [00:38<00:00, 1313.14it/s]\n"
]
],
[
[
"The higher learning rate used here allows the network with batch normalization to surpass 90% in about 30 thousand batches. The network without it never gets anywhere.",
"_____no_output_____"
],
[
"**The following creates two networks using a sigmoid activation function, a learning rate of 1, and bad starting weights.**",
"_____no_output_____"
]
],
[
[
"train_and_test(True, 1, tf.nn.sigmoid)",
"100%|██████████| 50000/50000 [00:35<00:00, 1409.45it/s]\n"
]
],
[
[
"Using sigmoid works better than ReLUs for this higher learning rate. However, you can see that without batch normalization, the network takes a long time tro train, bounces around a lot, and spends a long time stuck at 90%. The network with batch normalization trains much more quickly, seems to be more stable, and achieves a higher accuracy.",
"_____no_output_____"
],
[
"**The following creates two networks using a ReLU activation function, a learning rate of 2, and bad starting weights.**<a id=\"successful_example_lr_2\"></a>",
"_____no_output_____"
]
],
[
[
"train_and_test(True, 2, tf.nn.relu)",
"100%|██████████| 50000/50000 [00:35<00:00, 1392.83it/s]\n"
]
],
[
[
"We've already seen that ReLUs do not do as well as sigmoids with higher learning rates, and here we are using an extremely high rate. As expected, without batch normalization the network doesn't learn at all. But with batch normalization, it eventually achieves 90% accuracy. Notice, though, how its accuracy bounces around wildly during training - that's because the learning rate is really much too high, so the fact that this worked at all is a bit of luck.",
"_____no_output_____"
],
[
"**The following creates two networks using a sigmoid activation function, a learning rate of 2, and bad starting weights.**",
"_____no_output_____"
]
],
[
[
"train_and_test(True, 2, tf.nn.sigmoid)",
"100%|██████████| 50000/50000 [00:35<00:00, 1401.19it/s]\n"
]
],
[
[
"In this case, the network with batch normalization trained faster and reached a higher accuracy. Meanwhile, the high learning rate makes the network without normalization bounce around erratically and have trouble getting past 90%.",
"_____no_output_____"
],
[
"### Full Disclosure: Batch Normalization Doesn't Fix Everything\n\nBatch normalization isn't magic and it doesn't work every time. Weights are still randomly initialized and batches are chosen at random during training, so you never know exactly how training will go. Even for these tests, where we use the same initial weights for both networks, we still get _different_ weights each time we run.\n\nThis section includes two examples that show runs when batch normalization did not help at all.\n\n**The following creates two networks using a ReLU activation function, a learning rate of 1, and bad starting weights.**",
"_____no_output_____"
]
],
[
[
"train_and_test(True, 1, tf.nn.relu)",
"100%|██████████| 50000/50000 [00:36<00:00, 1386.17it/s]\n"
]
],
[
[
"When we used these same parameters [earlier](#successful_example_lr_1), we saw the network with batch normalization reach 92% validation accuracy. This time we used different starting weights, initialized using the same standard deviation as before, and the network doesn't learn at all. (Remember, an accuracy around 10% is what the network gets if it just guesses the same value all the time.)\n\n**The following creates two networks using a ReLU activation function, a learning rate of 2, and bad starting weights.**",
"_____no_output_____"
]
],
[
[
"train_and_test(True, 2, tf.nn.relu)",
"100%|██████████| 50000/50000 [00:35<00:00, 1398.39it/s]\n"
]
],
[
[
"When we trained with these parameters and batch normalization [earlier](#successful_example_lr_2), we reached 90% validation accuracy. However, this time the network _almost_ starts to make some progress in the beginning, but it quickly breaks down and stops learning. \n\n**Note:** Both of the above examples use *extremely* bad starting weights, along with learning rates that are too high. While we've shown batch normalization _can_ overcome bad values, we don't mean to encourage actually using them. The examples in this notebook are meant to show that batch normalization can help your networks train better. But these last two examples should remind you that you still want to try to use good network design choices and reasonable starting weights. It should also remind you that the results of each attempt to train a network are a bit random, even when using otherwise identical architectures.",
"_____no_output_____"
],
[
"# Batch Normalization: A Detailed Look<a id='implementation_2'></a>",
"_____no_output_____"
],
[
"The layer created by `tf.layers.batch_normalization` handles all the details of implementing batch normalization. Many students will be fine just using that and won't care about what's happening at the lower levels. However, some students may want to explore the details, so here is a short explanation of what's really happening, starting with the equations you're likely to come across if you ever read about batch normalization. ",
"_____no_output_____"
],
[
"In order to normalize the values, we first need to find the average value for the batch. If you look at the code, you can see that this is not the average value of the batch _inputs_, but the average value coming _out_ of any particular layer before we pass it through its non-linear activation function and then feed it as an input to the _next_ layer.\n\nWe represent the average as $\\mu_B$, which is simply the sum of all of the values $x_i$ divided by the number of values, $m$ \n\n$$\n\\mu_B \\leftarrow \\frac{1}{m}\\sum_{i=1}^m x_i\n$$\n\nWe then need to calculate the variance, or mean squared deviation, represented as $\\sigma_{B}^{2}$. If you aren't familiar with statistics, that simply means for each value $x_i$, we subtract the average value (calculated earlier as $\\mu_B$), which gives us what's called the \"deviation\" for that value. We square the result to get the squared deviation. Sum up the results of doing that for each of the values, then divide by the number of values, again $m$, to get the average, or mean, squared deviation.\n\n$$\n\\sigma_{B}^{2} \\leftarrow \\frac{1}{m}\\sum_{i=1}^m (x_i - \\mu_B)^2\n$$\n\nOnce we have the mean and variance, we can use them to normalize the values with the following equation. For each value, it subtracts the mean and divides by the (almost) standard deviation. (You've probably heard of standard deviation many times, but if you have not studied statistics you might not know that the standard deviation is actually the square root of the mean squared deviation.)\n\n$$\n\\hat{x_i} \\leftarrow \\frac{x_i - \\mu_B}{\\sqrt{\\sigma_{B}^{2} + \\epsilon}}\n$$\n\nAbove, we said \"(almost) standard deviation\". That's because the real standard deviation for the batch is calculated by $\\sqrt{\\sigma_{B}^{2}}$, but the above formula adds the term epsilon, $\\epsilon$, before taking the square root. The epsilon can be any small, positive constant - in our code we use the value `0.001`. It is there partially to make sure we don't try to divide by zero, but it also acts to increase the variance slightly for each batch. \n\nWhy increase the variance? Statistically, this makes sense because even though we are normalizing one batch at a time, we are also trying to estimate the population distribution – the total training set, which itself an estimate of the larger population of inputs your network wants to handle. The variance of a population is higher than the variance for any sample taken from that population, so increasing the variance a little bit for each batch helps take that into account. \n\nAt this point, we have a normalized value, represented as $\\hat{x_i}$. But rather than use it directly, we multiply it by a gamma value, $\\gamma$, and then add a beta value, $\\beta$. Both $\\gamma$ and $\\beta$ are learnable parameters of the network and serve to scale and shift the normalized value, respectively. Because they are learnable just like weights, they give your network some extra knobs to tweak during training to help it learn the function it is trying to approximate. \n\n$$\ny_i \\leftarrow \\gamma \\hat{x_i} + \\beta\n$$\n\nWe now have the final batch-normalized output of our layer, which we would then pass to a non-linear activation function like sigmoid, tanh, ReLU, Leaky ReLU, etc. In the original batch normalization paper (linked in the beginning of this notebook), they mention that there might be cases when you'd want to perform the batch normalization _after_ the non-linearity instead of before, but it is difficult to find any uses like that in practice.\n\nIn `NeuralNet`'s implementation of `fully_connected`, all of this math is hidden inside the following line, where `linear_output` serves as the $x_i$ from the equations:\n```python\nbatch_normalized_output = tf.layers.batch_normalization(linear_output, training=self.is_training)\n```\nThe next section shows you how to implement the math directly. ",
"_____no_output_____"
],
[
"### Batch normalization without the `tf.layers` package\n\nOur implementation of batch normalization in `NeuralNet` uses the high-level abstraction [tf.layers.batch_normalization](https://www.tensorflow.org/api_docs/python/tf/layers/batch_normalization), found in TensorFlow's [`tf.layers`](https://www.tensorflow.org/api_docs/python/tf/layers) package.\n\nHowever, if you would like to implement batch normalization at a lower level, the following code shows you how.\nIt uses [tf.nn.batch_normalization](https://www.tensorflow.org/api_docs/python/tf/nn/batch_normalization) from TensorFlow's [neural net (nn)](https://www.tensorflow.org/api_docs/python/tf/nn) package.\n\n**1)** You can replace the `fully_connected` function in the `NeuralNet` class with the below code and everything in `NeuralNet` will still work like it did before.",
"_____no_output_____"
]
],
[
[
"def fully_connected(self, layer_in, initial_weights, activation_fn=None):\n \"\"\"\n Creates a standard, fully connected layer. Its number of inputs and outputs will be\n defined by the shape of `initial_weights`, and its starting weight values will be\n taken directly from that same parameter. If `self.use_batch_norm` is True, this\n layer will include batch normalization, otherwise it will not. \n \n :param layer_in: Tensor\n The Tensor that feeds into this layer. It's either the input to the network or the output\n of a previous layer.\n :param initial_weights: NumPy array or Tensor\n Initial values for this layer's weights. The shape defines the number of nodes in the layer.\n e.g. Passing in 3 matrix of shape (784, 256) would create a layer with 784 inputs and 256 \n outputs. \n :param activation_fn: Callable or None (default None)\n The non-linearity used for the output of the layer. If None, this layer will not include \n batch normalization, regardless of the value of `self.use_batch_norm`. \n e.g. Pass tf.nn.relu to use ReLU activations on your hidden layers.\n \"\"\"\n if self.use_batch_norm and activation_fn:\n # Batch normalization uses weights as usual, but does NOT add a bias term. This is because \n # its calculations include gamma and beta variables that make the bias term unnecessary.\n weights = tf.Variable(initial_weights)\n linear_output = tf.matmul(layer_in, weights)\n\n num_out_nodes = initial_weights.shape[-1]\n\n # Batch normalization adds additional trainable variables: \n # gamma (for scaling) and beta (for shifting).\n gamma = tf.Variable(tf.ones([num_out_nodes]))\n beta = tf.Variable(tf.zeros([num_out_nodes]))\n\n # These variables will store the mean and variance for this layer over the entire training set,\n # which we assume represents the general population distribution.\n # By setting `trainable=False`, we tell TensorFlow not to modify these variables during\n # back propagation. Instead, we will assign values to these variables ourselves. \n pop_mean = tf.Variable(tf.zeros([num_out_nodes]), trainable=False)\n pop_variance = tf.Variable(tf.ones([num_out_nodes]), trainable=False)\n\n # Batch normalization requires a small constant epsilon, used to ensure we don't divide by zero.\n # This is the default value TensorFlow uses.\n epsilon = 1e-3\n\n def batch_norm_training():\n # Calculate the mean and variance for the data coming out of this layer's linear-combination step.\n # The [0] defines an array of axes to calculate over.\n batch_mean, batch_variance = tf.nn.moments(linear_output, [0])\n\n # Calculate a moving average of the training data's mean and variance while training.\n # These will be used during inference.\n # Decay should be some number less than 1. tf.layers.batch_normalization uses the parameter\n # \"momentum\" to accomplish this and defaults it to 0.99\n decay = 0.99\n train_mean = tf.assign(pop_mean, pop_mean * decay + batch_mean * (1 - decay))\n train_variance = tf.assign(pop_variance, pop_variance * decay + batch_variance * (1 - decay))\n\n # The 'tf.control_dependencies' context tells TensorFlow it must calculate 'train_mean' \n # and 'train_variance' before it calculates the 'tf.nn.batch_normalization' layer.\n # This is necessary because the those two operations are not actually in the graph\n # connecting the linear_output and batch_normalization layers, \n # so TensorFlow would otherwise just skip them.\n with tf.control_dependencies([train_mean, train_variance]):\n return tf.nn.batch_normalization(linear_output, batch_mean, batch_variance, beta, gamma, epsilon)\n \n def batch_norm_inference():\n # During inference, use the our estimated population mean and variance to normalize the layer\n return tf.nn.batch_normalization(linear_output, pop_mean, pop_variance, beta, gamma, epsilon)\n\n # Use `tf.cond` as a sort of if-check. When self.is_training is True, TensorFlow will execute \n # the operation returned from `batch_norm_training`; otherwise it will execute the graph\n # operation returned from `batch_norm_inference`.\n batch_normalized_output = tf.cond(self.is_training, batch_norm_training, batch_norm_inference)\n \n # Pass the batch-normalized layer output through the activation function.\n # The literature states there may be cases where you want to perform the batch normalization *after*\n # the activation function, but it is difficult to find any uses of that in practice.\n return activation_fn(batch_normalized_output)\n else:\n # When not using batch normalization, create a standard layer that multiplies\n # the inputs and weights, adds a bias, and optionally passes the result \n # through an activation function. \n weights = tf.Variable(initial_weights)\n biases = tf.Variable(tf.zeros([initial_weights.shape[-1]]))\n linear_output = tf.add(tf.matmul(layer_in, weights), biases)\n return linear_output if not activation_fn else activation_fn(linear_output)\n",
"_____no_output_____"
]
],
[
[
"This version of `fully_connected` is much longer than the original, but once again has extensive comments to help you understand it. Here are some important points:\n\n1. It explicitly creates variables to store gamma, beta, and the population mean and variance. These were all handled for us in the previous version of the function.\n2. It initializes gamma to one and beta to zero, so they start out having no effect in this calculation: $y_i \\leftarrow \\gamma \\hat{x_i} + \\beta$. However, during training the network learns the best values for these variables using back propagation, just like networks normally do with weights.\n3. Unlike gamma and beta, the variables for population mean and variance are marked as untrainable. That tells TensorFlow not to modify them during back propagation. Instead, the lines that call `tf.assign` are used to update these variables directly.\n4. TensorFlow won't automatically run the `tf.assign` operations during training because it only evaluates operations that are required based on the connections it finds in the graph. To get around that, we add this line: `with tf.control_dependencies([train_mean, train_variance]):` before we run the normalization operation. This tells TensorFlow it needs to run those operations before running anything inside the `with` block. \n5. The actual normalization math is still mostly hidden from us, this time using [`tf.nn.batch_normalization`](https://www.tensorflow.org/api_docs/python/tf/nn/batch_normalization).\n5. `tf.nn.batch_normalization` does not have a `training` parameter like `tf.layers.batch_normalization` did. However, we still need to handle training and inference differently, so we run different code in each case using the [`tf.cond`](https://www.tensorflow.org/api_docs/python/tf/cond) operation.\n6. We use the [`tf.nn.moments`](https://www.tensorflow.org/api_docs/python/tf/nn/moments) function to calculate the batch mean and variance.",
"_____no_output_____"
],
[
"**2)** The current version of the `train` function in `NeuralNet` will work fine with this new version of `fully_connected`. However, it uses these lines to ensure population statistics are updated when using batch normalization: \n```python\nif self.use_batch_norm:\n with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):\n train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy)\nelse:\n train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy)\n```\nOur new version of `fully_connected` handles updating the population statistics directly. That means you can also simplify your code by replacing the above `if`/`else` condition with just this line:\n```python\ntrain_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy)\n```",
"_____no_output_____"
],
[
"**3)** And just in case you want to implement every detail from scratch, you can replace this line in `batch_norm_training`:\n\n```python\nreturn tf.nn.batch_normalization(linear_output, batch_mean, batch_variance, beta, gamma, epsilon)\n```\nwith these lines:\n```python\nnormalized_linear_output = (linear_output - batch_mean) / tf.sqrt(batch_variance + epsilon)\nreturn gamma * normalized_linear_output + beta\n```\nAnd replace this line in `batch_norm_inference`:\n```python\nreturn tf.nn.batch_normalization(linear_output, pop_mean, pop_variance, beta, gamma, epsilon)\n```\nwith these lines:\n```python\nnormalized_linear_output = (linear_output - pop_mean) / tf.sqrt(pop_variance + epsilon)\nreturn gamma * normalized_linear_output + beta\n```\n\nAs you can see in each of the above substitutions, the two lines of replacement code simply implement the following two equations directly. The first line calculates the following equation, with `linear_output` representing $x_i$ and `normalized_linear_output` representing $\\hat{x_i}$: \n\n$$\n\\hat{x_i} \\leftarrow \\frac{x_i - \\mu_B}{\\sqrt{\\sigma_{B}^{2} + \\epsilon}}\n$$\n\nAnd the second line is a direct translation of the following equation:\n\n$$\ny_i \\leftarrow \\gamma \\hat{x_i} + \\beta\n$$\n\nWe still use the `tf.nn.moments` operation to implement the other two equations from earlier – the ones that calculate the batch mean and variance used in the normalization step. If you really wanted to do everything from scratch, you could replace that line, too, but we'll leave that to you. \n\n## Why the difference between training and inference?\n\nIn the original function that uses `tf.layers.batch_normalization`, we tell the layer whether or not the network is training by passing a value for its `training` parameter, like so:\n```python\nbatch_normalized_output = tf.layers.batch_normalization(linear_output, training=self.is_training)\n```\nAnd that forces us to provide a value for `self.is_training` in our `feed_dict`, like we do in this example from `NeuralNet`'s `train` function:\n```python\nsession.run(train_step, feed_dict={self.input_layer: batch_xs, \n labels: batch_ys, \n self.is_training: True})\n```\nIf you looked at the [low level implementation](#low_level_code), you probably noticed that, just like with `tf.layers.batch_normalization`, we need to do slightly different things during training and inference. But why is that?\n\nFirst, let's look at what happens when we don't. The following function is similar to `train_and_test` from earlier, but this time we are only testing one network and instead of plotting its accuracy, we perform 200 predictions on test inputs, 1 input at at time. We can use the `test_training_accuracy` parameter to test the network in training or inference modes (the equivalent of passing `True` or `False` to the `feed_dict` for `is_training`).",
"_____no_output_____"
]
],
[
[
"def batch_norm_test(test_training_accuracy):\n \"\"\"\n :param test_training_accuracy: bool\n If True, perform inference with batch normalization using batch mean and variance;\n if False, perform inference with batch normalization using estimated population mean and variance.\n \"\"\"\n\n weights = [np.random.normal(size=(784,100), scale=0.05).astype(np.float32),\n np.random.normal(size=(100,100), scale=0.05).astype(np.float32),\n np.random.normal(size=(100,100), scale=0.05).astype(np.float32),\n np.random.normal(size=(100,10), scale=0.05).astype(np.float32)\n ]\n\n tf.reset_default_graph()\n\n # Train the model\n bn = NeuralNet(weights, tf.nn.relu, True)\n \n # First train the network\n with tf.Session() as sess:\n tf.global_variables_initializer().run()\n\n bn.train(sess, 0.01, 2000, 2000)\n\n bn.test(sess, test_training_accuracy=test_training_accuracy, include_individual_predictions=True)",
"_____no_output_____"
]
],
[
[
"In the following cell, we pass `True` for `test_training_accuracy`, which performs the same batch normalization that we normally perform **during training**.",
"_____no_output_____"
]
],
[
[
"batch_norm_test(True)",
"100%|██████████| 2000/2000 [00:03<00:00, 514.57it/s]\n"
]
],
[
[
"As you can see, the network guessed the same value every time! But why? Because during training, a network with batch normalization adjusts the values at each layer based on the mean and variance **of that batch**. The \"batches\" we are using for these predictions have a single input each time, so their values _are_ the means, and their variances will always be 0. That means the network will normalize the values at any layer to zero. (Review the equations from before to see why a value that is equal to the mean would always normalize to zero.) So we end up with the same result for every input we give the network, because its the value the network produces when it applies its learned weights to zeros at every layer. \n\n**Note:** If you re-run that cell, you might get a different value from what we showed. That's because the specific weights the network learns will be different every time. But whatever value it is, it should be the same for all 200 predictions.\n\nTo overcome this problem, the network does not just normalize the batch at each layer. It also maintains an estimate of the mean and variance for the entire population. So when we perform inference, instead of letting it \"normalize\" all the values using their own means and variance, it uses the estimates of the population mean and variance that it calculated while training. \n\nSo in the following example, we pass `False` for `test_training_accuracy`, which tells the network that we it want to perform inference with the population statistics it calculates during training.",
"_____no_output_____"
]
],
[
[
"batch_norm_test(False)",
"100%|██████████| 2000/2000 [00:03<00:00, 511.58it/s]\n"
]
],
[
[
"As you can see, now that we're using the estimated population mean and variance, we get a 97% accuracy. That means it guessed correctly on 194 of the 200 samples – not too bad for something that trained in under 4 seconds. :)\n\n# Considerations for other network types\n\nThis notebook demonstrates batch normalization in a standard neural network with fully connected layers. You can also use batch normalization in other types of networks, but there are some special considerations.\n\n### ConvNets\n\nConvolution layers consist of multiple feature maps. (Remember, the depth of a convolutional layer refers to its number of feature maps.) And the weights for each feature map are shared across all the inputs that feed into the layer. Because of these differences, batch normalizaing convolutional layers requires batch/population mean and variance per feature map rather than per node in the layer.\n\nWhen using `tf.layers.batch_normalization`, be sure to pay attention to the order of your convolutionlal dimensions.\nSpecifically, you may want to set a different value for the `axis` parameter if your layers have their channels first instead of last. \n\nIn our low-level implementations, we used the following line to calculate the batch mean and variance:\n```python\nbatch_mean, batch_variance = tf.nn.moments(linear_output, [0])\n```\nIf we were dealing with a convolutional layer, we would calculate the mean and variance with a line like this instead:\n```python\nbatch_mean, batch_variance = tf.nn.moments(conv_layer, [0,1,2], keep_dims=False)\n```\nThe second parameter, `[0,1,2]`, tells TensorFlow to calculate the batch mean and variance over each feature map. (The three axes are the batch, height, and width.) And setting `keep_dims` to `False` tells `tf.nn.moments` not to return values with the same size as the inputs. Specifically, it ensures we get one mean/variance pair per feature map.\n\n### RNNs\n\nBatch normalization can work with recurrent neural networks, too, as shown in the 2016 paper [Recurrent Batch Normalization](https://arxiv.org/abs/1603.09025). It's a bit more work to implement, but basically involves calculating the means and variances per time step instead of per layer. You can find an example where someone extended `tf.nn.rnn_cell.RNNCell` to include batch normalization in [this GitHub repo](https://gist.github.com/spitis/27ab7d2a30bbaf5ef431b4a02194ac60).",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e77c5bd30672c3f78598e7d456ff8d2e4cb70928 | 25,532 | ipynb | Jupyter Notebook | Demo of LSTM_Sentiment_Classification_KOR.ipynb | yool-seoul/sentiment_analysis_lstm | cedd3f0b59897a1e77dfebce9352a1d6d7bc9376 | [
"MIT"
] | null | null | null | Demo of LSTM_Sentiment_Classification_KOR.ipynb | yool-seoul/sentiment_analysis_lstm | cedd3f0b59897a1e77dfebce9352a1d6d7bc9376 | [
"MIT"
] | null | null | null | Demo of LSTM_Sentiment_Classification_KOR.ipynb | yool-seoul/sentiment_analysis_lstm | cedd3f0b59897a1e77dfebce9352a1d6d7bc9376 | [
"MIT"
] | null | null | null | 25,532 | 25,532 | 0.692229 | [
[
[
"# 0. Environment Setting",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nimport time\nimport tensorflow as tf\nimport tensorflow.keras as keras\nfrom keras.models import load_model\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences",
"_____no_output_____"
],
[
"start_time = time.time()",
"_____no_output_____"
],
[
"# 학습완료된 모델, 전처리 완료된 데이터 다운로드\n!wget --no-check-certificate 'https://docs.google.com/uc?export=download&id=1-8A3zjgyBi3vjlWi9DX61IFxunCihb3-' -O demo_model.h5\n!wget --no-check-certificate 'https://docs.google.com/uc?export=download&id=1ApkVRmC0B2DgLjYQ3l1sbF6bx2GyBttY' -O demo_sentiment.xlsx",
"--2021-08-12 03:00:25-- https://docs.google.com/uc?export=download&id=1-8A3zjgyBi3vjlWi9DX61IFxunCihb3-\nResolving docs.google.com (docs.google.com)... 108.177.13.100, 108.177.13.139, 108.177.13.113, ...\nConnecting to docs.google.com (docs.google.com)|108.177.13.100|:443... connected.\nHTTP request sent, awaiting response... 302 Moved Temporarily\nLocation: https://doc-04-98-docs.googleusercontent.com/docs/securesc/ha0ro937gcuc7l7deffksulhg5h7mbp1/bqfdl0u6qal2sfcnuiqarlfn5uj60443/1628737200000/15913661007502099898/*/1-8A3zjgyBi3vjlWi9DX61IFxunCihb3-?e=download [following]\nWarning: wildcards not supported in HTTP.\n--2021-08-12 03:00:25-- https://doc-04-98-docs.googleusercontent.com/docs/securesc/ha0ro937gcuc7l7deffksulhg5h7mbp1/bqfdl0u6qal2sfcnuiqarlfn5uj60443/1628737200000/15913661007502099898/*/1-8A3zjgyBi3vjlWi9DX61IFxunCihb3-?e=download\nResolving doc-04-98-docs.googleusercontent.com (doc-04-98-docs.googleusercontent.com)... 108.177.12.132, 2607:f8b0:400c:c08::84\nConnecting to doc-04-98-docs.googleusercontent.com (doc-04-98-docs.googleusercontent.com)|108.177.12.132|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: unspecified [application/octet-stream]\nSaving to: ‘demo_model.h5’\n\ndemo_model.h5 [ <=> ] 10.91M 41.5MB/s in 0.3s \n\n2021-08-12 03:00:26 (41.5 MB/s) - ‘demo_model.h5’ saved [11435216]\n\n--2021-08-12 03:00:26-- https://docs.google.com/uc?export=download&id=1ApkVRmC0B2DgLjYQ3l1sbF6bx2GyBttY\nResolving docs.google.com (docs.google.com)... 74.125.26.101, 74.125.26.102, 74.125.26.100, ...\nConnecting to docs.google.com (docs.google.com)|74.125.26.101|:443... connected.\nHTTP request sent, awaiting response... 302 Moved Temporarily\nLocation: https://doc-04-98-docs.googleusercontent.com/docs/securesc/ha0ro937gcuc7l7deffksulhg5h7mbp1/5987ptllp6it20aim2nrj50s8fn9bafm/1628737200000/15913661007502099898/*/1ApkVRmC0B2DgLjYQ3l1sbF6bx2GyBttY?e=download [following]\nWarning: wildcards not supported in HTTP.\n--2021-08-12 03:00:27-- https://doc-04-98-docs.googleusercontent.com/docs/securesc/ha0ro937gcuc7l7deffksulhg5h7mbp1/5987ptllp6it20aim2nrj50s8fn9bafm/1628737200000/15913661007502099898/*/1ApkVRmC0B2DgLjYQ3l1sbF6bx2GyBttY?e=download\nResolving doc-04-98-docs.googleusercontent.com (doc-04-98-docs.googleusercontent.com)... 108.177.12.132, 2607:f8b0:400c:c08::84\nConnecting to doc-04-98-docs.googleusercontent.com (doc-04-98-docs.googleusercontent.com)|108.177.12.132|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: unspecified [application/vnd.openxmlformats-officedocument.spreadsheetml.sheet]\nSaving to: ‘demo_sentiment.xlsx’\n\ndemo_sentiment.xlsx [ <=> ] 10.51M 39.3MB/s in 0.3s \n\n2021-08-12 03:00:27 (39.3 MB/s) - ‘demo_sentiment.xlsx’ saved [11016871]\n\n"
],
[
"# Mecab 설치용 스크립트 (약 3분 걸림)\n!set -x \\\n&& pip install konlpy \\\n&& curl -s https://raw.githubusercontent.com/konlpy/konlpy/master/scripts/mecab.sh | bash -x",
"+ pip install konlpy\nRequirement already satisfied: konlpy in /usr/local/lib/python3.7/dist-packages (0.5.2)\nRequirement already satisfied: lxml>=4.1.0 in /usr/local/lib/python3.7/dist-packages (from konlpy) (4.2.6)\nRequirement already satisfied: tweepy>=3.7.0 in /usr/local/lib/python3.7/dist-packages (from konlpy) (3.10.0)\nRequirement already satisfied: JPype1>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from konlpy) (1.3.0)\nRequirement already satisfied: numpy>=1.6 in /usr/local/lib/python3.7/dist-packages (from konlpy) (1.19.5)\nRequirement already satisfied: beautifulsoup4==4.6.0 in /usr/local/lib/python3.7/dist-packages (from konlpy) (4.6.0)\nRequirement already satisfied: colorama in /usr/local/lib/python3.7/dist-packages (from konlpy) (0.4.4)\nRequirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from JPype1>=0.7.0->konlpy) (3.7.4.3)\nRequirement already satisfied: six>=1.10.0 in /usr/local/lib/python3.7/dist-packages (from tweepy>=3.7.0->konlpy) (1.15.0)\nRequirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from tweepy>=3.7.0->konlpy) (1.3.0)\nRequirement already satisfied: requests[socks]>=2.11.1 in /usr/local/lib/python3.7/dist-packages (from tweepy>=3.7.0->konlpy) (2.23.0)\nRequirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from requests-oauthlib>=0.7.0->tweepy>=3.7.0->konlpy) (3.1.1)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests[socks]>=2.11.1->tweepy>=3.7.0->konlpy) (2021.5.30)\nRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests[socks]>=2.11.1->tweepy>=3.7.0->konlpy) (2.10)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests[socks]>=2.11.1->tweepy>=3.7.0->konlpy) (1.24.3)\nRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests[socks]>=2.11.1->tweepy>=3.7.0->konlpy) (3.0.4)\nRequirement already satisfied: PySocks!=1.5.7,>=1.5.6 in /usr/local/lib/python3.7/dist-packages (from requests[socks]>=2.11.1->tweepy>=3.7.0->konlpy) (1.7.1)\n+ bash -x\n+ curl -s https://raw.githubusercontent.com/konlpy/konlpy/master/scripts/mecab.sh\n+ mecab_dicdir=/usr/local/lib/mecab/dic/mecab-ko-dic\n+ set -e\n++ uname\n+ os=Linux\n+ [[ ! Linux == \\L\\i\\n\\u\\x ]]\n+ hash sudo\n+ sudo=sudo\n+ python=python3\n+ hash pyenv\n+ at_user_site=\n++ check_python_site_location_is_writable\n++ python3 -\n+ [[ 1 == \\0 ]]\n+ hash automake\n+ hash mecab\n+ echo 'mecab-ko is already installed'\nmecab-ko is already installed\n+ [[ -d /usr/local/lib/mecab/dic/mecab-ko-dic ]]\n+ echo 'mecab-ko-dic is already installed'\nmecab-ko-dic is already installed\n++ python3 -c 'import pkgutil; print(1 if pkgutil.find_loader(\"MeCab\") else 0)'\n+ [[ 1 == \\1 ]]\n+ echo 'mecab-python is already installed'\nmecab-python is already installed\n+ echo Done.\nDone.\n"
],
[
"# 잘 설치되었는지 테스트\nfrom konlpy.tag import Mecab\nm = Mecab()\nm.pos('아버지가방에들어가신다.')",
"_____no_output_____"
]
],
[
[
"# 1. Data loading",
"_____no_output_____"
]
],
[
[
"MAX_LEN = 50\nVOCAB_SIZE = 13648",
"_____no_output_____"
],
[
"# Tokenizer 인코딩을 위한 학습용 엑셀 파일읽어들이기 약 30초 걸림.\ndf1 = pd.read_excel('./demo_sentiment.xlsx', sheet_name='Train')",
"_____no_output_____"
],
[
"def tokenize(s):\n return ['/'.join(t) for t in m.pos(s)]\n\ntrain_docs = [tokenize(row[1]['sentence']) for row in df1.iterrows()]",
"_____no_output_____"
],
[
"tokenizer = Tokenizer(num_words = VOCAB_SIZE)\ntokenizer.fit_on_texts(train_docs)",
"_____no_output_____"
],
[
"# 학습을 완료한 모델을 불러오기\nloaded_model = load_model('demo_model.h5')",
"_____no_output_____"
],
[
"end_time = time.time()\nprint(\"Elapsed time for ready :\", time.strftime('%H:%M:%S', time.localtime(end_time - start_time)))",
"Elapsed time for ready : 00:01:11\n"
]
],
[
[
"# 2. Ready to test",
"_____no_output_____"
]
],
[
[
"# 이용자가 알아보기 쉽게 결과를 분석해서 출력해 주는 함수들.\ndef sentiment_predict(sentence, log=False):\n sentences = tokenize(sentence)\n encoded = tokenizer.texts_to_sequences([sentences])\n padded = pad_sequences(encoded, maxlen=MAX_LEN)\n score = loaded_model.predict(padded)\n if log:\n print('Predict score: ', score)\n return score\n\ndef print_sentiment(lst):\n sent = ['기쁨', '불안', '당황', '슬픔', '분노', '상처']\n return sent[np.argmax(lst)]",
"_____no_output_____"
],
[
"print_sentiment(sentiment_predict('니가 어떻게 나에게 이럴수가 있어?', True))",
"Predict score: [[0.64731556 0.10514342 0.11939979 0.07021657 0.0094684 0.04845627]]\n"
],
[
"print_sentiment(sentiment_predict('아니, 니가 어떻게 나에게 이럴수가 있어?', True))",
"Predict score: [[0.144451 0.05985985 0.43685517 0.2238917 0.03347811 0.10146421]]\n"
],
[
"print_sentiment(sentiment_predict('감히 니가 어떻게 나에게 이럴수가 있어?', True))",
"Predict score: [[0.10038799 0.00701625 0.0068602 0.04465635 0.8361947 0.00488456]]\n"
],
[
"print_sentiment(sentiment_predict('그래, 너 참 잘났다.', True))",
"Predict score: [[0.27811512 0.01648478 0.4914975 0.12529652 0.05300648 0.03559963]]\n"
],
[
"print_sentiment(sentiment_predict('너 참 잘났다.', True))",
"Predict score: [[0.48111573 0.03345519 0.33038217 0.05245472 0.07973 0.02286207]]\n"
],
[
"print_sentiment(sentiment_predict('잘들논다.', True))",
"Predict score: [[0.6240433 0.13965438 0.08255927 0.06877399 0.04602019 0.03894896]]\n"
],
[
"print_sentiment(sentiment_predict('아이고, 잘들논다.', True))",
"Predict score: [[0.08556036 0.08469302 0.04617947 0.6354081 0.1436197 0.00453937]]\n"
],
[
"print_sentiment(sentiment_predict('방금 저녁을 먹었는데 왜 또 배가고프지?', True))",
"Predict score: [[0.00149013 0.01824094 0.12491249 0.47754213 0.28039864 0.09741567]]\n"
],
[
"print_sentiment(sentiment_predict('오늘 저녁에 내가 좋아하는 친구의 생일파티에 초대받았어', True))",
"Predict score: [[0.80365133 0.02223701 0.01515409 0.11137892 0.00547363 0.0421051 ]]\n"
],
[
"print_sentiment(sentiment_predict('이번 여름은 코로나 때문에 여행을 가지 못했어.', True))",
"Predict score: [[0.13640569 0.15130658 0.23596878 0.04992492 0.41861936 0.00777466]]\n"
],
[
"print_sentiment(sentiment_predict('다음 주에 개학인데, 나는 아직 방학숙제를 다 못했어.', True))",
"Predict score: [[2.5222797e-04 5.8436580e-03 7.8574214e-03 9.6365899e-01 2.1302477e-02\n 1.0852749e-03]]\n"
],
[
"# 자유롭게 문장을 입력해보자.\nmessages = ['어제 한국과 일본이 배구경기를 했는데, 한국이 이겼어.',\n '어제 한국과 일본이 배구경기를 했는데, 한국이 이겼어. 그런데 나는 일본사람이야.',\n '어제 한국과 일본이 배구경기를 했는데, 한국이 이겼어. 그런데 나는 한국사람이야.',\n '어제 한국과 일본이 배구경기를 했는데, 한국이 이겼어. 그런데 나는 중국사람이야.',\n '하루종일 아무것도 먹지 않았더니 몸에 힘이 없어.',\n '신규확진 1823명, 열흘만에 다시 1800명 역대 세 번째 큰 규모',\n '오늘 날씨가 너무 더워서 공부하기 힘들어',\n '니가 어떻게 나에게 이럴 수가 있어?',\n '오늘 낮에 내가 황당한 스팸 문자를 받았어',\n '아니 왜 가만히 있는 우리를 괴롭히는거야?',\n '약속시간에 늦었어, 어떡하지?',\n # 아주 짧은 문장은 어떻게 될지\n '이게 되네?',\n # 엄청 긴 문장은 과연...\n '지난 7월 소비자물가 상승률이 연중 최고치인 2.6%인 것으로 확인되면서 하반기부터는 물가가 2% 이내로 안정화될 것이라는 정부 전망은 빗나갔다. 한은이 제시한 물가안정목표치(2.0%)도 훌쩍 넘길 가능성이 커지고 있다. 물가 불안이 확대되자 정부는 ‘물가 잡기’ 총력전을 펼치는 상황이다. 작황 부진과 폭염으로 인한 폐사 등으로 서민 체감이 큰 밥상 물가가 크게 오르고, 부동산 정책 실패로 집세는 천정부지인데다 수요회복으로 서비스 가격이 뛰는 등 “안오르는게 없는” 상황에 민심 역시 악화되고 있기 때문이다. 특히 지난 5월 조류독감(AI)가 종식됐는데도 가격이 내리지 않는 계란을 놓고는, 문재인 대통령이 직접 “달걀은 필수 먹거리인 만큼 소비자들에게도 피해가 갈 수 있으니 생산단계, 유통단계, 판매단계를 점검하라”고 부처들에 주문하기도 했다. 계란값 잡기에는 물가 총괄 부처인 기재부와 함께 농림부가 나섰고, 여기에 공정거래위원회까지 담합 가능성을 살펴보겠다며 가담한 상태다.'\n]\n\nfor msg in messages:\n res = sentiment_predict(msg, True)\n print('입력문장: ', msg)\n print('감정상태: ', print_sentiment(res), '\\n')",
"Predict score: [[9.8391855e-01 1.0111522e-02 3.6681539e-04 4.6310546e-03 7.7225443e-04\n 1.9985103e-04]]\n입력문장: 어제 한국과 일본이 배구경기를 했는데, 한국이 이겼어.\n감정상태: 기쁨 \n\nPredict score: [[0.0016408 0.91486216 0.00112159 0.07445558 0.00658606 0.00133386]]\n입력문장: 어제 한국과 일본이 배구경기를 했는데, 한국이 이겼어. 그런데 나는 일본사람이야.\n감정상태: 불안 \n\nPredict score: [[9.3392795e-01 4.4720571e-02 1.8743742e-03 1.6720915e-02 2.2889334e-03\n 4.6740769e-04]]\n입력문장: 어제 한국과 일본이 배구경기를 했는데, 한국이 이겼어. 그런데 나는 한국사람이야.\n감정상태: 기쁨 \n\nPredict score: [[9.8761320e-01 6.8793707e-03 1.1007789e-03 2.6576861e-03 1.5988504e-03\n 1.5010379e-04]]\n입력문장: 어제 한국과 일본이 배구경기를 했는데, 한국이 이겼어. 그런데 나는 중국사람이야.\n감정상태: 기쁨 \n\nPredict score: [[0.00238074 0.15599112 0.2536087 0.450239 0.01611555 0.12166484]]\n입력문장: 하루종일 아무것도 먹지 않았더니 몸에 힘이 없어.\n감정상태: 슬픔 \n\nPredict score: [[0.3290947 0.04057013 0.44995427 0.16539021 0.00722547 0.00776529]]\n입력문장: 신규확진 1823명, 열흘만에 다시 1800명 역대 세 번째 큰 규모\n감정상태: 당황 \n\nPredict score: [[0.11999366 0.5234851 0.03501412 0.15736395 0.04501909 0.11912409]]\n입력문장: 오늘 날씨가 너무 더워서 공부하기 힘들어\n감정상태: 불안 \n\nPredict score: [[0.64731556 0.10514342 0.11939979 0.07021657 0.0094684 0.04845627]]\n입력문장: 니가 어떻게 나에게 이럴 수가 있어?\n감정상태: 기쁨 \n\nPredict score: [[1.8562200e-04 3.0873516e-03 9.8431301e-01 2.4380665e-03 2.5868646e-03\n 7.3890984e-03]]\n입력문장: 오늘 낮에 내가 황당한 스팸 문자를 받았어\n감정상태: 당황 \n\nPredict score: [[0.01350475 0.08442044 0.11124678 0.08692257 0.5757272 0.12817827]]\n입력문장: 아니 왜 가만히 있는 우리를 괴롭히는거야?\n감정상태: 분노 \n\nPredict score: [[0.01145534 0.13259123 0.17604479 0.24381906 0.29960954 0.13648005]]\n입력문장: 약속시간에 늦었어, 어떡하지?\n감정상태: 분노 \n\nPredict score: [[0.36998498 0.19697861 0.18539032 0.06249116 0.07014333 0.11501155]]\n입력문장: 이게 되네?\n감정상태: 기쁨 \n\nPredict score: [[0.00086347 0.00424972 0.10977216 0.03608122 0.8422188 0.00681463]]\n입력문장: 지난 7월 소비자물가 상승률이 연중 최고치인 2.6%인 것으로 확인되면서 하반기부터는 물가가 2% 이내로 안정화될 것이라는 정부 전망은 빗나갔다. 한은이 제시한 물가안정목표치(2.0%)도 훌쩍 넘길 가능성이 커지고 있다. 물가 불안이 확대되자 정부는 ‘물가 잡기’ 총력전을 펼치는 상황이다. 작황 부진과 폭염으로 인한 폐사 등으로 서민 체감이 큰 밥상 물가가 크게 오르고, 부동산 정책 실패로 집세는 천정부지인데다 수요회복으로 서비스 가격이 뛰는 등 “안오르는게 없는” 상황에 민심 역시 악화되고 있기 때문이다. 특히 지난 5월 조류독감(AI)가 종식됐는데도 가격이 내리지 않는 계란을 놓고는, 문재인 대통령이 직접 “달걀은 필수 먹거리인 만큼 소비자들에게도 피해가 갈 수 있으니 생산단계, 유통단계, 판매단계를 점검하라”고 부처들에 주문하기도 했다. 계란값 잡기에는 물가 총괄 부처인 기재부와 함께 농림부가 나섰고, 여기에 공정거래위원회까지 담합 가능성을 살펴보겠다며 가담한 상태다.\n감정상태: 분노 \n\n"
],
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e77c61c51f07af54327f64e7949b1cc43b0ff23d | 50,140 | ipynb | Jupyter Notebook | Recurrent Neural Networks/LSTM-MNIST.ipynb | KostadinPlachkov/DeepLearning | 1dc7d6c61c3283ff24f5c4066d696c4332f552fc | [
"MIT"
] | 2 | 2019-07-23T00:15:39.000Z | 2021-04-18T22:04:33.000Z | Recurrent Neural Networks/LSTM-MNIST.ipynb | KostadinPlachkov/DeepLearning | 1dc7d6c61c3283ff24f5c4066d696c4332f552fc | [
"MIT"
] | 1 | 2018-05-22T20:55:59.000Z | 2018-05-22T20:55:59.000Z | Recurrent Neural Networks/LSTM-MNIST.ipynb | KostadinPlachkov/DeepLearning | 1dc7d6c61c3283ff24f5c4066d696c4332f552fc | [
"MIT"
] | 3 | 2020-05-21T16:13:46.000Z | 2021-04-29T07:50:21.000Z | 80.224 | 24,620 | 0.788971 | [
[
[
"# Sequence Classification with LSTM on MNIST",
"_____no_output_____"
],
[
"<div class=\"alert alert-block alert-info\">\n<font size = 3><strong>Table of contents</strong></font>\n<p><a href=\"#intro\">- Introduction</a></p>\n<p><a href=\"#arch\">- Architectures</a></p>\n<p><a href=\"#lstm\">- Long Short-Term Memory Model (LSTM)</a></p>\n<p><a href=\"#build\">- Building a LSTM with TensorFlow</a></p>\n</div>",
"_____no_output_____"
],
[
"## <a id=\"intro\"/> Introduction\nRecurrent Neural Networks are Deep Learning models with simple structures and a feedback mechanism builted-in, or in different words, the output of a layer is added to the next input and fed back to the same layer.\n\nThe Recurrent Neural Network is a specialized type of Neural Network that solves the issue of **maintaining context for Sequential data** - such as Weather data, Stocks, Genes, etc. At each iterative step, the processing unit takes in an input and the current state of the network, and produces an output and a new state that is **re-fed into the network**.\n\nHowever, **this model has some problems**. It's very computationally expensive to maintain the state for a large amount of units, even more so over a long amount of time. Additionally, Recurrent Networks are very sensitive to changes in their parameters. As such, they are prone to different problems with their Gradient Descent optimizer - they either grow exponentially (Exploding Gradient) or drop down to near zero and stabilize (Vanishing Gradient), both problems that greatly harm a model's learning capability.\n\nTo solve these problems, Hochreiter and Schmidhuber published a paper in 1997 describing a way to keep information over long periods of time and additionally solve the oversensitivity to parameter changes, i.e., make backpropagating through the Recurrent Networks more viable.",
"_____no_output_____"
],
[
"## <a id=\"arch\"/>Architectures\n- Fully Recurrent Network\n- Recursive Neural Networks\n- Hopfield Networks\n- Elman Networks and Jordan Networks\n- Echo State Networks\n- Neural history compressor\n- **The Long Short-Term Memory Model (LSTM)**\n\n<img src=\"https://ibm.box.com/shared/static/v7p90neiaqghmpwawpiecmz9n7080m59.png\" width=\"800\"/>",
"_____no_output_____"
],
[
"## <a id=\"lstm\"/>LSTM\nLSTM is one of the proposed solutions or upgrades to the **Recurrent Neural Network model**. ",
"_____no_output_____"
],
[
"It is an abstraction of how computer memory works. It is \"bundled\" with whatever processing unit is implemented in the Recurrent Network, although outside of its flow, and is responsible for keeping, reading, and outputting information for the model. The way it works is simple: you have a linear unit, which is the information cell itself, surrounded by three logistic gates responsible for maintaining the data. One gate is for inputting data into the information cell, one is for outputting data from the input cell, and the last one is to keep or forget data depending on the needs of the network.\n\nThanks to that, it not only solves the problem of keeping states, because the network can choose to forget data whenever information is not needed, it also solves the gradient problems, since the Logistic Gates have a very nice derivative.\n\n### Long Short-Term Memory Architecture\n\nAs seen before, the Long Short-Term Memory is composed of a linear unit surrounded by three logistic gates. The name for these gates vary from place to place, but the most usual names for them are:\n- the \"Input\" or \"Write\" Gate, which handles the writing of data into the information cell \n- the \"Output\" or \"Read\" Gate, which handles the sending of data back onto the Recurrent Network \n- the \"Keep\" or \"Forget\" Gate, which handles the maintaining and modification of the data stored in the information cell.\n\n<img src=\"https://ibm.box.com/shared/static/zx10duv5egw0baw6gh2hzsgr8ex45gsg.png\" width=\"720\"/>\n<center>*Diagram of the Long Short-Term Memory Unit*</center>\n\nThe three gates are the centerpiece of the LSTM unit. The gates, when activated by the network, perform their respective functions. For example, the Input Gate will write whatever data it is passed onto the information cell, the Output Gate will return whatever data is in the information cell, and the Keep Gate will maintain the data in the information cell. These gates are analog and multiplicative, and as such, can modify the data based on the signal they are sent.",
"_____no_output_____"
],
[
"## <a id=\"build\"/> Building a LSTM with TensorFlow",
"_____no_output_____"
],
[
"#### LSTM for Classification\nAlthough RNN is mostly used to model sequences and predict sequential data, we can still classify images using a LSTM network. If we consider every image row as a sequence of pixels, we can feed a LSTM network for classification. Lets use the famous MNIST dataset here. Because MNIST image shape is 28*28px, we will then handle 28 sequences of 28 steps for every sample.",
"_____no_output_____"
],
[
"#### MNIST Dataset\n\nTensor flow already provides **helper functions** to download and process the MNIST dataset.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf",
"_____no_output_____"
],
[
"from tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets(\".\", one_hot=True)",
"Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes.\nExtracting ./train-images-idx3-ubyte.gz\nSuccessfully downloaded train-labels-idx1-ubyte.gz 28881 bytes.\nExtracting ./train-labels-idx1-ubyte.gz\nSuccessfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes.\nExtracting ./t10k-images-idx3-ubyte.gz\nSuccessfully downloaded t10k-labels-idx1-ubyte.gz 4542 bytes.\nExtracting ./t10k-labels-idx1-ubyte.gz\n"
]
],
[
[
"The function **`input_data.read_data_sets(...)`** loads the entire dataset and returns an object **`tensorflow.contrib.learn.python.learn.datasets.mnist.DataSets`**\n\n\nThe argument **(`one_hot=True`)** creates the label arrays as 10-dimensional binary vectors (only zeros and ones), in which the index cell for the number one, is the class label.",
"_____no_output_____"
]
],
[
[
"train_imgs = mnist.train.images\ntrain_labels = mnist.train.labels\ntest_imgs = mnist.test.images\ntest_labels = mnist.test.labels \n\nn_train = train_imgs.shape[0]\nn_test = test_imgs.shape[0]\ndim = train_imgs.shape[1]\nn_classes = train_labels.shape[1]\nprint(\"Train Images:\", train_imgs.shape)\nprint(\"Train Labels:\", train_labels.shape)\nprint()\nprint(\"Test Images:\", test_imgs.shape)\nprint(\"Test Labels:\", test_labels.shape)",
"Train Images: (55000, 784)\nTrain Labels: (55000, 10)\n\nTest Images: (10000, 784)\nTest Labels: (10000, 10)\n"
]
],
[
[
"### Let's get one sample, just to understand the structure of MNIST dataset \n\nThe next code snippet prints the **label vector** (one_hot format), **the class** and actual sample formatted as **image**:",
"_____no_output_____"
]
],
[
[
"samplesIdx = [100, 101, 102] # Change these numbers here to see other samples.\n\nfrom mpl_toolkits.mplot3d import Axes3D\nfig = plt.figure()\n\nax1 = fig.add_subplot(121)\nax1.imshow(test_imgs[samplesIdx[0]].reshape([28, 28]), cmap='gray')\n\nxx, yy = np.meshgrid(np.linspace(0, 28, 28), np.linspace(0, 28, 28))\nX = xx\nY = yy\nZ = 100 * np.ones(X.shape)\n\nimg = test_imgs[77].reshape([28, 28])\nax = fig.add_subplot(122, projection='3d')\nax.set_zlim((0, 200))\n\noffset = 200\nfor i in samplesIdx:\n img = test_imgs[i].reshape([28,28]).transpose()\n ax.contourf(X, Y, img, 200, zdir='z', offset=offset, cmap=\"gray\")\n offset -= 100\n ax.set_xticks([])\n\nax.set_yticks([])\nax.set_zticks([])\n\nplt.show()\n\nfor i in samplesIdx:\n print(\"Sample: {0} - Class: {1} - Label Vector: {2} \".format(i, np.nonzero(test_labels[i])[0], test_labels[i]))",
"_____no_output_____"
]
],
[
[
"---\n### Let's understand the parameters, inputs and outputs\n\nWe will treat the MNIST image $\\in \\mathcal{R}^{28 \\times 28}$ as $28$ sequences of a vector $\\mathbf{x} \\in \\mathcal{R}^{28}$. \n\n#### Our simple RNN consists of: \n1. One input layer which converts a $28*28$ dimensional input to an $128$ dimensional hidden layer, \n2. One intermediate recurrent neural network (LSTM) \n3. One output layer which converts an $128$ dimensional output of the LSTM to $10$ dimensional output indicating a class label. ",
"_____no_output_____"
]
],
[
[
"n_input = 28 # MNIST data input (img shape: 28*28).\nn_steps = 28 # Timesteps.\nn_hidden = 128 # Hidden layer number of features.\nn_classes = 10 # MNIST total classes (0-9 digits).\n\nlearning_rate = 0.001\ntraining_iters = 100000\nbatch_size = 100\ndisplay_step = 10",
"_____no_output_____"
]
],
[
[
"#### Construct a Recurrent Neural Network",
"_____no_output_____"
],
[
"The input should be a Tensor of shape: [batch_size, time_steps, input_dimension], but in our case it would be (?, 28, 28)",
"_____no_output_____"
]
],
[
[
"x = tf.placeholder(dtype=\"float\", shape=[None, n_steps, n_input], name=\"x\") # Current data input shape: (batch_size, n_steps, n_input) [100x28x28]\ny = tf.placeholder(dtype=\"float\", shape=[None, n_classes], name=\"y\")",
"_____no_output_____"
]
],
[
[
"Lets create the weights and biases for the read out layer.",
"_____no_output_____"
]
],
[
[
"weights = {\n 'out': tf.Variable(tf.random_normal([n_hidden, n_classes]))\n}\nbiases = {\n 'out': tf.Variable(tf.random_normal([n_classes]))\n}",
"_____no_output_____"
]
],
[
[
"Lets define a lstm cell with tensorflow.",
"_____no_output_____"
]
],
[
[
"lstm_cell = tf.contrib.rnn.BasicLSTMCell(n_hidden, forget_bias=1.0)",
"_____no_output_____"
]
],
[
[
"__dynamic_rnn__ creates a recurrent neural network specified from __lstm_cell__:",
"_____no_output_____"
]
],
[
[
"outputs, states = tf.nn.dynamic_rnn(lstm_cell, inputs=x, dtype=tf.float32)",
"_____no_output_____"
]
],
[
[
"The output of the RNN would be a [100x28x128] matrix. We use the linear activation to map it to a [?x10] matrix.",
"_____no_output_____"
]
],
[
[
"output = tf.reshape(tf.split(outputs, 28, axis=1, num=None, name='split')[-1], [-1,128])\npred = tf.matmul(output, weights['out']) + biases['out']\npred",
"_____no_output_____"
]
],
[
[
"Now, we define the cost function and optimizer:",
"_____no_output_____"
]
],
[
[
"cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=pred))\noptimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)",
"_____no_output_____"
]
],
[
[
"Here we define the accuracy and evaluation methods to be used in the learning process:",
"_____no_output_____"
]
],
[
[
"correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))",
"_____no_output_____"
]
],
[
[
"Just recall that we will treat the MNIST image $\\in \\mathcal{R}^{28 \\times 28}$ as $28$ sequences of a vector $\\mathbf{x} \\in \\mathcal{R}^{28}$. ",
"_____no_output_____"
]
],
[
[
"init = tf.global_variables_initializer()\n\nwith tf.Session() as sess:\n sess.run(init)\n step = 1\n # Keep training until reach max iterations.\n while step * batch_size < training_iters:\n # We will read a batch of 100 images [100 x 784] as batch_x\n # batch_y is a matrix of [100x10]\n batch_x, batch_y = mnist.train.next_batch(batch_size)\n \n # We consider each row of the image as one sequence.\n # Reshape data to get 28 seq of 28 elements, so that, batxh_x is [100x28x28]\n batch_x = batch_x.reshape((batch_size, n_steps, n_input))\n \n # Run optimization op (backprop)\n sess.run(optimizer, feed_dict={x: batch_x, y: batch_y})\n \n if step % display_step == 0:\n # Calculate batch accuracy.\n acc = sess.run(accuracy, feed_dict={x: batch_x, y: batch_y})\n # Calculate batch loss.\n loss = sess.run(cost, feed_dict={x: batch_x, y: batch_y})\n print(\"Iter \" + str(step*batch_size) + \", Minibatch Loss= \" + \\\n \"{:.6f}\".format(loss) + \", Training Accuracy= \" + \\\n \"{:.5f}\".format(acc))\n step += 1\n print(\"Optimization Finished!\")\n\n # Calculate accuracy for 128 mnist test images.\n test_len = 128\n test_data = mnist.test.images[:test_len].reshape((-1, n_steps, n_input))\n test_label = mnist.test.labels[:test_len]\n print(\"Testing Accuracy:\", \\\n sess.run(accuracy, feed_dict={x: test_data, y: test_label}))",
"Iter 1000, Minibatch Loss= 1.895056, Training Accuracy= 0.34000\nIter 2000, Minibatch Loss= 1.700692, Training Accuracy= 0.44000\nIter 3000, Minibatch Loss= 1.353452, Training Accuracy= 0.53000\nIter 4000, Minibatch Loss= 1.235619, Training Accuracy= 0.55000\nIter 5000, Minibatch Loss= 1.130953, Training Accuracy= 0.62000\nIter 6000, Minibatch Loss= 0.764099, Training Accuracy= 0.75000\nIter 7000, Minibatch Loss= 0.952095, Training Accuracy= 0.68000\nIter 8000, Minibatch Loss= 0.613401, Training Accuracy= 0.80000\nIter 9000, Minibatch Loss= 0.544535, Training Accuracy= 0.84000\nIter 10000, Minibatch Loss= 0.494656, Training Accuracy= 0.86000\nIter 11000, Minibatch Loss= 0.389980, Training Accuracy= 0.86000\nIter 12000, Minibatch Loss= 0.406611, Training Accuracy= 0.87000\nIter 13000, Minibatch Loss= 0.451887, Training Accuracy= 0.83000\nIter 14000, Minibatch Loss= 0.410924, Training Accuracy= 0.87000\nIter 15000, Minibatch Loss= 0.307586, Training Accuracy= 0.94000\nIter 16000, Minibatch Loss= 0.277040, Training Accuracy= 0.91000\nIter 17000, Minibatch Loss= 0.405284, Training Accuracy= 0.90000\nIter 18000, Minibatch Loss= 0.372731, Training Accuracy= 0.91000\nIter 19000, Minibatch Loss= 0.326833, Training Accuracy= 0.88000\nIter 20000, Minibatch Loss= 0.135278, Training Accuracy= 0.96000\nIter 21000, Minibatch Loss= 0.303646, Training Accuracy= 0.88000\nIter 22000, Minibatch Loss= 0.441021, Training Accuracy= 0.90000\nIter 23000, Minibatch Loss= 0.261169, Training Accuracy= 0.92000\nIter 24000, Minibatch Loss= 0.268554, Training Accuracy= 0.89000\nIter 25000, Minibatch Loss= 0.266681, Training Accuracy= 0.94000\nIter 26000, Minibatch Loss= 0.301150, Training Accuracy= 0.92000\nIter 27000, Minibatch Loss= 0.260287, Training Accuracy= 0.90000\nIter 28000, Minibatch Loss= 0.155004, Training Accuracy= 0.95000\nIter 29000, Minibatch Loss= 0.218751, Training Accuracy= 0.94000\nIter 30000, Minibatch Loss= 0.452535, Training Accuracy= 0.90000\nIter 31000, Minibatch Loss= 0.112114, Training Accuracy= 0.96000\nIter 32000, Minibatch Loss= 0.196423, Training Accuracy= 0.94000\nIter 33000, Minibatch Loss= 0.148391, Training Accuracy= 0.97000\nIter 34000, Minibatch Loss= 0.155989, Training Accuracy= 0.94000\nIter 35000, Minibatch Loss= 0.150589, Training Accuracy= 0.95000\nIter 36000, Minibatch Loss= 0.229687, Training Accuracy= 0.93000\nIter 37000, Minibatch Loss= 0.236373, Training Accuracy= 0.91000\nIter 38000, Minibatch Loss= 0.133781, Training Accuracy= 0.96000\nIter 39000, Minibatch Loss= 0.182079, Training Accuracy= 0.96000\nIter 40000, Minibatch Loss= 0.116615, Training Accuracy= 0.97000\nIter 41000, Minibatch Loss= 0.141804, Training Accuracy= 0.96000\nIter 42000, Minibatch Loss= 0.109360, Training Accuracy= 0.94000\nIter 43000, Minibatch Loss= 0.188747, Training Accuracy= 0.96000\nIter 44000, Minibatch Loss= 0.134070, Training Accuracy= 0.91000\nIter 45000, Minibatch Loss= 0.118572, Training Accuracy= 0.97000\nIter 46000, Minibatch Loss= 0.170567, Training Accuracy= 0.93000\nIter 47000, Minibatch Loss= 0.145138, Training Accuracy= 0.96000\nIter 48000, Minibatch Loss= 0.102076, Training Accuracy= 0.98000\nIter 49000, Minibatch Loss= 0.092502, Training Accuracy= 0.96000\nIter 50000, Minibatch Loss= 0.088999, Training Accuracy= 0.96000\nIter 51000, Minibatch Loss= 0.078510, Training Accuracy= 0.98000\nIter 52000, Minibatch Loss= 0.119967, Training Accuracy= 0.97000\nIter 53000, Minibatch Loss= 0.121145, Training Accuracy= 0.95000\nIter 54000, Minibatch Loss= 0.080230, Training Accuracy= 0.97000\nIter 55000, Minibatch Loss= 0.055615, Training Accuracy= 0.99000\nIter 56000, Minibatch Loss= 0.227320, Training Accuracy= 0.94000\nIter 57000, Minibatch Loss= 0.056998, Training Accuracy= 0.98000\nIter 58000, Minibatch Loss= 0.144088, Training Accuracy= 0.94000\nIter 59000, Minibatch Loss= 0.109980, Training Accuracy= 0.96000\nIter 60000, Minibatch Loss= 0.141181, Training Accuracy= 0.96000\nIter 61000, Minibatch Loss= 0.058751, Training Accuracy= 0.98000\nIter 62000, Minibatch Loss= 0.120615, Training Accuracy= 0.96000\nIter 63000, Minibatch Loss= 0.144596, Training Accuracy= 0.98000\nIter 64000, Minibatch Loss= 0.062411, Training Accuracy= 1.00000\nIter 65000, Minibatch Loss= 0.065744, Training Accuracy= 0.99000\nIter 66000, Minibatch Loss= 0.107868, Training Accuracy= 0.98000\nIter 67000, Minibatch Loss= 0.079728, Training Accuracy= 0.97000\nIter 68000, Minibatch Loss= 0.171261, Training Accuracy= 0.95000\nIter 69000, Minibatch Loss= 0.137883, Training Accuracy= 0.97000\nIter 70000, Minibatch Loss= 0.052228, Training Accuracy= 0.98000\nIter 71000, Minibatch Loss= 0.203305, Training Accuracy= 0.96000\nIter 72000, Minibatch Loss= 0.076091, Training Accuracy= 0.97000\nIter 73000, Minibatch Loss= 0.067544, Training Accuracy= 0.97000\nIter 74000, Minibatch Loss= 0.054274, Training Accuracy= 0.98000\nIter 75000, Minibatch Loss= 0.099623, Training Accuracy= 0.98000\nIter 76000, Minibatch Loss= 0.141817, Training Accuracy= 0.95000\nIter 77000, Minibatch Loss= 0.042978, Training Accuracy= 0.99000\nIter 78000, Minibatch Loss= 0.085202, Training Accuracy= 0.97000\nIter 79000, Minibatch Loss= 0.107307, Training Accuracy= 0.96000\nIter 80000, Minibatch Loss= 0.071859, Training Accuracy= 0.96000\nIter 81000, Minibatch Loss= 0.074657, Training Accuracy= 0.98000\nIter 82000, Minibatch Loss= 0.076571, Training Accuracy= 0.98000\nIter 83000, Minibatch Loss= 0.058815, Training Accuracy= 1.00000\nIter 84000, Minibatch Loss= 0.099125, Training Accuracy= 0.98000\nIter 85000, Minibatch Loss= 0.066267, Training Accuracy= 0.99000\nIter 86000, Minibatch Loss= 0.045011, Training Accuracy= 0.99000\nIter 87000, Minibatch Loss= 0.076440, Training Accuracy= 0.98000\nIter 88000, Minibatch Loss= 0.055731, Training Accuracy= 0.98000\nIter 89000, Minibatch Loss= 0.054876, Training Accuracy= 0.99000\nIter 90000, Minibatch Loss= 0.077145, Training Accuracy= 0.97000\nIter 91000, Minibatch Loss= 0.135062, Training Accuracy= 0.95000\nIter 92000, Minibatch Loss= 0.037483, Training Accuracy= 0.99000\nIter 93000, Minibatch Loss= 0.043812, Training Accuracy= 0.99000\nIter 94000, Minibatch Loss= 0.112872, Training Accuracy= 0.95000\nIter 95000, Minibatch Loss= 0.057080, Training Accuracy= 0.98000\nIter 96000, Minibatch Loss= 0.103392, Training Accuracy= 0.98000\nIter 97000, Minibatch Loss= 0.161658, Training Accuracy= 0.94000\nIter 98000, Minibatch Loss= 0.056578, Training Accuracy= 0.98000\nIter 99000, Minibatch Loss= 0.082810, Training Accuracy= 0.96000\nOptimization Finished!\nTesting Accuracy: 0.9609375\n"
],
[
"sess.close()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e77c654b74329adb37b4b4f49fad763d1a9706bd | 540,715 | ipynb | Jupyter Notebook | docs/practices/cv/super_resolution_sub_pixel.ipynb | nemonameless/docs | 946e985763dcc3ae0f029147b8141c3af4fd9d9a | [
"Apache-2.0"
] | null | null | null | docs/practices/cv/super_resolution_sub_pixel.ipynb | nemonameless/docs | 946e985763dcc3ae0f029147b8141c3af4fd9d9a | [
"Apache-2.0"
] | null | null | null | docs/practices/cv/super_resolution_sub_pixel.ipynb | nemonameless/docs | 946e985763dcc3ae0f029147b8141c3af4fd9d9a | [
"Apache-2.0"
] | null | null | null | 646.015532 | 171,340 | 0.944459 | [
[
[
"# 通过Sub-Pixel实现图像超分辨率\n**作者:** [Ralph LU](https://github.com/ralph0813)<br>\n**日期:** 2022.4 <br>\n**摘要:** 本示例通过Sub-Pixel实现图像超分辨率。",
"_____no_output_____"
],
[
"## 一、简要介绍\n\n在计算机视觉中,图像超分辨率(Image Super Resolution)是指由一幅低分辨率图像或图像序列恢复出高分辨率图像。图像超分辨率技术分为超分辨率复原和超分辨率重建。\n\n本示例简要介绍如何通过飞桨开源框架,实现图像超分辨率。包括数据集的定义、模型的搭建与训练。\n\n参考论文:《Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional Neural Network》\n\n论文链接:https://arxiv.org/abs/1609.05158",
"_____no_output_____"
],
[
"## 二、环境设置\n导入一些比较基础常用的模块,确认自己的飞桨版本。",
"_____no_output_____"
]
],
[
[
"import os\nimport io\nimport math\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\nfrom IPython.display import display\n\nimport paddle\nfrom paddle.io import Dataset\nfrom paddle.vision.transforms import transforms\n\nprint(paddle.__version__)",
"2.3.0-rc0\n"
]
],
[
[
"## 三、数据集\n### 3.1 数据集下载\n本案例使用BSR_bsds500数据集,下载链接:http://www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/BSR/BSR_bsds500.tgz",
"_____no_output_____"
]
],
[
[
"!wget --no-check-certificate --no-cookies --header \"Cookie: oraclelicense=accept-securebackup-cookie\" http://www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/BSR/BSR_bsds500.tgz\n!tar -zxvf BSR_bsds500.tgz",
"_____no_output_____"
]
],
[
[
"### 3.2 数据集概览\n```\nBSR\n├── BSDS500\n│ └── data\n│ ├── groundTruth\n│ │ ├── test\n│ │ ├── train\n│ │ └── val\n│ └── images\n│ ├── test\n│ ├── train\n│ └── val\n├── bench\n│ ├── benchmarks\n│ ├── data\n│ │ ├── ...\n│ │ └── ...\n│ └── source\n└── documentation\n```\n\n可以看到需要的图片文件在BSR/BSDS500/images文件夹下,train、test各200张,val为100张。",
"_____no_output_____"
],
[
"### 3.3 数据集类定义\n飞桨(PaddlePaddle)数据集加载方案是统一使用Dataset(数据集定义) + DataLoader(多进程数据集加载)。\n\n首先先进行数据集的定义,数据集定义主要是实现一个新的Dataset类,继承父类paddle.io.Dataset,并实现父类中以下两个抽象方法,__getitem__和__len__:\n```python\nclass MyDataset(Dataset):\n def __init__(self):\n ...\n\n # 每次迭代时返回数据和对应的标签\n def __getitem__(self, idx):\n return x, y\n\n # 返回整个数据集的总数\n def __len__(self):\n return count(samples)\n```\n",
"_____no_output_____"
]
],
[
[
"class BSD_data(Dataset):\n \"\"\"\n 继承paddle.io.Dataset类\n \"\"\"\n def __init__(self, mode='train',image_path=\"BSR/BSDS500/data/images/\"):\n \"\"\"\n 实现构造函数,定义数据读取方式,划分训练和测试数据集\n \"\"\"\n super(BSD_data, self).__init__()\n \n self.mode = mode.lower()\n if self.mode == 'train':\n self.image_path = os.path.join(image_path,'train')\n elif self.mode == 'val':\n self.image_path = os.path.join(image_path,'val')\n else:\n raise ValueError('mode must be \"train\" or \"val\"')\n \n # 原始图像的缩放大小\n self.crop_size = 300\n # 缩放倍率\n self.upscale_factor = 3\n # 缩小后送入神经网络的大小\n self.input_size = self.crop_size // self.upscale_factor\n # numpy随机数种子\n self.seed=1337\n # 图片集合\n self.temp_images = []\n # 加载数据\n self._parse_dataset()\n \n def transforms(self, img):\n \"\"\"\n 图像预处理工具,用于将升维(100, 100) => (100, 100,1),\n 并对图像的维度进行转换从HWC变为CHW\n \"\"\"\n if len(img.shape) == 2:\n img = np.expand_dims(img, axis=2)\n return img.transpose((2, 0, 1))\n \n def __getitem__(self, idx):\n \"\"\"\n 返回 缩小3倍后的图片 和 原始图片\n \"\"\"\n \n # 加载原始图像\n img = self._load_img(self.temp_images[idx])\n # 将原始图像缩放到(3, 300, 300)\n img = img.resize([self.crop_size,self.crop_size], Image.BICUBIC)\n\n #转换为YCbCr图像\n ycbcr = img.convert(\"YCbCr\")\n\n # 因为人眼对亮度敏感,所以只取Y通道\n y, cb, cr = ycbcr.split()\n y = np.asarray(y,dtype='float32')\n y = y / 255.0\n\n # 缩放后的图像和前面采取一样的操作\n img_ = img.resize([self.input_size,self.input_size], Image.BICUBIC)\n ycbcr_ = img_.convert(\"YCbCr\")\n y_, cb_, cr_ = ycbcr_.split()\n y_ = np.asarray(y_,dtype='float32')\n y_ = y_ / 255.0\n\n # 升纬并将HWC转换为CHW\n y = self.transforms(y)\n x = self.transforms(y_)\n\n # x为缩小3倍后的图片(1, 100, 100) y是原始图片(1, 300, 300)\n return x, y\n\n\n def __len__(self):\n \"\"\"\n 实现__len__方法,返回数据集总数目\n \"\"\"\n return len(self.temp_images)\n \n def _sort_images(self, img_dir):\n \"\"\"\n 对文件夹内的图像进行按照文件名排序\n \"\"\"\n files = []\n\n for item in os.listdir(img_dir):\n if item.split('.')[-1].lower() in [\"jpg\",'jpeg','png']:\n files.append(os.path.join(img_dir, item))\n\n return sorted(files)\n \n def _parse_dataset(self):\n \"\"\"\n 处理数据集\n \"\"\"\n self.temp_images = self._sort_images(self.image_path)\n random.Random(self.seed).shuffle(self.temp_images)\n \n def _load_img(self, path):\n \"\"\"\n 从磁盘读取图片\n \"\"\"\n with open(path, 'rb') as f:\n img = Image.open(io.BytesIO(f.read()))\n img = img.convert('RGB')\n return img",
"_____no_output_____"
]
],
[
[
"### 3.4 PetDataSet数据集抽样展示\n实现好BSD_data数据集后,我们来测试一下数据集是否符合预期,因为BSD_data是一个可以被迭代的Class,我们通过for循环从里面读取数据进行展示。",
"_____no_output_____"
]
],
[
[
"# 测试定义的数据集\ntrain_dataset = BSD_data(mode='train')\nval_dataset = BSD_data(mode='val')\n\nprint('=============train dataset=============')\nx, y = train_dataset[0]\nx = x[0]\ny = y[0]\nx = x * 255\ny = y * 255\nimg_ = Image.fromarray(np.uint8(x), mode=\"L\")\nimg = Image.fromarray(np.uint8(y), mode=\"L\")\ndisplay(img_)\ndisplay(img_.size)\ndisplay(img)\ndisplay(img.size)",
"=============train dataset=============\n"
]
],
[
[
"## 四、模型组网\nSub_Pixel_CNN是一个全卷积网络,网络结构比较简单,这里采用Layer类继承方式组网。",
"_____no_output_____"
]
],
[
[
"class Sub_Pixel_CNN(paddle.nn.Layer):\n\n def __init__(self, upscale_factor=3, channels=1):\n super(Sub_Pixel_CNN, self).__init__()\n \n self.conv1 = paddle.nn.Conv2D(channels,64,5,stride=1, padding=2)\n self.conv2 = paddle.nn.Conv2D(64,64,3,stride=1, padding=1)\n self.conv3 = paddle.nn.Conv2D(64,32,3,stride=1, padding=1)\n self.conv4 = paddle.nn.Conv2D(32,channels * (upscale_factor ** 2),3,stride=1, padding=1)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.conv2(x)\n x = self.conv3(x)\n x = self.conv4(x)\n x = paddle.nn.functional.pixel_shuffle(x,3)\n return x",
"_____no_output_____"
]
],
[
[
"### 4.1 模型封装",
"_____no_output_____"
]
],
[
[
"# 模型封装\nmodel = paddle.Model(Sub_Pixel_CNN())",
"W0422 19:56:08.608785 191 gpu_context.cc:244] Please NOTE: device: 0, GPU Compute Capability: 7.0, Driver API Version: 10.1, Runtime API Version: 10.1\nW0422 19:56:08.614269 191 gpu_context.cc:272] device: 0, cuDNN Version: 7.6.\n"
]
],
[
[
"### 4.2 模型可视化\n调用飞桨提供的summary接口对组建好的模型进行可视化,方便进行模型结构和参数信息的查看和确认。",
"_____no_output_____"
]
],
[
[
"model.summary((1,1, 100, 100))",
"---------------------------------------------------------------------------\n Layer (type) Input Shape Output Shape Param # \n===========================================================================\n Conv2D-1 [[1, 1, 100, 100]] [1, 64, 100, 100] 1,664 \n Conv2D-2 [[1, 64, 100, 100]] [1, 64, 100, 100] 36,928 \n Conv2D-3 [[1, 64, 100, 100]] [1, 32, 100, 100] 18,464 \n Conv2D-4 [[1, 32, 100, 100]] [1, 9, 100, 100] 2,601 \n===========================================================================\nTotal params: 59,657\nTrainable params: 59,657\nNon-trainable params: 0\n---------------------------------------------------------------------------\nInput size (MB): 0.04\nForward/backward pass size (MB): 12.89\nParams size (MB): 0.23\nEstimated Total Size (MB): 13.16\n---------------------------------------------------------------------------\n\n"
]
],
[
[
"## 五、模型训练",
"_____no_output_____"
],
[
"### 5.1 启动模型训练\n\n使用模型代码进行Model实例生成,使用prepare接口定义优化器、损失函数和评价指标等信息,用于后续训练使用。在所有初步配置完成后,调用fit接口开启训练执行过程,调用fit时只需要将前面定义好的训练数据集、测试数据集、训练轮次(Epoch)和批次大小(batch_size)配置好即可。",
"_____no_output_____"
]
],
[
[
"model.prepare(paddle.optimizer.Adam(learning_rate=0.001,parameters=model.parameters()),\n paddle.nn.MSELoss()\n )\n\n# 启动模型训练,指定训练数据集,设置训练轮次,设置每次数据集计算的批次大小,设置日志格式\nmodel.fit(train_dataset,\n epochs=20,\n batch_size=16,\n verbose=1)",
"The loss value printed in the log is the current step, and the metric is the average value of previous steps.\nEpoch 1/20\n"
]
],
[
[
"## 六、模型预测",
"_____no_output_____"
],
[
"### 6.1 预测\n我们可以直接使用model.predict接口来对数据集进行预测操作,只需要将预测数据集传递到接口内即可。",
"_____no_output_____"
]
],
[
[
"predict_results = model.predict(val_dataset)",
"Predict begin...\nstep 100/100 [==============================] - 8ms/step \nPredict samples: 100\n"
]
],
[
[
"### 6.2 定义预测结果可视化函数",
"_____no_output_____"
]
],
[
[
"import math\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes\nfrom mpl_toolkits.axes_grid1.inset_locator import mark_inset\n\ndef psnr(img1, img2):\n \"\"\"\n PSMR计算函数\n \"\"\"\n mse = np.mean( (img1/255. - img2/255.) ** 2 )\n if mse < 1.0e-10:\n return 100\n PIXEL_MAX = 1\n return 20 * math.log10(PIXEL_MAX / math.sqrt(mse))\n\ndef plot_results(img, title='results', prefix='out'):\n \"\"\"\n 画图展示函数\n \"\"\"\n img_array = np.asarray(img, dtype='float32')\n img_array = img_array.astype(\"float32\") / 255.0\n\n fig, ax = plt.subplots()\n im = ax.imshow(img_array[::-1], origin=\"lower\")\n\n plt.title(title)\n axins = zoomed_inset_axes(ax, 2, loc=2)\n axins.imshow(img_array[::-1], origin=\"lower\")\n\n x1, x2, y1, y2 = 200, 300, 100, 200\n axins.set_xlim(x1, x2)\n axins.set_ylim(y1, y2)\n\n plt.yticks(visible=False)\n plt.xticks(visible=False)\n\n mark_inset(ax, axins, loc1=1, loc2=3, fc=\"none\", ec=\"blue\")\n plt.savefig(str(prefix) + \"-\" + title + \".png\")\n plt.show()\n \ndef get_lowres_image(img, upscale_factor):\n \"\"\"\n 缩放图片\n \"\"\"\n return img.resize(\n (img.size[0] // upscale_factor, img.size[1] // upscale_factor),\n Image.BICUBIC,\n )\n\ndef upscale_image(model, img):\n '''\n 输入小图,返回上采样三倍的大图像\n '''\n # 把图片复转换到YCbCr格式\n ycbcr = img.convert(\"YCbCr\")\n y, cb, cr = ycbcr.split()\n y = np.asarray(y, dtype='float32')\n y = y / 255.0\n img = np.expand_dims(y, axis=0) # 升维度到(1,w,h)一张image\n img = np.expand_dims(img, axis=0) # 升维度到(1,1,w,h)一个batch\n img = np.expand_dims(img, axis=0) # 升维度到(1,1,1,w,h)可迭代的batch\n \n out = model.predict(img) # predict输入要求为可迭代的batch\n\n out_img_y = out[0][0][0] # 得到predict输出结果\n out_img_y *= 255.0\n\n # 把图片复转换回RGB格式\n out_img_y = out_img_y.reshape((np.shape(out_img_y)[1], np.shape(out_img_y)[2]))\n out_img_y = Image.fromarray(np.uint8(out_img_y), mode=\"L\")\n out_img_cb = cb.resize(out_img_y.size, Image.BICUBIC)\n out_img_cr = cr.resize(out_img_y.size, Image.BICUBIC)\n out_img = Image.merge(\"YCbCr\", (out_img_y, out_img_cb, out_img_cr)).convert(\n \"RGB\"\n )\n return out_img\n\ndef main(model, img, upscale_factor=3):\n # 读取图像\n with open(img, 'rb') as f:\n img = Image.open(io.BytesIO(f.read()))\n # 缩小三倍\n lowres_input = get_lowres_image(img, upscale_factor)\n w = lowres_input.size[0] * upscale_factor\n h = lowres_input.size[1] * upscale_factor\n # 将缩小后的图片再放大三倍\n lowres_img = lowres_input.resize((w, h)) \n # 确保未经缩放的图像和其他两张图片大小一致\n highres_img = img.resize((w, h))\n # 得到缩小后又经过 Efficient Sub-Pixel CNN放大的图片\n prediction = upscale_image(model, lowres_input)\n psmr_low = psnr(np.asarray(lowres_img), np.asarray(highres_img))\n psmr_pre = psnr(np.asarray(prediction), np.asarray(highres_img))\n # 展示三张图片\n plot_results(lowres_img, \"lowres\")\n plot_results(highres_img, \"highres\")\n plot_results(prediction, \"prediction\")\n print(\"psmr_low:\", psmr_low, \"psmr_pre:\", psmr_pre)",
"_____no_output_____"
]
],
[
[
"### 6.3 执行预测\n从我们的预测数据集中抽1个张图片来看看预测的效果,展示一下原图、小图和预测结果。",
"_____no_output_____"
]
],
[
[
"main(model,'BSR/BSDS500/data/images/test/100007.jpg')",
"Predict begin...\nstep 1/1 [==============================] - 4ms/step\nPredict samples: 1\n"
]
],
[
[
"# 7.模型保存\n将模型保存到 checkpoint/model_final ,并保留训练参数",
"_____no_output_____"
]
],
[
[
"model.save('checkpoint/model_final',training=True)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e77c668b13c50a9b2cb27b6c5f0e7ed7144700a1 | 39,889 | ipynb | Jupyter Notebook | notebooks/Case4.ipynb | teuben/study7 | e0c4f369b4b66795e34129b63a53bb2eb45f1792 | [
"MIT"
] | null | null | null | notebooks/Case4.ipynb | teuben/study7 | e0c4f369b4b66795e34129b63a53bb2eb45f1792 | [
"MIT"
] | 2 | 2020-01-18T04:40:28.000Z | 2020-03-10T21:02:47.000Z | notebooks/Case4.ipynb | teuben/study7 | e0c4f369b4b66795e34129b63a53bb2eb45f1792 | [
"MIT"
] | null | null | null | 58.232117 | 11,268 | 0.651809 | [
[
[
"# Science Case #4: NGC3504 \n\nThe galaxy NGC3504 has been observed in two unrelated ALMA projects, both in band 6 at at 230 GHz, cause for an interesting comparison.\n\n1. **2016.1.00650.S** - one 7m and two 12m observations of just NGC3504, to study flow in a bar\n2. **2017.1.00964.S** - a collection of 7 galaxies with the purpose of measure gas flow near the central black hole. For NGC3504 two datasets were collected.\n\nHere we are focusing on the commonalities and differences between these two observations.\n\n",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport matplotlib.pyplot as plt ",
"_____no_output_____"
],
[
"source = \"NGC3504\"",
"_____no_output_____"
]
],
[
[
"### astroquery.alma\n\nFirst we should query the science archive, we can do https://almascience.nrao.edu/aq/ as well, but we want also show this via the notebook. \n",
"_____no_output_____"
]
],
[
[
"from astroquery.alma import Alma\nimport pandas as pd\n# display the whole table in the notebook\npd.set_option('display.max_rows', None)\npd.set_option('display.max_columns', None)\npd.set_option('display.width', None)\npd.set_option('display.max_colwidth',25)\n# more to come here. here we just want to show how much you can do with the current query, before science\nalma = Alma()",
"_____no_output_____"
],
[
"n = Alma.query_object(source)",
"_____no_output_____"
],
[
"print(pd.unique(n['proposal_id']))\nprint(pd.unique(n['obs_id']))",
"[b'2017.1.00964.S' b'2016.1.00650.S']\n[b'uid://A001/X1288/Xba6' b'uid://A001/X1288/Xba8' b'uid://A001/X87a/X70a'\n b'uid://A001/X87a/X708' b'uid://A001/X87a/X706']\n"
]
],
[
[
"Thus we have indeed two projects,and five observations across those two.\n\nLets print how many beams we have across the image",
"_____no_output_____"
]
],
[
[
"ci=['obs_id','s_fov','s_resolution']\nn['nres'] = 3600*n['s_fov']/n['s_resolution']\nprint(n[ci])",
" obs_id s_fov s_resolution \n deg deg \n--------------------- -------------------- --------------------\nuid://A001/X1288/Xba6 0.006863718695429476 0.034121085407438106\nuid://A001/X1288/Xba6 0.006863718695429476 0.034121085407438106\nuid://A001/X1288/Xba6 0.006863718695429476 0.034121085407438106\nuid://A001/X1288/Xba6 0.006863718695429476 0.034121085407438106\nuid://A001/X1288/Xba8 0.00686371854646795 0.20065563262611036\nuid://A001/X1288/Xba8 0.00686371854646795 0.20065563262611036\nuid://A001/X1288/Xba8 0.00686371854646795 0.20065563262611036\nuid://A001/X1288/Xba8 0.00686371854646795 0.20065563262611036\n uid://A001/X87a/X70a 0.017853666133604822 5.503583966319726\n uid://A001/X87a/X70a 0.017853666133604822 5.503583966319726\n uid://A001/X87a/X70a 0.017853666133604822 5.503583966319726\n uid://A001/X87a/X70a 0.017853666133604822 5.503583966319726\n uid://A001/X87a/X708 0.01305128673735267 1.7825652390462614\n uid://A001/X87a/X708 0.01305128673735267 1.7825652390462614\n uid://A001/X87a/X708 0.01305128673735267 1.7825652390462614\n uid://A001/X87a/X708 0.01305128673735267 1.7825652390462614\n uid://A001/X87a/X706 0.013051297132328152 0.565397979165851\n uid://A001/X87a/X706 0.013051297132328152 0.565397979165851\n uid://A001/X87a/X706 0.013051297132328152 0.565397979165851\n uid://A001/X87a/X706 0.013051297132328152 0.565397979165851\n"
]
],
[
[
"Notice there appears to be a units issue with s_resolution: they appear to be in arcsec. There is also a 'spatial_resolution', but it has the same issue.\n\n",
"_____no_output_____"
],
[
"### astroquery.admit",
"_____no_output_____"
]
],
[
[
"from astroquery.admit import ADMIT\nimport pandas as pd\n\npd.set_option('display.max_rows', None)\npd.set_option('display.max_columns', None)\npd.set_option('display.width', None)\npd.set_option('display.max_colwidth',25)\n\n\na = ADMIT()\na.check()",
"Found /home/teuben/ALMA/study7/query/admit.db\nChecking db.... 0\n71 71 71\nDatabase version: 27-feb-2022. core.py version: 26-feb-2022\nheader : 1 entries\nalma : 124 entries\nwin : 123 entries\nlines : 33 entries\nsources : 769 entries\n"
]
],
[
[
"# Continuum\n\nFirst we want to see if any continuum is detected, so we select all windows with one channel.\n\n",
"_____no_output_____"
]
],
[
[
"p = a.query(source_name_alma=source,nchan=1,flux='>0')\nprint(p.shape)",
"select * from alma inner join win on (win.a_id = alma.id) inner join sources on (sources.w_id = win.id) WHERE alma.target_name='NGC3504' AND win.nchan=1 AND sources.flux>=0.0 AND sources.l_id = 0 \n\n(23, 40)\n"
],
[
"a.key_description.show_in_notebook(display_length=20)",
"_____no_output_____"
]
],
[
[
"We collect a few observables: observing time, as well as peak and flux and the resolution\n\nNote we need to clean up the units",
"_____no_output_____"
]
],
[
[
"ci=['obs_id','spw','nsources','t_min', 'flux', 'peak_s','fop','bmaj_arcsec','smaj_arcsec']\np['fop'] = p['flux']/p['peak_s']\np['bmaj_arcsec'] = p['bmaj'] * 3600\np['smaj_arcsec'] = p['smaj'] * 3600\nprint(p[ci])",
" obs_id spw nsources t_min flux \\\n0 uid://A001/X1288/Xba6 spw21 1 58050.543677 0.000860 \n1 uid://A001/X1288/Xba8 spw19 1 58119.297186 0.001110 \n2 uid://A001/X1288/Xba8 spw21 1 58119.297186 0.001240 \n3 uid://A001/X1288/Xba8 spw23 1 58119.297186 0.001790 \n4 uid://A001/X1288/Xba8 spw25 1 58119.297186 0.001450 \n5 uid://A001/X87a/X706 spw23 1 57713.452563 0.001730 \n6 uid://A001/X87a/X706 spw25 1 57713.452563 0.001510 \n7 uid://A001/X87a/X706 spw27 1 57713.452563 0.001560 \n8 uid://A001/X87a/X706 spw29 1 57713.452563 0.001730 \n9 uid://A001/X87a/X708 spw23 3 57830.136178 0.007700 \n10 uid://A001/X87a/X708 spw23 3 57830.136178 0.013800 \n11 uid://A001/X87a/X708 spw23 3 57830.136178 0.024200 \n12 uid://A001/X87a/X708 spw25 2 57830.136178 0.010600 \n13 uid://A001/X87a/X708 spw25 2 57830.136178 0.009770 \n14 uid://A001/X87a/X708 spw27 2 57830.136178 0.008230 \n15 uid://A001/X87a/X708 spw27 2 57830.136178 0.014200 \n16 uid://A001/X87a/X708 spw29 1 57830.136178 0.008840 \n17 uid://A001/X87a/X70a spw16 1 57704.450990 0.015200 \n18 uid://A001/X87a/X70a spw18 1 57704.450990 0.015000 \n19 uid://A001/X87a/X70a spw20 1 57704.450990 0.018400 \n20 uid://A001/X87a/X70a spw22 1 57704.450990 0.016900 \n21 uid://A001/X1288/Xba6 spw19_21_23_25 1 58050.543677 0.000618 \n22 uid://A001/X1288/Xba8 spw19_21_23_25 1 58119.297186 0.001290 \n\n peak_s fop bmaj_arcsec smaj_arcsec \n0 0.000151 5.695364 0.049721 0.0 \n1 0.000512 2.167969 0.218953 0.0 \n2 0.000580 2.137931 0.208199 0.0 \n3 0.000594 3.013468 0.206176 0.0 \n4 0.000706 2.053824 0.219428 0.0 \n5 0.001090 1.587156 0.617609 0.0 \n6 0.000968 1.559917 0.660397 0.0 \n7 0.001020 1.529412 0.655523 0.0 \n8 0.001260 1.373016 0.623399 0.0 \n9 0.002080 3.701923 1.810933 3.6 \n10 0.002040 6.764706 1.810933 7.2 \n11 0.001940 12.474227 1.810933 7.2 \n12 0.002120 5.000000 1.919427 7.2 \n13 0.001710 5.713450 1.919427 3.6 \n14 0.002290 3.593886 2.262012 3.6 \n15 0.002310 6.147186 2.262012 7.2 \n16 0.002280 3.877193 1.812930 3.6 \n17 0.009540 1.593291 6.312150 7.2 \n18 0.009410 1.594049 6.296568 7.2 \n19 0.010600 1.735849 5.772073 7.2 \n20 0.009970 1.695085 5.714493 7.2 \n21 0.000160 3.862500 0.041953 0.0 \n22 0.000570 2.263158 0.212872 0.0 \n"
]
],
[
[
"It's a little surprising that flux/peak is 1.5 for the lowest and highest resolution array data, but there clearly is something very odd about the middle resolution (X708) data.",
"_____no_output_____"
]
],
[
[
"plt.scatter(p['t_min'],p['flux']);\nplt.title(source + \" continuum lightcurve\")\nplt.xlabel('MJD')\nplt.ylabel('Flux (Jy)');",
"_____no_output_____"
]
],
[
[
"well, the fluxes are somewhat all over the place..... averaging 10-15 mJy.\n\nThe other dataset of NGC3504 at mjd > 58000 seems to have lost a lot of flux.\n\nHere is a figure of the continuum source, as seen in the three different ALMA confirmation. Figures have been taking from ADMIT, including where sources were detected. ADMIT was using CASA's ia.findsources()\n\n",
"_____no_output_____"
],
[
"# Spectral Lines",
"_____no_output_____"
]
],
[
[
"p = a.query(source_name_alma=source,nchan='>1',mom0flux='>0')",
"select * from alma inner join win on (win.a_id = alma.id) inner join lines on (lines.w_id = win.id ) WHERE alma.target_name='NGC3504' AND win.nchan>=1.0 AND lines.mom0flux>=0.0 \n\n"
],
[
"p = a.query(nchan='>1',mom0flux='>0')",
"select * from alma inner join win on (win.a_id = alma.id) inner join lines on (lines.w_id = win.id ) WHERE win.nchan>=1.0 AND lines.mom0flux>=0.0 \n\n"
],
[
"print(p.shape)\nprint(p.columns)\n\n",
"(33, 39)\nIndex(['id', 'obs_id', 'target_name', 's_ra', 's_dec', 'frequency', 't_min',\n 'cont_sensitivity_bandwidth', 'sensitivity_10kms', 'project_abstract',\n 'obs_title', 'science_keyword', 'scientific_category',\n 'proposal_authors', 'id', 'a_id', 'spw', 'freqc', 'freqw', 'vlsr',\n 'nlines', 'nsources', 'nchan', 'peak_w', 'rms_w', 'bmaj', 'bmin', 'bpa',\n 'fcoverage', 'id', 'w_id', 'formula', 'transition', 'restfreq', 'vmin',\n 'vmax', 'mom0flux', 'mom1peak', 'mom2peak'],\n dtype='object')\n"
],
[
"ci=['obs_id','spw','restfreq','formula','mom0flux','mom1peak','mom2peak']\nci=['spw','restfreq','formula','mom0flux','mom1peak','vlsr','mom2peak','nlines']\nprint(p[ci])",
" spw restfreq formula mom0flux mom1peak vlsr mom2peak \\\n0 spw21 243.48293 H2COH+ 1863.8500 1457.430 1447.989431 31.01830 \n1 spw23 244.59816 HCOOH 4235.2400 1427.340 1447.989431 31.75560 \n2 spw23 244.59816 HCOOH 313.3270 1420.510 1447.989431 38.15480 \n3 spw23 244.63395 CH3CH2OH 309.1810 1448.800 1447.989431 33.36400 \n4 spw25 230.53800 CO 2698.2200 1475.480 1447.989431 20.86430 \n5 spw23 244.93556 CS 3429.8800 1831.720 1521.106704 33.66740 \n6 spw25 230.53800 CO 3388.7800 1516.190 1521.106704 34.98030 \n7 spw23 244.93556 CS 1090.5600 1549.750 1521.106704 80.49340 \n8 spw25 230.53800 CO 18313.7000 1547.690 1521.106704 58.09510 \n9 spw16 230.53800 CO 11534.2000 639.522 628.000000 70.28280 \n10 spw21 242.49769 CH3COOH 477.7500 241.190 232.006873 37.10220 \n11 spw21 242.50962 CH3COOH 0.0000 0.000 232.006873 0.00000 \n12 spw21 242.90447 CH3CH2CN 4678.6600 755.657 715.580697 32.75740 \n13 spw23 244.93556 CS 1365.7300 969.082 715.580697 47.37710 \n14 spw21 242.90447 CH3CH2CN 1217.1900 751.218 715.580697 29.58540 \n15 spw23 244.93556 CS 405.3630 989.835 715.580697 49.21610 \n16 spw25 230.53800 CO 9306.8000 710.181 715.580697 62.40980 \n17 spw21 242.61847 CH2DCCH 1438.9200 393.771 401.856222 32.58840 \n18 spw21 242.63925 H2NCH2CN 1496.2700 408.513 401.856222 34.56510 \n19 spw25 230.53800 CO 436.5640 387.738 401.856222 10.90870 \n20 spw25 230.53800 CO 894.7710 397.203 401.856222 15.01770 \n21 spw19 228.60363 CH2CHCHO 500.2180 1008.250 978.913173 52.92020 \n22 spw21 243.08765 SO2 833.0270 974.240 978.913173 33.24510 \n23 spw23 244.22213 HCCCH 646.3020 980.356 978.913173 30.18990 \n24 spw21 243.12925 CH2OHCHO 370.0540 991.099 978.913173 31.06460 \n25 spw23 244.23979 CH3CH2CN 264.3150 949.060 978.913173 36.27090 \n26 spw25 230.53800 CO 323.7160 980.293 978.913173 6.99879 \n27 spw25 230.53800 CO 24782.4000 1548.350 1521.106704 60.99150 \n28 spw29 244.93556 CS 140.5190 1483.460 1521.106704 15.87380 \n29 spw25 230.53800 CO 32461.2000 1539.720 1521.106704 59.09890 \n30 spw29 244.93556 CS 107.7540 1538.800 1521.106704 31.05040 \n31 spw16 230.53800 CO 26393.2000 1537.470 1521.106704 40.22490 \n32 spw20 244.93556 CS 91.1055 1544.310 1521.106704 24.96880 \n\n nlines \n0 1 \n1 1 \n2 2 \n3 2 \n4 1 \n5 1 \n6 1 \n7 1 \n8 1 \n9 1 \n10 2 \n11 2 \n12 1 \n13 1 \n14 1 \n15 1 \n16 1 \n17 2 \n18 2 \n19 1 \n20 1 \n21 1 \n22 1 \n23 1 \n24 1 \n25 1 \n26 1 \n27 1 \n28 1 \n29 1 \n30 1 \n31 1 \n32 1 \n"
]
],
[
[
"To note here in the current set of tables the mom0flux values are probed at the location where in the CubeSum a source was detected. There is no mom0flux value generated for the CubeSum, this might have been useful here to compare to.\n\n\n\nOne caveat: the CO line appears to be missing (Xba6,8), whereas the CS line is there.... which turned out to be because the CO cubes crashed in ADMIT (some I/O error). ",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
e77c716a0bf0b893d49ed9c34bb6b7ddc5f9bb78 | 2,101 | ipynb | Jupyter Notebook | Supervised-Learning/Perceptron.ipynb | immu0001/Udacity-Data-Scientist-Nanodegree-TERM-1 | acb3d7248bbde8905bb38f87c0787e3430162572 | [
"MIT"
] | null | null | null | Supervised-Learning/Perceptron.ipynb | immu0001/Udacity-Data-Scientist-Nanodegree-TERM-1 | acb3d7248bbde8905bb38f87c0787e3430162572 | [
"MIT"
] | null | null | null | Supervised-Learning/Perceptron.ipynb | immu0001/Udacity-Data-Scientist-Nanodegree-TERM-1 | acb3d7248bbde8905bb38f87c0787e3430162572 | [
"MIT"
] | 1 | 2020-07-04T10:34:10.000Z | 2020-07-04T10:34:10.000Z | 23.344444 | 87 | 0.507377 | [
[
[
"import numpy as np\n# Setting the random seed, feel free to change it and see different solutions.\nnp.random.seed(42)",
"_____no_output_____"
],
[
"def stepFunction(t):\n if t >= 0:\n return 1\n return 0",
"_____no_output_____"
],
[
"def prediction(X, W, b):\n return stepFunction((np.matmul(X,W)+b)[0])",
"_____no_output_____"
],
[
"def perceptronStep(X, y, W, b, learn_rate = 0.01):\n # Fill in code\n return W, b",
"_____no_output_____"
],
[
"def trainPerceptronAlgorithm(X, y, learn_rate = 0.01, num_epochs = 25):\n x_min, x_max = min(X.T[0]), max(X.T[0])\n y_min, y_max = min(X.T[1]), max(X.T[1])\n W = np.array(np.random.rand(2,1))\n b = np.random.rand(1)[0] + x_max\n # These are the solution lines that get plotted below.\n boundary_lines = []\n for i in range(num_epochs):\n # In each epoch, we apply the perceptron step.\n W, b = perceptronStep(X, y, W, b, learn_rate)\n boundary_lines.append((-W[0]/W[1], -b/W[1]))\n return boundary_lines",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code"
]
] |
e77c746920fc482e93a7c66aeb70019519d9eb0e | 46,056 | ipynb | Jupyter Notebook | attention/Attention_Basics_Solution.ipynb | Muhanad23/udacity-deep-learning-nanodegree | b543be63eefca6dd599b75a128efb56bcae7efb7 | [
"MIT"
] | null | null | null | attention/Attention_Basics_Solution.ipynb | Muhanad23/udacity-deep-learning-nanodegree | b543be63eefca6dd599b75a128efb56bcae7efb7 | [
"MIT"
] | 7 | 2019-12-16T21:54:38.000Z | 2022-02-10T00:10:37.000Z | attention/Attention_Basics_Solution.ipynb | Joonsoo/udacity-deep-learning-2019 | 0eb1f130e1ebeb62bd035d4f657d8b772e4631c3 | [
"MIT"
] | null | null | null | 105.633028 | 11,300 | 0.867487 | [
[
[
"# [SOLUTION] Attention Basics\nIn this notebook, we look at how attention is implemented. We will focus on implementing attention in isolation from a larger model. That's because when implementing attention in a real-world model, a lot of the focus goes into piping the data and juggling the various vectors rather than the concepts of attention themselves.\n\nWe will implement attention scoring as well as calculating an attention context vector.\n\n## Attention Scoring\n### Inputs to the scoring function\nLet's start by looking at the inputs we'll give to the scoring function. We will assume we're in the first step in the decoding phase. The first input to the scoring function is the hidden state of decoder (assuming a toy RNN with three hidden nodes -- not usable in real life, but easier to illustrate):",
"_____no_output_____"
]
],
[
[
"dec_hidden_state = [5,1,20]",
"_____no_output_____"
]
],
[
[
"Let's visualize this vector:",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Let's visualize our decoder hidden state\nplt.figure(figsize=(1.5, 4.5))\nsns.heatmap(np.transpose(np.matrix(dec_hidden_state)), annot=True, cmap=sns.light_palette(\"purple\", as_cmap=True), linewidths=1)",
"_____no_output_____"
]
],
[
[
"Our first scoring function will score a single annotation (encoder hidden state), which looks like this:",
"_____no_output_____"
]
],
[
[
"annotation = [3,12,45] #e.g. Encoder hidden state",
"_____no_output_____"
],
[
"# Let's visualize the single annotation\nplt.figure(figsize=(1.5, 4.5))\nsns.heatmap(np.transpose(np.matrix(annotation)), annot=True, cmap=sns.light_palette(\"orange\", as_cmap=True), linewidths=1)",
"_____no_output_____"
]
],
[
[
"### IMPLEMENT: Scoring a Single Annotation\nLet's calculate the dot product of a single annotation. NumPy's [dot()](https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html) is a good candidate for this operation",
"_____no_output_____"
]
],
[
[
"def single_dot_attention_score(dec_hidden_state, enc_hidden_state):\n # TODO: return the dot product of the two vectors\n return np.dot(dec_hidden_state, enc_hidden_state)\n \nsingle_dot_attention_score(dec_hidden_state, annotation)",
"_____no_output_____"
]
],
[
[
"\n### Annotations Matrix\nLet's now look at scoring all the annotations at once. To do that, here's our annotation matrix:",
"_____no_output_____"
]
],
[
[
"annotations = np.transpose([[3,12,45], [59,2,5], [1,43,5], [4,3,45.3]])",
"_____no_output_____"
]
],
[
[
"And it can be visualized like this (each column is a hidden state of an encoder time step):",
"_____no_output_____"
]
],
[
[
"# Let's visualize our annotation (each column is an annotation)\nax = sns.heatmap(annotations, annot=True, cmap=sns.light_palette(\"orange\", as_cmap=True), linewidths=1)",
"_____no_output_____"
]
],
[
[
"### IMPLEMENT: Scoring All Annotations at Once\nLet's calculate the scores of all the annotations in one step using matrix multiplication. Let's continue to us the dot scoring method\n\n<img src=\"images/scoring_functions.png\" />\n\nTo do that, we'll have to transpose `dec_hidden_state` and [matrix multiply](https://docs.scipy.org/doc/numpy/reference/generated/numpy.matmul.html) it with `annotations`.",
"_____no_output_____"
]
],
[
[
"def dot_attention_score(dec_hidden_state, annotations):\n # TODO: return the product of dec_hidden_state transpose and enc_hidden_states\n return np.matmul(np.transpose(dec_hidden_state), annotations)\n \nattention_weights_raw = dot_attention_score(dec_hidden_state, annotations)\nattention_weights_raw",
"_____no_output_____"
]
],
[
[
"Looking at these scores, can you guess which of the four vectors will get the most attention from the decoder at this time step?\n\n## Softmax\nNow that we have our scores, let's apply softmax:\n<img src=\"images/softmax.png\" />",
"_____no_output_____"
]
],
[
[
"def softmax(x):\n x = np.array(x, dtype=np.float128)\n e_x = np.exp(x)\n return e_x / e_x.sum(axis=0) \n\nattention_weights = softmax(attention_weights_raw)\nattention_weights",
"_____no_output_____"
]
],
[
[
"Even when knowing which annotation will get the most focus, it's interesting to see how drastic softmax makes the end score become. The first and last annotation had the respective scores of 927 and 929. But after softmax, the attention they'll get is 0.119 and 0.880 respectively.\n\n# Applying the scores back on the annotations\nNow that we have our scores, let's multiply each annotation by its score to proceed closer to the attention context vector. This is the multiplication part of this formula (we'll tackle the summation part in the latter cells)\n\n<img src=\"images/Context_vector.png\" />",
"_____no_output_____"
]
],
[
[
"def apply_attention_scores(attention_weights, annotations):\n # TODO: Multiple the annotations by their weights\n return attention_weights * annotations\n\napplied_attention = apply_attention_scores(attention_weights, annotations)\napplied_attention",
"_____no_output_____"
]
],
[
[
"Let's visualize how the context vector looks now that we've applied the attention scores back on it:",
"_____no_output_____"
]
],
[
[
"# Let's visualize our annotations after applying attention to them\nax = sns.heatmap(applied_attention, annot=True, cmap=sns.light_palette(\"orange\", as_cmap=True), linewidths=1)",
"_____no_output_____"
]
],
[
[
"Contrast this with the raw annotations visualized earlier in the notebook, and we can see that the second and third annotations (columns) have been nearly wiped out. The first annotation maintains some of its value, and the fourth annotation is the most pronounced.\n\n# Calculating the Attention Context Vector\nAll that remains to produce our attention context vector now is to sum up the four columns to produce a single attention context vector\n",
"_____no_output_____"
]
],
[
[
"def calculate_attention_vector(applied_attention):\n return np.sum(applied_attention, axis=1)\n\nattention_vector = calculate_attention_vector(applied_attention)\nattention_vector",
"_____no_output_____"
],
[
"# Let's visualize the attention context vector\nplt.figure(figsize=(1.5, 4.5))\nsns.heatmap(np.transpose(np.matrix(attention_vector)), annot=True, cmap=sns.light_palette(\"Blue\", as_cmap=True), linewidths=1)",
"_____no_output_____"
]
],
[
[
"Now that we have the context vector, we can concatenate it with the hidden state and pass it through a hidden layer to produce the the result of this decoding time step.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
e77c76f99a4017de463ba8831e2c7027c446e849 | 44,565 | ipynb | Jupyter Notebook | assignments/demo/assignment09_time_series.ipynb | geomars/oldschool | 55ca1cb713baea429c509bd03598257f71481cf3 | [
"MIT"
] | null | null | null | assignments/demo/assignment09_time_series.ipynb | geomars/oldschool | 55ca1cb713baea429c509bd03598257f71481cf3 | [
"MIT"
] | 1 | 2018-11-09T12:43:21.000Z | 2018-11-09T12:43:21.000Z | assignments/demo/assignment09_time_series.ipynb | geomars/oldschool | 55ca1cb713baea429c509bd03598257f71481cf3 | [
"MIT"
] | 1 | 2018-11-09T05:50:07.000Z | 2018-11-09T05:50:07.000Z | 36.769802 | 8,947 | 0.443016 | [
[
[
"<center>\n<img src=\"../../img/ods_stickers.jpg\">\n## Open Machine Learning Course\n<center>Author: Mariya Mansurova, Analyst & developer in Yandex.Metrics team. <br>Translated by Ivan Zakharov, ML enthusiast.\n<br>All content is distributed under the [Creative Commons CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/) license.",
"_____no_output_____"
],
[
"# <center> Assignment #9 (demo)\n## <center> Time series analysis\n \n**Fill cells marked with \"Your code here\" and submit your answers to the questions through the [web form](https://goo.gl/forms/Hu0thpYw2rXLfEjI2).**",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport os\n\nfrom plotly import __version__\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\nfrom plotly import graph_objs as go\nimport requests\nimport pandas as pd\n\nprint(__version__) # need 1.9.0 or greater\n\ninit_notebook_mode(connected = True)\n\ndef plotly_df(df, title = ''):\n data = []\n \n for column in df.columns:\n trace = go.Scatter(\n x = df.index,\n y = df[column],\n mode = 'lines',\n name = column\n )\n data.append(trace)\n \n layout = dict(title = title)\n fig = dict(data = data, layout = layout)\n iplot(fig, show_link=False)",
"2.7.0\n"
]
],
[
[
"## Data preparation\n\nFirst, read the data in as a `dataframe`. Today we will predict the number of views of the [Machine Learning](https://en.wikipedia.org/wiki/Machine_learning) wiki page. I downloaded the data using the [Wikipediatrend](https://www.r-bloggers.com/using-wikipediatrend/) library for `R`.",
"_____no_output_____"
]
],
[
[
"df = pd.read_csv('../../data/wiki_machine_learning.csv', sep = ' ')\ndf = df[df['count'] != 0]\ndf.head()",
"_____no_output_____"
],
[
"df.shape",
"_____no_output_____"
],
[
"df.date = pd.to_datetime(df.date)",
"_____no_output_____"
],
[
"plotly_df(df.set_index('date')[['count']])",
"_____no_output_____"
]
],
[
[
"## Predicting with Facebook Prophet\n\nWe will build a prediction using the simple library `Facebook Prophet`. In order to evaluate the quality of the model, we drop the last 30 days from the training sample.",
"_____no_output_____"
]
],
[
[
"from fbprophet import Prophet",
"_____no_output_____"
],
[
"predictions = 30\n\ndf = df[['date', 'count']]\ndf.columns = ['ds', 'y']\ntrain_df = df[:-predictions].copy()",
"_____no_output_____"
],
[
"# Your code here",
"_____no_output_____"
]
],
[
[
"** Question 1: ** What is the prediction of the number of views of the wiki page on January 20? Round to the nearest integer.\n\n- 4947\n- 3833\n- 5229\n- 2744",
"_____no_output_____"
],
[
"Estimate the quality of the prediction with the last 30 points.",
"_____no_output_____"
]
],
[
[
"# Your code here",
"_____no_output_____"
]
],
[
[
"** Question 2 **: What is MAPE equal to?\n\n- 38.38\n- 42.42\n- 5.39\n- 65.91",
"_____no_output_____"
],
[
"** Question 3 **: What is MAE equal to?\n\n- 355\n- 4007\n- 713\n- 903",
"_____no_output_____"
],
[
"## Predicting with ARIMA",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom scipy import stats\nimport statsmodels.api as sm",
"_____no_output_____"
]
],
[
[
"** Question 4: ** Let's verify the stationarity of the series using the Dickey-Fuller test. Is the series stationary? What is the p-value?\n\n- Series is stationary, p_value = 0.107\n- Series is not stationary, p_value = 0.107\n- Series is stationary, p_value = 0.001\n- Series is not stationary, p_value = 0.001",
"_____no_output_____"
]
],
[
[
"# Your code here",
"_____no_output_____"
]
],
[
[
"** Question 5 **: Next, we turn to the construction of the SARIMAX model (`sm.tsa.statespace.SARIMAX`). What is the best set of parameters (among listed) for the SARIMAX model according to the `AIC` criterion?\n\n- D = 1, d = 0, Q = 0, q = 2, P = 3, p = 1\n- D = 2, d = 1, Q = 1, q = 2, P = 3, p = 1\n- D = 1, d = 1, Q = 1, q = 2, P = 3, p = 1\n- D = 0, d = 0, Q = 0, q = 2, P = 3, p = 1",
"_____no_output_____"
]
],
[
[
"# Your code here",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e77c7778c2ac475b3ec95d4a99139f44f4ca3e51 | 190,897 | ipynb | Jupyter Notebook | DataScience/Olist/EnfaseLabs.ipynb | brunereduardo/DataPortfolio | 078bde3862bccd43de38b3a5456b2e1b18fe0fbd | [
"MIT"
] | null | null | null | DataScience/Olist/EnfaseLabs.ipynb | brunereduardo/DataPortfolio | 078bde3862bccd43de38b3a5456b2e1b18fe0fbd | [
"MIT"
] | null | null | null | DataScience/Olist/EnfaseLabs.ipynb | brunereduardo/DataPortfolio | 078bde3862bccd43de38b3a5456b2e1b18fe0fbd | [
"MIT"
] | null | null | null | 78.493832 | 23,060 | 0.714794 | [
[
[
"# Bruner Eduardo Augusto Albrecht",
"_____no_output_____"
],
[
"## Case - Data Engineering\n\nApós a compra de um produto através do Olist, o vendedor recebe uma notificação para começar a processar o pedido e o cliente recebe uma estimativa de data de entrega. Possivelmente, nem todas as decisões da empresa foram acertadas no quesito de carteira de produtos e profitabilidade.\n\nApresente uma análise das vendas da empresa, baseando-se nos dados presentes no dataset, e a partir dela encontre soluções para melhorar os resultados da empresa. Tais sugestões podem ser na linha de **logística, marketing, vendas, produtos, entre outros**.",
"_____no_output_____"
],
[
"### Configurando o notebook e carregando os Dados",
"_____no_output_____"
]
],
[
[
"#Carregando as bibliotecas\nimport pandas as pd\nimport matplotlib.pyplot as plt\nprint(\"Setup Complete\")",
"Setup Complete\n"
],
[
"#carreagando os datasets para os dataframes \n\n#Informação geográfica sobre os vendedores\nsellers = pd.read_csv('sellers_dataset.csv',index_col = 'seller_id', parse_dates=True)\n\n#Informação geográfica sobre os clientes\ncustomers = pd.read_csv('customers_dataset.csv',index_col = 'customer_unique_id', parse_dates=True)\n\n#Pedidos de compra\norders = pd.read_csv('orders_dataset.csv',index_col = 'order_id', parse_dates=True) \n\n#Inclui os itens adquiridos em cada pedido de compra\nitems = pd.read_csv('order_items_dataset.csv', index_col = 'order_id', parse_dates=True)\n\n#Métodos de pagamentos, valores e parcelas\npayments = pd.read_csv('order_payments_dataset.csv', index_col = 'order_id', parse_dates=True)",
"_____no_output_____"
],
[
"#Verificando por possíveis valores nulos em vendedores\nprint(sellers.info())\nsellers.head()",
"<class 'pandas.core.frame.DataFrame'>\nIndex: 3095 entries, 3442f8959a84dea7ee197c632cb2df15 to 9e25199f6ef7e7c347120ff175652c3b\nData columns (total 3 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 seller_zip_code_prefix 3095 non-null int64 \n 1 seller_city 3095 non-null object\n 2 seller_state 3095 non-null object\ndtypes: int64(1), object(2)\nmemory usage: 96.7+ KB\nNone\n"
],
[
"#Verificando por possíveis valores nulos em compradores\nprint(customers.info())\ncustomers.head()",
"<class 'pandas.core.frame.DataFrame'>\nIndex: 99441 entries, 861eff4711a542e4b93843c6dd7febb0 to 84732c5050c01db9b23e19ba39899398\nData columns (total 4 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 customer_id 99441 non-null object\n 1 customer_zip_code_prefix 99441 non-null int64 \n 2 customer_city 99441 non-null object\n 3 customer_state 99441 non-null object\ndtypes: int64(1), object(3)\nmemory usage: 3.8+ MB\nNone\n"
],
[
"#Verificando por possíveis valores nulos em pagamentos\nprint(payments.info())\npayments.head()",
"<class 'pandas.core.frame.DataFrame'>\nIndex: 103886 entries, b81ef226f3fe1789b1e8b2acac839d17 to 28bbae6599b09d39ca406b747b6632b1\nData columns (total 4 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 payment_sequential 103886 non-null int64 \n 1 payment_type 103886 non-null object \n 2 payment_installments 103886 non-null int64 \n 3 payment_value 103886 non-null float64\ndtypes: float64(1), int64(2), object(1)\nmemory usage: 4.0+ MB\nNone\n"
],
[
"#Verificando por possíveis valores nulos em pedidos\nprint(orders.info())\norders.head()",
"<class 'pandas.core.frame.DataFrame'>\nIndex: 99441 entries, e481f51cbdc54678b7cc49136f2d6af7 to 66dea50a8b16d9b4dee7af250b4be1a5\nData columns (total 7 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 customer_id 99441 non-null object\n 1 order_status 99441 non-null object\n 2 order_purchase_timestamp 99441 non-null object\n 3 order_approved_at 99281 non-null object\n 4 order_delivered_carrier_date 97658 non-null object\n 5 order_delivered_customer_date 96476 non-null object\n 6 order_estimated_delivery_date 99441 non-null object\ndtypes: object(7)\nmemory usage: 6.1+ MB\nNone\n"
],
[
"#Verificando por possíveis valores nulos em items\nprint(items.info())\nitems.head()",
"<class 'pandas.core.frame.DataFrame'>\nIndex: 112650 entries, 00010242fe8c5a6d1ba2dd792cb16214 to fffe41c64501cc87c801fd61db3f6244\nData columns (total 6 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 order_item_id 112650 non-null int64 \n 1 product_id 112650 non-null object \n 2 seller_id 112650 non-null object \n 3 shipping_limit_date 112650 non-null object \n 4 price 112650 non-null float64\n 5 freight_value 112650 non-null float64\ndtypes: float64(2), int64(1), object(3)\nmemory usage: 6.0+ MB\nNone\n"
]
],
[
[
"### Análise para Vendas:",
"_____no_output_____"
],
[
">**Vendas por Estado**",
"_____no_output_____"
]
],
[
[
"orders_by_state = pd.merge(left = customers, right = orders, on='customer_id', right_index=False)\norders_by_state",
"_____no_output_____"
],
[
"result = orders_by_state.groupby(['customer_state'])['customer_id'].count()\nprint(result)\nresult.plot()",
"customer_state\nAC 81\nAL 413\nAM 148\nAP 68\nBA 3380\nCE 1336\nDF 2140\nES 2033\nGO 2020\nMA 747\nMG 11635\nMS 715\nMT 907\nPA 975\nPB 536\nPE 1652\nPI 495\nPR 5045\nRJ 12852\nRN 485\nRO 253\nRR 46\nRS 5466\nSC 3637\nSE 350\nSP 41746\nTO 280\nName: customer_id, dtype: int64\n"
]
],
[
[
">**vendas por dia/semana/mês no marketplace:**\n> * Seria interesente quando montasse o dataframe ter conhecimento sobre cada um dos dados, pois assim poderiamos aplicar o dtype para adeguar os dados à sua melhor forma",
"_____no_output_____"
]
],
[
[
"orders[\"Day\"] = orders[\"order_approved_at\"].apply(lambda x: pd.Timestamp(x).day_name())\n#orders[\"Day\"] = pd.to_datetime(orders[\"order_purchase_timestamp\"]).dt.isocalendar().day #dias da semana em números,1->7\norders[\"Week\"] = pd.to_datetime(orders[\"order_approved_at\"]).dt.isocalendar().week \norders[\"Month\"] = orders[\"order_approved_at\"].apply(lambda x: pd.Timestamp(x).month_name())\n\norders",
"_____no_output_____"
],
[
"orders_by_day = orders.groupby(['Day']).size()\nprint(orders_by_day)\n#necessita colocar título, ylabel, e organizar as labels pro x\norders_by_day.plot.bar()",
"Day\nFriday 14659\nMonday 13001\nSaturday 12196\nSunday 9014\nThursday 15471\nTuesday 19154\nWednesday 15786\ndtype: int64\n"
],
[
"orders_by_month = orders.groupby(['Month']).size()\nprint(orders_by_month)\n#necessita colocar título, ylabel, e organizar as labels pro x\norders_by_month.plot.barh()",
"Month\nApril 9152\nAugust 10968\nDecember 5833\nFebruary 8471\nJanuary 7947\nJuly 10150\nJune 9416\nMarch 9977\nMay 10759\nNovember 7395\nOctober 4910\nSeptember 4303\ndtype: int64\n"
],
[
"orders_by_week = orders.groupby(['Week']).size()\n#print(orders_by_week)\n#necessita colocar título e ylabel \norders_by_week.plot()",
"_____no_output_____"
]
],
[
[
">**Quais são as quantidades de produtos que cada vendedor vende?**",
"_____no_output_____"
]
],
[
[
"products_by_sellers = items.groupby(['seller_id', 'product_id']).size().reset_index()\nproducts_by_sellers.sort_values(0, ascending=False)\nproducts_by_sellers = products_by_sellers.rename(columns={'seller_id':'Seller_id','product_id':'Product_id',0:'Qntd'})\nproducts_by_sellers",
"_____no_output_____"
]
],
[
[
">**Taxa de conversão (%) = (Número de pedidos de uma dado vendendor / número de visitantes no site) x 100**\n> * Levando em conta os números de pedidos já enviados( ou que o pagamentga já foi aceito)/ pelo núemro de customer_unique_id",
"_____no_output_____"
]
],
[
[
"items",
"_____no_output_____"
],
[
"#dar merge para uma nova tabela\nnumber_of_clients= len(customers.index)\norders_by_sellers = items.groupby(['seller_id', 'order_id'])['order_id'].count().reset_index()\norders_by_sellers.sort_values(0, ascending=False)\norders_by_sellers = orders_by_sellers.rename(columns={'seller_id':'Seller_id','order_id':'Order_id',0:'Qntd'})\norders_by_sellers",
"_____no_output_____"
]
],
[
[
">**Qual método de compra se sobresai?** ",
"_____no_output_____"
]
],
[
[
"most_payments_methods =payments.groupby(['payment_type'])['payment_type'].count()\n\nmost_payments_methods.plot.bar()",
"_____no_output_____"
]
],
[
[
"### Análise para Produtos:",
"_____no_output_____"
],
[
"> **Quais produtos são mais comprados (Top 10 produtos mais comprados)**",
"_____no_output_____"
]
],
[
[
"top_items = items.groupby(['product_id']).size().reset_index()\ntop_items = top_items.set_index('product_id')\ntop_items = top_items.rename(columns={0:'Qntd'})\ntop_items = top_items.sort_values('Qntd', ascending=False)\ntop_items.head(10)\n#top_items.head(10).plot.barh()",
"_____no_output_____"
]
],
[
[
"> **Quantas vezes um produto foi parcelado**",
"_____no_output_____"
]
],
[
[
"#juntar tabela items(product_id) com a tabela payments(payment_installments) em order_id\nmost_products_installments = pd.merge(left=items, right= payments, on='order_id')\nproducts_by_installments = most_products_installments.groupby(['product_id','payment_installments'])['payment_installments'].size()\nproducts_by_installments = products_by_installments.sort_values(0, ascending=False)\nproducts_by_installments = pd.DataFrame(data=products_by_installments)\nproducts_by_installments = products_by_installments.rename(columns={\"payment_installments\":'Quantities of Products Installments'})\nproducts_by_installments",
"_____no_output_____"
]
],
[
[
">**ticket médio = Soma do faturamento em vendas (R$)/Nº de vendas concluídas**",
"_____no_output_____"
],
[
"### Análise para Logística:",
"_____no_output_____"
],
[
">Maior valor de frete encontrado por estado",
"_____no_output_____"
]
],
[
[
"aux = pd.merge(left=items, right=orders, on= 'order_id') #customers(ligando pelo customer_id e pegando os valores de estado e cidade)\n# items(order_id e pegando freight_value) #orders(ligando por order_id e pegando o customer_id)\nbiggest_freight_value = pd.merge(left=customers, right=aux, on='customer_id')\nfreight_value_by_state = biggest_freight_value.groupby(['customer_state'])['freight_value'].max()\nfreight_value_by_state = freight_value_by_state.sort_values(0, ascending=False)\nfreight_value_by_state = pd.DataFrame(data=freight_value_by_state)\nfreight_value_by_state = freight_value_by_state.rename(columns={'freight_value':'Biggest Freight Value'})\nfreight_value_by_state.plot.bar()",
"_____no_output_____"
],
[
"freight_value_by_state.boxplot()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
e77c7887679f7d4f11dcd16e2c61ffeeba13be44 | 6,900 | ipynb | Jupyter Notebook | Models/pinyin_formatB/CNN3-FC2-pinyin.ipynb | koalaGreener/Character-level-Convolutional-Network-for-Text-Classification-Applied-to-Chinese-Corpus | 156dca1fc156151e86dc92d12adeb6d63bb64648 | [
"MIT"
] | 40 | 2016-09-09T00:53:35.000Z | 2022-03-21T13:20:22.000Z | Models/pinyin_formatB/CNN3-FC2-pinyin.ipynb | koalaGreener/Character-level-Convolutional-Network-for-Text-Classification-Applied-to-Chinese-Corpus | 156dca1fc156151e86dc92d12adeb6d63bb64648 | [
"MIT"
] | null | null | null | Models/pinyin_formatB/CNN3-FC2-pinyin.ipynb | koalaGreener/Character-level-Convolutional-Network-for-Text-Classification-Applied-to-Chinese-Corpus | 156dca1fc156151e86dc92d12adeb6d63bb64648 | [
"MIT"
] | 9 | 2017-01-11T06:37:26.000Z | 2019-09-10T06:49:42.000Z | 36.702128 | 173 | 0.582174 | [
[
[
"# coding: utf-8\n\nimport pandas as pd\nimport numpy as np\nfrom keras.preprocessing import sequence\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Lambda, Flatten\nfrom keras.layers import Embedding\nfrom keras.layers import Convolution1D, MaxPooling1D\nfrom keras.datasets import imdb\nfrom keras import backend as K\nimport re\nfrom keras.utils import np_utils\nfrom keras.preprocessing import text\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.regularizers import l2\n\n\n# 生成的 word vector 的 dimension\nmaxlen = 1000\nalphabet = 'abcdefghijklmnopqrstuvwxyz0123456789,.!? '\ndatatrain = pd.read_csv(\"new_CSV_Data/Tone2_train.csv\", header=0)\ndatatest = pd.read_csv(\"new_CSV_Data/Tone2_test.csv\", header=0)\n\nchars = set(alphabet)\nprint('total chars:', len(chars))\nchar_indices = dict((c, i) for i, c in enumerate(chars))\nindices_char = dict((i, c) for i, c in enumerate(chars))\n\n# 创建 len(docs)个, 1 * maxlen 的矩阵\nX_train = np.ones((datatrain.shape[0], maxlen), dtype = np.int64) * 0\n\ndocs = []\nlabels = []\n\nprint('zipping the data:')\nepoch = 0\nfor label, content in zip(datatrain.classes, datatrain.content):\n content = re.sub(\"[^a-z0-9\\,\\.\\!\\?]\", \" \", content)\n docs.append(content)\n labels.append(label)\n epoch = epoch + 1\n if (epoch % 20000 == 0):\n print('zipping the training data:', epoch)\nprint('Success!')\n\nprint('There are training set:', datatrain.shape[0])\n\n\nprint('Doing one hot encoding:')\n # One-Hot encoding 另外应该是反过来进行 encode 的,,稀疏部分用0代替\nfor i, doc in enumerate(docs):\n # 倒着数后面的maxlen个数字,但是输出顺序不变\n for t, char in enumerate(doc[-maxlen:]):\n X_train[i, (maxlen-1-t)] = char_indices[char]\nprint('Success!')\n\n\nY_train = np.array(labels)\n\nprint('Convert class vector to binary class matrix (for use with categorical_crossentropy)')\nnb_classes = 5\nprint(nb_classes, 'classes in the dataset')\nY_train = np_utils.to_categorical(Y_train, nb_classes)\nprint('Success!')\n\n\nX_test = np.ones((datatest.shape[0], maxlen), dtype = np.int64) * 0\ndocs = []\nlabels = []\n\nprint('zipping the test data:')\nepoch = 0\nfor label, content in zip(datatest.classes, datatest.content):\n content = re.sub(\"[^a-z0-9\\,\\.\\!\\?]\", \" \", content)\n docs.append(content)\n labels.append(label)\n epoch = epoch + 1\n if (epoch % 20000 == 0):\n print('zipping the test data:', epoch)\nprint('Success!')\n\nprint('There are test set:', datatest.shape[0])\n\nprint('Doing one hot encoding:')\n # One-Hot encoding 另外应该是反过来进行 encode 的,,稀疏部分用-1代替\nfor i, doc in enumerate(docs):\n # 倒着数后面的maxlen个数字,但是输出顺序不变\n for t, char in enumerate(doc[-maxlen:]):\n X_test[i, (maxlen-1-t)] = char_indices[char]\nprint('Success!')\n\nY_test = np.array(labels)\n\nprint('Convert class vector to binary class matrix (for use with categorical_crossentropy)')\nnb_classes = 5\nprint(nb_classes, 'classes in the dataset')\nY_test = np_utils.to_categorical(Y_test, nb_classes)\nprint('Success!')\n\nprint(\"All of the pre-processde work is done.\")\n\nmodel = Sequential()\n\n# we start off with an efficient embedding layer which maps\n# our vocab indices into embedding_dims dimensions\nmodel.add(Embedding(input_dim = 41, output_dim = 50, input_length = maxlen, init = 'he_normal', W_regularizer=l2(0.01)) )\n\n# we add a Convolution1D, which will learn nb_filter\n# word group filters of size filter_length:\nmodel.add(Convolution1D(nb_filter = 128, filter_length = 3, W_regularizer=l2(0.01), init = 'he_normal', border_mode='same', activation='relu', subsample_length=1))\nmodel.add(Convolution1D(nb_filter = 128, filter_length = 3, W_regularizer=l2(0.01), init = 'he_normal', border_mode='same', activation='relu', subsample_length=1))\nmodel.add(Convolution1D(nb_filter = 128, filter_length = 3, W_regularizer=l2(0.01), init = 'he_normal', border_mode='same', activation='relu', subsample_length=1))\n\n\n\n# we use max pooling:\nmodel.add(MaxPooling1D(pool_length = model.output_shape[1]))\n#model.add(MaxPooling1D(pool_length = 2))\n#print(model.output_shape[1], \"pooling shape\")\n# We flatten the output of the conv layer,\n# so that we can add a vanilla dense layer:\nmodel.add(Flatten())\n\n\n# We add a vanilla hidden layer:\nmodel.add(Dense(100))\n#model.add(Dropout(0.1))\nmodel.add(Activation('relu'))\n\n# We add a vanilla hidden layer:\nmodel.add(Dense(100))\n#model.add(Dropout(0.1))\nmodel.add(Activation('relu'))\n\n# We project onto a single unit output layer, and squash it with a sigmoid:\nmodel.add(Dense(5))\nmodel.add(Activation('softmax'))\n\n\ncheckpointers = ModelCheckpoint(\"parameters/weights.{epoch:02d}-{val_acc:.4f}.hdf5\", monitor='val_acc', verbose=0, save_best_only=False, mode='auto')\n\n#model.load_weights(\"parameters/weights.39-0.32.hdf5\")\n\nmodel.summary()\n\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\nmodel.fit(X_train, Y_train, batch_size = 64, nb_epoch = 20, validation_data=(X_test, Y_test), callbacks = [checkpointers])\n\n\n\n",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code"
]
] |
e77c938c62604e97f9876e789ff52f522b7912d1 | 4,793 | ipynb | Jupyter Notebook | tests/expenses.tests.ipynb | gabrielnogueiralt/ProjetoESS---AdmFinancas | c6b7b4b29fabb5c39bf7d6d65582da3e1be04c20 | [
"MIT"
] | 2 | 2021-11-04T16:28:27.000Z | 2021-12-21T19:33:00.000Z | tests/expenses.tests.ipynb | MatheusAlvesAlmeida/ProjetoESS---AdmFinancas | c6b7b4b29fabb5c39bf7d6d65582da3e1be04c20 | [
"MIT"
] | 24 | 2021-11-04T16:14:58.000Z | 2021-12-21T14:43:00.000Z | tests/expenses.tests.ipynb | gabrielnogueiralt/ProjetoESS---AdmFinancas | c6b7b4b29fabb5c39bf7d6d65582da3e1be04c20 | [
"MIT"
] | 2 | 2021-11-04T15:43:54.000Z | 2021-12-20T17:02:57.000Z | 28.02924 | 83 | 0.578761 | [
[
[
"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom webdriver_manager.firefox import GeckoDriverManager\n\ndriver = webdriver.Firefox(executable_path=GeckoDriverManager().install())\ndriver.get(\"http://localhost:4200/\")\n\nemail = driver.find_element_by_name(\"emailInput\")\nemail.clear()\nemail.send_keys('[email protected]')\n\npassword = driver.find_element_by_name(\"passwordInput\")\npassword.clear()\npassword.send_keys('123456')\n\nsubmit = driver.find_element_by_name(\"submitLogin\")\nsubmit.click()\nassert \"No results found.\" not in driver.page_source\n",
"_____no_output_____"
],
[
"driver.get(\"http://localhost:4200/expenses\")\nassert \"Gastos fixos\" in driver.title",
"_____no_output_____"
],
[
"# Preencher gastos com sucesso\ntype = driver.find_element_by_name(\"typebox\")\ntype.clear()\ntype.send_keys(\"Alimentação\")\npercentage = driver.find_element_by_name(\"percentagebox\")\npercentage.clear()\npercentage.send_keys(\"80\")\n\nbutton = driver.find_element_by_name(\"addButton\")\nbutton.click()\n\ntype = driver.find_element_by_name(\"typebox\")\ntype.clear()\ntype.send_keys(\"Academia\")\npercentage = driver.find_element_by_name(\"percentagebox\")\npercentage.clear()\npercentage.send_keys(\"20\")\n\nbutton = driver.find_element_by_name(\"addButton\")\nbutton.click()\n\nconfirmButton = driver.find_element_by_name('confirmButton')\nconfirmButton.click()\n\nalert = driver.switch_to.alert\nalert_text = alert.text\nif(alert_text == 'Gastos fixos confirmados com sucesso!'):\n print(\"Passou!\")\n alert.accept()\nelse:\n print(\"Não passou!\")\n alert.accept()\n",
"_____no_output_____"
],
[
"#Deletando gastos mensais corretamente\ndeleteButton = driver.find_element_by_name(\"deleteButton\")\ndeleteButton.click()\n\nalert = driver.switch_to.alert\nalert_text = alert.text\nif(alert_text == 'Gasto fixo deletado com sucesso!'):\n print(\"Passou!\")\n alert.accept()\nelse:\n print(\"Não passou!\")\n alert.accept()",
"_____no_output_____"
],
[
"#Adicionando gastos mensais preechendo com % a mais que o possível (100%)\ntype = driver.find_element_by_name(\"typebox\")\ntype.clear()\ntype.send_keys(\"Alimentação\")\npercentage = driver.find_element_by_name(\"percentagebox\")\npercentage.clear()\npercentage.send_keys(\"80\")\n\nbutton = driver.find_element_by_name(\"addButton\")\nbutton.click()\n\ntype = driver.find_element_by_name(\"typebox\")\ntype.clear()\ntype.send_keys(\"Academia\")\npercentage = driver.find_element_by_name(\"percentagebox\")\npercentage.clear()\npercentage.send_keys(\"30\")\n\nbutton = driver.find_element_by_name(\"addButton\")\nbutton.click()\n\ntry:\n closeButton = driver.find_element_by_name('closeButton')\n closeButton.click()\n print(\"Passou!\")\nexcept:\n print(\"Não passou!\")",
"_____no_output_____"
],
[
"#assert \"No results found.\" not in driver.page_source\n#driver.close()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e77c97c878e1945f650177f2ac814825a1d6506b | 24,745 | ipynb | Jupyter Notebook | debug.ipynb | thanakijwanavit/villa-product-database | 448e2cdfa6cf2637c86fa21b34327c303435d160 | [
"Apache-2.0"
] | null | null | null | debug.ipynb | thanakijwanavit/villa-product-database | 448e2cdfa6cf2637c86fa21b34327c303435d160 | [
"Apache-2.0"
] | null | null | null | debug.ipynb | thanakijwanavit/villa-product-database | 448e2cdfa6cf2637c86fa21b34327c303435d160 | [
"Apache-2.0"
] | null | null | null | 30.854115 | 289 | 0.412811 | [
[
[
"# debug Class\n\n> API details.",
"_____no_output_____"
]
],
[
[
"#hide\nimport logging\nlogging.basicConfig(level= logging.WARNING)\nlog = logging.getLogger(\"pynamodb\")\nlog.setLevel(logging.DEBUG)\nlog.setLevel(logging.WARNING)\nlog.propagate = True\n",
"_____no_output_____"
],
[
"#hide\nimport pickle, os, json\n\nos.environ['DATABASE_TABLE_NAME'] = 'product-table-dev-manual'\nos.environ['BRANCH'] = 'dev'\nos.environ['REGION'] = 'ap-southeast-1'\nos.environ['INVENTORY_BUCKET_NAME'] = 'product-bucket-dev-manual'\nos.environ['INPUT_BUCKET_NAME'] = 'input-product-bucket-dev-manual'\nos.environ['DAX_ENDPOINT'] = 'longtermcluster.vuu7lr.clustercfg.dax.apse1.cache.amazonaws.com:8111'\nos.environ['LINEKEY'] = '2uAfV4AoYglUGmKTAk2xNOm0aV2Ufgh1BQPvQl9vJd4'\nos.environ['INTCOLS'] = json.dumps(['cprcode', 'iprcode', 'oprcode', 'sellingPrice'])\nREGION = 'ap-southeast-1'",
"_____no_output_____"
],
[
"\nBRANCH='dev'\nECOMMERCE_COL_LIST = f'https://raw.githubusercontent.com/thanakijwanavit/villaMasterSchema/{BRANCH}/product/ecommerceColList.yaml'",
"_____no_output_____"
],
[
"#hide\nprint(json.dumps(os.environ['INTCOLS']))",
"\"[\\\"cprcode\\\", \\\"iprcode\\\", \\\"oprcode\\\", \\\"sellingPrice\\\"]\"\n"
],
[
"from villaProductDatabase.database import ProductDatabase, lambdaDumpOnlineS3\nimport pandas as pd\nfrom typing import List\nimport yaml, requests",
"_____no_output_____"
]
],
[
[
"## LambdaDumpOnline",
"_____no_output_____"
]
],
[
[
"lambdaDumpOnlineS3({})",
"ecommece col list is https://raw.githubusercontent.com/thanakijwanavit/villaMasterSchema/dev/product/ecommerceColList.yaml\n"
],
[
"from inspect import getsource",
"_____no_output_____"
],
[
"print(getsource(lambdaDumpOnlineS3))",
"def lambdaDumpOnlineS3(event, *args):\n print(f'ecommece col list is {ECOMMERCE_COL_LIST}')\n # get all products from db\n df:pd.DataFrame = pd.DataFrame([i.data for i in ProductDatabase.scan()])\n # get online list from ECOMMERCE_COL_LIST\n onlineList:List[str] = yaml.load(requests.get(ECOMMERCE_COL_LIST).content)\n # filter df for item\n ## condition 1 master online is true\n condition1 = df['master_online'] == True\n ## condition 2 hema_name_en is not blank\n condition2 = df['hema_name_en'] != ''\n ## filtered df\n onlineDf:pd.DataFrame = df[condition1 & condition2].loc[:,onlineList]\n ### log shape and size\n print('shape is:',onlineDf.shape)\n print('size is:',sys.getsizeof(onlineDf.to_json(orient='split'))/1e6, 'Mb')\n\n # save file as gzip\n key = 'onlineData'\n bucket = INVENTORY_BUCKET_NAME\n path = '/tmp/inventory.json'\n ## export to gzip\n onlineDf.to_json(path ,orient='split',compression='gzip')\n ## upload file to s3\n S3.saveFile(key=key,path=path,bucket=bucket,\n ExtraArgs = {**ExtraArgs.gzip, **ExtraArgs.publicRead })\n return Response.returnSuccess()\n\n"
]
],
[
[
"## get all products",
"_____no_output_____"
]
],
[
[
"df:pd.DataFrame = pd.DataFrame([i.data for i in ProductDatabase.scan()])\ndf.head()",
"_____no_output_____"
]
],
[
[
"### filter products",
"_____no_output_____"
]
],
[
[
"condition1 = df['master_online'] == True\ncondition2 = df['hema_name_en'] != ''\nonlineList:List[str] = yaml.load(requests.get(ECOMMERCE_COL_LIST).content)\nonlineDf:pd.DataFrame = df[condition1 & condition2].loc[:,onlineList]\nonlineDf.head()",
"<ipython-input-31-7921d4e71dc6>:3: YAMLLoadWarning: calling yaml.load() without Loader=... is deprecated, as the default Loader is unsafe. Please read https://msg.pyyaml.org/load for full details.\n onlineList:List[str] = yaml.load(requests.get(ECOMMERCE_COL_LIST).content)\n"
],
[
"df.shape",
"_____no_output_____"
],
[
"df[condition1].shape ## filter for master_online",
"_____no_output_____"
],
[
"df[condition1 & condition2].shape ## filter products with missing hema_name",
"_____no_output_____"
],
[
"onlineDf[onlineDf.cprcode == 241490]",
"_____no_output_____"
],
[
"url = 'https://product-bucket-dev-manual.s3-ap-southeast-1.amazonaws.com/onlineData'\nr = pd.read_json(url, orient = 'split', compression = 'gzip')\nr.shape",
"_____no_output_____"
],
[
"r.shape",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e77ca3d7d79a3eee9180f69c2a78e4f5f7422029 | 14,001 | ipynb | Jupyter Notebook | 001_Anagram_Check.ipynb | ishancoderr/Coffee_code_Algorithms | 49a5ad9af0fa70301fb631a3330aef8409352cc7 | [
"MIT"
] | null | null | null | 001_Anagram_Check.ipynb | ishancoderr/Coffee_code_Algorithms | 49a5ad9af0fa70301fb631a3330aef8409352cc7 | [
"MIT"
] | null | null | null | 001_Anagram_Check.ipynb | ishancoderr/Coffee_code_Algorithms | 49a5ad9af0fa70301fb631a3330aef8409352cc7 | [
"MIT"
] | null | null | null | 68.632353 | 9,397 | 0.779587 | [
[
[
"<a href=\"https://colab.research.google.com/github/ishancoderr/Coffee_code_Algorithms/blob/main/001_Anagram_Check.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# **Check whether two string are anagram of each other**",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"**solution**",
"_____no_output_____"
]
],
[
[
"def anagram(w1,w2):\n w1=w1.replace(' ','').lower()\n w2=w2.replace(' ','').lower()\n\n return sorted(w1)==sorted(w2)\n ",
"_____no_output_____"
],
[
"anagram('do g','GOd')",
"_____no_output_____"
],
[
"def anagramer(w1,w2):\n w1=w1.replace(' ','').lower()\n w2=w2.replace(' ','').lower()\n\n \n if len(w1) != len(w2):\n return False\n\n count ={}\n\n for letter in w1:\n print(letter)\n if letter in count:\n print(letter)\n count[letter] += 1\n else:\n count[letter] = 1\n\n for letter in w2:\n if letter in count:\n count[letter] -= 1\n else:\n count[letter] =1\n\n for k in count:\n if count[k] != 0:\n return False\n\n return True\n\n\n ",
"_____no_output_____"
],
[
"anagramer('wera','wesa')",
"w\ne\nr\na\n"
],
[
"anagramer('rabbt','t bbra')",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
e77ca5401f8b3fdba31d1f711bd3e723e720253c | 55,955 | ipynb | Jupyter Notebook | scarselli_etal_2021/plot_Fig2.ipynb | burakbudanur/gridemic | 7429fd53555a1abd21614e1cce104f043576e05d | [
"MIT"
] | null | null | null | scarselli_etal_2021/plot_Fig2.ipynb | burakbudanur/gridemic | 7429fd53555a1abd21614e1cce104f043576e05d | [
"MIT"
] | null | null | null | scarselli_etal_2021/plot_Fig2.ipynb | burakbudanur/gridemic | 7429fd53555a1abd21614e1cce104f043576e05d | [
"MIT"
] | null | null | null | 297.632979 | 50,184 | 0.922652 | [
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.gridspec import GridSpec\nfrom mpl_toolkits.axes_grid.inset_locator import inset_axes, InsetPosition",
"_____no_output_____"
],
[
"# Prepare data\n\nN = 3162\n# Figure 2a, 2b and 2c\nR0_cont = np.linspace(0,3,101)\nR0_disc = np.linspace(0,3,101)\n\nNf_cont = np.zeros(R0_cont.size)\nNf_disc = np.zeros(R0_disc.size)\n\nM = 10000\nTotCases_cont = np.zeros((R0_cont.size,M))\nTotCases_disc = np.zeros((R0_disc.size,M))\nNewCases_cont = np.zeros((R0_cont.size,M))\nNewCases_disc = np.zeros((R0_disc.size,M))\n\nfor j in range(R0_cont.size):\n P_cont = np.loadtxt('data/Pop_R0={:04.2f}_NTests=0.dat'.format(R0_cont[j]))\n TotCases_cont[j,:] = np.sum(P_cont[:,1:5],axis=1)[:M] \n NewCases_cont[j,:] = np.gradient(TotCases_cont[j,:]) \n Nf_cont[j] = np.max(TotCases_cont[j,:])\n\nfor j in range(R0_disc.size):\n P_disc = np.loadtxt('data/Pop_R0={:04.2f}_NTests=1000.dat'.format(R0_disc[j]))\n TotCases_disc[j,:] = np.sum(P_disc[:,1:5],axis=1)[:M] \n NewCases_disc[j,:] = np.gradient(TotCases_disc[j,:])\n Nf_disc[j] = np.max(TotCases_disc[j,:])",
"_____no_output_____"
],
[
"# Figure 2d\n\nK1 = 400\nK2 = 100\n\nRt1 = np.zeros((K1,200))\nRt2 = np.zeros((K2,200))\n\nfor k in range(K1):\n Rt1[k,:] = np.loadtxt('data/Rt_R0=2.3_k={}.dat'.format(k))\n\nfor k in range(K2):\n Rt2[k,:] = np.loadtxt('data/Rt_R0=2.7_k={}.dat'.format(k))\n\n\nRt1mean = np.nanmean(Rt1,axis=0)\nRt2mean = np.nanmean(Rt2,axis=0)",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(2,2,figsize=(6,6),tight_layout=True)\n\nthold_cont = 0.95\nthold_disc = 2.52\n\ncolor_cont = 'royalblue'\ncolor_disc = 'crimson'\n\n# Discontinuous flattening\nax[0,0].set_xlim([0,600])\nax[0,0].set_ylim([0,220e3])\nax[0,0].set_xlabel(r'Days')\nax[0,0].set_ylabel(r'New daily cases')\nax[0,0].ticklabel_format(axis='y',style='sci',useMathText=True,scilimits=(0,0))\nax[0,0].text(-.2,1.08,r'a',transform=ax[0,0].transAxes,fontweight='bold')\n#ax[0,0].plot(NewCases_disc[100,:],color=color_disc)\n#ax[0,0].plot(NewCases_disc[85,:],color=color_disc)\n\nfor j in [87, 89, 90, 94, 100]:\n ax[0,0].plot(NewCases_disc[j,:],color=color_disc)\n\n# Continuous flattening\nax[0,1].set_xlim([0,600])\nax[0,1].set_ylim([0,220e3])\nax[0,1].set_xlabel(r'Days')\nax[0,1].set_ylabel(r'New daily cases')\nax[0,1].ticklabel_format(axis='y',style='sci',useMathText=True,scilimits=(0,0))\nax[0,1].text(-.2,1.08,r'b',transform=ax[0,1].transAxes,fontweight='bold')\n\n\nfor j in [36, 38, 40, 42, 44, 46]:\n ax[0,1].plot(NewCases_cont[j,:],color=color_cont)\n \n# Epidemic transition\nax[1,0].set_xlabel(r'Basic reproduction number ($R_0$)')\nax[1,0].set_ylabel(r'Fraction of infected ($N_F/P$)')\nax[1,0].text(-.2,1.08,r'c',transform=ax[1,0].transAxes,fontweight='bold')\n\nfor j in range(R0_cont.size):\n if R0_cont[j] > thold_cont:\n ax[1,0].scatter(R0_cont[j],Nf_cont[j]/N**2,marker='.',color=color_cont,zorder=1000)\n else:\n ax[1,0].scatter(R0_cont[j],Nf_cont[j]/N**2,marker='.',color='black')\n \nfor j in range(R0_disc.size):\n if R0_disc[j] > thold_disc:\n ax[1,0].scatter(R0_disc[j],Nf_disc[j]/N**2,marker='.',color=color_disc)\n else:\n ax[1,0].scatter(R0_disc[j],Nf_disc[j]/N**2,marker='.',color='black')\n\nax[1,1].text(-.2,1.08,r'd',transform=ax[1,1].transAxes,fontweight='bold')\nax[1,1].set_xlabel(r'Days')\nax[1,1].set_ylabel(r'Reproduction number ($R_t$)')\n\nax[1,1].plot(Rt1mean,'.',color='black',label=r'$R_0=2.3$')\nax[1,1].plot(Rt2mean,'.',color='crimson',label=r'$R_0=2.7$')\nax[1,1].plot([0,120],[1,1],'--',color='seagreen')\nax[1,1].set_xlim([0,120])\nax[1,1].set_ylim([0.8,1.8])\nax[1,1].legend(loc='upper left',borderpad=0)\n\nfig.savefig('Fig2.pdf')",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code"
]
] |
e77cd53eb168cf831d62d37c7c77cff4bdf29663 | 120,831 | ipynb | Jupyter Notebook | IPYNB Notebooks/modeling_with_top_3_tags.ipynb | sandeeppanda22/Movie-Tag-Prediction- | 31055bf3252e6a25c595df518e5ef6c86a4da1db | [
"Apache-2.0"
] | null | null | null | IPYNB Notebooks/modeling_with_top_3_tags.ipynb | sandeeppanda22/Movie-Tag-Prediction- | 31055bf3252e6a25c595df518e5ef6c86a4da1db | [
"Apache-2.0"
] | null | null | null | IPYNB Notebooks/modeling_with_top_3_tags.ipynb | sandeeppanda22/Movie-Tag-Prediction- | 31055bf3252e6a25c595df518e5ef6c86a4da1db | [
"Apache-2.0"
] | 1 | 2021-05-04T19:22:32.000Z | 2021-05-04T19:22:32.000Z | 32.429147 | 273 | 0.493524 | [
[
[
"<h1><center>MPST: A Corpus of Movie Plot Synopses with Tags</center></h1>",
"_____no_output_____"
]
],
[
[
"!pip install scikit-multilearn\n\nimport re\nimport os\nimport tqdm\nimport nltk\nimport pickle\nimport sqlite3\nimport warnings\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nimport seaborn as sns\nimport xgboost as xgb\nimport tensorflow as tf\nfrom sklearn import metrics\nfrom tensorflow import keras\nfrom nltk.corpus import words\nfrom datetime import datetime\nfrom bs4 import BeautifulSoup\nfrom wordcloud import WordCloud\nimport matplotlib.pyplot as plt\nfrom nltk.corpus import stopwords\nfrom gensim.models import Word2Vec\nfrom itertools import combinations\nfrom keras.models import load_model\nfrom keras.models import Sequential\nfrom tensorflow.keras import layers\nfrom nltk.stem import SnowballStemmer\nfrom sklearn.pipeline import Pipeline\nfrom nltk.tokenize import sent_tokenize\nfrom keras.preprocessing import sequence\nfrom scipy.sparse import coo_matrix, hstack\nfrom tensorflow.keras.utils import plot_model\nfrom keras.layers.embeddings import Embedding\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import classification_report\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.preprocessing import MultiLabelBinarizer\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom skmultilearn.problem_transform import BinaryRelevance\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nfrom sklearn.metrics import f1_score,precision_score,recall_score,hamming_loss\nfrom keras.layers import Conv1D, Conv2D, Dense, Dropout, Flatten, LSTM, GlobalMaxPooling1D, MaxPooling2D, Activation, BatchNormalization\n\n%matplotlib inline\nnltk.download('punkt')\nnltk.download('wordnet')\nwarnings.filterwarnings(\"ignore\")\nstemmer = SnowballStemmer('english')\n\n%autosave 120",
"Requirement already satisfied: scikit-multilearn in c:\\programdata\\anaconda3\\lib\\site-packages (0.2.0)\n"
],
[
"data_with_all_tags = pd.read_csv(\"data_with_all_tags.csv\")\ndata_with_all_tags.head()",
"_____no_output_____"
],
[
"conn = sqlite3.connect('data.db')\ndata_with_all_tags.to_sql('data', conn, if_exists='replace', index=False)\ntrain = pd.read_sql(\"Select * From data where split = 'train' OR split='val'\",conn)\ntest = pd.read_sql(\"Select * From data where split = 'test'\",conn)\nconn.close()",
"_____no_output_____"
],
[
"X_train = train[\"CleanedSynopsis\"]\ny_train= train[\"tags\"]\n\nX_test = test[\"CleanedSynopsis\"]\ny_test= test[\"tags\"]",
"_____no_output_____"
],
[
"def tokenize(x):\n x=x.split(',')\n tags=[i.strip() for i in x] #Some tags contains whitespaces before them, so we need to strip them\n return tags\n\ncnt_vectorizer = CountVectorizer(tokenizer = tokenize, max_features=3, binary='true').fit(y_train)\ny_train_multilabel = cnt_vectorizer.transform(y_train)\ny_test_multilabel = cnt_vectorizer.transform(y_test)",
"_____no_output_____"
]
],
[
[
"<h1> 1. TfidfVectorizer with 1 grams: </h1>",
"_____no_output_____"
]
],
[
[
"tf_vectorizer = TfidfVectorizer(min_df=0.09, tokenizer = lambda x: x.split(\" \"), ngram_range=(1,1))\n\nX_train_multilabel = tf_vectorizer.fit_transform(X_train)\nX_test_multilabel = tf_vectorizer.transform(X_test)\n\nprint(\"Dimensions of train data X:\",X_train_multilabel.shape, \"Y :\",y_train_multilabel.shape)\nprint(\"Dimensions of test data X:\",X_test_multilabel.shape,\"Y:\",y_test_multilabel.shape)",
"Dimensions of train data X: (10989, 657) Y : (10989, 3)\nDimensions of test data X: (2768, 657) Y: (2768, 3)\n"
]
],
[
[
"<h2> 1.1 OneVsRestClassifier + MultinomialNB:</h2>",
"_____no_output_____"
]
],
[
[
"mb = MultinomialNB(class_prior = [0.5, 0.5])\n\nclf = OneVsRestClassifier(mb)\nclf.fit(X_train_multilabel, y_train_multilabel)",
"_____no_output_____"
],
[
"prediction1 = clf.predict(X_test_multilabel)\n\nprecision1 = precision_score(y_test_multilabel, prediction1, average='micro')\n\nrecall1 = recall_score(y_test_multilabel, prediction1, average='micro')\n\nf1_score1 = 2*((precision1 * recall1)/(precision1 + recall1))\n\nprint(\"precision1: {:.4f}, recall1: {:.4f}, F1-measure: {:.4f}\".format(precision1, recall1, f1_score1))",
"precision1: 0.4674, recall1: 0.6864, F1-measure: 0.5561\n"
],
[
"for i in range(5):\n k = test.sample(1).index[0]\n print(\"Movie: \", test['title'][k]) \n print(\"Actual genre: \",y_test[k])\n print(\"Predicted tag: \", cnt_vectorizer.inverse_transform(prediction1[k])[0],\"\\n\")",
"Movie: Anastasia\nActual genre: romantic, cute, entertaining\nPredicted tag: [] \n\nMovie: Dog City\nActual genre: psychedelic\nPredicted tag: [] \n\nMovie: Aftermath\nActual genre: violence\nPredicted tag: ['flashback' 'murder' 'violence'] \n\nMovie: What a Nightmare, Charlie Brown!\nActual genre: psychedelic\nPredicted tag: [] \n\nMovie: Witchcraft 7: Judgement Hour\nActual genre: paranormal\nPredicted tag: ['flashback' 'murder' 'violence'] \n\n"
]
],
[
[
"<h2> 1.2 OneVsRestClassifier + SGDClassifier with LOG Loss:</h2>",
"_____no_output_____"
]
],
[
[
"sgl = SGDClassifier(loss='log', class_weight='balanced')\n\nclf = OneVsRestClassifier(sgl)\nclf.fit(X_train_multilabel, y_train_multilabel)",
"_____no_output_____"
],
[
"prediction2 = clf.predict(X_test_multilabel)\n\nprecision2 = precision_score(y_test_multilabel, prediction2, average='micro')\n\nrecall2 = recall_score(y_test_multilabel, prediction2, average='micro')\n\nf1_score2 = 2*((precision2 * recall2)/(precision2 + recall2))\n\nprint(\"precision2: {:.4f}, recall2: {:.4f}, F1-measure: {:.4f}\".format(precision2, recall2, f1_score2))",
"precision2: 0.5057, recall2: 0.6680, F1-measure: 0.5757\n"
],
[
"for i in range(5):\n k = test.sample(1).index[0]\n print(\"Movie: \", test['title'][k]) \n print(\"Actual genre: \",y_test[k])\n print(\"Predicted tag: \", cnt_vectorizer.inverse_transform(prediction2[k])[0],\"\\n\")",
"Movie: Capitalism: A Love Story\nActual genre: sentimental\nPredicted tag: ['flashback'] \n\nMovie: Saved!\nActual genre: romantic, humor, satire\nPredicted tag: [] \n\nMovie: How to Train Your Dragon 2\nActual genre: revenge, cute\nPredicted tag: ['violence'] \n\nMovie: Orfeu Negro\nActual genre: atmospheric\nPredicted tag: ['murder'] \n\nMovie: Accepted\nActual genre: romantic, action\nPredicted tag: [] \n\n"
]
],
[
[
"<h2> 1.3 OneVsRestClassifier + SGDClassifier with Hinge Loss:</h2>",
"_____no_output_____"
]
],
[
[
"sgh = SGDClassifier(loss='hinge', class_weight='balanced')\n\nclf = OneVsRestClassifier(sgh)\nclf.fit(X_train_multilabel, y_train_multilabel)",
"_____no_output_____"
],
[
"prediction3 = clf.predict(X_test_multilabel)\n\nprecision3 = precision_score(y_test_multilabel, prediction3, average='micro')\n\nrecall3 = recall_score(y_test_multilabel, prediction3, average='micro')\n\nf1_score3 = 2*((precision3 * recall3)/(precision3 + recall3))\n\nprint(\"precision3: {:.4f}, recall3: {:.4f}, F1-measure: {:.4f}\".format(precision3, recall3, f1_score3))",
"precision3: 0.5110, recall3: 0.6608, F1-measure: 0.5763\n"
],
[
"for i in range(5):\n k = test.sample(1).index[0]\n print(\"Movie: \", test['title'][k]) \n print(\"Actual genre: \",y_test[k])\n print(\"Predicted tag: \", cnt_vectorizer.inverse_transform(prediction3[k])[0],\"\\n\")",
"Movie: Assassin's Creed IV: Black Flag\nActual genre: action\nPredicted tag: ['flashback' 'murder' 'violence'] \n\nMovie: The Kite Runner\nActual genre: romantic, violence, murder, storytelling, flashback\nPredicted tag: ['flashback' 'violence'] \n\nMovie: Guest House Paradiso\nActual genre: psychedelic, comedy\nPredicted tag: [] \n\nMovie: Gingerdead Man 2: Passion of the Crust\nActual genre: comedy, murder, violence\nPredicted tag: ['flashback' 'murder' 'violence'] \n\nMovie: Zazie dans le métro\nActual genre: absurd, psychedelic\nPredicted tag: [] \n\n"
]
],
[
[
"<h2> 1.4 OneVsRestClassifier + LogisticRegression:</h2>",
"_____no_output_____"
]
],
[
[
"lr = LogisticRegression(class_weight='balanced')\n\nclf = OneVsRestClassifier(lr)\nclf.fit(X_train_multilabel, y_train_multilabel)",
"_____no_output_____"
],
[
"prediction4 = clf.predict(X_test_multilabel)\n\nprecision4 = precision_score(y_test_multilabel, prediction4, average='micro')\n\nrecall4 = recall_score(y_test_multilabel, prediction4, average='micro')\n\nf1_score4 = 2*((precision4 * recall4)/(precision4 + recall4))\n\nprint(\"precision4: {:.4f}, recall4: {:.4f}, F1-measure: {:.4f}\".format(precision4, recall4, f1_score4))",
"precision4: 0.5076, recall4: 0.6836, F1-measure: 0.5826\n"
],
[
"for i in range(5):\n k = test.sample(1).index[0]\n print(\"Movie: \", test['title'][k]) \n print(\"Actual genre: \",y_test[k])\n print(\"Predicted tag: \", cnt_vectorizer.inverse_transform(prediction4[k])[0],\"\\n\")",
"Movie: The Sting\nActual genre: boring, depressing, murder, cult, plot twist, clever, inspiring, revenge, entertaining\nPredicted tag: ['flashback' 'murder'] \n\nMovie: Olivia\nActual genre: neo noir, cruelty, murder, violence, revenge, sadist\nPredicted tag: [] \n\nMovie: El capo\nActual genre: satire\nPredicted tag: ['flashback' 'murder' 'violence'] \n\nMovie: Bereavement\nActual genre: cult\nPredicted tag: ['murder' 'violence'] \n\nMovie: Arpointeu\nActual genre: neo noir, murder, paranormal, violence, flashback, revenge\nPredicted tag: ['flashback' 'murder' 'violence'] \n\n"
]
],
[
[
"<h1>2. TfidfVectorizer with (1 - 2 Grams):<?h1>",
"_____no_output_____"
]
],
[
[
"tf_vectorizer = TfidfVectorizer(min_df=0.09, tokenizer = lambda x: x.split(\" \"), ngram_range=(1,2))\n\nX_train_multilabel = tf_vectorizer.fit_transform(X_train)\nX_test_multilabel = tf_vectorizer.transform(X_test)\n\nprint(\"Dimensions of train data X:\",X_train_multilabel.shape, \"Y :\",y_train_multilabel.shape)\nprint(\"Dimensions of test data X:\",X_test_multilabel.shape,\"Y:\",y_test_multilabel.shape)",
"Dimensions of train data X: (10989, 666) Y : (10989, 3)\nDimensions of test data X: (2768, 666) Y: (2768, 3)\n"
]
],
[
[
"<H2> 2.1 OneVsRestClassifier + MultinomialNB :</H2>",
"_____no_output_____"
]
],
[
[
"mb = MultinomialNB(class_prior = [0.5, 0.5])\n\nclf = OneVsRestClassifier(mb)\nclf.fit(X_train_multilabel, y_train_multilabel)",
"_____no_output_____"
],
[
"prediction5 = clf.predict(X_test_multilabel)\n\nprecision5 = precision_score(y_test_multilabel, prediction5, average='micro')\n\nrecall5 = recall_score(y_test_multilabel, prediction5, average='micro')\n\nf1_score5 = 2*((precision5 * recall5)/(precision5 + recall5))\n\nprint(\"precision5: {:.4f}, recall5: {:.4f}, F1-measure: {:.4f}\".format(precision5, recall5, f1_score5))",
"precision5: 0.4680, recall5: 0.6860, F1-measure: 0.5564\n"
],
[
"for i in range(5):\n k = test.sample(1).index[0]\n print(\"Movie: \", test['title'][k]) \n print(\"Actual genre: \",y_test[k])\n print(\"Predicted tag: \", cnt_vectorizer.inverse_transform(prediction5[k])[0],\"\\n\")",
"Movie: Long-Distance Princess\nActual genre: romantic\nPredicted tag: ['flashback'] \n\nMovie: Time Lapse\nActual genre: plot twist, mystery, murder\nPredicted tag: ['murder'] \n\nMovie: What's Eating Gilbert Grape\nActual genre: tragedy, whimsical, psychedelic, boring, depressing\nPredicted tag: ['flashback'] \n\nMovie: The Rebound\nActual genre: comedy, romantic\nPredicted tag: ['flashback'] \n\nMovie: Une liaison pornographique\nActual genre: pornographic, realism, flashback\nPredicted tag: ['flashback'] \n\n"
]
],
[
[
"<h2> 2.2 OneVsRestClassifier + SGDClassifier with LOG Loss :</h2>",
"_____no_output_____"
]
],
[
[
"sgl = SGDClassifier(loss='log', class_weight='balanced')\n\nclf = OneVsRestClassifier(sgl)\nclf.fit(X_train_multilabel, y_train_multilabel)",
"_____no_output_____"
],
[
"prediction6 = clf.predict(X_test_multilabel)\n\nprecision6 = precision_score(y_test_multilabel, prediction6, average='micro')\n\nrecall6 = recall_score(y_test_multilabel, prediction6, average='micro')\n\nf1_score6 = 2*((precision6 * recall6)/(precision6 + recall6))\n\nprint(\"precision6: {:.4f}, recall6: {:.4f}, F1-measure: {:.4f}\".format(precision6, recall6, f1_score6))",
"precision6: 0.5160, recall6: 0.6776, F1-measure: 0.5858\n"
],
[
"for i in range(5):\n k = test.sample(1).index[0]\n print(\"Movie: \", test['title'][k]) \n print(\"Actual genre: \",y_test[k])\n print(\"Predicted tag: \", cnt_vectorizer.inverse_transform(prediction6[k])[0],\"\\n\")",
"Movie: Cape Fear\nActual genre: suspenseful, gothic, murder, neo noir, mystery, violence, cult, horror, flashback, good versus evil, revenge\nPredicted tag: ['flashback' 'murder' 'violence'] \n\nMovie: Wild Bill\nActual genre: cult, revenge, storytelling, flashback\nPredicted tag: ['violence'] \n\nMovie: Beyond the Law\nActual genre: romantic, neo noir, murder, violence, flashback\nPredicted tag: ['murder'] \n\nMovie: Blancanieves\nActual genre: cruelty, murder\nPredicted tag: [] \n\nMovie: Gabriel Over the White House\nActual genre: depressing\nPredicted tag: ['violence'] \n\n"
]
],
[
[
"<h2> 2.3 OneVsRestClassifier + SGDClassifier with HINGE Loss : </h2>",
"_____no_output_____"
]
],
[
[
"sgh = SGDClassifier(loss='hinge', class_weight='balanced')\n\nclf = OneVsRestClassifier(sgh)\nclf.fit(X_train_multilabel, y_train_multilabel)",
"_____no_output_____"
],
[
"prediction7 = clf.predict(X_test_multilabel)\n\nprecision7 = precision_score(y_test_multilabel, prediction7, average='micro')\n\nrecall7 = recall_score(y_test_multilabel, prediction7, average='micro')\n\nf1_score7 = 2*((precision7 * recall7)/(precision7 + recall7))\n\nprint(\"precision7: {:.4f}, recall7: {:.4f}, F1-measure: {:.4f}\".format(precision7, recall7, f1_score7))",
"precision7: 0.4907, recall7: 0.7023, F1-measure: 0.5777\n"
],
[
"for i in range(5):\n k = test.sample(1).index[0]\n print(\"Movie: \", test['title'][k]) \n print(\"Actual genre: \",y_test[k])\n print(\"Predicted tag: \", cnt_vectorizer.inverse_transform(prediction7[k])[0],\"\\n\")",
"Movie: Les deux orphelines vampires\nActual genre: insanity\nPredicted tag: ['murder'] \n\nMovie: The Blob\nActual genre: violence, cult, suspenseful, comedy, murder\nPredicted tag: ['murder'] \n\nMovie: La casa muda\nActual genre: plot twist, revenge\nPredicted tag: [] \n\nMovie: Fist Fight\nActual genre: prank\nPredicted tag: [] \n\nMovie: Linewatch\nActual genre: good versus evil, violence\nPredicted tag: ['murder' 'violence'] \n\n"
]
],
[
[
"<h2> 2.4 OneVsRestClassifier + LogisticRegression:</h2>",
"_____no_output_____"
]
],
[
[
"lr = LogisticRegression(class_weight='balanced')\n\nclf = OneVsRestClassifier(lr)\nclf.fit(X_train_multilabel, y_train_multilabel)",
"_____no_output_____"
],
[
"prediction8 = clf.predict(X_test_multilabel)\n\nprecision8 = precision_score(y_test_multilabel, prediction8, average='micro')\n\nrecall8 = recall_score(y_test_multilabel, prediction8, average='micro')\n\nf1_score8 = 2*((precision8 * recall8)/(precision8 + recall8))\n\nprint(\"precision8: {:.4f}, recall8: {:.4f}, F1-measure: {:.4f}\".format(precision8, recall8, f1_score8))",
"precision8: 0.5081, recall8: 0.6848, F1-measure: 0.5834\n"
],
[
"for i in range(5):\n k = test.sample(1).index[0]\n print(\"Movie: \", test['title'][k]) \n print(\"Actual genre: \",y_test[k])\n print(\"Predicted tag: \", cnt_vectorizer.inverse_transform(prediction8[k])[0],\"\\n\")",
"Movie: Hare and Loathing in Las Vegas\nActual genre: psychedelic\nPredicted tag: [] \n\nMovie: Misconduct\nActual genre: neo noir\nPredicted tag: ['murder' 'violence'] \n\nMovie: Ten Little Indians\nActual genre: murder\nPredicted tag: ['flashback' 'murder' 'violence'] \n\nMovie: Hostel\nActual genre: boring, gothic, murder, stupid, violence, cult, horror, action, revenge, sadist\nPredicted tag: ['violence'] \n\nMovie: Scooby-Doo and the Witch's Ghost\nActual genre: paranormal, psychedelic, horror, mystery\nPredicted tag: [] \n\n"
]
],
[
[
"<h1>3. TfidfVectorizer with (1 - 3 Grams):<?h1>",
"_____no_output_____"
]
],
[
[
"tf_vectorizer = TfidfVectorizer(min_df=0.09, tokenizer = lambda x: x.split(\" \"), ngram_range=(1,3))\n\nX_train_multilabel = tf_vectorizer.fit_transform(X_train)\nX_test_multilabel = tf_vectorizer.transform(X_test)\n\nprint(\"Dimensions of train data X:\",X_train_multilabel.shape, \"Y :\",y_train_multilabel.shape)\nprint(\"Dimensions of test data X:\",X_test_multilabel.shape,\"Y:\",y_test_multilabel.shape)",
"Dimensions of train data X: (10989, 666) Y : (10989, 3)\nDimensions of test data X: (2768, 666) Y: (2768, 3)\n"
]
],
[
[
"<H2> 3.1 OneVsRestClassifier + MultinomialNB :</H2>",
"_____no_output_____"
]
],
[
[
"mb = MultinomialNB(class_prior = [0.5, 0.5])\n\nclf = OneVsRestClassifier(mb)\nclf.fit(X_train_multilabel, y_train_multilabel)",
"_____no_output_____"
],
[
"prediction9 = clf.predict(X_test_multilabel)\n\nprecision9 = precision_score(y_test_multilabel, prediction9, average='micro')\n\nrecall9 = recall_score(y_test_multilabel, prediction9, average='micro')\n\nf1_score9 = 2*((precision9 * recall9)/(precision9 + recall9))\n\nprint(\"precision9: {:.4f}, recall9: {:.4f}, F1-measure: {:.4f}\".format(precision9, recall9, f1_score9))",
"precision9: 0.4680, recall9: 0.6860, F1-measure: 0.5564\n"
],
[
"for i in range(5):\n k = test.sample(1).index[0]\n print(\"Movie: \", test['title'][k]) \n print(\"Actual genre: \",y_test[k])\n print(\"Predicted tag: \", cnt_vectorizer.inverse_transform(prediction9[k])[0],\"\\n\")",
"Movie: Tezaab\nActual genre: revenge, romantic, flashback\nPredicted tag: ['flashback' 'murder' 'violence'] \n\nMovie: My Summer of Love\nActual genre: dramatic, romantic, queer\nPredicted tag: ['flashback'] \n\nMovie: The Ten Commandments: The Musical\nActual genre: historical fiction\nPredicted tag: ['violence'] \n\nMovie: The Gambler and the Lady\nActual genre: revenge, murder\nPredicted tag: ['murder' 'violence'] \n\nMovie: Roxanne\nActual genre: romantic, psychedelic, entertaining\nPredicted tag: ['flashback'] \n\n"
]
],
[
[
"<H2> 3.2 OneVsRestClassifier + SGDClassifier with LOG Loss :</H2>",
"_____no_output_____"
]
],
[
[
"sgl = SGDClassifier(loss='log', class_weight='balanced')\n\nclf = OneVsRestClassifier(sgl)\nclf.fit(X_train_multilabel, y_train_multilabel)",
"_____no_output_____"
],
[
"prediction10 = clf.predict(X_test_multilabel)\n\nprecision10 = precision_score(y_test_multilabel, prediction10, average='micro')\n\nrecall10 = recall_score(y_test_multilabel, prediction10, average='micro')\n\nf1_score10 = 2*((precision10 * recall10)/(precision10 + recall10))\n\nprint(\"precision10: {:.4f}, recall10: {:.4f}, F1-measure: {:.4f}\".format(precision10, recall10, f1_score10))",
"precision10: 0.5174, recall10: 0.6688, F1-measure: 0.5835\n"
],
[
"for i in range(5):\n k = test.sample(1).index[0]\n print(\"Movie: \", test['title'][k]) \n print(\"Actual genre: \",y_test[k])\n print(\"Predicted tag: \", cnt_vectorizer.inverse_transform(prediction10[k])[0],\"\\n\")",
"Movie: American Son\nActual genre: violence, romantic, flashback\nPredicted tag: ['flashback'] \n\nMovie: Conan the Destroyer\nActual genre: murder, cult, fantasy, alternate history, violence\nPredicted tag: ['murder' 'violence'] \n\nMovie: Love & Other Drugs\nActual genre: romantic\nPredicted tag: ['flashback'] \n\nMovie: The Gazebo\nActual genre: suspenseful, murder\nPredicted tag: ['murder'] \n\nMovie: Kuch Kuch Hota Hai\nActual genre: flashback\nPredicted tag: ['flashback'] \n\n"
]
],
[
[
"<h2> 3.3 OneVsRestClassifier + SGDClassifier with HINGE Loss : </h2>",
"_____no_output_____"
]
],
[
[
"sgh = SGDClassifier(loss='hinge', class_weight='balanced')\n\nclf = OneVsRestClassifier(sgh)\nclf.fit(X_train_multilabel, y_train_multilabel)",
"_____no_output_____"
],
[
"prediction11 = clf.predict(X_test_multilabel)\n\nprecision11 = precision_score(y_test_multilabel, prediction11, average='micro')\n\nrecall11 = recall_score(y_test_multilabel, prediction11, average='micro')\n\nf1_score11 = 2*((precision11 * recall11)/(precision11 + recall11))\n\nprint(\"precision11: {:.4f}, recall11: {:.4f}, F1-measure: {:.4f}\".format(precision11, recall11, f1_score11))",
"precision11: 0.4960, recall11: 0.6864, F1-measure: 0.5758\n"
],
[
"for i in range(5):\n k = test.sample(1).index[0]\n print(\"Movie: \", test['title'][k]) \n print(\"Actual genre: \",y_test[k])\n print(\"Predicted tag: \", cnt_vectorizer.inverse_transform(prediction11[k])[0],\"\\n\")",
"Movie: Austin Powers: International Man of Mystery\nActual genre: comedy, boring, cult, good versus evil, psychedelic, humor, satire, revenge, entertaining\nPredicted tag: [] \n\nMovie: American Dreamer\nActual genre: intrigue\nPredicted tag: ['flashback'] \n\nMovie: Shootout at Wadala\nActual genre: violence\nPredicted tag: ['flashback' 'murder' 'violence'] \n\nMovie: Haunted - 3D\nActual genre: paranormal\nPredicted tag: ['flashback'] \n\nMovie: All-Star Superman\nActual genre: tragedy, whimsical, romantic, action\nPredicted tag: ['flashback'] \n\n"
]
],
[
[
"<h2> 3.4 OneVsRestClassifier + LogisticRegression:</h2>",
"_____no_output_____"
]
],
[
[
"lr = LogisticRegression(class_weight='balanced')\n\nclf = OneVsRestClassifier(lr)\nclf.fit(X_train_multilabel, y_train_multilabel)",
"_____no_output_____"
],
[
"prediction12 = clf.predict(X_test_multilabel)\n\nprecision12 = precision_score(y_test_multilabel, prediction12, average='micro')\n\nrecall12 = recall_score(y_test_multilabel, prediction12, average='micro')\n\nf1_score12 = 2*((precision12 * recall12)/(precision12 + recall12))\n\nprint(\"precision12: {:.4f}, recall12: {:.4f}, F1-measure: {:.4f}\".format(precision12, recall12, f1_score12))",
"precision12: 0.5081, recall12: 0.6848, F1-measure: 0.5834\n"
],
[
"for i in range(5):\n k = test.sample(1).index[0]\n print(\"Movie: \", test['title'][k]) \n print(\"Actual genre: \",y_test[k])\n print(\"Predicted tag: \", cnt_vectorizer.inverse_transform(prediction12[k])[0],\"\\n\")",
"Movie: End of Days\nActual genre: mystery, neo noir, murder, stupid, violence, flashback, good versus evil, suspenseful\nPredicted tag: ['flashback' 'murder' 'violence'] \n\nMovie: Zombeavers\nActual genre: absurd, entertaining\nPredicted tag: ['violence'] \n\nMovie: The Witches of Eastwick\nActual genre: comedy\nPredicted tag: ['flashback'] \n\nMovie: Chain of Desire\nActual genre: murder\nPredicted tag: [] \n\nMovie: Did You Hear About the Morgans?\nActual genre: entertaining, murder\nPredicted tag: ['flashback' 'murder'] \n\n"
]
],
[
[
"<h1>4. TfidfVectorizer with (1 - 4 Grams):</h1>",
"_____no_output_____"
]
],
[
[
"tf_vectorizer = TfidfVectorizer(min_df=0.09, tokenizer = lambda x: x.split(\" \"), ngram_range=(1, 4))\n\nX_train_multilabel = tf_vectorizer.fit_transform(X_train)\nX_test_multilabel = tf_vectorizer.transform(X_test)\n\nprint(\"Dimensions of train data X:\",X_train_multilabel.shape, \"Y :\",y_train_multilabel.shape)\nprint(\"Dimensions of test data X:\",X_test_multilabel.shape,\"Y:\",y_test_multilabel.shape)",
"Dimensions of train data X: (10989, 666) Y : (10989, 3)\nDimensions of test data X: (2768, 666) Y: (2768, 3)\n"
]
],
[
[
"<H2> 4.1 OneVsRestClassifier + MultinomialNB :</H2>",
"_____no_output_____"
]
],
[
[
"mb = MultinomialNB(class_prior = [0.5, 0.5])\n\nclf = OneVsRestClassifier(mb)\nclf.fit(X_train_multilabel, y_train_multilabel)",
"_____no_output_____"
],
[
"prediction13 = clf.predict(X_test_multilabel)\n\nprecision13 = precision_score(y_test_multilabel, prediction13, average='micro')\n\nrecall13 = recall_score(y_test_multilabel, prediction13, average='micro')\n\nf1_score13 = 2*((precision13 * recall13)/(precision13 + recall13))\n\nprint(\"precision13: {:.4f}, recall13: {:.4f}, F1-measure: {:.4f}\".format(precision13, recall13, f1_score13))",
"precision13: 0.4680, recall13: 0.6860, F1-measure: 0.5564\n"
],
[
"for i in range(5):\n k = test.sample(1).index[0]\n print(\"Movie: \", test['title'][k]) \n print(\"Actual genre: \",y_test[k])\n print(\"Predicted tag: \", cnt_vectorizer.inverse_transform(prediction13[k])[0],\"\\n\")",
"Movie: Hold Your Breath\nActual genre: violence\nPredicted tag: ['flashback' 'murder' 'violence'] \n\nMovie: Nae Yeojachinguneun Gumiho\nActual genre: romantic\nPredicted tag: [] \n\nMovie: World Without End\nActual genre: murder\nPredicted tag: ['violence'] \n\nMovie: Absolon\nActual genre: philosophical\nPredicted tag: ['flashback' 'murder' 'violence'] \n\nMovie: Dread\nActual genre: violence, cruelty, murder, flashback\nPredicted tag: ['flashback' 'murder' 'violence'] \n\n"
]
],
[
[
"<h2> 4.2 OneVsRestClassifier + SGDClassifier with LOG Loss :</h2>",
"_____no_output_____"
]
],
[
[
"sgl = SGDClassifier(loss='log', class_weight='balanced')\n\nclf = OneVsRestClassifier(sgl)\nclf.fit(X_train_multilabel, y_train_multilabel)",
"_____no_output_____"
],
[
"prediction14 = clf.predict(X_test_multilabel)\n\nprecision14 = precision_score(y_test_multilabel, prediction14, average='micro')\n\nrecall14 = recall_score(y_test_multilabel, prediction14, average='micro')\n\nf1_score14 = 2*((precision14 * recall14)/(precision14 + recall14))\n\nprint(\"precision14: {:.4f}, recall14: {:.4f}, F1-measure: {:.4f}\".format(precision14, recall14, f1_score14))",
"precision14: 0.5068, recall14: 0.6864, F1-measure: 0.5831\n"
],
[
"for i in range(5):\n k = test.sample(1).index[0]\n print(\"Movie: \", test['title'][k]) \n print(\"Actual genre: \",y_test[k])\n print(\"Predicted tag: \", cnt_vectorizer.inverse_transform(prediction14[k])[0],\"\\n\")",
"Movie: The Spanish Main\nActual genre: intrigue, action, violence\nPredicted tag: ['violence'] \n\nMovie: The Importance of Being Earnest\nActual genre: romantic\nPredicted tag: [] \n\nMovie: Anastasia\nActual genre: romantic, cute, entertaining\nPredicted tag: ['flashback'] \n\nMovie: Flawless\nActual genre: violence, romantic, murder, storytelling\nPredicted tag: ['flashback' 'murder'] \n\nMovie: 8MM\nActual genre: mystery, cruelty, murder, neo noir, cult, revenge, violence, suspenseful, sadist\nPredicted tag: ['murder' 'violence'] \n\n"
]
],
[
[
"<h2> 4.3 OneVsRestClassifier + SGDClassifier with HINGE Loss : </h2>",
"_____no_output_____"
]
],
[
[
"sgh = SGDClassifier(loss='hinge', class_weight='balanced')\n\nclf = OneVsRestClassifier(sgh)\nclf.fit(X_train_multilabel, y_train_multilabel)",
"_____no_output_____"
],
[
"prediction15 = clf.predict(X_test_multilabel)\n\nprecision15 = precision_score(y_test_multilabel, prediction15, average='micro')\n\nrecall15 = recall_score(y_test_multilabel, prediction15, average='micro')\n\nf1_score15 = 2*((precision15 * recall15)/(precision15 + recall15))\n\nprint(\"precision15: {:.4f}, recall15: {:.4f}, F1-measure: {:.4f}\".format(precision15, recall15, f1_score15))",
"precision15: 0.4954, recall15: 0.6891, F1-measure: 0.5764\n"
],
[
"for i in range(5):\n k = test.sample(1).index[0]\n print(\"Movie: \", test['title'][k]) \n print(\"Actual genre: \",y_test[k])\n print(\"Predicted tag: \", cnt_vectorizer.inverse_transform(prediction15[k])[0],\"\\n\")",
"Movie: Elizabeth: The Golden Age\nActual genre: intrigue\nPredicted tag: ['murder'] \n\nMovie: Dishonored 2\nActual genre: sci-fi\nPredicted tag: ['murder' 'violence'] \n\nMovie: In Your Eyes\nActual genre: paranormal, romantic, fantasy, mystery\nPredicted tag: [] \n\nMovie: Final Fantasy: The Spirits Within\nActual genre: psychedelic, romantic, flashback\nPredicted tag: ['violence'] \n\nMovie: From A to Z-Z-Z-Z\nActual genre: psychedelic\nPredicted tag: [] \n\n"
]
],
[
[
"<h2> 4.4 OneVsRestClassifier + LogisticRegression:</h2>",
"_____no_output_____"
]
],
[
[
"lr = LogisticRegression(class_weight='balanced')\n\nclf = OneVsRestClassifier(lr)\nclf.fit(X_train_multilabel, y_train_multilabel)",
"_____no_output_____"
],
[
"prediction16 = clf.predict(X_test_multilabel)\n\nprecision16 = precision_score(y_test_multilabel, prediction16, average='micro')\n\nrecall16 = recall_score(y_test_multilabel, prediction16, average='micro')\n\nf1_score16 = 2*((precision16 * recall16)/(precision16 + recall16))\n\nprint(\"precision16: {:.4f}, recall16: {:.4f}, F1-measure: {:.4f}\".format(precision16, recall16, f1_score16))",
"precision16: 0.5081, recall16: 0.6848, F1-measure: 0.5834\n"
],
[
"for i in range(5):\n k = test.sample(1).index[0]\n print(\"Movie: \", test['title'][k]) \n print(\"Actual genre: \",y_test[k])\n print(\"Predicted tag: \", cnt_vectorizer.inverse_transform(prediction16[k])[0],\"\\n\")",
"Movie: Red Sky\nActual genre: violence, murder\nPredicted tag: [] \n\nMovie: Last Summer\nActual genre: violence, cruelty, romantic\nPredicted tag: [] \n\nMovie: Real Life\nActual genre: satire\nPredicted tag: [] \n\nMovie: One Crazy Summer\nActual genre: psychedelic\nPredicted tag: [] \n\nMovie: Mumsy, Nanny, Sonny & Girly\nActual genre: insanity, cult, murder\nPredicted tag: [] \n\n"
]
],
[
[
"<h1> Conclusion: </h1>",
"_____no_output_____"
]
],
[
[
"from prettytable import PrettyTable\n\ntabel = PrettyTable()\n\ntabel.field_names=['Model','Vectorizer','ngrams','Precision','recall','f1_score']\n\n\n\ntabel.add_row(['MultinomialNB', 'TfidfVectorizer', '(1, 1)', round(precision1, 3),round(recall1, 3), round(f1_score1, 3)])\n\ntabel.add_row(['SGDClassifier(log)', 'TfidfVectorizer', '(1, 1)', round(precision2, 3), round(recall2, 3), round(f1_score2, 3)])\n\ntabel.add_row(['SGDClassifier(hinge)','TfidfVectorizer','(1, 1)' ,round(precision3, 3), round(recall3, 3), round(f1_score3, 3)])\n\ntabel.add_row(['LogisticRegression','TfidfVectorizer','(1, 1)', round(precision4, 3), round(recall4, 3), round(f1_score4, 3)])\n\ntabel.add_row(['','','','','',''])\ntabel.add_row(['','','','','',''])\n\n\ntabel.add_row(['MultinomialNB', 'TfidfVectorizer', '(1, 2)', round(precision5, 3), round(recall5, 3), round(f1_score5, 3)])\n\ntabel.add_row(['SGDClassifier(log)', 'TfidfVectorizer', '(1, 2)', round(precision6, 3), round(recall6, 3), round(f1_score6, 3)])\n\ntabel.add_row(['SGDClassifier(hinge)','TfidfVectorizer','(1, 2)', round(precision7, 3), round(recall7, 3), round(f1_score7, 3)])\n\ntabel.add_row(['LogisticRegression','TfidfVectorizer','(1, 2)', round(precision8, 3), round(recall8, 3), round(f1_score8, 3)])\n\ntabel.add_row(['','','','','',''])\ntabel.add_row(['','','','','',''])\n\n\ntabel.add_row(['MultinomialNB', 'TfidfVectorizer', '(1, 3)', round(precision9, 3), round(recall9, 3), round(f1_score9, 3)])\n\ntabel.add_row(['SGDClassifier(log)', 'TfidfVectorizer', '(1, 3)', round(precision10, 3), round(recall10, 3), round(f1_score10, 3)])\n\ntabel.add_row(['SGDClassifier(hinge)','TfidfVectorizer','(1, 3)', round(precision11, 3), round(recall11, 3), round(f1_score11, 3)])\n\ntabel.add_row(['LogisticRegression','TfidfVectorizer','(1, 3)', round(precision12, 3), round(recall12, 3), round(f1_score12, 3)])\n\ntabel.add_row(['','','','','',''])\ntabel.add_row(['','','','','',''])\n\ntabel.add_row(['MultinomialNB', 'TfidfVectorizer', '(1, 4)', round(precision13, 3), round(recall13, 3), round(f1_score13, 3)])\n\ntabel.add_row(['SGDClassifier(log)', 'TfidfVectorizer', '(1, 4)', round(precision14, 3), round(recall14, 3), round(f1_score14, 3)])\n\ntabel.add_row(['SGDClassifier(hinge)','TfidfVectorizer','(1, 4)', round(precision15, 3), round(recall15, 3), round(f1_score15, 3)])\n\ntabel.add_row(['LogisticRegression','TfidfVectorizer','(1, 4)', round(precision16, 3), round(recall16, 3), round(f1_score16, 3)])\n\n\n\nprint(tabel)",
"+----------------------+-----------------+--------+-----------+--------+----------+\n| Model | Vectorizer | ngrams | Precision | recall | f1_score |\n+----------------------+-----------------+--------+-----------+--------+----------+\n| MultinomialNB | TfidfVectorizer | (1, 1) | 0.467 | 0.686 | 0.556 |\n| SGDClassifier(log) | TfidfVectorizer | (1, 1) | 0.506 | 0.668 | 0.576 |\n| SGDClassifier(hinge) | TfidfVectorizer | (1, 1) | 0.511 | 0.661 | 0.576 |\n| LogisticRegression | TfidfVectorizer | (1, 1) | 0.508 | 0.684 | 0.583 |\n| | | | | | |\n| | | | | | |\n| MultinomialNB | TfidfVectorizer | (1, 2) | 0.468 | 0.686 | 0.556 |\n| SGDClassifier(log) | TfidfVectorizer | (1, 2) | 0.516 | 0.678 | 0.586 |\n| SGDClassifier(hinge) | TfidfVectorizer | (1, 2) | 0.491 | 0.702 | 0.578 |\n| LogisticRegression | TfidfVectorizer | (1, 2) | 0.508 | 0.685 | 0.583 |\n| | | | | | |\n| | | | | | |\n| MultinomialNB | TfidfVectorizer | (1, 3) | 0.468 | 0.686 | 0.556 |\n| SGDClassifier(log) | TfidfVectorizer | (1, 3) | 0.517 | 0.669 | 0.583 |\n| SGDClassifier(hinge) | TfidfVectorizer | (1, 3) | 0.496 | 0.686 | 0.576 |\n| LogisticRegression | TfidfVectorizer | (1, 3) | 0.508 | 0.685 | 0.583 |\n| | | | | | |\n| | | | | | |\n| MultinomialNB | TfidfVectorizer | (1, 4) | 0.468 | 0.686 | 0.556 |\n| SGDClassifier(log) | TfidfVectorizer | (1, 4) | 0.507 | 0.686 | 0.583 |\n| SGDClassifier(hinge) | TfidfVectorizer | (1, 4) | 0.495 | 0.689 | 0.576 |\n| LogisticRegression | TfidfVectorizer | (1, 4) | 0.508 | 0.685 | 0.583 |\n+----------------------+-----------------+--------+-----------+--------+----------+\n"
]
],
[
[
"<h1>5. Word2Vec</h1>",
"_____no_output_____"
]
],
[
[
"X_train_new = []\n\nfor i in tqdm(range(len(list(X_train)))):\n X_train_new.append(X_train[i].split(\" \"))",
"100%|█████████████████████████████████████████████████████████████████████████| 10989/10989 [00:00<00:00, 12660.62it/s]\n"
],
[
"with open('glove.6B.300d.pkl', 'rb') as f:\n new_model = pickle.load(f)\n words = set(new_model.keys())",
"_____no_output_____"
],
[
"X_train_multilabel = []; # the avg-w2v for each sentence/review is stored in this list\nfor sentence in tqdm(X_train.values): # for each review/sentence\n vector = np.zeros(300) # as word vectors are of zero length\n cnt_words =0; # num of words with a valid vector in the sentence/review\n for word in sentence.split():\n if word in words:\n vector += new_model[word]\n cnt_words += 1\n if cnt_words != 0:\n vector /= cnt_words\n X_train_multilabel.append(vector)",
"100%|███████████████████████████████████████████████████████████████████████████| 10989/10989 [00:11<00:00, 939.76it/s]\n"
],
[
"X_test_multilabel = []; # the avg-w2v for each sentence/review is stored in this list\nfor sentence in tqdm(X_test.values): # for each review/sentence\n vector = np.zeros(300) # as word vectors are of zero length\n cnt_words =0; # num of words with a valid vector in the sentence/review\n for word in sentence.split():\n if word in words:\n vector += new_model[word]\n cnt_words += 1\n if cnt_words != 0:\n vector /= cnt_words\n X_test_multilabel.append(vector)",
"100%|█████████████████████████████████████████████████████████████████████████████| 2768/2768 [00:03<00:00, 877.01it/s]\n"
]
],
[
[
"<H2> 5.1 OneVsRestClassifier + SGDClassifier with LOG Loss :</H2>",
"_____no_output_____"
]
],
[
[
"sgl = SGDClassifier(loss='log', class_weight='balanced')\n\nclf = OneVsRestClassifier(sgl)\nclf.fit(X_train_multilabel, y_train_multilabel)",
"_____no_output_____"
],
[
"prediction17 = clf.predict(X_test_multilabel)\n\nprecision17 = precision_score(y_test_multilabel, prediction17, average='micro')\n\nrecall17 = recall_score(y_test_multilabel, prediction17, average='micro')\n\nf1_score17 = 2*((precision17 * recall17)/(precision17 + recall17))\n\nprint(\"precision17: {:.4f}, recall17: {:.4f}, F1-measure: {:.4f}\".format(precision17, recall17, f1_score17))",
"precision17: 0.4235, recall17: 0.7881, F1-measure: 0.5509\n"
],
[
"for i in range(5):\n k = test.sample(1).index[0]\n print(\"Movie: \", test['title'][k]) \n print(\"Actual genre: \",y_test[k])\n print(\"Predicted tag: \", cnt_vectorizer.inverse_transform(prediction17[k])[0],\"\\n\")",
"Movie: Topper\nActual genre: comedy\nPredicted tag: [] \n\nMovie: La otra\nActual genre: murder, melodrama\nPredicted tag: ['flashback' 'murder'] \n\nMovie: Conan the Destroyer\nActual genre: murder, cult, fantasy, alternate history, violence\nPredicted tag: ['violence'] \n\nMovie: Magnificent Obsession\nActual genre: melodrama, flashback\nPredicted tag: ['flashback'] \n\nMovie: Lilja 4-ever\nActual genre: tragedy, violence, depressing\nPredicted tag: ['flashback' 'murder' 'violence'] \n\n"
]
],
[
[
"<h2> 5.2 OneVsRestClassifier + SGDClassifier with HINGE Loss : </h2>",
"_____no_output_____"
]
],
[
[
"sgh = SGDClassifier(loss='hinge', class_weight='balanced')\n\nclf = OneVsRestClassifier(sgh)\nclf.fit(X_train_multilabel, y_train_multilabel)",
"_____no_output_____"
],
[
"prediction18 = clf.predict(X_test_multilabel)\n\nprecision18 = precision_score(y_test_multilabel, prediction18, average='micro')\n\nrecall18 = recall_score(y_test_multilabel, prediction18, average='micro')\n\nf1_score18 = 2*((precision18 * recall18)/(precision18 + recall18))\n\nprint(\"precision18: {:.4f}, recall18: {:.4f}, F1-measure: {:.4f}\".format(precision18, recall18, f1_score18))",
"precision18: 0.4624, recall18: 0.6903, F1-measure: 0.5539\n"
],
[
"for i in range(5):\n k = test.sample(1).index[0]\n print(\"Movie: \", test['title'][k]) \n print(\"Actual genre: \",y_test[k])\n print(\"Predicted tag: \", cnt_vectorizer.inverse_transform(prediction18[k])[0],\"\\n\")",
"Movie: Orange County\nActual genre: flashback\nPredicted tag: [] \n\nMovie: Mo' Money\nActual genre: murder\nPredicted tag: ['flashback' 'murder' 'violence'] \n\nMovie: Serbuan maut\nActual genre: cult, suspenseful, murder, violence, flashback\nPredicted tag: ['murder' 'violence'] \n\nMovie: Dog Park\nActual genre: romantic\nPredicted tag: [] \n\nMovie: Aan\nActual genre: romantic\nPredicted tag: [] \n\n"
]
],
[
[
"<h2> 5.3 OneVsRestClassifier + LogisticRegression:</h2>",
"_____no_output_____"
]
],
[
[
"lr = LogisticRegression(class_weight='balanced')\n\nclf = OneVsRestClassifier(lr)\nclf.fit(X_train_multilabel, y_train_multilabel)",
"_____no_output_____"
],
[
"prediction19 = clf.predict(X_test_multilabel)\n\nprecision19 = precision_score(y_test_multilabel, prediction19, average='micro')\n\nrecall19 = recall_score(y_test_multilabel, prediction19, average='micro')\n\nf1_score19 = 2*((precision19 * recall19)/(precision19 + recall19))\n\nprint(\"precision19: {:.4f}, recall19: {:.4f}, F1-measure: {:.4f}\".format(precision19, recall19, f1_score19))",
"precision19: 0.4765, recall19: 0.6864, F1-measure: 0.5625\n"
],
[
"for i in range(5):\n k = test.sample(1).index[0]\n print(\"Movie: \", test['title'][k]) \n print(\"Actual genre: \",y_test[k])\n print(\"Predicted tag: \", cnt_vectorizer.inverse_transform(prediction19[k])[0],\"\\n\")",
"Movie: In the Line of Fire\nActual genre: suspenseful, neo noir, murder, mystery, violence, revenge, flashback, good versus evil, humor, action, romantic\nPredicted tag: ['flashback' 'murder' 'violence'] \n\nMovie: Huang jia shi jie\nActual genre: violence\nPredicted tag: ['murder'] \n\nMovie: The Mirror Crack'd\nActual genre: melodrama, mystery, satire, murder, flashback\nPredicted tag: ['flashback' 'murder'] \n\nMovie: Troll\nActual genre: fantasy\nPredicted tag: ['violence'] \n\nMovie: Doragon bôru Z: Ginga girigiri!! Butchigiri no sugoi yatsu\nActual genre: violence\nPredicted tag: ['violence'] \n\n"
]
],
[
[
"<h1>Conclusion</h1>",
"_____no_output_____"
]
],
[
[
"from prettytable import PrettyTable\n\ntabel = PrettyTable()\n\ntabel.field_names=['Model', 'Vectorizer', 'Precision','recall','f1_score']\n\n\ntabel.add_row(['SGDClassifier(log)', 'AVG W2V', round(precision17, 3), round(recall17, 3), round(f1_score17, 3)])\n\ntabel.add_row(['SGDClassifier(hinge)','AVG W2V', round(precision18, 3), round(recall18, 3), round(f1_score18, 3)])\n\ntabel.add_row(['LogisticRegression','AVG W2V', round(precision19, 3), round(recall19, 3), round(f1_score19, 3)])\n\n\nprint(tabel)",
"+----------------------+------------+-----------+--------+----------+\n| Model | Vectorizer | Precision | recall | f1_score |\n+----------------------+------------+-----------+--------+----------+\n| SGDClassifier(log) | AVG W2V | 0.423 | 0.788 | 0.551 |\n| SGDClassifier(hinge) | AVG W2V | 0.462 | 0.69 | 0.554 |\n| LogisticRegression | AVG W2V | 0.476 | 0.686 | 0.562 |\n+----------------------+------------+-----------+--------+----------+\n"
]
],
[
[
"<h1>6. LSTM-CNN Model</h1>",
"_____no_output_____"
]
],
[
[
"max_review_length = 400\nX_train = sequence.pad_sequences(X_train_multilabel, maxlen=max_review_length, padding='post')\nX_test = sequence.pad_sequences(X_test_multilabel, maxlen=max_review_length, padding='post')",
"_____no_output_____"
],
[
"inputt = 8252\nbatch_size = 32\nepochs = 10",
"_____no_output_____"
],
[
"model =Sequential()\n\nmodel.add(Embedding(inputt, 50, input_length=max_review_length))\n\nmodel.add(LSTM(100, return_sequences=True))\n\nmodel.add(Dropout(0.2))\n\nmodel.add(BatchNormalization())\n\nmodel.add(LSTM(100, return_sequences=True))\n\nmodel.add(Dropout(0.2))\n\nmodel.add(BatchNormalization())\n\nmodel.add(LSTM(100, return_sequences=True))\n\nmodel.add(Dropout(0.2))\n\nmodel.add(Activation('relu'))\n\nmodel.add(BatchNormalization())\n\nmodel.add(GlobalMaxPooling1D())\n\nmodel.add(Dense(3, activation='sigmoid'))\n\nprint(model.summary())",
"Model: \"sequential_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nembedding_1 (Embedding) (None, 400, 50) 412600 \n_________________________________________________________________\nlstm_1 (LSTM) (None, 400, 100) 60400 \n_________________________________________________________________\ndropout_1 (Dropout) (None, 400, 100) 0 \n_________________________________________________________________\nbatch_normalization_1 (Batch (None, 400, 100) 400 \n_________________________________________________________________\nlstm_2 (LSTM) (None, 400, 100) 80400 \n_________________________________________________________________\ndropout_2 (Dropout) (None, 400, 100) 0 \n_________________________________________________________________\nbatch_normalization_2 (Batch (None, 400, 100) 400 \n_________________________________________________________________\nlstm_3 (LSTM) (None, 400, 100) 80400 \n_________________________________________________________________\ndropout_3 (Dropout) (None, 400, 100) 0 \n_________________________________________________________________\nactivation_1 (Activation) (None, 400, 100) 0 \n_________________________________________________________________\nbatch_normalization_3 (Batch (None, 400, 100) 400 \n_________________________________________________________________\nglobal_max_pooling1d_1 (Glob (None, 100) 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 3) 303 \n=================================================================\nTotal params: 635,303\nTrainable params: 634,703\nNon-trainable params: 600\n_________________________________________________________________\nNone\n"
],
[
"model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])",
"_____no_output_____"
],
[
"model.fit(X_train, y_train_multilabel, \n batch_size = batch_size,\n validation_data=(X_test, y_test_multilabel),\n epochs=epochs)",
"WARNING:tensorflow:From C:\\ProgramData\\Anaconda3\\lib\\site-packages\\tensorflow\\python\\ops\\math_grad.py:1250: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse tf.where in 2.0, which has the same broadcast rule as np.where\nWARNING:tensorflow:From C:\\ProgramData\\Anaconda3\\lib\\site-packages\\keras\\backend\\tensorflow_backend.py:422: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead.\n\nTrain on 10989 samples, validate on 2768 samples\nEpoch 1/10\n10989/10989 [==============================] - 664s 60ms/step - loss: 0.9664 - accuracy: 0.2839 - val_loss: 0.9825 - val_accuracy: 0.2840\nEpoch 2/10\n10989/10989 [==============================] - 658s 60ms/step - loss: 0.9637 - accuracy: 0.2856 - val_loss: 0.9757 - val_accuracy: 0.2840\nEpoch 3/10\n10989/10989 [==============================] - 658s 60ms/step - loss: 0.9592 - accuracy: 0.2856 - val_loss: 1.0022 - val_accuracy: 0.2840\nEpoch 4/10\n10989/10989 [==============================] - 656s 60ms/step - loss: 0.9593 - accuracy: 0.2856 - val_loss: 0.9749 - val_accuracy: 0.2840\nEpoch 5/10\n10989/10989 [==============================] - 654s 60ms/step - loss: 0.9567 - accuracy: 0.2856 - val_loss: 0.9732 - val_accuracy: 0.2840\nEpoch 6/10\n10989/10989 [==============================] - 653s 59ms/step - loss: 0.9575 - accuracy: 0.2856 - val_loss: 0.9680 - val_accuracy: 0.2840\nEpoch 7/10\n10989/10989 [==============================] - 651s 59ms/step - loss: 0.9553 - accuracy: 0.2856 - val_loss: 0.9700 - val_accuracy: 0.2840\nEpoch 8/10\n10989/10989 [==============================] - 652s 59ms/step - loss: 0.9552 - accuracy: 0.2856 - val_loss: 1.0163 - val_accuracy: 0.6105\nEpoch 9/10\n10989/10989 [==============================] - 650s 59ms/step - loss: 0.9534 - accuracy: 0.2856 - val_loss: 0.9665 - val_accuracy: 0.2840\nEpoch 10/10\n10989/10989 [==============================] - 650s 59ms/step - loss: 0.9531 - accuracy: 0.2856 - val_loss: 0.9675 - val_accuracy: 0.2840\n"
],
[
"test_loss, test_acc = model.evaluate(X_test, y_test_multilabel, verbose=2)\n\nprint('\\nTest accuracy:', test_acc)",
"\nTest accuracy: 0.2839595377445221\n"
],
[
"model.save('lstm_model_top3.h5') #Saving the Model for Future Use",
"_____no_output_____"
],
[
"model = load_model('lstm_model_top3.h5') #Loading the Model",
"_____no_output_____"
],
[
"model_prediction = model.predict(X_test, verbose=0)",
"_____no_output_____"
],
[
"for i in range(5):\n k = test.sample(1).index[0]\n print(\"Movie: \", test['title'][k]) \n print(\"Actual genre: \", y_test[k])\n print(\"Predicted tag: \", cnt_vectorizer.inverse_transform(model_prediction[k])[0],\"\\n\")",
"Movie: Beyond Tomorrow\nActual genre: romantic, murder\nPredicted tag: ['flashback' 'murder' 'violence'] \n\nMovie: Rabbit's Kin\nActual genre: psychedelic\nPredicted tag: ['flashback' 'murder' 'violence'] \n\nMovie: Zerophilia\nActual genre: pornographic\nPredicted tag: ['flashback' 'murder' 'violence'] \n\nMovie: Austin Powers: International Man of Mystery\nActual genre: comedy, boring, cult, good versus evil, psychedelic, humor, satire, revenge, entertaining\nPredicted tag: ['flashback' 'murder' 'violence'] \n\nMovie: The Lost World\nActual genre: revenge\nPredicted tag: ['flashback' 'murder' 'violence'] \n\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e77cfc3b778d8665a33d22d2703cbf09116e0054 | 30,823 | ipynb | Jupyter Notebook | examples/agaricus.ipynb | jpjuvo/wideboost | ba2ec3bc62d70aecce3c2728197ac6abd011a434 | [
"MIT"
] | 11 | 2020-07-22T18:40:03.000Z | 2022-02-18T13:43:02.000Z | examples/agaricus.ipynb | jpjuvo/wideboost | ba2ec3bc62d70aecce3c2728197ac6abd011a434 | [
"MIT"
] | 3 | 2020-10-31T01:45:27.000Z | 2021-04-02T07:37:21.000Z | examples/agaricus.ipynb | jpjuvo/wideboost | ba2ec3bc62d70aecce3c2728197ac6abd011a434 | [
"MIT"
] | 2 | 2020-09-15T15:13:36.000Z | 2020-10-28T06:11:19.000Z | 95.723602 | 17,684 | 0.813873 | [
[
[
"import numpy as np\nimport xgboost as xgb\nfrom wideboost.wrappers import wxgb\n\nfrom matplotlib import pyplot as plt",
"_____no_output_____"
],
[
"dtrain = xgb.DMatrix('../../xgboost/demo/data/agaricus.txt.train')\ndtest = xgb.DMatrix('../../xgboost/demo/data/agaricus.txt.test')",
"[14:26:15] 6513x127 matrix with 143286 entries loaded from ../../xgboost/demo/data/agaricus.txt.train\n[14:26:15] 1611x127 matrix with 35442 entries loaded from ../../xgboost/demo/data/agaricus.txt.test\n"
],
[
"param = {'max_depth':2, 'eta':0.1, 'objective':'binary:logistic','eval_metric':['error'] }\nnum_round = 50\nwatchlist = [(dtrain,'train'),(dtest,'test')]\nxgb_results = dict()\nbst = xgb.train(param, dtrain, num_round,watchlist,evals_result=xgb_results)",
"[0]\ttrain-error:0.04652\ttest-error:0.04283\n[1]\ttrain-error:0.04161\ttest-error:0.04035\n[2]\ttrain-error:0.04652\ttest-error:0.04283\n[3]\ttrain-error:0.04161\ttest-error:0.04035\n[4]\ttrain-error:0.04161\ttest-error:0.04035\n[5]\ttrain-error:0.04161\ttest-error:0.04035\n[6]\ttrain-error:0.02334\ttest-error:0.02483\n[7]\ttrain-error:0.04161\ttest-error:0.04035\n[8]\ttrain-error:0.04161\ttest-error:0.04035\n[9]\ttrain-error:0.02334\ttest-error:0.02483\n[10]\ttrain-error:0.00599\ttest-error:0.00559\n[11]\ttrain-error:0.01735\ttest-error:0.01924\n[12]\ttrain-error:0.01735\ttest-error:0.01924\n[13]\ttrain-error:0.01735\ttest-error:0.01924\n[14]\ttrain-error:0.01735\ttest-error:0.01924\n[15]\ttrain-error:0.01735\ttest-error:0.01924\n[16]\ttrain-error:0.01735\ttest-error:0.01924\n[17]\ttrain-error:0.01735\ttest-error:0.01924\n[18]\ttrain-error:0.01336\ttest-error:0.01552\n[19]\ttrain-error:0.02150\ttest-error:0.02731\n[20]\ttrain-error:0.02150\ttest-error:0.02731\n[21]\ttrain-error:0.02150\ttest-error:0.02731\n[22]\ttrain-error:0.02150\ttest-error:0.02731\n[23]\ttrain-error:0.02150\ttest-error:0.02731\n[24]\ttrain-error:0.02150\ttest-error:0.02731\n[25]\ttrain-error:0.02150\ttest-error:0.02731\n[26]\ttrain-error:0.02150\ttest-error:0.02731\n[27]\ttrain-error:0.02150\ttest-error:0.02731\n[28]\ttrain-error:0.02150\ttest-error:0.02731\n[29]\ttrain-error:0.02150\ttest-error:0.02731\n[30]\ttrain-error:0.02150\ttest-error:0.02731\n[31]\ttrain-error:0.01336\ttest-error:0.01552\n[32]\ttrain-error:0.02150\ttest-error:0.02731\n[33]\ttrain-error:0.02150\ttest-error:0.02731\n[34]\ttrain-error:0.02150\ttest-error:0.02731\n[35]\ttrain-error:0.01013\ttest-error:0.01366\n[36]\ttrain-error:0.00200\ttest-error:0.00186\n[37]\ttrain-error:0.00200\ttest-error:0.00186\n[38]\ttrain-error:0.01013\ttest-error:0.01366\n[39]\ttrain-error:0.01013\ttest-error:0.01366\n[40]\ttrain-error:0.01013\ttest-error:0.01366\n[41]\ttrain-error:0.00200\ttest-error:0.00186\n[42]\ttrain-error:0.00200\ttest-error:0.00186\n[43]\ttrain-error:0.00200\ttest-error:0.00186\n[44]\ttrain-error:0.00200\ttest-error:0.00186\n[45]\ttrain-error:0.00200\ttest-error:0.00186\n[46]\ttrain-error:0.00200\ttest-error:0.00186\n[47]\ttrain-error:0.00200\ttest-error:0.00186\n[48]\ttrain-error:0.00200\ttest-error:0.00186\n[49]\ttrain-error:0.00200\ttest-error:0.00186\n"
],
[
"## Matches xgboost when there are zero extra dimensions\nparam['btype'] = 'I'\nparam['extra_dims'] = 0\nwbst = wxgb.train(param, dtrain, num_round,watchlist)",
"Overwriting param `num_class`\nOverwriting param `objective` while setting `obj` in train.\nTaking first argument of eval_metric. Multiple evals not supported using xgboost backend.\nMoving param `eval_metric` to an feval.\nSetting param `disable_default_eval_metric` to 1.\n[14:26:15] WARNING: /Users/travis/build/dmlc/xgboost/src/learner.cc:480: \nParameters: { btype } might not be used.\n\n This may not be accurate due to some parameters are only used in language bindings but\n passed down to XGBoost core. Or some parameters are not used but slip through this\n verification. Please open an issue if you find above cases.\n\n\n[0]\ttrain-error:0.04652\ttest-error:0.04283\n[1]\ttrain-error:0.04161\ttest-error:0.04035\n[2]\ttrain-error:0.04652\ttest-error:0.04283\n[3]\ttrain-error:0.04161\ttest-error:0.04035\n[4]\ttrain-error:0.04161\ttest-error:0.04035\n[5]\ttrain-error:0.04161\ttest-error:0.04035\n[6]\ttrain-error:0.02334\ttest-error:0.02483\n[7]\ttrain-error:0.04161\ttest-error:0.04035\n[8]\ttrain-error:0.04161\ttest-error:0.04035\n[9]\ttrain-error:0.02334\ttest-error:0.02483\n[10]\ttrain-error:0.00599\ttest-error:0.00559\n[11]\ttrain-error:0.01735\ttest-error:0.01924\n[12]\ttrain-error:0.01735\ttest-error:0.01924\n[13]\ttrain-error:0.01735\ttest-error:0.01924\n[14]\ttrain-error:0.01735\ttest-error:0.01924\n[15]\ttrain-error:0.01735\ttest-error:0.01924\n[16]\ttrain-error:0.01735\ttest-error:0.01924\n[17]\ttrain-error:0.01735\ttest-error:0.01924\n[18]\ttrain-error:0.01336\ttest-error:0.01552\n[19]\ttrain-error:0.02150\ttest-error:0.02731\n[20]\ttrain-error:0.02150\ttest-error:0.02731\n[21]\ttrain-error:0.02150\ttest-error:0.02731\n[22]\ttrain-error:0.02150\ttest-error:0.02731\n[23]\ttrain-error:0.02150\ttest-error:0.02731\n[24]\ttrain-error:0.02150\ttest-error:0.02731\n[25]\ttrain-error:0.02150\ttest-error:0.02731\n[26]\ttrain-error:0.02150\ttest-error:0.02731\n[27]\ttrain-error:0.02150\ttest-error:0.02731\n[28]\ttrain-error:0.02150\ttest-error:0.02731\n[29]\ttrain-error:0.02150\ttest-error:0.02731\n[30]\ttrain-error:0.02150\ttest-error:0.02731\n[31]\ttrain-error:0.01336\ttest-error:0.01552\n[32]\ttrain-error:0.02150\ttest-error:0.02731\n[33]\ttrain-error:0.02150\ttest-error:0.02731\n[34]\ttrain-error:0.02150\ttest-error:0.02731\n[35]\ttrain-error:0.01013\ttest-error:0.01366\n[36]\ttrain-error:0.00200\ttest-error:0.00186\n[37]\ttrain-error:0.00200\ttest-error:0.00186\n[38]\ttrain-error:0.01013\ttest-error:0.01366\n[39]\ttrain-error:0.01013\ttest-error:0.01366\n[40]\ttrain-error:0.01013\ttest-error:0.01366\n[41]\ttrain-error:0.00200\ttest-error:0.00186\n[42]\ttrain-error:0.00200\ttest-error:0.00186\n[43]\ttrain-error:0.00200\ttest-error:0.00186\n[44]\ttrain-error:0.00200\ttest-error:0.00186\n[45]\ttrain-error:0.00200\ttest-error:0.00186\n[46]\ttrain-error:0.00200\ttest-error:0.00186\n[47]\ttrain-error:0.00200\ttest-error:0.00186\n[48]\ttrain-error:0.00200\ttest-error:0.00186\n[49]\ttrain-error:0.00200\ttest-error:0.00186\n"
],
[
"param['extra_dims'] = 2\ned1_results = dict()\nwbst = wxgb.train(param, dtrain, num_round,watchlist,evals_result=ed1_results)",
"Overwriting param `num_class`\nOverwriting param `objective` while setting `obj` in train.\nTaking first argument of eval_metric. Multiple evals not supported using xgboost backend.\nMoving param `eval_metric` to an feval.\nSetting param `disable_default_eval_metric` to 1.\n[14:26:16] WARNING: /Users/travis/build/dmlc/xgboost/src/learner.cc:480: \nParameters: { btype } might not be used.\n\n This may not be accurate due to some parameters are only used in language bindings but\n passed down to XGBoost core. Or some parameters are not used but slip through this\n verification. Please open an issue if you find above cases.\n\n\n[0]\ttrain-error:0.04652\ttest-error:0.04283\n[1]\ttrain-error:0.04652\ttest-error:0.04283\n[2]\ttrain-error:0.02334\ttest-error:0.02483\n[3]\ttrain-error:0.04161\ttest-error:0.04035\n[4]\ttrain-error:0.01735\ttest-error:0.01924\n[5]\ttrain-error:0.02226\ttest-error:0.02173\n[6]\ttrain-error:0.01735\ttest-error:0.01924\n[7]\ttrain-error:0.02549\ttest-error:0.03104\n[8]\ttrain-error:0.02150\ttest-error:0.02731\n[9]\ttrain-error:0.02150\ttest-error:0.02731\n[10]\ttrain-error:0.02150\ttest-error:0.02731\n[11]\ttrain-error:0.02150\ttest-error:0.02731\n[12]\ttrain-error:0.02150\ttest-error:0.02731\n[13]\ttrain-error:0.01013\ttest-error:0.01366\n[14]\ttrain-error:0.00200\ttest-error:0.00186\n[15]\ttrain-error:0.00200\ttest-error:0.00186\n[16]\ttrain-error:0.00200\ttest-error:0.00186\n[17]\ttrain-error:0.00200\ttest-error:0.00186\n[18]\ttrain-error:0.00200\ttest-error:0.00186\n[19]\ttrain-error:0.00200\ttest-error:0.00186\n[20]\ttrain-error:0.00200\ttest-error:0.00186\n[21]\ttrain-error:0.00200\ttest-error:0.00186\n[22]\ttrain-error:0.00200\ttest-error:0.00186\n[23]\ttrain-error:0.00200\ttest-error:0.00186\n[24]\ttrain-error:0.00200\ttest-error:0.00186\n[25]\ttrain-error:0.00200\ttest-error:0.00186\n[26]\ttrain-error:0.00200\ttest-error:0.00186\n[27]\ttrain-error:0.00200\ttest-error:0.00186\n[28]\ttrain-error:0.00200\ttest-error:0.00186\n[29]\ttrain-error:0.00200\ttest-error:0.00186\n[30]\ttrain-error:0.00200\ttest-error:0.00186\n[31]\ttrain-error:0.00200\ttest-error:0.00186\n[32]\ttrain-error:0.00200\ttest-error:0.00186\n[33]\ttrain-error:0.00200\ttest-error:0.00186\n[34]\ttrain-error:0.00200\ttest-error:0.00186\n[35]\ttrain-error:0.00200\ttest-error:0.00186\n[36]\ttrain-error:0.00200\ttest-error:0.00186\n[37]\ttrain-error:0.00123\ttest-error:0.00000\n[38]\ttrain-error:0.00123\ttest-error:0.00000\n[39]\ttrain-error:0.00123\ttest-error:0.00000\n[40]\ttrain-error:0.00123\ttest-error:0.00000\n[41]\ttrain-error:0.00123\ttest-error:0.00000\n[42]\ttrain-error:0.00123\ttest-error:0.00000\n[43]\ttrain-error:0.00123\ttest-error:0.00000\n[44]\ttrain-error:0.00123\ttest-error:0.00000\n[45]\ttrain-error:0.00123\ttest-error:0.00000\n[46]\ttrain-error:0.00123\ttest-error:0.00000\n[47]\ttrain-error:0.00123\ttest-error:0.00000\n[48]\ttrain-error:0.00123\ttest-error:0.00000\n[49]\ttrain-error:0.00123\ttest-error:0.00000\n"
],
[
"plt.plot(xgb_results['test']['error'])\nplt.plot(ed1_results['test']['error'])\nplt.show()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e77cfe9798ad5aa0b2c66c63fd10202b03a8bf22 | 68,750 | ipynb | Jupyter Notebook | notebooks/CDC Syphilis Serology Prioritization Algorithm Script v3.ipynb | CDCgov/Syphilis_Record_Search_and_Review_Algorithm | 9800480cce78b9a70ef0d09c699bfeeac8f81aab | [
"Apache-2.0"
] | 4 | 2021-12-09T17:41:48.000Z | 2022-01-28T18:30:02.000Z | notebooks/CDC Syphilis Serology Prioritization Algorithm Script v3.ipynb | CDCgov/Syphilis_Record_Search_and_Review_Algorithm | 9800480cce78b9a70ef0d09c699bfeeac8f81aab | [
"Apache-2.0"
] | null | null | null | notebooks/CDC Syphilis Serology Prioritization Algorithm Script v3.ipynb | CDCgov/Syphilis_Record_Search_and_Review_Algorithm | 9800480cce78b9a70ef0d09c699bfeeac8f81aab | [
"Apache-2.0"
] | null | null | null | 43.734097 | 1,954 | 0.522851 | [
[
[
"# Jupyter Notebook: Prioritization of Syphilis Serologies for Investigation (Modernizing the Syphilis Reactor Grid)",
"_____no_output_____"
],
[
"## Notes to keep in mind when using this notebook:\n\n* Please ignore the number on the left (that says \"In [x]\") when running these cells. When we refer to a cell number, look for it in the beginning of the cell body. \n",
"_____no_output_____"
],
[
"##### Cell number 1: This cell is for importing python libraries to support the codes that have been used in this Notebook.",
"_____no_output_____"
]
],
[
[
"# Cell number 1\n\nimport sys\nimport pandas as pd\nimport numpy as np\nimport os\nimport textwrap\nimport datetime as dt\n\nfrom collections import defaultdict\n\n# warning suppression\nimport warnings\nwarnings.filterwarnings('ignore')",
"_____no_output_____"
]
],
[
[
"##### Cell number 2: Jupyter Notebook cells output only 1 result by default. Lines 3-4 enable the cell to output all the results as an outcome of the script in the cell. This cell also holds several utility functions for the main algorithm loop. We've also included a convenience function to convert XLSX (excel) files to CSV files.",
"_____no_output_____"
]
],
[
[
"# Cell number 2\n\nfrom IPython.core.interactiveshell import InteractiveShell\nInteractiveShell.ast_node_interactivity = \"all\"\n\n### Utility Functions\n\n# cleans a column of strings by typecasting to str and stripping whitespace\ndef cleanstring(df, column):\n df[column] = df[column].astype(str) # converts column items into string\n df[column] = [x.strip() for x in df[column]] # removes any whitespace from the strings generated previously\n\n# these functions are used in the algorithm main loop towards the bottom of this notebook\ndef reactive_nTT(df:pd.DataFrame, col:str, R:str, W:str, U:str, P:str) -> pd.DataFrame:\n return df[(df[col] != R) & (df[col] != W) & (df[col] != U) & (df[col] != P)];\n\ndef step3_nonreactive_TT(df:pd.DataFrame, col:str, R:str, W:str, U:str, P:str) -> pd.DataFrame:\n return df[(df[col] == R) | (df[col] == W) | (df[col] == U) | (df[col] == P)];\n\ndef step4_TT(df:pd.DataFrame, col:str, filters:list) -> pd.DataFrame:\n return df[(df[col] == filters[0]) | (df[col] == filters[1]) | (df[col] == filters[2]) | (df[col] == filters[3]) | (df[col] == filters[4]) |\n (df[col] == filters[5]) | (df[col] == filters[6]) | (df[col] == filters[7]) | (df[col] == filters[8]) | (df[col] == filters[9])];\n######\n\n# converts a given excel file to a csv\ndef excel2csv(file, name):\n p = pd.read_excel(file)\n p.to_csv(f'{name}.csv', sep=\",\") ",
"_____no_output_____"
]
],
[
[
"##### Cell number 3: This is the script to import and read the CSV file. Please copy/paste the address of your file in place of \"Please enter your file path and file name here.csv\".\n\n##### This file is read into a DataFrame: `df_main`. It may take a while for the data to be read into `df_main`, so please wait for the cell to be fully executed before proceeding. ",
"_____no_output_____"
]
],
[
[
"#Cell number 3\ndf_main = pd.read_csv(\"Please enter your file path and file name here.csv\")",
"_____no_output_____"
]
],
[
[
"##### Cell number 4: Displays the column names of the imported file ( saved as `df_main`) and the first 5 lines of your uploaded dataframe",
"_____no_output_____"
]
],
[
[
"#Cell number 4\ndf_main_columns = df_main.columns\ndf_main.columns = [x.strip() for x in df_main.columns]\ndf_main.columns\ndf_main.head()",
"_____no_output_____"
]
],
[
[
"##### Cell number 5: This changes the column names for the dataframe. The DataFrame might contain more elements than is required for this algorithm. Those column names can be left as is. Please change the corresponding column names for the following data elements to:\n| Column Name | Data Element |\n| --- | --- |\n| `ID_Profile` | Unique identifier for an individual |\n| `Test` | Name of the test (e.g. VDRL, RPR, TP-AB, FTA-ABS) |\n| `DT_Specimen` | Date of the above test (specimen collected) |\n| `QuantitativeResult` | Quantitative result for test (titer) |\n| `QualitativeResult` | Qualitative result for test |\n| `CD_Gender` | Gender |\n| `Age` | Age (in years) |\n| `Disposition` | Disposition assigned |\n| `DT_Disposition` | Date the disposition was assigned by the DIS (or the STD program) |\n\n_Note: We require that age be in years. Please handle this yourself or email the maintainers for further assistance._\n\n##### For example, if the output of cell number 4 is: \n`['columnA', 'UniqueIdentifier', 'columnB', 'QualitativeResult','DateOfSpecimen', 'columnC', 'QuantitativeResult', 'NameOfTest', 'columnD','Gender',' Age', 'DS_Disposition','DT_Disposition']`\n\n##### Your code will be:\n`df_main.columns = ['columnA', 'ID_Profile', 'columnB', 'QualitativeResult' ,'DT_Specimen', 'columnC', 'QuantitativeResult', 'Test', 'columnD','CD_Gender', 'Age', 'Disposition','DT_Disposition']`\n\n##### Put any column renaming in the cell below:",
"_____no_output_____"
]
],
[
[
"#Cell number 5\ndf_main.columns\ndf_main.rename(columns={'DS_QualitativeResult':'QualitativeResult', 'DS_QuantitativeResult':'QuantitativeResult', 'DS_Test':'Test', 'DS_Disposition':'Disposition'}, inplace=True)\ndf_main.columns",
"_____no_output_____"
]
],
[
[
"###### Cell number 6: The CSV file does not have date attributes. The script below will assign a python date attribute to this column. The same script can be used for any other date elements. \n###### **The CSV file must contain date the date in the YYYY-MM-DD format. If it is not possible to create it in this format, please let us know.**\n###### The final line in this cell creates a new column and assigns the index number of the row to it. This will be used to join on at later stages. If you see output in this cell, please ignore it.",
"_____no_output_____"
]
],
[
[
"#Cell number 6 \n\n# function to convert strings in column `var` in pandas DataFrame `df` to datetime\ndef str2date(df, var, dateformat='%Y-%m-%d'):\n cleanstring(df, var)\n \n # The line below can be adjusted to meet unique formats. For example, if the date appears as MM/DD/YYYY, the following\n # format will work: '%m/%d/%Y' Please let us know if you have more complicated date formats.\n # Furthermore, the last parameter can be customized in the function call section to change the specific date time to match your dataset\n # See the function calls section below for a commented out example of this\n df[var] = pd.to_datetime(df[var], format=dateformat) # converts the string to a datetime if it follows YYYY-MM-DD format\n \n\n# function calls\nstr2date(df_main, 'DT_Specimen')\nstr2date(df_main, 'DT_Disposition')\n\n## function call example showing how to process datetimes for DT_Specimen if the format is MM/DD/YYYY\n# str2date(df_main, 'DT_Specimen', dateformat='%m/%d/%Y')\n\ndf_main['S_No'] = df_main.index",
"_____no_output_____"
]
],
[
[
"###### Cell number 7: The database might default titers as '1:x', the following code removes the '1:' part from it and converts it to an integer. Only use the script below if the quantitative result in the dataframe is not extracted as a number. The script below takes away \"1:\" from, converts it into a number, and converts nan (No value) to 0. Cell number 7.b will execute the cleaning.",
"_____no_output_____"
]
],
[
[
"#Cell number 7\n\ndef cleannum(a):\n if a == 'nan':\n return 0\n else:\n return (a[2:])\n\ndef cleanquant(df, var):\n \n cleanstring(df, var)\n df['quanttest'] = df[var].apply(cleannum)\n df['quanttest'] = df['quanttest'].astype(int)\n ",
"_____no_output_____"
],
[
"# cell number 7.b\ndf_main['QuantitativeResult'].value_counts()\n# execute function\ncleanquant(df_main, 'QuantitativeResult')\ndf_main['quanttest'].value_counts()",
"_____no_output_____"
],
[
"df_main.columns\ndf_main['QuantitativeResult'].value_counts()",
"_____no_output_____"
]
],
[
[
"###### Cell number 8: If the quantitative result or titer was a number in the data extract and cell number 7 was not required, we change the column name to `quanttest`\n\n\n###### Run Cell number 8 customized to the column headings, labelling the column with titer results (quantitative results) as quanttest, only if cell number 7 was not required",
"_____no_output_____"
]
],
[
[
"#Cell number 8\n\n#df_main.columns = ['columnA', 'ID_Profile', 'columnB', 'DS_QualitativeResult','DT_Specimen', 'columnC', 'quanttest', 'DS_Test', 'columnD','CD_Gender','Age_clean']\n",
"_____no_output_____"
]
],
[
[
"###### Cell number 9: As part of data-wrangling, the following script ensures that the values for `ID_Profile`, `QualitativeResult`, and `Test` do not contain any spaces and are in string format.\n\n###### The data type displayed should show :\n| Column Name | Datatype |\n| --- | --- |\n| `ID_Profile` | `object` |\n| `Test` | `object` |\n| `DT_Specimen` | `datetime64[ns]` |\n| `QuantitativeResult` | `object` |\n| `quanttest` | `int32` |\n| `CD_Gender` | `object` |\n| `Age_clean` | `int32` |\n| `Disposition` | `object` |\n| `DT_Disposition` | `datetime64[ns]` |",
"_____no_output_____"
]
],
[
[
"#Cell number 9\ndirty_columns = ['ID_Profile', 'QualitativeResult', 'Test', 'CD_Gender', 'Disposition']\nfor c in dirty_columns:\n cleanstring(df_main, c)\n\ndf_main.dtypes",
"_____no_output_____"
]
],
[
[
"###### Cell number 10: Removes all tests with no dates (they can't be calculated in the algorithm) and reveals how many rows and columns are there in the DataFrame. The following step is not compulsory, but it ensures that all specimen dates have dates else the program will crash.",
"_____no_output_____"
]
],
[
[
"# Cell number 10\nnulldates = df_main[df_main['DT_Specimen'].isnull()] \nbeforelen = len(np.unique(nulldates['ID_Profile']))\nnulldates_idx = nulldates.index\n\ndf_main = df_main.drop(nulldates_idx)\nafterlen = len(np.unique(df_main['ID_Profile']))\n\n# ------ output ------\nprint(f\"\")\nprint(f\"Number of Null Dates Before Removal: {beforelen}\")\nprint(f\"Shape: {df_main.shape}\")\nprint(f\"Number of Tests After Null Removal: {afterlen}\")",
"\nNumber of Null Dates Before Removal: 7946\nShape: (534599, 24)\nNumber of Tests After Null Removal: 113507\n"
]
],
[
[
"###### Cell number 11: Creating a DataFrame for running the algorithm with only the essential columns. Since we select the core data elements, we remove duplicates (same person, same test, same result, same day). The row index is created as a separate column. This `index_no` will be used to join the rest of the data elements for analysis later on\n###### We display the number of rows and columns in this DataFrame. There should be 10 columns, the rows depend on how big the dataset is",
"_____no_output_____"
]
],
[
[
"# Cell number 11\n\ndf_main_dd = df_main[['ID_Profile','Test','DT_Specimen','quanttest','QualitativeResult','DT_Disposition']]\ndf_main_dd = df_main_dd.drop_duplicates()\ndf_main_dd['index_no'] = df_main_dd.index\n\ndf_main_dd = df_main_dd.merge(df_main, left_on = 'index_no', right_on = 'S_No', how = 'left')\n\n# df_main_dd drops invalid tests with no assigned date \n# if there is an error, see below\ndf_main_dd = df_main_dd[['ID_Profile_x', 'Test_x', 'DT_Specimen_x', 'quanttest_x',\n 'QualitativeResult_x','DT_Disposition_x', 'index_no', 'CD_Gender',\n 'Disposition', 'Age']]\n\n\ndf_main_dd.columns = ['ID_Profile','Test','DT_Specimen','quanttest','QualitativeResult', 'DT_Disposition','index_no','CD_Gender', 'Disposition', 'Age']\n\n#if there is an error:\n #It could be because the column names did not match\n #In a separate cell, please run\n #df_main_dd.dtypes\n #df_main_dd.columns\n \n #under the comment above, please insert how the column name appears in your output in place of these fields above:\n #['ID_Profile_x', 'DS_Test_x', 'DT_Specimen_x', 'quanttest_x',\n #'DS_QualitativeResult_x', 'index_no', 'CD_Gender',\n #'DS_Disposition', 'Age_clean']",
"_____no_output_____"
],
[
"# This cell simply prints the dimension of the dataset as well as the column names. \n# Feel free to use this cell to debug the previous cell.\ndf_main_dd.shape\ndf_main_dd.columns\ndf_main_dd.dtypes",
"_____no_output_____"
]
],
[
[
"###### Cell number 12: This is were we define all of our variables. This ensures that we don't have to modify the codes everytime and can just make some adjustments here",
"_____no_output_____"
]
],
[
[
"# Cell number 12 \n\n#Step 8 allows for a cut-off date for titers since we found that titers can be from a long time ago and should not be compared.\n#This can be modified anytime. We define the duration as 'DaysBetweenTests'\nDaysBetweenTests = 365\n\n#Step 8 quantifies what should be considered a high titer, given that the previous test is much older\n#This can be modified anytime. We define the titer cutoff as 'TiterCutOff'\nTiterCutOff = 32\n\n#'Female' maybe coded in many foms, please assign the exact variable as it is in your DataFrame\nFemale = 'F'\n\n#Step 8 also considers female of reproductive age, to prevent congenital syphilis. We have set the cut-off age as 50\n#This can be modified anytime. We define the age as 'FemaleAge'\nFemaleAge = 50\n\n#Step 8 was added, in part, to prevent congenital syphilis. For the general population, older titer is considered > 1year\n#For females of reproductive age, we consider the duration as 180 days and high titer as more than 1:9\n#This can be modified anytime. We define the duration as 'FemaleDaysBetweenTests' and the titer as 'FemaleTiterCutOff'\nFemaleDaysBetweenTests = 180\nFemaleTiterCutOff = 8\n\n#Step 8: We found that if patient was not previously treated, their titer might not change and can be reached now\n#Please assign the exact disposition that the DIS had assigned corresponding to an individual who was infected but not treated\ndisposition_InfNotTx = 'Infected, Not Treated'\n#Please assign the exact disposition that the DIS had assigned corresponding to an individual who was uable to be located\nunable_to_locate = 'Unable to Locate'\n#Please assign the exact disposition that the DIS had assigned corresponding to an individual who was out of jurisdiction\nOOJ = 'Administrative Closure OOJ'\n\n# Please assign values to the corresponding variable as it appears in your dataframe:\n#R is for reactive tests\nR = 'R'\n#W is for weakly positive/reactive tests\nW = 'W'\n#U is for unknown\nU = 'U'\n#P is for positive. RAPID tests seem to be assigned this qualitative result\nP = 'P'\n#N is for negative tests\nN = 'N'\n\n#Please assign how each non-Treponemal Test is coded in your dataframe. ONLY these 5 tests will be considered as NTTs.\nRPR = 'RPR'\nVDRL = 'VDRL'\nCSF_VDRL = 'CSF-VDRL'\nRPR_CordBlood = 'RPR Cord Blood'\nTRUST = 'TRUST'\n\n#Please assign how each Treponemal Test is coded in your dataframe. ONLY these10 tests will be considere as TTs.\nFTA_ABS = 'FTA-ABS'\nIgG_EIA = 'IgG EIA'\nTP_AB = 'TP-AB'\nTP_PA = 'TP-PA'\nRAPID = 'RAPID'\nEIA = 'EIA'\nMHATP = 'MHATP'\nFTA_IgG = 'FTA-IgG'\nCIA = 'CIA (CLIA)'\nTPHA = 'TPHA'\n\n#This defines all the Treponemal Tests used for filtering the dataframe in the main loop.\ntests = [FTA_ABS, IgG_EIA, TP_AB, TP_PA, RAPID, EIA, MHATP, FTA_IgG, CIA, TPHA]",
"_____no_output_____"
]
],
[
[
"### Algorithm to Prioritize Reactive Non-Treponemal Tests Reported to Health Departments for Investigating Suspected Cases of Syphilis\n\n",
"_____no_output_____"
],
[
"## Step 1: select only reactive Non-Treponemal Tests (NTT)\n#### Cell number 13 selects the tests for Step 1 in the algorithm",
"_____no_output_____"
]
],
[
[
"# cell number 13\ndfm_6m_ntt = df_main_dd[(df_main_dd['Test'] == RPR) | (df_main_dd['Test'] == VDRL) | (df_main_dd['Test'] == CSF_VDRL)| (df_main_dd['Test'] == RPR_CordBlood)|(df_main_dd['Test']==TRUST)]\ndfm_6m_ntt = dfm_6m_ntt[(dfm_6m_ntt['QualitativeResult'] == R) | (dfm_6m_ntt['QualitativeResult'] == W) | (dfm_6m_ntt['QualitativeResult'] == U)]\ndfm_6m_ntt = [group[group['DT_Specimen'] == group['DT_Specimen'].max()] for name , group in dfm_6m_ntt.groupby(\"ID_Profile\")]\ndfm_6m_ntt = pd.concat(dfm_6m_ntt)",
"_____no_output_____"
],
[
"dfm_6m_ntt['Test'].value_counts()\ndfm_6m_ntt.shape\nnp.unique(dfm_6m_ntt['ID_Profile'])",
"_____no_output_____"
]
],
[
[
"#### Cell number 13.1. We want to identify the first test in the latest DT_Disposition (episode of disease). Ideally, we would want to assign a disposition to this first test",
"_____no_output_____"
],
[
"For the purpose of this study, we identify the <span style=\"text-decoration:underline;\">latest test</span> in the database to simulate it as the current, reported test under evaluation that the algorithm would assign a disposition to. Typically, this is straightforward, we just locate the latest test by reviewing the date when the specimen was collected (`DT_Specimen`). However, in some cases (specifically for a retrospective analysis of a large dataset), identifying the latest test will lead to errors in the disposition. This is because sometimes dispositions are assigned to an ___episode___ of infection, which may be represented by multiple reported serologies over a period of time. We determined that if a disposition was assigned for a group of tests representing one episode of infection, the disposition date (`DT_Disposition`) would be the same (even if there could potentially be multiple serologies reported over that period of __one__ infectious episode). The figure represents the testing history of an individual. The serologies contained within the yellow rectangle are represented by a <span style=\"text-decoration:underline;\">single disposition date</span> and would represent __one episode of infection__. Therefore, we must identify the <span style=\"text-decoration:underline;font-weight:bold;font-style:italic;\">first test</span> in that episode to assign the disposition to since subsequent serologies would be follow-up serologies. It would also be inaccurate to assign disposition to the follow-up serologies. For e.g., the serologies contained within the red rectangle is the latest test, however, the algorithm would close it because it is not a 4-fold increase compared to the previous titer (and they fall under the same infectious period). The first test would be opened because 1:128 (tested on 02/27/2018) would represent a 4-fold increase compared to the previous titer of 1:16 (tested on 01/17/2017).\n\n",
"_____no_output_____"
]
],
[
[
"#13.1\nlist1 = np.unique(dfm_6m_ntt['ID_Profile'])\nlen(list1)\ndf_first_test = pd.DataFrame(columns=['ID_Profile','Test','DT_Specimen','quanttest','QualitativeResult','CD_Gender', 'Age', 'DT_Disposition', 'index_no'])\n\nfor i in list1:\n IncTest = dfm_6m_ntt[dfm_6m_ntt['ID_Profile']==i]\n time_IncTest = IncTest['DT_Disposition']\n time_IncTest = time_IncTest.values[0]\n \n df_all = df_main[df_main['ID_Profile'] == i]\n df_all = df_all[(df_all['Test'] == RPR) | (df_all['Test'] == VDRL) | (df_all['Test'] == CSF_VDRL) | (df_all['Test'] == RPR_CordBlood) | (df_all['Test'] == TRUST)]\n df_sameDT = df_all[df_all['DT_Disposition'] == time_IncTest]\n df_earliestTest = [group[group['DT_Specimen'] == group['DT_Specimen'].min()] for name , group in df_sameDT.groupby(\"ID_Profile\")]\n \n # skips to the next profile if its group doesn't exist\n if not df_earliestTest:\n continue\n \n df_earliestTest = pd.concat(df_earliestTest)\n df_first_test=df_first_test.append(df_earliestTest) \n\ndf_first_test",
"_____no_output_____"
],
[
"dfm_6m_ntt = df_first_test\n\ndfm_6m_ntt['Test'].value_counts()\ndfm_6m_ntt.shape",
"_____no_output_____"
]
],
[
[
"##### Cell number 14: A list (`profile_list`) is created with distinct unique identifiers. This profile list is used to loop in the program. \n##### A single unique identifier (`ID_Profile`) or a subset can be run by creating a list of the subset as `profile_list`. This is especially useful to debug the process and view a specific subset instead of running the entire dataset",
"_____no_output_____"
]
],
[
[
"# Cell number 14\nprofile_list = dfm_6m_ntt['ID_Profile'].unique()\nprofile_list\nlen(profile_list)",
"_____no_output_____"
]
],
[
[
"##### An example of cell 14.1 to run a fraction of the dataset (for e.g. a cut-off date) instead of the entire dataset. This will be useful to see if there are any bugs or issues.",
"_____no_output_____"
]
],
[
[
"# Cell number 14.1\nprofile_list = profile_list[:100]\nlen(profile_list)",
"_____no_output_____"
],
[
"#baseline_date = pd.to_datetime('20190318', format='%Y%m%d') #---->change the date within the '' to what you'd like\n#baseline_date\n#df_main_6m_ntt = df_main_dd[df_main_dd['DT_Specimen'] >= baseline_date]\n\n#df_main_6m_ntt = df_main_dd[(df_main_dd['DS_Test'] == RPR) | (df_main_dd['DS_Test'] == VDRL)|(df_main_dd['DS_Test']==CSF_VDRL)|(df_main_dd['DS_Test']==RPR_CordBlood)]\n#df_main_6m_ntt = df_main_6m_ntt[(df_main_6m_ntt['DS_QualitativeResult']==R) | (df_main_6m_ntt['DS_QualitativeResult']==W) | (df_main_6m_ntt['DS_QualitativeResult']==U)]\n#df_main_6m_ntt = [group[group['DT_Specimen'] == group['DT_Specimen'].max()] for name , group in df_main_6m_ntt.groupby(\"ID_Profile\")]\n#df_main_6m_ntt = pd.concat(df_main_6m_ntt)\n\n#df_main_6m_ntt['DS_Test'].value_counts()\n#df_main_6m_ntt.shape",
"_____no_output_____"
]
],
[
[
"## All of the code for the algorithm is below in cell number 1\n### Each loop corresponding to the Step number in the algorithm is assigned that loop number.\n### Apart from the disposition assigned in the algorithm, tests are also assigned the exact decision point (for debugging and testing).\n### Steps are numbered and commented at every decision node. In case there is an issue with the code, we can print each step to determine where the problem lies.\n",
"_____no_output_____"
]
],
[
[
"count = 0\ndispo_type = 0\ncol1 = ['ID_Profile','Test','DT_Specimen','quanttest','QualitativeResult','CD_Gender', 'Age']\ncol2 = col1.copy()\ncol2.append('index_no')\n\n# final dataframe which is written to a file at the end\ndf_complete_merged = pd.DataFrame(columns = ['ID_Profile', 'Test_x', 'DT_Specimen_x', 'quanttest_x',\n 'QualitativeResult_x', 'CD_Gender_x', 'Age_x', 'index_no',\n 'algo_dispo', 'dispo', 'dis_type', 'Test_y', 'DT_Specimen_y',\n 'quanttest_y', 'QualitativeResult_y', 'CD_Gender_y', 'Age_y'])\n\n#1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111\nfor profile_id in profile_list:\n #profile_id\n count = count+1\n sero = 0 \n algo_dispo = 'NA'\n al_dis = 'NA'\n test_tocompare = pd.DataFrame(columns = col1)\n test_incoming = pd.DataFrame(columns = col2)\n \n #Dataframe df_incoming_test isolates the tests for that particular profile_id.\n #We will identify the test that should be assigned a disposition from this \n df_incoming_test = dfm_6m_ntt[dfm_6m_ntt['ID_Profile'] == profile_id]\n\n########### This is taking in the reactive nontreponemal tests. We intend to assign a disposition to these tests, whether to administratively close or open for investigation########\n \n #We first select the latest test as 'test_incoming', we will assign a disposition to this test\n if len(df_incoming_test.index) > 1:\n incoming_test = [group[group['DT_Specimen'] == group['DT_Specimen'].max()] for name , group in df_incoming_test.groupby(\"ID_Profile\")]\n test_incoming = pd.concat(incoming_test)\n else:\n test_incoming = df_incoming_test\n\n #################### We identified test_incoming as THE TEST to assign this disposition ###################\n\n\n #time_of_test is the time the specimen was collected for 'test_incoming', it will be used for decision logic below\n time_of_test = pd.to_datetime(test_incoming['DT_Specimen'].values[0])\n\n \n #!!!!!!!!!! df_match contains the entire dataset; we use this to identify the matches for the test !!!!!!\n df_match = df_main_dd[df_main_dd['ID_Profile'] == profile_id]\n \n #Creating a dataframe 'df_match_all' which has all the tests before 'time_of_test' for each individual ID_Profile\n df_match_all = df_match[df_match['DT_Specimen'] < time_of_test]\n \n #Creating a dataframe 'TT_tocompare' which has all the nonreactive treponemal tests before for each individual ID_Profile\n TT_tocompare = df_match\n TT_tocompare = reactive_nTT(TT_tocompare, 'QualitativeResult', R, W, U, P) \n TT_tocompare = step4_TT(TT_tocompare, 'Test', tests)\n \n TT_tocompare = TT_tocompare[~(TT_tocompare['DT_Specimen'] > time_of_test)]\n \n #Creating a marker step_3b. It is 1 when 2.b condition is met, otherwise it is 0.\n step_3b = 0\n csf_cord = test_incoming[(test_incoming['Test'] == CSF_VDRL) | (test_incoming['Test'] == RPR_CordBlood)]\n \n #########################Step 222222222222222222222222222222222222222222222\n ######################As per Step 2: current titer CSF or cord blood? #########################\n if csf_cord.empty is False:\n csf_cord = [group[group['quanttest'] == group['quanttest'].max()] for name , group in csf_cord.groupby(\"ID_Profile\")]\n test_incoming = pd.concat(csf_cord)\n test_incoming = test_incoming.iloc[[0]]\n algo_dispo = 'Open: CSF/Cord'\n al_dis = 'Open'\n dispo_type = '2.b'\n \n else:\n \n #333333333333333333333333333333333333333333333333333333333333333333333333333333\n if TT_tocompare.empty is False:\n #If there is a Non-Reactive TT, we identify the latest test\n TT_tocompare = [group[group['DT_Specimen'] == group['DT_Specimen'].max()] for name , group in TT_tocompare.groupby(\"ID_Profile\")]\n TT_tocompare = pd.concat(TT_tocompare) \n positive_TT = df_match\n \n positive_TT = step3_nonreactive_TT(positive_TT, 'QualitativeResult', R, W, U, P)\n positive_TT = step4_TT(positive_TT, 'Test', tests)\n positive_TT = positive_TT[~(positive_TT['DT_Specimen'] > time_of_test)]\n \n negative_TT = positive_TT[(positive_TT['QualitativeResult'] != R)]\n negative_TT = negative_TT[(positive_TT['QualitativeResult'] != W)]\n negative_TT = negative_TT[(positive_TT['QualitativeResult'] != U)]\n negative_TT = negative_TT[(positive_TT['QualitativeResult'] != P)]\n positive_TT = positive_TT[~(positive_TT['QualitativeResult'].isin(negative_TT['QualitativeResult']))]\n \n if len(positive_TT)>1: \n if (((pd.to_datetime(time_of_test) - pd.to_datetime(positive_TT['DT_Specimen'].values[0]))/np.timedelta64(1,'D')) <= 14):\n positive_TT = positive_TT.iloc[[0]]\n \n \n ##################### Step 3 in the algorithm 3333333333333333333333333333333333333\n ################# Non-reactive TT in last 14 days with no reactive TT reported within this duration\n \n if (positive_TT.empty is True) & (((pd.to_datetime(time_of_test) - pd.to_datetime(TT_tocompare['DT_Specimen'].values[0]))/np.timedelta64(1,'D')) <= 14): #& (((pd.to_datetime(time_of_test) - pd.to_datetime(TT_tocompare['DT_Specimen'].values[0]))/np.timedelta64(1,'D')) >=0):\n #As per step 3: Non-Reactive Treponemal Test <= 14 Days Prior to Treponemal Test? ############################\n algo_dispo = 'Close: TT_14d'\n al_dis = 'Close'\n dispo_type = '3.b'\n test_tocompare = TT_tocompare.iloc[[0]]\n test_incoming = test_incoming.iloc[[0]]\n # if serology meets this condition then 'step_3b' is assigned a value '1' and exits the next loop ########\n step_3b = 1\n \n ############################### If step 3 was not met ################################ \n if step_3b == 0:\n \n # test_incoming := latest test with disposition to assign to\n\n prior_test_date = df_match_all['DT_Specimen'].max()\n prior_test = df_match_all[df_match_all['DT_Specimen'] == prior_test_date]\n prior_test = step4_TT(prior_test, 'Test', tests)\n prior_test = reactive_nTT(prior_test, 'QualitativeResult', R, W, U, P)\n \n ########################## Step 4 in the algorithm 4444444444444444444444444444444444444444444\n ###################### Penultimate test has a negative treponemal test ###################\n if prior_test.empty is False:\n test_tocompare = prior_test.iloc[[0]] \n test_incoming = test_incoming.iloc[[0]]\n algo_dispo = 'Open: Pen_N_TT'\n al_dis = 'Open'\n dispo_type = '4.b'\n else: \n\n \n ############################ Step 5 in the algorithm 555555555555555555555555555555555555555\n #################### Does patient have Prior Syphilis Non-Treponemal Test? ####################\n \n #'df_match_ntt' creates a dataframe for Non_Treponemal Tests\n df_match_ntt = df_match_all[(df_match_all['Test'] == RPR) | (df_match_all['Test'] == VDRL)]\n \n ## Step 5 logic found in the else statement below near the end of loop close:\n \n if df_match_ntt.empty is False:\n incoming_test = test_incoming[test_incoming['quanttest']>0]\n if len(incoming_test) > 0:\n incoming_test = [group[group['quanttest'] == group['quanttest'].max()] for name , group in incoming_test.groupby(\"ID_Profile\")]\n incoming_test = pd.concat(incoming_test)\n \n ########################## Step 6 in the algorithm 66666666666666666666666666666666666\n\n if len(df_match_all) > 1:\n previouslynotx = [group[group['DT_Specimen'] == group['DT_Specimen'].max()] for name , group in df_match_all.groupby(\"ID_Profile\")]\n previouslynotx = pd.concat(previouslynotx)\n previouslynotx = previouslynotx[(previouslynotx['Disposition'] == unable_to_locate) | (previouslynotx['Disposition'] == unable_to_locate) | (previouslynotx['Disposition'] == OOJ) | (previouslynotx['Disposition'] == disposition_InfNotTx)]\n else:\n previouslynotx = df_match_all[(df_match_all['Disposition'] == unable_to_locate) | (df_match_all['Disposition'] == unable_to_locate) | (df_match_all['Disposition'] == OOJ) | (df_match_all['Disposition'] == disposition_InfNotTx)]\n if len(previouslynotx)>1:\n previouslynotx = [group[group['DT_Specimen'] == group['DT_Specimen'].max()] for name , group in previouslynotx.groupby(\"ID_Profile\")]\n previouslynotx = pd.concat(previouslynotx)\n \n ########################## Previous disposition 'infected, not treated': yes ################\n if previouslynotx.empty is False:\n algo_dispo = 'Open: PrevNoTx'\n al_dis = 'Open'\n dispo_type = '6.b'\n previouslynotx = previouslynotx[['ID_Profile','Test','DT_Specimen','quanttest','QualitativeResult']]\n test_tocompare = previouslynotx.iloc[[0]]\n test_incoming = test_incoming.iloc[[0]]\n\n else:\n ########################## Step 7 in the algorithm 77777777777777777777777777777777777\n \n ## Step 7 logic found in the else statement below near the end of loop close:\n if incoming_test.empty is False:\n test_incoming = incoming_test\n latest_titer = df_match_ntt[df_match_ntt['quanttest'] > 0]\n \n #@@@@@@ START: these codes :-\n ## 1: find previous titer to compare to current serology\n ## 2: any negative serology prior to current serology to look for serconversion\n if len(latest_titer) > 0:\n latest_titer = [group[group['DT_Specimen'] == group['DT_Specimen'].max()] for name , group in latest_titer.groupby(\"ID_Profile\")]\n # 'latest_titer' identifies the previous titer, before the current reported serology\n latest_titer = pd.concat(latest_titer)\n seroconversion = df_match_ntt[df_match_ntt['QualitativeResult'] == N]\n seroconversion = seroconversion[seroconversion['DT_Specimen']>=latest_titer['DT_Specimen'].values[0]]\n else:\n last_titer = df_match_ntt[df_match_ntt['QualitativeResult']!=N]\n\n if len(last_titer) > 0:\n last_titer = [group[group['DT_Specimen'] == group['DT_Specimen'].max()] for name , group in last_titer.groupby(\"ID_Profile\")]\n last_titer = pd.concat(last_titer)\n seroconversion = df_match_ntt[df_match_ntt['QualitativeResult'] == N]\n seroconversion = seroconversion[seroconversion['DT_Specimen'] >= last_titer['DT_Specimen'].values[0]]\n else:\n seroconversion = df_match_ntt[df_match_ntt['QualitativeResult'] == N]\n\n if len(seroconversion) > 1:\n seroconversion = [group[group['DT_Specimen'] == group['DT_Specimen'].max()] for name , group in seroconversion.groupby(\"ID_Profile\")]\n seroconversion = pd.concat(seroconversion)\n seroconversion = seroconversion.iloc[[0]]\n #@@@@@@ END: these codes :-\n ## 1: find previous titer to compare to current serology\n ## 2: any negative serology prior to current serology to look for serconversion\n\n ########################## Step 8 in the algorithm 8888888888888888888888888888888888888\n if latest_titer.empty is False:\n ############## (Current titer>1:32 AND previous titer >1 year) #####################\n ############## OR #####################\n ########### (Female < 50y AND titer > 1:8 AND previous titer > 6m) #################\n \n duration = (pd.to_datetime(time_of_test) - pd.to_datetime(latest_titer['DT_Specimen'].values[0]))/np.timedelta64(1,'D')\n sero2 = (pd.to_datetime(seroconversion['DT_Specimen']) - pd.to_datetime(latest_titer['DT_Specimen'].values[0]))/np.timedelta64(1,'D')\n\n if (test_incoming['CD_Gender'].values[0]==Female) & (duration >= FemaleDaysBetweenTests) & (int(test_incoming['Age'].values[0]) < FemaleAge) & (test_incoming['quanttest'].values[0] > FemaleTiterCutOff):\n algo_dispo = 'Open: ModCrit'\n al_dis = 'Open'\n dispo_type = '8.b2'\n test_tocompare = latest_titer.iloc[[0]] \n test_incoming = test_incoming.iloc[[0]]\n elif (duration >= DaysBetweenTests) & (test_incoming['quanttest'].values[0]>TiterCutOff):\n algo_dispo = 'Open: ModCrit'\n al_dis = 'Open'\n dispo_type = '8.b1'\n test_tocompare = latest_titer.iloc[[0]]\n test_incoming = test_incoming.iloc[[0]]\n \n else:\n ##################### Step 9 in the algorithm 999999999999999999999999999999999999\n ##################### >=4-fold Titer Increase: Yes ###############################\n \n if test_incoming['quanttest'].values[0] >= ((latest_titer['quanttest'].values[0]*2)*2):\n algo_dispo = 'Open: 4f'\n al_dis = 'Open'\n dispo_type = '9.b1'\n test_tocompare = latest_titer.iloc[[0]]\n test_incoming = test_incoming.iloc[[0]]\n else:\n ################# Step 10 in the algorithm 1010101010101010101010101010101010\n \n if (test_incoming['QualitativeResult'].values[0]==R) & seroconversion.empty is False:\n ################# Check for serocoversion ###################################\n algo_dispo = 'Open: SeroConv'\n al_dis = 'Open'\n dispo_type = '10.b1'\n test_tocompare = seroconversion\n test_incoming = test_incoming.iloc[[0]]\n\n else:\n ################# No seroconversion, close: no 4-fold increase ###############\n algo_dispo = 'Close: 4f'\n al_dis = 'Close'\n dispo_type = '10.a1'\n test_incoming = test_incoming[test_incoming['QualitativeResult'] == R]\n test_incoming = test_incoming.iloc[[0]]\n test_tocompare = latest_titer.iloc[[0]]\n ############ Step 10 close loop 1010101010101010101010101010101010101010\n ################ Step 9 close loop 999999999999999999999999999999999999999999\n \n #################### if there were no titers reported previously#####################\n else:\n \n ################## if serconversion is present ############################\n if (test_incoming['QualitativeResult'].values[0]==R) & seroconversion.empty is False:\n #As per step Non-Treponemal Seroconversion: Yes **********************\n algo_dispo = 'Open: SeroConv'\n al_dis = 'Open'\n dispo_type = '10.b2'\n test_tocompare = seroconversion.iloc[[0]]\n test_incoming = test_incoming.iloc[[0]]\n \n ################## no seroconversion, no previous titer ############################ \n elif last_titer.empty is False:\n algo_dispo = 'Open: NoPrevTi'\n al_dis = 'Open'\n dispo_type = '9.b2'\n test_tocompare = last_titer.iloc[[0]]\n test_incoming = test_incoming.iloc[[0]]\n test_incoming = test_incoming.iloc[[0]]\n \n ################## does not meet 4-fold increase criteria ##########################\n else:\n \n algo_dispo = 'Close: 4f'\n al_dis = 'Close'\n dispo_type = '10.a2'\n test_incoming = test_incoming[test_incoming['QualitativeResult'] == R]\n test_incoming = test_incoming.iloc[[0]]\n test_tocompare = latest_titer.iloc[[0]]\n \n ####################### Step 8 close loop 888888888888888888888888888888888888888888\n ######################## Step 7 in the algorithm#############################\n ####################### Quantitative titer reported on current serology? ####################\n else:\n algo_dispo = 'Open: NoC_NTT'\n al_dis = 'Open'\n dispo_type = '7.a'\n test_incoming = test_incoming.iloc[[0]]\n\n ########################### Step 7 close loop 77777777777777777777777777777777777777777\n ############################### Step 6 close loop 66666666666666666666666666666666666666666\n ######################## Step 5 in the algorithm#############################\n ####################### Does patient have Prior Syphilis Non-Treponemal Test? ####################\n \n else:\n algo_dispo = 'Open: NoM'\n al_dis = 'Open'\n dispo_type = '5.a'\n test_incoming = [group[group['quanttest'] == group['quanttest'].max()] for name , group in test_incoming.groupby(\"ID_Profile\")]\n test_incoming = pd.concat(test_incoming)\n test_incoming = test_incoming.iloc[[0]]\n\n #################################### Step 5 close loop 5555555555555555555555555555555555555555\n ######################################## Step 4 close loop 4444444444444444444444444444444444444444\n ############################################ Step 3 close loop 3333333333333333333333333333333333333333\n ################################################ Step 2 close loop 2222222222222222222222222222222222222222\n test_incoming['algo_dispo'] = algo_dispo\n test_incoming['dispo'] = al_dis\n test_incoming['dis_type'] = dispo_type\n df_complete = pd.merge(test_incoming, test_tocompare, on='ID_Profile',how='left')\n df_complete_merged = df_complete_merged.append(df_complete)\n#1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111\n#print(count) \n#df_complete_merged",
"_____no_output_____"
]
],
[
[
"##### Cell number 16: The script below assigns 1 column for index number for the test. This index number is inherited from the original file df_main",
"_____no_output_____"
]
],
[
[
"df_complete_merged['test_index'] = df_complete_merged['index_no'].astype(str) + df_complete_merged['index_no_x'].astype(str)\ndf_complete_merged['test_index'] = df_complete_merged['test_index'].map(lambda x: x.lstrip('nan').rstrip('nan'))\ndf_complete_merged=df_complete_merged.drop(columns=['index_no', 'index_no_x'])\n\nstr2date(df_complete_merged, 'DT_Specimen_x')\nstr2date(df_complete_merged, 'DT_Specimen_y')\n\ndf_complete_merged['day_diff'] = pd.to_datetime(df_complete_merged['DT_Specimen_x']) - pd.to_datetime(df_complete_merged['DT_Specimen_y'])\ndf_complete_merged['day_value'] = df_complete_merged['day_diff']/np.timedelta64(1,'D')\n#df_complete_merged",
"_____no_output_____"
],
[
"df_complete_merged['dispo'].value_counts()\ndf_complete_merged['algo_dispo'].value_counts()\ndf_complete_merged['dis_type'].value_counts()",
"_____no_output_____"
]
],
[
[
"##### Cell number 17 creates a CSV file for this dataset. Please replace 'ResultOfAlgorithm.csv' with a file path and name of your choice.",
"_____no_output_____"
]
],
[
[
"# Cell number 17\ndf_complete_merged.to_csv(r'ResultOfAlgorithm.csv', index=False)",
"_____no_output_____"
]
],
[
[
"##### Cell number 18\n\nWe join the dataset generated by the algorithm script (`df_complete_merged`) on the main dataset (`df_main`). `test_index` and `S_No` are the same index inherited from `df_main`. We conduct a left join on this index number of both datasets because `Disposition` is assigned to the serology identified on `df_complete_merged`. Using `text_index` from `df_main`, we identify the test which helped make the Disposition decision in the algorithm. If there was no match found (\"Open: NoM\"), then there will be a missing value (`nan`) in those columns. ",
"_____no_output_____"
]
],
[
[
"# Cell number 18\ndf_comp_merged_co = df_complete_merged.copy()\ndf_main_co = df_main.copy()\n\ndf_comp_merged_co['S_No'] = df_comp_merged_co['S_No'].astype(str)\ndf_main_co['S_No'] = df_main_co['S_No'].astype(str)\ndf_joined = df_comp_merged_co.merge(df_main_co, left_on='test_index',right_on = 'S_No', how='left')",
"_____no_output_____"
]
],
[
[
"##### Cell number 19 creates a CSV file for this dataset. Please replace 'AlgorithmMerged.csv' with a file path and name of your choice.",
"_____no_output_____"
]
],
[
[
"# Cell number 19\ndf_joined.to_csv(r'AlgorithmMerged.csv', index=False)",
"_____no_output_____"
]
],
[
[
"## This is the end of the script for the algorithm",
"_____no_output_____"
]
],
[
[
"df_complete_merged['dispo'].value_counts()\ndf_complete_merged['algo_dispo'].value_counts()\ndf_complete_merged['dis_type'].value_counts()",
"_____no_output_____"
],
[
"df_complete_merged.groupby(['Disposition','algo_dispo'])[\"ID_Profile\"].count()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e77d0ab68c88b4448b9450f3a519bb3448a3bb42 | 152,291 | ipynb | Jupyter Notebook | 06 - Work with Data.ipynb | ChidiNdego/azure-challenge-mslearn-dp100 | d17eae17d7968fc69d41c664533676d547b5900f | [
"MIT"
] | null | null | null | 06 - Work with Data.ipynb | ChidiNdego/azure-challenge-mslearn-dp100 | d17eae17d7968fc69d41c664533676d547b5900f | [
"MIT"
] | null | null | null | 06 - Work with Data.ipynb | ChidiNdego/azure-challenge-mslearn-dp100 | d17eae17d7968fc69d41c664533676d547b5900f | [
"MIT"
] | null | null | null | 93.775246 | 46,299 | 0.703311 | [
[
[
"# Work with Data\n\nData is the foundation on which machine learning models are built. Managing data centrally in the cloud, and making it accessible to teams of data scientists who are running experiments and training models on multiple workstations and compute targets is an important part of any professional data science solution.\n\nIn this notebook, you'll explore two Azure Machine Learning objects for working with data: *datastores*, and *datasets*.",
"_____no_output_____"
],
[
"## Connect to your workspace\n\nTo get started, connect to your workspace.\n\n> **Note**: If you haven't already established an authenticated session with your Azure subscription, you'll be prompted to authenticate by clicking a link, entering an authentication code, and signing into Azure.",
"_____no_output_____"
]
],
[
[
"import azureml.core\nfrom azureml.core import Workspace\n\n# Load the workspace from the saved config file\nws = Workspace.from_config()\nprint('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 azure_ds_challenge\n"
]
],
[
[
"## Work with datastores\n\nIn Azure ML, *datastores* are references to storage locations, such as Azure Storage blob containers. Every workspace has a default datastore - usually the Azure storage blob container that was created with the workspace. If you need to work with data that is stored in different locations, you can add custom datastores to your workspace and set any of them to be the default.\n\n### View datastores\n\nRun the following code to determine the datastores in your workspace:",
"_____no_output_____"
]
],
[
[
"# Get the default datastore\ndefault_ds = ws.get_default_datastore()\n\n# Enumerate all datastores, indicating which is the default\nfor ds_name in ws.datastores:\n print(ds_name, \"- Default =\", ds_name == default_ds.name)",
"azureml_globaldatasets - Default = False\nworkspacefilestore - Default = False\nworkspaceblobstore - Default = True\n"
]
],
[
[
"#### Extra note:\n\n#### Considerations for datastores\n\nWhen planning for datastores, consider the following guidelines:\n\n When using Azure blob storage, premium level storage may provide improved I/O performance for large datasets. However, this option will increase cost and may limit replication options for data redundancy.\n When working with data files, although CSV format is very common, Parquet format generally results in better performance.\n You can access any datastore by name, but you may want to consider changing the default datastore (which is initially the built-in workspaceblobstore datastore).\n\nTo change the default datastore, use the set_default_datastore() method:\n\n```\nws.set_default_datastore('blob_data')\n```",
"_____no_output_____"
],
[
"You can also view and manage datastores in your workspace on the **Datastores** page for your workspace in [Azure Machine Learning studio](https://ml.azure.com).\n\n### Upload data to a datastore\n\nNow that you have determined the available datastores, you can upload files from your local file system to a datastore so that it will be accessible to experiments running in the workspace, regardless of where the experiment script is actually being run.",
"_____no_output_____"
]
],
[
[
"default_ds.upload_files(files=['./data/diabetes.csv', './data/diabetes2.csv'], # Upload the diabetes csv files in /data\n target_path='diabetes-data/', # Put it in a folder path in the datastore\n overwrite=True, # Replace existing files of the same name\n show_progress=True)",
"Uploading an estimated of 2 files\nUploading ./data/diabetes.csv\nUploaded ./data/diabetes.csv, 1 files out of an estimated total of 2\nUploading ./data/diabetes2.csv\nUploaded ./data/diabetes2.csv, 2 files out of an estimated total of 2\nUploaded 2 files\n"
]
],
[
[
"## Work with datasets\n\nAzure Machine Learning provides an abstraction for data in the form of *datasets*. A dataset is a versioned reference to a specific set of data that you may want to use in an experiment. Datasets can be *tabular* or *file*-based.\n\n### Create a tabular dataset\n\nLet's create a dataset from the diabetes data you uploaded to the datastore, and view the first 20 records. In this case, the data is in a structured format in a CSV file, so we'll use a *tabular* dataset.",
"_____no_output_____"
]
],
[
[
"from azureml.core import Dataset\n\n# Get the default datastore\ndefault_ds = ws.get_default_datastore()\n\n#Create a tabular dataset from the path on the datastore (this may take a short while)\ntab_data_set = Dataset.Tabular.from_delimited_files(path=(default_ds, 'diabetes-data/*.csv'))\n\n# Display the first 20 rows as a Pandas dataframe\ntab_data_set.take(20).to_pandas_dataframe()",
"_____no_output_____"
]
],
[
[
"#### Types of dataset\n\nDatasets are typically based on files in a datastore, though they can also be based on URLs and other sources. You can create the following types of dataset:\n\n Tabular: The data is read from the dataset as a table. You should use this type of dataset when your data is consistently structured and you want to work with it in common tabular data structures, such as Pandas dataframes.\n File: The dataset presents a list of file paths that can be read as though from the file system. Use this type of dataset when your data is unstructured, or when you need to process the data at the file level (for example, to train a convolutional neural network from a set of image files).\n\n#### Creating and registering datasets\n\nYou can use the visual interface in Azure Machine Learning studio or the Azure Machine Learning SDK to create datasets from individual files or multiple file paths. The paths can include wildcards (for example, /files/*.csv) making it possible to encapsulate data from a large number of files in a single dataset.\n\nAfter you've created a dataset, you can register it in the workspace to make it available for use in experiments and data processing pipelines later.",
"_____no_output_____"
],
[
"As you can see in the code above, it's easy to convert a tabular dataset to a Pandas dataframe, enabling you to work with the data using common python techniques.\n\n### Create a file Dataset\n\nThe dataset you created is a *tabular* dataset that can be read as a dataframe containing all of the data in the structured files that are included in the dataset definition. This works well for tabular data, but in some machine learning scenarios you might need to work with data that is unstructured; or you may simply want to handle reading the data from files in your own code. To accomplish this, you can use a *file* dataset, which creates a list of file paths in a virtual mount point, which you can use to read the data in the files.",
"_____no_output_____"
]
],
[
[
"#Create a file dataset from the path on the datastore (this may take a short while)\nfile_data_set = Dataset.File.from_files(path=(default_ds, 'diabetes-data/*.csv'))\n\n# Get the files in the dataset\nfor file_path in file_data_set.to_path():\n print(file_path)",
"/diabetes.csv\n/diabetes2.csv\n"
]
],
[
[
"### Register datasets\n\nNow that you have created datasets that reference the diabetes data, you can register them to make them easily accessible to any experiment being run in the workspace.\n\nWe'll register the tabular dataset as **diabetes dataset**, and the file dataset as **diabetes files**.",
"_____no_output_____"
]
],
[
[
"# Register the tabular dataset\ntry:\n tab_data_set = tab_data_set.register(workspace=ws, \n name='diabetes dataset',\n description='diabetes data',\n tags = {'format':'CSV'},\n create_new_version=True)\nexcept Exception as ex:\n print(ex)\n\n# Register the file dataset\ntry:\n file_data_set = file_data_set.register(workspace=ws,\n name='diabetes file dataset',\n description='diabetes files',\n tags = {'format':'CSV'},\n create_new_version=True)\nexcept Exception as ex:\n print(ex)\n\nprint('Datasets registered')",
"Datasets registered\n"
]
],
[
[
"#### Retrieving a registered dataset\n\nAfter registering a dataset, you can retrieve it by using any of the following techniques:\n\n The datasets dictionary attribute of a Workspace object.\n The get_by_name or get_by_id method of the Dataset class.\n\nBoth of these techniques are shown in the following code:\n\n```\nimport azureml.core\nfrom azureml.core import Workspace, Dataset\n\n# Load the workspace from the saved config file\nws = Workspace.from_config()\n\n# Get a dataset from the workspace datasets collection\nds1 = ws.datasets['csv_table']\n\n# Get a dataset by name from the datasets class\nds2 = Dataset.get_by_name(ws, 'img_files')\n```",
"_____no_output_____"
],
[
"You can view and manage datasets on the **Datasets** page for your workspace in [Azure Machine Learning studio](https://ml.azure.com). You can also get a list of datasets from the workspace object:",
"_____no_output_____"
]
],
[
[
"print(\"Datasets:\")\nfor dataset_name in list(ws.datasets.keys()):\n dataset = Dataset.get_by_name(ws, dataset_name)\n print(\"\\t\", dataset.name, 'version', dataset.version)",
"Datasets:\n\t diabetes file dataset version 1\n\t diabetes dataset version 1\n\t TD-Auto_Price_Training-Clean_Missing_Data-Cleaning_transformation-91e1ac5f version 1\n\t TD-Auto_Price_Training-Normalize_Data-Transformation_function-0f39eb1a version 1\n\t MD-Auto_Price_Training-Train_Model-Trained_model-559e7cee version 1\n\t bike-rentals version 1\n"
]
],
[
[
"#### Dataset versioning\n\nDatasets can be versioned, enabling you to track historical versions of datasets that were used in experiments, and reproduce those experiments with data in the same state.\n\nYou can create a new version of a dataset by registering it with the same name as a previously registered dataset and specifying the create_new_version property:\n\n```\nimg_paths = [(blob_ds, 'data/files/images/*.jpg'),\n (blob_ds, 'data/files/images/*.png')]\nfile_ds = Dataset.File.from_files(path=img_paths)\nfile_ds = file_ds.register(workspace=ws, name='img_files', create_new_version=True)\n```\n\nIn this example, the .png files in the images folder have been added to the definition of the img_paths dataset example used in the previous topic.\n\n\n#### Retrieving a specific dataset version\n\nYou can retrieve a specific version of a dataset by specifying the version parameter in the get_by_name method of the Dataset class.\n\n```\nimg_ds = Dataset.get_by_name(workspace=ws, name='img_files', version=2)\n```",
"_____no_output_____"
],
[
"The ability to version datasets enables you to redefine datasets without breaking existing experiments or pipelines that rely on previous definitions. By default, the latest version of a named dataset is returned, but you can retrieve a specific version of a dataset by specifying the version number, like this:\n\n```python\ndataset_v1 = Dataset.get_by_name(ws, 'diabetes dataset', version = 1)\n```\n\n\n### Train a model from a tabular dataset\n\nNow that you have datasets, you're ready to start training models from them. You can pass datasets to scripts as *inputs* in the estimator being used to run the script.\n\nRun the following two code cells to create:\n\n1. A folder named **diabetes_training_from_tab_dataset**\n2. A script that trains a classification model by using a tabular dataset that is passed to is as an argument.",
"_____no_output_____"
]
],
[
[
"import os\n\n# Create a folder for the experiment files\nexperiment_folder = 'diabetes_training_from_tab_dataset'\nos.makedirs(experiment_folder, exist_ok=True)\nprint(experiment_folder, 'folder created')",
"diabetes_training_from_tab_dataset folder created\n"
],
[
"%%writefile $experiment_folder/diabetes_training.py\n# Import libraries\nimport os\nimport argparse\nfrom azureml.core import Run, Dataset\nimport pandas as pd\nimport numpy as np\nimport joblib\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import roc_curve\n\n# Get the script arguments (regularization rate and training dataset ID)\nparser = argparse.ArgumentParser()\nparser.add_argument('--regularization', type=float, dest='reg_rate', default=0.01, help='regularization rate')\nparser.add_argument(\"--input-data\", type=str, dest='training_dataset_id', help='training dataset')\nargs = parser.parse_args()\n\n# Set regularization hyperparameter (passed as an argument to the script)\nreg = args.reg_rate\n\n# Get the experiment run context\nrun = Run.get_context()\n\n# Get the training dataset\nprint(\"Loading Data...\")\ndiabetes = run.input_datasets['training_data'].to_pandas_dataframe()\n\n# Separate features and labels\nX, y = diabetes[['Pregnancies','PlasmaGlucose','DiastolicBloodPressure','TricepsThickness','SerumInsulin','BMI','DiabetesPedigree','Age']].values, diabetes['Diabetic'].values\n\n# Split data into training set and test set\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=0)\n\n# Train a logistic regression model\nprint('Training a logistic regression model with regularization rate of', reg)\nrun.log('Regularization Rate', np.float(reg))\nmodel = LogisticRegression(C=1/reg, solver=\"liblinear\").fit(X_train, y_train)\n\n# calculate accuracy\ny_hat = model.predict(X_test)\nacc = np.average(y_hat == y_test)\nprint('Accuracy:', acc)\nrun.log('Accuracy', np.float(acc))\n\n# calculate AUC\ny_scores = model.predict_proba(X_test)\nauc = roc_auc_score(y_test,y_scores[:,1])\nprint('AUC: ' + str(auc))\nrun.log('AUC', np.float(auc))\n\nos.makedirs('outputs', exist_ok=True)\n# note file saved in the outputs folder is automatically uploaded into experiment record\njoblib.dump(value=model, filename='outputs/diabetes_model.pkl')\n\nrun.complete()",
"Writing diabetes_training_from_tab_dataset/diabetes_training.py\n"
]
],
[
[
"#### Extra note:\n\n#### Use a script argument for a tabular dataset\n\nYou can pass a tabular dataset as a script argument. When you take this approach, the argument received by the script is the unique ID for the dataset in your workspace. In the script, you can then get the workspace from the run context and use it to retrieve the dataset by it's ID.\n\nScriptRunConfig:\n\n```\nenv = Environment('my_env')\npackages = CondaDependencies.create(conda_packages=['pip'],\n pip_packages=['azureml-defaults',\n 'azureml-dataprep[pandas]'])\nenv.python.conda_dependencies = packages\n\nscript_config = ScriptRunConfig(source_directory='my_dir',\n script='script.py',\n arguments=['--ds', tab_ds],\n environment=env)\n```\n\nScript:\n\n```\nfrom azureml.core import Run, Dataset\n\nparser.add_argument('--ds', type=str, dest='dataset_id')\nargs = parser.parse_args()\n\nrun = Run.get_context()\nws = run.experiment.workspace\ndataset = Dataset.get_by_id(ws, id=args.dataset_id)\ndata = dataset.to_pandas_dataframe()\n```\n\n#### Use a named input for a tabular dataset\n\nAlternatively, you can pass a tabular dataset as a named input. In this approach, you use the as_named_input method of the dataset to specify a name for the dataset. Then in the script, you can retrieve the dataset by name from the run context's input_datasets collection without needing to retrieve it from the workspace. Note that if you use this approach, you still need to include a script argument for the dataset, even though you don’t actually use it to retrieve the dataset.\n\nScriptRunConfig:\n\n```\nenv = Environment('my_env')\npackages = CondaDependencies.create(conda_packages=['pip'],\n pip_packages=['azureml-defaults',\n 'azureml-dataprep[pandas]'])\nenv.python.conda_dependencies = packages\n\nscript_config = ScriptRunConfig(source_directory='my_dir',\n script='script.py',\n arguments=['--ds', tab_ds.as_named_input('my_dataset')],\n environment=env)\n```\n\nScript:\n\n```\nfrom azureml.core import Run\n\nparser.add_argument('--ds', type=str, dest='ds_id')\nargs = parser.parse_args()\n\nrun = Run.get_context()\ndataset = run.input_datasets['my_dataset']\ndata = dataset.to_pandas_dataframe()\n```",
"_____no_output_____"
],
[
"> **Note**: In the script, the dataset is passed as a parameter (or argument). In the case of a tabular dataset, this argument will contain the ID of the registered dataset; so you could write code in the script to get the experiment's workspace from the run context, and then get the dataset using its ID; like this:\n>\n> ```\n> run = Run.get_context()\n> ws = run.experiment.workspace\n> dataset = Dataset.get_by_id(ws, id=args.training_dataset_id)\n> diabetes = dataset.to_pandas_dataframe()\n> ```\n>\n> However, Azure Machine Learning runs automatically identify arguments that reference named datasets and add them to the run's **input_datasets** collection, so you can also retrieve the dataset from this collection by specifying its \"friendly name\" (which as you'll see shortly, is specified in the argument definition in the script run configuration for the experiment). This is the approach taken in the script above.\n\nNow you can run a script as an experiment, defining an argument for the training dataset, which is read by the script.\n\n> **Note**: The **Dataset** class depends on some components in the **azureml-dataprep** package, which includes optional support for **pandas** that is used by the **to_pandas_dataframe()** method. So you need to include this package in the environment where the training experiment will be run.",
"_____no_output_____"
]
],
[
[
"from azureml.core import Experiment, ScriptRunConfig, Environment\nfrom azureml.core.conda_dependencies import CondaDependencies\nfrom azureml.widgets import RunDetails\n\n\n# Create a Python environment for the experiment\nsklearn_env = Environment(\"sklearn-env\")\n\n# Ensure the required packages are installed (we need scikit-learn, Azure ML defaults, and Azure ML dataprep)\npackages = CondaDependencies.create(conda_packages=['scikit-learn','pip'],\n pip_packages=['azureml-defaults','azureml-dataprep[pandas]'])\nsklearn_env.python.conda_dependencies = packages\n\n# Get the training dataset\ndiabetes_ds = ws.datasets.get(\"diabetes dataset\")\n\n# Create a script config\nscript_config = ScriptRunConfig(source_directory=experiment_folder,\n script='diabetes_training.py',\n arguments = ['--regularization', 0.1, # Regularizaton rate parameter\n '--input-data', diabetes_ds.as_named_input('training_data')], # Reference to dataset\n environment=sklearn_env) \n\n# submit the experiment\nexperiment_name = 'mslearn-train-diabetes'\nexperiment = Experiment(workspace=ws, name=experiment_name)\nrun = experiment.submit(config=script_config)\nRunDetails(run).show()\nrun.wait_for_completion()",
"_____no_output_____"
]
],
[
[
"> **Note:** The **--input-data** argument passes the dataset as a *named input* that includes a *friendly name* for the dataset, which is used by the script to read it from the **input_datasets** collection in the experiment run. The string value in the **--input-data** argument is actually the registered dataset's ID. As an alternative approach, you could simply pass `diabetes_ds.id`, in which case the script can access the dataset ID from the script arguments and use it to get the dataset from the workspace, but not from the **input_datasets** collection.\n\nThe first time the experiment is run, it may take some time to set up the Python environment - subsequent runs will be quicker.\n\nWhen the experiment has completed, in the widget, view the **azureml-logs/70_driver_log.txt** output log and the metrics generated by the run.\n\n### Register the trained model\n\nAs with any training experiment, you can retrieve the trained model and register it in your Azure Machine Learning workspace.",
"_____no_output_____"
]
],
[
[
"from azureml.core import Model\n\nrun.register_model(model_path='outputs/diabetes_model.pkl', model_name='diabetes_model',\n tags={'Training context':'Tabular dataset'}, properties={'AUC': run.get_metrics()['AUC'], 'Accuracy': run.get_metrics()['Accuracy']})\n\nfor model in Model.list(ws):\n print(model.name, 'version:', model.version)\n for tag_name in model.tags:\n tag = model.tags[tag_name]\n print ('\\t',tag_name, ':', tag)\n for prop_name in model.properties:\n prop = model.properties[prop_name]\n print ('\\t',prop_name, ':', prop)\n print('\\n')",
"diabetes_model version: 3\n\t Training context : Tabular dataset\n\t AUC : 0.8568595320655352\n\t Accuracy : 0.7891111111111111\n\n\ndiabetes_model version: 2\n\t Training context : Parameterized script\n\t AUC : 0.8484357430717946\n\t Accuracy : 0.774\n\n\ndiabetes_model version: 1\n\t Training context : Script\n\t AUC : 0.8483203144435048\n\t Accuracy : 0.774\n\n\n"
]
],
[
[
"### Train a model from a file dataset\n\nYou've seen how to train a model using training data in a *tabular* dataset; but what about a *file* dataset?\n\nWhen you're using a file dataset, the dataset argument passed to the script represents a mount point containing file paths. How you read the data from these files depends on the kind of data in the files and what you want to do with it. In the case of the diabetes CSV files, you can use the Python **glob** module to create a list of files in the virtual mount point defined by the dataset, and read them all into Pandas dataframes that are concatenated into a single dataframe.\n\nRun the following two code cells to create:\n\n1. A folder named **diabetes_training_from_file_dataset**\n2. A script that trains a classification model by using a file dataset that is passed to is as an *input*.",
"_____no_output_____"
]
],
[
[
"import os\n\n# Create a folder for the experiment files\nexperiment_folder = 'diabetes_training_from_file_dataset'\nos.makedirs(experiment_folder, exist_ok=True)\nprint(experiment_folder, 'folder created')",
"diabetes_training_from_file_dataset folder created\n"
],
[
"%%writefile $experiment_folder/diabetes_training.py\n# Import libraries\nimport os\nimport argparse\nfrom azureml.core import Dataset, Run\nimport pandas as pd\nimport numpy as np\nimport joblib\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import roc_curve\nimport glob\n\n# Get script arguments (rgularization rate and file dataset mount point)\nparser = argparse.ArgumentParser()\nparser.add_argument('--regularization', type=float, dest='reg_rate', default=0.01, help='regularization rate')\nparser.add_argument('--input-data', type=str, dest='dataset_folder', help='data mount point')\nargs = parser.parse_args()\n\n# Set regularization hyperparameter (passed as an argument to the script)\nreg = args.reg_rate\n\n# Get the experiment run context\nrun = Run.get_context()\n\n# load the diabetes dataset\nprint(\"Loading Data...\")\ndata_path = run.input_datasets['training_files'] # Get the training data path from the input\n# (You could also just use args.data_folder if you don't want to rely on a hard-coded friendly name)\n\n# Read the files\nall_files = glob.glob(data_path + \"/*.csv\")\ndiabetes = pd.concat((pd.read_csv(f) for f in all_files), sort=False)\n\n# Separate features and labels\nX, y = diabetes[['Pregnancies','PlasmaGlucose','DiastolicBloodPressure','TricepsThickness','SerumInsulin','BMI','DiabetesPedigree','Age']].values, diabetes['Diabetic'].values\n\n# Split data into training set and test set\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=0)\n\n# Train a logistic regression model\nprint('Training a logistic regression model with regularization rate of', reg)\nrun.log('Regularization Rate', np.float(reg))\nmodel = LogisticRegression(C=1/reg, solver=\"liblinear\").fit(X_train, y_train)\n\n# calculate accuracy\ny_hat = model.predict(X_test)\nacc = np.average(y_hat == y_test)\nprint('Accuracy:', acc)\nrun.log('Accuracy', np.float(acc))\n\n# calculate AUC\ny_scores = model.predict_proba(X_test)\nauc = roc_auc_score(y_test,y_scores[:,1])\nprint('AUC: ' + str(auc))\nrun.log('AUC', np.float(auc))\n\nos.makedirs('outputs', exist_ok=True)\n# note file saved in the outputs folder is automatically uploaded into experiment record\njoblib.dump(value=model, filename='outputs/diabetes_model.pkl')\n\nrun.complete()",
"Writing diabetes_training_from_file_dataset/diabetes_training.py\n"
]
],
[
[
"Just as with tabular datasets, you can retrieve a file dataset from the **input_datasets** collection by using its friendly name. You can also retrieve it from the script argument, which in the case of a file dataset contains a mount path to the files (rather than the dataset ID passed for a tabular dataset).\n\nNext we need to change the way we pass the dataset to the script - it needs to define a path from which the script can read the files. You can use either the **as_download** or **as_mount** method to do this. Using **as_download** causes the files in the file dataset to be downloaded to a temporary location on the compute where the script is being run, while **as_mount** creates a mount point from which the files can be streamed directly from the datasetore.\n\nYou can combine the access method with the **as_named_input** method to include the dataset in the **input_datasets** collection in the experiment run (if you omit this, for example by setting the argument to `diabetes_ds.as_mount()`, the script will be able to access the dataset mount point from the script arguments, but not from the **input_datasets** collection).",
"_____no_output_____"
],
[
"#### Extra note:\n\n#### Use a script argument for a file dataset\n\nYou can pass a file dataset as a script argument. Unlike with a tabular dataset, you must specify a mode for the file dataset argument, which can be as_download or as_mount. This provides an access point that the script can use to read the files in the dataset. In most cases, you should use as_download, which copies the files to a temporary location on the compute where the script is being run. However, if you are working with a large amount of data for which there may not be enough storage space on the experiment compute, use as_mount to stream the files directly from their source.\n\nScriptRunConfig:\n\n```\nenv = Environment('my_env')\npackages = CondaDependencies.create(conda_packages=['pip'],\n pip_packages=['azureml-defaults',\n 'azureml-dataprep[pandas]'])\nenv.python.conda_dependencies = packages\n\nscript_config = ScriptRunConfig(source_directory='my_dir',\n script='script.py',\n arguments=['--ds', file_ds.as_download()],\n environment=env)\n```\n\nScript:\n\n```\nfrom azureml.core import Run\nimport glob\n\nparser.add_argument('--ds', type=str, dest='ds_ref')\nargs = parser.parse_args()\nrun = Run.get_context()\n\nimgs = glob.glob(ds_ref + \"/*.jpg\")\n```\n\n#### Use a named input for a file dataset\n\nYou can also pass a file dataset as a named input. In this approach, you use the as_named_input method of the dataset to specify a name before specifying the access mode. Then in the script, you can retrieve the dataset by name from the run context's input_datasets collection and read the files from there. As with tabular datasets, if you use a named input, you still need to include a script argument for the dataset, even though you don’t actually use it to retrieve the dataset.\n\nScriptRunConfig:\n\n```\nenv = Environment('my_env')\npackages = CondaDependencies.create(conda_packages=['pip'],\n pip_packages=['azureml-defaults',\n 'azureml-dataprep[pandas]'])\nenv.python.conda_dependencies = packages\n\nscript_config = ScriptRunConfig(source_directory='my_dir',\n script='script.py',\n arguments=['--ds', file_ds.as_named_input('my_ds').as_download()],\n environment=env)\n```\n\nScript:\n\n```\nfrom azureml.core import Run\nimport glob\n\nparser.add_argument('--ds', type=str, dest='ds_ref')\nargs = parser.parse_args()\nrun = Run.get_context()\n\ndataset = run.input_datasets['my_ds']\nimgs= glob.glob(dataset + \"/*.jpg\")\n```",
"_____no_output_____"
]
],
[
[
"from azureml.core import Experiment\nfrom azureml.widgets import RunDetails\n\n\n# Get the training dataset\ndiabetes_ds = ws.datasets.get(\"diabetes file dataset\")\n\n# Create a script config\nscript_config = ScriptRunConfig(source_directory=experiment_folder,\n script='diabetes_training.py',\n arguments = ['--regularization', 0.1, # Regularizaton rate parameter\n '--input-data', diabetes_ds.as_named_input('training_files').as_download()], # Reference to dataset location\n environment=sklearn_env) # Use the environment created previously\n\n# submit the experiment\nexperiment_name = 'mslearn-train-diabetes'\nexperiment = Experiment(workspace=ws, name=experiment_name)\nrun = experiment.submit(config=script_config)\nRunDetails(run).show()\nrun.wait_for_completion()",
"_____no_output_____"
]
],
[
[
"When the experiment has completed, in the widget, view the **azureml-logs/70_driver_log.txt** output log to verify that the files in the file dataset were downloaded to a temporary folder to enable the script to read the files.\n\n### Register the trained model\n\nOnce again, you can register the model that was trained by the experiment.",
"_____no_output_____"
]
],
[
[
"from azureml.core import Model\n\nrun.register_model(model_path='outputs/diabetes_model.pkl', model_name='diabetes_model',\n tags={'Training context':'File dataset'}, properties={'AUC': run.get_metrics()['AUC'], 'Accuracy': run.get_metrics()['Accuracy']})\n\nfor model in Model.list(ws):\n print(model.name, 'version:', model.version)\n for tag_name in model.tags:\n tag = model.tags[tag_name]\n print ('\\t',tag_name, ':', tag)\n for prop_name in model.properties:\n prop = model.properties[prop_name]\n print ('\\t',prop_name, ':', prop)\n print('\\n')",
"diabetes_model version: 4\n\t Training context : File dataset\n\t AUC : 0.8568517900798176\n\t Accuracy : 0.7891111111111111\n\n\ndiabetes_model version: 3\n\t Training context : Tabular dataset\n\t AUC : 0.8568595320655352\n\t Accuracy : 0.7891111111111111\n\n\ndiabetes_model version: 2\n\t Training context : Parameterized script\n\t AUC : 0.8484357430717946\n\t Accuracy : 0.774\n\n\ndiabetes_model version: 1\n\t Training context : Script\n\t AUC : 0.8483203144435048\n\t Accuracy : 0.774\n\n\n"
]
],
[
[
"> **More Information**: For more information about training with datasets, see [Training with Datasets](https://docs.microsoft.com/azure/machine-learning/how-to-train-with-datasets) in the Azure ML documentation.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e77d0f02643eb47896b22b4f63a08be3ba685846 | 2,974 | ipynb | Jupyter Notebook | data/.ipynb_checkpoints/Generate Disaggregate Data-checkpoint.ipynb | jungangl/forecast-machine-learning | 8e0574aee4999d244ed0d5db1ae142542398df62 | [
"MIT"
] | null | null | null | data/.ipynb_checkpoints/Generate Disaggregate Data-checkpoint.ipynb | jungangl/forecast-machine-learning | 8e0574aee4999d244ed0d5db1ae142542398df62 | [
"MIT"
] | null | null | null | data/.ipynb_checkpoints/Generate Disaggregate Data-checkpoint.ipynb | jungangl/forecast-machine-learning | 8e0574aee4999d244ed0d5db1ae142542398df62 | [
"MIT"
] | null | null | null | 27.284404 | 150 | 0.54842 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
e77d100109b8d1977b76cef9a648ee6dd4248977 | 173,677 | ipynb | Jupyter Notebook | module3-nosql-and-document-oriented-databases/mongodb_scratch.ipynb | dmhliu/DS-Unit-3-Sprint-2-SQL-and-Databases | 2146634b252270e5641fb9e6fd20b8e7300aa291 | [
"MIT"
] | null | null | null | module3-nosql-and-document-oriented-databases/mongodb_scratch.ipynb | dmhliu/DS-Unit-3-Sprint-2-SQL-and-Databases | 2146634b252270e5641fb9e6fd20b8e7300aa291 | [
"MIT"
] | null | null | null | module3-nosql-and-document-oriented-databases/mongodb_scratch.ipynb | dmhliu/DS-Unit-3-Sprint-2-SQL-and-Databases | 2146634b252270e5641fb9e6fd20b8e7300aa291 | [
"MIT"
] | null | null | null | 159.923573 | 292 | 0.608152 | [
[
[
"import pymongo \nimport datetime\nimport json\nclient = pymongo.MongoClient(\"mongodb+srv://foobarfoobar:[email protected]/?retryWrites=true&w=majority\")\ndb = client.test\n#collection = db.test_collection\n\n\"\"\"EXAMPLE FROM DOCS\nrepresent a document as a dict, or json\"\"\"\n\ntestpost = {\"author\": \"Dave Liu\",\n \"text\": \"trivial example of document\",\n \"tags\": [\"mongodb\", \"hello world\", \"python\"],\n \"date\": datetime.datetime.now()}\nposts = db.posts\npost_id = posts.insert_one(testpost).inserted_id\nprint(post_id)\n\n\"\"\"rpg \"\"\"\n\nrpg_character = {'id': 1, \"data\": {'name': \"test char\", 'attr': [10,3,0,0]}}\n\nrpg_test = db.rpg_test\n\nrpg_test.insert_one(rpg_character)\n",
"5f10b4a3ac6ec7d00bad89b2\n"
],
[
"rpg_test.drop()\nrpg_mdb.drop()",
"_____no_output_____"
],
[
"with open('testdata.json') as json_file:\n r= json.load(json_file)\n",
"_____no_output_____"
],
[
"\njson_url = \"https://github.com/LambdaSchool/Django-RPG/blob/master/testdata.json\"\n\nwith open('testdata.json') as json_file:\n rpg_json = json.load(json_file)\n \ncoll = db.rpg_data #collection\nfor r in rpg_json:\n coll.insert_one(r)",
"{'model': 'charactercreator.character', 'pk': 1, 'fields': {'name': 'Aliquid iste optio reiciendi', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [20, 58, 85]}, '_id': ObjectId('5f10b501ac6ec7d00bad89b4')}\n{'model': 'charactercreator.character', 'pk': 2, 'fields': {'name': 'Optio dolorem ex a', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [93, 115, 133]}, '_id': ObjectId('5f10b501ac6ec7d00bad89b5')}\n{'model': 'charactercreator.character', 'pk': 3, 'fields': {'name': 'Minus c', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [8, 43]}, '_id': ObjectId('5f10b501ac6ec7d00bad89b6')}\n{'model': 'charactercreator.character', 'pk': 4, 'fields': {'name': 'Sit ut repr', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [21, 82, 85, 135]}, '_id': ObjectId('5f10b501ac6ec7d00bad89b7')}\n{'model': 'charactercreator.character', 'pk': 5, 'fields': {'name': 'At id recusandae expl', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [7, 96, 140, 145]}, '_id': ObjectId('5f10b501ac6ec7d00bad89b8')}\n{'model': 'charactercreator.character', 'pk': 6, 'fields': {'name': 'Non nobis et of', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [93]}, '_id': ObjectId('5f10b501ac6ec7d00bad89b9')}\n{'model': 'charactercreator.character', 'pk': 7, 'fields': {'name': 'Perferendis', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [38, 42, 85, 123, 166]}, '_id': ObjectId('5f10b501ac6ec7d00bad89ba')}\n{'model': 'charactercreator.character', 'pk': 8, 'fields': {'name': 'Accusantium amet quidem eve', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [43, 48, 119]}, '_id': ObjectId('5f10b501ac6ec7d00bad89bb')}\n{'model': 'charactercreator.character', 'pk': 9, 'fields': {'name': 'Sed nostrum inventore error m', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [32, 106, 116, 125]}, '_id': ObjectId('5f10b501ac6ec7d00bad89bc')}\n{'model': 'charactercreator.character', 'pk': 10, 'fields': {'name': 'Harum repellendus omnis od', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [117, 129, 131, 135]}, '_id': ObjectId('5f10b502ac6ec7d00bad89bd')}\n{'model': 'charactercreator.character', 'pk': 11, 'fields': {'name': 'Itaque ut commodi,', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [54, 108, 158]}, '_id': ObjectId('5f10b502ac6ec7d00bad89be')}\n{'model': 'charactercreator.character', 'pk': 12, 'fields': {'name': 'Molestiae quis', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [65, 115, 126]}, '_id': ObjectId('5f10b502ac6ec7d00bad89bf')}\n{'model': 'charactercreator.character', 'pk': 13, 'fields': {'name': 'Ali', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [38, 44, 62, 125]}, '_id': ObjectId('5f10b502ac6ec7d00bad89c0')}\n{'model': 'charactercreator.character', 'pk': 14, 'fields': {'name': 'Tempora quod optio possimus il', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [34, 41, 65, 68]}, '_id': ObjectId('5f10b502ac6ec7d00bad89c1')}\n{'model': 'charactercreator.character', 'pk': 15, 'fields': {'name': 'Sed itaque beatae pari', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [34, 56, 74, 84]}, '_id': ObjectId('5f10b502ac6ec7d00bad89c2')}\n{'model': 'charactercreator.character', 'pk': 16, 'fields': {'name': 'Quam dolor', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [87]}, '_id': ObjectId('5f10b502ac6ec7d00bad89c3')}\n{'model': 'charactercreator.character', 'pk': 17, 'fields': {'name': 'Molestias expedita', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [64, 68, 116, 128, 136]}, '_id': ObjectId('5f10b502ac6ec7d00bad89c4')}\n{'model': 'charactercreator.character', 'pk': 18, 'fields': {'name': 'Lauda', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [17, 60, 62, 64, 90]}, '_id': ObjectId('5f10b502ac6ec7d00bad89c5')}\n{'model': 'charactercreator.character', 'pk': 19, 'fields': {'name': 'Incidunt sint perferen', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [5, 52, 113]}, '_id': ObjectId('5f10b503ac6ec7d00bad89c6')}\n{'model': 'charactercreator.character', 'pk': 20, 'fields': {'name': 'Laboriosa', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [156]}, '_id': ObjectId('5f10b503ac6ec7d00bad89c7')}\n{'model': 'charactercreator.character', 'pk': 21, 'fields': {'name': 'Dolore esse nesciunt fugit com', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [33, 34, 51, 117]}, '_id': ObjectId('5f10b503ac6ec7d00bad89c8')}\n{'model': 'charactercreator.character', 'pk': 22, 'fields': {'name': 'Dolorum nam reic', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [41, 43, 164]}, '_id': ObjectId('5f10b503ac6ec7d00bad89c9')}\n{'model': 'charactercreator.character', 'pk': 23, 'fields': {'name': 'Repellat ad numquam volu', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [33, 61, 160]}, '_id': ObjectId('5f10b503ac6ec7d00bad89ca')}\n{'model': 'charactercreator.character', 'pk': 24, 'fields': {'name': 'Facere enim velit eligend', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [8]}, '_id': ObjectId('5f10b503ac6ec7d00bad89cb')}\n{'model': 'charactercreator.character', 'pk': 25, 'fields': {'name': 'Sed ratione quis rep', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [50, 122]}, '_id': ObjectId('5f10b503ac6ec7d00bad89cc')}\n{'model': 'charactercreator.character', 'pk': 26, 'fields': {'name': 'Doloribus neque', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [112, 149]}, '_id': ObjectId('5f10b503ac6ec7d00bad89cd')}\n{'model': 'charactercreator.character', 'pk': 27, 'fields': {'name': 'Ab voluptas se', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [10, 104, 148, 157, 172]}, '_id': ObjectId('5f10b503ac6ec7d00bad89ce')}\n{'model': 'charactercreator.character', 'pk': 28, 'fields': {'name': 'Molestias m', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [51]}, '_id': ObjectId('5f10b503ac6ec7d00bad89cf')}\n{'model': 'charactercreator.character', 'pk': 29, 'fields': {'name': 'In pariatur corpori', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [107, 120, 157, 170]}, '_id': ObjectId('5f10b503ac6ec7d00bad89d0')}\n{'model': 'charactercreator.character', 'pk': 30, 'fields': {'name': 'Possimus ad dignissimos vel, a', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [69, 109, 114, 138]}, '_id': ObjectId('5f10b503ac6ec7d00bad89d1')}\n{'model': 'charactercreator.character', 'pk': 31, 'fields': {'name': 'At minus accusa', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [9, 45, 61]}, '_id': ObjectId('5f10b503ac6ec7d00bad89d2')}\n{'model': 'charactercreator.character', 'pk': 32, 'fields': {'name': 'Ad necess', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [111, 142]}, '_id': ObjectId('5f10b503ac6ec7d00bad89d3')}\n{'model': 'charactercreator.character', 'pk': 33, 'fields': {'name': 'Expedita c', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [64, 110]}, '_id': ObjectId('5f10b504ac6ec7d00bad89d4')}\n{'model': 'charactercreator.character', 'pk': 34, 'fields': {'name': 'Voluptates sunt voluptas volu', 'level': 0, 'exp': 0, 'hp': 10, 'strength': 1, 'intelligence': 1, 'dexterity': 1, 'wisdom': 1, 'inventory': [5, 90, 132, 160]}, '_id': ObjectId('5f10b504ac6ec7d00bad89d5')}\n"
],
[
"#rpgmdb.rpgdata # collection \nc= db[\"rpg_data\"] \n\n\nc.estimated_document_count()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code"
]
] |
e77d1164bfc22a0f318134b6b466f151fd532af7 | 12,496 | ipynb | Jupyter Notebook | ikdp2korp.ipynb | langdoc/eaf2korp | 937a54e6f805c3109d92ec432f2489bdd4a3f46c | [
"Apache-2.0"
] | 1 | 2020-04-12T10:48:33.000Z | 2020-04-12T10:48:33.000Z | ikdp2korp.ipynb | langdoc/eaf2korp | 937a54e6f805c3109d92ec432f2489bdd4a3f46c | [
"Apache-2.0"
] | null | null | null | ikdp2korp.ipynb | langdoc/eaf2korp | 937a54e6f805c3109d92ec432f2489bdd4a3f46c | [
"Apache-2.0"
] | null | null | null | 50.796748 | 432 | 0.643166 | [
[
[
"import os, shutil\nfrom pathlib import Path\nfrom uralicNLP.cg3 import Cg3\nfrom uralicNLP import uralicApi\nfrom nltk.tokenize import word_tokenize\nimport pympi\nimport xml.etree.cElementTree as ET\nimport re\n\nimport eaf2korp",
"_____no_output_____"
]
],
[
[
"We have a folder called `vrt`, however, we want to empty it first before writing new annotation files into it. The idea should be that we modify ELAN files, and the changes there result in update of old VRT files. Of course replacing all of them at once is not very effective, so there probably should be Git commit info in VRT, or in configuration file, with a check whether there has been an update or not since that commit.",
"_____no_output_____"
]
],
[
[
"folder = './vrt'\nfor the_file in os.listdir(folder):\n file_path = os.path.join(folder, the_file)\n try:\n if os.path.isfile(file_path):\n os.unlink(file_path)\n except Exception as e:\n print(e)",
"_____no_output_____"
]
],
[
[
"`eaf2vrt` function is designed so that it takes an ELAN file and writes it into an arbitrary location as a VRT file. Thereby both input and output file have to be specified. Also ELAN tier that contains the annotations we want to work with has to be specified.",
"_____no_output_____"
]
],
[
[
"filenames = sorted(Path('/Users/niko/langdoc/kpv/').glob('**/kpv_izva*.eaf'))\n\nfor filename in filenames:\n elan_file = str(filename)\n session_name = Path(elan_file).stem\n vrt_file = 'vrt/' + session_name + '.vrt'\n eaf2korp.eaf2vrt(elan_file_path = elan_file, vrt_file_path = vrt_file)\n ",
"Parsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\nParsing unknown version of ELAN spec... This could result in errors...\n"
]
],
[
[
"This leaves us with a folder full of VRT files. In this point we just have to specify the language which uralicNLP uses to run the analyser.",
"_____no_output_____"
]
],
[
[
"filenames = sorted(Path('vrt/').glob('*.vrt'))\n\nfor filename in filenames:\n vrt_file = str(filename)\n eaf2korp.annotate_vrt(vrt_file_path = vrt_file, language = \"kpv\")\n",
"_____no_output_____"
]
],
[
[
"The whole analysis takes few minutes, which seems more than reasonable.",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e77d11dac60f377c7bc6d598979c2d0aac960f55 | 971,238 | ipynb | Jupyter Notebook | notebooks/archive/2.0-hef-beacon-exploration.ipynb | intelligent-environments-lab/utx000 | af60a6162d21e38f8cfa5cdebc0f14e717205f12 | [
"MIT"
] | null | null | null | notebooks/archive/2.0-hef-beacon-exploration.ipynb | intelligent-environments-lab/utx000 | af60a6162d21e38f8cfa5cdebc0f14e717205f12 | [
"MIT"
] | 95 | 2020-06-08T17:29:13.000Z | 2021-11-04T02:03:22.000Z | notebooks/archive/2.0-hef-beacon-exploration.ipynb | intelligent-environments-lab/utx000 | af60a6162d21e38f8cfa5cdebc0f14e717205f12 | [
"MIT"
] | 1 | 2022-02-17T17:14:03.000Z | 2022-02-17T17:14:03.000Z | 689.799716 | 128,564 | 0.940644 | [
[
[
"# UT2000 Home Environment Exploratory Analysis\nWe now take a closer look at the beacon and home environment survey data to see if we can tease anything out of it or at least show something. ",
"_____no_output_____"
]
],
[
[
"import math",
"_____no_output_____"
]
],
[
[
"# Data Import\nWe have two things to import: (1) the home environment survey and (2) the beacon data",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nimport os\nfrom datetime import datetime",
"_____no_output_____"
]
],
[
[
"## Home Environment Survey\nThe get the home environment survey data, please make sure to run ```$ python3 src/data/make_dataset.py``` and choose the option for the HEH survey. This will combine, clean, and save the home environment survey data to the processed data directory.",
"_____no_output_____"
]
],
[
[
"HEH = pd.read_csv(f'/Users/hagenfritz/Projects/utx000/data/processed/ut3000-heh.csv')\nHEH.head()",
"_____no_output_____"
]
],
[
[
"## Beacons\nTo get the beacon data for the UT2000 study, be sure ture run ```$ python3 src/data/make_dataset.py``` and chooose the option for the ut2000 beacons. This will combine, clean, and save the beacon data to the processed data directory.",
"_____no_output_____"
]
],
[
[
"beacons = pd.read_csv(f'/Users/hagenfritz/Projects/utx000/data/processed/ut2000-beacon.csv',\n index_col=0,parse_dates=True,infer_datetime_format=True)\nbeacons.head()",
"_____no_output_____"
]
],
[
[
"# Visualization and Analysis\nNow we get to the meat of it - visualizing and doing some simple statistics on the data.",
"_____no_output_____"
]
],
[
[
"import seaborn as sns\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nfrom matplotlib.colors import ListedColormap, LinearSegmentedColormap",
"_____no_output_____"
]
],
[
[
"## Heat Maps",
"_____no_output_____"
],
[
"Investigating Participant 36dsqll3 (Beacon 6) who we used in the MADS Framework paper. There were some questions about the values reported in the Figure 3 which corresponds to 3/30.",
"_____no_output_____"
]
],
[
[
"fig,ax = plt.subplots(figsize=(8,6))\ndf = df_hm\nsns.heatmap(data=df,cmap='inferno_r',cbar=True,square=False,ax=ax)\nlabels = []\nfor d in df.index:\n dd = datetime(d.year,d.month,d.day)\n if dd >= datetime(2019,3,18) and dd <= datetime(2019,3,23):\n labels.append(datetime.strftime(d,'%a %m/%d')+'*')\n else:\n labels.append(datetime.strftime(d,'%a %m/%d'))\nax.set_yticklabels(labels)\nax.set_xlabel('Hour of Day')\n\nplt.show()\nplt.close()",
"_____no_output_____"
]
],
[
[
"<div class=\"alert alert-block alert-danger\">\n Seems the concentration spikes for whatever reason on 3/30\n</div>",
"_____no_output_____"
]
],
[
[
"def plot_heat_map(df):\n '''\n \n '''\n \n fig,ax = plt.subplots(figsize=(8,6))\n df = df/np.nanmax(df)\n sns.heatmap(data=df,cmap='inferno_r',cbar=True,cbar_kws={'ticks':[]},square=False,ax=ax)\n ax.text(25,27.4,'Minimum',bbox={'facecolor':'white'},zorder=10)\n ax.text(25,-1,'Maximum',bbox={'facecolor':'white'},zorder=10)\n labels = []\n for d in df.index:\n dd = datetime(d.year,d.month,d.day)\n if dd >= datetime(2019,3,18) and dd <= datetime(2019,3,23):\n labels.append(datetime.strftime(d,'%a %m/%d')+'*')\n else:\n labels.append(datetime.strftime(d,'%a %m/%d'))\n ax.set_yticklabels(labels)\n ax.set_ylabel('Day in 2019')\n ax.set_xlabel('Hour of Day')\n\n return ax",
"_____no_output_____"
]
],
[
[
"### per Beacon\nThe following cell creates heat maps for each beacon for each sensor.",
"_____no_output_____"
]
],
[
[
"for b in [1,2,5]:\n df = beacons[beacons['number'] == b]\n df = df.resample('1h').mean()\n df['hour'] = df.index.hour\n df['day'] = df.index.date\n df = df.dropna()\n df = df[datetime(2019,3,16):datetime(2019,4,5,23)]\n df_pm = df.pivot_table(index='day',columns='hour',values='pm2.5')\n df_tc = df.pivot_table(index='day',columns='hour',values='TC')\n df_rh = df.pivot_table(index='day',columns='hour',values='RH')\n df_tvoc = df.pivot_table(index='day',columns='hour',values='TVOC')\n fig, ax = plt.subplots(2,3,figsize=(14,14),gridspec_kw={'width_ratios': [15, 14, 1]})\n sns.heatmap(df_pm,cmap='inferno_r',ax=ax[0,0], cbar=False)\n sns.heatmap(df_tvoc,cmap='inferno_r',ax=ax[0,1],cbar_ax=ax[0,2],cbar_kws={'ticks':[]})\n sns.heatmap(df_tc,cmap='inferno_r',ax=ax[1,0], cbar=False)\n sns.heatmap(df_rh,cmap='inferno_r',ax=ax[1,1],cbar_ax=ax[1,2],cbar_kws={'ticks':[]})\n\n labels = []\n for d in df_pm.index:\n dd = datetime(d.year,d.month,d.day)\n if dd >= datetime(2019,3,18) and dd <= datetime(2019,3,23):\n labels.append(datetime.strftime(d,'%a %m/%d')+'*')\n else:\n labels.append(datetime.strftime(d,'%a %m/%d'))\n axis = ax[0,0]\n axis.set_yticklabels(labels)\n axis.set_ylabel('Day in 2019')\n axis.set_xlabel('Hour of Day')\n axis.set_title('PM2.5 Concentration')\n axis = ax[0,1]\n axis.set_yticks([])\n axis.set_ylabel('')\n axis.set_xlabel('Hour of Day')\n axis.set_title('TVOC Concentration')\n axis = ax[1,0]\n axis.set_yticklabels(labels)\n axis.set_ylabel('Day in 2019')\n axis.set_ylabel('')\n axis.set_xlabel('Hour of Day')\n axis.set_title('Temperature')\n axis = ax[1,1]\n axis.set_yticks([])\n axis.set_ylabel('')\n axis.set_xlabel('Hour of Day')\n axis.set_title('Relative Humidity')\n ax[0,2].text(30,np.nanmin(df_tvoc),'Minimum',bbox={'facecolor':'white'},zorder=10,ha='center',va='top')\n ax[0,2].text(30,np.nanmax(df_tvoc),'Maximum',bbox={'facecolor':'white'},zorder=10,ha='center',va='bottom')\n ax[1,2].text(30,np.nanmin(df_rh),'Minimum',bbox={'facecolor':'white'},zorder=10,ha='center',va='top')\n ax[1,2].text(30,np.nanmax(df_rh),'Maximum',bbox={'facecolor':'white'},zorder=10,ha='center',va='bottom')\n\n plt.subplots_adjust(wspace=0.1)\n plt.savefig(f'/Users/hagenfritz/Projects/utx000/reports/figures/framework_paper/ut2000-beacon{b}-sensortrends-heatmap.png')\n plt.show()\n plt.close()",
"_____no_output_____"
]
],
[
[
"### per Beacon per Sensor\nNow we get even more fine-grained and show the heat map for each sensor on each beacon.",
"_____no_output_____"
]
],
[
[
"for no in [1,2,5,6]:\n df = beacons[beacons['number'] == no]\n df = df.resample('1h').mean()\n df['hour'] = df.index.hour\n df['day'] = df.index.date\n df = df.dropna()\n df = df[datetime(2019,3,11):datetime(2019,4,5)]\n df_hm = df.pivot_table(index='day',columns='hour',values='pm2.5')\n if len(df_hm) > 7:\n ax = plot_heat_map(df_hm)\n plt.savefig(f'/Users/hagenfritz/Projects/utx000/reports/figures/framework_paper/ut2000-beacon{no}-pm2p5-heatmap.png')\n ax.set_title(f'Beacon {no}: PM2.5')\n plt.show()\n plt.close()\n \n df_tc = df.pivot_table(index='day',columns='hour',values='TC')\n if len(df_tc) > 7:\n ax = plot_heat_map(df_tc)\n plt.savefig(f'/Users/hagenfritz/Projects/utx000/reports/figures/framework_paper/ut2000-beacon{no}-tc-heatmap.png')\n ax.set_title(f'Beacon {no}: Temperature')\n plt.show()\n plt.close()\n \n df_tvoc = df.pivot_table(index='day',columns='hour',values='TVOC')\n if len(df_tvoc) > 7:\n ax = plot_heat_map(df_tvoc)\n plt.savefig(f'/Users/hagenfritz/Projects/utx000/reports/figures/framework_paper/ut2000-beacon{no}-tvoc-heatmap.png')\n ax.set_title(f'Beacon {no}: TVOC')\n plt.show()\n plt.close()\n ",
"_____no_output_____"
]
],
[
[
"### Everything\nNow we combine all the beacons and all the sensors into one heat map. We still normalize the data, but now we do it per sensor for all the beacons.",
"_____no_output_____"
]
],
[
[
"fig, ax = plt.subplots(4,4,figsize=(16,18),sharex='col',gridspec_kw={'width_ratios': [15, 15, 15, 1]})\nrow = 0\nfor value in ['pm2.5','TVOC','TC','RH']:\n col = 0\n for b in [1,2,5]:\n # Getting heatmap dataframe\n df = beacons[beacons['number'] == b]\n df = df.resample('1h').mean()\n df['hour'] = df.index.hour\n df['day'] = df.index.date\n df = df.dropna()\n df = df[datetime(2019,3,16):datetime(2019,4,2,23)]\n df_var = df.pivot_table(index='day',columns='hour',values=value)\n df_var /= np.max(df_var)\n # plotting with the colobar from the last figure\n if col == 2:\n sns.heatmap(df_var,cmap='inferno_r',ax=ax[row,col],cbar_ax=ax[row,col+1],cbar_kws={'ticks':[]})\n else:\n sns.heatmap(df_var,cmap='inferno_r',ax=ax[row,col], cbar=False)\n # Formatting axes\n ax[row,col].set_xlabel('')\n ax[row,col].set_ylabel('')\n if col == 0:\n labels = []\n for d in df_var.index:\n dd = datetime(d.year,d.month,d.day)\n if dd >= datetime(2019,3,18) and dd <= datetime(2019,3,23):\n labels.append(datetime.strftime(d,'%a %m/%d')+'*')\n else:\n labels.append(datetime.strftime(d,'%a %m/%d')) \n #ax[row,col].set_yticks(df_var.index)\n ax[row,col].set_yticklabels(labels)\n else:\n ax[row,col].set_yticks([])\n\n if col == 1:\n if value == 'pm2.5':\n ax[row,col].set_title('PM2.5 Concentration')\n elif value == 'TVOC':\n ax[row,col].set_title('TVOC Concentration')\n elif value == 'TC':\n ax[row,col].set_title('Temperature')\n elif value == 'RH':\n ax[row,col].set_title('Relative Humidity')\n \n if row == 3:\n ax[row,col].set_xlabel('Hour of Day')\n \n col += 1\n \n row += 1\n \nax[3,3].text(0.75,0,'Min',zorder=10,ha='center',va='center')\nax[3,3].text(0.75,1,'Max',zorder=10,ha='center',va='bottom')\n#ax[2,3].text(30,np.nanmin(df_rh),'Minimum',bbox={'facecolor':'white'},zorder=10,ha='center',va='top')\n#ax[3,3].text(30,np.nanmax(df_rh),'Maximum',bbox={'facecolor':'white'},zorder=10,ha='center',va='bottom')\nplt.subplots_adjust(wspace=0.05,hspace=0.1)\nplt.savefig(f'/Users/hagenfritz/Projects/utx000/reports/figures/framework_paper/ut2000-beacon-comprehensive-heatmap.png')\nplt.show()\nplt.close()",
"_____no_output_____"
]
],
[
[
"### Split Heatmap",
"_____no_output_____"
]
],
[
[
"def create_cmap(colors,nodes):\n cmap = LinearSegmentedColormap.from_list(\"mycmap\", list(zip(nodes, colors)))\n return cmap",
"_____no_output_____"
]
],
[
[
"#### IAQ Heat Map\nThis heat map is NOT scaled but includes the actual values.",
"_____no_output_____"
]
],
[
[
"fig, ax = plt.subplots(2,3,figsize=(18,8),sharex='col',gridspec_kw={'width_ratios': [8, 8, 9]})\nrow = 0\nfor value in ['pm2.5','TVOC']:\n col = 0\n for b in [1,2,5]:\n # Getting heatmap dataframe\n df = beacons[beacons['number'] == b]\n df = df.resample('1h').mean()\n df['hour'] = df.index.hour\n df['day'] = df.index.date\n df = df.dropna()\n df = df[datetime(2019,3,16):datetime(2019,4,2,23)]\n df_var = df.pivot_table(index='day',columns='hour',values=value)\n # plotting with the colobar from the last figure\n if value == 'pm2.5':\n if col == 2:\n sns.heatmap(df_var,vmin=0,vmax=500,cmap=create_cmap([\"green\", \"yellow\", \"orange\", \"red\", \"purple\", \"black\"],[0.0, 0.048, 0.14, 0.22, 0.6, 1]),\n ax=ax[row,col],cbar_kws={'ticks':[35,150,250,500]})\n else:\n sns.heatmap(df_var,vmin=0,vmax=500,cmap=create_cmap([\"green\", \"yellow\", \"orange\", \"red\", \"purple\", \"black\"],[0.0, 0.048, 0.14, 0.22, 0.6, 1]),\n ax=ax[row,col], cbar=False)\n else:\n if col == 2:\n sns.heatmap(df_var,vmin=0,vmax=2200,cmap=create_cmap([\"green\", \"yellow\", \"orange\", \"red\", \"purple\"],[0.0, 0.03, 0.1, 0.3, 1]),\n ax=ax[row,col],cbar_kws={'ticks':[65,220,660,2200]})\n else:\n sns.heatmap(df_var,vmin=0,vmax=2200,cmap=create_cmap([\"green\", \"yellow\", \"orange\", \"red\", \"purple\"],[0.0, 0.03, 0.1, 0.3, 1]),\n ax=ax[row,col], cbar=False)\n # Formatting axes\n ax[row,col].set_xlabel('')\n ax[row,col].set_ylabel('')\n if col == 0:\n labels = np.arange(1,len(df_var)+1,1)\n ax[row,col].set_yticklabels(labels)\n else:\n ax[row,col].set_yticks([])\n\n if col == 1:\n if value == 'pm2.5':\n ax[row,col].set_title('PM2.5 Concentration ($\\mu$g/m$^3$)')\n elif value == 'TVOC':\n ax[row,col].set_title('TVOC Concentration (ppb)')\n \n if row == 1:\n ax[row,col].set_xlabel('('+chr(ord('@')+col+1)+')')\n \n col += 1\n \n row += 1\n \nfig.text(0.5, 0.05, 'Hour of the Day', ha='center', va='center',size='x-large')\nfig.text(0.1, 0.5, 'Day During Study', ha='center', va='center', rotation='vertical',size='x-large')\n\nplt.subplots_adjust(wspace=0.05,hspace=0.15)\nplt.savefig(f'/Users/hagenfritz/Projects/utx000/reports/figures/framework_paper/ut2000-beacon-iaq-heatmap.pdf',bbox_inches='tight')\nplt.show()\nplt.close()",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(2,2,figsize=(16,8),sharex='col',gridspec_kw={'width_ratios': [8, 9]})\nrow = 0\nfor value in ['pm2.5','TVOC']:\n col = 0\n for b in [1,2]:\n # Getting heatmap dataframe\n df = beacons[beacons['number'] == b]\n df = df.resample('1h').mean()\n df['hour'] = df.index.hour\n df['day'] = df.index.date\n df = df.dropna()\n df = df[datetime(2019,3,16):datetime(2019,4,2,23)]\n df_var = df.pivot_table(index='day',columns='hour',values=value)\n # plotting with the colobar from the last figure\n if value == 'pm2.5':\n if col == 1:\n sns.heatmap(df_var,vmin=0,vmax=500,cmap=create_cmap([\"green\", \"yellow\", \"orange\", \"red\", \"purple\", \"black\"],[0.0, 0.048, 0.14, 0.22, 0.6, 1]),\n ax=ax[row,col],cbar_kws={'ticks':[35,150,250,500]})\n else:\n sns.heatmap(df_var,vmin=0,vmax=500,cmap=create_cmap([\"green\", \"yellow\", \"orange\", \"red\", \"purple\", \"black\"],[0.0, 0.048, 0.14, 0.22, 0.6, 1]),\n ax=ax[row,col], cbar=False)\n else:\n if col == 1:\n sns.heatmap(df_var,vmin=0,vmax=2200,cmap=create_cmap([\"green\", \"yellow\", \"orange\", \"red\", \"purple\"],[0.0, 0.03, 0.1, 0.3, 1]),\n ax=ax[row,col],cbar_kws={'ticks':[65,220,660,2200]})\n else:\n sns.heatmap(df_var,vmin=0,vmax=2200,cmap=create_cmap([\"green\", \"yellow\", \"orange\", \"red\", \"purple\"],[0.0, 0.03, 0.1, 0.3, 1]),\n ax=ax[row,col], cbar=False)\n # Formatting axes\n ax[row,col].set_xlabel('')\n ax[row,col].set_ylabel('')\n if col == 0:\n labels = np.arange(1,len(df_var)+1,1)\n ax[row,col].set_yticklabels(labels)\n else:\n ax[row,col].set_yticks([])\n\n if col == 1:\n if value == 'pm2.5':\n ax[row,col].set_title('PM2.5 Concentration ($\\mu$g/m$^3$)')\n elif value == 'TVOC':\n ax[row,col].set_title('TVOC Concentration (ppb)')\n \n if row == 1:\n ax[row,col].set_xlabel('('+chr(ord('@')+col+1)+')')\n \n col += 1\n \n row += 1\n \nfig.text(0.5, 0.05, 'Hour of the Day', ha='center', va='center',size='x-large')\nfig.text(0.1, 0.5, 'Day During Study', ha='center', va='center', rotation='vertical',size='x-large')\n\nplt.subplots_adjust(wspace=0.05,hspace=0.15)\nplt.savefig(f'/Users/hagenfritz/Projects/utx000/reports/figures/framework_paper/ut2000-beacon-iaq-heatmap-b1and2.pdf',bbox_inches='tight')\nplt.show()\nplt.close()",
"_____no_output_____"
]
],
[
[
"#### T/RH Heat Map\nThe T/RH values are scaled between 0 and 1. ",
"_____no_output_____"
]
],
[
[
"fig, ax = plt.subplots(2,3,figsize=(18,8),sharex='col',gridspec_kw={'width_ratios': [8, 8, 9]})\nrow = 0\nfor value in ['TC','RH']:\n col = 0\n for b in [1,2,5]:\n # Getting heatmap dataframe\n df = beacons[beacons['number'] == b]\n df = df.resample('1h').mean()\n df['hour'] = df.index.hour\n df['day'] = df.index.date\n df = df.dropna()\n df = df[datetime(2019,3,16):datetime(2019,4,2,23)]\n df_var = df.pivot_table(index='day',columns='hour',values=value)\n df_var = (df_var-df_var.min())/(df_var.max()-df_var.min())\n # plotting with the colobar from the last figure\n if col == 2:\n sns.heatmap(df_var,vmin=0,vmax=1,cmap='coolwarm',\n ax=ax[row,col])\n else:\n sns.heatmap(df_var,vmin=0,vmax=1,cmap='coolwarm',\n ax=ax[row,col], cbar=False)\n # Formatting axes\n ax[row,col].set_xlabel('')\n ax[row,col].set_ylabel('')\n if col == 0:\n labels = np.arange(1,len(df_var)+1,1)\n ax[row,col].set_yticklabels(labels)\n else:\n ax[row,col].set_yticks([])\n\n if col == 1:\n if value == 'TC':\n ax[row,col].set_title('Temperature')\n elif value == 'RH':\n ax[row,col].set_title('Relative Humidity')\n \n if row == 1:\n ax[row,col].set_xlabel('('+chr(ord('@')+col+1)+')')\n \n col += 1\n \n row += 1\n \nfig.text(0.5, 0.05, 'Hour of the Day', ha='center', va='center',size='x-large')\nfig.text(0.1, 0.5, 'Day During Study', ha='center', va='center', rotation='vertical',size='x-large')\n\nplt.subplots_adjust(wspace=0.05,hspace=0.15)\nplt.savefig(f'/Users/hagenfritz/Projects/utx000/reports/figures/framework_paper/ut2000-beacon-trh-heatmap.pdf',bbox_inches='tight')\nplt.show()\nplt.close()",
"_____no_output_____"
]
],
[
[
"## Beacon Covariance Plot\nThe covariance plot will give a nice look at the relationship between the four variables measured on the beacon2.0: PM, TVOC, Temperature, and RH.",
"_____no_output_____"
]
],
[
[
"# Cleaning up the dataframe\n## Removing high values\ndf = beacons[beacons['TVOC'] < 800]\ndf = df[df['pm2.5'] < 300]\n## Removing and renaming columns\ndf = df[['pm2.5','TVOC','TC','RH']]\ndf.columns = ['PM2.5 ($\\mu$g/m$^3$)','TVOC (ppb)', 'Temperature ($^\\circ$C)', 'Relative Humidity']\n# Plotting\nsns.pairplot(df,corner=False)\nplt.savefig('/Users/hagenfritz/Projects/utx000/reports/figures/framework_paper/ut2000-beacon-beacon-pairplot.png')\nplt.show()\nplt.close()",
"_____no_output_____"
]
],
[
[
"## Floor Type and PM/TVOC",
"_____no_output_____"
]
],
[
[
"# Getting only the ut200 responses and simplifying the dataframe\nheh2000 = HEH[HEH['study'] == 'ut2000']\nfloor2000 = heh2000[['record_id', 'amt_carpet','hardwd_amt', 'tile_amt','beacon']]\nfloor2000",
"_____no_output_____"
],
[
"# Plotting the distributions of air pollutants based on floor type\nfig, ax = plt.subplots(2,1,figsize=(12,12))\nheh2000.sort_values(['beacon'],inplace=True)\nfor no in heh2000['beacon'].unique():\n df = beacons[beacons['number'] == no]\n # Removing high tvoc/pm values and resaving\n df_tvoc = df[df['TVOC'] < 800]\n df_pm = df[df['pm2.5'] < 300]\n # Getting the row from the heh that corresponds to the beacon\n floorBeacon = floor2000[floor2000['beacon'] == no]\n # Plotting with slightly different formats for each floor type\n if floorBeacon['amt_carpet'].values[0] > 80:\n sns.kdeplot(df_tvoc['TVOC'],linewidth=2,color='firebrick',ax=ax[0],label=f'B{str(no)[:-2]}: carpet')\n sns.kdeplot(df_pm['pm2.5'],linewidth=2,color='firebrick',ax=ax[1],label='_nolabel_')\n elif floorBeacon['hardwd_amt'].values[0] > 80:\n sns.kdeplot(df_tvoc['TVOC'],color='gold',ax=ax[0],label=f'B{str(no)[:-2]}: hardwood')\n sns.kdeplot(df_pm['pm2.5'],color='gold',ax=ax[1],label='_nolabel_')\n elif floorBeacon['tile_amt'].values[0] > 80:\n sns.kdeplot(df_tvoc['TVOC'],color='seagreen',ax=ax[0],label=f'B{str(no)[:-2]}: tile')\n sns.kdeplot(df_pm['pm2.5'],color='seagreen',ax=ax[1],label='_nolabel_')\n else:\n print(f'No dominant floor type for the participant with beacon {no}')\n \nax[0].legend(title='Beacon and Dwelling Type',loc='upper right',frameon=True,ncol=2)\nax[0].set_xlabel('TVOC Concentration (ppb)')\nax[1].set_xlabel('PM2.5 Concentration ($\\mu$g/m$^3$)')\nplt.subplots_adjust(hspace=0.15)\nplt.savefig('../reports/figures/framework_paper/ut2000-beacon-heh-pollutants-flooring-distribution.png')\nplt.show()\nplt.close()",
"_____no_output_____"
]
],
[
[
"## Dwelling Type and Pollution\nNow we look at the different dwelling type and see if that has an effect on the pollutant concentration.",
"_____no_output_____"
]
],
[
[
"dwelling2000 = heh2000[['record_id', 'livingsit','beacon']]\ndwelling2000",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(2,1,figsize=(12,12))\nfor no in heh2000['beacon'].unique():\n df = beacons[beacons['number'] == no]\n # Removing high tvoc/pm values and resaving\n df_tvoc = df[df['TVOC'] < 800]\n df_pm = df[df['pm2.5'] < 300]\n # Getting the row from the heh that corresponds to the beacon\n dwellingBeacon = dwelling2000[dwelling2000['beacon'] == no]\n # Plotting with slightly different formats for each floor type\n if dwellingBeacon['livingsit'].values[0] == 'Apartment':\n sns.kdeplot(df_tvoc['TVOC'],linewidth=2,color='black',alpha=0.8,ax=ax[0],label=f'B{str(no)[:-2]}: Apt')\n sns.kdeplot(df_pm['pm2.5'],linewidth=2,color='black',alpha=0.8,ax=ax[1],label='_nolabel_')\n else:\n sns.kdeplot(df_tvoc['TVOC'],color='cornflowerblue',linewidth=2,ax=ax[0],label=f'B{str(no)[:-2]}: House')\n sns.kdeplot(df_pm['pm2.5'],color='cornflowerblue',linewidth=2,ax=ax[1],label='_nolabel_')\n \nax[0].legend(title='Beacon and Dwelling Type',loc='upper right',frameon=True,ncol=2)\nax[0].set_xlabel('TVOC Concentration (ppb)')\nax[1].set_xlabel('PM2.5 Concentration ($\\mu$g/m$^3$)')\nplt.subplots_adjust(hspace=0.15)\nplt.savefig('../reports/figures/framework_paper/ut2000-beacon-heh-pollutants-dwelling-distribution.png')\nplt.show()\nplt.close()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e77d11e2145b7b459636a1e1f34544e209e98767 | 298,453 | ipynb | Jupyter Notebook | predict_image.ipynb | NeoBryant/Brain_Image_Segmentation | 001826a3872db27682e929a2acd6ea27dbba7125 | [
"Apache-2.0"
] | null | null | null | predict_image.ipynb | NeoBryant/Brain_Image_Segmentation | 001826a3872db27682e929a2acd6ea27dbba7125 | [
"Apache-2.0"
] | null | null | null | predict_image.ipynb | NeoBryant/Brain_Image_Segmentation | 001826a3872db27682e929a2acd6ea27dbba7125 | [
"Apache-2.0"
] | null | null | null | 470.746057 | 99,676 | 0.928173 | [
[
[
"import torch\nimport numpy as np\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data.sampler import SubsetRandomSampler\nfrom load_LIDC_data import LIDC_IDRI\nfrom probabilistic_unet import ProbabilisticUnet\nfrom utils import l2_regularisation\nfrom save_load_net import save_model, load_model\n\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\ndataset = LIDC_IDRI(dataset_location = 'data/')\ndataset_size = len(dataset)\nindices = list(range(dataset_size))\nsplit = int(np.floor(0.1 * dataset_size))\nnp.random.shuffle(indices)\ntrain_indices, test_indices = indices[split:], indices[:split]\ntrain_sampler = SubsetRandomSampler(train_indices)\ntest_sampler = SubsetRandomSampler(test_indices)\n\ntrain_loader = DataLoader(dataset, batch_size=5, sampler=train_sampler)\ntest_loader = DataLoader(dataset, batch_size=1, sampler=test_sampler)\nprint(\"Number of training/test patches:\", (len(train_indices),len(test_indices)))\n\n# 加载已经训练好的网络进行预测\nmodel = ProbabilisticUnet(input_channels=1, num_classes=1, num_filters=[32,64,128,192], latent_dim=2, no_convs_fcomb=4, beta=10.0)\nnet = load_model(model=model, path='model/unet.pt', device=device)\n\noptimizer = torch.optim.Adam(net.parameters(), lr=1e-4, weight_decay=0)\n",
"Loading file data_lidc.pickle\nNumber of training/test patches: (27173, 3019)\n"
],
[
"#%matplotlib inline\nimport matplotlib.pyplot as plt\nimport matplotlib\n\nfor step, (patch, mask, _) in enumerate(test_loader): \n if step == 0:\n ## show the image\n label_np = mask.numpy()[0]\n image_np = patch.numpy()[0][0]\n\n ## through the net to predict\n patch = patch.to(device)\n mask = mask.to(device)\n mask = torch.unsqueeze(mask,1)\n net.forward(patch, None, training=False)\n result = net.sample(testing=True).cpu()[0][0]\n\n ## show the image\n fig, ax = plt.subplots(2,2, sharey=True, figsize=(14,12))\n result_np = result.detach().numpy() \n \n index = np.unravel_index(result_np.argmax(), result_np.shape)\n max_value = result_np[index[0]][index[1]]\n index = np.unravel_index(result_np.argmin(), result_np.shape)\n min_value = result_np[index[0]][index[1]]\n result_np = (result_np - min_value)/(max_value-min_value)\n \n threshold = 0.95\n result_binary = result_np.copy()\n result_binary[ result_binary>=threshold ] = 1\n result_binary[ result_binary< threshold ] = 0\n \n ax[0][0].set_title(\"Original data\")\n ax[0][1].set_title(\"Ground Truth\")\n ax[1][0].set_title(\"Probility heatmap\")\n ax[1][1].set_title(\"Predicted\")\n \n ax00 = ax[0][0].imshow(image_np, aspect=\"auto\", cmap=\"gray\")\n ax01 = ax[0][1].imshow(label_np, aspect=\"auto\")\n ax10 = ax[1][0].imshow(result_np, aspect=\"auto\")\n ax11 = ax[1][1].imshow(result_binary, aspect=\"auto\")\n \n fig.colorbar(ax00, ax=ax[0][0])\n fig.colorbar(ax01, ax=ax[0][1])\n fig.colorbar(ax10, ax=ax[1][0])\n fig.colorbar(ax11, ax=ax[1][1])",
"_____no_output_____"
],
[
"import torch\nimport numpy as np\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data.sampler import SubsetRandomSampler\nfrom load_LIDC_data import LIDC_IDRI\nfrom probabilistic_unet import ProbabilisticUnet\nfrom utils import l2_regularisation\nfrom save_load_net import save_model, load_model\n\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\ndataset = LIDC_IDRI(dataset_location = 'data/')\ndataset_size = len(dataset)\nindices = list(range(dataset_size))\nsplit = int(np.floor(0.1 * dataset_size))\nnp.random.shuffle(indices)\ntrain_indices, test_indices = indices[split:], indices[:split]\ntrain_sampler = SubsetRandomSampler(train_indices)\ntest_sampler = SubsetRandomSampler(test_indices)\n\ntrain_loader = DataLoader(dataset, batch_size=5, sampler=train_sampler)\ntest_loader = DataLoader(dataset, batch_size=1, sampler=test_sampler)\nprint(\"Number of training/test patches:\", (len(train_indices),len(test_indices)))\n\n# 加载已经训练好的网络进行预测\nmodel = ProbabilisticUnet(input_channels=1, num_classes=1, num_filters=[32,64,128,192], latent_dim=2, no_convs_fcomb=4, beta=10.0)\nnet = load_model(model=model, path='model/unet_1.pt', device=device)\n\noptimizer = torch.optim.Adam(net.parameters(), lr=1e-4, weight_decay=0)\n",
"Loading file data_lidc.pickle\nNumber of training/test patches: (40760, 4528)\n"
],
[
"#%matplotlib inline\nimport matplotlib.pyplot as plt\nimport matplotlib\n\nfor step, (patch, mask, _) in enumerate(test_loader): \n if step == 0:\n ## show the image\n label_np = mask.numpy()[0]\n image_np = patch.numpy()[0][0]\n\n ## through the net to predict\n patch = patch.to(device)\n mask = mask.to(device)\n mask = torch.unsqueeze(mask,1)\n net.forward(patch, None, training=False)\n result = net.sample(testing=True).cpu()[0][0]\n\n ## show the image\n fig, ax = plt.subplots(2,2, sharey=True, figsize=(14,12))\n result_np = result.detach().numpy() \n \n index = np.unravel_index(result_np.argmax(), result_np.shape)\n max_value = result_np[index[0]][index[1]]\n index = np.unravel_index(result_np.argmin(), result_np.shape)\n min_value = result_np[index[0]][index[1]]\n result_np = (result_np - min_value)/(max_value-min_value)\n \n threshold = 0.99\n result_binary = result_np.copy()\n result_binary[ result_binary>=threshold ] = 1\n result_binary[ result_binary< threshold ] = 0\n \n ax[0][0].set_title(\"Original data\")\n ax[0][1].set_title(\"Ground Truth\")\n ax[1][0].set_title(\"Probility heatmap\")\n ax[1][1].set_title(\"Predicted\")\n \n ax00 = ax[0][0].imshow(image_np, aspect=\"auto\", cmap=\"gray\")\n ax01 = ax[0][1].imshow(label_np, aspect=\"auto\")\n ax10 = ax[1][0].imshow(result_np, aspect=\"auto\")\n ax11 = ax[1][1].imshow(result_binary, aspect=\"auto\")\n \n fig.colorbar(ax00, ax=ax[0][0])\n fig.colorbar(ax01, ax=ax[0][1])\n fig.colorbar(ax10, ax=ax[1][0])\n fig.colorbar(ax11, ax=ax[1][1])",
"_____no_output_____"
],
[
"import torch\nfrom probabilistic_unet import ProbabilisticUnet\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n# 加载已经训练好的网络进行预测\nmodel = ProbabilisticUnet(input_channels=1, num_classes=1, num_filters=[32,64,128,192], latent_dim=2, no_convs_fcomb=4, beta=10.0)\nnet = load_model(model=model, path='model/unet.pt', device=device)\n\nnet",
"_____no_output_____"
],
[
"import torch\nimport numpy as np\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data.sampler import SubsetRandomSampler\nfrom load_LIDC_data import LIDC_IDRI\nfrom probabilistic_unet import ProbabilisticUnet\nfrom utils import l2_regularisation\nfrom save_load_net import save_model, load_model\n\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\ndataset = LIDC_IDRI(dataset_location = 'data/')\ndataset_size = len(dataset)\nindices = list(range(dataset_size))\nsplit = int(np.floor(0.1 * dataset_size))\nnp.random.shuffle(indices)\ntrain_indices, test_indices = indices[split:], indices[:split]\ntrain_sampler = SubsetRandomSampler(train_indices)\ntest_sampler = SubsetRandomSampler(test_indices)\n\ntrain_loader = DataLoader(dataset, batch_size=5, sampler=train_sampler)\ntest_loader = DataLoader(dataset, batch_size=1, sampler=test_sampler)\nprint(\"Number of training/test patches:\", (len(train_indices),len(test_indices)))\n\n# 加载已经训练好的网络进行预测\nmodel = ProbabilisticUnet(input_channels=1, num_classes=1, num_filters=[32,64,128,192], latent_dim=2, no_convs_fcomb=4, beta=10.0)\nnet = load_model(model=model, path='model/unet.pt', device=device)\n\noptimizer = torch.optim.Adam(net.parameters(), lr=1e-4, weight_decay=0)\n",
"Loading file data_lidc.pickle\nNumber of training/test patches: (27173, 3019)\n"
],
[
"#%matplotlib inline\nimport matplotlib.pyplot as plt\nimport matplotlib\n\nfor step, (patch, mask, _) in enumerate(test_loader): \n if step == 0:\n ## show the image\n label_np = mask.numpy()[0]\n image_np = patch.numpy()[0][0]\n\n ## through the net to predict\n patch = patch.to(device)\n mask = mask.to(device)\n mask = torch.unsqueeze(mask,1)\n net.forward(patch, None, training=False)\n result = net.sample(testing=True).cpu()[0][0]\n\n ## show the image\n fig, ax = plt.subplots(2,2, sharey=True, figsize=(14,12))\n result_np = result.detach().numpy() \n \n index = np.unravel_index(result_np.argmax(), result_np.shape)\n max_value = result_np[index[0]][index[1]]\n index = np.unravel_index(result_np.argmin(), result_np.shape)\n min_value = result_np[index[0]][index[1]]\n result_np = (result_np - min_value)/(max_value-min_value)\n \n threshold = 0.95\n result_binary = result_np.copy()\n result_binary[ result_binary>=threshold ] = 1\n result_binary[ result_binary< threshold ] = 0\n \n ax[0][0].set_title(\"Original data\")\n ax[0][1].set_title(\"Ground Truth\")\n ax[1][0].set_title(\"Probility heatmap\")\n ax[1][1].set_title(\"Predicted\")\n \n ax00 = ax[0][0].imshow(image_np, aspect=\"auto\", cmap=\"gray\")\n ax01 = ax[0][1].imshow(label_np, aspect=\"auto\")\n ax10 = ax[1][0].imshow(result_np, aspect=\"auto\")\n ax11 = ax[1][1].imshow(result_binary, aspect=\"auto\")\n \n fig.colorbar(ax00, ax=ax[0][0])\n fig.colorbar(ax01, ax=ax[0][1])\n fig.colorbar(ax10, ax=ax[1][0])\n fig.colorbar(ax11, ax=ax[1][1])",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e77d28b202da6c51e4a686170af9fa75df01200a | 9,776 | ipynb | Jupyter Notebook | 自动生成字幕.ipynb | zhenghao0379/autosubpy | 6aabac0e432f2185a06eab7140570bafea74b5e1 | [
"MIT"
] | 15 | 2020-05-07T15:39:02.000Z | 2022-02-28T03:43:31.000Z | 自动生成字幕.ipynb | zhenghao0379/autosubpy | 6aabac0e432f2185a06eab7140570bafea74b5e1 | [
"MIT"
] | null | null | null | 自动生成字幕.ipynb | zhenghao0379/autosubpy | 6aabac0e432f2185a06eab7140570bafea74b5e1 | [
"MIT"
] | 9 | 2020-05-07T15:39:06.000Z | 2021-12-28T22:58:53.000Z | 22.06772 | 296 | 0.476882 | [
[
[
"# 自动生成字幕",
"_____no_output_____"
],
[
"工作内容:\n- 从视频文件自动生成外挂型字幕文件,不进行视频编辑等操作\n- 包括,时间轴\n\n\n主要工作:\n- 获取视频文件中的音频文件\n- 将音频文件分段\n- 采用IBM CLOUD进行语音转文字,每月500分钟免费\n- 自动构建B站字幕\n\n后续工作:\n- 采用 翻译API,自动进行初步翻译\n - google: googletrans包,因为墙pass\n - youdao: 翻译 api",
"_____no_output_____"
],
[
"## B站字幕文件 .bcc 格式",
"_____no_output_____"
]
],
[
[
"# 示例\n{\n \"font_size\":0.4, # 字体大小\n \"font_color\":\"#FFFFFF\", # 字体颜色\n \"background_alpha\":0.5, # 背景透明度 \n \"background_color\":\"#9C27B0\", # 背景颜色\n \"Stroke\":\"none\", # \n \"body\":[ # 主体\n {\n \"from\":13, # 起始处\n \"to\":14.95, # 结束处\n \"location\":2, # \n \"content\":\"Hi I`m Larry Bill\" # 主体\n },\n {\"from\":14.95,\"to\":18.825,\"location\":2,\"content\":\"I`m chair guitar department Berklee College of Music\"},\n {\"from\":20.342341,\"to\":25.342341,\"location\":2,\"content\":\"and it's my pleasure to work with you to \"}\n ]\n}",
"_____no_output_____"
]
],
[
[
"## 获取视频转音频",
"_____no_output_____"
]
],
[
[
"import moviepy.editor as mve",
"_____no_output_____"
],
[
"path = r'D:\\Music\\电吉他\\Berklee - Modern Method for Guitar - Vol1 (DVD)\\video\\Lesson 1'\n\nfile = '001.mov'\n\nfilepath = path + \"\\\\\" + file\n\nfilepath",
"_____no_output_____"
],
[
"video = mve.VideoFileClip(filepath)\naudio = video.audio",
"_____no_output_____"
],
[
"audio.write_audiofile('test.mp3')",
"MoviePy - Writing audio in test.mp3\n"
],
[
"audio.write_audiofile('test.mp3')",
"_____no_output_____"
],
[
"# import ffmpeg\n# autosub,使用的时google 和 ffmpeg",
"_____no_output_____"
]
],
[
[
"## 音频转文字",
"_____no_output_____"
]
],
[
[
"# IBM Cloud Speech to text\n# API密钥:-ijVpcr8DbYekYCkOEtalbfH6uMO1rI0qJAz0mEbDvre\n# URL:https://api.us-south.speech-to-text.watson.cloud.ibm.com/instances/48476942-3322-4bba-aae3-18a2b84015d7",
"_____no_output_____"
]
],
[
[
"## 文字构成字幕",
"_____no_output_____"
],
[
"## 翻译",
"_____no_output_____"
]
],
[
[
"# 工具包\nimport requests\nimport json",
"_____no_output_____"
],
[
"# 有道翻译,调用有道翻译API(较不准,较快,稳定)\ndef youdao_trans(text, t_type='AUTO'):\n text = text.replace(' ', '%20')\n url = 'http://fanyi.youdao.com/translate?&doctype=json&type='+t_type+'&i='+text\n# print(url)\n header = {}\n out = requests.get(url)\n out_json = out.json()\n# print(out_json)\n out_tgt = out_json['translateResult'][0][0]['tgt']\n# print(out_tgt)\n return out_tgt",
"_____no_output_____"
],
[
"# test\nyoudao_trans(\"I'm chair of the guitar department here at Berklee college of music\")",
"_____no_output_____"
],
[
"# 谷歌翻译_1,调用谷歌翻译(较准,较慢,超时)\nfrom googletrans import Translator\ntranslator = Translator(service_urls=['translate.google.cn'])\n\ndef google_trans0(text, dest='zh-cn'):\n try :\n out = translator.translate(text, dest=dest).text\n return out\n except:\n return '翻译异常'",
"_____no_output_____"
],
[
"# test\ngoogle_trans0(\"I'm chair of the guitar department here at Berklee college of music\")",
"_____no_output_____"
],
[
"text = \"After you're done with this book and actually while you're playing this book you will develop a sense of musicality you'll develop strength in your hands you'll develop a sense of time with the chords a sense of melody and you'll just get better as a guitarist and as a musician.\"",
"_____no_output_____"
],
[
"youdao_trans(text)",
"_____no_output_____"
],
[
"google_trans0(text)",
"_____no_output_____"
],
[
"# 谷歌翻译_2,调用网页版(准)\n# 构建中,tk解密破解\ndef google_trans(text, sl='auto', tl='zh_CN'):\n text = text.replace(' ', '%20')\n url = 'http://translate.google.cn/translate_a/single?client=t&dt=t&dj=1&ie=UTF-8&sl='+sl+'%tl='+tl+'&q='+text\n print(url)\n header = {}\n out = requests.get(url)\n out_json = out.json()\n print(out_json)\n out_tgt = out_json['translateResult'][0][0]['tgt']\n print(out_tgt)\n return out_tgt",
"_____no_output_____"
],
[
"# test\n# google_trans2('guitar department berklee college of music')",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e77d310d2d47a5223a9c8410d704ebf0f9128d83 | 3,141 | ipynb | Jupyter Notebook | 0.16/_downloads/plot_morph_data.ipynb | drammock/mne-tools.github.io | 5d3a104d174255644d8d5335f58036e32695e85d | [
"BSD-3-Clause"
] | null | null | null | 0.16/_downloads/plot_morph_data.ipynb | drammock/mne-tools.github.io | 5d3a104d174255644d8d5335f58036e32695e85d | [
"BSD-3-Clause"
] | null | null | null | 0.16/_downloads/plot_morph_data.ipynb | drammock/mne-tools.github.io | 5d3a104d174255644d8d5335f58036e32695e85d | [
"BSD-3-Clause"
] | null | null | null | 58.166667 | 1,914 | 0.630372 | [
[
[
"%matplotlib inline",
"_____no_output_____"
]
],
[
[
"\n# Morph source estimates from one subject to another subject\n\n\nA source estimate from a given subject 'sample' is morphed\nto the anatomy of another subject 'fsaverage'. The output\nis a source estimate defined on the anatomy of 'fsaverage'\n\n\n",
"_____no_output_____"
]
],
[
[
"# Authors: Alexandre Gramfort <[email protected]>\n# Eric Larson <[email protected]>\n#\n# License: BSD (3-clause)\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport mne\nfrom mne.datasets import sample\n\nprint(__doc__)\n\ndata_path = sample.data_path()\n\nsubject_from = 'sample'\nsubject_to = 'fsaverage'\nsubjects_dir = data_path + '/subjects'\n\nfname = data_path + '/MEG/sample/sample_audvis-meg'\n\n# Read input stc file\nstc_from = mne.read_source_estimate(fname)\n# Morph using one method (supplying the vertices in fsaverage's source\n# space makes it faster). Note that for any generic subject, you could do:\n# vertices_to = mne.grade_to_vertices(subject_to, grade=5)\n# But fsaverage's source space was set up so we can just do this:\nvertices_to = [np.arange(10242), np.arange(10242)]\nstc_to = mne.morph_data(subject_from, subject_to, stc_from, n_jobs=1,\n grade=vertices_to, subjects_dir=subjects_dir)\nstc_to.save('%s_audvis-meg' % subject_to)\n\n# Morph using another method -- useful if you're going to do a lot of the\n# same inter-subject morphing operations; you could save and load morph_mat\nmorph_mat = mne.compute_morph_matrix(subject_from, subject_to,\n stc_from.vertices, vertices_to,\n subjects_dir=subjects_dir)\nstc_to_2 = mne.morph_data_precomputed(subject_from, subject_to,\n stc_from, vertices_to, morph_mat)\nstc_to_2.save('%s_audvis-meg_2' % subject_to)\n\n# View source activations\nplt.plot(stc_from.times, stc_from.data.mean(axis=0), 'r', label='from')\nplt.plot(stc_to.times, stc_to.data.mean(axis=0), 'b', label='to')\nplt.plot(stc_to_2.times, stc_to.data.mean(axis=0), 'g', label='to_2')\nplt.xlabel('time (ms)')\nplt.ylabel('Mean Source amplitude')\nplt.legend()\nplt.show()",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e77d3b5ce6be6d325c2c8e921174eea786e7cf31 | 7,355 | ipynb | Jupyter Notebook | notebook/pathlib_absolute_relative.ipynb | puyopop/python-snippets | 9d70aa3b2a867dd22f5a5e6178a5c0c5081add73 | [
"MIT"
] | 174 | 2018-05-30T21:14:50.000Z | 2022-03-25T07:59:37.000Z | notebook/pathlib_absolute_relative.ipynb | puyopop/python-snippets | 9d70aa3b2a867dd22f5a5e6178a5c0c5081add73 | [
"MIT"
] | 5 | 2019-08-10T03:22:02.000Z | 2021-07-12T20:31:17.000Z | notebook/pathlib_absolute_relative.ipynb | puyopop/python-snippets | 9d70aa3b2a867dd22f5a5e6178a5c0c5081add73 | [
"MIT"
] | 53 | 2018-04-27T05:26:35.000Z | 2022-03-25T07:59:37.000Z | 17.144522 | 119 | 0.475459 | [
[
[
"import util_make_files\n\nutil_make_files.pathlib_basic()",
"_____no_output_____"
],
[
"import pathlib\nimport os",
"_____no_output_____"
],
[
"p = pathlib.Path('temp/file.txt')",
"_____no_output_____"
],
[
"print(p)",
"temp/file.txt\n"
],
[
"print(type(p))",
"<class 'pathlib.PosixPath'>\n"
],
[
"print(p.cwd())",
"/Users/mbp/Documents/my-project/python-snippets/notebook\n"
],
[
"print(type(p.cwd()))",
"<class 'pathlib.PosixPath'>\n"
],
[
"print(pathlib.Path.cwd())",
"/Users/mbp/Documents/my-project/python-snippets/notebook\n"
],
[
"print(type(pathlib.Path.cwd()))",
"<class 'pathlib.PosixPath'>\n"
],
[
"print(os.getcwd())",
"/Users/mbp/Documents/my-project/python-snippets/notebook\n"
],
[
"print(type(os.getcwd()))",
"<class 'str'>\n"
],
[
"print(p.resolve())",
"/Users/mbp/Documents/my-project/python-snippets/notebook/temp/file.txt\n"
],
[
"p_rel = pathlib.Path('temp/dir/../file.txt')",
"_____no_output_____"
],
[
"print(p_rel)",
"temp/dir/../file.txt\n"
],
[
"print(p_rel.resolve())",
"/Users/mbp/Documents/my-project/python-snippets/notebook/temp/file.txt\n"
],
[
"p_abs = pathlib.Path('/Users/mbp/Documents/my-project/python-snippets/notebook/temp/file.txt')",
"_____no_output_____"
],
[
"print(p_abs)",
"/Users/mbp/Documents/my-project/python-snippets/notebook/temp/file.txt\n"
],
[
"print(p_abs.relative_to(p.cwd()))",
"temp/file.txt\n"
],
[
"print(p_abs.relative_to('/Users/mbp/Documents/my-project'))",
"python-snippets/notebook/temp/file.txt\n"
],
[
"# print(p_abs.relative_to('/usr/'))\n# ValueError: '/Users/mbp/Documents/my-project/python-snippets/notebook/temp/file.txt' does not start with '/usr'",
"_____no_output_____"
],
[
"p_rel = pathlib.Path('temp/dir/sub_dir/file2.txt')",
"_____no_output_____"
],
[
"print(p_rel.relative_to('temp/dir'))",
"sub_dir/file2.txt\n"
],
[
"print(p_abs)",
"/Users/mbp/Documents/my-project/python-snippets/notebook/temp/file.txt\n"
],
[
"print(p_abs.is_absolute())",
"True\n"
],
[
"print(p_rel)",
"temp/dir/sub_dir/file2.txt\n"
],
[
"print(p_rel.is_absolute())",
"False\n"
],
[
"import shutil\n\nshutil.rmtree('temp')",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e77d455c1c191095bb937296e34c86efb1a5407f | 9,005 | ipynb | Jupyter Notebook | 01_07_python_3.ipynb | mengwangk/FortuneNet | 953596551673f5c67e3508513d2c3714d9c52826 | [
"MIT"
] | 1 | 2021-08-07T12:49:13.000Z | 2021-08-07T12:49:13.000Z | 01_07_python_3.ipynb | mengwangk/FortuneNet | 953596551673f5c67e3508513d2c3714d9c52826 | [
"MIT"
] | null | null | null | 01_07_python_3.ipynb | mengwangk/FortuneNet | 953596551673f5c67e3508513d2c3714d9c52826 | [
"MIT"
] | 1 | 2021-08-07T12:49:12.000Z | 2021-08-07T12:49:12.000Z | 20.281532 | 67 | 0.42965 | [
[
[
"from IPython.core.interactiveshell import InteractiveShell\nInteractiveShell.ast_node_interactivity = \"all\"",
"_____no_output_____"
],
[
"people = [\n{ 'name': 'John', \"age\": 64 },\n{ 'name': 'Janet', \"age\": 34 },\n{ 'name': 'Ed', \"age\": 24 },\n{ 'name': 'Sara', \"age\": 64 },\n{ 'name': 'John', \"age\": 32 },\n{ 'name': 'Jane', \"age\": 34 },\n{ 'name': 'John', \"age\": 99 },\n]",
"_____no_output_____"
],
[
"# Sorting objects by multiple keys\nimport operator\npeople.sort(key=operator.itemgetter('age'))\npeople\n\npeople.sort(key=operator.itemgetter('name'))\npeople",
"_____no_output_____"
],
[
"# List Comprehensions\nmylist = [i for i in range(10)]\nprint(mylist)\n\nsquares = [x**2 for x in range(10)]\nprint(squares)\n\ndef some_function(a):\n return (a + 5) / 2\n \nmy_formula = [some_function(i) for i in range(10)]\nprint(my_formula)\n\nfiltered = [i for i in range(20) if i%2==0]\nprint(filtered)",
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]\n[2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0]\n[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]\n"
],
[
"# Check memory usage of your objects\nimport sys\n\nmylist = range(0, 10000)\nprint(sys.getsizeof(mylist))\n\nmyreallist = [x for x in range(0, 10000)]\nprint(sys.getsizeof(myreallist))",
"48\n87632\n"
],
[
"# Data classes\nfrom dataclasses import dataclass\n\n@dataclass\nclass Card:\n rank: str\n suit: str\n \ncard = Card(\"Q\", \"hearts\")\n\nprint(card == card)\n# True\n\nprint(card.rank)\n# 'Q'\n\nprint(card)\nCard(rank='Q', suit='hearts')",
"True\nQ\nCard(rank='Q', suit='hearts')\n"
],
[
"# Merging dictionaries\ndict1 = { 'a': 1, 'b': 2 }\ndict2 = { 'b': 3, 'c': 4 }\nmerged = { **dict1, **dict2 }\nprint (merged)\n# {'a': 1, 'b': 3, 'c': 4}\n\n# Python 3.9\n#merged = dict1 | dict2",
"{'a': 1, 'b': 3, 'c': 4}\n"
],
[
"# Find most frequent occuring values\ntest = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]\nprint(max(set(test), key = test.count))",
"4\n"
],
[
"# Reverse a string\na = \"!dlrow olleH\"\nbackward = a[::-1]\nbackward",
"_____no_output_____"
],
[
"# Dim as variable\narray = [5, 10, 15, 20]\nfive, ten, fift, twent = array\nfive",
"_____no_output_____"
],
[
"# itertools\nc = [[1, 2], [3, 4], [5, 6]]\n# Let's convert this matrix to a 1 dimensional list.\nimport itertools as it\nnewlist = list(it.chain.from_iterable(c))\nnewlist",
"_____no_output_____"
],
[
"# Intelligent unpacking\na, *b, c = [1, 2, 3, 4, 5]\na, b, c",
"_____no_output_____"
],
[
"# enumerate\nfor i,w in enumerate(array):\n print(i,w)",
"0 5\n1 10\n2 15\n3 20\n"
],
[
"# slice\na = [0, 1, 2, 3, 4, 5]\nLASTTHREE = slice(-3, None)\nslice(-3, None, None)\nprint(a[LASTTHREE])",
"[3, 4, 5]\n"
],
[
"# group adjacent list\na = [1, 2, 3, 4, 5, 6] \ngroup_adjacent = lambda a, k: zip(*([iter(a)] * k)) \nprint(tuple(group_adjacent(a, 3)))\nprint(list(group_adjacent(a, 2)))\nprint(list(group_adjacent(a, 1)))",
"((1, 2, 3), (4, 5, 6))\n[(1, 2), (3, 4), (5, 6)]\n[(1,), (2,), (3,), (4,), (5,), (6,)]\n"
],
[
"# Dequeue\nimport collections\nQ = collections.deque() \nQ.append(1) \nQ.appendleft(2) \nQ.extend([3, 4]) \nQ.extendleft([5, 6]) \nQ.pop()\nQ.popleft()\nQ.rotate(3) \nQ.rotate(-3)\nprint(Q)",
"deque([5, 2, 1, 3])\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e77d48bdfc07657ba627fd4263649a16f8e16589 | 274,538 | ipynb | Jupyter Notebook | conditional/.ipynb_checkpoints/main_conditional_disentangle_cifar_bs900_sratio_0_5_drop_0_5_rl_stdscale_6_run1-checkpoint.ipynb | minhtannguyen/ffjord | f3418249eaa4647f4339aea8d814cf2ce33be141 | [
"MIT"
] | null | null | null | conditional/.ipynb_checkpoints/main_conditional_disentangle_cifar_bs900_sratio_0_5_drop_0_5_rl_stdscale_6_run1-checkpoint.ipynb | minhtannguyen/ffjord | f3418249eaa4647f4339aea8d814cf2ce33be141 | [
"MIT"
] | null | null | null | conditional/.ipynb_checkpoints/main_conditional_disentangle_cifar_bs900_sratio_0_5_drop_0_5_rl_stdscale_6_run1-checkpoint.ipynb | minhtannguyen/ffjord | f3418249eaa4647f4339aea8d814cf2ce33be141 | [
"MIT"
] | null | null | null | 99.650817 | 1,313 | 0.575643 | [
[
[
"import os\nos.environ['CUDA_VISIBLE_DEVICES']='0,1,2,3'",
"_____no_output_____"
],
[
"%run -p ../train_cnf_disentangle_rl.py --data cifar10 --dims 64,64,64 --strides 1,1,1,1 --num_blocks 2 --layer_type concat --multiscale True --rademacher True --batch_size 900 --test_batch_size 500 --save ../experiments_published/cnf_conditional_disentangle_cifar10_bs900_sratio_0_5_drop_0_5_rl_stdscale_6_run1 --resume ../experiments_published/cnf_conditional_disentangle_cifar10_bs900_sratio_0_5_drop_0_5_rl_stdscale_6_run1/epoch_270_checkpt.pth --seed 1 --lr 0.0001 --conditional True --controlled_tol False --train_mode semisup --log_freq 10 --weight_y 0.5 --condition_ratio 0.5 --dropout_rate 0.5 --scale_fac 1.0 --scale_std 6.0\n#",
"/tancode/repos/tan-ffjord/train_cnf_disentangle_rl.py\nimport argparse\nimport os\nimport time\nimport numpy as np\n\nimport torch\nimport torch.optim as optim\nimport torchvision.datasets as dset\nimport torchvision.transforms as tforms\nfrom torchvision.utils import save_image\n\nimport torch.utils.data as data\nfrom torch.utils.data import Dataset\n\nimport matplotlib.pyplot as plt\nplt.rcParams['figure.dpi'] = 300\n\nfrom PIL import Image\nimport os.path\nimport errno\nimport codecs\n\nimport lib.layers as layers\nimport lib.utils as utils\nimport lib.multiscale_parallel as multiscale_parallel\nimport lib.modules as modules\nimport lib.thops as thops\n\nfrom train_misc import standard_normal_logprob\nfrom train_misc import set_cnf_options, count_nfe, count_parameters, count_total_time, count_nfe_gate\nfrom train_misc import add_spectral_norm, spectral_norm_power_iteration\nfrom train_misc import create_regularization_fns, get_regularization, append_regularization_to_log\n\nfrom tensorboardX import SummaryWriter\n\n# go fast boi!!\ntorch.backends.cudnn.benchmark = True\nSOLVERS = [\"dopri5\", \"bdf\", \"rk4\", \"midpoint\", 'adams', 'explicit_adams']\nGATES = [\"cnn1\", \"cnn2\", \"rnn\"]\n\nparser = argparse.ArgumentParser(\"Continuous Normalizing Flow\")\nparser.add_argument(\"--data\", choices=[\"mnist\", \"colormnist\", \"svhn\", \"cifar10\", 'lsun_church'], type=str, default=\"mnist\")\nparser.add_argument(\"--dims\", type=str, default=\"8,32,32,8\")\nparser.add_argument(\"--strides\", type=str, default=\"2,2,1,-2,-2\")\nparser.add_argument(\"--num_blocks\", type=int, default=1, help='Number of stacked CNFs.')\n\nparser.add_argument(\"--conv\", type=eval, default=True, choices=[True, False])\nparser.add_argument(\n \"--layer_type\", type=str, default=\"ignore\",\n choices=[\"ignore\", \"concat\", \"concat_v2\", \"squash\", \"concatsquash\", \"concatcoord\", \"hyper\", \"blend\"]\n)\nparser.add_argument(\"--divergence_fn\", type=str, default=\"approximate\", choices=[\"brute_force\", \"approximate\"])\nparser.add_argument(\n \"--nonlinearity\", type=str, default=\"softplus\", choices=[\"tanh\", \"relu\", \"softplus\", \"elu\", \"swish\"]\n)\n\nparser.add_argument(\"--seed\", type=int, default=0)\n\nparser.add_argument('--solver', type=str, default='dopri5', choices=SOLVERS)\nparser.add_argument('--atol', type=float, default=1e-5)\nparser.add_argument('--rtol', type=float, default=1e-5)\nparser.add_argument(\"--step_size\", type=float, default=None, help=\"Optional fixed step size.\")\n\nparser.add_argument('--gate', type=str, default='cnn1', choices=GATES)\nparser.add_argument('--scale', type=float, default=1.0)\nparser.add_argument('--scale_fac', type=float, default=1.0)\nparser.add_argument('--scale_std', type=float, default=1.0)\nparser.add_argument('--eta', default=0.1, type=float,\n help='tuning parameter that allows us to trade-off the competing goals of' \n 'minimizing the prediction loss and maximizing the gate rewards ')\nparser.add_argument('--rl-weight', default=0.01, type=float,\n help='rl weight')\n\nparser.add_argument('--gamma', default=0.99, type=float,\n help='discount factor, default: (0.99)')\n\nparser.add_argument('--test_solver', type=str, default=None, choices=SOLVERS + [None])\nparser.add_argument('--test_atol', type=float, default=None)\nparser.add_argument('--test_rtol', type=float, default=None)\n\nparser.add_argument(\"--imagesize\", type=int, default=None)\nparser.add_argument(\"--alpha\", type=float, default=1e-6)\nparser.add_argument('--time_length', type=float, default=1.0)\nparser.add_argument('--train_T', type=eval, default=True)\n\nparser.add_argument(\"--num_epochs\", type=int, default=500)\nparser.add_argument(\"--batch_size\", type=int, default=200)\nparser.add_argument(\n \"--batch_size_schedule\", type=str, default=\"\", help=\"Increases the batchsize at every given epoch, dash separated.\"\n)\nparser.add_argument(\"--test_batch_size\", type=int, default=200)\nparser.add_argument(\"--lr\", type=float, default=1e-3)\nparser.add_argument(\"--warmup_iters\", type=float, default=1000)\nparser.add_argument(\"--weight_decay\", type=float, default=0.0)\nparser.add_argument(\"--spectral_norm_niter\", type=int, default=10)\nparser.add_argument(\"--weight_y\", type=float, default=0.5)\nparser.add_argument(\"--annealing_std\", type=eval, default=False, choices=[True, False])\nparser.add_argument(\"--y_class\", type=int, default=10)\nparser.add_argument(\"--y_color\", type=int, default=10)\n\nparser.add_argument(\"--add_noise\", type=eval, default=True, choices=[True, False])\nparser.add_argument(\"--batch_norm\", type=eval, default=False, choices=[True, False])\nparser.add_argument('--residual', type=eval, default=False, choices=[True, False])\nparser.add_argument('--autoencode', type=eval, default=False, choices=[True, False])\nparser.add_argument('--rademacher', type=eval, default=True, choices=[True, False])\nparser.add_argument('--spectral_norm', type=eval, default=False, choices=[True, False])\nparser.add_argument('--multiscale', type=eval, default=False, choices=[True, False])\nparser.add_argument('--parallel', type=eval, default=False, choices=[True, False])\nparser.add_argument('--conditional', type=eval, default=False, choices=[True, False])\nparser.add_argument('--controlled_tol', type=eval, default=False, choices=[True, False])\nparser.add_argument(\"--train_mode\", choices=[\"semisup\", \"sup\", \"unsup\"], type=str, default=\"semisup\")\nparser.add_argument(\"--condition_ratio\", type=float, default=0.5)\nparser.add_argument(\"--dropout_rate\", type=float, default=0.0)\n\n\n# Regularizations\nparser.add_argument('--l1int', type=float, default=None, help=\"int_t ||f||_1\")\nparser.add_argument('--l2int', type=float, default=None, help=\"int_t ||f||_2\")\nparser.add_argument('--dl2int', type=float, default=None, help=\"int_t ||f^T df/dt||_2\")\nparser.add_argument('--JFrobint', type=float, default=None, help=\"int_t ||df/dx||_F\")\nparser.add_argument('--JdiagFrobint', type=float, default=None, help=\"int_t ||df_i/dx_i||_F\")\nparser.add_argument('--JoffdiagFrobint', type=float, default=None, help=\"int_t ||df/dx - df_i/dx_i||_F\")\n\nparser.add_argument(\"--time_penalty\", type=float, default=0, help=\"Regularization on the end_time.\")\nparser.add_argument(\n \"--max_grad_norm\", type=float, default=1e10,\n help=\"Max norm of graidents (default is just stupidly high to avoid any clipping)\"\n)\n\nparser.add_argument(\"--begin_epoch\", type=int, default=1)\nparser.add_argument(\"--resume\", type=str, default=None)\nparser.add_argument(\"--save\", type=str, default=\"experiments/cnf\")\nparser.add_argument(\"--val_freq\", type=int, default=1)\nparser.add_argument(\"--log_freq\", type=int, default=1)\n\nargs = parser.parse_args()\n\nimport lib.odenvp_conditional_rl as odenvp\n \n# set seed\ntorch.manual_seed(args.seed)\nnp.random.seed(args.seed)\n\n# logger\nutils.makedirs(args.save)\nlogger = utils.get_logger(logpath=os.path.join(args.save, 'logs'), filepath=os.path.abspath(__file__)) # write to log file\nwriter = SummaryWriter(os.path.join(args.save, 'tensorboard')) # write to tensorboard\n\nif args.layer_type == \"blend\":\n logger.info(\"!! Setting time_length from None to 1.0 due to use of Blend layers.\")\n args.time_length = 1.0\n\nlogger.info(args)\n\nclass ColorMNIST(data.Dataset):\n \"\"\"\n ColorMNIST\n \"\"\"\n urls = [\n 'http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz',\n 'http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz',\n 'http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz',\n 'http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz',\n ]\n raw_folder = 'raw'\n processed_folder = 'processed'\n training_file = 'training.pt'\n test_file = 'test.pt'\n\n def __init__(self, root, train=True, transform=None, target_transform=None, download=False):\n self.root = os.path.expanduser(root)\n self.transform = transform\n self.target_transform = target_transform\n self.train = train # training set or test set\n\n if download:\n self.download()\n\n if not self._check_exists():\n raise RuntimeError('Dataset not found.' +\n ' You can use download=True to download it')\n\n if self.train:\n self.train_data, self.train_labels = torch.load(\n os.path.join(self.root, self.processed_folder, self.training_file))\n \n self.train_data = np.tile(self.train_data[:, :, :, np.newaxis], 3)\n else:\n self.test_data, self.test_labels = torch.load(\n os.path.join(self.root, self.processed_folder, self.test_file))\n \n self.test_data = np.tile(self.test_data[:, :, :, np.newaxis], 3)\n \n self.pallette = [[31, 119, 180],\n [255, 127, 14],\n [44, 160, 44],\n [214, 39, 40],\n [148, 103, 189],\n [140, 86, 75],\n [227, 119, 194],\n [127, 127, 127],\n [188, 189, 34],\n [23, 190, 207]]\n\n def __getitem__(self, index):\n \"\"\"\n Args:\n index (int): Index\n\n Returns:\n tuple: (image, target) where target is index of the target class.\n \"\"\"\n if self.train:\n img, target = self.train_data[index].copy(), self.train_labels[index]\n else:\n img, target = self.test_data[index].copy(), self.test_labels[index]\n \n # doing this so that it is consistent with all other datasets\n # to return a PIL Image\n y_color_digit = np.random.randint(0, args.y_color)\n c_digit = self.pallette[y_color_digit]\n \n img[:, :, 0] = img[:, :, 0] / 255 * c_digit[0]\n img[:, :, 1] = img[:, :, 1] / 255 * c_digit[1]\n img[:, :, 2] = img[:, :, 2] / 255 * c_digit[2]\n \n img = Image.fromarray(img)\n\n if self.transform is not None:\n img = self.transform(img)\n\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n return img, [target,torch.from_numpy(np.array(y_color_digit))]\n\n def __len__(self):\n if self.train:\n return len(self.train_data)\n else:\n return len(self.test_data)\n\n def _check_exists(self):\n return os.path.exists(os.path.join(self.root, self.processed_folder, self.training_file)) and \\\n os.path.exists(os.path.join(self.root, self.processed_folder, self.test_file))\n\n def download(self):\n \"\"\"Download the MNIST data if it doesn't exist in processed_folder already.\"\"\"\n from six.moves import urllib\n import gzip\n\n if self._check_exists():\n return\n\n # download files\n try:\n os.makedirs(os.path.join(self.root, self.raw_folder))\n os.makedirs(os.path.join(self.root, self.processed_folder))\n except OSError as e:\n if e.errno == errno.EEXIST:\n pass\n else:\n raise\n\n for url in self.urls:\n print('Downloading ' + url)\n data = urllib.request.urlopen(url)\n filename = url.rpartition('/')[2]\n file_path = os.path.join(self.root, self.raw_folder, filename)\n with open(file_path, 'wb') as f:\n f.write(data.read())\n with open(file_path.replace('.gz', ''), 'wb') as out_f, \\\n gzip.GzipFile(file_path) as zip_f:\n out_f.write(zip_f.read())\n os.unlink(file_path)\n\n # process and save as torch files\n print('Processing...')\n\n training_set = (\n read_image_file(os.path.join(self.root, self.raw_folder, 'train-images-idx3-ubyte')),\n read_label_file(os.path.join(self.root, self.raw_folder, 'train-labels-idx1-ubyte'))\n )\n test_set = (\n read_image_file(os.path.join(self.root, self.raw_folder, 't10k-images-idx3-ubyte')),\n read_label_file(os.path.join(self.root, self.raw_folder, 't10k-labels-idx1-ubyte'))\n )\n with open(os.path.join(self.root, self.processed_folder, self.training_file), 'wb') as f:\n torch.save(training_set, f)\n with open(os.path.join(self.root, self.processed_folder, self.test_file), 'wb') as f:\n torch.save(test_set, f)\n\n print('Done!')\n\n def __repr__(self):\n fmt_str = 'Dataset ' + self.__class__.__name__ + '\\n'\n fmt_str += ' Number of datapoints: {}\\n'.format(self.__len__())\n tmp = 'train' if self.train is True else 'test'\n fmt_str += ' Split: {}\\n'.format(tmp)\n fmt_str += ' Root Location: {}\\n'.format(self.root)\n tmp = ' Transforms (if any): '\n fmt_str += '{0}{1}\\n'.format(tmp, self.transform.__repr__().replace('\\n', '\\n' + ' ' * len(tmp)))\n tmp = ' Target Transforms (if any): '\n fmt_str += '{0}{1}'.format(tmp, self.target_transform.__repr__().replace('\\n', '\\n' + ' ' * len(tmp)))\n return fmt_str\n\ndef add_noise(x):\n \"\"\"\n [0, 1] -> [0, 255] -> add noise -> [0, 1]\n \"\"\"\n if args.add_noise:\n noise = x.new().resize_as_(x).uniform_()\n x = x * 255 + noise\n x = x / 256\n return x\n\n\ndef update_lr(optimizer, itr):\n iter_frac = min(float(itr + 1) / max(args.warmup_iters, 1), 1.0)\n lr = args.lr * iter_frac\n for param_group in optimizer.param_groups:\n param_group[\"lr\"] = lr\n\n \ndef update_scale_std(model, epoch):\n epoch_frac = 1.0 - float(epoch - 1) / max(args.num_epochs + 1, 1)\n scale_std = args.scale_std * epoch_frac\n model.set_scale_std(scale_std)\n\n\ndef get_train_loader(train_set, epoch):\n if args.batch_size_schedule != \"\":\n epochs = [0] + list(map(int, args.batch_size_schedule.split(\"-\")))\n n_passed = sum(np.array(epochs) <= epoch)\n current_batch_size = int(args.batch_size * n_passed)\n else:\n current_batch_size = args.batch_size\n train_loader = torch.utils.data.DataLoader(\n dataset=train_set, batch_size=current_batch_size, shuffle=True, drop_last=True, pin_memory=True\n )\n logger.info(\"===> Using batch size {}. Total {} iterations/epoch.\".format(current_batch_size, len(train_loader)))\n return train_loader\n\n\ndef get_dataset(args):\n trans = lambda im_size: tforms.Compose([tforms.Resize(im_size), tforms.ToTensor(), add_noise])\n\n if args.data == \"mnist\":\n im_dim = 1\n im_size = 28 if args.imagesize is None else args.imagesize\n train_set = dset.MNIST(root=\"../data\", train=True, transform=trans(im_size), download=True)\n test_set = dset.MNIST(root=\"../data\", train=False, transform=trans(im_size), download=True)\n elif args.data == \"colormnist\":\n im_dim = 3\n im_size = 28 if args.imagesize is None else args.imagesize\n train_set = ColorMNIST(root=\"../data\", train=True, transform=trans(im_size), download=True)\n test_set = ColorMNIST(root=\"../data\", train=False, transform=trans(im_size), download=True)\n elif args.data == \"svhn\":\n im_dim = 3\n im_size = 32 if args.imagesize is None else args.imagesize\n train_set = dset.SVHN(root=\"../data\", split=\"train\", transform=trans(im_size), download=True)\n test_set = dset.SVHN(root=\"../data\", split=\"test\", transform=trans(im_size), download=True)\n elif args.data == \"cifar10\":\n im_dim = 3\n im_size = 32 if args.imagesize is None else args.imagesize\n train_set = dset.CIFAR10(\n root=\"../data\", train=True, transform=tforms.Compose([\n tforms.Resize(im_size),\n tforms.RandomHorizontalFlip(),\n tforms.ToTensor(),\n add_noise,\n ]), download=True\n )\n test_set = dset.CIFAR10(root=\"../data\", train=False, transform=trans(im_size), download=True)\n elif args.data == 'celeba':\n im_dim = 3\n im_size = 64 if args.imagesize is None else args.imagesize\n train_set = dset.CelebA(\n train=True, transform=tforms.Compose([\n tforms.ToPILImage(),\n tforms.Resize(im_size),\n tforms.RandomHorizontalFlip(),\n tforms.ToTensor(),\n add_noise,\n ])\n )\n test_set = dset.CelebA(\n train=False, transform=tforms.Compose([\n tforms.ToPILImage(),\n tforms.Resize(im_size),\n tforms.ToTensor(),\n add_noise,\n ])\n )\n elif args.data == 'lsun_church':\n im_dim = 3\n im_size = 64 if args.imagesize is None else args.imagesize\n train_set = dset.LSUN(\n '../data', ['church_outdoor_train'], transform=tforms.Compose([\n tforms.Resize(96),\n tforms.RandomCrop(64),\n tforms.Resize(im_size),\n tforms.ToTensor(),\n add_noise,\n ])\n )\n test_set = dset.LSUN(\n '../data', ['church_outdoor_val'], transform=tforms.Compose([\n tforms.Resize(96),\n tforms.RandomCrop(64),\n tforms.Resize(im_size),\n tforms.ToTensor(),\n add_noise,\n ])\n ) \n elif args.data == 'imagenet_64':\n im_dim = 3\n im_size = 64 if args.imagesize is None else args.imagesize\n train_set = dset.ImageFolder(\n train=True, transform=tforms.Compose([\n tforms.ToPILImage(),\n tforms.Resize(im_size),\n tforms.RandomHorizontalFlip(),\n tforms.ToTensor(),\n add_noise,\n ])\n )\n test_set = dset.ImageFolder(\n train=False, transform=tforms.Compose([\n tforms.ToPILImage(),\n tforms.Resize(im_size),\n tforms.ToTensor(),\n add_noise,\n ])\n )\n \n data_shape = (im_dim, im_size, im_size)\n if not args.conv:\n data_shape = (im_dim * im_size * im_size,)\n\n test_loader = torch.utils.data.DataLoader(\n dataset=test_set, batch_size=args.test_batch_size, shuffle=False, drop_last=True\n )\n return train_set, test_loader, data_shape\n\n\ndef compute_bits_per_dim(x, model):\n zero = torch.zeros(x.shape[0], 1).to(x)\n\n # Don't use data parallelize if batch size is small.\n # if x.shape[0] < 200:\n # model = model.module\n \n z, delta_logp, atol, rtol, logp_actions, nfe = model(x, zero) # run model forward\n\n logpz = standard_normal_logprob(z).view(z.shape[0], -1).sum(1, keepdim=True) # logp(z)\n logpx = logpz - delta_logp\n\n logpx_per_dim = torch.sum(logpx) / x.nelement() # averaged over batches\n bits_per_dim = -(logpx_per_dim - np.log(256)) / np.log(2)\n\n return bits_per_dim, atol, rtol, logp_actions, nfe\n\ndef compute_bits_per_dim_conditional(x, y, model):\n zero = torch.zeros(x.shape[0], 1).to(x)\n y_onehot = thops.onehot(y, num_classes=model.module.y_class).to(x)\n\n # Don't use data parallelize if batch size is small.\n # if x.shape[0] < 200:\n # model = model.module\n \n z, delta_logp, atol, rtol, logp_actions, nfe = model(x, zero) # run model forward\n \n dim_sup = int(args.condition_ratio * np.prod(z.size()[1:]))\n \n # prior\n mean, logs = model.module._prior(y_onehot)\n\n logpz_sup = modules.GaussianDiag.logp(mean, logs, z[:, 0:dim_sup]).view(-1,1) # logp(z)_sup\n logpz_unsup = standard_normal_logprob(z[:, dim_sup:]).view(z.shape[0], -1).sum(1, keepdim=True)\n logpz = logpz_sup + logpz_unsup\n logpx = logpz - delta_logp\n\n logpx_per_dim = torch.sum(logpx) / x.nelement() # averaged over batches\n bits_per_dim = -(logpx_per_dim - np.log(256)) / np.log(2)\n \n # dropout\n if args.dropout_rate > 0:\n zsup = model.module.dropout(z[:, 0:dim_sup])\n else:\n zsup = z[:, 0:dim_sup]\n \n # compute xentropy loss\n y_logits = model.module.project_class(zsup)\n loss_xent = model.module.loss_class(y_logits, y.to(x.get_device()))\n y_predicted = np.argmax(y_logits.cpu().detach().numpy(), axis=1)\n\n return bits_per_dim, loss_xent, y_predicted, atol, rtol, logp_actions, nfe\n\ndef create_model(args, data_shape, regularization_fns):\n hidden_dims = tuple(map(int, args.dims.split(\",\")))\n strides = tuple(map(int, args.strides.split(\",\")))\n\n if args.multiscale:\n model = odenvp.ODENVP(\n (args.batch_size, *data_shape),\n n_blocks=args.num_blocks,\n intermediate_dims=hidden_dims,\n nonlinearity=args.nonlinearity,\n alpha=args.alpha,\n cnf_kwargs={\"T\": args.time_length, \"train_T\": args.train_T, \"regularization_fns\": regularization_fns, \"solver\": args.solver, \"atol\": args.atol, \"rtol\": args.rtol, \"scale\": args.scale, \"scale_fac\": args.scale_fac, \"scale_std\": args.scale_std, \"gate\": args.gate},\n condition_ratio=args.condition_ratio,\n dropout_rate=args.dropout_rate,\n y_class = args.y_class)\n elif args.parallel:\n model = multiscale_parallel.MultiscaleParallelCNF(\n (args.batch_size, *data_shape),\n n_blocks=args.num_blocks,\n intermediate_dims=hidden_dims,\n alpha=args.alpha,\n time_length=args.time_length,\n )\n else:\n if args.autoencode:\n\n def build_cnf():\n autoencoder_diffeq = layers.AutoencoderDiffEqNet(\n hidden_dims=hidden_dims,\n input_shape=data_shape,\n strides=strides,\n conv=args.conv,\n layer_type=args.layer_type,\n nonlinearity=args.nonlinearity,\n )\n odefunc = layers.AutoencoderODEfunc(\n autoencoder_diffeq=autoencoder_diffeq,\n divergence_fn=args.divergence_fn,\n residual=args.residual,\n rademacher=args.rademacher,\n )\n cnf = layers.CNF(\n odefunc=odefunc,\n T=args.time_length,\n regularization_fns=regularization_fns,\n solver=args.solver,\n )\n return cnf\n else:\n\n def build_cnf():\n diffeq = layers.ODEnet(\n hidden_dims=hidden_dims,\n input_shape=data_shape,\n strides=strides,\n conv=args.conv,\n layer_type=args.layer_type,\n nonlinearity=args.nonlinearity,\n )\n odefunc = layers.ODEfunc(\n diffeq=diffeq,\n divergence_fn=args.divergence_fn,\n residual=args.residual,\n rademacher=args.rademacher,\n )\n cnf = layers.CNF(\n odefunc=odefunc,\n T=args.time_length,\n train_T=args.train_T,\n regularization_fns=regularization_fns,\n solver=args.solver,\n )\n return cnf\n\n chain = [layers.LogitTransform(alpha=args.alpha)] if args.alpha > 0 else [layers.ZeroMeanTransform()]\n chain = chain + [build_cnf() for _ in range(args.num_blocks)]\n if args.batch_norm:\n chain.append(layers.MovingBatchNorm2d(data_shape[0]))\n model = layers.SequentialFlow(chain)\n return model\n\n\nif __name__ == \"__main__\":\n\n # get deivce\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n cvt = lambda x: x.type(torch.float32).to(device, non_blocking=True)\n\n # load dataset\n train_set, test_loader, data_shape = get_dataset(args)\n\n # build model\n regularization_fns, regularization_coeffs = create_regularization_fns(args)\n model = create_model(args, data_shape, regularization_fns)\n\n if args.spectral_norm: add_spectral_norm(model, logger)\n set_cnf_options(args, model)\n\n logger.info(model)\n logger.info(\"Number of trainable parameters: {}\".format(count_parameters(model)))\n \n writer.add_text('info', \"Number of trainable parameters: {}\".format(count_parameters(model)))\n\n # optimizer\n optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)\n \n # set initial iter\n itr = 1\n \n # set the meters\n time_epoch_meter = utils.RunningAverageMeter(0.97)\n time_meter = utils.RunningAverageMeter(0.97)\n loss_meter = utils.RunningAverageMeter(0.97) # track total loss\n nll_meter = utils.RunningAverageMeter(0.97) # track negative log-likelihood\n xent_meter = utils.RunningAverageMeter(0.97) # track xentropy score\n error_meter = utils.RunningAverageMeter(0.97) # track error score\n steps_meter = utils.RunningAverageMeter(0.97)\n grad_meter = utils.RunningAverageMeter(0.97)\n tt_meter = utils.RunningAverageMeter(0.97)\n\n # restore parameters\n if args.resume is not None:\n checkpt = torch.load(args.resume, map_location=lambda storage, loc: storage)\n model.load_state_dict(checkpt[\"state_dict\"])\n if \"optim_state_dict\" in checkpt.keys():\n optimizer.load_state_dict(checkpt[\"optim_state_dict\"])\n # Manually move optimizer state to device.\n for state in optimizer.state.values():\n for k, v in state.items():\n if torch.is_tensor(v):\n state[k] = cvt(v)\n args.begin_epoch = checkpt['epoch'] + 1\n itr = checkpt['iter'] + 1\n time_epoch_meter.set(checkpt['epoch_time_avg'])\n time_meter.set(checkpt['time_train'])\n loss_meter.set(checkpt['loss_train'])\n nll_meter.set(checkpt['bits_per_dim_train'])\n xent_meter.set(checkpt['xent_train'])\n error_meter.set(checkpt['error_train'])\n steps_meter.set(checkpt['nfe_train'])\n grad_meter.set(checkpt['grad_train'])\n tt_meter.set(checkpt['total_time_train'])\n\n if torch.cuda.is_available():\n model = torch.nn.DataParallel(model).cuda()\n\n # For visualization.\n if args.conditional:\n dim_unsup = int((1.0 - args.condition_ratio) * np.prod(data_shape))\n fixed_y = torch.from_numpy(np.arange(model.module.y_class)).repeat(model.module.y_class).type(torch.long).to(device, non_blocking=True)\n fixed_y_onehot = thops.onehot(fixed_y, num_classes=model.module.y_class)\n with torch.no_grad():\n mean, logs = model.module._prior(fixed_y_onehot)\n fixed_z_sup = modules.GaussianDiag.sample(mean, logs)\n fixed_z_unsup = cvt(torch.randn(model.module.y_class**2, dim_unsup))\n fixed_z = torch.cat((fixed_z_sup, fixed_z_unsup),1)\n else:\n fixed_z = cvt(torch.randn(100, *data_shape))\n \n\n if args.spectral_norm and not args.resume: spectral_norm_power_iteration(model, 500)\n\n best_loss_nll = float(\"inf\")\n best_error_score = float(\"inf\")\n \n for epoch in range(args.begin_epoch, args.num_epochs + 1):\n start_epoch = time.time()\n model.train()\n if args.annealing_std:\n update_scale_std(model.module, epoch)\n \n train_loader = get_train_loader(train_set, epoch)\n for _, (x, y) in enumerate(train_loader):\n if args.data == \"colormnist\":\n y = y[0]\n \n start = time.time()\n update_lr(optimizer, itr)\n optimizer.zero_grad()\n\n if not args.conv:\n x = x.view(x.shape[0], -1)\n\n # cast data and move to device\n x = cvt(x)\n \n # compute loss\n if args.conditional:\n loss_nll, loss_xent, y_predicted, atol, rtol, logp_actions, nfe = compute_bits_per_dim_conditional(x, y, model)\n if args.train_mode == \"semisup\":\n loss = loss_nll + args.weight_y * loss_xent\n elif args.train_mode == \"sup\":\n loss = loss_xent\n elif args.train_mode == \"unsup\":\n loss = loss_nll\n else:\n raise ValueError('Choose supported train_mode: semisup, sup, unsup')\n error_score = 1. - np.mean(y_predicted.astype(int) == y.numpy()) \n \n else:\n loss, atol, rtol, logp_actions, nfe = compute_bits_per_dim(x, model)\n loss_nll, loss_xent, error_score = loss, 0., 0.\n \n if regularization_coeffs:\n reg_states = get_regularization(model, regularization_coeffs)\n reg_loss = sum(\n reg_state * coeff for reg_state, coeff in zip(reg_states, regularization_coeffs) if coeff != 0\n )\n loss = loss + reg_loss\n total_time = count_total_time(model)\n loss = loss + total_time * args.time_penalty\n\n # re-weight the gate rewards\n normalized_eta = args.eta / len(logp_actions)\n \n # collect cumulative future rewards\n R = - loss\n cum_rewards = []\n for r in nfe[::-1]:\n R = -normalized_eta * r.view(-1,1) + args.gamma * R\n cum_rewards.insert(0,R)\n \n # apply REINFORCE\n rl_loss = 0\n for lpa, r in zip(logp_actions, cum_rewards):\n rl_loss = rl_loss - lpa.view(-1,1) * args.rl_weight * r\n \n loss = loss + rl_loss.mean()\n \n loss.backward()\n \n grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)\n\n optimizer.step()\n\n if args.spectral_norm: spectral_norm_power_iteration(model, args.spectral_norm_niter)\n \n time_meter.update(time.time() - start)\n loss_meter.update(loss.item())\n nll_meter.update(loss_nll.item())\n if args.conditional:\n xent_meter.update(loss_xent.item())\n else:\n xent_meter.update(loss_xent)\n error_meter.update(error_score)\n steps_meter.update(count_nfe_gate(model))\n grad_meter.update(grad_norm)\n tt_meter.update(total_time)\n \n for idx in range(len(model.module.transforms)):\n for layer in model.module.transforms[idx].chain:\n if hasattr(layer, 'atol'):\n layer.odefunc.after_odeint()\n \n # write to tensorboard\n writer.add_scalars('time', {'train_iter': time_meter.val}, itr)\n writer.add_scalars('loss', {'train_iter': loss_meter.val}, itr)\n writer.add_scalars('bits_per_dim', {'train_iter': nll_meter.val}, itr)\n writer.add_scalars('xent', {'train_iter': xent_meter.val}, itr)\n writer.add_scalars('error', {'train_iter': error_meter.val}, itr)\n writer.add_scalars('nfe', {'train_iter': steps_meter.val}, itr)\n writer.add_scalars('grad', {'train_iter': grad_meter.val}, itr)\n writer.add_scalars('total_time', {'train_iter': tt_meter.val}, itr)\n\n if itr % args.log_freq == 0:\n for tol_indx in range(len(atol)):\n writer.add_scalars('atol_%i'%tol_indx, {'train': atol[tol_indx].mean()}, itr)\n writer.add_scalars('rtol_%i'%tol_indx, {'train': rtol[tol_indx].mean()}, itr)\n \n log_message = (\n \"Iter {:04d} | Time {:.4f}({:.4f}) | Bit/dim {:.4f}({:.4f}) | Xent {:.4f}({:.4f}) | Loss {:.4f}({:.4f}) | Error {:.4f}({:.4f}) \"\n \"Steps {:.0f}({:.2f}) | Grad Norm {:.4f}({:.4f}) | Total Time {:.2f}({:.2f})\".format(\n itr, time_meter.val, time_meter.avg, nll_meter.val, nll_meter.avg, xent_meter.val, xent_meter.avg, loss_meter.val, loss_meter.avg, error_meter.val, error_meter.avg, steps_meter.val, steps_meter.avg, grad_meter.val, grad_meter.avg, tt_meter.val, tt_meter.avg\n )\n )\n if regularization_coeffs:\n log_message = append_regularization_to_log(log_message, regularization_fns, reg_states)\n logger.info(log_message)\n writer.add_text('info', log_message, itr)\n\n itr += 1\n \n if args.data == \"colormnist\":\n # print train images\n xall = []\n ximg = x[0:40].cpu().numpy().transpose((0,2,3,1))\n for i in range(ximg.shape[0]):\n xall.append(ximg[i])\n \n xall = np.hstack(xall)\n\n plt.imshow(xall)\n plt.axis('off')\n plt.show()\n \n # compute test loss\n model.eval()\n if epoch % args.val_freq == 0:\n with torch.no_grad():\n # write to tensorboard\n writer.add_scalars('time', {'train_epoch': time_meter.avg}, epoch)\n writer.add_scalars('loss', {'train_epoch': loss_meter.avg}, epoch)\n writer.add_scalars('bits_per_dim', {'train_epoch': nll_meter.avg}, epoch)\n writer.add_scalars('xent', {'train_epoch': xent_meter.avg}, epoch)\n writer.add_scalars('error', {'train_epoch': error_meter.avg}, epoch)\n writer.add_scalars('nfe', {'train_epoch': steps_meter.avg}, epoch)\n writer.add_scalars('grad', {'train_epoch': grad_meter.avg}, epoch)\n writer.add_scalars('total_time', {'train_epoch': tt_meter.avg}, epoch)\n \n start = time.time()\n logger.info(\"validating...\")\n writer.add_text('info', \"validating...\", epoch)\n losses_nll = []; losses_xent = []; losses = []\n total_correct = 0\n \n for (x, y) in test_loader:\n if args.data == \"colormnist\":\n y = y[0]\n \n if not args.conv:\n x = x.view(x.shape[0], -1)\n x = cvt(x)\n if args.conditional:\n loss_nll, loss_xent, y_predicted, atol, rtol, logp_actions, nfe = compute_bits_per_dim_conditional(x, y, model)\n if args.train_mode == \"semisup\":\n loss = loss_nll + args.weight_y * loss_xent\n elif args.train_mode == \"sup\":\n loss = loss_xent\n elif args.train_mode == \"unsup\":\n loss = loss_nll\n else:\n raise ValueError('Choose supported train_mode: semisup, sup, unsup')\n total_correct += np.sum(y_predicted.astype(int) == y.numpy())\n else:\n loss, atol, rtol, logp_actions, nfe = compute_bits_per_dim(x, model)\n loss_nll, loss_xent = loss, 0.\n losses_nll.append(loss_nll.cpu().numpy()); losses.append(loss.cpu().numpy())\n if args.conditional: \n losses_xent.append(loss_xent.cpu().numpy())\n else:\n losses_xent.append(loss_xent)\n \n if args.data == \"colormnist\":\n # print test images\n xall = []\n ximg = x[0:40].cpu().numpy().transpose((0,2,3,1))\n for i in range(ximg.shape[0]):\n xall.append(ximg[i])\n\n xall = np.hstack(xall)\n\n plt.imshow(xall)\n plt.axis('off')\n plt.show()\n \n loss_nll = np.mean(losses_nll); loss_xent = np.mean(losses_xent); loss = np.mean(losses)\n error_score = 1. - total_correct / len(test_loader.dataset)\n time_epoch_meter.update(time.time() - start_epoch)\n \n # write to tensorboard\n test_time_spent = time.time() - start\n writer.add_scalars('time', {'validation': test_time_spent}, epoch)\n writer.add_scalars('epoch_time', {'validation': time_epoch_meter.val}, epoch)\n writer.add_scalars('bits_per_dim', {'validation': loss_nll}, epoch)\n writer.add_scalars('xent', {'validation': loss_xent}, epoch)\n writer.add_scalars('loss', {'validation': loss}, epoch)\n writer.add_scalars('error', {'validation': error_score}, epoch)\n \n for tol_indx in range(len(atol)):\n writer.add_scalars('atol_%i'%tol_indx, {'validation': atol[tol_indx].mean()}, epoch)\n writer.add_scalars('rtol_%i'%tol_indx, {'validation': rtol[tol_indx].mean()}, epoch)\n \n log_message = \"Epoch {:04d} | Time {:.4f}, Epoch Time {:.4f}({:.4f}), Bit/dim {:.4f}(best: {:.4f}), Xent {:.4f}, Loss {:.4f}, Error {:.4f}(best: {:.4f})\".format(epoch, time.time() - start, time_epoch_meter.val, time_epoch_meter.avg, loss_nll, best_loss_nll, loss_xent, loss, error_score, best_error_score)\n logger.info(log_message)\n writer.add_text('info', log_message, epoch)\n \n for name, param in model.named_parameters():\n writer.add_histogram(name, param.clone().cpu().data.numpy(), epoch)\n \n \n utils.makedirs(args.save)\n torch.save({\n \"args\": args,\n \"state_dict\": model.module.state_dict() if torch.cuda.is_available() else model.state_dict(),\n \"optim_state_dict\": optimizer.state_dict(),\n \"epoch\": epoch,\n \"iter\": itr-1,\n \"error\": error_score,\n \"loss\": loss,\n \"xent\": loss_xent,\n \"bits_per_dim\": loss_nll,\n \"best_bits_per_dim\": best_loss_nll,\n \"best_error_score\": best_error_score,\n \"epoch_time\": time_epoch_meter.val,\n \"epoch_time_avg\": time_epoch_meter.avg,\n \"time\": test_time_spent,\n \"error_train\": error_meter.avg,\n \"loss_train\": loss_meter.avg,\n \"xent_train\": xent_meter.avg,\n \"bits_per_dim_train\": nll_meter.avg,\n \"total_time_train\": tt_meter.avg,\n \"time_train\": time_meter.avg,\n \"nfe_train\": steps_meter.avg,\n \"grad_train\": grad_meter.avg,\n }, os.path.join(args.save, \"epoch_%i_checkpt.pth\"%epoch))\n \n torch.save({\n \"args\": args,\n \"state_dict\": model.module.state_dict() if torch.cuda.is_available() else model.state_dict(),\n \"optim_state_dict\": optimizer.state_dict(),\n \"epoch\": epoch,\n \"iter\": itr-1,\n \"error\": error_score,\n \"loss\": loss,\n \"xent\": loss_xent,\n \"bits_per_dim\": loss_nll,\n \"best_bits_per_dim\": best_loss_nll,\n \"best_error_score\": best_error_score,\n \"epoch_time\": time_epoch_meter.val,\n \"epoch_time_avg\": time_epoch_meter.avg,\n \"time\": test_time_spent,\n \"error_train\": error_meter.avg,\n \"loss_train\": loss_meter.avg,\n \"xent_train\": xent_meter.avg,\n \"bits_per_dim_train\": nll_meter.avg,\n \"total_time_train\": tt_meter.avg,\n \"time_train\": time_meter.avg,\n \"nfe_train\": steps_meter.avg,\n \"grad_train\": grad_meter.avg,\n }, os.path.join(args.save, \"current_checkpt.pth\"))\n \n if loss_nll < best_loss_nll:\n best_loss_nll = loss_nll\n utils.makedirs(args.save)\n torch.save({\n \"args\": args,\n \"state_dict\": model.module.state_dict() if torch.cuda.is_available() else model.state_dict(),\n \"optim_state_dict\": optimizer.state_dict(),\n \"epoch\": epoch,\n \"iter\": itr-1,\n \"error\": error_score,\n \"loss\": loss,\n \"xent\": loss_xent,\n \"bits_per_dim\": loss_nll,\n \"best_bits_per_dim\": best_loss_nll,\n \"best_error_score\": best_error_score,\n \"epoch_time\": time_epoch_meter.val,\n \"epoch_time_avg\": time_epoch_meter.avg,\n \"time\": test_time_spent,\n \"error_train\": error_meter.avg,\n \"loss_train\": loss_meter.avg,\n \"xent_train\": xent_meter.avg,\n \"bits_per_dim_train\": nll_meter.avg,\n \"total_time_train\": tt_meter.avg,\n \"time_train\": time_meter.avg,\n \"nfe_train\": steps_meter.avg,\n \"grad_train\": grad_meter.avg,\n }, os.path.join(args.save, \"best_nll_checkpt.pth\"))\n \n if args.conditional:\n if error_score < best_error_score:\n best_error_score = error_score\n utils.makedirs(args.save)\n torch.save({\n \"args\": args,\n \"state_dict\": model.module.state_dict() if torch.cuda.is_available() else model.state_dict(),\n \"optim_state_dict\": optimizer.state_dict(),\n \"epoch\": epoch,\n \"iter\": itr-1,\n \"error\": error_score,\n \"loss\": loss,\n \"xent\": loss_xent,\n \"bits_per_dim\": loss_nll,\n \"best_bits_per_dim\": best_loss_nll,\n \"best_error_score\": best_error_score,\n \"epoch_time\": time_epoch_meter.val,\n \"epoch_time_avg\": time_epoch_meter.avg,\n \"time\": test_time_spent,\n \"error_train\": error_meter.avg,\n \"loss_train\": loss_meter.avg,\n \"xent_train\": xent_meter.avg,\n \"bits_per_dim_train\": nll_meter.avg,\n \"total_time_train\": tt_meter.avg,\n \"time_train\": time_meter.avg,\n \"nfe_train\": steps_meter.avg,\n \"grad_train\": grad_meter.avg,\n }, os.path.join(args.save, \"best_error_checkpt.pth\"))\n \n\n # visualize samples and density\n with torch.no_grad():\n fig_filename = os.path.join(args.save, \"figs\", \"{:04d}.jpg\".format(epoch))\n utils.makedirs(os.path.dirname(fig_filename))\n generated_samples, atol, rtol, logp_actions, nfe = model(fixed_z, reverse=True)\n generated_samples = generated_samples.view(-1, *data_shape)\n for tol_indx in range(len(atol)):\n writer.add_scalars('atol_gen_%i'%tol_indx, {'validation': atol[tol_indx].mean()}, epoch)\n writer.add_scalars('rtol_gen_%i'%tol_indx, {'validation': rtol[tol_indx].mean()}, epoch)\n save_image(generated_samples, fig_filename, nrow=10)\n if args.data == \"mnist\":\n writer.add_images('generated_images', generated_samples.repeat(1,3,1,1), epoch)\n else:\n writer.add_images('generated_images', generated_samples.repeat(1,1,1,1), epoch)\nNamespace(JFrobint=None, JdiagFrobint=None, JoffdiagFrobint=None, add_noise=True, alpha=1e-06, annealing_std=False, atol=1e-05, autoencode=False, batch_norm=False, batch_size=900, batch_size_schedule='', begin_epoch=1, condition_ratio=0.5, conditional=True, controlled_tol=False, conv=True, data='cifar10', dims='64,64,64', divergence_fn='approximate', dl2int=None, dropout_rate=0.5, eta=0.1, gamma=0.99, gate='cnn1', imagesize=None, l1int=None, l2int=None, layer_type='concat', log_freq=10, lr=0.0001, max_grad_norm=10000000000.0, multiscale=True, nonlinearity='softplus', num_blocks=2, num_epochs=500, parallel=False, rademacher=True, residual=False, resume='../experiments_published/cnf_conditional_disentangle_cifar10_bs900_sratio_0_5_drop_0_5_rl_stdscale_6_run1/current_checkpt.pth', rl_weight=0.01, rtol=1e-05, save='../experiments_published/cnf_conditional_disentangle_cifar10_bs900_sratio_0_5_drop_0_5_rl_stdscale_6_run1', scale=1.0, scale_fac=1.0, scale_std=6.0, seed=1, solver='dopri5', spectral_norm=False, spectral_norm_niter=10, step_size=None, strides='1,1,1,1', test_atol=None, test_batch_size=500, test_rtol=None, test_solver=None, time_length=1.0, time_penalty=0, train_T=True, train_mode='semisup', val_freq=1, warmup_iters=1000, weight_decay=0.0, weight_y=0.5, y_class=10, y_color=10)\n"
]
]
] | [
"code"
] | [
[
"code",
"code"
]
] |
e77d56fcd1c153d5267820b146df89d7bbcf0d70 | 26,620 | ipynb | Jupyter Notebook | session/language-detection/12.deep-learning.ipynb | AetherPrior/malaya | 45d37b171dff9e92c5d30bd7260b282cd0912a7d | [
"MIT"
] | 88 | 2021-01-06T10:01:31.000Z | 2022-03-30T17:34:09.000Z | session/language-detection/12.deep-learning.ipynb | AetherPrior/malaya | 45d37b171dff9e92c5d30bd7260b282cd0912a7d | [
"MIT"
] | 43 | 2021-01-14T02:44:41.000Z | 2022-03-31T19:47:42.000Z | session/language-detection/12.deep-learning.ipynb | AetherPrior/malaya | 45d37b171dff9e92c5d30bd7260b282cd0912a7d | [
"MIT"
] | 38 | 2021-01-06T07:15:03.000Z | 2022-03-19T05:07:50.000Z | 34.128205 | 241 | 0.528813 | [
[
[
"import os\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"3\"",
"_____no_output_____"
],
[
"import pickle\nimport youtokentome as yttm\nimport json\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.naive_bayes import ComplementNB\nimport numpy as np",
"_____no_output_____"
],
[
"with open('bow-language-detection.pkl', 'rb') as fopen:\n bow = pickle.load(fopen)",
"_____no_output_____"
],
[
"v = bow.transform(['▁dengan ▁stim ▁dan ▁pengeluaran'])\nv",
"_____no_output_____"
],
[
"with open('train-test.json') as fopen:\n train_test = json.load(fopen)\n \ntrain_test.keys()",
"_____no_output_____"
],
[
"train_Y = LabelEncoder().fit_transform(train_test['train_Y'])",
"_____no_output_____"
],
[
"test_Y = LabelEncoder().fit_transform(train_test['test_Y'])",
"_____no_output_____"
],
[
"bpe = yttm.BPE(model='language-detection.model')",
"_____no_output_____"
],
[
"train_test['train_Y'][8]",
"_____no_output_____"
],
[
"subs = [' '.join(s) for s in bpe.encode(train_test['train_X'], output_type=yttm.OutputType.SUBWORD)]\nlen(subs)",
"_____no_output_____"
],
[
"test_subs = [' '.join(s) for s in bpe.encode(train_test['test_X'], output_type=yttm.OutputType.SUBWORD)]\nlen(test_subs)",
"_____no_output_____"
],
[
"train_X = bow.transform(subs)",
"_____no_output_____"
],
[
"test_X = bow.transform(test_subs)",
"_____no_output_____"
],
[
"import tensorflow as tf",
"_____no_output_____"
],
[
"def convert_sparse_matrix_to_sparse_tensor(X):\n coo = X.tocoo()\n indices = np.mat([coo.row, coo.col]).transpose()\n # coo.data[coo.data > limit] = limit\n return tf.SparseTensorValue(indices, coo.col, coo.shape), tf.SparseTensorValue(indices, coo.data, coo.shape)",
"_____no_output_____"
],
[
"class Model:\n def __init__(self, learning_rate, dimension = 32, output = 6):\n self.X = tf.sparse_placeholder(tf.int32)\n self.W = tf.sparse_placeholder(tf.int32)\n self.Y = tf.placeholder(tf.int32, [None])\n embeddings = tf.Variable(tf.truncated_normal([train_X.shape[1],dimension]))\n embed = tf.nn.embedding_lookup_sparse(embeddings, self.X, self.W, combiner='mean')\n self.embed = embed\n self.logits = tf.layers.dense(embed, output)\n self.cost = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(\n logits = self.logits, labels = self.Y))\n self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n correct_pred = tf.equal(tf.argmax(self.logits, 1,output_type=tf.int32), self.Y)\n self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))",
"_____no_output_____"
],
[
"tf.reset_default_graph()\nsess = tf.InteractiveSession()\nmodel = Model(1e-3)\nsess.run(tf.global_variables_initializer())",
"WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/embedding_ops.py:515: div (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nDeprecated in favor of operator or tf.math.divide.\nWARNING:tensorflow:From <ipython-input-16-f18d73326ce7>:9: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse keras.layers.Dense instead.\nWARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/layers/core.py:187: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease use `layer.__call__` method instead.\n"
],
[
"batch_size = 256\nepoch = 10",
"_____no_output_____"
],
[
"saver = tf.train.Saver(tf.trainable_variables())\nsaver.save(sess, 'lang-detection-w/model.ckpt')",
"_____no_output_____"
],
[
"import time\nfrom tqdm import tqdm\n\nfor e in range(epoch):\n lasttime = time.time()\n train_acc, train_loss, test_acc, test_loss = [], [], [], []\n pbar = tqdm(\n range(0, train_X.shape[0], batch_size), desc = 'train minibatch loop'\n )\n for i in pbar:\n batch_x = convert_sparse_matrix_to_sparse_tensor(train_X[i : min(i + batch_size, train_X.shape[0])])\n batch_y = train_Y[i : min(i + batch_size, train_X.shape[0])]\n acc, cost, _ = sess.run(\n [model.accuracy, model.cost, model.optimizer],\n feed_dict = {\n model.X: batch_x[0],\n model.W: batch_x[1],\n model.Y: batch_y\n },\n )\n assert not np.isnan(cost)\n train_loss.append(cost)\n train_acc.append(acc)\n pbar.set_postfix(cost = cost, accuracy = acc)\n \n pbar = tqdm(range(0, test_X.shape[0], batch_size), desc = 'test minibatch loop')\n for i in pbar:\n batch_x = convert_sparse_matrix_to_sparse_tensor(test_X[i : min(i + batch_size, test_X.shape[0])])\n batch_y = test_Y[i : min(i + batch_size, test_X.shape[0])]\n batch_x_expand = np.expand_dims(batch_x,axis = 1)\n acc, cost = sess.run(\n [model.accuracy, model.cost],\n feed_dict = {\n model.X: batch_x[0],\n model.W: batch_x[1],\n model.Y: batch_y\n },\n )\n test_loss.append(cost)\n test_acc.append(acc)\n pbar.set_postfix(cost = cost, accuracy = acc)\n\n train_loss = np.mean(train_loss)\n train_acc = np.mean(train_acc)\n test_loss = np.mean(test_loss)\n test_acc = np.mean(test_acc)\n \n print('time taken:', time.time() - lasttime)\n print(\n 'epoch: %d, training loss: %f, training acc: %f, valid loss: %f, valid acc: %f\\n'\n % (e, train_loss, train_acc, test_loss, test_acc)\n )",
"train minibatch loop: 100%|██████████| 73901/73901 [07:16<00:00, 169.40it/s, accuracy=0.974, cost=0.123] \ntest minibatch loop: 100%|██████████| 18476/18476 [01:10<00:00, 260.37it/s, accuracy=0.98, cost=0.043] \ntrain minibatch loop: 0%| | 18/73901 [00:00<07:14, 170.19it/s, accuracy=0.977, cost=0.0879]"
],
[
"sess.run(\n [model.accuracy, model.cost, tf.nn.softmax(model.logits)],\n feed_dict = {\n model.X: batch_x[0],\n model.W: batch_x[1],\n model.Y: batch_y\n },\n)",
"_____no_output_____"
],
[
"saver.save(sess, 'lang-detection-w/model.ckpt')",
"_____no_output_____"
],
[
"import boto3\n\nbucketName = 'huseinhouse-storage'\nKey = 'lang-detection-w/model.ckpt.data-00000-of-00001'\noutPutname = \"v34/language-detection/model.ckpt.data-00000-of-00001\"\n\ns3 = boto3.client('s3')\ns3.upload_file(Key,bucketName,outPutname)",
"_____no_output_____"
],
[
"Key = 'lang-detection-w/model.ckpt.index'\noutPutname = \"v34/language-detection/model.ckpt.index\"\n\ns3 = boto3.client('s3')\ns3.upload_file(Key,bucketName,outPutname)",
"_____no_output_____"
],
[
"Key = 'lang-detection-w/model.ckpt.meta'\noutPutname = \"v34/language-detection/model.ckpt.meta\"\n\ns3 = boto3.client('s3')\ns3.upload_file(Key,bucketName,outPutname)",
"_____no_output_____"
],
[
"Key = 'bow-language-detection.pkl'\noutPutname = \"v34/language-detection/bow-language-detection.pkl\"\n\ns3 = boto3.client('s3')\ns3.upload_file(Key,bucketName,outPutname)",
"_____no_output_____"
],
[
"Key = 'language-detection.model'\noutPutname = \"v34/language-detection/language-detection.model\"\n\ns3 = boto3.client('s3')\ns3.upload_file(Key,bucketName,outPutname)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e77d5ef1a21725d151c36b704125df5978fde011 | 43,406 | ipynb | Jupyter Notebook | 14.5 Shifting Data Through Time (Lagging and Leading).ipynb | SiamakMushakhian/Numpy-Pandas-Seaborn | cf831097e59b65e793a2768b983993d93c844c0e | [
"MIT"
] | null | null | null | 14.5 Shifting Data Through Time (Lagging and Leading).ipynb | SiamakMushakhian/Numpy-Pandas-Seaborn | cf831097e59b65e793a2768b983993d93c844c0e | [
"MIT"
] | null | null | null | 14.5 Shifting Data Through Time (Lagging and Leading).ipynb | SiamakMushakhian/Numpy-Pandas-Seaborn | cf831097e59b65e793a2768b983993d93c844c0e | [
"MIT"
] | 1 | 2022-01-26T04:11:41.000Z | 2022-01-26T04:11:41.000Z | 27.437421 | 250 | 0.336405 | [
[
[
"",
"_____no_output_____"
],
[
"<center><em>Copyright! This material is protected, please do not copy or distribute. by:Taher Assaf</em></center>",
"_____no_output_____"
],
[
"***\n<h1 align=\"center\">Udemy course : Python Bootcamp for Data Science 2021 Numpy Pandas & Seaborn</h1> \n\n***",
"_____no_output_____"
],
[
"## 14.5 Shifting Data Through Time (Lagging and Leading)",
"_____no_output_____"
],
[
"First we import pandas library:",
"_____no_output_____"
]
],
[
[
"import pandas as pd",
"_____no_output_____"
]
],
[
[
"Lets read a time series from a csv file using the function **pd.read_csv()**, we set the index column to be the date column using the argument **index_col**, and we convert the dates to datatime format using the argument **parse_dates = True**:",
"_____no_output_____"
]
],
[
[
"TS = pd.read_csv('data/ex17.csv', index_col = 'date', parse_dates = True)\nTS",
"_____no_output_____"
]
],
[
[
"We can shift the price **one day** backward by using the function **shift()**:",
"_____no_output_____"
]
],
[
[
"TS.shift(periods = 1)",
"_____no_output_____"
]
],
[
[
"We can shift the price **two days** backward by using the function **shift()**:",
"_____no_output_____"
]
],
[
[
"TS.shift(periods = 2)",
"_____no_output_____"
]
],
[
[
"We can shift the price **three days** backward by using the function **shift()**:",
"_____no_output_____"
]
],
[
[
"TS.shift(periods = 3)",
"_____no_output_____"
]
],
[
[
"We do not need to write the name of the argument **(periods)**, we can just pass the number of periods like this:",
"_____no_output_____"
]
],
[
[
"TS.shift(3)",
"_____no_output_____"
]
],
[
[
"We can make a forward shift by using **minus** for the periods. Here we use **(-1)** to shift the data one day forward:",
"_____no_output_____"
]
],
[
[
"TS.shift(-1)",
"_____no_output_____"
]
],
[
[
"Usually when dealing with time series, we create a shifted data and attach it as a new column in the time series, like this:",
"_____no_output_____"
]
],
[
[
"TS['lag1'] = TS['apple'].shift(1)\nTS",
"_____no_output_____"
]
],
[
[
"Shifting data in time series generates **missing values**, we can delete these missing values using the function **dropna()**, and to make the changes reflected in the original times series we use the argument **inplace = True**:",
"_____no_output_____"
]
],
[
[
"TS.dropna(inplace = True)\nTS",
"_____no_output_____"
]
],
[
[
"For example we can calculate the daily percent change for stock prices using the **shift()** function like this:",
"_____no_output_____"
]
],
[
[
"TS['percent_change'] = ( TS['apple'] / TS['apple'].shift(1) ) -1\nTS",
"_____no_output_____"
]
],
[
[
"Again here we can delete the missing values like this:",
"_____no_output_____"
]
],
[
[
"TS.dropna(inplace = True)\nTS",
"_____no_output_____"
]
],
[
[
"***\n\n<h1 align=\"center\">Thank You</h1> \n\n***",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e77d74085366852f341e28d6ade8da71ea36c7b0 | 141,928 | ipynb | Jupyter Notebook | notebooks/alternative_resp_v1.ipynb | malfarasplux/biofeatures | 90cba009a34dbaf35ec112edc8f2e93a72563c5b | [
"ISC"
] | null | null | null | notebooks/alternative_resp_v1.ipynb | malfarasplux/biofeatures | 90cba009a34dbaf35ec112edc8f2e93a72563c5b | [
"ISC"
] | null | null | null | notebooks/alternative_resp_v1.ipynb | malfarasplux/biofeatures | 90cba009a34dbaf35ec112edc8f2e93a72563c5b | [
"ISC"
] | 1 | 2020-02-10T09:55:58.000Z | 2020-02-10T09:55:58.000Z | 57.741253 | 22,068 | 0.702497 | [
[
[
"## Set Up ",
"_____no_output_____"
]
],
[
[
"from pythonosc import dispatcher, osc_server\nfrom pythonosc.udp_client import SimpleUDPClient\nimport time\n\nfrom bitalino import BITalino\nimport biofeatures",
"_____no_output_____"
],
[
"bitalino_ip = '192.168.0.101'\nbitalino_port = 31000\n\nactuator_ip = '192.168.0.100'\nactuator_port = 12000\n\nosc_client = SimpleUDPClient(actuator_ip, actuator_port) \n",
"_____no_output_____"
],
[
"def process_riot_data(unused_addr, *values):\n global resp_data, last_update, client, inflated, inflating, deflating\n \n new_data = values[12]\n resp_data.append(new_data)\n \n if len(resp_data) > 200*10 and time.time() - last_update > update_freq:\n last_int, breathe_in = biofeatures.resp_intervals(resp_data, sampling_rate = 200, last_breath = True)\n \n if breathe_in:\n print(\"Breathing in\")\n client.send_message(\"/actuator/inflate\", 100.0)\n inflating = True\n deflating = False\n else:\n print(\"Breathing out\")\n client.send_message(\"/actuator/inflate\", -100.0)\n deflating = True\n inflating = False\n \n last_update = time.time()\n \n # only save the last 5 min of data\n if len(resp_data) > 200 * 60 * 5:\n resp_data = resp_data[-200*60*5:]",
"_____no_output_____"
],
[
"def handle_pressure(unused_addr, pressure):\n global client, inflated, inflating, deflating, stop_flag, pressure_readings, pressure_readings_wearable, t0, wearable\n print(pressure)\n \n if time.time() - t0 > 30:\n stop_flag = False\n wearable = False\n t0 = time.time()\n \n if stop_flag:\n if wearable:\n pressure_readings_wearable.append(pressure)\n else:\n pressure_readings.append(pressure)\n return\n \n if pressure < 800:\n print(\"Fully deflated!\")\n client.send_message(\"/actuator/inflate\", 0.0)\n deflating = False\n \n elif deflating and pressure > 1000:\n print(\"Squeeze!\")\n \n elif pressure > 1150:\n print(\"Careful!\")\n client.send_message(\"/actuator/inflate\", 0.0)\n t0 = time.time()\n stop_flag = True\n # deflating = True\n \n elif not deflating:\n client.send_message(\"/actuator/inflate\", 70.0)",
"_____no_output_____"
],
[
"import pythonosc\nimport time\n\ndispatcher2 = pythonosc.dispatcher.Dispatcher()\ndispatcher2.map(\"/sensor/pressure\", handle_pressure)\n\nclient = SimpleUDPClient(actuator_ip, actuator_port) \n\ninflated = False\ninflating = False\ndeflating = False\nstop_flag = False\n\npressure_readings_wearable = []\npressure_readings = []\nwearable = True\nt0 = time.time()\n\nserver = osc_server.ThreadingOSCUDPServer((bitalino_ip, bitalino_port), dispatcher2)\nprint(\"Serving on {}\".format(server.server_address))\nserver.serve_forever()",
"Serving on ('192.168.0.101', 31000)\n1029.7313232421875\n1029.871337890625\n1042.6334228515625\n1072.517822265625\n1072.9322509765625\n1066.05908203125\n1070.0159912109375\n1075.80859375\n1074.6732177734375\n1069.4910888671875\n1073.4776611328125\n1079.0081787109375\n1078.5517578125\n1072.5494384765625\n1076.8997802734375\n1082.7587890625\n1080.748046875\n1074.8040771484375\n1082.1650390625\n1085.326416015625\n1083.3231201171875\n1081.6016845703125\n1088.9788818359375\n1090.183349609375\n1085.83056640625\n1092.3472900390625\n1094.2293701171875\n1088.7969970703125\n1093.946533203125\n1098.3531494140625\n1093.0625\n1095.6416015625\n1100.6995849609375\n1097.809814453125\n1095.775390625\n1102.6822509765625\n1100.2384033203125\n1096.6998291015625\n1105.947265625\n1102.80224609375\n1098.733154296875\n1108.9573974609375\n1109.92919921875\n1102.2755126953125\n1112.6314697265625\n1111.832275390625\n1109.85400390625\n1119.5228271484375\n1115.1395263671875\n1118.8228759765625\n1126.5543212890625\n1120.7806396484375\n1130.750732421875\n1129.1265869140625\n1130.087646484375\n1138.4063720703125\n1132.5133056640625\n1143.2310791015625\n1140.19189453125\n1143.9974365234375\n1148.70947265625\n1143.8255615234375\n1154.9879150390625\nCareful!\n1145.3251953125\n1115.773193359375\n1103.178466796875\n1117.552490234375\n1119.236083984375\n1119.0093994140625\n1118.926513671875\n1118.5909423828125\n1118.203369140625\n1117.8861083984375\n1117.3916015625\n1116.774658203125\n1116.242919921875\n1115.60595703125\n1114.949951171875\n1114.155517578125\n1113.41845703125\n1112.5230712890625\n1111.552490234375\n1110.8775634765625\n1110.1602783203125\n1109.5919189453125\n1109.2275390625\n1108.7734375\n1108.196533203125\n1107.90576171875\n1107.5390625\n1107.37646484375\n1106.9974365234375\n1107.0123291015625\n1106.832763671875\n1106.7882080078125\n1106.67919921875\n1106.690673828125\n1106.8153076171875\n1106.5408935546875\n1106.2733154296875\n1106.0902099609375\n1105.7938232421875\n1105.6986083984375\n1105.7977294921875\n1105.95166015625\n1106.15234375\n1106.2135009765625\n1106.50048828125\n1106.462158203125\n1106.546875\n1106.7315673828125\n1106.97265625\n1106.9088134765625\n1107.1968994140625\n1107.127685546875\n1107.272216796875\n1107.474853515625\n1107.689697265625\n1107.67333984375\n1107.7896728515625\n1107.711181640625\n1107.729736328125\n1107.54150390625\n1107.610107421875\n1107.6624755859375\n1107.639404296875\n1107.751953125\n1107.7830810546875\n1107.5023193359375\n1107.3475341796875\n1107.1734619140625\n1106.8516845703125\n1106.35302734375\n1106.0093994140625\n1105.685791015625\n1105.38525390625\n1104.9959716796875\n1104.6134033203125\n1104.16357421875\n1103.5419921875\n1102.879150390625\n1102.24951171875\n1101.4443359375\n1100.936767578125\n1100.2518310546875\n1099.638427734375\n1098.9930419921875\n1098.4752197265625\n1097.78759765625\n1097.474365234375\n1097.147705078125\n1096.9329833984375\n1096.506591796875\n1096.3289794921875\n1096.0299072265625\n1095.8995361328125\n1095.71728515625\n1095.5640869140625\n1095.3214111328125\n1095.29052734375\n1095.23193359375\n1095.8572998046875\n1095.948974609375\n1096.2503662109375\n1096.5234375\n1096.6925048828125\n1096.9710693359375\n1097.0924072265625\n1097.6572265625\n1097.982177734375\n1098.49072265625\n1098.850830078125\n1099.2801513671875\n1099.63232421875\n1099.927001953125\n1100.066162109375\n1099.9525146484375\n1100.12255859375\n1100.4818115234375\n1100.66748046875\n1101.0518798828125\n1101.3160400390625\n1101.8387451171875\n1101.916015625\n1101.9512939453125\n1102.1380615234375\n1102.04052734375\n1101.736083984375\n1101.3829345703125\n1100.7615966796875\n1100.2056884765625\n1099.5162353515625\n1098.770263671875\n1098.166259765625\n1097.1112060546875\n1096.222900390625\n1095.18310546875\n1094.5087890625\n1093.7657470703125\n1093.00927734375\n1092.3118896484375\n1091.7568359375\n1091.2752685546875\n1090.7581787109375\n1090.3394775390625\n1090.0306396484375\n1089.6439208984375\n1089.3548583984375\n1089.0352783203125\n1088.66552734375\n1088.4793701171875\n1088.37158203125\n1088.371826171875\n1088.40771484375\n1088.8748779296875\n1089.205078125\n1089.823486328125\n1090.4522705078125\n1091.101318359375\n1091.597900390625\n1092.2791748046875\n1092.6173095703125\n1093.333740234375\n1093.7813720703125\n1094.3638916015625\n1095.1942138671875\n1095.739990234375\n1096.552001953125\n1097.232666015625\n1097.85888671875\n1098.389892578125\n1098.7242431640625\n1098.76025390625\n1099.310302734375\n1099.888916015625\n1100.8575439453125\n1101.59130859375\n1102.3201904296875\n1102.5367431640625\n1102.6693115234375\n1102.458251953125\n1102.65576171875\n1102.6671142578125\n1102.6427001953125\n1102.9525146484375\n1103.64404296875\n1104.04638671875\n1104.3067626953125\n1104.5657958984375\n1104.6502685546875\n1105.1605224609375\n1105.4462890625\n1105.4349365234375\n1105.5892333984375\n1105.7022705078125\n1106.371337890625\n1106.59765625\n1106.263427734375\n1105.9219970703125\n1105.4462890625\n1105.42431640625\n1105.630126953125\n1105.865966796875\n1106.0728759765625\n1106.140380859375\n1105.8641357421875\n1105.6080322265625\n1105.6138916015625\n1105.61328125\n1105.779296875\n1105.5892333984375\n1105.46533203125\n1105.2657470703125\n1105.19140625\n1104.5802001953125\n1103.7213134765625\n1103.29296875\n1103.2877197265625\n1102.9219970703125\n1102.8267822265625\n1102.74072265625\n1102.7755126953125\n1102.5054931640625\n1102.6129150390625\n1102.5675048828125\n1102.2147216796875\n1102.11572265625\n1101.772216796875\n1101.752685546875\n1101.8017578125\n1101.652099609375\n1101.6290283203125\n1101.847900390625\n1102.0537109375\n1101.802978515625\n1101.4010009765625\n1100.8033447265625\n1100.5909423828125\n1100.4573974609375\n1100.5826416015625\n1100.1995849609375\n1100.6326904296875\n1100.6556396484375\n1100.8707275390625\n1100.8565673828125\n1100.74609375\n1100.780029296875\n1100.640869140625\n1100.57470703125\n1100.4815673828125\n1100.490966796875\n1100.4879150390625\n1100.4818115234375\n1100.5787353515625\n1100.591796875\n1100.4178466796875\n1100.01318359375\n1099.7335205078125\n1099.532958984375\n1099.478759765625\n1099.54248046875\n1099.5782470703125\n1099.659423828125\n1099.5015869140625\n1099.6796875\n1099.6915283203125\n1099.6348876953125\n1099.7452392578125\n1099.6739501953125\n1099.73583984375\n1099.5443115234375\n1099.404052734375\n1099.1781005859375\n1098.9671630859375\n1098.8577880859375\n1098.8013916015625\n1098.770751953125\n1098.6763916015625\n1098.1705322265625\n1098.6107177734375\n1097.2860107421875\n1097.118896484375\n1097.19775390625\n1097.2177734375\n1097.220703125\n1097.123779296875\n1096.9395751953125\n1096.906005859375\n1097.0250244140625\n1096.791015625\n1096.6004638671875\n1096.70068359375\n1096.6243896484375\n1096.6875\n1096.28173828125\n1096.396240234375\n1096.4285888671875\n1096.1534423828125\n1096.189208984375\n1095.8470458984375\n1095.4407958984375\n1094.8863525390625\n1094.656005859375\n1094.795166015625\n1094.54150390625\n1094.3389892578125\n1094.270751953125\n1094.19775390625\n1094.2469482421875\n1094.3316650390625\n1094.03564453125\n1094.0023193359375\n1093.933349609375\n1093.9202880859375\n1093.8394775390625\n1093.864990234375\n1093.76318359375\n1093.681884765625\n1093.6650390625\n1093.3380126953125\n1092.9725341796875\n1092.6448974609375\n1092.295166015625\n1092.326904296875\n1092.32275390625\n1092.003662109375\n1091.990478515625\n1091.9603271484375\n1091.8111572265625\n1092.0322265625\n1091.9720458984375\n1091.89306640625\n1091.897216796875\n1091.8104248046875\n1091.7454833984375\n1091.961669921875\n1092.1480712890625\n1092.481201171875\n1092.3583984375\n1091.7056884765625\n1090.6600341796875\n1089.7325439453125\n1088.9884033203125\n1088.0904541015625\n1087.4320068359375\n1086.537109375\n1086.0604248046875\n1085.5831298828125\n1084.8856201171875\n1084.3228759765625\n1084.92236328125\n1083.228271484375\n1083.6195068359375\n1082.298583984375\n1081.681640625\n1081.300048828125\n1080.9102783203125\n1080.05419921875\n1079.3065185546875\n1078.447998046875\n1077.8836669921875\n1077.298828125\n1076.6500244140625\n1075.9642333984375\n1075.0850830078125\n1074.6060791015625\n1073.696044921875\n1073.1279296875\n1072.48486328125\n1071.999755859375\n1071.20654296875\n1070.8564453125\n1070.298583984375\n1069.81982421875\n1069.2689208984375\n1068.8223876953125\n1068.39111328125\n1068.209228515625\n1067.9395751953125\n1067.9053955078125\n1067.6546630859375\n1067.5618896484375\n1067.3511962890625\n1067.2794189453125\n1067.3990478515625\n1068.1142578125\n1068.72998046875\n1069.5723876953125\n1070.3017578125\n1070.9129638671875\n1071.6768798828125\n1072.3330078125\n1072.993896484375\n1073.4718017578125\n1074.080078125\n1074.66064453125\n"
],
[
"client = SimpleUDPClient(actuator_ip, actuator_port) \n\nclient.send_message(\"/actuator/inflate\", 0.0)",
"_____no_output_____"
],
[
"client = SimpleUDPClient('192.168.0.101', 32000) \n\nclient.send_message(\"/actuator/1/inflate\", 0.0)",
"_____no_output_____"
],
[
"# deflating: 970\n# deflating when empty: <800\n# neutral empty: 1016\n# neutral full: 1050 going down slowly to 1020\n# inflating: 1068-1200\n# squeezed: 1050 - 1200\n",
"_____no_output_____"
],
[
"%matplotlib inline\nimport matplotlib.pyplot as plt\n\nplt.plot(pressure_readings_wearable)",
"_____no_output_____"
],
[
"%matplotlib inline\nimport matplotlib.pyplot as plt\n\nplt.plot(pressure_readings)",
"_____no_output_____"
],
[
"import numpy as np\n\nreadings = np.array(pressure_readings_wearable) - np.array(pressure_readings)",
"_____no_output_____"
],
[
"plt.plot(readings[20:])",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e77d80f09d0a4ffa29c194ac28f6255797b9efb9 | 159,343 | ipynb | Jupyter Notebook | extra/Base_colors_detection.ipynb | Gan4x4/hse-cv2019 | 30abf105dcfd54099051b3ea4e3a960fed99fbe8 | [
"MIT"
] | null | null | null | extra/Base_colors_detection.ipynb | Gan4x4/hse-cv2019 | 30abf105dcfd54099051b3ea4e3a960fed99fbe8 | [
"MIT"
] | null | null | null | extra/Base_colors_detection.ipynb | Gan4x4/hse-cv2019 | 30abf105dcfd54099051b3ea4e3a960fed99fbe8 | [
"MIT"
] | 1 | 2020-04-10T17:27:25.000Z | 2020-04-10T17:27:25.000Z | 265.129784 | 15,354 | 0.887074 | [
[
[
"<a href=\"https://colab.research.google.com/github/Gan4x4/CV-HSE2019/blob/master/extra/Detetion_of_image_base_colors_.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"from torchvision import datasets, transforms\nimport numpy\n\ntransform = transforms.Compose([transforms.Lambda(lambda pil_im: numpy.array(pil_im))])\ntransform = None\ntestset = datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)\n",
"Downloading https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz to ./data/cifar-10-python.tar.gz\n"
],
[
"from PIL import Image\nimport numpy as np\nimport cv2\nimport imutils\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n#https://en.wikipedia.org/wiki/Web_colors\nclass ColorDetector():\n COLORS = {\n 'RED': [\n [255, 0,0],\n [220, 20, 60], #Crismon\n [255, 20, 147], #Deep pink\n ],\n 'ORANGE': [\n [255, 69, 0], #Orange red\n [255, 140, 0], #Dark orange\n ],\n 'BLUE': [\n [0, 0, 255],\n [0, 255, 255], #Aqua/Cyan\n [0, 206, 209], #DarkTurquoise\n [ 0, 0, 128] #Navy\n ],\n 'GREEN': [\n [0, 128, 0],\n [0, 100, 0], #Dark green\n #[154, 205, 50], #Yellow green\n #[128, 128, 0] #Olive\n ],\n 'YELLOW': [\n [255, 255 , 0],\n [255, 215, 0], #Gold\n ],\n\n #'PURPLE': [\n # [128, 0 ,128],\n # [255, 0, 255], #Fuchsia\n #],\n\n 'BROWN': [\n [165, 42, 42], #Brown\n [210, 105, 30], #Chocolate\n [128, 0, 0] #Maroon\n ],\n 'DARK': [\n [0, 0, 0],\n #[169, 169, 169], #Dim gray \n\n ], \n 'LIGHT': [\n [255, 255, 255],\n [248, 248, 255], #GhostWhite\n [255, 255, 240], #Ivory\n [255, 248, 220], #Cornsilk\n [224, 255, 255], #LightCyan \n [192, 192, 192], #Silver \n [176, 224, 230], #PowderBlue\n ]\n }\n\n def __init__(self, pil_image):\n self.image = pil_image\n self.palimage = Image.new('P', (16, 16))\n self.palimage.putpalette(self.colors2vec())\n self.png = im_pil.quantize( method=0, kmeans=0, palette=self.palimage)\n self.px_count = im_pil.size[0]*im_pil.size[1]\n\n def colors2vec(self):\n out = []\n for l in ColorDetector.COLORS.values():\n out += [item for sublist in l for item in sublist]\n vec2 = out*32\n return vec2[:256*3]\n \n def get_colors(self,im_pil):\n names = []\n tmp_png = self.png.copy()\n color_usage = np.array(tmp_png.getcolors())\n for key, cl in ColorDetector.COLORS.items():\n pixels_count = 0\n for c in cl:\n c_ind = tmp_png.palette.getcolor(tuple(c))\n cu = color_usage[color_usage[:,1] == c_ind]\n if len(cu) > 0:\n pixels_count += cu[0][0]\n if pixels_count > 0:\n # pixel count to %\n names.append((key,pixels_count/self.px_count))\n names.sort(key=lambda tup: tup[1], reverse = True)\n return names\n\ndef show(pil, png,title = \"\"):\n plt.rcParams[\"figure.figsize\"] = (5,5)\n fig = plt.figure()\n plt.axis('off')\n plt.subplot(1, 2, 1)\n plt.imshow(im_pil)\n plt.subplot(1, 2, 2)\n plt.imshow(png)\n plt.title(title)\n \nfor i in range(10):\n im_pil, cl_num = testset.__getitem__(i)\n cd = ColorDetector(im_pil)\n colors = cd.get_colors(im_pil)\n show(im_pil,cd.png,\", \".join((colors[0][0],colors[1][0],colors[2][0])))\n \n",
"_____no_output_____"
],
[
"#Another approach\n#https://www.pyimagesearch.com/2014/08/04/opencv-python-color-detection/",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
e77d9db284bca5b6b96a9dad878f37fa3da821bd | 112,340 | ipynb | Jupyter Notebook | Notebook 1 - The FHIR API.ipynb | Alvearie/FHIR-from-Jupyter | 212b8135a48689c47316ac8ad2fd1bb88c8acbd8 | [
"Apache-2.0"
] | 4 | 2020-11-25T12:48:03.000Z | 2021-08-24T07:55:46.000Z | Notebook 1 - The FHIR API.ipynb | Alvearie/FHIR-from-Jupyter | 212b8135a48689c47316ac8ad2fd1bb88c8acbd8 | [
"Apache-2.0"
] | null | null | null | Notebook 1 - The FHIR API.ipynb | Alvearie/FHIR-from-Jupyter | 212b8135a48689c47316ac8ad2fd1bb88c8acbd8 | [
"Apache-2.0"
] | 5 | 2020-11-18T01:55:05.000Z | 2021-08-24T07:55:51.000Z | 64.861432 | 1,218 | 0.587903 | [
[
[
"<img src=\"https://www.hl7.org/fhir/assets/images/fhir-logo-www.png\" style=\"float: left; width: 25%; margin-bottom: 0.5em;\">",
"_____no_output_____"
],
[
"Author: **Lee Surprenant** [email protected]\n- [Section 1: The FHIR HTTP API](#Section-1.-The-FHIR-REST-API)\n- [Section 2: FHIR Search](#Section-2:-FHIR-Search)\n- [Section 3: Search paramater types](#Section-3:-Search-parameter-types)\n- [Section 4: Chaining and includes](#Section-4:-Chaining-and-includes)\n- [Section 5: Putting it together](#Section-5:-Putting-it-together)\n- [Section 6: Bulk export](#Section-6:-Bulk-export)",
"_____no_output_____"
]
],
[
[
"# save the base url of the FHIR server\nbase = 'https://cluster1-573846-250babbbe4c3000e15508cd07c1d282b-0000.us-east.containers.appdomain.cloud/open'\n\n# setup imports\nimport os\nfrom requests import get\nfrom requests import post\nfrom requests import put\nfrom requests import delete\nfrom requests import head\nfrom IPython.display import IFrame\n\n# a function to print the top x rows and add a newline\ndef peek(string, line_count=25):\n print(os.linesep.join(string.split(os.linesep)[:line_count]) + '\\n')",
"_____no_output_____"
],
[
"#(Optional)\n# install jsonpointer\n!pip install jsonpointer\nfrom jsonpointer import resolve_pointer as resolve",
"/opt/conda/envs/Python-3.7-main/lib/python3.7/site-packages/secretstorage/dhcrypto.py:16: CryptographyDeprecationWarning: int_from_bytes is deprecated, use int.from_bytes instead\n from cryptography.utils import int_from_bytes\n/opt/conda/envs/Python-3.7-main/lib/python3.7/site-packages/secretstorage/util.py:25: CryptographyDeprecationWarning: int_from_bytes is deprecated, use int.from_bytes instead\n from cryptography.utils import int_from_bytes\nRequirement already satisfied: jsonpointer in /opt/conda/envs/Python-3.7-main/lib/python3.7/site-packages (2.1)\n"
]
],
[
[
"## Section 1. The FHIR REST API",
"_____no_output_____"
]
],
[
[
"# HL7 FHIR defines a set of \"resources\" for exchanging information.\nIFrame('https://www.hl7.org/fhir/resourcelist.html#tabs', width=1200, height=330)",
"_____no_output_____"
],
[
"# Each resource type supports the same set of interactions, categorized in the spec into \"instance-level\" and \"type-level\" interactions.\nIFrame('https://www.hl7.org/fhir/http.html#operations', width=1200, height=330)",
"_____no_output_____"
],
[
"# This notebook focuses on the FHIR Search API, but first we use the \"capabilities\" interaction to learn about our target server.\n\n# retrieve the server \"CapabilityStatement\" and print the important bits\nresponse = get(base + '/metadata')\nprint('Response code: ' + str(response.status_code))\nresult = response.json()\nprint('Server: ' + result['name'] + ' ' + result['version'])\nprint('Security: ' + str(result['rest'][0]['security']))\nresources = result['rest'][0]['resource']\n\nsupported_types = {r['type']: [i['code'] for i in r['interaction']] for r in resources}\n\nprint('Supported types: ')\nfor k,v in supported_types.items():\n print(' ' + k + ': ' + str(v))",
"Response code: 200\nServer: IBM FHIR Server 4.8.0\nSecurity: {'cors': True}\nSupported types: \n Measure: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n MedicinalProductIndication: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Organization: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n EvidenceVariable: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Library: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n CarePlan: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n MedicinalProductAuthorization: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Account: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n OperationOutcome: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n MeasureReport: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n PractitionerRole: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Binary: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n ImmunizationEvaluation: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n MedicationDispense: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n DiagnosticReport: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n MedicinalProductUndesirableEffect: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n DeviceUseStatement: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n PlanDefinition: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Immunization: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n NutritionOrder: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Person: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n MedicinalProduct: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n AdverseEvent: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n ClaimResponse: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n DeviceDefinition: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n GraphDefinition: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n MolecularSequence: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n DeviceMetric: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n MessageHeader: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Invoice: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Linkage: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n MedicationKnowledge: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n EventDefinition: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n ServiceRequest: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n ActivityDefinition: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n SpecimenDefinition: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n SubstanceReferenceInformation: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n ChargeItem: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n DetectedIssue: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n EffectEvidenceSynthesis: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n FamilyMemberHistory: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n ImplementationGuide: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n ClinicalImpression: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n CoverageEligibilityRequest: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n EnrollmentRequest: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n OrganizationAffiliation: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n StructureMap: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n EnrollmentResponse: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n List: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n SubstanceProtein: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n ResearchStudy: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Condition: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Practitioner: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n AppointmentResponse: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Task: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Provenance: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Coverage: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n InsurancePlan: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Slot: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Device: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Bundle: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n ConceptMap: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n BodyStructure: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Location: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n MedicinalProductContraindication: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n RequestGroup: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n BiologicallyDerivedProduct: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Medication: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n TerminologyCapabilities: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Group: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n ValueSet: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n MedicinalProductManufactured: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n SupplyDelivery: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n MedicinalProductInteraction: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n CoverageEligibilityResponse: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n ChargeItemDefinition: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n ObservationDefinition: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n VerificationResult: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Basic: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n CommunicationRequest: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Parameters: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n RelatedPerson: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n CompartmentDefinition: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n TestScript: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n AllergyIntolerance: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n GuidanceResponse: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n MessageDefinition: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Substance: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Composition: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n ImmunizationRecommendation: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n SearchParameter: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n AuditEvent: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n ImagingStudy: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n NamingSystem: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n SubstanceSourceMaterial: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n ResearchElementDefinition: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n EpisodeOfCare: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Goal: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n ResearchDefinition: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n ExampleScenario: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n SubstanceNucleicAcid: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Contract: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n QuestionnaireResponse: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Endpoint: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n StructureDefinition: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n CodeSystem: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n PaymentReconciliation: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Flag: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n RiskEvidenceSynthesis: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n CareTeam: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n SubstanceSpecification: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Subscription: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n ExplanationOfBenefit: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n VisionPrescription: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n DeviceRequest: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n HealthcareService: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Questionnaire: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n OperationDefinition: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Consent: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n RiskAssessment: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n SubstancePolymer: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Encounter: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n MedicationRequest: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n MedicationStatement: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n CapabilityStatement: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Patient: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Specimen: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n MedicinalProductPackaged: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n ResearchSubject: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n MedicinalProductIngredient: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Evidence: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n PaymentNotice: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n CatalogEntry: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n MedicinalProductPharmaceutical: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n SupplyRequest: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n TestReport: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Appointment: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Communication: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Claim: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n DocumentReference: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Observation: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Schedule: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Procedure: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n DocumentManifest: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n Media: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n MedicationAdministration: ['create', 'read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'search-type']\n"
]
],
[
[
"## Section 2: FHIR Search",
"_____no_output_____"
]
],
[
[
"# Now that we know our server supports the \"search-type\" interaction on all resource types, lets start working with the Patient endpoint.\n\n# query for all Patient resources, then print the HTTP status code and the first 25 lines of the response\nresponse = get(base + '/Patient')\nprint('Response code: ' + str(response.status_code))\npeek('Response body: \\n' + response.text)\nprint('Number of entries: ' + str(len(response.json().get('entry'))))\n\n# technically you've now performed your first FHIR \"search\" (just with no parameters)",
"Response code: 200\nResponse body: \n{\n \"resourceType\": \"Bundle\",\n \"id\": \"b6bce8fe-46e4-4618-8f4e-ff3f7323e946\",\n \"type\": \"searchset\",\n \"total\": 32655,\n \"link\": [\n {\n \"relation\": \"self\",\n \"url\": \"https://cluster1-573846-250babbbe4c3000e15508cd07c1d282b-0000.us-east.containers.appdomain.cloud/open/Patient?_count=10&_page=1\"\n },\n {\n \"relation\": \"next\",\n \"url\": \"https://cluster1-573846-250babbbe4c3000e15508cd07c1d282b-0000.us-east.containers.appdomain.cloud/open/Patient?_count=10&_page=2\"\n }\n ],\n \"entry\": [\n {\n \"fullUrl\": \"https://cluster1-573846-250babbbe4c3000e15508cd07c1d282b-0000.us-east.containers.appdomain.cloud/open/Patient/17598bed122-d90e0186-8458-4482-a580-5b18b554ed3c\",\n \"resource\": {\n \"resourceType\": \"Patient\",\n \"id\": \"17598bed122-d90e0186-8458-4482-a580-5b18b554ed3c\",\n \"meta\": {\n \"versionId\": \"4\",\n \"lastUpdated\": \"2021-03-12T03:13:48.626Z\",\n\nNumber of entries: 10\n"
],
[
"# note that results are paged and the \"link\" field in the response Bundle contains links to the previous, current, and next page of results\nfor link in response.json().get('link'):\n if link.get('relation') == 'next':\n page2 = get(link.get('url')) \npeek('Second page: \\n' + page2.text)\nprint('Number of entries: ' + str(len(response.json().get('entry'))))",
"Second page: \n{\n \"resourceType\": \"Bundle\",\n \"id\": \"93e11f34-1abd-4124-bbb1-8cd1edf31dad\",\n \"type\": \"searchset\",\n \"total\": 32655,\n \"link\": [\n {\n \"relation\": \"self\",\n \"url\": \"https://cluster1-573846-250babbbe4c3000e15508cd07c1d282b-0000.us-east.containers.appdomain.cloud/open/Patient?_count=10&_page=2\"\n },\n {\n \"relation\": \"next\",\n \"url\": \"https://cluster1-573846-250babbbe4c3000e15508cd07c1d282b-0000.us-east.containers.appdomain.cloud/open/Patient?_count=10&_page=3\"\n },\n {\n \"relation\": \"previous\",\n \"url\": \"https://cluster1-573846-250babbbe4c3000e15508cd07c1d282b-0000.us-east.containers.appdomain.cloud/open/Patient?_count=10&_page=1\"\n }\n ],\n \"entry\": [\n {\n \"fullUrl\": \"https://cluster1-573846-250babbbe4c3000e15508cd07c1d282b-0000.us-east.containers.appdomain.cloud/open/Patient/17598bf809c-1a099ca4-cdb9-4837-8692-51338082cd97\",\n \"resource\": {\n \"resourceType\": \"Patient\",\n\nNumber of entries: 10\n"
],
[
"# we can control the number of resources on each page by passing the _count parameter\nresponse = get(base + '/Patient?_count=1')\npeek('Single resource per page: \\n' + response.text)\nprint('Number of entries: ' + str(len(response.json().get('entry'))))",
"Single resource per page: \n{\n \"resourceType\": \"Bundle\",\n \"id\": \"b0140878-b70b-4130-8a7d-138bca685f6b\",\n \"type\": \"searchset\",\n \"total\": 32655,\n \"link\": [\n {\n \"relation\": \"self\",\n \"url\": \"https://cluster1-573846-250babbbe4c3000e15508cd07c1d282b-0000.us-east.containers.appdomain.cloud/open/Patient?_count=1&_page=1\"\n },\n {\n \"relation\": \"next\",\n \"url\": \"https://cluster1-573846-250babbbe4c3000e15508cd07c1d282b-0000.us-east.containers.appdomain.cloud/open/Patient?_count=1&_page=2\"\n }\n ],\n \"entry\": [\n {\n \"fullUrl\": \"https://cluster1-573846-250babbbe4c3000e15508cd07c1d282b-0000.us-east.containers.appdomain.cloud/open/Patient/17598bed122-d90e0186-8458-4482-a580-5b18b554ed3c\",\n \"resource\": {\n \"resourceType\": \"Patient\",\n \"id\": \"17598bed122-d90e0186-8458-4482-a580-5b18b554ed3c\",\n \"meta\": {\n \"versionId\": \"4\",\n \"lastUpdated\": \"2021-03-12T03:13:48.626Z\",\n\nNumber of entries: 1\n"
],
[
"# if you're only interested in the count, you can specify that via either\n# A. _count=0 (0 results per page); or\n# B. _summary=count\n\nprint(get(base + '/Patient' + '?' + '_summary=count').text)",
"{\n \"resourceType\": \"Bundle\",\n \"id\": \"178e1b23-7962-43c8-87b0-e4863644420b\",\n \"meta\": {\n \"tag\": [\n {\n \"system\": \"http://terminology.hl7.org/CodeSystem/v3-ObservationValue\",\n \"code\": \"SUBSETTED\",\n \"display\": \"subsetted\"\n }\n ]\n },\n \"type\": \"searchset\",\n \"total\": 32655,\n \"link\": [\n {\n \"relation\": \"self\",\n \"url\": \"https://cluster1-573846-250babbbe4c3000e15508cd07c1d282b-0000.us-east.containers.appdomain.cloud/open/Patient?_count=10&_summary=count&_page=1\"\n }\n ]\n}\n"
],
[
"# if you want a lot of results per page, you can reduce the amount of data returned via the _summary or _elements parameters\n\n# first, lets review the structure of the Patient resource\nIFrame('https://hl7.org/fhir/patient.html#resource', width=1200, height=330)",
"_____no_output_____"
],
[
"# print the list of top-level elements in the first Patient resource returned\nresponse = get(base + '/Patient')\npeek('Normal: \\n' + str(response.json().get('entry')[0].get('resource').keys()))\n\n# look for the Σ flag in the Resource Content section of the resource page in the specification for what elements are considered \"summary\" elements \nresponse = get(base + '/Patient?' + '_summary=true')\npeek('Summary: \\n' + str(response.json().get('entry')[0].get('resource').keys()))\n\n# need more control?\n# you can use the _elements parameter to ask for specific fields back (although the server should include required fields and modifier fields as well)\nresponse = get(base + '/Patient?' + '_elements=id,gender')\npeek('Elements: \\n' + str(response.json().get('entry')[0].get('resource').keys()))",
"Normal: \ndict_keys(['resourceType', 'id', 'meta', 'text', 'extension', 'identifier', 'name', 'telecom', 'gender', 'birthDate', 'address', 'maritalStatus', 'multipleBirthBoolean', 'communication'])\n\nSummary: \ndict_keys(['resourceType', 'id', 'meta', 'identifier', 'name', 'telecom', 'gender', 'birthDate', 'address'])\n\nElements: \ndict_keys(['resourceType', 'id', 'meta', 'gender'])\n\n"
],
[
"# this can add up!\n\nresponse = get(base + '/Patient?_count=100')\nprint('Normal: \\t' + str(len(response.content)) + ' bytes \\t(' + str(response.elapsed.total_seconds()) + ' s)')\n\nresponse = get(base + '/Patient?_count=100&_summary=true')\nprint('Summary: \\t' + str(len(response.content)) + ' bytes \\t(' + str(response.elapsed.total_seconds()) + ' s)')\n\nresponse = get(base + '/Patient?_count=100&_elements=id,gender,birthDate')\nprint('Elements: \\t' + str(len(response.content)) + ' bytes \\t(' + str(response.elapsed.total_seconds()) + ' s)')\n",
"Normal: \t902254 bytes \t(0.327694 s)\nSummary: \t526541 bytes \t(0.279208 s)\nElements: \t114154 bytes \t(0.241758 s)\n"
],
[
"# now add some search parameters\n\n# each FHIR resource type has its own set of parameters; find them toward the bottom of the page for that resource type in the specification\n# for example, for the Patient resource type, see https://www.hl7.org/fhir/patient.html#search\nIFrame('https://www.hl7.org/fhir/patient.html#search', width=1200, height=500)",
"_____no_output_____"
],
[
"# for example, lets use the search parameter named \"gender\"\nresponse = get(base + '/Patient' + '?' + 'gender=male')\nprint('Response code: ' + str(response.status_code))\npeek('Response body: \\n' + response.text)",
"Response code: 200\nResponse body: \n{\n \"resourceType\": \"Bundle\",\n \"id\": \"6f3f1954-e5cc-482b-b469-f9c05aa70b3c\",\n \"type\": \"searchset\",\n \"total\": 15450,\n \"link\": [\n {\n \"relation\": \"self\",\n \"url\": \"https://cluster1-573846-250babbbe4c3000e15508cd07c1d282b-0000.us-east.containers.appdomain.cloud/open/Patient?_count=10&gender=male&_page=1\"\n },\n {\n \"relation\": \"next\",\n \"url\": \"https://cluster1-573846-250babbbe4c3000e15508cd07c1d282b-0000.us-east.containers.appdomain.cloud/open/Patient?_count=10&gender=male&_page=2\"\n }\n ],\n \"entry\": [\n {\n \"fullUrl\": \"https://cluster1-573846-250babbbe4c3000e15508cd07c1d282b-0000.us-east.containers.appdomain.cloud/open/Patient/17598bed122-d90e0186-8458-4482-a580-5b18b554ed3c\",\n \"resource\": {\n \"resourceType\": \"Patient\",\n \"id\": \"17598bed122-d90e0186-8458-4482-a580-5b18b554ed3c\",\n \"meta\": {\n \"versionId\": \"4\",\n \"lastUpdated\": \"2021-03-12T03:13:48.626Z\",\n\n"
],
[
"# pro tip: combine your search query with _summary=count to explore the data\nprint('male: \\t' + str(get(base + '/Patient' + '?' + 'gender=male' + '&' + '_summary=count').json().get('total')))\nprint('female: \\t' + str(get(base + '/Patient' + '?' + 'gender=female' + '&' + '_summary=count').json().get('total')))\n\n# use the \"missing\" modifier to look for resources that do NOT have a value for the target parameter\nresponse = get(base + '/Patient' + '?' + 'gender:missing=true' + '&' + '_summary=count')\nprint('missing gender: ' + str(response.json().get('total')))",
"male: \t15450\nfemale: \t17204\nmissing gender: 1\n"
]
],
[
[
"## Section 3: Search parameter types",
"_____no_output_____"
]
],
[
[
"# search parameters have types\n\n# gender is considered a \"token\" search parameter\n\n# Token search\n# this parameter type is common for 'coded' values (Code, Coding, and CodeableConcept) and identifiers\n# token values consist of a system and a code, although sometimes the system is implicit (like in the case of gender)\n# users can search on the system and code (system|code), the code alone (code), system-less codes (|code), or even the system alone (system|)\nresponse = get(base + '/Patient' + '?' + 'gender=http://hl7.org/fhir/administrative-gender|male' + '&_count=1&_elements=gender')\nprint('male:\\n' + response.text)\n\n\n# there are also Number, Date/DateTime, String, Reference, Quantity, URI, and Composite parameter types",
"male:\n{\n \"resourceType\": \"Bundle\",\n \"id\": \"630d24e0-bb85-4aa1-88ad-156e52e8ac8a\",\n \"meta\": {\n \"tag\": [\n {\n \"system\": \"http://terminology.hl7.org/CodeSystem/v3-ObservationValue\",\n \"code\": \"SUBSETTED\",\n \"display\": \"subsetted\"\n }\n ]\n },\n \"type\": \"searchset\",\n \"total\": 15450,\n \"link\": [\n {\n \"relation\": \"self\",\n \"url\": \"https://cluster1-573846-250babbbe4c3000e15508cd07c1d282b-0000.us-east.containers.appdomain.cloud/open/Patient?_count=1&gender=http://hl7.org/fhir/administrative-gender%7Cmale&_elements=gender&_page=1\"\n },\n {\n \"relation\": \"next\",\n \"url\": \"https://cluster1-573846-250babbbe4c3000e15508cd07c1d282b-0000.us-east.containers.appdomain.cloud/open/Patient?_count=1&gender=http://hl7.org/fhir/administrative-gender%7Cmale&_elements=gender&_page=2\"\n }\n ],\n \"entry\": [\n {\n \"fullUrl\": \"https://cluster1-573846-250babbbe4c3000e15508cd07c1d282b-0000.us-east.containers.appdomain.cloud/open/Patient/17598bed122-d90e0186-8458-4482-a580-5b18b554ed3c\",\n \"resource\": {\n \"resourceType\": \"Patient\",\n \"id\": \"17598bed122-d90e0186-8458-4482-a580-5b18b554ed3c\",\n \"meta\": {\n \"versionId\": \"4\",\n \"lastUpdated\": \"2021-03-12T03:13:48.626Z\",\n \"profile\": [\n \"http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient\"\n ],\n \"tag\": [\n {\n \"system\": \"http://terminology.hl7.org/CodeSystem/v3-ObservationValue\",\n \"code\": \"SUBSETTED\",\n \"display\": \"subsetted\"\n }\n ]\n },\n \"gender\": \"male\"\n },\n \"search\": {\n \"mode\": \"match\",\n \"score\": 1\n }\n }\n ]\n}\n"
],
[
"# String search\nresponse = get(base + '/Patient' + '?' + 'family=Smith' + '&_elements=name')\nprint('Smiths:')\nfor entry in response.json().get('entry'):\n resource = entry.get('resource')\n print(resource.get('id'), end=': ')\n print(', '.join(map(lambda n: n.get('family'), resource.get('name'))))\n ",
"Smiths:\n17598d8e9df-706d630f-784d-473d-a0d2-37af26e3c36e: Smitham\n17598dc69c4-fe632367-ce4f-413b-9639-5f409631fdbd: Smith\n17598e7faf2-37231ae2-90fa-4668-90cc-9d413e44ff73: Smitham\n17598fe2d81-8588df6c-a4e5-486f-8de7-f2a457e1ecbb: Smitham\n175991c2ff1-8b5aef81-6ed2-4173-8ee0-3a38612ece43: Smitham\n175991de90e-b9364b28-a200-4d19-9bba-1cd4d5d9f037: Heller, Smith\n175992f962b-159acf20-e5d5-4370-bf38-8e02eef6d761: Smith\n17599326aa9-40e01d7e-1d5b-4f1b-9bed-9c0a0b031df1: Smith\n175993420d0-eb6a0968-589a-4a71-a010-19e84056c44e: Smitham\n17599375dc6-21078467-b048-499a-b8c4-9f5ddfc6ffd3: Haley, Smitham\n"
],
[
"# wait, \"Smitham\" !?\n\n# string search performs a case-insensitive \"begins-with\" search by default!\n# use the modifier \":exact\" if you want exact matches (and improved performance)\nresponse = get(base + '/Patient' + '?' + 'family:exact=Smith' + '&_elements=name')\nprint('Smiths:')\nfor entry in response.json().get('entry'):\n resource = entry.get('resource')\n print(resource.get('id'), end=': ')\n print(', '.join(map(lambda n: n.get('family'), resource.get('name'))))\nprint()\n\n# string search also has a \":contains\" modifier\nresponse = get(base + '/Patient' + '?' + 'family:contains=ski' + '&_elements=name')\nprint('Skis:')\nfor entry in response.json().get('entry'):\n resource = entry.get('resource')\n print(resource.get('id'), end=': ')\n print(', '.join(map(lambda n: n.get('family'), resource.get('name'))))\n",
"Smiths:\n17598dc69c4-fe632367-ce4f-413b-9639-5f409631fdbd: Smith\n175991de90e-b9364b28-a200-4d19-9bba-1cd4d5d9f037: Heller, Smith\n175992f962b-159acf20-e5d5-4370-bf38-8e02eef6d761: Smith\n17599326aa9-40e01d7e-1d5b-4f1b-9bed-9c0a0b031df1: Smith\n175993c2874-5f898109-a18d-4d6e-8cfb-ecd69eb37862: Smith\n17599522520-bdb4311f-3765-45f2-bd5d-1f1aca14a931: Smith\n17599539a99-bccf02f3-57ef-4399-a4c6-0296aa8356c1: Purdy, Smith\n1759954cc00-9def2bdc-a444-4e84-bf77-a0e79e449d19: Rosenbaum, Smith\n175995a5564-869be93e-c7c2-4cab-9951-d15063f39975: Wintheiser, Smith\n175995ad366-3722d3d9-c56e-4d06-ba32-1b662e18bfbe: Wehner, Smith\n\nSkis:\n17598bf6496-92b7682f-d882-4b3c-8e37-178b11cde674: Gusikowski, West\n17598c069d0-3b1b68c5-13e0-4c46-b929-1fea6d13454f: Osinski\n17598c0689e-e60c055e-c166-406d-a9b0-f6d113292dcc: Gutkowski\n17598c10cbc-642eb489-8d83-4220-8591-a31adc7a9189: Gusikowski\n17598c3ebc7-63c73ac0-7cc7-492f-b1f5-661c9da0b95e: Gulgowski\n17598c45f73-e1ac3687-ae53-4591-b9f7-65deb78c8a1b: Jaskolski\n17598c61295-bf40a9c1-ebc2-46cb-b4e5-c1ea732c0960: Gusikowski\n17598c88bd6-e98052ab-8f37-46c5-ade7-c3b441573a90: Swaniawski\n17598cbac2b-5b5193d4-9b35-48a9-88b1-b2912fd0c896: Jaskolski, Erdman\n17598ccda87-246aadea-59a6-4287-a472-7a9117e89059: Powlowski\n"
],
[
"# Date search\nresponse = get(base + '/Patient' + '?' + 'birthdate=1984' + '&_elements=birthDate')\nprint('Born in 1984:')\nfor entry in response.json().get('entry'):\n resource = entry.get('resource')\n print(resource.get('id'), end=': ')\n print(resource.get('birthDate'))",
"Born in 1984:\n17598c01014-694ba51f-a02d-4686-b956-7d6eb9d7e5fa: 1984-12-05\n17598c330b0-817d8bac-b275-449d-8163-0ae095d6a7d5: 1984-03-23\n17598d78d31-639632e7-4f79-4b1a-81e8-f462de2c5912: 1984-09-18\n17598dc812f-37fd8fe9-e900-4f11-b166-5515fd7b4125: 1984-12-26\n17598dda658-9243965e-f6e2-4909-b2f6-89dcd7dcf799: 1984-05-04\n17598de13a7-c2c48b25-a1cc-498a-9b98-08629619ae15: 1984-03-04\n17598e32314-d67c7847-5ca3-4b0c-86df-195e40626a65: 1984-10-05\n17598e54dfe-683137bf-6a96-4b94-9218-7be5ff4ee2fb: 1984-04-21\n17598eed38d-eb24c019-4ab9-4f14-9c66-db95a1ed22dc: 1984-10-23\n17598f52f36-17f4bfd8-c305-468f-9c38-792a461e28a3: 1984-04-26\n"
],
[
"# date searches support lt(<), le(<=), gt(>), ge(>=), sa(starts after), and eb(ends before) \"prefixes\"\nresponse = get(base + '/Patient' + '?' + 'birthdate=eb1984' + '&_elements=birthDate')\nprint('Born before 1984:')\nfor entry in response.json().get('entry'):\n resource = entry.get('resource')\n print(resource.get('id'), end=': ')\n print(resource.get('birthDate'))\n\nresponse = get(base + '/Patient' + '?' + 'birthdate=sa1984' + '&_elements=birthDate')\nprint('\\n' + 'Born after 1984:')\nfor entry in response.json().get('entry'):\n resource = entry.get('resource')\n print(resource.get('id'), end=': ')\n print(resource.get('birthDate'))\n\n# some servers support ap(approximately equal) as well, although the spec lets the server decide exactly what that means...\nresponse = get(base + '/Patient' + '?' + 'birthdate=ap1984' + '&_elements=birthDate')\nprint('\\n' + 'Born \"around\" 1984:')\nfor entry in response.json().get('entry'):\n resource = entry.get('resource')\n print(resource.get('id'), end=': ')\n print(resource.get('birthDate'))",
"Born before 1984:\n17598bf0165-6eda45e2-f9c1-4c4c-9ef2-1776cfbb0a7d: 1976-10-11\n17598bf1688-037fcb72-18af-40ce-a96b-c393a595dd49: 1975-07-10\n17598bf28f3-257b9fe9-9084-41d6-bb0f-43b4729a7f0d: 1982-01-13\n17598bf36c7-fedcedc3-b78c-4688-82ef-622e0cc71b22: 1973-03-03\n17598bf6cd6-d8388338-897d-48a0-b334-a877459941b2: 1979-03-01\n17598bf3d06-15fa6deb-59ad-4bd2-b8a1-8a2fa606d084: 1924-10-07\n17598bf6496-92b7682f-d882-4b3c-8e37-178b11cde674: 1948-12-25\n17598bf98b2-789821a7-b30c-48d4-b388-5343a933d8ad: 1972-06-15\n17598bfb281-9ca10cb0-6ba0-4691-85f4-424423b1869d: 1970-12-02\n17598bfa2da-9c19d3ed-5bef-49ab-b6b0-1d731446ddf6: 1960-11-21\n\nBorn after 1984:\n17598bed122-d90e0186-8458-4482-a580-5b18b554ed3c: 1990-02-05\n17598beef3c-73a65dab-c8e5-4756-a60a-69bbc48cef4f: 1986-07-15\n17598bf4a5d-185e291b-d0e3-42d3-9b70-eeae60debeec: 2005-11-09\n17598bf2ea9-7238cb29-0108-47a7-bf50-c94c6468ad2b: 2020-01-19\n17598bf555d-8e5857a0-4da9-4e6c-b9be-8624f80cf080: 1990-01-07\n17598bf809c-1a099ca4-cdb9-4837-8692-51338082cd97: 2019-09-05\n17598bf8b6a-ef83ac85-d722-406a-893a-7b016f060867: 1994-08-22\n17598bf9bf3-72e9d777-a355-4e7c-9b61-6a7dd30a61f4: 1999-10-06\n17598bfb106-0f9d95e0-84de-4b28-b8ad-d6a0f4caa980: 1993-01-07\n17598bfd0cf-22472597-7a8f-47b4-abb9-b36ab298ee12: 2007-08-05\n\nBorn \"around\" 1984:\n17598beef3c-73a65dab-c8e5-4756-a60a-69bbc48cef4f: 1986-07-15\n17598bf28f3-257b9fe9-9084-41d6-bb0f-43b4729a7f0d: 1982-01-13\n17598c01014-694ba51f-a02d-4686-b956-7d6eb9d7e5fa: 1984-12-05\n17598c05638-14568b50-6d51-4ab4-a94c-096c49ac8a4e: 1982-04-20\n17598c0a7ca-46d519f3-9866-427f-91b3-75f834a5eb72: 1983-10-29\n17598c1650a-20726259-3909-46b4-8d70-effe09390d7c: 1982-09-15\n17598c31418-c137d962-05b5-4f50-aec7-70033c0de3c1: 1983-05-29\n17598c330b0-817d8bac-b275-449d-8163-0ae095d6a7d5: 1984-03-23\n17598c38744-b7e7533a-5d2d-40bd-8f34-ab16eedd8062: 1988-06-29\n17598c41945-9802183c-797e-48ef-8f92-da84f0c00aa1: 1980-04-24\n"
],
[
"# Reference search\nresponse = get(base + '/Patient?general-practitioner:missing=false&_elements=generalPractitioner,link,managingOrganization&_count=1')\npeek('Patients with a general-practitioner: \\n' + response.text, 15)",
"Patients with a general-practitioner: \n{\n \"resourceType\": \"Bundle\",\n \"id\": \"0b24f3ee-94b9-4bde-8dd1-5a5479c3c53f\",\n \"meta\": {\n \"tag\": [\n {\n \"system\": \"http://terminology.hl7.org/CodeSystem/v3-ObservationValue\",\n \"code\": \"SUBSETTED\",\n \"display\": \"subsetted\"\n }\n ]\n },\n \"type\": \"searchset\",\n \"total\": 0,\n\n"
],
[
"# since our model doesn't have any reference fields on the Patient resources, lets look at Conditions instead\nIFrame('https://hl7.org/fhir/condition.html#resource', width=1200, height=480)",
"_____no_output_____"
],
[
"# get all conditions that reference a specific patient\nresponse = get(base + '/Condition' + '?' + 'subject=Patient/17598beef3c-73a65dab-c8e5-4756-a60a-69bbc48cef4f' + '&_elements=code')\nprint('Conditions for patient 17598beef3c-73a65dab-c8e5-4756-a60a-69bbc48cef4f:')\nfor entry in response.json().get('entry'):\n resource = entry.get('resource')\n print(resource.get('code'))\n\n# when the type of the reference is fixed to a single value, it can be omitted (Patient/x -> x)\nresponse2 = get(base + '/Condition' + '?' + 'patient=17598beef3c-73a65dab-c8e5-4756-a60a-69bbc48cef4f' + '&_elements=code')\nprint('\\n' + 'Result entries match? ' + str(response.json().get('entry') == response2.json().get('entry')))\n\n# a reference to a resource's full url on the server should be equivalent to the relative reference format mentioned above\nresponse3 = get(base + '/Condition' + '?' + 'patient=' + base + '/Patient/17598beef3c-73a65dab-c8e5-4756-a60a-69bbc48cef4f' + '&_elements=code')\nprint('\\n' + 'Result entries match? ' + str(response.json().get('entry') == response3.json().get('entry')))\n\n# references can also reference resources on other servers",
"Conditions for patient 17598beef3c-73a65dab-c8e5-4756-a60a-69bbc48cef4f:\n{'coding': [{'system': 'http://snomed.info/sct', 'code': '10509002', 'display': 'Acute bronchitis (disorder)'}], 'text': 'Acute bronchitis (disorder)'}\n{'coding': [{'system': 'http://snomed.info/sct', 'code': '195662009', 'display': 'Acute viral pharyngitis (disorder)'}], 'text': 'Acute viral pharyngitis (disorder)'}\n{'coding': [{'system': 'http://snomed.info/sct', 'code': '68235000', 'display': 'Nasal congestion (finding)'}], 'text': 'Nasal congestion (finding)'}\n{'coding': [{'system': 'http://snomed.info/sct', 'code': '267102003', 'display': 'Sore throat symptom (finding)'}], 'text': 'Sore throat symptom (finding)'}\n{'coding': [{'system': 'http://snomed.info/sct', 'code': '248595008', 'display': 'Sputum finding (finding)'}], 'text': 'Sputum finding (finding)'}\n{'coding': [{'system': 'http://snomed.info/sct', 'code': '84229001', 'display': 'Fatigue (finding)'}], 'text': 'Fatigue (finding)'}\n{'coding': [{'system': 'http://snomed.info/sct', 'code': '267036007', 'display': 'Dyspnea (finding)'}], 'text': 'Dyspnea (finding)'}\n{'coding': [{'system': 'http://snomed.info/sct', 'code': '56018004', 'display': 'Wheezing (finding)'}], 'text': 'Wheezing (finding)'}\n{'coding': [{'system': 'http://snomed.info/sct', 'code': '43724002', 'display': 'Chill (finding)'}], 'text': 'Chill (finding)'}\n{'coding': [{'system': 'http://snomed.info/sct', 'code': '386661006', 'display': 'Fever (finding)'}], 'text': 'Fever (finding)'}\n\nResult entries match? True\n\nResult entries match? True\n"
]
],
[
[
"## Section 4: Chaining and includes",
"_____no_output_____"
]
],
[
[
"# Chaining\n\n# where reference parameters get really interesting is when you want to query one resource type based on a property of another resource to which its linked\n# for example, here is a search for Type II Diabetes in female patients\nresponse = get(base + '/Condition' + '?' + 'code=http://snomed.info/sct|44054006' + '&' + 'patient:Patient.gender=female' + '&_count=1')\npeek('Type II Diabetes in female patients: \\n' + str(response.text), 100)",
"Type II Diabetes in female patients: \n{\n \"resourceType\": \"Bundle\",\n \"id\": \"6824f74d-3375-489d-8204-e11448d6d959\",\n \"type\": \"searchset\",\n \"total\": 600,\n \"link\": [\n {\n \"relation\": \"self\",\n \"url\": \"https://cluster1-573846-250babbbe4c3000e15508cd07c1d282b-0000.us-east.containers.appdomain.cloud/open/Condition?_count=1&code=http://snomed.info/sct%7C44054006&patient:Patient.gender=female&_page=1\"\n },\n {\n \"relation\": \"next\",\n \"url\": \"https://cluster1-573846-250babbbe4c3000e15508cd07c1d282b-0000.us-east.containers.appdomain.cloud/open/Condition?_count=1&code=http://snomed.info/sct%7C44054006&patient:Patient.gender=female&_page=2\"\n }\n ],\n \"entry\": [\n {\n \"fullUrl\": \"https://cluster1-573846-250babbbe4c3000e15508cd07c1d282b-0000.us-east.containers.appdomain.cloud/open/Condition/17598ca24de-8a64595d-1f7f-4a9d-af9b-9623bbd3db6d\",\n \"resource\": {\n \"resourceType\": \"Condition\",\n \"id\": \"17598ca24de-8a64595d-1f7f-4a9d-af9b-9623bbd3db6d\",\n \"meta\": {\n \"versionId\": \"2\",\n \"lastUpdated\": \"2021-03-12T03:09:00.332Z\",\n \"profile\": [\n \"http://hl7.org/fhir/us/core/StructureDefinition/us-core-condition\"\n ]\n },\n \"clinicalStatus\": {\n \"coding\": [\n {\n \"system\": \"http://terminology.hl7.org/CodeSystem/condition-clinical\",\n \"code\": \"active\"\n }\n ]\n },\n \"verificationStatus\": {\n \"coding\": [\n {\n \"system\": \"http://terminology.hl7.org/CodeSystem/condition-ver-status\",\n \"code\": \"confirmed\"\n }\n ]\n },\n \"category\": [\n {\n \"coding\": [\n {\n \"system\": \"http://terminology.hl7.org/CodeSystem/condition-category\",\n \"code\": \"encounter-diagnosis\",\n \"display\": \"Encounter Diagnosis\"\n }\n ]\n }\n ],\n \"code\": {\n \"coding\": [\n {\n \"system\": \"http://snomed.info/sct\",\n \"code\": \"44054006\",\n \"display\": \"Diabetes\"\n }\n ],\n \"text\": \"Diabetes\"\n },\n \"subject\": {\n \"reference\": \"Patient/17598ca24dd-04a58485-e8ac-4b6d-b85f-de4f55bf0787\"\n },\n \"encounter\": {\n \"reference\": \"Encounter/17598ca24de-40d4ed3a-1b8a-4551-a89a-eca22e717f48\"\n },\n \"onsetDateTime\": \"2017-12-18T16:16:32-05:00\",\n \"recordedDate\": \"2017-12-18T16:16:32-05:00\"\n },\n \"search\": {\n \"mode\": \"match\",\n \"score\": 1\n }\n }\n ]\n}\n\n"
],
[
"# Reverse chaining\n\n# references can be searched the other way around via the \"_has\" parameter\nresponse = get(base + '/Patient' + '?' + '_has:Condition:patient:code=http://snomed.info/sct|44054006' + '&_count=1')\npeek('Patients with Type II Diabetes: \\n' + response.text)",
"Patients with Type II Diabetes: \n{\n \"resourceType\": \"Bundle\",\n \"id\": \"b984c979-395c-455e-bc74-bda8718a87d1\",\n \"type\": \"searchset\",\n \"total\": 1063,\n \"link\": [\n {\n \"relation\": \"self\",\n \"url\": \"https://cluster1-573846-250babbbe4c3000e15508cd07c1d282b-0000.us-east.containers.appdomain.cloud/open/Patient?_count=1&_has:Condition:patient:code=http://snomed.info/sct%7C44054006&_page=1\"\n },\n {\n \"relation\": \"next\",\n \"url\": \"https://cluster1-573846-250babbbe4c3000e15508cd07c1d282b-0000.us-east.containers.appdomain.cloud/open/Patient?_count=1&_has:Condition:patient:code=http://snomed.info/sct%7C44054006&_page=2\"\n }\n ],\n \"entry\": [\n {\n \"fullUrl\": \"https://cluster1-573846-250babbbe4c3000e15508cd07c1d282b-0000.us-east.containers.appdomain.cloud/open/Patient/17598c0ea1f-f838725e-91e0-4a98-9eb6-f3e7323e9dfa\",\n \"resource\": {\n \"resourceType\": \"Patient\",\n \"id\": \"17598c0ea1f-f838725e-91e0-4a98-9eb6-f3e7323e9dfa\",\n \"meta\": {\n \"versionId\": \"4\",\n \"lastUpdated\": \"2021-03-12T03:09:46.128Z\",\n\n"
],
[
"# Includes\n\n# its also possible to get a resource and its related resources back in a single query\nresponse = get(base + '/Condition?code=http://snomed.info/sct|44054006' + '&' + '_include=Condition:patient' + '&_count=2')\npeek('Response contains both Conditions and Patients, but only the Conditions are counted in the page size and total:')\nprint('Total: ' + str(response.json().get('total')))\nfor entry in response.json().get('entry'):\n resource = entry.get('resource')\n print(resource.get('resourceType'), end=': ')\n print(resource.get('id'))\n",
"Response contains both Conditions and Patients, but only the Conditions are counted in the page size and total:\n\nTotal: 1063\nCondition: 17598c0ea20-7b251c64-b10a-4942-b72b-3014af79875f\nCondition: 17598c6d269-b8bd24cc-0280-48f8-a835-db262812387e\nPatient: 17598c0ea1f-f838725e-91e0-4a98-9eb6-f3e7323e9dfa\nPatient: 17598c6d269-6c393947-fbeb-44b7-9ec7-fbaede13bc8a\n"
],
[
"# Reverse Includes\n\nresponse = get(base + '/Patient?gender=female' + '&' + '_revinclude=Condition:patient' + '&_count=2')\npeek('Response contains both Patients and Conditions, but only the Patients are counted in the page size and total:')\nprint('Total: ' + str(response.json().get('total')))\nfor entry in response.json().get('entry'):\n resource = entry.get('resource')\n print(resource.get('resourceType'), end=': ')\n print(resource.get('id'))",
"Response contains both Patients and Conditions, but only the Patients are counted in the page size and total:\n\nTotal: 17204\nPatient: 17598bf36c7-fedcedc3-b78c-4688-82ef-622e0cc71b22\nPatient: 17598bf4a5d-185e291b-d0e3-42d3-9b70-eeae60debeec\nCondition: 17598bf36c8-5800bd67-4c08-4a68-8968-054c670ef2a6\nCondition: 17598bf36c8-7d2861ad-e607-4122-90b3-74265240aaca\nCondition: 17598bf36c9-d53628c0-8fc4-4570-bb9a-25af21328712\nCondition: 17598bf36c9-9dec87f6-1a92-4b8a-b02a-ad1ab3dabd30\nCondition: 17598bf36c9-5c6f054a-eb02-4eac-ae3e-f02d3472b15c\nCondition: 17598bf36c9-4fb95111-885e-421f-8a5b-a9942a759020\nCondition: 17598bf36c9-a8f8bb3d-c403-4fb9-8f18-5a8c0cbe2b78\nCondition: 17598bf36c9-b1f1fc40-ef31-49b5-8579-4a45cca657b2\nCondition: 17598bf4a5e-b9e99052-25a6-4400-a8b8-da48b8cbb22d\nCondition: 17598bf4a65-ee99ca87-65c3-4a14-900f-02e90ec4db4a\nCondition: 17598bf4a66-49d7afde-a7f1-42e4-858d-990f49a2f1ca\nCondition: 17598bf4a66-39d8080e-27ee-488d-9e35-59275a486457\nCondition: 17598bf4a6f-b87ac7b6-6faf-49b5-95fd-3eddf4f7494c\nCondition: 17598bf4a6f-ec9abd6f-ee59-4f71-8fa5-c737ac1be63b\nCondition: 17598bf4a70-b98f87d7-d469-4b3d-987e-02b78336b82e\nCondition: 17598bf4a70-6e7537b4-1a90-4a3c-842c-6c5c1db45ad3\nCondition: 17598bf4a70-ca048f40-02a3-4c24-a1b6-f53ffb3c1667\n"
]
],
[
[
"## Section 5: Putting it together",
"_____no_output_____"
]
],
[
[
"response = get(base + '/Condition' + '?' + 'code=http://snomed.info/sct|44054006' + '&_count=1')\nprint('Patients with Type II Diabetes: ' + str(response.json().get('total')))",
"Patients with Type II Diabetes: 1063\n"
],
[
"# SNOMED concepts for comorbidities of Type II Diabetes\n#coronary heart disease (CHD), 53741008\n#chronic kidney disease (CKD), 709044004\n#atrial fibrillation, 49436004\n#stroke, 230690007\n#hypertension, 38341003\n#heart failure, 84114007\n#peripheral vascular disease (PVD), 400047006\n#rheumatoid arthritis, 69896004\n#Malignant neoplasm, primary (morphologic abnormality), 86049000\n#Malignant neoplastic disease (disorder), 363346000\n#osteoporosis, 64859006\n#depression, 35489007\n#asthma, 195967001\n#chronic obstructive pulmonary disease (COPD), 13645005\n#dementia, 52448006\n#severe mental illness (SMI), 391193001\n#epilepsy, 84757009\n#hypothyroidism, 40930008\n#learning disability, 1855002\n\nprint('CHD: \\t\\t\\t' + str(get(base + '/Condition?_summary=count&code=http://snomed.info/sct|' + '53741008').json().get('total')))\nprint('CKD: \\t\\t\\t' + str(get(base + '/Condition?_summary=count&code=http://snomed.info/sct|' + '709044004').json().get('total')))\nprint('AFib: \\t\\t\\t' + str(get(base + '/Condition?_summary=count&code=http://snomed.info/sct|' + '49436004').json().get('total')))\nprint('stroke: \\t\\t' + str(get(base + '/Condition?_summary=count&code=http://snomed.info/sct|' + '230690007').json().get('total')))\nprint('hypertension: \\t\\t' + str(get(base + '/Condition?_summary=count&code=http://snomed.info/sct|' + '38341003').json().get('total')))\nprint('heart failure: \\t\\t' + str(get(base + '/Condition?_summary=count&code=http://snomed.info/sct|' + '84114007').json().get('total')))\nprint('PVD: \\t\\t\\t' + str(get(base + '/Condition?_summary=count&code=http://snomed.info/sct|' + '400047006').json().get('total')))\nprint('arthritis: \\t\\t' + str(get(base + '/Condition?_summary=count&code=http://snomed.info/sct|' + '69896004').json().get('total')))\nprint('cancer: \\t\\t' + str(get(base + '/Condition?_summary=count&code=http://snomed.info/sct|' + '86049000').json().get('total') + get(base + '/Condition?_summary=count&code=http://snomed.info/sct|' + '363346000').json().get('total')))\nprint('osteoporosis: \\t\\t' + str(get(base + '/Condition?_summary=count&code=http://snomed.info/sct|' + '64859006').json().get('total')))\nprint('depression: \\t\\t' + str(get(base + '/Condition?_summary=count&code=http://snomed.info/sct|' + '35489007').json().get('total')))\nprint('asthma: \\t\\t' + str(get(base + '/Condition?_summary=count&code=http://snomed.info/sct|' + '195967001').json().get('total')))\nprint('COPD: \\t\\t\\t' + str(get(base + '/Condition?_summary=count&code=http://snomed.info/sct|' + '13645005').json().get('total')))\nprint('dementia: \\t\\t' + str(get(base + '/Condition?_summary=count&code=http://snomed.info/sct|' + '52448006').json().get('total')))\nprint('SMI: \\t\\t\\t' + str(get(base + '/Condition?_summary=count&code=http://snomed.info/sct|' + '391193001').json().get('total')))\nprint('epilepsy: \\t\\t' + str(get(base + '/Condition?_summary=count&code=http://snomed.info/sct|' + '84757009').json().get('total')))\nprint('hypothyroidism: \\t' + str(get(base + '/Condition?_summary=count&code=http://snomed.info/sct|' + '40930008').json().get('total')))\nprint('learning disability: \\t' + str(get(base + '/Condition?_summary=count&code=http://snomed.info/sct|' + '1855002').json().get('total')))",
"CHD: \t\t\t1059\nCKD: \t\t\t0\nAFib: \t\t\t359\nstroke: \t\t1008\nhypertension: \t\t0\nheart failure: \t\t84\nPVD: \t\t\t0\narthritis: \t\t48\ncancer: \t\t0\nosteoporosis: \t\t762\ndepression: \t\t0\nasthma: \t\t24\nCOPD: \t\t\t0\ndementia: \t\t0\nSMI: \t\t\t0\nepilepsy: \t\t546\nhypothyroidism: \t0\nlearning disability: \t0\n"
],
[
"# Patients with Type II Diabetes *and* comorbidities\nhasDiabetes = base + '/Patient?_elements=id&_has:Condition:patient:code=http://snomed.info/sct|44054006'\n\ndef printPatientsWithComorbidity(conceptId):\n responseJSON = get(hasDiabetes + '&_has:Condition:patient:code=http://snomed.info/sct|' + conceptId).json()\n print('Total: ' + str(responseJSON.get('total')))\n if 'entry' in responseJSON:\n for entry in responseJSON.get('entry'):\n print(entry.get('resource').get('id'), end=\", \")\n print('\\n')\n\nprint('CHD:')\nprintPatientsWithComorbidity('53741008')\n\nprint('AFib:')\nprintPatientsWithComorbidity('49436004')\n\nprint('stroke:')\nprintPatientsWithComorbidity('230690007')\n\nprint('heart failure:')\nprintPatientsWithComorbidity('84114007')\n\nprint('arthritis:')\nprintPatientsWithComorbidity('69896004')\n\nprint('osteoporosis:')\nprintPatientsWithComorbidity('64859006')\n\nprint('asthma:')\nprintPatientsWithComorbidity('195967001')\n\nprint('epilepsy:')\nprintPatientsWithComorbidity('84757009')",
"CHD:\nTotal: 30\n1759a06f11a-77b7ee76-ae8d-47a8-9a8e-17e7278e4137, 1759bccd5dc-a4192660-b224-4d88-acf6-bfb538fc0052, 1759c042626-da786c63-fcd4-4a86-aaec-54ec28458861, 1759c7179ab-cdc927fb-ec72-4c10-961e-a424bb8241f3, 1759c906bce-6fcc151d-240e-441f-aa3f-3a8123222d0c, 1759c9d0e32-10946dda-2ac9-4f8e-a6ba-eade9aba6ac8, 175b90993dc-7568b0d3-91ce-4862-be00-7cb99389f323, 175ba73ffc5-86182577-c52f-4c24-b09c-acfdc0043b8c, 175babfca99-31bcaafc-876a-453a-905c-b0482607b2c5, 175bb745e4f-1f3f83a8-6f6c-43da-adf1-fdc5440d88b5, \n\nAFib:\nTotal: 23\n1759b62a9bc-650fc722-8bb1-4a81-827c-95b73a83d7b4, 1759be696c1-fd6cfa13-8e69-454f-ad73-d3b27a051f6f, 1759c1d61ec-500b2890-fcc9-428c-86c2-bcb15a5cbaa5, 1759c4dfa60-d50fbfcb-dda0-4669-82c8-42e73c5bb239, 1759c76bdcd-dfc226a9-37b6-4a72-b303-1613ed7ec838, 175b9f4c2a0-e971ee19-f55e-4319-85bd-57737b23ba26, 175ba948672-bc9ba458-81df-4def-8064-da02406e9f62, 175ba9518ee-29c6291a-ae29-4c62-8283-6c5a1264c404, 175ba9ca813-0a7f0565-f701-4c66-9d11-7b2754dddf6d, 175baa492a2-c7306451-8ede-4d55-9a21-2da3932f036c, \n\nstroke:\nTotal: 36\n175998f05f8-29eebaa9-2179-4d7b-9603-ca9c7cf25e23, 1759b62a9bc-650fc722-8bb1-4a81-827c-95b73a83d7b4, 1759b7179b6-d3d28532-15b8-41db-8781-fbde5c781fab, 1759b91f0bf-5a8bf1c3-7aa4-4d8b-a4d3-83d5097f18c4, 1759bcaf1a7-188d7217-1e1d-4664-bc7a-e07bc658539d, 1759c048c78-1e94db2f-f936-4a12-b427-a89667db2ee8, 1759c363589-398bc35f-8c6c-41f7-8840-572e653a30e5, 1759c3a8255-0131fdfe-0db6-47e3-9cb9-d770efee0012, 1759c4dfa60-d50fbfcb-dda0-4669-82c8-42e73c5bb239, 1759c51e871-214856d2-a5be-47ca-99a7-e9b43b21dc26, \n\nheart failure:\nTotal: 5\n1759b62a9bc-650fc722-8bb1-4a81-827c-95b73a83d7b4, 175b9f4c2a0-e971ee19-f55e-4319-85bd-57737b23ba26, 175c0fd9b65-022a8b08-76b1-481e-bef9-82866c621bd9, 175c1151cca-345c1f27-af3e-403f-8aad-42be1a128b73, 175c2e6aa49-7a8d5bae-e376-41fc-8d51-659148290cbe, \n\narthritis:\nTotal: 0\n\n\nosteoporosis:\nTotal: 25\n175998be983-6278fae0-a059-467f-8637-3cbff69d9b4e, 1759b7afa3c-e89ecf98-c0b2-4e69-866b-ef6e89f6fba0, 1759bfa2d15-72ddae5b-292a-40f5-8558-8c062211dd42, 1759c0c9587-ab5bdbf5-56e3-4328-b347-089d17ea59b8, 1759c14d16a-fa7ed5df-d034-4b8c-bc74-296cc4b32c31, 1759c51e871-214856d2-a5be-47ca-99a7-e9b43b21dc26, 1759c64e1fd-de32b308-29ab-4a04-8850-564e574b20fd, 1759c685bbc-bff3331b-d71e-4987-8246-657b653a77c2, 175b98dc155-70c909ff-7125-414d-beff-ff17bd202c40, 175ba10c839-3767563a-d7f3-4dbd-88a4-cf54a587d310, \n\nasthma:\nTotal: 1\n175c2b7c38a-61ab893b-7b40-45ae-9955-6f26107de9cc, \n\nepilepsy:\nTotal: 8\n1759ba18cd9-617df281-8a07-4a25-919d-d320d53f4da2, 1759c181967-bd8686d0-bcf5-475c-932d-e41f1f3769bc, 175ba3d7afe-c2a50287-ebb2-48b0-90f8-3654e28244c1, 175bae212ec-e15e067c-7a7a-4d60-9635-213cdfcae928, 175bae68708-0423d3ed-55d0-4f64-ac98-717649009b04, 175c0c66c0a-f500462c-e568-47ac-ad35-045a11eb8b8f, 175c15e0a00-c2dcdc18-a2f6-4cd1-b9f4-e78a940e8064, 175c2ac659d-cc743967-f254-43bb-b345-17a5282088fe, \n\n"
]
],
[
[
"## Section 6: Bulk export",
"_____no_output_____"
]
],
[
[
"# To perform deeper analysis of the data, it can be useful to export some or all of the data into \"bulk fhir\" format\nexport_response = get(base + '/$export' + '?' + '_type=Patient,Condition')\nprint('Response code: ' + str(export_response.status_code))\nprint(export_response.headers)",
"Response code: 202\n{'Date': 'Wed, 05 May 2021 18:12:57 GMT', 'Content-Length': '0', 'Connection': 'keep-alive', 'Content-Location': 'https://cluster1-573846-250babbbe4c3000e15508cd07c1d282b-0000.us-east.containers.appdomain.cloud/open/$bulkdata-status?job=060hzfxJyNUqyFck7t7tpg', 'Content-Language': 'en-US', 'Strict-Transport-Security': 'max-age=86400; includeSubDomains'}\n"
],
[
"import time\n\n# poll the status endpoint (returned in the Content-Location header of the $export response)\nstatus_response = get(export_response.headers['Content-Location'])\nprint('Response code: ' + str(status_response.status_code))\n\nwhile(status_response.status_code != 200):\n time.sleep(20)\n status_response = get(export_response.headers['Content-Location'])\n print('Response code: ' + str(status_response.status_code))\n \nprint('Response body: ' + str(status_response.text))",
"Response code: 202\nResponse code: 200\nResponse body: \n{\n \"transactionTime\": \"2021-05-05T18:13:26.251Z\",\n \"request\": \"https://cluster1-573846-250babbbe4c3000e15508cd07c1d282b-0000.us-east.containers.appdomain.cloud/open/$export?_type=Patient,Condition\",\n \"requiresAccessToken\": false,\n \"output\": [\n {\n \"type\": \"Patient\",\n \"url\": \"https://s3.us-east.cloud-object-storage.appdomain.cloud/fhir-export-2fbaaea5-68b5-4775-8a40-c1eb3c4f12d5/rjEjBkGMmlfuzFJjtMOk6Z2eF-GMLPaFXll9lxVLaPE/Patient_1.ndjson?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=972a2cff12b94328b3f020c1a8e14e9b%2F20210505%2Fus-east%2Fs3%2Faws4_request&X-Amz-Date=20210505T181328Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=a2528b4d1647ce8bfa1369a9843983f423962368487f2eb1e35d2497a16b8571\",\n \"count\": 32655\n },\n {\n \"type\": \"Condition\",\n \"url\": \"https://s3.us-east.cloud-object-storage.appdomain.cloud/fhir-export-2fbaaea5-68b5-4775-8a40-c1eb3c4f12d5/rjEjBkGMmlfuzFJjtMOk6Z2eF-GMLPaFXll9lxVLaPE/Condition_1.ndjson?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=972a2cff12b94328b3f020c1a8e14e9b%2F20210505%2Fus-east%2Fs3%2Faws4_request&X-Amz-Date=20210505T181328Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=3d56444e07212c39008fbe8399d26abeeb839176d3a7208b57314b1f3d55e7a8\",\n \"count\": 197224\n },\n {\n \"type\": \"Condition\",\n \"url\": \"https://s3.us-east.cloud-object-storage.appdomain.cloud/fhir-export-2fbaaea5-68b5-4775-8a40-c1eb3c4f12d5/rjEjBkGMmlfuzFJjtMOk6Z2eF-GMLPaFXll9lxVLaPE/Condition_2.ndjson?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=972a2cff12b94328b3f020c1a8e14e9b%2F20210505%2Fus-east%2Fs3%2Faws4_request&X-Amz-Date=20210505T181328Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=2bef855c1ace93d533f694df588bb45a5b66531ee225502cb1acc90a55712283\",\n \"count\": 163153\n }\n ]\n}\n"
],
[
"# retrieve one of the NDJSON files and view the first 25 rows\nndjson = get(status_response.json().get('output')[1].get('url'))\npeek(ndjson.text)",
"{\"resourceType\":\"Condition\",\"id\":\"17598c3c90d-be7a5be7-3d07-432d-ab17-44e4785e1585\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2020-11-05T14:16:11.388Z\",\"profile\":[\"http://hl7.org/fhir/us/core/StructureDefinition/us-core-condition\"]},\"clinicalStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-clinical\",\"code\":\"resolved\"}]},\"verificationStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-ver-status\",\"code\":\"confirmed\"}]},\"category\":[{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-category\",\"code\":\"encounter-diagnosis\",\"display\":\"Encounter Diagnosis\"}]}],\"code\":{\"coding\":[{\"system\":\"http://snomed.info/sct\",\"code\":\"195662009\",\"display\":\"Acute viral pharyngitis (disorder)\"}],\"text\":\"Acute viral pharyngitis (disorder)\"},\"subject\":{\"reference\":\"Patient/17598c3c90c-87fd6c16-1180-41de-b33d-311b3ad6a30e\"},\"encounter\":{\"reference\":\"Encounter/17598c3c90d-d38b9c07-78d7-4717-bc47-c52ae6d194e2\"},\"onsetDateTime\":\"1951-03-26T08:03:26-05:00\",\"abatementDateTime\":\"1951-04-06T08:03:26-05:00\",\"recordedDate\":\"1951-03-26T08:03:26-05:00\"}\n{\"resourceType\":\"Condition\",\"id\":\"17598c8856f-08420a2b-4523-486e-b20b-fc6717ceb258\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2020-11-05T14:21:24.736Z\",\"profile\":[\"http://hl7.org/fhir/us/core/StructureDefinition/us-core-condition\"]},\"clinicalStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-clinical\",\"code\":\"resolved\"}]},\"verificationStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-ver-status\",\"code\":\"confirmed\"}]},\"category\":[{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-category\",\"code\":\"encounter-diagnosis\",\"display\":\"Encounter Diagnosis\"}]}],\"code\":{\"coding\":[{\"system\":\"http://snomed.info/sct\",\"code\":\"840539006\",\"display\":\"COVID-19\"}],\"text\":\"COVID-19\"},\"subject\":{\"reference\":\"Patient/17598c8856e-b131763b-baa1-4b54-a75a-1049081e1434\"},\"encounter\":{\"reference\":\"Encounter/17598c8856f-b09dd0a9-0a0d-436e-8cc1-ff44007baede\"},\"onsetDateTime\":\"2020-03-05T07:59:39-05:00\",\"abatementDateTime\":\"2020-03-28T08:59:39-04:00\",\"recordedDate\":\"2020-03-05T07:59:39-05:00\"}\n{\"resourceType\":\"Condition\",\"id\":\"17598cdb804-4c4b158b-7174-4632-859c-da81333f8a4d\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2020-11-05T14:27:06.441Z\",\"profile\":[\"http://hl7.org/fhir/us/core/StructureDefinition/us-core-condition\"]},\"clinicalStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-clinical\",\"code\":\"resolved\"}]},\"verificationStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-ver-status\",\"code\":\"confirmed\"}]},\"category\":[{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-category\",\"code\":\"encounter-diagnosis\",\"display\":\"Encounter Diagnosis\"}]}],\"code\":{\"coding\":[{\"system\":\"http://snomed.info/sct\",\"code\":\"840539006\",\"display\":\"COVID-19\"}],\"text\":\"COVID-19\"},\"subject\":{\"reference\":\"Patient/17598cdb803-9d55c785-bf19-4e93-b229-f52e4d8fd6d3\"},\"encounter\":{\"reference\":\"Encounter/17598cdb804-c1ed7712-04f7-45c0-98cd-ee1c54451135\"},\"onsetDateTime\":\"2020-03-06T12:40:48-05:00\",\"abatementDateTime\":\"2020-03-31T13:40:48-04:00\",\"recordedDate\":\"2020-03-06T12:40:48-05:00\"}\n{\"resourceType\":\"Condition\",\"id\":\"17598d2fafe-4d345524-8d51-427f-9ef3-1ac9205a829f\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2020-11-05T14:32:50.139Z\",\"profile\":[\"http://hl7.org/fhir/us/core/StructureDefinition/us-core-condition\"]},\"clinicalStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-clinical\",\"code\":\"resolved\"}]},\"verificationStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-ver-status\",\"code\":\"confirmed\"}]},\"category\":[{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-category\",\"code\":\"encounter-diagnosis\",\"display\":\"Encounter Diagnosis\"}]}],\"code\":{\"coding\":[{\"system\":\"http://snomed.info/sct\",\"code\":\"195662009\",\"display\":\"Acute viral pharyngitis (disorder)\"}],\"text\":\"Acute viral pharyngitis (disorder)\"},\"subject\":{\"reference\":\"Patient/17598d2fafd-5a9c2126-832d-46d5-a3e4-903a531bbbd3\"},\"encounter\":{\"reference\":\"Encounter/17598d2fafe-a6929b08-2ef1-43f5-b00f-aef93d27a4f6\"},\"onsetDateTime\":\"2018-10-13T12:55:51-04:00\",\"abatementDateTime\":\"2018-10-22T12:55:51-04:00\",\"recordedDate\":\"2018-10-13T12:55:51-04:00\"}\n{\"resourceType\":\"Condition\",\"id\":\"17598d828df-6073b4a4-df68-4809-a2bc-61829b0d770b\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2020-11-05T14:38:28.786Z\",\"profile\":[\"http://hl7.org/fhir/us/core/StructureDefinition/us-core-condition\"]},\"clinicalStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-clinical\",\"code\":\"resolved\"}]},\"verificationStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-ver-status\",\"code\":\"confirmed\"}]},\"category\":[{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-category\",\"code\":\"encounter-diagnosis\",\"display\":\"Encounter Diagnosis\"}]}],\"code\":{\"coding\":[{\"system\":\"http://snomed.info/sct\",\"code\":\"195662009\",\"display\":\"Acute viral pharyngitis (disorder)\"}],\"text\":\"Acute viral pharyngitis (disorder)\"},\"subject\":{\"reference\":\"Patient/17598d828df-00fc7ed6-25a1-40e1-8f1c-b6644ef165c6\"},\"encounter\":{\"reference\":\"Encounter/17598d828df-5a439b3f-9261-4958-bfd2-b71f5936b71f\"},\"onsetDateTime\":\"2012-12-01T21:56:21-05:00\",\"abatementDateTime\":\"2012-12-08T21:56:21-05:00\",\"recordedDate\":\"2012-12-01T21:56:21-05:00\"}\n{\"resourceType\":\"Condition\",\"id\":\"17598dcae2d-573c3fda-94ef-4570-bcd3-9248458ef17a\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2020-11-05T14:43:20.847Z\",\"profile\":[\"http://hl7.org/fhir/us/core/StructureDefinition/us-core-condition\"]},\"clinicalStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-clinical\",\"code\":\"active\"}]},\"verificationStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-ver-status\",\"code\":\"confirmed\"}]},\"category\":[{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-category\",\"code\":\"encounter-diagnosis\",\"display\":\"Encounter Diagnosis\"}]}],\"code\":{\"coding\":[{\"system\":\"http://snomed.info/sct\",\"code\":\"162864005\",\"display\":\"Body mass index 30+ - obesity (finding)\"}],\"text\":\"Body mass index 30+ - obesity (finding)\"},\"subject\":{\"reference\":\"Patient/17598dcae2d-72f9a40f-6691-401f-ab24-2b3ce7b85f53\"},\"encounter\":{\"reference\":\"Encounter/17598dcae2d-fd5770f1-52c1-4794-8fb4-df10eaffd98f\"},\"onsetDateTime\":\"1983-04-28T12:27:45-04:00\",\"recordedDate\":\"1983-04-28T12:27:45-04:00\"}\n{\"resourceType\":\"Condition\",\"id\":\"17598e1b968-37f7e6b9-dd60-455d-8112-145e0f9113f7\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2020-11-05T14:48:53.012Z\",\"profile\":[\"http://hl7.org/fhir/us/core/StructureDefinition/us-core-condition\"]},\"clinicalStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-clinical\",\"code\":\"active\"}]},\"verificationStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-ver-status\",\"code\":\"confirmed\"}]},\"category\":[{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-category\",\"code\":\"encounter-diagnosis\",\"display\":\"Encounter Diagnosis\"}]}],\"code\":{\"coding\":[{\"system\":\"http://snomed.info/sct\",\"code\":\"74400008\",\"display\":\"Appendicitis\"}],\"text\":\"Appendicitis\"},\"subject\":{\"reference\":\"Patient/17598e1b967-a99859d6-5212-40f2-8e5a-748333f05e76\"},\"encounter\":{\"reference\":\"Encounter/17598e1b968-1f029e87-0c49-4111-b0f4-d38a51ddfcd7\"},\"onsetDateTime\":\"2009-10-11T06:02:22-04:00\",\"recordedDate\":\"2009-10-11T06:02:22-04:00\"}\n{\"resourceType\":\"Condition\",\"id\":\"17598e6e218-364170ba-7a8d-48a0-b702-34a16bae3f7c\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2020-11-05T14:54:29.445Z\",\"profile\":[\"http://hl7.org/fhir/us/core/StructureDefinition/us-core-condition\"]},\"clinicalStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-clinical\",\"code\":\"resolved\"}]},\"verificationStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-ver-status\",\"code\":\"confirmed\"}]},\"category\":[{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-category\",\"code\":\"encounter-diagnosis\",\"display\":\"Encounter Diagnosis\"}]}],\"code\":{\"coding\":[{\"system\":\"http://snomed.info/sct\",\"code\":\"65363002\",\"display\":\"Otitis media\"}],\"text\":\"Otitis media\"},\"subject\":{\"reference\":\"Patient/17598e6e218-b0bcd073-6828-4898-8ac1-ea067dd92834\"},\"encounter\":{\"reference\":\"Encounter/17598e6e218-6287caf6-4283-4d9f-8338-193fc8f551dc\"},\"onsetDateTime\":\"1988-01-28T13:23:32-05:00\",\"abatementDateTime\":\"1988-04-10T14:23:32-04:00\",\"recordedDate\":\"1988-01-28T13:23:32-05:00\"}\n{\"resourceType\":\"Condition\",\"id\":\"17598ed0c86-89a32650-85a8-4faa-9cb6-f4529b329344\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2020-11-05T15:01:24.217Z\",\"profile\":[\"http://hl7.org/fhir/us/core/StructureDefinition/us-core-condition\"]},\"clinicalStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-clinical\",\"code\":\"resolved\"}]},\"verificationStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-ver-status\",\"code\":\"confirmed\"}]},\"category\":[{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-category\",\"code\":\"encounter-diagnosis\",\"display\":\"Encounter Diagnosis\"}]}],\"code\":{\"coding\":[{\"system\":\"http://snomed.info/sct\",\"code\":\"840539006\",\"display\":\"COVID-19\"}],\"text\":\"COVID-19\"},\"subject\":{\"reference\":\"Patient/17598ed0c82-2a197bfe-9015-4db9-9029-c4f809f01899\"},\"encounter\":{\"reference\":\"Encounter/17598ed0c86-a66f9796-8979-4617-bb12-514837094c76\"},\"onsetDateTime\":\"2020-03-06T05:05:16-05:00\",\"abatementDateTime\":\"2020-03-26T06:05:16-04:00\",\"recordedDate\":\"2020-03-06T05:05:16-05:00\"}\n{\"resourceType\":\"Condition\",\"id\":\"17598f2b750-1f6ce5b8-8f9e-4d0f-8611-8b7a0b4024f1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2020-11-05T15:07:27.543Z\",\"profile\":[\"http://hl7.org/fhir/us/core/StructureDefinition/us-core-condition\"]},\"clinicalStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-clinical\",\"code\":\"resolved\"}]},\"verificationStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-ver-status\",\"code\":\"confirmed\"}]},\"category\":[{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-category\",\"code\":\"encounter-diagnosis\",\"display\":\"Encounter Diagnosis\"}]}],\"code\":{\"coding\":[{\"system\":\"http://snomed.info/sct\",\"code\":\"68962001\",\"display\":\"Muscle pain (finding)\"}],\"text\":\"Muscle pain (finding)\"},\"subject\":{\"reference\":\"Patient/17598f2b750-8c870b72-2dad-43a0-9cdc-7f9c3d82bde3\"},\"encounter\":{\"reference\":\"Encounter/17598f2b750-d32c0f70-45a5-4f38-a1fa-adb14397f0a3\"},\"onsetDateTime\":\"2020-03-09T03:19:02-04:00\",\"abatementDateTime\":\"2020-04-02T04:55:02-04:00\",\"recordedDate\":\"2020-03-09T03:19:02-04:00\"}\n{\"resourceType\":\"Condition\",\"id\":\"17598f7ae74-21b8d06f-86ad-4af3-bf5b-7a73bfa4a422\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2020-11-05T15:12:50.658Z\",\"profile\":[\"http://hl7.org/fhir/us/core/StructureDefinition/us-core-condition\"]},\"clinicalStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-clinical\",\"code\":\"active\"}]},\"verificationStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-ver-status\",\"code\":\"confirmed\"}]},\"category\":[{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-category\",\"code\":\"encounter-diagnosis\",\"display\":\"Encounter Diagnosis\"}]}],\"code\":{\"coding\":[{\"system\":\"http://snomed.info/sct\",\"code\":\"271737000\",\"display\":\"Anemia (disorder)\"}],\"text\":\"Anemia (disorder)\"},\"subject\":{\"reference\":\"Patient/17598f7ae74-a024b31f-d642-41db-bbac-f8d83c8a83ed\"},\"encounter\":{\"reference\":\"Encounter/17598f7ae74-326ddddd-183a-441d-b92c-858fdb377981\"},\"onsetDateTime\":\"2012-12-09T07:09:58-05:00\",\"recordedDate\":\"2012-12-09T07:09:58-05:00\"}\n{\"resourceType\":\"Condition\",\"id\":\"17598fcf5d5-5a728336-0ad6-4f9e-84ca-c2b988fb31f2\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2020-11-05T15:18:39.352Z\",\"profile\":[\"http://hl7.org/fhir/us/core/StructureDefinition/us-core-condition\"]},\"clinicalStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-clinical\",\"code\":\"resolved\"}]},\"verificationStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-ver-status\",\"code\":\"confirmed\"}]},\"category\":[{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-category\",\"code\":\"encounter-diagnosis\",\"display\":\"Encounter Diagnosis\"}]}],\"code\":{\"coding\":[{\"system\":\"http://snomed.info/sct\",\"code\":\"840539006\",\"display\":\"COVID-19\"}],\"text\":\"COVID-19\"},\"subject\":{\"reference\":\"Patient/17598fcf5d5-a7329c52-b2cf-463c-8a5d-a538219a8242\"},\"encounter\":{\"reference\":\"Encounter/17598fcf5d5-d69f9ba6-21da-461f-a8df-637a4d94df85\"},\"onsetDateTime\":\"2020-03-04T11:29:37-05:00\",\"abatementDateTime\":\"2020-03-19T12:29:37-04:00\",\"recordedDate\":\"2020-03-04T11:29:37-05:00\"}\n{\"resourceType\":\"Condition\",\"id\":\"1759902fd82-e10349c2-8907-4d77-a3bb-9e1e012438ad\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2020-11-05T15:25:19.935Z\",\"profile\":[\"http://hl7.org/fhir/us/core/StructureDefinition/us-core-condition\"]},\"clinicalStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-clinical\",\"code\":\"active\"}]},\"verificationStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-ver-status\",\"code\":\"confirmed\"}]},\"category\":[{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-category\",\"code\":\"encounter-diagnosis\",\"display\":\"Encounter Diagnosis\"}]}],\"code\":{\"coding\":[{\"system\":\"http://snomed.info/sct\",\"code\":\"40055000\",\"display\":\"Chronic sinusitis (disorder)\"}],\"text\":\"Chronic sinusitis (disorder)\"},\"subject\":{\"reference\":\"Patient/1759902fd81-42de7379-6a7c-4164-aa24-1da68e686fae\"},\"encounter\":{\"reference\":\"Encounter/1759902fd82-8da1d566-5b7b-4b67-8008-2ed4b7ca5e0b\"},\"onsetDateTime\":\"2018-08-31T11:47:18-04:00\",\"recordedDate\":\"2018-08-31T11:47:18-04:00\"}\n{\"resourceType\":\"Condition\",\"id\":\"1759908a4c7-31c67178-f894-48fb-8df1-86e4cfc948ee\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2020-11-05T15:31:28.498Z\",\"profile\":[\"http://hl7.org/fhir/us/core/StructureDefinition/us-core-condition\"]},\"clinicalStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-clinical\",\"code\":\"resolved\"}]},\"verificationStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-ver-status\",\"code\":\"confirmed\"}]},\"category\":[{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-category\",\"code\":\"encounter-diagnosis\",\"display\":\"Encounter Diagnosis\"}]}],\"code\":{\"coding\":[{\"system\":\"http://snomed.info/sct\",\"code\":\"386661006\",\"display\":\"Fever (finding)\"}],\"text\":\"Fever (finding)\"},\"subject\":{\"reference\":\"Patient/1759908a4c6-523cb823-eb3b-4813-9c6f-f02a33431345\"},\"encounter\":{\"reference\":\"Encounter/1759908a4c7-5437831b-5e59-4c9f-b4ff-f6e3c8c34718\"},\"onsetDateTime\":\"2020-03-17T14:20:52-04:00\",\"abatementDateTime\":\"2020-04-14T15:09:52-04:00\",\"recordedDate\":\"2020-03-17T14:20:52-04:00\"}\n{\"resourceType\":\"Condition\",\"id\":\"175990d829f-ed8eb8d8-9064-4e02-9e7b-6140cb2a6c28\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2020-11-05T15:36:48.155Z\",\"profile\":[\"http://hl7.org/fhir/us/core/StructureDefinition/us-core-condition\"]},\"clinicalStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-clinical\",\"code\":\"active\"}]},\"verificationStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-ver-status\",\"code\":\"confirmed\"}]},\"category\":[{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-category\",\"code\":\"encounter-diagnosis\",\"display\":\"Encounter Diagnosis\"}]}],\"code\":{\"coding\":[{\"system\":\"http://snomed.info/sct\",\"code\":\"232353008\",\"display\":\"Perennial allergic rhinitis with seasonal variation\"}],\"text\":\"Perennial allergic rhinitis with seasonal variation\"},\"subject\":{\"reference\":\"Patient/175990d829e-f0ebd8b5-329e-4e71-a4d8-fd30c6b91482\"},\"encounter\":{\"reference\":\"Encounter/175990d829f-aaed0d3e-e42b-4b31-94fd-53326c6b392a\"},\"onsetDateTime\":\"2016-12-03T23:57:50-05:00\",\"recordedDate\":\"2016-12-03T23:57:50-05:00\"}\n{\"resourceType\":\"Condition\",\"id\":\"17599160f37-17c00e92-d82c-4f93-b090-87289ba586e1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2020-11-05T15:46:01.202Z\",\"profile\":[\"http://hl7.org/fhir/us/core/StructureDefinition/us-core-condition\"]},\"clinicalStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-clinical\",\"code\":\"active\"}]},\"verificationStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-ver-status\",\"code\":\"confirmed\"}]},\"category\":[{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-category\",\"code\":\"encounter-diagnosis\",\"display\":\"Encounter Diagnosis\"}]}],\"code\":{\"coding\":[{\"system\":\"http://snomed.info/sct\",\"code\":\"703151001\",\"display\":\"History of single seizure (situation)\"}],\"text\":\"History of single seizure (situation)\"},\"subject\":{\"reference\":\"Patient/17599160f37-29744fc6-fdec-4e9b-bf6c-5b152a53e7e7\"},\"encounter\":{\"reference\":\"Encounter/17599160f37-114c118d-5dbc-4211-bcd0-5e50f76ca4e7\"},\"onsetDateTime\":\"1975-09-15T20:09:41-04:00\",\"recordedDate\":\"1975-09-15T20:09:41-04:00\"}\n{\"resourceType\":\"Condition\",\"id\":\"175991b6b46-c48bcf86-9b6f-4c7a-926c-9a705ca6ae8a\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2020-11-05T15:51:53.824Z\",\"profile\":[\"http://hl7.org/fhir/us/core/StructureDefinition/us-core-condition\"]},\"clinicalStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-clinical\",\"code\":\"active\"}]},\"verificationStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-ver-status\",\"code\":\"confirmed\"}]},\"category\":[{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-category\",\"code\":\"encounter-diagnosis\",\"display\":\"Encounter Diagnosis\"}]}],\"code\":{\"coding\":[{\"system\":\"http://snomed.info/sct\",\"code\":\"162864005\",\"display\":\"Body mass index 30+ - obesity (finding)\"}],\"text\":\"Body mass index 30+ - obesity (finding)\"},\"subject\":{\"reference\":\"Patient/175991b6b46-a81892b3-6edf-4fce-820a-398d6a3fc19d\"},\"encounter\":{\"reference\":\"Encounter/175991b6b46-fd05fdb9-b3f6-4631-99e7-a8f78eeead1e\"},\"onsetDateTime\":\"2014-11-18T21:31:23-05:00\",\"recordedDate\":\"2014-11-18T21:31:23-05:00\"}\n{\"resourceType\":\"Condition\",\"id\":\"1759920c9c2-9bb9cc62-9cc6-4de0-bbae-50bd3e08eb1e\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2020-11-05T15:57:47.558Z\",\"profile\":[\"http://hl7.org/fhir/us/core/StructureDefinition/us-core-condition\"]},\"clinicalStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-clinical\",\"code\":\"active\"}]},\"verificationStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-ver-status\",\"code\":\"confirmed\"}]},\"category\":[{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-category\",\"code\":\"encounter-diagnosis\",\"display\":\"Encounter Diagnosis\"}]}],\"code\":{\"coding\":[{\"system\":\"http://snomed.info/sct\",\"code\":\"429007001\",\"display\":\"History of cardiac arrest (situation)\"}],\"text\":\"History of cardiac arrest (situation)\"},\"subject\":{\"reference\":\"Patient/1759920c9c2-5e1f4581-6ffc-4f37-87cb-7993746f458d\"},\"encounter\":{\"reference\":\"Encounter/1759920c9c2-9fc2e706-f067-4ee9-8508-0d21ab55baef\"},\"onsetDateTime\":\"2014-07-10T01:27:35-04:00\",\"recordedDate\":\"2014-07-10T01:27:35-04:00\"}\n{\"resourceType\":\"Condition\",\"id\":\"1759925ccc0-9c57a4a7-afeb-4921-aa48-004861296c0f\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2020-11-05T16:03:20.869Z\",\"profile\":[\"http://hl7.org/fhir/us/core/StructureDefinition/us-core-condition\"]},\"clinicalStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-clinical\",\"code\":\"resolved\"}]},\"verificationStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-ver-status\",\"code\":\"confirmed\"}]},\"category\":[{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-category\",\"code\":\"encounter-diagnosis\",\"display\":\"Encounter Diagnosis\"}]}],\"code\":{\"coding\":[{\"system\":\"http://snomed.info/sct\",\"code\":\"444814009\",\"display\":\"Viral sinusitis (disorder)\"}],\"text\":\"Viral sinusitis (disorder)\"},\"subject\":{\"reference\":\"Patient/1759925ccbf-6adbc8f2-0ee8-4bd3-b57a-9bc4dcf55ee8\"},\"encounter\":{\"reference\":\"Encounter/1759925ccc0-02d7382f-c6d3-4e21-8dfe-7c6627b0b3a6\"},\"onsetDateTime\":\"2017-12-09T23:35:59-05:00\",\"abatementDateTime\":\"2017-12-23T23:35:59-05:00\",\"recordedDate\":\"2017-12-09T23:35:59-05:00\"}\n{\"resourceType\":\"Condition\",\"id\":\"175992c73bf-ee56bd69-92a1-4490-91f0-e3d8fcc07cd9\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2020-11-05T16:10:33.461Z\",\"profile\":[\"http://hl7.org/fhir/us/core/StructureDefinition/us-core-condition\"]},\"clinicalStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-clinical\",\"code\":\"resolved\"}]},\"verificationStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-ver-status\",\"code\":\"confirmed\"}]},\"category\":[{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-category\",\"code\":\"encounter-diagnosis\",\"display\":\"Encounter Diagnosis\"}]}],\"code\":{\"coding\":[{\"system\":\"http://snomed.info/sct\",\"code\":\"386661006\",\"display\":\"Fever (finding)\"}],\"text\":\"Fever (finding)\"},\"subject\":{\"reference\":\"Patient/175992c73be-5fb46052-093a-44d1-ad04-55f0488d4390\"},\"encounter\":{\"reference\":\"Encounter/175992c73bf-ffd404eb-197d-4791-bb85-e90ae6be0e64\"},\"onsetDateTime\":\"2020-03-06T06:55:23-05:00\",\"abatementDateTime\":\"2020-03-28T09:12:23-04:00\",\"recordedDate\":\"2020-03-06T06:55:23-05:00\"}\n{\"resourceType\":\"Condition\",\"id\":\"17599325f8f-ecb82619-ba37-420d-b5ce-257dbce2177d\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2020-11-05T16:16:59.868Z\",\"profile\":[\"http://hl7.org/fhir/us/core/StructureDefinition/us-core-condition\"]},\"clinicalStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-clinical\",\"code\":\"resolved\"}]},\"verificationStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-ver-status\",\"code\":\"confirmed\"}]},\"category\":[{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-category\",\"code\":\"encounter-diagnosis\",\"display\":\"Encounter Diagnosis\"}]}],\"code\":{\"coding\":[{\"system\":\"http://snomed.info/sct\",\"code\":\"36955009\",\"display\":\"Loss of taste (finding)\"}],\"text\":\"Loss of taste (finding)\"},\"subject\":{\"reference\":\"Patient/17599325f8f-2eb4384f-bbb4-4f88-80fa-e478d2d4b116\"},\"encounter\":{\"reference\":\"Encounter/17599325f8f-cd773def-fb3e-4460-835f-e63d528d7327\"},\"onsetDateTime\":\"2020-03-09T00:41:00-04:00\",\"abatementDateTime\":\"2020-04-14T02:06:00-04:00\",\"recordedDate\":\"2020-03-09T00:41:00-04:00\"}\n{\"resourceType\":\"Condition\",\"id\":\"175993848db-f26f11f8-855f-4c23-941c-23eef2f3e6cf\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2020-11-05T16:23:35.161Z\",\"profile\":[\"http://hl7.org/fhir/us/core/StructureDefinition/us-core-condition\"]},\"clinicalStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-clinical\",\"code\":\"active\"}]},\"verificationStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-ver-status\",\"code\":\"confirmed\"}]},\"category\":[{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-category\",\"code\":\"encounter-diagnosis\",\"display\":\"Encounter Diagnosis\"}]}],\"code\":{\"coding\":[{\"system\":\"http://snomed.info/sct\",\"code\":\"36955009\",\"display\":\"Loss of taste (finding)\"}],\"text\":\"Loss of taste (finding)\"},\"subject\":{\"reference\":\"Patient/175993848d9-90779ddf-a0c4-4052-8051-1c7bc1581add\"},\"encounter\":{\"reference\":\"Encounter/175993848db-a5362f40-ee21-41f6-8413-0c7d58875cf8\"},\"onsetDateTime\":\"2020-03-06T14:40:01-05:00\",\"recordedDate\":\"2020-03-06T14:40:01-05:00\"}\n{\"resourceType\":\"Condition\",\"id\":\"175993e337e-9c6dcc25-7f46-4b9b-9739-9630d8a5a265\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2020-11-05T16:29:53.501Z\",\"profile\":[\"http://hl7.org/fhir/us/core/StructureDefinition/us-core-condition\"]},\"clinicalStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-clinical\",\"code\":\"resolved\"}]},\"verificationStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-ver-status\",\"code\":\"confirmed\"}]},\"category\":[{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-category\",\"code\":\"encounter-diagnosis\",\"display\":\"Encounter Diagnosis\"}]}],\"code\":{\"coding\":[{\"system\":\"http://snomed.info/sct\",\"code\":\"16114001\",\"display\":\"Fracture of ankle\"}],\"text\":\"Fracture of ankle\"},\"subject\":{\"reference\":\"Patient/175993e337e-57854f5d-6b14-46ba-b6fa-2a2cd7e1fa23\"},\"encounter\":{\"reference\":\"Encounter/175993e337e-bd75e82c-ce79-4a93-9ef2-69c7ac952985\"},\"onsetDateTime\":\"2013-03-30T21:49:05-04:00\",\"abatementDateTime\":\"2013-05-29T22:27:05-04:00\",\"recordedDate\":\"2013-03-30T21:49:05-04:00\"}\n{\"resourceType\":\"Condition\",\"id\":\"1759944ebac-b92fdc8d-0849-48ff-93b9-7010774fe889\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2020-11-05T16:37:20.091Z\",\"profile\":[\"http://hl7.org/fhir/us/core/StructureDefinition/us-core-condition\"]},\"clinicalStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-clinical\",\"code\":\"active\"}]},\"verificationStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-ver-status\",\"code\":\"confirmed\"}]},\"category\":[{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-category\",\"code\":\"encounter-diagnosis\",\"display\":\"Encounter Diagnosis\"}]}],\"code\":{\"coding\":[{\"system\":\"http://snomed.info/sct\",\"code\":\"40055000\",\"display\":\"Chronic sinusitis (disorder)\"}],\"text\":\"Chronic sinusitis (disorder)\"},\"subject\":{\"reference\":\"Patient/1759944ebab-22fa6c7e-dc9f-49ec-897f-c8300a988d57\"},\"encounter\":{\"reference\":\"Encounter/1759944ebac-58caa8bb-1c81-4e4f-80e6-05ffb30ea358\"},\"onsetDateTime\":\"2017-08-15T08:41:05-04:00\",\"recordedDate\":\"2017-08-15T08:41:05-04:00\"}\n{\"resourceType\":\"Condition\",\"id\":\"175994b17ae-a55091ab-ec13-44f4-b129-7a9e8784f2f8\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2020-11-05T16:43:56.779Z\",\"profile\":[\"http://hl7.org/fhir/us/core/StructureDefinition/us-core-condition\"]},\"clinicalStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-clinical\",\"code\":\"active\"}]},\"verificationStatus\":{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-ver-status\",\"code\":\"confirmed\"}]},\"category\":[{\"coding\":[{\"system\":\"http://terminology.hl7.org/CodeSystem/condition-category\",\"code\":\"encounter-diagnosis\",\"display\":\"Encounter Diagnosis\"}]}],\"code\":{\"coding\":[{\"system\":\"http://snomed.info/sct\",\"code\":\"19169002\",\"display\":\"Miscarriage in first trimester\"}],\"text\":\"Miscarriage in first trimester\"},\"subject\":{\"reference\":\"Patient/175994b17ae-428989d4-e791-4525-b95b-b39a058b0ecc\"},\"encounter\":{\"reference\":\"Encounter/175994b17ae-5a8f7850-e8c5-4820-b67c-cda707544e4c\"},\"onsetDateTime\":\"1992-06-07T15:12:53-04:00\",\"recordedDate\":\"1992-06-07T15:12:53-04:00\"}\n\n"
],
[
"%%html\n<style>\ndiv.output_area pre {\n white-space: pre;\n}\n</style>",
"_____no_output_____"
]
],
[
[
"---\nFHIR® is the registered trademark of HL7 and is used with the permission of HL7. Use of the FHIR trademark does not constitute endorsement of this product by HL7.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
e77d9ed76c6bb2909b690d3d6f4e872ec8994dd2 | 31,817 | ipynb | Jupyter Notebook | docs_src/tabular.transform.ipynb | dienhoa/fastai_docs | 3ea94b6afd341de5430dd9c7f0a410f016239da1 | [
"Apache-2.0"
] | null | null | null | docs_src/tabular.transform.ipynb | dienhoa/fastai_docs | 3ea94b6afd341de5430dd9c7f0a410f016239da1 | [
"Apache-2.0"
] | null | null | null | docs_src/tabular.transform.ipynb | dienhoa/fastai_docs | 3ea94b6afd341de5430dd9c7f0a410f016239da1 | [
"Apache-2.0"
] | null | null | null | 30.38873 | 427 | 0.453814 | [
[
[
"# Tabular data preprocessing",
"_____no_output_____"
]
],
[
[
"from fastai.gen_doc.nbdoc import *\nfrom fastai.tabular import *\nfrom fastai import *",
"_____no_output_____"
]
],
[
[
"## Overview",
"_____no_output_____"
],
[
"This package contains the basic class to define a transformation for preprocessing dataframes of tabular data, as well as basic [`TabularTransform`](/tabular.transform.html#TabularTransform). Preprocessing includes things like\n- replacing non-numerical variables by categories, then their ids,\n- filling missing values,\n- normalizing continuous variables.\n\nIn all those steps we have to be careful to use the correspondance we decide on our training set (which id we give to each category, what is the value we put for missing data, or how the mean/std we use to normalize) on our validation or test set. To deal with this, we use a speciall class called [`TabularTransform`](/tabular.transform.html#TabularTransform).\n\nThe data used in this document page is a subset of the [adult dataset](https://archive.ics.uci.edu/ml/datasets/adult). It gives a certain amount of data on individuals to train a model to predict wether their salary is greater than \\$50k or not.",
"_____no_output_____"
]
],
[
[
"path = untar_data(URLs.ADULT_SAMPLE)\ndf = pd.read_csv(path/'adult.csv')\ntrain_df, valid_df = df[:800].copy(),df[800:].copy()\ntrain_df.head()",
"_____no_output_____"
]
],
[
[
"We see it contains numerical variables (like `age` or `education-num`) as well as categorical ones (like `workclass` or `relationship`). The original dataset is clean, but we removed a few values to give examples of dealing with missing variables.",
"_____no_output_____"
]
],
[
[
"cat_names = ['workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race', 'sex', 'native-country']\ncont_names = ['age', 'fnlwgt', 'education-num', 'capital-gain', 'capital-loss', 'hours-per-week']",
"_____no_output_____"
]
],
[
[
"## Transforms for tabular data",
"_____no_output_____"
]
],
[
[
"show_doc(TabularTransform, doc_string=False)",
"_____no_output_____"
]
],
[
[
"Base class for creating transforms for dataframes with categorical variables `cat_names` and continuous variables `cont_names`. Note that any column not in one of those lists won't be touched.",
"_____no_output_____"
]
],
[
[
"show_doc(TabularTransform.__call__)",
"_____no_output_____"
]
],
[
[
"This simply calls `apply_test` if `test` or `apply_train` otherwise. Those functions apply the changes in place.",
"_____no_output_____"
]
],
[
[
"show_doc(TabularTransform.apply_train, doc_string=False)",
"_____no_output_____"
]
],
[
[
"Must be implemented by an inherited class with the desired transformation logic.",
"_____no_output_____"
]
],
[
[
"show_doc(TabularTransform.apply_test, doc_string=False)",
"_____no_output_____"
]
],
[
[
"If not implemented by an inherited class, defaults to calling `apply_train`.",
"_____no_output_____"
],
[
"The following [`TabularTransform`](/tabular.transform.html#TabularTransform) are implemented in the fastai library. Note that the replacement from categories to codes as well as the normalization of continuous variables are automatically done in a [`TabularDataset`](/tabular.data.html#TabularDataset).",
"_____no_output_____"
]
],
[
[
"show_doc(Categorify, doc_string=False)",
"_____no_output_____"
]
],
[
[
"Changes the categorical variables in `cat_names` in categories. Variables in `cont_names` aren't affected.",
"_____no_output_____"
]
],
[
[
"show_doc(Categorify.apply_train, doc_string=False)",
"_____no_output_____"
]
],
[
[
"Transforms the variable in the `cat_names` columns in categories. The category codes are the unique values in these columns.",
"_____no_output_____"
]
],
[
[
"show_doc(Categorify.apply_test, doc_string=False)",
"_____no_output_____"
]
],
[
[
"Transforms the variable in the `cat_names` columns in categories. The category codes are the ones used for the training set, new categories are replaced by NaN. ",
"_____no_output_____"
]
],
[
[
"tfm = Categorify(cat_names, cont_names)\ntfm(train_df)\ntfm(valid_df, test=True)",
"_____no_output_____"
]
],
[
[
"Since we haven't changed the categories by their codes, nothing visible has changed in the dataframe yet, but we can check that the variables are now categorical and view their corresponding codes.",
"_____no_output_____"
]
],
[
[
"train_df['workclass'].cat.categories",
"_____no_output_____"
]
],
[
[
"The test set will be given the same category codes as the training set.",
"_____no_output_____"
]
],
[
[
"valid_df['workclass'].cat.categories",
"_____no_output_____"
],
[
"show_doc(FillMissing, doc_string=False)",
"_____no_output_____"
]
],
[
[
"Transform that fills the missing values in `cont_names`. `cat_names` variables are left untouched (their missing value will be raplced by code 0 in the [`TabularDataset`](/tabular.data.html#TabularDataset)). [`fill_strategy`](#FillStrategy) is adopted to replace those nans and if `add_col` is True, whenever a column `c` has missing values, a column named `c_nan` is added and flags the line where the value was missing.",
"_____no_output_____"
]
],
[
[
"show_doc(FillMissing.apply_train, doc_string=False)",
"_____no_output_____"
]
],
[
[
"Fills the missing values in the `cont_names` columns.",
"_____no_output_____"
]
],
[
[
"show_doc(FillMissing.apply_test, doc_string=False)",
"_____no_output_____"
]
],
[
[
"Fills the missing values in the `cont_names` columns with the ones picked during train.",
"_____no_output_____"
]
],
[
[
"train_df[cont_names].head()",
"_____no_output_____"
],
[
"tfm = FillMissing(cat_names, cont_names)\ntfm(train_df)\ntfm(valid_df, test=True)\ntrain_df[cont_names].head()",
"_____no_output_____"
]
],
[
[
"Values issing in the `education-num` column are replaced by 10, which is the median of the column in `train_df`. Categorical variables are not changed, since `nan` is simply used as another category.",
"_____no_output_____"
]
],
[
[
"valid_df[cont_names].head()",
"_____no_output_____"
],
[
"%reload_ext autoreload\n%autoreload 2\n%matplotlib inline",
"_____no_output_____"
],
[
"show_doc(FillStrategy, alt_doc_string='Enum flag represents determines how `FillMissing` should handle missing/nan values', arg_comments={\n 'MEDIAN':'nans are replaced by the median value of the column',\n 'COMMON': 'nans are replaced by the most common value of the column',\n 'CONSTANT': 'nans are replaced by `fill_val`'\n})",
"_____no_output_____"
]
],
[
[
"## Undocumented Methods - Methods moved below this line will intentionally be hidden",
"_____no_output_____"
],
[
"## New Methods - Please document or move to the undocumented section",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
e77dc82bd5713a8374f9501423acf7ab4500d7c4 | 87,023 | ipynb | Jupyter Notebook | notebooks/poisson-intro.ipynb | shyams2/jax-fenics-adjoint | 7c0f1e9ea3b74966d44f38e29135fc2aa05ec6dd | [
"MIT"
] | 61 | 2020-03-03T22:01:29.000Z | 2022-03-31T19:32:14.000Z | notebooks/poisson-intro.ipynb | shyams2/jax-fenics-adjoint | 7c0f1e9ea3b74966d44f38e29135fc2aa05ec6dd | [
"MIT"
] | 6 | 2020-03-04T15:42:45.000Z | 2021-12-25T23:04:14.000Z | notebooks/poisson-intro.ipynb | shyams2/jax-fenics-adjoint | 7c0f1e9ea3b74966d44f38e29135fc2aa05ec6dd | [
"MIT"
] | 10 | 2020-03-04T15:14:57.000Z | 2022-01-19T03:29:50.000Z | 168.649225 | 24,476 | 0.894568 | [
[
[
"# Automatic Differentiation of PDE solvers with JAX and dolfin-adjoint\n\nDerivative information is the crucial requirement for using effective algorithms for design optimization, parameter estimation, optimal control, model\nreduction and experimental design, and other tasks. This notebook gives an example how to use JAX together with FEniCS and dolfin-adjoint for computing derivatives.\n\n## Poisson equation\nThe Poisson equation is the canonical elliptic partial differential equation. For a domain $\\Omega \\subset \\mathbb{R}^n$ with boundary $\\partial \\Omega = \\Gamma_{D}$, the Poisson equation with particular boundary conditions reads:\n\n$$\\begin{align*} - \\nabla^{2} u &= f \\quad {\\rm in} \\ \\Omega, \\\\ u &= 0 \\quad {\\rm on} \\ \\Gamma_{D}. \\\\ \\end{align*}$$\nHere, $f$ is input data. The most standard variational form of Poisson equation reads: find $u \\in V$ such that\n\n$$\\begin{equation*} a(u, v) = L(v) \\quad \\forall \\ v \\in V, \\end{equation*}$$\nwhere $V$ is a suitable function space and\n\n$$\\begin{align*} a(u, v) &= \\int_{\\Omega} \\nabla u \\cdot \\nabla v \\, {\\rm d} x, \\\\ L(v) &= \\int_{\\Omega} f v \\, {\\rm d} x. \\end{align*}$$\n\n\n",
"_____no_output_____"
]
],
[
[
"# Let's import all needed stuff\nimport jax\nfrom jax.config import config\n\nimport jax.numpy as np\nimport numpy as onp\n\nfrom scipy.optimize import minimize\n\n# Library for automated PDE solution\nimport fenics\n# Library for automated derivative computation of FEniCS programs\nimport fenics_adjoint\n# UFL is domain specific language (DSL) for declaration of finite element discretizations of variational forms\nimport ufl \n\n# Suppress JIT compile message from FEniCS\nimport logging\nlogging.getLogger('FFC').setLevel(logging.WARNING)\nlogging.getLogger('UFL').setLevel(logging.WARNING)\n\n# This is the core function here\nfrom jaxfenics_adjoint import build_jax_fem_eval\nfrom jaxfenics_adjoint import from_jax\n\nimport matplotlib.pyplot as plt\n\nconfig.update(\"jax_enable_x64\", True)\n# fenics.set_log_level(fenics.LogLevel.ERROR)",
"_____no_output_____"
]
],
[
[
"PDEs are spatial models and require a domain to be defined on. Here we choose the domain to be a unit square and it is triangulated for finite element discretization.",
"_____no_output_____"
]
],
[
[
"# Create mesh\nn = 16\nmesh = fenics_adjoint.UnitSquareMesh(n, n)\nfenics.plot(mesh)",
"_____no_output_____"
]
],
[
[
"Another important part of the Poisson variational problem is the function space $V$. This object is resposible for representation of the disretized functions on the chosen mesh. Here we choose the function space to consist of piece-wise linear functions (P1 in finite element terminology, or CG1 for Continuous Galerkin of degree 1). DG corresponds to Discontinuous Galerkin function space. DG0 is piece-wise constant function in each mesh element. If the mesh was consisting of quads then it would be similar to pixel image.",
"_____no_output_____"
]
],
[
[
"# Define discrete function spaces and functions\nV = fenics.FunctionSpace(mesh, \"CG\", 1)\nW = fenics.FunctionSpace(mesh, \"DG\", 0)",
"_____no_output_____"
]
],
[
[
"JAX-FEniCS interface needs an auxilary information to be able to freely convert data between the libraries, therefore we need \"templates\" which represent what is the expected input to FEniCS function.",
"_____no_output_____"
]
],
[
[
"solve_templates = (fenics_adjoint.Function(W),)",
"_____no_output_____"
]
],
[
[
"Now we define the `fenics_solve` function which takes a function `f` which lives in the function space `W` and outputs the solution `u` to the Poisson equation.\n\n`build_jax_fem_eval` is a wrapper decorator that registers `fenics_solve` for JAX.",
"_____no_output_____"
]
],
[
[
"# Define and solve the Poisson equation\n@build_jax_fem_eval(solve_templates)\ndef fenics_solve(f):\n u = fenics.TrialFunction(V)\n v = fenics.TestFunction(V)\n inner, grad, dx = ufl.inner, ufl.grad, ufl.dx\n # Compare this code to the mathematical formulation above\n a = inner(grad(u), grad(v)) * dx\n L = f * v * dx\n bcs = fenics_adjoint.DirichletBC(V, 0.0, \"on_boundary\")\n u = fenics_adjoint.Function(V, name=\"PDE Solution\")\n fenics_adjoint.solve(a == L, u, bcs)\n return u",
"_____no_output_____"
],
[
"# Let's create a vector of ones with size equal to the number of cells in the mesh\nf = np.ones(W.dim())\n# and solve the Poisson equation for given `f`\nu = fenics_solve(f) # u is JAX's array",
"/u/65/yashchi1/unix/.conda/envs/fenicsproject/lib/python3.8/site-packages/jax/lib/xla_bridge.py:122: UserWarning: No GPU/TPU found, falling back to CPU.\n warnings.warn('No GPU/TPU found, falling back to CPU.')\n"
],
[
" # We need to explicitly provide the template function for conversion to FEniCS\nu_fenics = from_jax(u, fenics.Function(V))\nc = fenics.plot(u_fenics)\nplt.colorbar(c)",
"_____no_output_____"
]
],
[
[
"Here comes the JAX specific part. Having defined a mapping from $f$ to $u$ we can differentiate it. For example calculating vector-Jacobian product with `jax.vjp`:",
"_____no_output_____"
]
],
[
[
"%%time\nu, vjp_fun = jax.vjp(fenics_solve, f)\ng = np.ones_like(u)\nvjp_result = vjp_fun(g)",
"CPU times: user 48.7 ms, sys: 351 µs, total: 49.1 ms\nWall time: 49.4 ms\n"
],
[
"vjp_result_fenics = from_jax(*vjp_result, fenics.Function(W))\nc = fenics.plot(vjp_result_fenics)\nplt.colorbar(c)",
"_____no_output_____"
]
],
[
[
"It is also possible to calculate the full (dense) Jacobian matrix $\\frac{du}{df}$ with `jax.jacrev`:",
"_____no_output_____"
]
],
[
[
"%%time\ndudf = jax.jacrev(fenics_solve)(f)",
"CPU times: user 2.9 s, sys: 58.5 ms, total: 2.96 s\nWall time: 2.88 s\n"
],
[
"# function `fenics_solve` maps R^512 (dimension of W) to R^289 (dimension of V)\n# therefore the Jacobian matrix dimension is dim V x dim W\nassert dudf.shape == (V.dim(), W.dim())",
"_____no_output_____"
]
],
[
[
"The same Jacobian matrix can be calculated using finite-differences, for example with `fdm` library. However, it takes considerably more time because it requires a lot of `fenics_solve` calls. The difference is even more drastic for larger models.",
"_____no_output_____"
],
[
"`jaxfenics_adjoint` library makes it possible to combine FEniCS programs with arbitrary JAX programs. In above example `f` could be the output of a neural network and passed as an input to the PDE solver or `u` could be further processed in JAX for evaluating functionals that are not integrals over the domain (this case can be handled in FEniCS).",
"_____no_output_____"
]
],
[
[
"# stax is JAX's mini-library for neural networks\nfrom jax.experimental import stax\nfrom jax.experimental.stax import Dense, Relu\nfrom jax import random\n\n# Use stax to set up network initialization and evaluation functions\n# Define R^2 -> R^1 function\nnet_init, net_apply = stax.serial(\n Dense(2), Relu,\n Dense(10), Relu,\n Dense(1), \n)\n\n# Initialize parameters, not committing to a batch shape\nrng = random.PRNGKey(0)\nin_shape = (-1, 2)\nout_shape, net_params = net_init(rng, in_shape)\n\n# Apply network to dummy inputs\npredictions = net_apply(net_params, W.tabulate_dof_coordinates())\nsource_nn = from_jax(predictions, fenics.Function(W))",
"_____no_output_____"
],
[
"# Plot neural network prediction\nc = fenics.plot(source_nn)\nplt.colorbar(c)",
"_____no_output_____"
],
[
"def eval_nn(net_params):\n f_nn = np.ravel(net_apply(net_params, W.tabulate_dof_coordinates()))\n u = fenics_solve(f_nn)\n norm_u = np.linalg.norm(u)\n return norm_u",
"_____no_output_____"
],
[
"%%time\njax.grad(eval_nn)(net_params)",
"CPU times: user 340 ms, sys: 7.82 ms, total: 348 ms\nWall time: 337 ms\n"
]
],
[
[
"For further FEniCS examples check out [FEniCS' demos](https://bitbucket.org/fenics-project/dolfin/src/master/python/demo/documented/) and [dolfin-adjoint webiste](http://www.dolfin-adjoint.org/en/latest/documentation/examples.html).\n\nFor further examples on using FEniCS with JAX check out [`examples/` folder here](https://github.com/IvanYashchuk/jax-fenics-adjoint/tree/master/examples).",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
e77dd0a87ad84120b74514c7b727847ad936befd | 48,177 | ipynb | Jupyter Notebook | notebooks/Example ring graph.ipynb | csimal/metaplex-networks | 2010f6bdb9a0cb7be78e74f8bf64dd9aba5871ad | [
"MIT"
] | null | null | null | notebooks/Example ring graph.ipynb | csimal/metaplex-networks | 2010f6bdb9a0cb7be78e74f8bf64dd9aba5871ad | [
"MIT"
] | null | null | null | notebooks/Example ring graph.ipynb | csimal/metaplex-networks | 2010f6bdb9a0cb7be78e74f8bf64dd9aba5871ad | [
"MIT"
] | null | null | null | 104.505423 | 35,949 | 0.658613 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
e77ddf28e8c289a5040a4c1aadcf67086f4ddf47 | 905,090 | ipynb | Jupyter Notebook | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures | 1419a7ed57fa569dc60252444ebf85d5ff437d84 | [
"CC-BY-4.0"
] | 1 | 2021-04-03T12:15:19.000Z | 2021-04-03T12:15:19.000Z | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures | 1419a7ed57fa569dc60252444ebf85d5ff437d84 | [
"CC-BY-4.0"
] | null | null | null | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures | 1419a7ed57fa569dc60252444ebf85d5ff437d84 | [
"CC-BY-4.0"
] | 3 | 2021-05-31T15:10:53.000Z | 2021-09-28T16:53:14.000Z | 214.070482 | 162,376 | 0.901119 | [
[
[
"<img alt=\"QuantRocket logo\" src=\"https://www.quantrocket.com/assets/img/notebook-header-logo.png\">\n\n© Copyright Quantopian Inc.<br>\n© Modifications Copyright QuantRocket LLC<br>\nLicensed under the [Creative Commons Attribution 4.0](https://creativecommons.org/licenses/by/4.0/legalcode).\n\n<a href=\"https://www.quantrocket.com/disclaimer/\">Disclaimer</a>",
"_____no_output_____"
],
[
"# Introduction to pandas\nby Maxwell Margenot\n",
"_____no_output_____"
],
[
"pandas is a Python library that provides a collection of powerful data structures to better help you manage data. In this lecture, we will cover how to use the `Series` and `DataFrame` objects to handle data. These objects have a strong integration with NumPy, allowing us to easily do the necessary statistical and mathematical calculations that we need for finance.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt",
"_____no_output_____"
]
],
[
[
"With pandas, it is easy to store, visualize, and perform calculations on your data. With only a few lines of code we can modify our data and present it in an easily-understandable way. Here we simulate some returns in NumPy, put them into a pandas `DataFrame`, and perform calculations to turn them into prices and plot them, all only using a few lines of code.",
"_____no_output_____"
]
],
[
[
"returns = pd.DataFrame(np.random.normal(1.0, 0.03, (100, 10)))\nprices = returns.cumprod()\nprices.plot()\nplt.title('Randomly-generated Prices')\nplt.xlabel('Time')\nplt.ylabel('Price')\nplt.legend(loc=0);",
"_____no_output_____"
]
],
[
[
"So let's have a look at how we actually build up to this point!",
"_____no_output_____"
],
[
"## pandas Data Structures\n\n### `Series`\n\nA pandas `Series` is a 1-dimensional array with labels that can contain any data type. We primarily use them for handling time series data. Creating a `Series` is as easy as calling `pandas.Series()` on a Python list or NumPy array.",
"_____no_output_____"
]
],
[
[
"s = pd.Series([1, 2, np.nan, 4, 5])\nprint(s)",
"0 1.0\n1 2.0\n2 NaN\n3 4.0\n4 5.0\ndtype: float64\n"
]
],
[
[
"Every `Series` has a name. We can give the series a name as a parameter or we can define it afterwards by directly accessing the name attribute. In this case, we have given our time series no name so the attribute should be empty.",
"_____no_output_____"
]
],
[
[
"print(s.name)",
"None\n"
]
],
[
[
"This name can be directly modified with no repercussions.",
"_____no_output_____"
]
],
[
[
"s.name = \"Toy Series\"\nprint(s.name)",
"Toy Series\n"
]
],
[
[
"We call the collected axis labels of a `Series` its index. An index can either passed to a `Series` as a parameter or added later, similarly to its name. In the absence of an index, a `Series` will simply contain an index composed of integers, starting at $0$, as in the case of our \"Toy Series\".",
"_____no_output_____"
]
],
[
[
"print(s.index)",
"RangeIndex(start=0, stop=5, step=1)\n"
]
],
[
[
"pandas has a built-in function specifically for creating date indices, `date_range()`. We use the function here to create a new index for `s`.",
"_____no_output_____"
]
],
[
[
"new_index = pd.date_range(\"2016-01-01\", periods=len(s), freq=\"D\")\nprint(new_index)",
"DatetimeIndex(['2016-01-01', '2016-01-02', '2016-01-03', '2016-01-04',\n '2016-01-05'],\n dtype='datetime64[ns]', freq='D')\n"
]
],
[
[
"An index must be exactly the same length as the `Series` itself. Each index must match one-to-one with each element of the `Series`. Once this is satisfied, we can directly modify the `Series` index, as with the name, to use our new and more informative index (relatively speaking).",
"_____no_output_____"
]
],
[
[
"s.index = new_index\nprint(s.index)",
"DatetimeIndex(['2016-01-01', '2016-01-02', '2016-01-03', '2016-01-04',\n '2016-01-05'],\n dtype='datetime64[ns]', freq='D')\n"
]
],
[
[
"The index of the `Series` is crucial for handling time series, which we will get into a little later.",
"_____no_output_____"
],
[
"#### Accessing `Series` Elements\n\n`Series` are typically accessed using the `iloc[]` and `loc[]` methods. We use `iloc[]` to access elements by integer index and we use `loc[]` to access the index of the Series.",
"_____no_output_____"
]
],
[
[
"print(\"First element of the series:\", s.iloc[0])\nprint(\"Last element of the series:\", s.iloc[len(s)-1])",
"First element of the series: 1.0\nLast element of the series: 5.0\n"
]
],
[
[
"We can slice a `Series` similarly to our favorite collections, Python lists and NumPy arrays. We use the colon operator to indicate the slice.",
"_____no_output_____"
]
],
[
[
"s.iloc[:2]",
"_____no_output_____"
]
],
[
[
"When creating a slice, we have the options of specifying a beginning, an end, and a step. The slice will begin at the start index, and take steps of size `step` until it passes the end index, not including the end.",
"_____no_output_____"
]
],
[
[
"start = 0\nend = len(s) - 1\nstep = 1\n\ns.iloc[start:end:step]",
"_____no_output_____"
]
],
[
[
"We can even reverse a `Series` by specifying a negative step size. Similarly, we can index the start and end with a negative integer value.",
"_____no_output_____"
]
],
[
[
"s.iloc[::-1]",
"_____no_output_____"
]
],
[
[
"This returns a slice of the series that starts from the second to last element and ends at the third to last element (because the fourth to last is not included, taking steps of size $1$).",
"_____no_output_____"
]
],
[
[
"s.iloc[-2:-4:-1]",
"_____no_output_____"
]
],
[
[
"We can also access a series by using the values of its index. Since we indexed `s` with a collection of dates (`Timestamp` objects) we can look at the value contained in `s` for a particular date.",
"_____no_output_____"
]
],
[
[
"s.loc['2016-01-01']",
"_____no_output_____"
]
],
[
[
"Or even for a range of dates!",
"_____no_output_____"
]
],
[
[
"s.loc['2016-01-02':'2016-01-04']",
"_____no_output_____"
]
],
[
[
"With `Series`, we *can* just use the brackets (`[]`) to access elements, but this is not best practice. The brackets are ambiguous because they can be used to access `Series` (and `DataFrames`) using both index and integer values and the results will change based on context (especially with `DataFrames`).",
"_____no_output_____"
],
[
"#### Boolean Indexing\n\nIn addition to the above-mentioned access methods, you can filter `Series` using boolean arrays. `Series` are compatible with your standard comparators. Once compared with whatever condition you like, you get back yet another `Series`, this time filled with boolean values.",
"_____no_output_____"
]
],
[
[
"print(s < 3)",
"2016-01-01 True\n2016-01-02 True\n2016-01-03 False\n2016-01-04 False\n2016-01-05 False\nFreq: D, Name: Toy Series, dtype: bool\n"
]
],
[
[
"We can pass *this* `Series` back into the original `Series` to filter out only the elements for which our condition is `True`.",
"_____no_output_____"
]
],
[
[
"print(s.loc[s < 3])",
"2016-01-01 1.0\n2016-01-02 2.0\nFreq: D, Name: Toy Series, dtype: float64\n"
]
],
[
[
"If we so desire, we can group multiple conditions together using the logical operators `&`, `|`, and `~` (and, or, and not, respectively).",
"_____no_output_____"
]
],
[
[
"print(s.loc[(s < 3) & (s > 1)])",
"2016-01-02 2.0\nFreq: D, Name: Toy Series, dtype: float64\n"
]
],
[
[
"This is very convenient for getting only elements of a `Series` that fulfill specific criteria that we need. It gets even more convenient when we are handling `DataFrames`.",
"_____no_output_____"
],
[
"#### Indexing and Time Series\n\nSince we use `Series` for handling time series, it's worth covering a little bit of how we handle the time component. For our purposes we use pandas `Timestamp` objects. Let's pull a full time series, complete with all the appropriate labels, by using our `get_prices()` function. All data pulled with `get_prices()` will be in `DataFrame` format. We can modify this index however we like.",
"_____no_output_____"
]
],
[
[
"from quantrocket.master import get_securities\nsecurities = get_securities(symbols='XOM', fields=['Sid','Symbol','Exchange'], vendors='usstock')\nsecurities",
"_____no_output_____"
],
[
"from quantrocket import get_prices\nXOM = securities.index[0]\nstart = \"2012-01-01\"\nend = \"2016-01-01\"\nprices = get_prices(\"usstock-free-1min\", data_frequency=\"daily\", sids=XOM, start_date=start, end_date=end, fields=\"Close\")\nprices = prices.loc[\"Close\"][XOM]",
"_____no_output_____"
]
],
[
[
"We can display the first few elements of our series by using the `head()` method and specifying the number of elements that we want. The analogous method for the last few elements is `tail()`.",
"_____no_output_____"
]
],
[
[
"print(type(prices))\nprices.head(5) ",
"<class 'pandas.core.series.Series'>\n"
]
],
[
[
"As with our toy example, we can specify a name for our time series, if only to clarify the name the `get_pricing()` provides us.",
"_____no_output_____"
]
],
[
[
"print('Old name:', prices.name)\nprices.name = \"XOM\"\nprint('New name:', prices.name)",
"Old name: FIBBG000GZQ728\nNew name: XOM\n"
]
],
[
[
"Let's take a closer look at the `DatetimeIndex` of our `prices` time series.",
"_____no_output_____"
]
],
[
[
"print(prices.index)\nprint(\"tz:\", prices.index.tz)",
"DatetimeIndex(['2012-01-03', '2012-01-04', '2012-01-05', '2012-01-06',\n '2012-01-09', '2012-01-10', '2012-01-11', '2012-01-12',\n '2012-01-13', '2012-01-17',\n ...\n '2015-12-17', '2015-12-18', '2015-12-21', '2015-12-22',\n '2015-12-23', '2015-12-24', '2015-12-28', '2015-12-29',\n '2015-12-30', '2015-12-31'],\n dtype='datetime64[ns]', name='Date', length=1006, freq=None)\ntz: None\n"
]
],
[
[
"Notice that this `DatetimeIndex` has a collection of associated information. In particular it has an associated frequency (`freq`) and an associated timezone (`tz`). The frequency indicates whether the data is daily vs monthly vs some other period while the timezone indicates what locale this index is relative to. We can modify all of this extra information!\n\nIf we resample our `Series`, we can adjust the frequency of our data. We currently have daily data (excluding weekends). Let's downsample from this daily data to monthly data using the `resample()` method.",
"_____no_output_____"
]
],
[
[
"monthly_prices = prices.resample('M').last()\nmonthly_prices.head(10)",
"_____no_output_____"
]
],
[
[
"In the above example we use the last value of the lower level data to create the higher level data. We can specify how else we might want the down-sampling to be calculated, for example using the median.",
"_____no_output_____"
]
],
[
[
"monthly_prices_med = prices.resample('M').median()\nmonthly_prices_med.head(10)",
"_____no_output_____"
]
],
[
[
"We can even specify how we want the calculation of the new period to be done. Here we create a `custom_resampler()` function that will return the first value of the period. In our specific case, this will return a `Series` where the monthly value is the first value of that month.",
"_____no_output_____"
]
],
[
[
"def custom_resampler(array_like):\n \"\"\" Returns the first value of the period \"\"\"\n return array_like[0]\n\nfirst_of_month_prices = prices.resample('M').apply(custom_resampler)\nfirst_of_month_prices.head(10)",
"_____no_output_____"
]
],
[
[
"We can also adjust the timezone of a `Series` to adapt the time of real-world data. In our case, our time series isn't localized to a timezone, but let's say that we want to localize the time to be 'America/New_York'. In this case we use the `tz_localize()` method, since the time isn't already localized.",
"_____no_output_____"
]
],
[
[
"eastern_prices = prices.tz_localize('America/New_York')\neastern_prices.head(10)",
"_____no_output_____"
]
],
[
[
"In addition to the capacity for timezone and frequency management, each time series has a built-in `reindex()` method that we can use to realign the existing data according to a new set of index labels. If data does not exist for a particular label, the data will be filled with a placeholder value. This is typically `np.nan`, though we can provide a fill method.\n\nThe data that we get from `get_prices()` only includes market days. But what if we want prices for every single calendar day? This will include holidays and weekends, times when you normally cannot trade equities. First let's create a new `DatetimeIndex` that contains all that we want.",
"_____no_output_____"
]
],
[
[
"calendar_dates = pd.date_range(start=start, end=end, freq='D')\nprint(calendar_dates)",
"DatetimeIndex(['2012-01-01', '2012-01-02', '2012-01-03', '2012-01-04',\n '2012-01-05', '2012-01-06', '2012-01-07', '2012-01-08',\n '2012-01-09', '2012-01-10',\n ...\n '2015-12-23', '2015-12-24', '2015-12-25', '2015-12-26',\n '2015-12-27', '2015-12-28', '2015-12-29', '2015-12-30',\n '2015-12-31', '2016-01-01'],\n dtype='datetime64[ns]', length=1462, freq='D')\n"
]
],
[
[
"Now let's use this new set of dates to reindex our time series. We tell the function that the fill method that we want is `ffill`. This denotes \"forward fill\". Any `NaN` values will be filled by the *last value* listed. So the price on the weekend or on a holiday will be listed as the price on the last market day that we know about.",
"_____no_output_____"
]
],
[
[
"calendar_prices = prices.reindex(calendar_dates, method='ffill')\ncalendar_prices.head(15)",
"_____no_output_____"
]
],
[
[
"You'll notice that we still have a couple of `NaN` values right at the beginning of our time series. This is because the first of January in 2012 was a Sunday and the second was a market holiday! Because these are the earliest data points and we don't have any information from before them, they cannot be forward-filled. We will take care of these `NaN` values in the next section, when we deal with missing data.",
"_____no_output_____"
],
[
"#### Missing Data\n\nWhenever we deal with real data, there is a very real possibility of encountering missing values. Real data is riddled with holes and pandas provides us with ways to handle them. Sometimes resampling or reindexing can create `NaN` values. Fortunately, pandas provides us with ways to handle them. We have two primary means of coping with missing data. The first of these is filling in the missing data with `fillna()`. For example, say that we want to fill in the missing days with the mean price of all days.",
"_____no_output_____"
]
],
[
[
"meanfilled_prices = calendar_prices.fillna(calendar_prices.mean())\nmeanfilled_prices.head(10)",
"_____no_output_____"
]
],
[
[
"Using `fillna()` is fairly easy. It is just a matter of indicating the value that you want to fill the spaces with. Unfortunately, this particular case doesn't make a whole lot of sense, for reasons discussed in the lecture on stationarity in the Lecture series. We could fill them with with $0$, simply, but that's similarly uninformative.\n\nRather than filling in specific values, we can use the `method` parameter. We could use \"backward fill\", where `NaN`s are filled with the *next* filled value (instead of forward fill's *last* filled value) like so:",
"_____no_output_____"
]
],
[
[
"bfilled_prices = calendar_prices.fillna(method='bfill')\nbfilled_prices.head(10)",
"_____no_output_____"
]
],
[
[
"But again, this is a bad idea for the same reasons as the previous option. Both of these so-called solutions take into account *future data* that was not available at the time of the data points that we are trying to fill. In the case of using the mean or the median, these summary statistics are calculated by taking into account the entire time series. Backward filling is equivalent to saying that the price of a particular security today, right now, is tomorrow's price. This also makes no sense. These two options are both examples of look-ahead bias, using data that would be unknown or unavailable at the desired time, and should be avoided.\n\nOur next option is significantly more appealing. We could simply drop the missing data using the `dropna()` method. This is much better alternative than filling `NaN` values in with arbitrary numbers.",
"_____no_output_____"
]
],
[
[
"dropped_prices = calendar_prices.dropna()\ndropped_prices.head(10)",
"_____no_output_____"
]
],
[
[
"Now our time series is cleaned for the calendar year, with all of our `NaN` values properly handled. It is time to talk about how to actually do time series analysis with pandas data structures.",
"_____no_output_____"
],
[
"#### Time Series Analysis with pandas\n\nLet's do some basic time series analysis on our original prices. Each pandas `Series` has a built-in plotting method.",
"_____no_output_____"
]
],
[
[
"prices.plot();\n# We still need to add the axis labels and title ourselves\nplt.title(\"XOM Prices\")\nplt.ylabel(\"Price\")\nplt.xlabel(\"Date\");",
"_____no_output_____"
]
],
[
[
"As well as some built-in descriptive statistics. We can either calculate these individually or using the `describe()` method.",
"_____no_output_____"
]
],
[
[
"print(\"Mean:\", prices.mean())\nprint(\"Standard deviation:\", prices.std())",
"Mean: 86.77727534791242\nStandard deviation: 6.800728542530041\n"
],
[
"print(\"Summary Statistics\")\nprint(prices.describe())",
"Summary Statistics\ncount 1006.000000\nmean 86.777275\nstd 6.800729\nmin 68.116000\n25% 82.356500\n50% 85.377000\n75% 91.559500\nmax 102.762000\nName: XOM, dtype: float64\n"
]
],
[
[
"We can easily modify `Series` with scalars using our basic mathematical operators.",
"_____no_output_____"
]
],
[
[
"modified_prices = prices * 2 - 10\nmodified_prices.head(5)",
"_____no_output_____"
]
],
[
[
"And we can create linear combinations of `Series` themselves using the basic mathematical operators. pandas will group up matching indices and perform the calculations elementwise to produce a new `Series`. ",
"_____no_output_____"
]
],
[
[
"noisy_prices = prices + 5 * pd.Series(np.random.normal(0, 5, len(prices)), index=prices.index) + 20\nnoisy_prices.head(5)",
"_____no_output_____"
]
],
[
[
"If there are no matching indices, however, we may get an empty `Series` in return.",
"_____no_output_____"
]
],
[
[
"empty_series = prices + pd.Series(np.random.normal(0, 1, len(prices)))\nempty_series.head(5)",
"_____no_output_____"
]
],
[
[
"Rather than looking at a time series itself, we may want to look at its first-order differences or percent change (in order to get additive or multiplicative returns, in our particular case). Both of these are built-in methods.",
"_____no_output_____"
]
],
[
[
"add_returns = prices.diff()[1:]\nmult_returns = prices.pct_change()[1:]",
"_____no_output_____"
],
[
"plt.title(\"Multiplicative returns of XOM\")\nplt.xlabel(\"Date\")\nplt.ylabel(\"Percent Returns\")\nmult_returns.plot();",
"_____no_output_____"
]
],
[
[
"pandas has convenient functions for calculating rolling means and standard deviations, as well!",
"_____no_output_____"
]
],
[
[
"rolling_mean = prices.rolling(30).mean()\nrolling_mean.name = \"30-day rolling mean\"",
"_____no_output_____"
],
[
"prices.plot()\nrolling_mean.plot()\nplt.title(\"XOM Price\")\nplt.xlabel(\"Date\")\nplt.ylabel(\"Price\")\nplt.legend();",
"_____no_output_____"
],
[
"rolling_std = prices.rolling(30).std()\nrolling_std.name = \"30-day rolling volatility\"",
"_____no_output_____"
],
[
"rolling_std.plot()\nplt.title(rolling_std.name);\nplt.xlabel(\"Date\")\nplt.ylabel(\"Standard Deviation\");",
"_____no_output_____"
]
],
[
[
"Many NumPy functions will work on `Series` the same way that they work on 1-dimensional NumPy arrays.",
"_____no_output_____"
]
],
[
[
"print(np.median(mult_returns))",
"-0.000332104546511\n"
]
],
[
[
"The majority of these functions, however, are already implemented directly as `Series` and `DataFrame` methods.",
"_____no_output_____"
]
],
[
[
"print(mult_returns.median())",
"-0.0003321045465112249\n"
]
],
[
[
"In every case, using the built-in pandas method will be better than using the NumPy function on a pandas data structure due to improvements in performance. Make sure to check out the `Series` [documentation](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html) before resorting to other calculations of common functions.",
"_____no_output_____"
],
[
"### `DataFrames`\n\nMany of the aspects of working with `Series` carry over into `DataFrames`. pandas `DataFrames` allow us to easily manage our data with their intuitive structure. \n\nLike `Series`, `DataFrames` can hold multiple types of data, but `DataFrames` are 2-dimensional objects, unlike `Series`. Each `DataFrame` has an index and a columns attribute, which we will cover more in-depth when we start actually playing with an object. The index attribute is like the index of a `Series`, though indices in pandas have some extra features that we will unfortunately not be able to cover here. If you are interested in this, check out the [pandas documentation](https://pandas.pydata.org/docs/user_guide/advanced.html) on advanced indexing. The columns attribute is what provides the second dimension of our `DataFrames`, allowing us to combine named columns (all `Series`), into a cohesive object with the index lined-up.\n\nWe can create a `DataFrame` by calling `pandas.DataFrame()` on a dictionary or NumPy `ndarray`. We can also concatenate a group of pandas `Series` into a `DataFrame` using `pandas.concat()`.",
"_____no_output_____"
]
],
[
[
"dict_data = {\n 'a' : [1, 2, 3, 4, 5],\n 'b' : ['L', 'K', 'J', 'M', 'Z'],\n 'c' : np.random.normal(0, 1, 5)\n}\nprint(dict_data)",
"{'a': [1, 2, 3, 4, 5], 'b': ['L', 'K', 'J', 'M', 'Z'], 'c': array([-0.56478731, -0.54468815, -0.97128315, 0.73563591, -0.02876649])}\n"
]
],
[
[
"Each `DataFrame` has a few key attributes that we need to keep in mind. The first of these is the index attribute. We can easily include an index of `Timestamp` objects like we did with `Series`.",
"_____no_output_____"
]
],
[
[
"frame_data = pd.DataFrame(dict_data, index=pd.date_range('2016-01-01', periods=5))\nprint(frame_data)",
" a b c\n2016-01-01 1 L -0.564787\n2016-01-02 2 K -0.544688\n2016-01-03 3 J -0.971283\n2016-01-04 4 M 0.735636\n2016-01-05 5 Z -0.028766\n"
]
],
[
[
"As mentioned above, we can combine `Series` into `DataFrames`. Concatatenating `Series` like this will match elements up based on their corresponding index. As the following `Series` do not have an index assigned, they each default to an integer index. ",
"_____no_output_____"
]
],
[
[
"s_1 = pd.Series([2, 4, 6, 8, 10], name='Evens')\ns_2 = pd.Series([1, 3, 5, 7, 9], name=\"Odds\")\nnumbers = pd.concat([s_1, s_2], axis=1)\nprint(numbers)",
" Evens Odds\n0 2 1\n1 4 3\n2 6 5\n3 8 7\n4 10 9\n"
]
],
[
[
"We will use `pandas.concat()` again later to combine multiple `DataFrame`s into one. ",
"_____no_output_____"
],
[
"Each `DataFrame` also has a `columns` attribute. These can either be assigned when we call `pandas.DataFrame` or they can be modified directly like the index. Note that when we concatenated the two `Series` above, the column names were the names of those `Series`.",
"_____no_output_____"
]
],
[
[
"print(numbers.columns)",
"Index(['Evens', 'Odds'], dtype='object')\n"
]
],
[
[
"To modify the columns after object creation, we need only do the following:",
"_____no_output_____"
]
],
[
[
"numbers.columns = ['Shmevens', 'Shmodds']\nprint(numbers)",
" Shmevens Shmodds\n0 2 1\n1 4 3\n2 6 5\n3 8 7\n4 10 9\n"
]
],
[
[
"In the same vein, the index of a `DataFrame` can be changed after the fact.",
"_____no_output_____"
]
],
[
[
"print(numbers.index)",
"RangeIndex(start=0, stop=5, step=1)\n"
],
[
"numbers.index = pd.date_range(\"2016-01-01\", periods=len(numbers))\nprint(numbers)",
" Shmevens Shmodds\n2016-01-01 2 1\n2016-01-02 4 3\n2016-01-03 6 5\n2016-01-04 8 7\n2016-01-05 10 9\n"
]
],
[
[
"Separate from the columns and index of a `DataFrame`, we can also directly access the values they contain by looking at the values attribute.",
"_____no_output_____"
]
],
[
[
"numbers.values",
"_____no_output_____"
]
],
[
[
"This returns a NumPy array.",
"_____no_output_____"
]
],
[
[
"type(numbers.values)",
"_____no_output_____"
]
],
[
[
"#### Accessing `DataFrame` elements\n\nAgain we see a lot of carryover from `Series` in how we access the elements of `DataFrames`. The key sticking point here is that everything has to take into account multiple dimensions now. The main way that this happens is through the access of the columns of a `DataFrame`, either individually or in groups. We can do this either by directly accessing the attributes or by using the methods we already are familiar with.",
"_____no_output_____"
],
[
"Let's start by loading price data for several securities:",
"_____no_output_____"
]
],
[
[
"securities = get_securities(symbols=['XOM', 'JNJ', 'MON', 'KKD'], vendors='usstock')\nsecurities",
"_____no_output_____"
]
],
[
[
"Since `get_securities` returns sids in the index, we can call the index's `tolist()` method to pass a list of sids to `get_prices`:",
"_____no_output_____"
]
],
[
[
"start = \"2012-01-01\"\nend = \"2017-01-01\"\n\nprices = get_prices(\"usstock-free-1min\", data_frequency=\"daily\", sids=securities.index.tolist(), start_date=start, end_date=end, fields=\"Close\")\nprices = prices.loc[\"Close\"]\nprices.head()",
"_____no_output_____"
]
],
[
[
"For the purpose of this tutorial, it will be more convenient to reference the data by symbol instead of sid. To do this, we can create a Python dictionary mapping sid to symbol, and use the dictionary to rename the columns, using the DataFrame's `rename` method: ",
"_____no_output_____"
]
],
[
[
"sids_to_symbols = securities.Symbol.to_dict()\nprices = prices.rename(columns=sids_to_symbols)\nprices.head()",
"_____no_output_____"
]
],
[
[
"Here we directly access the `XOM` column. Note that this style of access will only work if your column name has no spaces or unfriendly characters in it.",
"_____no_output_____"
]
],
[
[
"prices.XOM.head()",
"_____no_output_____"
]
],
[
[
"We can also access the column using the column name in brackets:",
"_____no_output_____"
]
],
[
[
"prices[\"XOM\"].head()",
"_____no_output_____"
]
],
[
[
"We can also use `loc[]` to access an individual column like so.",
"_____no_output_____"
]
],
[
[
"prices.loc[:, 'XOM'].head()",
"_____no_output_____"
]
],
[
[
"Accessing an individual column will return a `Series`, regardless of how we get it.",
"_____no_output_____"
]
],
[
[
"print(type(prices.XOM))\nprint(type(prices.loc[:, 'XOM']))",
"<class 'pandas.core.series.Series'>\n<class 'pandas.core.series.Series'>\n"
]
],
[
[
"Notice how we pass a tuple into the `loc[]` method? This is a key difference between accessing a `Series` and accessing a `DataFrame`, grounded in the fact that a `DataFrame` has multiple dimensions. When you pass a 2-dimensional tuple into a `DataFrame`, the first element of the tuple is applied to the rows and the second is applied to the columns. So, to break it down, the above line of code tells the `DataFrame` to return every single row of the column with label `'XOM'`. Lists of columns are also supported.",
"_____no_output_____"
]
],
[
[
"prices.loc[:, ['XOM', 'JNJ']].head()",
"_____no_output_____"
]
],
[
[
"We can also simply access the `DataFrame` by index value using `loc[]`, as with `Series`.",
"_____no_output_____"
]
],
[
[
"prices.loc['2015-12-15':'2015-12-22']",
"_____no_output_____"
]
],
[
[
"This plays nicely with lists of columns, too.",
"_____no_output_____"
]
],
[
[
"prices.loc['2015-12-15':'2015-12-22', ['XOM', 'JNJ']]",
"_____no_output_____"
]
],
[
[
"Using `iloc[]` also works similarly, allowing you to access parts of the `DataFrame` by integer index.",
"_____no_output_____"
]
],
[
[
"prices.iloc[0:2, 1]",
"_____no_output_____"
],
[
"# Access prices with integer index in\n# [1, 3, 5, 7, 9, 11, 13, ..., 99]\n# and in column 0 or 2\nprices.iloc[[1, 3, 5] + list(range(7, 100, 2)), [0, 2]].head(20)",
"_____no_output_____"
]
],
[
[
"#### Boolean indexing\n\nAs with `Series`, sometimes we want to filter a `DataFrame` according to a set of criteria. We do this by indexing our `DataFrame` with boolean values.",
"_____no_output_____"
]
],
[
[
"prices.loc[prices.MON > prices.JNJ].head()",
"_____no_output_____"
]
],
[
[
"We can add multiple boolean conditions by using the logical operators `&`, `|`, and `~` (and, or, and not, respectively) again!",
"_____no_output_____"
]
],
[
[
"prices.loc[(prices.MON > prices.JNJ) & ~(prices.XOM > 66)].head()",
"_____no_output_____"
]
],
[
[
"#### Adding, Removing Columns, Combining `DataFrames`/`Series`\n\nIt is all well and good when you already have a `DataFrame` filled with data, but it is also important to be able to add to the data that you have.\n\nWe add a new column simply by assigning data to a column that does not already exist. Here we use the `.loc[:, 'COL_NAME']` notation and store the output of `get_pricing()` (which returns a pandas `Series` if we only pass one security) there. This is the method that we would use to add a `Series` to an existing `DataFrame`.",
"_____no_output_____"
]
],
[
[
"securities = get_securities(symbols=\"AAPL\", vendors='usstock')\nsecurities",
"_____no_output_____"
],
[
"AAPL = securities.index[0]\n\ns_1 = get_prices(\"usstock-free-1min\", data_frequency=\"daily\", sids=AAPL, start_date=start, end_date=end, fields='Close').loc[\"Close\"][AAPL]\nprices.loc[:, AAPL] = s_1\nprices.head(5)",
"_____no_output_____"
]
],
[
[
"It is also just as easy to remove a column.",
"_____no_output_____"
]
],
[
[
"prices = prices.drop(AAPL, axis=1)\nprices.head(5)",
"_____no_output_____"
]
],
[
[
"#### Time Series Analysis with pandas\n\nUsing the built-in statistics methods for `DataFrames`, we can perform calculations on multiple time series at once! The code to perform calculations on `DataFrames` here is almost exactly the same as the methods used for `Series` above, so don't worry about re-learning everything.\n\nThe `plot()` method makes another appearance here, this time with a built-in legend that corresponds to the names of the columns that you are plotting.",
"_____no_output_____"
]
],
[
[
"prices.plot()\nplt.title(\"Collected Stock Prices\")\nplt.ylabel(\"Price\")\nplt.xlabel(\"Date\");",
"_____no_output_____"
]
],
[
[
"The same statistical functions from our interactions with `Series` resurface here with the addition of the `axis` parameter. By specifying the `axis`, we tell pandas to calculate the desired function along either the rows (`axis=0`) or the columns (`axis=1`). We can easily calculate the mean of each columns like so:",
"_____no_output_____"
]
],
[
[
"prices.mean(axis=0)",
"_____no_output_____"
]
],
[
[
"As well as the standard deviation:",
"_____no_output_____"
]
],
[
[
"prices.std(axis=0)",
"_____no_output_____"
]
],
[
[
"Again, the `describe()` function will provide us with summary statistics of our data if we would rather have all of our typical statistics in a convenient visual instead of calculating them individually.",
"_____no_output_____"
]
],
[
[
"prices.describe()",
"_____no_output_____"
]
],
[
[
"We can scale and add scalars to our `DataFrame`, as you might suspect after dealing with `Series`. This again works element-wise.",
"_____no_output_____"
]
],
[
[
"(2 * prices - 50).head(5)",
"_____no_output_____"
]
],
[
[
"Here we use the `pct_change()` method to get a `DataFrame` of the multiplicative returns of the securities that we are looking at.",
"_____no_output_____"
]
],
[
[
"mult_returns = prices.pct_change()[1:]\nmult_returns.head()",
"_____no_output_____"
]
],
[
[
"If we use our statistics methods to standardize the returns, a common procedure when examining data, then we can get a better idea of how they all move relative to each other on the same scale.",
"_____no_output_____"
]
],
[
[
"norm_returns = (mult_returns - mult_returns.mean(axis=0))/mult_returns.std(axis=0)\nnorm_returns.loc['2014-01-01':'2015-01-01'].plot();",
"_____no_output_____"
]
],
[
[
"This makes it easier to compare the motion of the different time series contained in our example.",
"_____no_output_____"
],
[
"Rolling means and standard deviations also work with `DataFrames`.",
"_____no_output_____"
]
],
[
[
"rolling_mean = prices.rolling(30).mean()\nrolling_mean.columns = prices.columns",
"_____no_output_____"
],
[
"rolling_mean.plot()\nplt.title(\"Rolling Mean of Prices\")\nplt.xlabel(\"Date\")\nplt.ylabel(\"Price\")\nplt.legend();",
"_____no_output_____"
]
],
[
[
"For a complete list of all the methods that are built into `DataFrame`s, check out the [documentation](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html).",
"_____no_output_____"
],
[
"# Next Steps\n\nManaging data gets a lot easier when you deal with pandas, though this has been a very general introduction. There are many more tools within the package which you may discover while trying to get your data to do precisely what you want. If you would rather read more on the additional capabilities of pandas, check out the [documentation](http://pandas.pydata.org/pandas-docs/stable/).",
"_____no_output_____"
],
[
"---\n\n**Next Lecture:** [Plotting Data](Lecture05-Plotting-Data.ipynb) \n\n[Back to Introduction](Introduction.ipynb) ",
"_____no_output_____"
],
[
"---\n\n*This presentation is for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation for any security; nor does it constitute an offer to provide investment advisory or other services by Quantopian, Inc. (\"Quantopian\") or QuantRocket LLC (\"QuantRocket\"). Nothing contained herein constitutes investment advice or offers any opinion with respect to the suitability of any security, and any views expressed herein should not be taken as advice to buy, sell, or hold any security or as an endorsement of any security or company. In preparing the information contained herein, neither Quantopian nor QuantRocket has taken into account the investment needs, objectives, and financial circumstances of any particular investor. Any views expressed and data illustrated herein were prepared based upon information believed to be reliable at the time of publication. Neither Quantopian nor QuantRocket makes any guarantees as to their accuracy or completeness. All information is subject to change and may quickly become unreliable for various reasons, including changes in market conditions or economic circumstances.*",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
e77de4ceeae58a6c564fd4277f07128817348810 | 807,769 | ipynb | Jupyter Notebook | notebooks/metacal_stats.ipynb | heather999/metacallEval | cbad06f9578ac472581fd026965853bf9a1b6428 | [
"BSD-3-Clause"
] | null | null | null | notebooks/metacal_stats.ipynb | heather999/metacallEval | cbad06f9578ac472581fd026965853bf9a1b6428 | [
"BSD-3-Clause"
] | null | null | null | notebooks/metacal_stats.ipynb | heather999/metacallEval | cbad06f9578ac472581fd026965853bf9a1b6428 | [
"BSD-3-Clause"
] | null | null | null | 594.384842 | 237,809 | 0.695835 | [
[
[
"import pathlib\nimport datetime\nimport sys\nimport re\nimport collections\nimport json",
"_____no_output_____"
],
[
"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport bokeh\nimport bokeh.plotting as bkh\nimport bokeh.models as bkhmodels\nfrom bokeh.plotting import figure\nfrom bokeh.io import output_notebook, show, output_file\nfrom bokeh.models import ColumnDataSource, HoverTool, Panel\nbkh.output_notebook()",
"_____no_output_____"
]
],
[
[
"# Metacal Log JSON data\n\n| columns | Description |\n|---------------------|------------------------------------------------------------|\n| tract | |\n| patch | |\n| cputime | CPU time returned by SRS |\n| cputimeseconds | CPU time returned by SRS in seconds |\n| deblendedsources | Number of Deblended Sources |\n| metcalmax_success | True if processDeblendedCoaddsMetacalMax ended successfully| \n| metacalmax_time | Running time (minutes) of processDeblendedCoaddsMetacalMax |\n| metacalmax_timeper | Running time (seconds) per source |\n| ngmixmax_success | True if processDeblendedCoaddsNGMixMax ended successfully |\n| ngmixmax_time | Running time (minutes) of processDeblendedCoaddsNGMixMax |\n| ngmixmax_timeper | Running time (seconds) per source |\n| maxfev | Set to True if calls to functin has reached maxfev logged |\n| maxfevstr | if maxfev==True, stores the full log message |\n| slots | Number of cores used for this job, expect it is alwasy 1 |\n| skiptract | Set to True if Skipping tract message was logged |\n| skiptracttstr | if skiptract==True, stores the full log message |",
"_____no_output_____"
]
],
[
[
"# Read metacal log data\ndf = pd.DataFrame()\n#df = pd.read_json('/global/cfs/cdirs/lsst/groups/CO/heatherk/Run2.2i/metacal/metacalEval/data/metacal_logs.json', convert_dates=False)\ndf = pd.read_json('../data/metacal_logs.json', convert_dates=False)",
"_____no_output_____"
],
[
"# Read coadd ?,?_nImage.fits data\ndf_coadds = pd.DataFrame()\ndf_coadds.append(pd.read_json('../data/g_band.json'))\ndf_coadds.append(pd.read_json('../data/i_band.json'))\ndf_coadds.append(pd.read_json('../data/r_band.json'))\ndf_coadds.append(pd.read_json('../data/i_band.json'))",
"_____no_output_____"
],
[
"#with open('/global/cfs/cdirs/lsst/groups/CO/heatherk/Run2.2i/metacal/metacalEval/data/metacal_logs.json') as f:\n# data = json.load(f)\n# print(data)",
"_____no_output_____"
],
[
"print(df)\ndf['cpuminutes'] = df.apply(lambda row: row.cpuseconds/60.0, axis = 1) \ncolumns = sorted(list(df))\nprint(columns)",
" logfile \\\n0 /global/cfs/cdirs/lsst/groups/CO/heatherk/Run2... \n1 /global/cfs/cdirs/lsst/groups/CO/heatherk/Run2... \n2 /global/cfs/cdirs/lsst/groups/CO/heatherk/Run2... \n3 /global/cfs/cdirs/lsst/groups/CO/heatherk/Run2... \n4 /global/cfs/cdirs/lsst/groups/CO/heatherk/Run2... \n... ... \n3501 /global/cfs/cdirs/lsst/groups/CO/heatherk/Run2... \n3502 /global/cfs/cdirs/lsst/groups/CO/heatherk/Run2... \n3503 /global/cfs/cdirs/lsst/groups/CO/heatherk/Run2... \n3504 /global/cfs/cdirs/lsst/groups/CO/heatherk/Run2... \n3505 /global/cfs/cdirs/lsst/groups/CO/heatherk/Run2... \n\n date deblendedsources metacalmax_success \\\n0 Wed May 27 12:40:17 CEST 2020 1248.0 True \n1 Wed May 27 12:40:06 CEST 2020 1010.0 True \n2 Thu Apr 16 13:19:37 CEST 2020 962.0 True \n3 Thu Apr 16 13:19:39 CEST 2020 1010.0 True \n4 Wed May 27 12:40:16 CEST 2020 954.0 True \n... ... ... ... \n3501 Wed Jun 03 08:22:20 CEST 2020 1810.0 True \n3502 Wed Apr 29 06:11:11 CEST 2020 3903.0 True \n3503 Wed Apr 29 06:10:52 CEST 2020 697.0 True \n3504 Wed Jun 03 08:22:19 CEST 2020 2743.0 True \n3505 Wed Apr 29 06:11:11 CEST 2020 2743.0 True \n\n metacalmax_detections metacalmax_time metacalmax_time_units \\\n0 1248.0 2.555770 min \n1 1010.0 0.759778 min \n2 962.0 1.022470 min \n3 1010.0 1.043080 min \n4 954.0 0.235491 min \n... ... ... ... \n3501 1810.0 6.950770 min \n3502 3903.0 48.756900 min \n3503 697.0 1.070220 min \n3504 2743.0 25.984900 min \n3505 2743.0 31.225400 min \n\n metacalmax_timeper metacalmax_timeper_units ngmixmax_success ... \\\n0 0.122775 sec True ... \n1 0.045091 sec True ... \n2 0.063705 sec True ... \n3 0.061904 sec True ... \n4 0.014795 sec True ... \n... ... ... ... ... \n3501 0.230285 sec True ... \n3502 0.749338 sec True ... \n3503 0.091996 sec True ... \n3504 0.568182 sec True ... \n3505 0.682771 sec True ... \n\n skiptract skipttractstr cputime cpuseconds vmem vmemunits \\\n0 False None 00:06:38 398.0 2.669 GB \n1 False None 00:04:36 276.0 3.819 GB \n2 False None 00:04:32 272.0 2.494 GB \n3 False None 00:06:35 395.0 2.710 GB \n4 False None 00:01:53 113.0 2.536 GB \n... ... ... ... ... ... ... \n3501 False None 00:12:42 762.0 2.609 GB \n3502 False None 01:18:25 4705.0 2.749 GB \n3503 False None 00:04:39 279.0 2.619 GB \n3504 False None 00:41:34 2494.0 2.547 GB \n3505 False None 00:50:19 3019.0 2.742 GB \n\n maxvmem maxvmemunits maxrss maxrssunits \n0 3.870 GB 1.371 GB \n1 3.892 GB 1.441 GB \n2 3.632 GB 1.324 GB \n3 3.962 GB 1.407 GB \n4 3.661 GB 1.310 GB \n... ... ... ... ... \n3501 3.847 GB 1.413 GB \n3502 4.378 GB 1.787 GB \n3503 3.743 GB 1.306 GB \n3504 3.988 GB 1.613 GB \n3505 4.320 GB 1.612 GB \n\n[3506 rows x 31 columns]\n['cpuminutes', 'cpuseconds', 'cputime', 'date', 'deblendedsources', 'logfile', 'maxfev', 'maxfevstr', 'maxrss', 'maxrssunits', 'maxvmem', 'maxvmemunits', 'metacalmax_detections', 'metacalmax_success', 'metacalmax_time', 'metacalmax_time_units', 'metacalmax_timeper', 'metacalmax_timeper_units', 'ngmixmax_detections', 'ngmixmax_success', 'ngmixmax_time', 'ngmixmax_time_units', 'ngmixmax_timeper', 'ngmixmax_timeper_units', 'patch', 'skiptract', 'skipttractstr', 'slots', 'streampath', 'tract', 'vmem', 'vmemunits']\n"
],
[
"print(df.shape)",
"(3506, 32)\n"
]
],
[
[
"# CPU Time vs Number of Deblended Sources",
"_____no_output_____"
]
],
[
[
"df.loc[(df['metacalmax_success']==True)&(df['ngmixmax_success']==True),\"deblendedsources\"].max()",
"_____no_output_____"
],
[
"# Focus on jobs where both processDeblendedCoaddsMetacalMax and processDeblendedCoaddsNGMixMax ran to completion successfully\n\nsuccessful_jobs = df.loc[(df['metacalmax_success'] == True)&(df['ngmixmax_success']==True)]\n\nsuccessful_jobs.loc[(successful_jobs['metacalmax_success']==True)&(successful_jobs['ngmixmax_success']==True),\"metacalmax_time\"].max()\n",
"_____no_output_____"
],
[
"successful_jobs.loc[(successful_jobs['metacalmax_success']==True)&(successful_jobs['ngmixmax_success']==True),\"metacalmax_time\"].min()\n",
"_____no_output_____"
],
[
"successful_jobs.loc[(successful_jobs['metacalmax_success']==True)&(successful_jobs['ngmixmax_success']==True),\"metacalmax_time\"].median()\n",
"_____no_output_____"
],
[
"# shamelessly \"borrowed\" \n\ndef hist_hover(dataframe, column, colors=[\"SteelBlue\", \"Tan\"], bins=30, log_scale=False, show_plot=True):\n\n # build histogram data with Numpy\n hist, edges = np.histogram(dataframe[column], bins = bins)\n hist_df = pd.DataFrame({column: hist,\n \"left\": edges[:-1],\n \"right\": edges[1:]})\n hist_df[\"interval\"] = [\"%d to %d\" % (left, right) for left, \n right in zip(hist_df[\"left\"], hist_df[\"right\"])]\n\n # bokeh histogram with hover tool\n if log_scale == True:\n hist_df[\"log\"] = np.log(hist_df[column])\n src = ColumnDataSource(hist_df)\n plot = figure(plot_height = 600, plot_width = 600,\n title = \"Histogram of {}\".format(column.capitalize()),\n x_axis_label = column.capitalize(),\n y_axis_label = \"Log Count\") \n plot.quad(bottom = 0, top = \"log\",left = \"left\", \n right = \"right\", source = src, fill_color = colors[0], \n line_color = \"black\", fill_alpha = 0.7,\n hover_fill_alpha = 1.0, hover_fill_color = colors[1])\n else:\n src = bkh.ColumnDataSource(hist_df)\n plot = bkh.figure(plot_height = 600, plot_width = 600,\n title = \"Histogram of {}\".format(column.capitalize()),\n x_axis_label = column.capitalize(),\n y_axis_label = \"Count\") \n plot.quad(bottom = 0, top = column,left = \"left\", \n right = \"right\", source = src, fill_color = colors[0], \n line_color = \"black\", fill_alpha = 0.7,\n hover_fill_alpha = 1.0, hover_fill_color = colors[1])\n # hover tool\n hover = bkhmodels.HoverTool(tooltips = [('Interval', '@interval'),\n ('Count', str(\"@\" + column))])\n plot.add_tools(hover)\n # output\n if show_plot == True:\n bkh.show(plot)\n else:\n return plot\n\n",
"_____no_output_____"
],
[
"# There were some jobs where number of deblended sources was NaN - need to look at that, but for now, just discarding\n\nnonan_jobs = successful_jobs.loc[(successful_jobs['deblendedsources'].notna())]\n\nhist_hover(nonan_jobs.fillna(value=-1,axis=1),\"deblendedsources\", bins=100)",
"_____no_output_____"
],
[
"hist_hover(nonan_jobs, \"cpuseconds\", bins=100)\nhist_hover(nonan_jobs, \"cpuminutes\", bins=100)",
"_____no_output_____"
],
[
"hist_hover(nonan_jobs, \"metacalmax_time\", bins=100)",
"_____no_output_____"
],
[
"def hist2d_hover(dataframe, xcol, ycol, title, xaxis, yaxis, colors=[\"SteelBlue\", \"Tan\"], bins=30, show_plot=True):\n p = bkh.figure()\n p.scatter(x=xcol, y=ycol,\n source=dataframe,\n size=10, color='green')\n p.title.text = title\n p.xaxis.axis_label = xaxis\n p.yaxis.axis_label = yaxis\n hover = HoverTool()\n hover.tooltips=[\n ('CPUseconds', '@cpuseconds'),\n ('tract', '@tract'),\n ('patch', '@patch'),\n ('metacalMax Time (min)', '@metacalmax_time'),\n ('ngmixMax Time (min)', '@ngmixmax_time') \n ]\n\n p.add_tools(hover)\n if show_plot == True:\n show(p)\n else:\n return p",
"_____no_output_____"
],
[
"hist2d_hover(nonan_jobs,'metacalmax_time', 'deblendedsources', \"metacalMax Time vs Deblended Sources\", \"metacalMax Time (min)\", \"Number of Deblended Sources\" )",
"_____no_output_____"
],
[
"hist2d_hover(nonan_jobs,'ngmixmax_time', 'deblendedsources', \"ngmixMax Time vs Deblended Sources\", \"ngmixMax Time (min)\", \"Number of Deblended Sources\" )",
"_____no_output_____"
],
[
"hist2d_hover(nonan_jobs,'cpuminutes', 'deblendedsources', \"Total CPU Time vs Deblended Sources\", \"CPU Time (min)\", \"Number of Deblended Sources\" )",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e77dff2b63e937b4566c298042b0a87007b54cc5 | 11,858 | ipynb | Jupyter Notebook | kickstarter_02_preparation.ipynb | dominikmn/ds-kickstarter-project | 55ea3e8deb5b3bb337e0ec6ff1c0bdb932c247f3 | [
"MIT"
] | 1 | 2021-04-14T19:29:37.000Z | 2021-04-14T19:29:37.000Z | kickstarter_02_preparation.ipynb | mue94/ds-kickstarter-project | a3dc66f58186f7936269c7dee1124c11ae8ef5b3 | [
"MIT"
] | null | null | null | kickstarter_02_preparation.ipynb | mue94/ds-kickstarter-project | a3dc66f58186f7936269c7dee1124c11ae8ef5b3 | [
"MIT"
] | 1 | 2021-03-15T09:46:34.000Z | 2021-03-15T09:46:34.000Z | 29.206897 | 192 | 0.481194 | [
[
[
"import pandas as pd\nimport numpy as np\nfrom datetime import datetime",
"_____no_output_____"
],
[
"def save_dataframe(data, file_name=None):\n if file_name:\n e = file_name\n else:\n t = datetime.now().strftime(\"%Y-%m-%d_%H%M%S\")\n e = f\"./data_frame_{t}.pickle\"\n print('Saving: '+e)\n data.to_pickle(e)",
"_____no_output_____"
],
[
"df_new = pd.read_pickle(\"./data_frame_raw_2021-03-12.pickle\")",
"_____no_output_____"
]
],
[
[
"# Extended data frame",
"_____no_output_____"
]
],
[
[
"df_new['duration'] = (df_new.deadline-df_new.launched_at)/(3600*24)\ndf_new['duration'] = df_new['duration'].round(2)",
"_____no_output_____"
],
[
"df_new['goal_usd'] = df_new['goal'] * df_new['static_usd_rate']\ndf_new['goal_usd'] = df_new['goal_usd'].round(2)",
"_____no_output_____"
],
[
"#df_new['launched_at_full'] = pd.to_datetime(df_new['launched_at'], unit='s')\ndf_new['launched_at_full'] = pd.to_datetime(df_new['launched_at'], unit='s')\ndf_new['launched_at_year'] = pd.DatetimeIndex(df_new['launched_at_full']).year\ndf_new['launched_at_month'] = pd.DatetimeIndex(df_new['launched_at_full']).month",
"_____no_output_____"
],
[
"df_new['created_at_full'] = pd.to_datetime(df_new['created_at'], unit='s')\ndf_new['created_at_year'] = pd.DatetimeIndex(df_new['created_at_full']).year\ndf_new['created_at_month'] = pd.DatetimeIndex(df_new['created_at_full']).month",
"_____no_output_____"
],
[
"df_new['deadline_full'] = pd.to_datetime(df_new['deadline'], unit='s')\ndf_new['deadline_year'] = pd.DatetimeIndex(df_new['deadline_full']).year\ndf_new['deadline_month'] = pd.DatetimeIndex(df_new['deadline_full']).month",
"_____no_output_____"
],
[
"from math import isnan\ncategory_dict = pd.Series(df_new['category_name'].values,index=df_new['category_id']).to_dict()\ndef parent_cat_mapper(row):\n if isnan(row['category_parent_id']):\n return row['category_name']\n else:\n return category_dict[row['category_parent_id']]",
"_____no_output_____"
],
[
"category_parent_name = df_new.apply(parent_cat_mapper, axis=1)\ndf_new['category_parent_name'] = category_parent_name",
"_____no_output_____"
],
[
"df_new.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 209222 entries, 0 to 209221\nColumns: 108 entries, backers_count to category_parent_name\ndtypes: bool(5), datetime64[ns](3), float64(18), int64(16), object(66)\nmemory usage: 165.4+ MB\n"
]
],
[
[
"### Save frame",
"_____no_output_____"
]
],
[
[
"save_dataframe(df_new, './data_frame_full_2021-03-12.pickle')",
"_____no_output_____"
]
],
[
[
"# Reduced data frame",
"_____no_output_____"
]
],
[
[
"for i , val in df_new.iloc[60060,:].items():\n print(i)\n print(val)\n print()",
"_____no_output_____"
],
[
"survival_lst = ['backers_count', 'blurb', 'country', 'created_at', 'currency', 'deadline','disable_communication', 'goal', 'launched_at','name', 'staff_pick','state', \n 'usd_pledged','usd_type','category_id','category_name','category_slug','category_parent_id', 'category_parent_name', 'location_id', 'location_name','location_type', \n 'photo_key', 'photo_full', 'duration', 'goal_usd', \n 'launched_at_full', 'launched_at_year', 'launched_at_month', 'created_at_full', 'created_at_year', 'created_at_month', 'deadline_full', 'deadline_year', 'deadline_month']",
"_____no_output_____"
],
[
"df_eda = df_new[survival_lst]",
"_____no_output_____"
],
[
"save_dataframe(df_eda, './data_frame_small_2021-03-12.pickle')",
"Saving: ./data_frame_small_2021-03-12.pickle\n"
],
[
"df_eda.head(2)",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
e77e00a8668a1b71d72c15fecfc627226ee007cd | 95,429 | ipynb | Jupyter Notebook | notebooks/two_asset.ipynb | gboehl/sequence-jacobian | 01d177cc254a2ccee57a3ed273117bea58554be2 | [
"MIT"
] | null | null | null | notebooks/two_asset.ipynb | gboehl/sequence-jacobian | 01d177cc254a2ccee57a3ed273117bea58554be2 | [
"MIT"
] | null | null | null | notebooks/two_asset.ipynb | gboehl/sequence-jacobian | 01d177cc254a2ccee57a3ed273117bea58554be2 | [
"MIT"
] | null | null | null | 124.743791 | 27,074 | 0.854363 | [
[
[
"# Tutorial 4: A two-asset HANK model\n\nIn this notebook we solve the two-asset HANK model from Auclert, Bardóczy, Rognlie, Straub (2021): \"Using the Sequence-Space Jacobian to Solve and Estimate Heterogeneous-Agent Models\" ([link to paper](https://www.bencebardoczy.com/publication/sequence-jacobian/sequence-jacobian.pdf)).\n\nNew concepts:\n- **Solved block**: an extension of simple blocks that enables much more efficient DAG representations of large macro models.\n- **Re-using saved Jacobians**: as the cost of these computations becomes non-trivial, avoiding redundancy becomes key.\n- **Fine-tuning options**: how to access and modify various options for each (block, method) pair\n\nFor more examples and information on the SSJ toolkit, please visit our [GitHub page](https://github.com/shade-econ/sequence-jacobian).",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sequence_jacobian import simple, solved, combine, create_model # functions\nfrom sequence_jacobian import grids, hetblocks # modules",
"_____no_output_____"
]
],
[
[
"## 1 Model description\n\nThe household problem is characterized by the Bellman equation\n$$\n\\begin{align} \\tag{1}\nV_t(e, b_{-}, a_{-}) = \\max_{c, b, a} &\\left\\{\\frac{c^{1-\\sigma}}{1-\\sigma} + \\beta \\mathbb{E}_t V_{t+1}(e', b, a) \\right\\}\n\\\\\nc + a + b &= z_t(e) + (1 + r_t^a)a_{-} + (1 + r_t^b)b_{-} - \\Psi(a, a_{-}) \n\\\\\na &\\geq \\underline{a}, \\quad b \\geq \\underline{b},\n\\end{align}\n$$\n\nwhere $z_t(e)$ is labor income and the adjustment cost function is specified as\n\n$$\n\\Psi(a, a_{-}) = \\frac{\\chi_1}{\\chi_2}\\left|\\frac{a - (1 + r_t^a) a_{-}}{(1 + r_{t}^a) a_{-} + \\chi_0}\\right|^{\\chi_2} \\left[(1 + r_t^a) a_{-} + \\chi_0 \\right],\n$$\n\nwith $\\chi_0, \\chi_1 > 0$ and $\\chi_2 > 1.$ For the full description of the model, including the problems of the other agents, please see appendix B.3 of the paper.",
"_____no_output_____"
],
[
"We embed this household block in a New Keynesian model with sticky prices, sticky wages, and capital adjustment costs. Thanks to the **solved blocks** (in green), we can write a DAG for this model in just 3 unknowns $(r, w, Y)$ and 3 targets, asset market clearing, Fisher equation, wage Phillips curve.",
"_____no_output_____"
],
[
"## 2 Define solved blocks\n\nSolved blocks are miniature models embedded as blocks inside of our larger model. Like simple blocks, solved blocks correspond to aggregate equilibrium conditions: they map sequences of aggregate inputs directly into sequences of aggregate outputs. The difference is that in the case of simple blocks, this mapping has to be analytical, while solved blocks are designed to accommodate implicit relationships that can only be evaluated numerically. \n\nSuch implicit mappings between variables become more common as macro complexity increases. Solved blocks are a valuable tool to simplify the DAG of large macro models.",
"_____no_output_____"
],
[
"### 2.1 Price setting (NKPC-p)\nThe Phillips curve characterizes $(\\pi)$ conditional on $(Y, mc, r):$ \n\n$$\n\\log(1+\\pi_t) = \\kappa_p \\left(mc_t - \\frac{1}{\\mu_p} \\right) + \\frac{1}{1+r_{t+1}} \\frac{Y_{t+1}}{Y_t} \\log(1+\\pi_{t+1})\n$$\n\nInflation shows up with two different time displacements, which means that inflation in any given period depends on the entire sequence of $(Y, mc, r)$. Simple blocks are not meant to represent such relationships. Instead, we write a function that returns the residual of the equation, and use the decorator `@solved` to make it into a `SolvedBlock`.",
"_____no_output_____"
]
],
[
[
"@solved(unknowns={'pi': (-0.1, 0.1)}, targets=['nkpc'], solver=\"brentq\")\ndef pricing_solved(pi, mc, r, Y, kappap, mup):\n nkpc = kappap * (mc - 1/mup) + Y(+1) / Y * (1 + pi(+1)).apply(np.log) / \\\n (1 + r(+1)) - (1 + pi).apply(np.log)\n return nkpc",
"_____no_output_____"
]
],
[
[
"When our routines encounter a solved block in `blocks`, they compute its Jacobian via the the implicit function theorem, as if it was a model on its own. Given the Jacobian, the rest of the code applies without modification. ",
"_____no_output_____"
],
[
"### 2.2 Equity price (equity & dividend)\nThe no arbitrage condition characterizes $(p)$ conditional on $(d, p, r).$\n\n$$\np_t = \\frac{d_{t+1} + p_{t+1}}{1 + r_{t+1}}\n$$",
"_____no_output_____"
]
],
[
[
"@solved(unknowns={'p': (5, 15)}, targets=['equity'], solver=\"brentq\")\ndef arbitrage_solved(div, p, r):\n equity = div(+1) + p(+1) - p * (1 + r(+1))\n return equity",
"_____no_output_____"
]
],
[
[
"### 2.3 Investment with adjustment costs (prod)\n\nSometimes multiple equilibrium conditions can be combined in a self-contained solved block. Investment subject to capital adjustment costs is such a case. In particular, we can use the following four equations to solve for $(K, Q)$ conditional on $(Y, w, r)$.\n \n - Production:\n \n $$\n Y_t = Z_t K_{t-1}^\\alpha N_t^{1-\\alpha}\n $$\n \n - Labor demand:\n \n $$\n w_t = (1-\\alpha)\\frac{Y_t}{N_t} mc_t\n $$\n \n - Investment equation:\n\n$$\nQ_t = 1 + \\frac{1}{\\delta \\epsilon_I}\\left(\\frac{K_t-K_{t-1}}{K_{t-1}}\\right)\n$$\n\n- Valuation equation\n\n$$\n(1+r_{t})Q_{t} = \\alpha Z_{t+1} \\left(\\frac{N_{t+1}}{K_t}\\right)^{1-\\alpha} mc_{t+1} - \\left[\\frac{K_{t+1}}{K_t} - (1-\\delta) + \\frac{1}{2\\delta \\epsilon_I}\\left(\\frac{K_{t+1} - K_t}{K_t}\\right)^2\\right] + \\frac{K_{t+1}}{K_t}Q_{t+1}\n$$",
"_____no_output_____"
],
[
"Solved blocks that contain multiple simple blocks have to be initialized with the `CombinedBlock.solved` method instead of the decorator `@solved`.",
"_____no_output_____"
]
],
[
[
"@simple\ndef labor(Y, w, K, Z, alpha):\n N = (Y / Z / K(-1) ** alpha) ** (1 / (1 - alpha))\n mc = w * N / (1 - alpha) / Y\n return N, mc\n\n\n@simple\ndef investment(Q, K, r, N, mc, Z, delta, epsI, alpha):\n inv = (K / K(-1) - 1) / (delta * epsI) + 1 - Q\n val = alpha * Z(+1) * (N(+1) / K) ** (1 - alpha) * mc(+1) -\\\n (K(+1) / K - (1 - delta) + (K(+1) / K - 1) ** 2 / (2 * delta * epsI)) +\\\n K(+1) / K * Q(+1) - (1 + r(+1)) * Q\n return inv, val\n\n\nproduction = combine([labor, investment]) # create combined block\nproduction_solved = production.solved(unknowns={'Q': 1., 'K': 10.}, # turn it into solved block\n targets=['inv', 'val'],\n solver='broyden_custom')",
"_____no_output_____"
]
],
[
[
"## 3 Build DAGs\n\nOne for transition dynamics (pictured above) and one for calibrating the steady state.\n\n### Step 1: Adapt HA block\n\nWe developed an efficient backward iteration function to solve the Bellman equation in (1). Although we view this as a contribution on its own, discussing the algorithm goes beyond the scope of this notebook. If you are interested in how we solve a two-asset model with convex portfolio-adjustment costs in discrete time, please see appendix E of the paper for a detailed description and `sequence_jacobian/hetblocks/hh_twoasset.py` for the implementation.\n\nHere, we take this generic two-asset model off the shelf, and embed it in our New Keynesian model with the help of two hetinputs.",
"_____no_output_____"
]
],
[
[
"def make_grids(bmax, amax, kmax, nB, nA, nK, nZ, rho_z, sigma_z):\n b_grid = grids.agrid(amax=bmax, n=nB)\n a_grid = grids.agrid(amax=amax, n=nA)\n k_grid = grids.agrid(amax=kmax, n=nK)[::-1].copy()\n e_grid, _, Pi = grids.markov_rouwenhorst(rho=rho_z, sigma=sigma_z, N=nZ)\n return b_grid, a_grid, k_grid, e_grid, Pi\n\n\ndef income(e_grid, tax, w, N):\n z_grid = (1 - tax) * w * N * e_grid\n return z_grid\n\nhh = hetblocks.hh_twoasset.hh\nhh_ext = hh.add_hetinputs([income, make_grids])",
"_____no_output_____"
]
],
[
[
"### Step 2: Complete dynamic DAG with simple blocks\n\nWe have set up all the blocks in the `sequence_jacobian/examples/two_asset.py` module. We omit the step-by-step discussion of these blocks since they should be familiar from the other model notebooks.",
"_____no_output_____"
]
],
[
[
"import sequence_jacobian.examples.two_asset as m\n\nblocks = [hh_ext, production_solved, pricing_solved, arbitrage_solved,\n m.dividend, m.taylor, m.fiscal, m.share_value,\n m.finance, m.wage, m.union, m.mkt_clearing]\n\nhank = create_model(blocks, name='Two-Asset HANK')\n\nprint(*hank.blocks, sep='\\n')",
"<SolvedBlock 'labor_to_investment_combined_solved'>\n<SolvedBlock 'pricing_solved'>\n<SimpleBlock 'wage'>\n<SimpleBlock 'taylor'>\n<SimpleBlock 'dividend'>\n<SolvedBlock 'arbitrage_solved'>\n<SimpleBlock 'share_value'>\n<SimpleBlock 'finance'>\n<SimpleBlock 'fiscal'>\n<HetBlock 'hh' with hetinput 'make_grids_marginal_cost_grid' and with hetoutput `adjustment_costs'>\n<SimpleBlock 'union'>\n<SimpleBlock 'mkt_clearing'>\n"
]
],
[
[
"### Step 3: Complete calibration DAG\n\nAnalytical:\n- find TFP `Z` to hit target for output `Y`\n- find markup `mup` to hit target for total wealth `p + Bg`\n- find capital share `alpha` to hit target for capital `K`\n- find wage `w` to hit Phillips curve given zero inflation \n- find disutility of labor `vphi` to hit wage Phillips curve given a target for employment\n\nNumerical:\n- find discount factor `beta` to satisfy asset market clearing given an interest rate `r`\n- find adjustment cost scale `chi1` to hit target for average liquid wealth `Bh`",
"_____no_output_____"
]
],
[
[
"blocks_ss = [hh_ext, m.partial_ss, m.union_ss,\n m.dividend, m.taylor, m.fiscal, m.share_value, m.finance, m.mkt_clearing]\n\nhank_ss = create_model(blocks_ss, name='Two-Asset HANK SS')\n\nprint(hank_ss)\nprint(f\"Inputs: {hank_ss.inputs}\")\n",
"<Model 'Two-Asset HANK SS'>\nInputs: ['beta', 'eis', 'chi0', 'chi1', 'chi2', 'N', 'bmax', 'amax', 'kmax', 'nB', 'nA', 'nK', 'nZ', 'rho_z', 'sigma_z', 'Y', 'K', 'r', 'tot_wealth', 'Bg', 'delta', 'muw', 'frisch', 'pi', 'kappap', 'epsI', 'rstar', 'phi', 'G', 'Bh', 'omega']\n"
]
],
[
[
"## 4 Results\n\nWe cover how to pass precomputed Jacobians to the main methods. This is useful when methods that need Jacobians are used repeatedly. These are\n- Solve methods: `solve_impulse_linear`, `solve_impulse_nonlinear`\n- Jacobian methods: `jacobian`, `solve_jacobian`\n\n### 4.1 Calibrate steady state\n\nUse the calibration DAG to internally calibrate the seven parameters (analytical + numerical). Evaluate the dynamic DAG at the resulting steady state `cali`. ",
"_____no_output_____"
]
],
[
[
"calibration = {'Y': 1., 'N': 1.0, 'K': 10., 'r': 0.0125, 'rstar': 0.0125, 'tot_wealth': 14,\n 'delta': 0.02, 'pi': 0., 'kappap': 0.1, 'muw': 1.1, 'Bh': 1.04, 'Bg': 2.8,\n 'G': 0.2, 'eis': 0.5, 'frisch': 1., 'chi0': 0.25, 'chi2': 2, 'epsI': 4,\n 'omega': 0.005, 'kappaw': 0.1, 'phi': 1.5, 'nZ': 3, 'nB': 50, 'nA': 70, 'nK': 50,\n 'bmax': 50, 'amax': 4000, 'kmax': 1, 'rho_z': 0.966, 'sigma_z': 0.92}\n\nunknowns_ss = {'beta': 0.976, 'chi1': 6.5}\ntargets_ss = {'asset_mkt': 0., 'B': 'Bh'}\n\ncali = hank_ss.solve_steady_state(calibration, unknowns_ss, targets_ss, solver='broyden_custom')",
"_____no_output_____"
]
],
[
[
"Verify solution, generate `ss` from dynamic DAG.",
"_____no_output_____"
]
],
[
[
"ss = hank.steady_state(cali)\n\nprint(f\"Liquid assets: {ss['B']: 0.2f}\")\nprint(f\"Asset market clearing: {ss['asset_mkt']: 0.2e}\")\nprint(f\"Goods market clearing (untargeted): {ss['goods_mkt']: 0.2e}\")",
"Liquid assets: 1.04\nAsset market clearing: 8.22e-13\nGoods market clearing (untargeted): 3.29e-08\n"
]
],
[
[
"### 4.2 Linearized impulse responses\n\nAs before, we can compute the general equilibrium Jacobians $G$ which is sufficient to map any shock into impulse responses. \n\nWhen the cost of computing a block Jacobian is non-trivial, it's a good idea to precompute it. We can supply block Jacobians for specific blocks via the `Js=` keyword argument. The precomputed Jacobians will only be used if they are **complete** (have all required inputs and outputs) and have the right **size** (truncation horizon).",
"_____no_output_____"
]
],
[
[
"exogenous = ['rstar', 'Z', 'G']\nunknowns = ['r', 'w', 'Y']\ntargets = ['asset_mkt', 'fisher', 'wnkpc']\nT = 300\n\nJ_ha = hh_ext.jacobian(ss, inputs=['N', 'r', 'ra', 'rb', 'tax', 'w'], T=T)\nG = hank.solve_jacobian(ss, unknowns, targets, exogenous, T=T, Js={'hh': J_ha})",
"_____no_output_____"
]
],
[
[
"The time saving from re-using the Jacobian of the household block is considerable.",
"_____no_output_____"
]
],
[
[
"%time G = hank.solve_jacobian(ss, unknowns, targets, exogenous, T=T, Js={'hh': J_ha})",
"Wall time: 433 ms\n"
],
[
"%time G = hank.solve_jacobian(ss, unknowns, targets, exogenous, T=T)",
"Wall time: 4.94 s\n"
]
],
[
[
"Note that some block Jacobians may be precomputed even if others are changing. For example, we can re-use `J_ha` while evalutating the model likelihood for 100,000 draws of price and wage adjustment cost.\n\nWhen we're not planning to change any part of the model, it's even better to store the `H_U` directly. (To be precise, we store the LU-factorized version of the matrix, which facilitates operations with its inverse.) That way, we save time on computing and packing all the block Jacobians. ",
"_____no_output_____"
]
],
[
[
"from sequence_jacobian.classes import FactoredJacobianDict\n\nH_U = hank.jacobian(ss, unknowns, targets, T=T, Js={'hh': J_ha})\nH_U_factored = FactoredJacobianDict(H_U, T)",
"_____no_output_____"
],
[
"%time G = hank.solve_jacobian(ss, unknowns, targets, exogenous, T=T, Js={'hh': J_ha}, H_U_factored=H_U_factored)",
"Wall time: 343 ms\n"
]
],
[
[
"Let's plot some impulse responses:",
"_____no_output_____"
]
],
[
[
"rhos = np.array([0.2, 0.4, 0.6, 0.8])\ndrstar = -0.0025 * rhos ** (np.arange(T)[:, np.newaxis])\ndY = 100 * G['Y']['rstar'] @ drstar\n\nplt.plot(dY[:21])\nplt.title(r'Output response to 25 bp monetary policy shocks with $\\rho=(0.2 ... 0.8)$')\nplt.xlabel('quarters')\nplt.ylabel('% deviation from ss')\nplt.show()",
"_____no_output_____"
]
],
[
[
"### 4.3 Nonlinear impulse responses\n\nLet's compute the nonlinear impulse response for the $\\rho=0.6$ shock above.\n- Don't forget to use the saved Jacobian.\n- Note how to look up and change options specific to (block type, method) pairs.",
"_____no_output_____"
]
],
[
[
"hank['pricing_solved'].solve_impulse_nonlinear_options",
"_____no_output_____"
]
],
[
[
"By default, `SolvedBlock.solve_impulse_linear` prints the error in each iteration (`verbose=True`). Let's turn this off for the internal solved blocks.",
"_____no_output_____"
]
],
[
[
"td_nonlin = hank.solve_impulse_nonlinear(ss, unknowns, targets, {\"rstar\": drstar[:, 2]},\n Js={'hh': J_ha}, H_U_factored=H_U_factored,\n options={'pricing_solved': {'verbose': False},\n 'arbitrage_solved': {'verbose': False},\n 'labor_to_investment_combined_solved': {'verbose': False}})",
"Solving Two-Asset HANK for ['r', 'w', 'Y'] to hit ['asset_mkt', 'fisher', 'wnkpc']\nOn iteration 0\n max error for asset_mkt is 3.92E-06\n max error for fisher is 2.50E-03\n max error for wnkpc is 4.72E-08\nOn iteration 1\n max error for asset_mkt is 2.66E-04\n max error for fisher is 1.55E-06\n max error for wnkpc is 2.15E-05\nOn iteration 2\n max error for asset_mkt is 7.56E-06\n max error for fisher is 9.69E-08\n max error for wnkpc is 6.57E-07\nOn iteration 3\n max error for asset_mkt is 4.01E-07\n max error for fisher is 2.24E-09\n max error for wnkpc is 1.64E-08\nOn iteration 4\n max error for asset_mkt is 2.20E-08\n max error for fisher is 1.06E-10\n max error for wnkpc is 7.46E-10\nOn iteration 5\n max error for asset_mkt is 1.23E-09\n max error for fisher is 5.44E-12\n max error for wnkpc is 3.72E-11\n"
]
],
[
[
"We see rapid convergence and mild nonlinearities in the solution.",
"_____no_output_____"
]
],
[
[
"dY_nonlin = 100 * td_nonlin['Y']\n\nplt.plot(dY[:21, 2], label='linear', linestyle='-', linewidth=2.5)\nplt.plot(dY_nonlin[:21], label='nonlinear', linestyle='--', linewidth=2.5)\nplt.title(r'Consumption response to 1% monetary policy shock')\nplt.xlabel('quarters')\nplt.ylabel('% deviation from ss')\nplt.legend()\nplt.show()",
"_____no_output_____"
]
],
[
[
"Alternatively, we can compute the impulse response to a version of the shock scaled down to 10% of its original size.",
"_____no_output_____"
]
],
[
[
"td_nonlin = hank.solve_impulse_nonlinear(ss, unknowns, targets, {\"rstar\": 0.1 * drstar[:, 2]},\n Js={'hh': J_ha},\n options={'pricing_solved': {'verbose': False},\n 'arbitrage_solved': {'verbose': False},\n 'labor_to_investment_combined_solved': {'verbose': False}})",
"Solving Two-Asset HANK for ['r', 'w', 'Y'] to hit ['asset_mkt', 'fisher', 'wnkpc']\nOn iteration 0\n max error for asset_mkt is 3.92E-06\n max error for fisher is 2.50E-04\n max error for wnkpc is 4.72E-08\nOn iteration 1\n max error for asset_mkt is 3.20E-06\n max error for fisher is 1.63E-08\n max error for wnkpc is 2.10E-06\nOn iteration 2\n max error for asset_mkt is 7.71E-08\n max error for fisher is 2.53E-10\n max error for wnkpc is 5.83E-09\nOn iteration 3\n max error for asset_mkt is 8.07E-10\n max error for fisher is 1.50E-12\n max error for wnkpc is 5.69E-11\n"
],
[
"dY_nonlin = 100 * td_nonlin['Y']\n\nplt.plot(0.1*dY[:21, 2], label='linear', linestyle='-', linewidth=2.5)\nplt.plot(dY_nonlin[:21], label='nonlinear', linestyle='--', linewidth=2.5)\nplt.title(r'Consumption response to 0.1% monetary policy shock')\nplt.xlabel('quarters')\nplt.ylabel('% deviation from ss')\nplt.legend()\nplt.show()",
"_____no_output_____"
]
],
[
[
"When the shock is this small, the linear and nonlinear impulse responses agree exactly. This is a good check, amid a highly complex model, that we didn't make any mistakes.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
e77e00fdc32e87fc1d7839963751d5240e02e447 | 48,779 | ipynb | Jupyter Notebook | ch04eval.ipynb | kanamori-takafumi/book_StatMachineLearn_with_Python | f3e6a55dc100a1f3541aebee078e1778e6bf5500 | [
"MIT"
] | 3 | 2021-03-08T01:43:28.000Z | 2022-03-22T09:50:05.000Z | ch04eval.ipynb | kanamori-takafumi/book_StatMachineLearn_with_Python | f3e6a55dc100a1f3541aebee078e1778e6bf5500 | [
"MIT"
] | null | null | null | ch04eval.ipynb | kanamori-takafumi/book_StatMachineLearn_with_Python | f3e6a55dc100a1f3541aebee078e1778e6bf5500 | [
"MIT"
] | 6 | 2019-03-18T07:17:36.000Z | 2021-12-16T05:14:28.000Z | 145.175595 | 33,658 | 0.881486 | [
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.stats",
"_____no_output_____"
]
],
[
[
"# 損失関数とトレーニング誤差・テスト誤差",
"_____no_output_____"
]
],
[
[
"par = np.linspace(-3,3,50) # パラメータの範囲\nte_err = (1+par**2)/2 # テスト誤差",
"_____no_output_____"
],
[
"# テスト誤差をプロット\nfor i in range(10):\n z = np.random.normal(size=20) # データ生成\n trerr = np.mean(np.subtract.outer(z,par)**2/2, axis=0) # トレーニング誤差\n plt.plot(par,trerr,'b--',linewidth=2) # トレーニング誤差をプロット\n\nplt.xlabel(\"par\")\nplt.ylabel(\"training/test errors\")\nplt.plot(par, te_err,'r-',linewidth=4)\nplt.show()",
"_____no_output_____"
]
],
[
[
"# テスト誤差の推定:交差検証法",
"_____no_output_____"
]
],
[
[
"from sklearn.tree import DecisionTreeRegressor\nn, K = 100, 10 # 設定:データ数100, 10重CV.\n# データ生成 \nx = np.random.uniform(-2,2,n) # 区間[-2,2]上の一様分布\ny = np.sin(2*np.pi*x)/x + np.random.normal(scale=0.5,size=n)\n# データをグループ分け \ncv_idx = np.tile(np.arange(K), int(np.ceil(n/K)))[:n] \nmaxdepths = np.arange(2,10) # 決定木の深さの候補\ncverr = np.array([])\nfor mp in maxdepths:\n cverr_lambda = np.array([])\n for k in range(K): \n tr_idx = (cv_idx!=k) \n te_idx = (cv_idx==k) \n cvx = x[tr_idx]; cvy = y[tr_idx] # CVのためデータを分割\n dtreg = DecisionTreeRegressor(max_depth=mp)\n dtreg.fit(np.array([cvx]).T, cvy) # 決定木で推定\n ypred = dtreg.predict(np.array([x[te_idx]]).T) # 予測\n # CV誤差の計算\n cl = np.append(cverr_lambda, np.mean((y[te_idx]-ypred)**2/2))\n cverr = np.append(cverr, np.mean(cl))",
"_____no_output_____"
],
[
"plt.scatter(maxdepths, cverr,c='k') # cv誤差のプロット\nplt.xlabel(\"max depth\"); plt.ylabel('cv error')\nplt.show()",
"_____no_output_____"
]
],
[
[
"# ROC曲線とAUC",
"_____no_output_____"
]
],
[
[
"n = 100 # データ数 100\nxp = np.random.normal(loc=1,size=n*2).reshape(n,2) # 信号アリ\nxn = np.random.normal(size=n*2).reshape(n,2) # 信号ナシ",
"_____no_output_____"
],
[
"# F1 のAUC\nnp.mean(np.subtract.outer(xp[:,0],xn[:,0]) >= 0) ",
"_____no_output_____"
],
[
"# F2 のAUC\nnp.mean(np.subtract.outer(np.sum(xp,1),np.sum(xn,1)) >= 0) ",
"_____no_output_____"
],
[
"n = 10000 # データ数 10000\nxp = np.random.normal(loc=1,size=n*2).reshape(n,2) # 信号アリ\nxn = np.random.normal(size=n*2).reshape(n,2) # 信号ナシ",
"_____no_output_____"
],
[
"# F1 のAUC\nnp.mean(np.subtract.outer(xp[:,0],xn[:,0]) >= 0) ",
"_____no_output_____"
],
[
"# F2 のAUC\nnp.mean(np.subtract.outer(np.sum(xp,1),np.sum(xn,1)) >= 0)",
"_____no_output_____"
],
[
"import scipy as sp\nfrom scipy import integrate # integrateを使う",
"_____no_output_____"
],
[
"# F1のAUC\ndef fpr(c):\n return(1-sp.stats.norm.cdf(c))\ndef tpr(c):\n return(1-sp.stats.norm.cdf(c,loc=1))\nc = np.arange(-10, 10, 0.01)\nsp.integrate.cumtrapz(tpr(c)[::-1],fpr(c)[::-1])[-1] # F1のAUCの計算",
"_____no_output_____"
],
[
"# F2のAUC\ndef fpr(c):\n return(1-sp.stats.norm.cdf(c,scale=np.sqrt(2))) \ndef tpr(c):\n return(1-sp.stats.norm.cdf(c,loc=2,scale=np.sqrt(2)))\nsp.integrate.cumtrapz(tpr(c)[::-1],fpr(c)[::-1])[-1] # F2のAUCの計算",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e77e0667462a94a89591cfaaa67e985dd2f67f90 | 137,196 | ipynb | Jupyter Notebook | CW1/OpenCV_Implementation/T2.hg.ipynb | lampard2a4/ICL-CVPR-Workspace | c5ce225aadd8636c9a4ff3599a856d7709e6cc72 | [
"MIT"
] | 1 | 2022-02-26T16:17:23.000Z | 2022-02-26T16:17:23.000Z | CW1/OpenCV_Implementation/T2.hg.ipynb | lampard2a4/ICL-CVPR-Workspace | c5ce225aadd8636c9a4ff3599a856d7709e6cc72 | [
"MIT"
] | null | null | null | CW1/OpenCV_Implementation/T2.hg.ipynb | lampard2a4/ICL-CVPR-Workspace | c5ce225aadd8636c9a4ff3599a856d7709e6cc72 | [
"MIT"
] | null | null | null | 612.482143 | 128,624 | 0.941944 | [
[
[
"Automatic correspondences matching.",
"_____no_output_____"
],
[
"Goal\nIn this chapter,\n\nWe will mix up the feature matching and findHomography from calib3d module to find known objects in a complex image.\nBasics\nSo what we did in last session? We used a queryImage, found some feature points in it, we took another trainImage, found the features in that image too and we found the best matches among them. In short, we found locations of some parts of an object in another cluttered image. This information is sufficient to find the object exactly on the trainImage.\n\nFor that, we can use a function from calib3d module, ie cv.findHomography(). If we pass the set of points from both the images, it will find the perspective transformation of that object. Then we can use cv.perspectiveTransform() to find the object. It needs atleast four correct points to find the transformation.\n\nWe have seen that there can be some possible errors while matching which may affect the result. To solve this problem, algorithm uses RANSAC or LEAST_MEDIAN (which can be decided by the flags). So good matches which provide correct estimation are called inliers and remaining are called outliers. cv.findHomography() returns a mask which specifies the inlier and outlier points.\n\nSo let's do it !!!",
"_____no_output_____"
],
[
"Code\n\nFirst, as usual, let's find SIFT features in images and apply the ratio test to find the best matches.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport cv2 as cv\nfrom matplotlib import pyplot as plt\n\nimg1 = cv.imread('hg_2_2.jpg',0) # queryImage\nimg2 = cv.imread('hg_2_8.jpg',0) # trainImage\n\n# Initiate SIFT detector\nsift = cv.SIFT_create()\n\n# find the keypoints and descriptors with SIFT\nkp1, des1 = sift.detectAndCompute(img1,None)\nkp2, des2 = sift.detectAndCompute(img2,None)\n\nFLANN_INDEX_KDTREE = 1\nindex_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)\nsearch_params = dict(checks = 50)\n\nflann = cv.FlannBasedMatcher(index_params, search_params)\n\nmatches = flann.knnMatch(des1,des2,k=2)\n\n# store all the good matches as per Lowe's ratio test.\ngood = []\nfor m,n in matches:\n if m.distance < 0.7*n.distance:\n good.append(m)\nprint(len(good))",
"3283\n"
]
],
[
[
"Now we set a condition that atleast 10 matches (defined by MIN_MATCH_COUNT) are to be there to find the object. Otherwise simply show a message saying not enough matches are present.\n\nIf enough matches are found, we extract the locations of matched keypoints in both the images. They are passed to find the perspective transformation. Once we get this 3x3 transformation matrix, we use it to transform the corners of queryImage to corresponding points in trainImage. Then we draw it.",
"_____no_output_____"
]
],
[
[
" src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1,1,2)\n dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1,1,2)\n print(len(src_pts))\n \n M, mask = cv.findHomography(src_pts, dst_pts, cv.RANSAC,5.0)\n matchesMask = mask.ravel().tolist()\n print(M)\n \n h,w = img1.shape\n pts = np.float32([ [0,0],[0,h-1],[w-1,h-1],[w-1,0] ]).reshape(-1,1,2)\n dst = cv.perspectiveTransform(pts,M)\n \n img2 = cv.polylines(img2,[np.int32(dst)],True,255,3, cv.LINE_AA)",
"3283\n[[ 6.53453067e-01 2.06501669e-01 -5.51251650e+00]\n [-2.02967609e-01 6.57965961e-01 9.85007522e+02]\n [ 1.24191783e-06 -2.13203451e-07 1.00000000e+00]]\n"
]
],
[
[
"Finally we draw our inliers (if successfully found the object) or matching keypoints (if failed).",
"_____no_output_____"
]
],
[
[
"draw_params = dict(matchColor = (0,255,0), # draw matches in green color\n singlePointColor = None,\n matchesMask = matchesMask, # draw only inliers\n flags = 2)\nimg3 = cv.drawMatches(img1,kp1,img2,kp2,good,(0,255,0),**draw_params)\nplt.imshow(img3, 'gray'),plt.show()",
"_____no_output_____"
],
[
"# Radius of circle\nradius = 2\n \n# Blue color in BGR\ncolor = (0, 255, 0)\n \n# Line thickness of 2 px\nthickness = 1\n \n# Using cv2.circle() method\n# Draw a circle with blue line borders of thickness of 2 px\n#image = cv2.circle(image, center_coordinates, radius, color, thickness)\nfor p1 in kp1:\n img4=cv.circle(img1, p1, radius, color, thickness)\nplt.imshow(img4, 'gray'),plt.show()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.