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
list | 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
list | 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
list | 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
list | cell_types
list | cell_type_groups
list |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cb5c02e5e700f36066df3d0d1a4bab2ea806a810 | 83,330 | ipynb | Jupyter Notebook | src/R/read_nc.ipynb | NIVANorge/martini-indicator-notebooks | f2d213d2c2f0a509473198c3a40b7d21ff72b0da | [
"MIT"
]
| null | null | null | src/R/read_nc.ipynb | NIVANorge/martini-indicator-notebooks | f2d213d2c2f0a509473198c3a40b7d21ff72b0da | [
"MIT"
]
| null | null | null | src/R/read_nc.ipynb | NIVANorge/martini-indicator-notebooks | f2d213d2c2f0a509473198c3a40b7d21ff72b0da | [
"MIT"
]
| null | null | null | 326.784314 | 76,998 | 0.917869 | [
[
[
"# Processing netcdf files\n\nload required R packages",
"_____no_output_____"
]
],
[
[
"require(dplyr)\nrequire(ncdf4)\nrequire(ggplot2)\nrequire(raster)\nrequire(leaflet)\nrequire(rgdal)",
"Loading required package: dplyr\n\nAttaching package: ‘dplyr’\n\nThe following objects are masked from ‘package:stats’:\n\n filter, lag\n\nThe following objects are masked from ‘package:base’:\n\n intersect, setdiff, setequal, union\n\nLoading required package: ncdf4\nLoading required package: ggplot2\nLoading required package: raster\nLoading required package: sp\n\nAttaching package: ‘raster’\n\nThe following object is masked from ‘package:dplyr’:\n\n select\n\nLoading required package: leaflet\nLoading required package: rgdal\nrgdal: version: 1.4-4, (SVN revision 833)\n Geospatial Data Abstraction Library extensions to R successfully loaded\n Loaded GDAL runtime: GDAL 2.4.2, released 2019/06/28\n Path to GDAL shared files: /opt/conda/share/gdal\n GDAL binary built with GEOS: TRUE \n Loaded PROJ.4 runtime: Rel. 6.1.0, May 15th, 2019, [PJ_VERSION: 610]\n Path to PROJ.4 shared files: /opt/conda/share/proj\n Linking to sp version: 1.3-1 \n"
]
],
[
[
"Source function for aggregating netcdf",
"_____no_output_____"
]
],
[
[
"source(\"read_nc.R\")",
"_____no_output_____"
]
],
[
[
"Function call:<br>\n<p>read_nc(file,stat=\"mean\", timesteps=c(1:364), varno=3, unitfactor=1, cleanNA=T)<p>\n \nParameters:<br>\n* file: netcdf file\n* stat: \"mean\" or \"90pc\". Default = \"mean\"\n* timesteps: time range over which we should aggregate. Default = c(1:364)\n* varno: the number of the variable we are interested in. Default=3\n* unitfactor: conversion factor. Default=1\n e.g. use unitfactor=0.032*0.7 for converting Dissolved Oxygen mmol/m3 -> mg/L -> ml/L\n* cleanNA: drop data points where the variable is NA. Default = TRUE\n ",
"_____no_output_____"
]
],
[
[
"# define function parameters for Chl\n\nncfile=\"~/shared/martini/martini800_v2_Chl_surf.nc\"\nstatistic=\"90pc\"\ntimesteps=c(1:364)\nvarno=5\nunitfactor=1\n\n# call the function\ndf <- read_nc(ncfile, statistic, timesteps, varno, unitfactor)",
"[1] \"lon_rho\" \"lat_rho\" \"Cs_r\" \"h\" \"light_Chl\"\n[1] \"light_Chl[mg/m^3] [ndims=4] averaged light/total chlorophyll a\"\n"
],
[
"names(df)",
"_____no_output_____"
],
[
"# read table matching id from nc data to positions in the epsg3035 grid\ndf_points<-read.table(file=\"grid_epsg3035.txt\",header=T,stringsAsFactors=F,sep=\";\")\n\n# rename the 'value' parameter in df\ndf <- df %>%\n dplyr::select(ID=id,value)\n\nparam = \"Chl\"\nnames(df)[names(df)==\"value\"]<-param\n\n# join the dataframe to positions in EPSG3035\ndf <- df_points %>%\n left_join(df,by=\"ID\")",
"_____no_output_____"
],
[
"# load the 'blank' raster file\nr <- raster(\"blank_raster.tif\")\ncrs(r)<-CRS(\"+init=epsg:3035\")\n\n# rasterize the MARTINI data to raster r\nx <- rasterize(df[, 1:2], r, df[,4], fun=mean)\n\n# plot the raster\nplot(x, main=param)",
"_____no_output_____"
],
[
"# save the raster file\nrasterfile=\"~/shared/martini/Chl_surf.grd\"\nrf <- writeRaster(x, filename=rasterfile,overwrite=TRUE)",
"_____no_output_____"
]
]
]
| [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
]
| [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
]
|
cb5c06e129cfc0198d33e5207ead9f952dfa16e2 | 683,407 | ipynb | Jupyter Notebook | DocumentedExamples/kinetic_energy.ipynb | paigem/cosima-recipes | 700499d91bea65ea41bb54cf91f5ae23dec22e59 | [
"Apache-2.0"
]
| null | null | null | DocumentedExamples/kinetic_energy.ipynb | paigem/cosima-recipes | 700499d91bea65ea41bb54cf91f5ae23dec22e59 | [
"Apache-2.0"
]
| null | null | null | DocumentedExamples/kinetic_energy.ipynb | paigem/cosima-recipes | 700499d91bea65ea41bb54cf91f5ae23dec22e59 | [
"Apache-2.0"
]
| null | null | null | 432.536076 | 219,076 | 0.917049 | [
[
[
"# Kinetic Energy\n\nMean and Eddy Kinetic Energy",
"_____no_output_____"
],
[
"## Theory",
"_____no_output_____"
],
[
"For a hydrostatic ocean like MOM5, the relevant kinetic energy per mass is \n\n$$ KE = \\frac{1}{2} (u^2 + v^2).$$\n\nThe vertical velocity component, $w$, does not appear in the mechanical energy budget. It is very much subdominant. But more fundamentally, it simply does not appear in the mechanical energy buget for a hydrostatic ocean. \n\nFor a non-steady fluid, we can define the time-averaged kinetic energy as the __total kinetic energy__, TKE\n\n$$ TKE = \\left< K \\right > = \\frac{1}{T} \\int_0^T \\frac{1}{2} \\left( u^2 + v^2 \\right) dt $$\n\nIt is useful to decompose the velocity in the mean and time varying components\n\n$$ u = \\bar{u} + u'$$\n\nThe __mean kinetic energy__ is the energy associated with the mean flow\n\n$$ MKE = \\frac{1}{2} \\left( \\bar{u}^2 + \\bar{v}^2 \\right) $$\n\nThe kinetic energy of the time varying component is the __eddy kinetic energy__, EKE. This quantity can be obtained by \nsubstracting the velocity means and calculating the kinetic energy of the \nperturbation velocity quantities.\n\n$$ EKE = \\left< \\frac{1}{2} \\left( \\left(u - \\left<u\\right>\\right)^2 + \n \\left(v - \\left<v\\right>\\right)^2\n \\right) \\right> $$\n \nMKE and EKE partition the total kinetic energy\n\n$$TKE = EKE + MKE $$\n",
"_____no_output_____"
],
[
"## Calculation\n",
"_____no_output_____"
],
[
"We start by importing some useful packages.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n\nimport cosima_cookbook as cc\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cmocean as cm\nimport xarray as xr\n\nfrom dask.distributed import Client",
"_____no_output_____"
]
],
[
[
"Start up a dask cluster.",
"_____no_output_____"
]
],
[
[
"client = Client(n_workers=6)\nclient",
"_____no_output_____"
]
],
[
[
"Create a database session and select an experiment. Here we choose an experiment which has daily velocities saved for the Southern Ocean.",
"_____no_output_____"
]
],
[
[
"session = cc.database.create_session()\nexpt = '01deg_jra55v13_ryf9091'",
"_____no_output_____"
]
],
[
[
"While not difficult to write down, this is fairly involved computation since to compute the eddy kinetic energy requires both the velocity and the mean of the velocity components. Since the dataset is large, we want to avoid loading all of the velocity data into memory at the same time.",
"_____no_output_____"
],
[
"To calculate EKE, we need horizontal velocities $u$ and $v$, preferably saved at `1 daily` frequency (or perhaps `5 daily`). You can check whether your experiment has that kind of data:",
"_____no_output_____"
]
],
[
[
"varlist = cc.querying.get_variables(session, expt,frequency = '1 daily')\nvarlist",
"_____no_output_____"
]
],
[
[
"### Example",
"_____no_output_____"
],
[
"For example, let's calculate the mean and eddy kinetic energy over the last year of this particular model run:",
"_____no_output_____"
]
],
[
[
"start_time = '1970-01-01'",
"_____no_output_____"
]
],
[
[
"Here we build datasets for the variables u and v",
"_____no_output_____"
]
],
[
[
"u = cc.querying.getvar(expt,'u',session,ncfile='ocean_daily_3d_u_%.nc',start_time = start_time)\nv = cc.querying.getvar(expt,'v',session,ncfile='ocean_daily_3d_v_%.nc',start_time = start_time)",
"/g/data3/hh5/public/apps/miniconda3/envs/analysis3-19.10/lib/python3.6/site-packages/cosima_cookbook/querying.py:134: FutureWarning: In xarray version 0.15 the default behaviour of `open_mfdataset`\nwill change. To retain the existing behavior, pass\ncombine='nested'. To use future default behavior, pass\ncombine='by_coords'. See\nhttp://xarray.pydata.org/en/stable/combining.html#combining-multi\n\n **xr_kwargs\n/g/data3/hh5/public/apps/miniconda3/envs/analysis3-19.10/lib/python3.6/site-packages/xarray/backends/api.py:933: FutureWarning: The datasets supplied have global dimension coordinates. You may want\nto use the new `combine_by_coords` function (or the\n`combine='by_coords'` option to `open_mfdataset`) to order the datasets\nbefore concatenation. Alternatively, to continue concatenating based\non the order the datasets are supplied in future, please use the new\n`combine_nested` function (or the `combine='nested'` option to\nopen_mfdataset).\n from_openmfds=True,\n/g/data3/hh5/public/apps/miniconda3/envs/analysis3-19.10/lib/python3.6/site-packages/cosima_cookbook/querying.py:134: FutureWarning: In xarray version 0.15 the default behaviour of `open_mfdataset`\nwill change. To retain the existing behavior, pass\ncombine='nested'. To use future default behavior, pass\ncombine='by_coords'. See\nhttp://xarray.pydata.org/en/stable/combining.html#combining-multi\n\n **xr_kwargs\n/g/data3/hh5/public/apps/miniconda3/envs/analysis3-19.10/lib/python3.6/site-packages/xarray/backends/api.py:933: FutureWarning: The datasets supplied have global dimension coordinates. You may want\nto use the new `combine_by_coords` function (or the\n`combine='by_coords'` option to `open_mfdataset`) to order the datasets\nbefore concatenation. Alternatively, to continue concatenating based\non the order the datasets are supplied in future, please use the new\n`combine_nested` function (or the `combine='nested'` option to\nopen_mfdataset).\n from_openmfds=True,\n"
]
],
[
[
"The kinetic energy is given by\n\n$$ KE = \\frac{1}{2} (u^2 + v^2)$$\n\nwe construct the following expression:",
"_____no_output_____"
]
],
[
[
"KE = 0.5*(u**2 + v**2)",
"_____no_output_____"
]
],
[
[
"You may notice that this line takes only a moment to run. The calculation is not (yet) being run. Rather, XArray needs to broadcast the squares of the velocity fields together to determine the final shape of KE. ",
"_____no_output_____"
]
],
[
[
"print(KE.shape)",
"(396, 75, 900, 3600)\n"
]
],
[
[
"This is too large to store locally. We need to reduce the data in some way. \n\nThe mean kinetic energy is calculated by this function",
"_____no_output_____"
]
],
[
[
"def calculate_MKE(KE):\n MKE = KE.mean('time').sum('st_ocean')\n return MKE",
"_____no_output_____"
]
],
[
[
"While we could try and compute this DataArray using the new mapblocks function:",
"_____no_output_____"
]
],
[
[
"MKE = xr.map_blocks(calculate_MKE, KE)\nMKE.data",
"_____no_output_____"
],
[
"MKE.plot()",
"_____no_output_____"
],
[
"KE.isel(time=1).sum('st_ocean').plot(vmax=10)",
"_____no_output_____"
]
],
[
[
"## Mean Kinetic Energy",
"_____no_output_____"
],
[
"For the mean kinetic energy, we need to average the velocities over time over time.",
"_____no_output_____"
]
],
[
[
"u_mean = u.mean('time')\nv_mean = v.mean('time')",
"_____no_output_____"
],
[
"MKE = 0.5*(u_mean**2 + v_mean**2)\nMKE = MKE.sum('st_ocean')",
"_____no_output_____"
],
[
"MKE.plot(vmax=1)",
"distributed.utils_perf - WARNING - full garbage collections took 14% CPU time recently (threshold: 10%)\ndistributed.utils_perf - WARNING - full garbage collections took 15% CPU time recently (threshold: 10%)\ndistributed.utils_perf - WARNING - full garbage collections took 15% CPU time recently (threshold: 10%)\ndistributed.utils_perf - WARNING - full garbage collections took 15% CPU time recently (threshold: 10%)\ndistributed.utils_perf - WARNING - full garbage collections took 15% CPU time recently (threshold: 10%)\ndistributed.utils_perf - WARNING - full garbage collections took 15% CPU time recently (threshold: 10%)\ndistributed.utils_perf - WARNING - full garbage collections took 15% CPU time recently (threshold: 10%)\n"
]
],
[
[
"## Eddy Kinetic Energy",
"_____no_output_____"
],
[
"We calculate the perturbation velocities",
"_____no_output_____"
]
],
[
[
"u_ = u - u_mean\nv_ = v - v_mean",
"_____no_output_____"
],
[
"EKE = 0.5 * (u_**2 + v_**2)",
"_____no_output_____"
],
[
"EKE = EKE.mean('time').sum(['st_ocean'])",
"_____no_output_____"
],
[
"EKE = cc.compute_by_block(EKE)",
"_____no_output_____"
],
[
"EKE.plot(vmax=1)\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Functions",
"_____no_output_____"
]
],
[
[
"from joblib import Memory\n\nmemory = Memory(cachedir='/g/data1/v45/cosima-cookbook/',verbose=0)",
"_____no_output_____"
]
],
[
[
"Here are functions for calculating both MKE and EKE.",
"_____no_output_____"
]
],
[
[
"@memory.cache\ndef calc_mke(expt, n=6):\n \n print('Opening datasets...')\n u = cc.get_nc_variable(expt, 'ocean__\\d+_\\d+.nc', 'u', \n time_units = 'days since 2000-01-01', \n n=n)\n v = cc.get_nc_variable(expt, 'ocean__\\d+_\\d+.nc', 'v', \n time_units = 'days since 2000-01-01', \n n=n)\n \n print('Preparing computation...')\n u_mean = u.mean('time')\n v_mean = v.mean('time')\n \n MKE = 0.5*(u_mean**2 + v_mean**2)\n MKE = MKE.sum('st_ocean')\n \n print('Calculating...')\n MKE = cc.compute_by_block(MKE)\n \n return MKE",
"_____no_output_____"
],
[
"%%time\nMKE = calc_mke('KDS75', n=6)",
"_____no_output_____"
],
[
"@memory.cache\ndef calc_eke(expt, n=6):\n \n print('Opening datasets...')\n u = cc.get_nc_variable(expt, 'ocean__\\d+_\\d+.nc', 'u', \n time_units = 'days since 2000-01-01', \n n=n)\n v = cc.get_nc_variable(expt, 'ocean__\\d+_\\d+.nc', 'v', \n time_units = 'days since 2000-01-01', \n n=n)\n \n print('Preparing computation...')\n u_mean = u.mean('time')\n v_mean = v.mean('time')\n \n u_ = u - u_mean\n v_ = v - v_mean\n \n EKE = 0.5 * (u_**2 + v_**2)\n EKE = EKE.mean('time')\n EKE = EKE.sum(['st_ocean'])\n \n print('Calculating...')\n EKE = cc.compute_by_block(EKE)\n \n return EKE",
"_____no_output_____"
],
[
"%%time\nEKE = calc_eke('KDS75', n=6)",
"_____no_output_____"
],
[
"EKE.plot(vmax=1)\nplt.show()",
"CPU times: user 974 ms, sys: 1.95 s, total: 2.92 s\nWall time: 2.56 s\n"
],
[
"%%time\nEKE = calc_eke('KDS75', n=72)",
"_____no_output_____"
],
[
"EKE.plot(vmax=1)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Using dask directly\n\nNote: Does not (yet) work but performance gains suggest that it may be further debugging for production use.",
"_____no_output_____"
]
],
[
[
"import netCDF4\nimport dask.array as da\nimport dataset",
"_____no_output_____"
],
[
"@memory.cache\ndef calc_mke_dask(expt, n=6):\n \n db = dataset.connect(cc.netcdf_index.database_url)\n\n res = db.query('SELECT ncfile'\n ' from ncfiles'\n ' where variable = \"u\"'\n ' AND experiment = \"%s\"'\n ' AND basename_pattern = \"ocean__\\d+_\\d+.nc\"'\n ' ORDER BY ncfile'\n ' LIMIT %d' % (expt, n),\n )\n rows = list(res)\n\n ncfiles = [row['ncfile'] for row in rows]\n\n u_dataarrays = [da.from_array(netCDF4.Dataset(ncfile, 'r')['u'],\n chunks=(1,7,300,400)) for ncfile in ncfiles]\n u = da.concatenate(u_dataarrays, axis=0)\n\n v_dataarrays = [da.from_array(netCDF4.Dataset(ncfile, 'r')['v'],\n chunks=(1,7,300,400)) for ncfile in ncfiles]\n v = da.concatenate(v_dataarrays, axis=0)\n\n u_mean = u.mean(axis=0)\n v_mean = v.mean(axis=0)\n\n MKE = 0.5*(u_mean**2 + v_mean**2)\n MKE = MKE.sum(axis=0)\n \n MKE = cc.compute_by_block(MKE)\n \n temp = cc.get_nc_variable(expt, 'ocean__\\d+_\\d+.nc', 'u', \n time_units = 'days since 2000-01-01', \n n=1)\n template = temp.mean('time').sum('st_ocean')\n result = xr.zeros_like(template).compute()\n result[:] = MKE\n result.name = 'MKE'\n \n return result",
"_____no_output_____"
],
[
"%%time\nMKE = calc_mke_dask('KDS75', n=6)",
"_____no_output_____"
],
[
"@memory.cache\ndef calc_eke_dask(expt, n=72):\n\n db = dataset.connect(cc.netcdf_index.database_url)\n\n res = db.query('SELECT ncfile'\n ' from ncfiles'\n ' where variable = \"u\"'\n ' AND experiment = \"%s\"'\n ' AND basename_pattern = \"ocean__\\d+_\\d+.nc\"'\n ' ORDER BY ncfile'\n ' LIMIT %d' % (expt, n)\n )\n ncfiles = [row['ncfile'] for row in res]\n\n u_dataarrays = [da.from_array(netCDF4.Dataset(ncfile, 'r')['u'],\n chunks=(1,7,300,400)) for ncfile in ncfiles]\n u = da.concatenate(u_dataarrays, axis=0)\n\n v_dataarrays = [da.from_array(netCDF4.Dataset(ncfile, 'r')['v'],\n chunks=(1,7,300,400)) for ncfile in ncfiles]\n v = da.concatenate(v_dataarrays, axis=0)\n\n u_mean = u.mean(axis=0)\n v_mean = v.mean(axis=0)\n\n u_ = u - u_mean\n v_ = v - v_mean\n\n EKE = 0.5 * (u_**2 + v_**2)\n EKE = EKE.mean(axis=0)\n EKE = EKE.sum(axis=0)\n \n EKE = cc.compute_by_block(EKE)\n \n temp = cc.get_nc_variable(expt, 'ocean__\\d+_\\d+.nc', 'u', \n time_units = 'days since 2000-01-01', \n n=1)\n template = temp.mean('time').sum('st_ocean')\n result = xr.zeros_like(template).compute()\n result[:] = EKE\n result.name = 'EKE'\n \n return result",
"_____no_output_____"
],
[
"%%time\nEKE = calc_eke_dask('KDS75', 2)",
"_____no_output_____"
],
[
"EKE.plot(vmax=1)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Visualization",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.basemap import Basemap",
"_____no_output_____"
],
[
"# Plot in basemap \n\nplt.figure(figsize=(15,6))\nlev = np.arange(0, 1.0, 0.05)\nmap = Basemap(projection='mbtfpq',\n lon_0 = -100, resolution='l')\nmap.drawcoastlines(linewidth=0.25)\nmap.fillcontinents(color='gray',lake_color='gray')\nmap.drawparallels(np.arange(-60.,61.,30.),\n labels=[True,False,False,False])\nmap.drawmeridians(np.arange(-180.,181.,90.),\n labels=[False,False,False,True])\n\nexpt = 'KDS75'\ndsx = calc_eke(expt, n=6)\n \nx=dsx.xu_ocean[:]\ny=dsx.yu_ocean[:]\nlon, lat = np.meshgrid(x, y)\n \nX, Y = map(lon,lat) \n\nmap.contourf(X, Y, dsx.data,\n cmap=plt.cm.hot,\n levels=lev,\n extend='both')\n\ncb = plt.colorbar(orientation='vertical',shrink = 0.7)\n\ncb.ax.set_xlabel('m^2 s$^{-2}$')\nplt.title('Eddy KE {}'.format(expt))",
"Opening 6 ncfiles...\nBuilding dataarray.\nDataarray constructed.\nOpening 6 ncfiles...\nBuilding dataarray.\nDataarray constructed.\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",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
]
|
cb5c0be9de6829bfeca3736cf861c6b39ac8df32 | 6,300 | ipynb | Jupyter Notebook | GradientDescent/7.Debug.ipynb | TobiahShaw/machine-learning-algorithm | 0ce0e0d463159d8d30b11a15ba98c5a64b2c5b89 | [
"Apache-2.0"
]
| null | null | null | GradientDescent/7.Debug.ipynb | TobiahShaw/machine-learning-algorithm | 0ce0e0d463159d8d30b11a15ba98c5a64b2c5b89 | [
"Apache-2.0"
]
| null | null | null | GradientDescent/7.Debug.ipynb | TobiahShaw/machine-learning-algorithm | 0ce0e0d463159d8d30b11a15ba98c5a64b2c5b89 | [
"Apache-2.0"
]
| null | null | null | 22.826087 | 240 | 0.469365 | [
[
[
"# 关于梯度的调试\n\n**有时求解梯度会有困难,我们可以通过近似的方法来求解某点的梯度**\n\n\n\n近似的计算导数\n\n$$\\frac{dJ}{d\\theta} = \\frac{J(\\theta + \\varepsilon) - J(\\theta + \\varepsilon)}{2\\varepsilon}$$\n\n多维近似求梯度\n\n$$\\theta = (\\theta_0, \\theta_1, \\theta_2, \\ldots , \\theta_n)$$\n\n$$\\frac{\\partial{J}}{\\partial{\\theta}} = (\\frac{\\partial{J}}{\\partial{\\theta_0}}, \\frac{\\partial{J}}{\\partial{\\theta_1}}, \\frac{\\partial{J}}{\\partial{\\theta_2}},\\ldots, \\frac{\\partial{J}}{\\partial{\\theta_n}})$$\n\n$$\\theta_0^+ = (\\theta_0 + \\varepsilon, \\theta_1, \\theta_2, \\ldots , \\theta_n)$$\n\n$$\\theta_0^- = (\\theta_0 - \\varepsilon, \\theta_1, \\theta_2, \\ldots , \\theta_n)$$\n\n$$\\frac{\\partial{J}}{\\partial{\\theta_0}} = \\frac{J(\\theta_0^+) - J(\\theta_0^-)}{2\\varepsilon}$$\n\n其他维度同理\n\n缺点:时间复杂度比较高",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"np.random.seed(666)\nX = np.random.random(size=(1000, 10))",
"_____no_output_____"
],
[
"true_theta = np.arange(1,12, dtype=float)\nX_b = np.hstack([np.ones((len(X), 1)), X])\ny = X_b.dot(true_theta) + np.random.normal(size = 1000)",
"_____no_output_____"
],
[
"X.shape",
"_____no_output_____"
],
[
"y.shape",
"_____no_output_____"
],
[
"true_theta",
"_____no_output_____"
],
[
"def J(theta, X_b, y):\n try:\n return np.sum((y - X_b.dot(theta)) ** 2) / len(X_b)\n except:\n return float('inf')",
"_____no_output_____"
],
[
"def dJ_math(theta, X_b, y):\n return X_b.T.dot(X_b.dot(theta) - y) * 2. / len(y)",
"_____no_output_____"
],
[
"def dJ_debug(theta, X_b, y, epsilon=0.01):\n res = np.empty(len(theta))\n for i in range(len(theta)):\n theta_1 = theta.copy()\n theta_1[i] += epsilon\n theta_2 = theta.copy()\n theta_2[i] -= epsilon\n res[i] = (J(theta_1, X_b, y) - J(theta_2, X_b, y)) / (2 * epsilon)\n return res",
"_____no_output_____"
],
[
"def gradient_descent(dJ, x_b, y, initial_theta, eta, n_iters=10000, epsilon=1e-8):\n theta = initial_theta\n i_iter = 0\n while i_iter < n_iters:\n gradient = dJ(theta, x_b, y)\n last_theta = theta\n theta = theta - eta * gradient\n i_iter = i_iter + 1\n if(abs(J(theta, x_b, y) - J(last_theta, x_b, y)) < epsilon):\n break\n return theta",
"_____no_output_____"
],
[
"initial_theta = np.ones((X_b.shape[1]))\neta = 0.01\n%time theta = gradient_descent(dJ_debug, X_b, y, initial_theta, eta)\ntheta",
"Wall time: 32 s\n"
],
[
"%time theta = gradient_descent(dJ_math, X_b, y, initial_theta, eta)\ntheta",
"Wall time: 4.44 s\n"
]
]
]
| [
"markdown",
"code"
]
| [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
]
|
cb5c1f0d51f42d04f49a63b97bda247a4635b689 | 70,252 | ipynb | Jupyter Notebook | Gradient_Descent(Univariate_Logistic_Regression).ipynb | rahul23aug/PY-machine_learning | 02d644c64290d78b37c9024cde2c332b8232636b | [
"MIT"
]
| null | null | null | Gradient_Descent(Univariate_Logistic_Regression).ipynb | rahul23aug/PY-machine_learning | 02d644c64290d78b37c9024cde2c332b8232636b | [
"MIT"
]
| null | null | null | Gradient_Descent(Univariate_Logistic_Regression).ipynb | rahul23aug/PY-machine_learning | 02d644c64290d78b37c9024cde2c332b8232636b | [
"MIT"
]
| null | null | null | 223.022222 | 45,774 | 0.901939 | [
[
[
"import numpy as np, pandas as pd\nimport matplotlib.pyplot as plt\n#Exception case for using sklearn: to split the dataset\nfrom sklearn import model_selection",
"_____no_output_____"
],
[
"#Create a simple dataset \nX =pd.DataFrame( np.linspace(0.1,1,1001))\ntest = X\ntest[test >=0.85] = 1\ntest[test < 0.85] = 0\n# thus the dataset is such that if observation is > =0.65, it is a positive case\nY = test\nX_train, X_test, Y_train, Y_test = model_selection.train_test_split(X,Y)\nX_train.insert(0,'ones',np.ones(Y_train.shape))\n#how balanced is the dataset\nprint(\"Positive Class count: \",X_train[X_train[X_train.columns[1]]==1].count()[0])\nprint(\"Negative Class count: \",X_train[X_train[X_train.columns[1]]==0].count()[0])",
"Positive Class count: 124\nNegative Class count: 626\n"
],
[
"def Logistic_Regression(X_train, Y_train, alpha=0.001, iter=100):\n theta = np.ones(X_train.shape[1]) / 100\n J = np.ones(X_train.shape[0]) \n theta.reshape(X_train.shape[1],1)\n Rl=[]\n \n m= X_train.shape[0]\n for iteration in range(iter):\n ht= (theta*X_train).sum(axis=1)\n Yp =1/(1+np.exp(-ht))\n for i in range(X_train.shape[0]):\n J[i] = -(Y_train.values[i] * np.log(Yp.values[i])) -((1-Y_train.values[i])*np.log(1-Yp.values[i]))\n Rl.append(J.sum())\n err= Yp- Y_train\n err = err[0]\n theta= theta - (alpha*(X_train.T.dot(err)))/m\n return theta, Rl, iter\nparams=Logistic_Regression(X_train, Y_train,2,30)",
"_____no_output_____"
],
[
"plt.title(\"Gradient descent\")\nX= np.arange(params[2])\nplt.plot(X,params[1])\nplt.xlabel('Iterations')\nplt.ylabel('Cost')\nplt.show()",
"_____no_output_____"
],
[
"def predict(x = X_test,theta = params[0]):\n ht= (theta * x).sum(axis=1)\n y =1/(1+np.exp(-ht))\n return y",
"_____no_output_____"
],
[
"#Test the model\n# change for X observations\nX_tr = X_test\nYp = predict(X_tr)\n# change for y responses\nY_tr = Y_test\n#Change threshold value to get improve performance\nYp[Yp>0.5] = 1\nYp[Yp<=0.5] = 0\nX_terms = np.arange(X_tr.shape[0])\n#some fun visualization\nplt.title('Actual Vs Predicted')\nplt.xlabel('Observations')\nplt.ylabel('Predicted Class')\nplt.plot(X_terms, Yp)\nplt.plot(X_terms, Y_tr)\nplt.show()",
"_____no_output_____"
]
],
[
[
"Model Metrics:",
"_____no_output_____"
]
],
[
[
"Predictions = pd.DataFrame(Y_tr.values)\nPredictions.insert(1,1,Yp.values)\nPredictions.columns=['Actual','Predicted']\n# Metric calculations \nTP=Predictions[(Predictions['Actual'] == 1 ) & (Predictions['Predicted'] == 1)].count()[0]\nTN=Predictions[(Predictions['Actual'] == 0) & (Predictions['Predicted'] == 0)].count()[0]\nFP=Predictions[(Predictions['Actual'] == 0 ) & (Predictions['Predicted'] == 1)].count()[0]\nFN=Predictions[(Predictions['Actual'] == 1 ) & (Predictions['Predicted'] == 0)].count()[0]\n# Create the confusion Matrix \nconfusion = pd.DataFrame(np.array([[TP, FP],[FN,TN]]))\nconfusion.columns = ['Actual_Positives','Actual_Negatives']\nconfusion.index = ['Predicted_Positives','Predicted_Negatives']\nPredicted_Positive= TP + FP\nPredicted_Negative= TN + FN\nActual_Positive= TP + FN\nActual_Negative= TN + FP\nAccuracy= (TP + TN)/(Actual_Positive + Actual_Negative)\nPrecision= TP / Predicted_Positive\n#Recall or Sensitivity\nRecall = TP / Actual_Positive\nSpecificity = TN / Actual_Negative\nF1_Score = (2*Precision * Recall) / (Precision + Recall)",
"_____no_output_____"
]
],
[
[
" Print all the metrics",
"_____no_output_____"
]
],
[
[
"a = np.array([[True_Positives, False_Positives],[False_Negatives,True_Negatives]])\nprint(confusion)\n",
" Actual_Positives Actual_Negatives\nPredicted_Positives 39 0\nPredicted_Negatives 0 212\n"
],
[
" print('Accuracy: ',Accuracy)\nprint('Precision: ', Precision)\nprint('Recall: ',Recall)\nprint('Specificity: ', Specificity)\nprint('F1_score: %.2F'%F1_Score)",
"Accuracy: 1.0\nPrecision: 1.0\nRecall: 1.0\nSpecificity: 1.0\nF1_score: 1.00\n"
]
]
]
| [
"code",
"markdown",
"code",
"markdown",
"code"
]
| [
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
]
|
cb5c229d858e991553e1a11e6d89b2720c2c99e3 | 20,248 | ipynb | Jupyter Notebook | train2.ipynb | mraad/mask_rcnn_notebooks | d2c655557860796983aad71191769721a3766a7e | [
"Apache-2.0"
]
| 2 | 2019-06-12T00:33:47.000Z | 2021-06-25T04:48:36.000Z | train2.ipynb | mraad/mask_rcnn_notebooks | d2c655557860796983aad71191769721a3766a7e | [
"Apache-2.0"
]
| null | null | null | train2.ipynb | mraad/mask_rcnn_notebooks | d2c655557860796983aad71191769721a3766a7e | [
"Apache-2.0"
]
| 1 | 2019-07-11T00:42:10.000Z | 2019-07-11T00:42:10.000Z | 34.318644 | 270 | 0.52262 | [
[
[
"import os\nimport sys\nimport random\nimport math\nimport re\nimport time\nimport numpy as np\nimport cv2\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n# Root directory of the project\nROOT_DIR = os.getenv(\"MRCNN_HOME\", \"/Mask_RCNN\")\n\n# Import Mask RCNN\nsys.path.append(ROOT_DIR) # To find local version of the library\nfrom mrcnn.config import Config\nfrom mrcnn import utils\nimport mrcnn.model as modellib\nfrom mrcnn import visualize\nfrom mrcnn.model import log\n\n%matplotlib inline \n\n# Directory to save logs and trained model\nMODEL_DIR = os.path.join(ROOT_DIR, \"logs\")\n\n# Local path to trained weights file\nCOCO_MODEL_PATH = os.path.join(ROOT_DIR, \"mask_rcnn_coco.h5\")\n# Download COCO trained weights from Releases if needed\nif not os.path.exists(COCO_MODEL_PATH):\n utils.download_trained_weights(COCO_MODEL_PATH)\n \nDATA_PATH = \"/data/RCNNTanks256Train/Yanbu\"\nDATA_PATH = os.path.join(\"E:\", os.sep, \"RCNNTanks256Train\")\n\nIMG_SIZE = 256",
"_____no_output_____"
],
[
"# set tf backend to allow memory to grow, instead of claiming everything\nimport tensorflow as tf\nimport keras \n\ndef get_session():\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n return tf.Session(config=config)\n\n# set the modified tf session as backend in keras\nkeras.backend.tensorflow_backend.set_session(get_session())",
"_____no_output_____"
]
],
[
[
"## Configurations",
"_____no_output_____"
]
],
[
[
"class MRConfig(Config):\n \"\"\"Configuration for training on the Miami buildings dataset.\n Derives from the base Config class and overrides values specific\n to the toy shapes dataset.\n \"\"\"\n # Give the configuration a recognizable name\n NAME = \"tank\"\n\n BATCH_SIZE = 8\n GPU_COUNT = 1\n IMAGES_PER_GPU = 8\n\n # Number of classes (including background)\n NUM_CLASSES = 1 + 1 \n\n # Use small images for faster training. Set the limits of the small side\n # the large side, and that determines the image shape.\n IMAGE_MIN_DIM = IMG_SIZE\n IMAGE_MAX_DIM = IMG_SIZE\n\n # Use smaller anchors because our image and objects are small\n RPN_ANCHOR_SCALES = (8, 16, 32, 64, 128) \n # RPN_ANCHOR_SCALES = (10, 20, 40, 80, 160) \n \n # Ratios of anchors at each cell (width/height)\n # A value of 1 represents a square anchor, and 0.5 is a wide anchor\n# RPN_ANCHOR_RATIOS = [0.25, 1, 4]\n \n \n # Loss weights for more precise optimization.\n # Can be used for R-CNN training setup.\n# LOSS_WEIGHTS = {\n# \"rpn_class_loss\": 1.,\n# \"rpn_bbox_loss\": 1.,\n# \"mrcnn_class_loss\": 1.,\n# \"mrcnn_bbox_loss\": 1.,\n# \"mrcnn_mask_loss\": 1.1\n# } \n\n # Reduce training ROIs per image because the images are small and have\n # few objects. Aim to allow ROI sampling to pick 33% positive ROIs.\n TRAIN_ROIS_PER_IMAGE = 256\n \n# ROI_POSITIVE_RATIO = 0.5 #makes no positive effect\n\n # Max number of final detections\n DETECTION_MAX_INSTANCES = 100\n\n # Maximum number of ground truth instances to use in one image\n MAX_GT_INSTANCES = 100\n\n # Use a small epoch since the data is simple\n STEPS_PER_EPOCH = 100\n\n # use small validation steps since the epoch is small\n VALIDATION_STEPS = 1\n \n # Image mean (RGB)\n MEAN_PIXEL = np.array([131.84381436753546, 125.43039054432134, 113.32320930217874])\n LEARNING_RATE = 1.e-4\n WEIGHT_DECAY = 1.e-5\n\n\nconfig = MRConfig()\nconfig.display()",
"_____no_output_____"
]
],
[
[
"## Notebook Preferences",
"_____no_output_____"
]
],
[
[
"def get_ax(rows=1, cols=1, size=8):\n fig, ax = plt.subplots(rows, cols, figsize=(size*cols, size*rows))\n return ax, fig",
"_____no_output_____"
],
[
"import glob\nimport skimage\n\nclass MRDataset(utils.Dataset):\n\n def load(self, dataset_dir):\n # Add classes\n self.add_class(\"tank\", 1, \"C_TankCompleted\")\n \n #loading images\n self._image_dir = os.path.join(dataset_dir, \"images/\")\n self._label_dir = os.path.join(dataset_dir, \"labels/\")\n for i, f in enumerate(glob.glob(os.path.join(self._image_dir, \"*.tif\"))):\n _, filename = os.path.split(f)\n self.add_image(\"tank\",\n image_id=i,\n path=f,\n width=config.IMAGE_MAX_DIM,\n height=config.IMAGE_MAX_DIM,\n filename=filename)\n \n def load_mask(self, image_id):\n info = self.image_info[image_id]\n fname = info[\"filename\"]\n masks = []\n class_ids = []\n #looping through all the classes, loading and processing corresponding masks\n for ci in self.class_info:\n class_name = ci[\"name\"]\n class_id = ci[\"id\"]\n try:\n m_src = skimage.io.imread(os.path.join(self._label_dir, class_name, fname))\n except:\n #no file with masks of this class found\n continue \n #making individual masks for each instance\n instance_ids = np.unique(m_src)\n for i in instance_ids:\n if i > 0:\n m = np.zeros(m_src.shape)\n m[m_src==i] = i\n if np.any(m==i):\n masks.append(m)\n class_ids.append(class_id)\n if len(masks) == 0:\n masks.append(np.zeros(m_src.shape))\n class_ids.append(1) \n masks = np.stack(masks, axis=-1) \n return masks.astype(np.bool), np.array(class_ids, dtype=np.int32)\n \n def image_reference(self, image_id):\n \"\"\"Return the shapes data of the image.\"\"\"\n info = self.image_info[image_id]\n if info[\"source\"] == \"tank\":\n return info[\"path\"]\n else:\n super(self.__class__).image_reference(self, image_id)",
"_____no_output_____"
],
[
"# Training dataset\ndataset_train = MRDataset()\ndataset_train.load(os.path.join(DATA_PATH, \"Karachi20170515_060830\"))\ndataset_train.prepare()\n\n# Validation dataset\ndataset_val = MRDataset()\ndataset_val.load(os.path.join(DATA_PATH, \"Paradip20170210_043931\"))\ndataset_val.prepare()\n\n# Test dataset\ndataset_test = MRDataset()\ndataset_test.load(os.path.join(DATA_PATH, \"Karachi20170718_055349\"))\ndataset_test.prepare()",
"_____no_output_____"
],
[
"# Load and display random samples\ndataset = dataset_test\nimage_ids = np.random.choice(dataset.image_ids, 4)\n\n# for ii in dataset.image_info:\n# if ii['filename'] == '000005160.tif':\n# image_ids = [ii['id']]\n# break\n\nfor image_id in image_ids:\n image = dataset.load_image(image_id)\n mask, class_ids = dataset.load_mask(image_id)\n visualize.display_top_masks(image, mask, class_ids, dataset.class_names)\n #print(dataset.image_info[image_id][\"filename\"])\n #log(\"mask\", mask)\n #log(\"class_ids\", class_ids)\n #print(class_ids)",
"_____no_output_____"
]
],
[
[
"dataset = dataset_train\navg0 = []\navg1 = []\navg2 = []\nfor i in dataset.image_ids:\n original_image, _, _, _, _ =\\\n modellib.load_image_gt(dataset, config, \n i, use_mini_mask=False)\n avg0.append(np.average(original_image[:,:,0]))\n avg1.append(np.average(original_image[:,:,1]))\n avg2.append(np.average(original_image[:,:,2]))\n \nprint(np.average(avg0), np.average(avg1), np.average(avg2))\n",
"_____no_output_____"
]
],
[
[
"## Ceate Model",
"_____no_output_____"
]
],
[
[
"# Create model in training mode\nmodel = modellib.MaskRCNN(mode=\"training\",\n config=config,\n model_dir=MODEL_DIR)",
"_____no_output_____"
],
[
"# Which weights to start with?\ninit_with = \"imagenet\" # imagenet, coco, or last\n\nif init_with == \"imagenet\":\n model.load_weights(model.get_imagenet_weights(), by_name=True)\nelif init_with == \"coco\":\n # Load weights trained on MS COCO, but skip layers that\n # are different due to the different number of classes\n # See README for instructions to download the COCO weights\n model.load_weights(COCO_MODEL_PATH, by_name=True,\n exclude=[\"mrcnn_class_logits\",\n \"mrcnn_bbox_fc\", \n \"mrcnn_bbox\",\n \"mrcnn_mask\"])\nelif init_with == \"last\":\n # Load the last model you trained and continue training\n model_path = model.find_last()\n print(\"Loading weights from \", model_path)\n model.load_weights(model_path, by_name=True)",
"_____no_output_____"
]
],
[
[
"## Training\n\nTrain in two stages:\n1. Only the heads. Here we're freezing all the backbone layers and training only the randomly initialized layers (i.e. the ones that we didn't use pre-trained weights from MS COCO). To train only the head layers, pass `layers='heads'` to the `train()` function.\n\n2. Fine-tune all layers. For this simple example it's not necessary, but we're including it to show the process. Simply pass `layers=\"all` to train all layers.",
"_____no_output_____"
]
],
[
[
"# Train the head branches\n# Passing layers=\"heads\" freezes all layers except the head\n# layers. You can also pass a regular expression to select\n# which layers to train by name pattern.\nmodel.train(dataset_train,\n dataset_val, \n learning_rate=config.LEARNING_RATE, \n epochs=10,\n layers='heads')",
"_____no_output_____"
],
[
"# Fine tune all layers\n# Passing layers=\"all\" trains all layers. You can also \n# pass a regular expression to select which layers to\n# train by name pattern.\n\n#image augmentation: https://github.com/aleju/imgaug\nimport imgaug as ia\nfrom imgaug import augmenters as iaa\n\nsometimes = lambda aug: iaa.Sometimes(0.5, aug)\nseqAug = iaa.Sequential(\n [\n # apply the following augmenters to most images\n iaa.Fliplr(0.5), # horizontally flip 50% of all images\n iaa.Flipud(0.5), # vertically flip 20% of all images\n # crop images by -10% to 10% of their height/width\n# sometimes(iaa.CropAndPad( # !!! Looks like memory curruption is hapenning somewhere in this C++ impl \n# percent=(-0.1, 0.1),\n# pad_mode=ia.ALL,\n# pad_cval=0\n# )),\n sometimes(iaa.Affine(\n scale={\"x\": (0.8, 1.2), \"y\": (0.8, 1.2)}, # scale images to 80-120% of their size, individually per axis\n translate_percent={\"x\": (-0.2, 0.2), \"y\": (-0.2, 0.2)}, # translate by -20 to +20 percent (per axis)\n rotate=(-175, 175), # rotate by -175 to +175 degrees\n shear=(-16, 16), # shear by -16 to +16 degrees\n order=[0, 1], # use nearest neighbour or bilinear interpolation (fast)\n cval=0, # if mode is constant, use a cval = 0\n mode=ia.ALL # use any of scikit-image's warping modes (see 2nd image from the top for examples)\n ))\n ],\n random_order=True\n)\n\nmodel.train(dataset_train, dataset_val, \n learning_rate=config.LEARNING_RATE / 100.0,\n epochs=180, \n layers=\"all\",\n augmentation=seqAug\n )",
"_____no_output_____"
]
],
[
[
"# Save weights\n# Typically not needed because callbacks save after every epoch\n# Uncomment to save manually\n# model_path = os.path.join(MODEL_DIR, \"mask_rcnn_shapes.h5\")\n# model.keras_model.save_weights(model_path)",
"_____no_output_____"
]
],
[
[
"## Detection",
"_____no_output_____"
]
],
[
[
"class InferenceConfig(MRConfig):\n GPU_COUNT = 1\n IMAGES_PER_GPU = 1\n DETECTION_MIN_CONFIDENCE = 0.9\n DETECTION_NMS_THRESHOLD = 0.2\n \n\ninference_config = InferenceConfig()\n\n# Recreate the model in inference mode\nmodel = modellib.MaskRCNN(mode=\"inference\", \n config=inference_config,\n model_dir=MODEL_DIR)\n\n# Get path to saved weights\n# Either set a specific path or find last trained weights\nmodel_path = model.find_last()\n# model_path = os.path.join(ROOT_DIR, \"./logs/r5_imgaug_roi1000_20180608T1627/mask_rcnn_r5_imgaug_roi1000__0570.h5\")\n\n# Load trained weights (fill in path to trained weights here)\nassert model_path != \"\", \"Provide path to trained weights\"\nprint(\"Loading weights from \", model_path)\nmodel.load_weights(model_path, by_name=True)",
"_____no_output_____"
],
[
"# Test on a random image\ndataset = dataset_test\n\nimage_id = random.choice(dataset.image_ids)\n\n# for ii in dataset.image_info:\n# if ii['filename'] == '000005160.tif':\n# image_id = ii['id']\n# break\n\noriginal_image, image_meta, gt_class_id, gt_bbox, gt_mask =\\\n modellib.load_image_gt(dataset, inference_config, \n image_id, use_mini_mask=False)\n\n# log(\"original_image\", original_image)\n# log(\"image_meta\", image_meta)\n# log(\"gt_class_id\", gt_class_id)\n# log(\"gt_bbox\", gt_bbox)\n# log(\"gt_mask\", gt_mask)\n# print(\"image_id: \", image_id)\n# print(dataset.image_info[image_id])\n\nresults = model.detect([original_image], verbose=1)\nr = results[0]\n#if r[\"masks\"].shape[2] > 0:\n# log(\"masks\", r[\"masks\"])\n\nax, fig = get_ax(1,2)\n\nvisualize.display_instances(original_image, gt_bbox, gt_mask, gt_class_id, \n dataset.class_names, ax=ax[0])\n\nvisualize.display_instances(original_image, r['rois'], r['masks'], r['class_ids'], \n dataset.class_names, r['scores'], ax=ax[1])\n\nAP, precisions, recalls, overlaps =\\\n utils.compute_ap(gt_bbox, gt_class_id, gt_mask,\n r[\"rois\"], r[\"class_ids\"], r[\"scores\"], r['masks'])\nprint(AP) ",
"_____no_output_____"
],
[
"fig.savefig(\"tank1.png\")",
"_____no_output_____"
]
],
[
[
"## Evaluation",
"_____no_output_____"
]
],
[
[
"# Compute VOC-Style mAP @ IoU=0.5\ndataset = dataset_val\nimage_ids = dataset.image_ids\nAPs = []\npss = []\nrcs = []\nops = []\nfor image_id in image_ids:\n # Load image and ground truth data\n image, image_meta, gt_class_id, gt_bbox, gt_mask =\\\n modellib.load_image_gt(dataset, inference_config,\n image_id, use_mini_mask=False)\n molded_images = np.expand_dims(modellib.mold_image(image, inference_config), 0)\n # Run object detection\n results = model.detect([image], verbose=0)\n r = results[0]\n # Compute AP\n AP, precisions, recalls, overlaps =\\\n utils.compute_ap(gt_bbox, gt_class_id, gt_mask,\n r[\"rois\"], r[\"class_ids\"], r[\"scores\"], r['masks'])\n APs.append(AP)\n pss.append(precisions)\n rcs.append(recalls)\n ops.append(overlaps)\n \nprint(\"mAP: \", np.mean(APs))",
"_____no_output_____"
]
]
]
| [
"code",
"markdown",
"code",
"markdown",
"code",
"raw",
"markdown",
"code",
"markdown",
"code",
"raw",
"markdown",
"code",
"markdown",
"code"
]
| [
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"raw"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"raw"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
]
|
cb5c22aa78454b84ecd3856637add6c60eaa2030 | 42,837 | ipynb | Jupyter Notebook | Week 2/Orthogonal Matching Pursuit.ipynb | Hanif-2610/Machine-Learning-Homework-Project | 16257c4b06eeb66ef847352b20e7009ed3ffaaf8 | [
"Unlicense"
]
| 1 | 2021-10-05T16:33:51.000Z | 2021-10-05T16:33:51.000Z | Week 2/Orthogonal Matching Pursuit.ipynb | Hanif-2610/Machine-Learning-Homework-Project | 16257c4b06eeb66ef847352b20e7009ed3ffaaf8 | [
"Unlicense"
]
| null | null | null | Week 2/Orthogonal Matching Pursuit.ipynb | Hanif-2610/Machine-Learning-Homework-Project | 16257c4b06eeb66ef847352b20e7009ed3ffaaf8 | [
"Unlicense"
]
| null | null | null | 42,837 | 42,837 | 0.928146 | [
[
[
"Using orthogonal matching pursuit for recovering a sparse signal from a noisy measurement encoded with a dictionary",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.linear_model import OrthogonalMatchingPursuit\nfrom sklearn.linear_model import OrthogonalMatchingPursuitCV\nfrom sklearn.datasets import make_sparse_coded_signal",
"_____no_output_____"
],
[
"n_components, n_features = 512, 100\nn_nonzero_coefs = 17",
"_____no_output_____"
],
[
"# generate the data\n\n# y = Xw\n# |x|_0 = n_nonzero_coefs\n\ny, X, w = make_sparse_coded_signal(\n n_samples=1,\n n_components=n_components,\n n_features=n_features,\n n_nonzero_coefs=n_nonzero_coefs,\n random_state=0,\n)\n\n(idx,) = w.nonzero()",
"_____no_output_____"
],
[
"# distort the clean signal\ny_noisy = y + 0.05 * np.random.randn(len(y))",
"_____no_output_____"
],
[
"# plot the sparse signal\nplt.figure(figsize=(7, 7))\nplt.subplot(4, 1, 1)\nplt.xlim(0, 512)\nplt.title(\"Sparse signal\")\nplt.stem(idx, w[idx], use_line_collection=True)",
"_____no_output_____"
],
[
"# plot the noise-free reconstruction\nomp = OrthogonalMatchingPursuit(n_nonzero_coefs=n_nonzero_coefs, normalize=False)\nomp.fit(X, y)\ncoef = omp.coef_\n(idx_r,) = coef.nonzero()\nplt.subplot(4, 1, 2)\nplt.xlim(0, 512)\nplt.title(\"Recovered signal from noise-free measurements\")\nplt.stem(idx_r, coef[idx_r], use_line_collection=True)",
"_____no_output_____"
],
[
"# plot the noisy reconstruction\nomp.fit(X, y_noisy)\ncoef = omp.coef_\n(idx_r,) = coef.nonzero()\nplt.subplot(4, 1, 3)\nplt.xlim(0, 512)\nplt.title(\"Recovered signal from noisy measurements\")\nplt.stem(idx_r, coef[idx_r], use_line_collection=True)",
"_____no_output_____"
],
[
"# plot the noisy reconstruction with number of non-zeros set by CV\nomp_cv = OrthogonalMatchingPursuitCV(normalize=False)\nomp_cv.fit(X, y_noisy)\ncoef = omp_cv.coef_\n(idx_r,) = coef.nonzero()\nplt.subplot(4, 1, 4)\nplt.xlim(0, 512)\nplt.title(\"Recovered signal from noisy measurements with CV\")\nplt.stem(idx_r, coef[idx_r], use_line_collection=True)\n\nplt.subplots_adjust(0.06, 0.04, 0.94, 0.90, 0.20, 0.38)\nplt.suptitle(\"Sparse signal recovery with Orthogonal Matching Pursuit\", fontsize=16)\nplt.show()",
"_____no_output_____"
]
]
]
| [
"markdown",
"code"
]
| [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
]
|
cb5c3fc15a1e782f67a7c7c133e8989c927b314a | 616 | ipynb | Jupyter Notebook | test/my-study/Untitled.ipynb | eoinmurray/cli-kyso-io | b5c8f5f21187604a6458b3cc7633d0171b4fad86 | [
"MIT"
]
| 3 | 2018-02-14T23:40:14.000Z | 2019-10-24T18:24:38.000Z | test/my-study/Untitled.ipynb | eoinmurray/cli-kyso-io | b5c8f5f21187604a6458b3cc7633d0171b4fad86 | [
"MIT"
]
| 1 | 2017-12-13T10:11:07.000Z | 2018-07-31T13:53:56.000Z | test/my-study/Untitled.ipynb | eoinmurray/cli-kyso-io | b5c8f5f21187604a6458b3cc7633d0171b4fad86 | [
"MIT"
]
| null | null | null | 16.648649 | 34 | 0.525974 | [
[
[
"Lest try some ES6 code\n",
"_____no_output_____"
]
]
]
| [
"code"
]
| [
[
"code"
]
]
|
cb5c44f96632ebfc20d022559a627801e02e03d0 | 93,020 | ipynb | Jupyter Notebook | Wk7_InClass.ipynb | Thomas6541/GEOS_505_Fall2018 | 45325703de3c07fd0fe889bb585472cdcfa0bba4 | [
"MIT"
]
| null | null | null | Wk7_InClass.ipynb | Thomas6541/GEOS_505_Fall2018 | 45325703de3c07fd0fe889bb585472cdcfa0bba4 | [
"MIT"
]
| null | null | null | Wk7_InClass.ipynb | Thomas6541/GEOS_505_Fall2018 | 45325703de3c07fd0fe889bb585472cdcfa0bba4 | [
"MIT"
]
| null | null | null | 246.084656 | 15,592 | 0.925177 | [
[
[
"import pandas\nimport numpy\nimport csv",
"_____no_output_____"
],
[
"Dict = pandas.read_csv('NURE_Reanalysis_DataDictionary_20171218.csv')",
"_____no_output_____"
],
[
"data = pandas.read_csv('reanalyzed_nure-hssrv2.0.csv')",
"_____no_output_____"
],
[
"data",
"_____no_output_____"
],
[
"IData = data.loc[data['State'] == 'ID']",
"_____no_output_____"
],
[
"Id_U = IData['U_ppm'].values",
"_____no_output_____"
],
[
"Id_U.max()",
"_____no_output_____"
],
[
"import matplotlib.pyplot \n#plot.set_ylabel('U_ppm')\nmatplotlib.pyplot.plot(Id_U,'g-')\nmatplotlib.pyplot.title('Uraniam in Idaho')\nmatplotlib.pyplot.xlabel('Sample #')\nmatplotlib.pyplot.ylabel('Uranium')\nmatplotlib.pyplot.show()",
"_____no_output_____"
]
],
[
[
"#### Note to self. \nTo plot the data as an area map with lat and long data, read email. \nhttps://matplotlib.org/api/_as_gen/matplotlib.pyplot.scatter.html ",
"_____no_output_____"
]
],
[
[
"MData = data.loc[data['State'] == 'MT']\nMT_U = MData['U_ppm'].values\nMT_U.max()",
"_____no_output_____"
],
[
"matplotlib.pyplot.plot(MT_U,'b-')\nmatplotlib.pyplot.title('Uraniam in Montana')\nmatplotlib.pyplot.xlabel('Sample #')\nmatplotlib.pyplot.ylabel('Uranium')\nmatplotlib.pyplot.show()",
"_____no_output_____"
],
[
"NMData = data.loc[data['State'] == 'NM']\nNM_U = NMData['U_ppm'].values\nNM_U.max()",
"_____no_output_____"
],
[
"matplotlib.pyplot.plot(NM_U,'b-')\nmatplotlib.pyplot.title('Uraniam in New Mexico')\nmatplotlib.pyplot.xlabel('Sample #')\nmatplotlib.pyplot.ylabel('Uranium')\nmatplotlib.pyplot.show()",
"_____no_output_____"
],
[
"AZData = data.loc[data['State'] == 'AZ']\nAZ_U = AZData['U_ppm'].values\nAZ_U.max()",
"_____no_output_____"
],
[
"matplotlib.pyplot.plot(AZ_U,'b-')\nmatplotlib.pyplot.title('Uraniam in Arizona')\nmatplotlib.pyplot.xlabel('Sample #')\nmatplotlib.pyplot.ylabel('Uranium')\nmatplotlib.pyplot.show()",
"_____no_output_____"
],
[
"NVData = data.loc[data['State'] == 'NV']\nNV_U = NVData['U_ppm'].values\nNV_U.max()\nmatplotlib.pyplot.plot(NV_U,'b-')\nmatplotlib.pyplot.title('Uraniam in Nevada')\nmatplotlib.pyplot.xlabel('Sample #')\nmatplotlib.pyplot.ylabel('Uranium')\nmatplotlib.pyplot.show()",
"_____no_output_____"
],
[
"UTData = data.loc[data['State'] == 'UT']\nUT_U = UTData['U_ppm'].values\nUT_U.max()\nmatplotlib.pyplot.plot(UT_U,'b-')\nmatplotlib.pyplot.title('Uraniam in Utah')\nmatplotlib.pyplot.xlabel('Sample #')\nmatplotlib.pyplot.ylabel('Uranium')\nmatplotlib.pyplot.show()",
"_____no_output_____"
]
],
[
[
"### In Class code to plot data that has an odd date format\nmatplot.lib tour\ndf.plot(x='Time',y='Quibits')\nplt.show()\n###### what is missing, is we need to force python to show the 'tick-labels'. \nto append a new array (datearr_dt) to the data, just do the following \n\ndf['NP_Datetime'] = datearr_dt\n\nthen the array is appended to the last column of the data\n###### now plot it\nax = df.plot(x='NP_Datetime',y='Quibits')\n\nmyFmt = mdates.DateFormatter('%d\\')\n\naz.xaxis.set_major_formatter(myfit)\n\nplt.show()",
"_____no_output_____"
]
]
]
| [
"code",
"markdown",
"code",
"markdown"
]
| [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
]
|
cb5c4a00c144a57b7aa402a1f9fa8bc63a5d2bea | 59,276 | ipynb | Jupyter Notebook | notebooks/02_parameter_exploration.ipynb | axiezai/complex_laplacian | e84574a7d9c051a95b5d37aa398765aeb5f85fa4 | [
"MIT"
]
| null | null | null | notebooks/02_parameter_exploration.ipynb | axiezai/complex_laplacian | e84574a7d9c051a95b5d37aa398765aeb5f85fa4 | [
"MIT"
]
| null | null | null | notebooks/02_parameter_exploration.ipynb | axiezai/complex_laplacian | e84574a7d9c051a95b5d37aa398765aeb5f85fa4 | [
"MIT"
]
| 1 | 2021-11-19T19:04:18.000Z | 2021-11-19T19:04:18.000Z | 122.724638 | 25,868 | 0.829493 | [
[
[
"Complex Laplacian and its eigenmodes are parameterized by $\\alpha$ and $k$.\n---\n\nTheory and math behind the eigenmodes:\n\nThe simplest possible dynamic behavior of a damped system is the first order differential equation with one term, and it's rate of exponential decay is governed by a rate contant $\\beta$:\n\n\\begin{equation}\n\\label{dampedSys}\n \\frac{dx_{1}(t)}{dt} = -\\beta x_{1}(t)\n\\end{equation}\n\nWhere $x_{1}(t)$ is the average neuronal activation signal between all neurons within a region of interest. Thus we can interpret the above equation as the refractory period after neural discharge. But when viewing the brain as a network of interconnected regions, we want to introduce activities originating from other regions:\n\n\\begin{equation}\n \\frac{dx_{i}(t)}{dt} = -\\beta (x_{i}(t) - \\frac{\\alpha}{\\pmb{deg_i}} \\sum_{i,j} c_{i,j} x_{j}(t-\\tau^{\\nu}_{i,j}))\n\\end{equation}\n\nThe above equation introduces a connectivity $c_{i,j}$ term, which is normalized by a diagonal degree matrix and scaled by a coupling term $\\alpha$. $\\alpha$ acts as both a coupling constant as well as a parameter to distinguish the rate of diffusion from connected regions from $\\beta$. By introducing connectivity, we also have to take into account the distance between each connected regions, therefore the term $\\tau^{\\nu}_{i,j}$ is introduced as delay, and is computed by dividing fiber tract distance between regions and signal transmission velocity. Now if we transform the above equation into the Fourier domain, we obtain the follow complex expression:\n\n\\begin{equation}\n\\begin{aligned}\n j\\omega X(\\omega)_{i} = -\\beta X(\\omega)_{i} + \\frac{\\alpha}{\\pmb{deg_i}} \\sum_j c_{i,j} e^{-j\\omega \\tau^{\\nu}_{i,j}} X(\\omega)\\\\\n j\\omega \\bar{X}(\\omega) = -\\beta (I - \\alpha \\Delta^{-\\frac{1}{2}} C^{*}(\\omega)) \\bar{X}(\\omega)\\\\\n j\\omega \\bar{X}(\\omega) = -B\\mathcal{L}\\bar{X}(\\omega)\\\\\n\\end{aligned}\n\\end{equation}\n\nHere, we introduced a complex component to our structural connectivity term as delays become phases in the Fourier domain, specifically, $x(t-\\tau^{\\nu}_{i,j}) \\to e^{-j\\omega \\tau^{\\nu}_{i,j}} X(\\omega)$, thus we can define a complex connectivity as a function of angular frequency $\\omega$ as $C(\\omega) = \\frac{1}{\\pmb{deg}}C^{*}(\\omega)$, where $C^{*}(\\omega) = c_{i,j}e^{-j\\omega \\tau^{\\nu}_{i,j}}$. By redefining the connectivity term from above, the complex Laplacian $\\mathcal{L}(\\omega)$ is then defined as $\\mathcal{L}(\\omega) = I - \\alpha C(\\omega)$. Next we decompose the complex Laplacian matrix $\\mathcal{L}$ into it's eigen modes and eigen values:\n\n\\begin{equation}\n \\mathcal{L}(\\omega) = \\pmb(U)(\\omega)\\pmb{\\Lambda}(\\omega)\\pmb{U}(\\omega)^H\n\\end{equation}\n\nWhere $\\pmb{\\Lambda}(\\omega) = diag([\\lambda_1(\\omega), ... , \\lambda_N(\\omega)])$ is a diagonal matrix consisting of the eigen values of the complex Laplacian matrix at angular frequency $\\omega$, and $\\pmb{U}(\\omega)$ are the eigen modes of the complex Laplacian matrix at angular frequency $\\omega$. We are going to see how these eigenmodes behave in their parameter space:",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# spectrome imports\nfrom spectrome.brain import Brain\nfrom spectrome.utils import functions, path\nfrom spectrome.forward import eigenmode, runforward",
"_____no_output_____"
],
[
"# Some house keeping:\ndata_dir = \"../data\"\n\n# Define frequency range of interest\nfmin = 2 # 2Hz - 45Hz signal range, filter for this with hbp\nfmax = 45\nfvec = np.linspace(fmin, fmax, 40)\n\n# Load Pablo's Yeo 2017 canonical network maps\nfc_dk = np.load(\"../data/com_dk.npy\", allow_pickle=True).item()\nfc_dk_normalized = pd.read_csv(\"../data/DK_dictionary_normalized.csv\").set_index(\n \"Unnamed: 0\"\n)\n\n# Define variables for analysis:\nalpha_vec = np.linspace(\n 0.5, 4.5, 17\n) # np.linspace(0.5,5,10) # coupling strength values we are going to explore\nk_vec = np.linspace(0, 100, 11) # wave numbers we are going to explore\nnum_fc = 7 # 7 canonical networks\nnum_emode = 86 # number of eigenmodes, we are using 86 region DK atlas\n\ndefault_k = 20 # default wave number\ndefault_alpha = 0.1 # default alpha\n\n# define list of canonical network names and re-order the dictionary using these names:\nfc_names = [\n \"Limbic\",\n \"Default\",\n \"Visual\",\n \"Fronto \\n parietal\",\n \"Somato \\n motor\",\n \"Dorsal \\n Attention\",\n \"Ventral \\n Attention\",\n]\nfc_dk_normalized = fc_dk_normalized.reindex(\n [\n \"Limbic\",\n \"Default\",\n \"Visual\",\n \"Frontoparietal\",\n \"Somatomotor\",\n \"Dorsal_Attention\",\n \"Ventral_Attention\",\n ]\n).fillna(0)\n\n# turbo color map\nturbo = functions.create_turbo_colormap()",
"_____no_output_____"
]
],
[
[
"#### Explore varying coupling strength while keeping wave number default first",
"_____no_output_____"
]
],
[
[
"## Create Brain object from spectrome\nalpha_brain = Brain.Brain()\nalpha_brain.add_connectome(data_dir)\nalpha_brain.reorder_connectome(alpha_brain.connectome, alpha_brain.distance_matrix)\nalpha_brain.bi_symmetric_c()\nalpha_brain.reduce_extreme_dir()\n\n## Compute correlation values:\nalpha_corr = np.zeros((num_emode, num_fc, len(alpha_vec)))\nfor a_ind in np.arange(0, len(alpha_vec)):\n alpha_brain.decompose_complex_laplacian(alpha=alpha_vec[a_ind], k=default_k)\n alpha_corr[:, :, a_ind] = eigenmode.get_correlation_df(\n alpha_brain.norm_eigenmodes, fc_dk_normalized, method=\"spearman\"\n )",
"_____no_output_____"
],
[
"## set-up some visualization details\ndynamic_range = [0.35, 0.65] # for colormap\n# for coupling strength labels and number of ticks on x-axis:\nalpha_labels = np.linspace(0.5, 4.5, 3)\nn_ticks = 3\n\n## PLOT\nwith plt.style.context(\"seaborn-paper\"):\n alpha_corr_fig, alpha_ax = plt.subplots(1, 7, figsize=(7.0, 4.0), sharey=True)\n for i, ax in enumerate(alpha_corr_fig.axes):\n im = ax.imshow(alpha_corr[:, i, :], vmin=0, vmax=1, cmap=turbo, aspect=\"auto\")\n ax.xaxis.set_major_locator(\n plt.LinearLocator(numticks=n_ticks)\n ) # LinearLocator(numticks = n_ticks)\n ax.set_yticklabels([0, 1, 10, 20, 30, 40, 50, 60, 70, 80])\n ax.xaxis.tick_top()\n ax.set_xticklabels(alpha_labels, linespacing=0.2)\n im.set_clim(dynamic_range)\n\n plt.suptitle(\"Coupling Strength\", fontsize=12, fontweight=\"bold\", y=1.025)\n\n #cbar_ax = alpha_corr_fig.add_axes([1, 0.15, 0.03, 0.7])\n #cb = alpha_corr_fig.colorbar(im, cax=cbar_ax, extend=\"both\")\n #alpha_corr_fig.add_subplot(1, 1, 1, frameon=False)\n #plt.tick_params(labelcolor=\"none\", which=\"both\", axis = \"both\", top=\"off\", bottom=\"off\", left=\"off\", right=\"off\")\n #plt.grid(False)\n #plt.ylabel(\"Eigenmode Number\", fontsize=12)\n \n alpha_corr_fig.text(-0.008, 0.25, 'Eigenmode Number', rotation = 'vertical', fontsize = 12)\n plt.tight_layout(w_pad = 0.30)\n plt.savefig(\"../figures/fig4/coupling_strength.png\", dpi=300, bbox_inches=\"tight\")",
"_____no_output_____"
]
],
[
[
"#### Set to default $\\alpha$ and explore wave number now:",
"_____no_output_____"
]
],
[
[
"## Brain object with spectrome\nk_brain = Brain.Brain()\nk_brain.add_connectome(data_dir)\nk_brain.reorder_connectome(k_brain.connectome, k_brain.distance_matrix)\nk_brain.bi_symmetric_c()\nk_brain.reduce_extreme_dir()\n\n# preallocate empty correlation df\nk_corr = np.zeros((num_emode, num_fc, len(k_vec)))\n\n## Compute correlations\nfor k in np.arange(0, len(k_vec)):\n k_brain.decompose_complex_laplacian(alpha=default_alpha, k=k_vec[k], num_ev=86)\n k_corr[:, :, k] = eigenmode.get_correlation_df(\n k_brain.norm_eigenmodes, fc_dk_normalized, method=\"spearman\"\n )",
"_____no_output_____"
],
[
"n_ticks = 3\nk_labels = [0, 50, 100]\n\n## PLOT\nwith plt.style.context(\"seaborn-paper\"):\n k_corr_fig, k_ax = plt.subplots(1, 7, figsize=(6.25, 4.0), sharey=True)\n for i, ax in enumerate(k_corr_fig.axes):\n im = ax.imshow(k_corr[:, i, :], vmin=0, vmax=1, cmap=turbo, aspect=\"auto\")\n ax.xaxis.set_major_locator(\n plt.LinearLocator(numticks=n_ticks)\n ) # LinearLocator(numticks = n_ticks)\n ax.set_yticklabels([0, 1, 10, 20, 30, 40, 50, 60, 70, 80])\n ax.xaxis.tick_top()\n ax.set_xticklabels(k_labels)\n im.set_clim(dynamic_range)\n if i < 3:\n ax.set_title(fc_names[i], y=-0.08, fontsize=8, weight=\"bold\")\n else:\n ax.set_title(fc_names[i], y=-0.12, fontsize=8, weight=\"bold\")\n\n plt.suptitle(\"Wave Number\", fontsize=12, fontweight=\"bold\", y=1.025)\n\n cbar_ax = k_corr_fig.add_axes([1, 0.15, 0.03, 0.7])\n cb = k_corr_fig.colorbar(im, cax=cbar_ax, extend=\"both\")\n cb.set_label(r'Spatial Similarity to $\\Psi_{CFN}$')\n #k_corr_fig.add_subplot(1, 1, 1, frameon=False)\n #plt.tick_params(labelcolor=\"none\", top=\"off\", bottom=\"off\", left=\"off\", right=\"off\")\n #plt.grid(False)\n #plt.ylabel(\"Eigenmode Number\", fontsize=12)\n k_corr_fig.text(-0.008, 0.35, 'Eigenmode Number', rotation = 'vertical', fontsize = 12)\n\n plt.tight_layout(w_pad = 0.25)\n plt.savefig(\"../figures/fig4/wave_number.png\", dpi=300, bbox_inches=\"tight\")",
"<ipython-input-33-caa4c14ef099>:32: UserWarning: This figure includes Axes that are not compatible with tight_layout, so results might be incorrect.\n plt.tight_layout(w_pad = 0.25)\n"
]
],
[
[
"Complex Laplacian Eigenmodes\n---\n\nFind the highest spatial corelation values achieved by the best performing eigenmodes for each canonical network:",
"_____no_output_____"
],
[
"Compute Spearman correlation values:",
"_____no_output_____"
]
],
[
[
"# pre-allocate an array for spearman R of best performing eigenmodes:\nparams_bestr = np.zeros((len(alpha_vec), len(k_vec), num_fc))\n\n# Create brain object from spectrome with HCP connectome:\nhcp_brain = Brain.Brain()\nhcp_brain.add_connectome(data_dir)\nhcp_brain.reorder_connectome(hcp_brain.connectome, hcp_brain.distance_matrix)\nhcp_brain.bi_symmetric_c()\nhcp_brain.reduce_extreme_dir()\n\n# for each network, scan through alpha and k values, compute all eigenmode's spearman R\n# then select the best performing eigenmode's spearman R\nfor i in np.arange(0, num_fc):\n print('Computing for {} network'.format(fc_dk_normalized.index[i]))\n for a_ind in np.arange(0, len(alpha_vec)):\n for k_ind in np.arange(0, len(k_vec)):\n # get eigenmodes of complex laplacian:\n hcp_brain.decompose_complex_laplacian(alpha = alpha_vec[a_ind], k = k_vec[k_ind])\n # compute spearman correlation\n spearman_eig = eigenmode.get_correlation_df(\n hcp_brain.norm_eigenmodes, fc_dk_normalized.iloc[[i]], method = 'spearman'\n )\n params_bestr[a_ind, k_ind, i] = np.max(spearman_eig.values)",
"_____no_output_____"
]
],
[
[
"Visualize in heatmap:",
"_____no_output_____"
]
],
[
[
"dynamic_range = [0.30, 0.65]\nk_ticks = 11\nk_labels = np.linspace(0, 100, 11).astype(int)\na_ticks = 3\na_labels = np.linspace(0.5, 4.5, 3)\n\nwith plt.style.context(\"seaborn-paper\"):\n corr_fig, corr_ax = plt.subplots(1,7, figsize = (8,5))\n for i, ax in enumerate(corr_fig.axes):\n im = ax.imshow(np.transpose(params_bestr[:,:,i]), vmin = 0, vmax = 1, cmap = turbo, aspect = 'auto')\n ax.yaxis.set_major_locator(plt.LinearLocator(numticks = k_ticks))\n ax.xaxis.tick_top()\n ax.set_yticklabels(k_labels)\n ax.xaxis.set_major_locator(plt.LinearLocator(numticks = a_ticks))\n ax.set_xticklabels(a_labels)\n im.set_clim(dynamic_range)\n if i < 3:\n ax.set_title(fc_names[i], y=-0.08, fontsize=8, weight=\"bold\")\n else:\n ax.set_title(fc_names[i], y=-0.12, fontsize=8, weight=\"bold\")\n \n plt.suptitle('Coupling Strength', fontsize = 12, y = 1)\n cbar_ax = corr_fig.add_axes([1, 0.15, 0.03, 0.7])\n cb = corr_fig.colorbar(im, cax=cbar_ax, extend=\"both\")\n corr_fig.add_subplot(1, 1, 1, frameon=False)\n plt.tick_params(labelcolor=\"none\", top=\"off\", bottom=\"off\", left=\"off\", right=\"off\")\n plt.grid(False)\n plt.ylabel('Wave Number', fontsize = 12)\n \n plt.tight_layout()\n plt.savefig('../figures/fig5/param_bestr.png', dpi = 300, bbox_inches = 'tight')",
"_____no_output_____"
]
],
[
[
"Note - global coupling doesn't affect the best performing eigenmode but may change which eigenmode is the best performing eigenmode as well as the other eigenmodes.",
"_____no_output_____"
],
[
"Split the wave number parameter into oscillatory frequency and signal transmission velocity since wave number $k$ is defined as $k = \\frac{2 \\pi f}{\\nu}$. Then perform the same exploratory exercise as above:",
"_____no_output_____"
]
],
[
[
"# define parameter ranges:\nfreq_vec = np.linspace(2, 47, 46)\nnu_vec = np.linspace(1, 20, 21)\n\n# define plotting visuals\ndynamic_range = [0.3, 0.7]\nf_ticks = 6\nf_labels = np.linspace(2, 47, 6).astype(int)\nnu_ticks = 3\nnu_labels = np.linspace(0.5, 20, 3).astype(int)\n\n#pre-allocate array for results\nk_bestr = np.zeros((len(freq_vec), len(nu_vec), num_fc))\n\n# compute spearman Rs:\nfor i in np.arange(0, num_fc):\n print('Computing for {} network'.format(fc_dk_normalized.index[i]))\n for f_ind in np.arange(0, len(freq_vec)):\n for v_ind in np.arange(0, len(nu_vec)):\n # get eigenmodes of complex laplacian:\n hcp_brain.decompose_complex_laplacian(alpha = default_alpha, k = None, f = freq_vec[f_ind], speed = nu_vec[v_ind])\n # compute spearman correlation\n spearman_eig = eigenmode.get_correlation_df(\n hcp_brain.norm_eigenmodes, fc_dk_normalized.iloc[[i]], method = 'spearman'\n )\n k_bestr[f_ind, v_ind, i] = np.max(spearman_eig.values)\n \n# Plot as above:\nwith plt.style.context(\"seaborn-paper\"):\n k_fig, k_ax = plt.subplots(1,7, figsize = (8,4))\n for i, ax in enumerate(k_fig.axes):\n im = ax.imshow(k_bestr[:,:,i], vmin = 0, vmax = 1, cmap = turbo, aspect = 'auto')\n ax.yaxis.set_major_locator(plt.LinearLocator(numticks = f_ticks))\n ax.xaxis.tick_top()\n ax.set_yticklabels(f_labels)\n ax.xaxis.set_major_locator(plt.LinearLocator(numticks = nu_ticks))\n ax.set_xticklabels(nu_labels)\n im.set_clim(dynamic_range)\n if i < 3:\n ax.set_title(fc_names[i], y=-0.08, fontsize=8, weight=\"bold\")\n else:\n ax.set_title(fc_names[i], y=-0.12, fontsize=8, weight=\"bold\")\n \n plt.suptitle('Transmission Velocity (m/s)', fontsize = 12, y = 1)\n cbar_ax = k_fig.add_axes([1, 0.15, 0.03, 0.7])\n cb = k_fig.colorbar(im, cax=cbar_ax, extend=\"both\")\n k_fig.add_subplot(1, 1, 1, frameon=False)\n plt.tick_params(labelcolor=\"none\", top=\"off\", bottom=\"off\", left=\"off\", right=\"off\")\n plt.grid(False)\n plt.ylabel('Frequency (Hz)', fontsize = 12)\n \n plt.tight_layout()\n plt.savefig('../figures/fig5/k_bestr.png', dpi = 300, bbox_inches = 'tight')",
"_____no_output_____"
]
]
]
| [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
]
| [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
]
]
|
cb5c4d0bc2a7b335e24924b26683ff4f9e92faf0 | 7,796 | ipynb | Jupyter Notebook | PyTorch Recipes/Part 1/loading_data_recipe.ipynb | LbsIrving/PyTorch | 314dbe9efc9e0116a7342d4ae3ab168c1c3afa32 | [
"MIT"
]
| null | null | null | PyTorch Recipes/Part 1/loading_data_recipe.ipynb | LbsIrving/PyTorch | 314dbe9efc9e0116a7342d4ae3ab168c1c3afa32 | [
"MIT"
]
| null | null | null | PyTorch Recipes/Part 1/loading_data_recipe.ipynb | LbsIrving/PyTorch | 314dbe9efc9e0116a7342d4ae3ab168c1c3afa32 | [
"MIT"
]
| null | null | null | 55.685714 | 1,256 | 0.618779 | [
[
[
"%matplotlib inline",
"_____no_output_____"
]
],
[
[
"\nLoading data in PyTorch\n=======================\nPyTorch features extensive neural network building blocks with a simple,\nintuitive, and stable API. PyTorch includes packages to prepare and load\ncommon datasets for your model.\n\nIntroduction\n------------\nAt the heart of PyTorch data loading utility is the\n`torch.utils.data.DataLoader <https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader>`__\nclass. It represents a Python iterable over a dataset. Libraries in\nPyTorch offer built-in high-quality datasets for you to use in\n`torch.utils.data.Dataset <https://pytorch.org/docs/stable/data.html#torch.utils.data.Dataset>`__.\nThese datasets are currently available in:\n\n* `torchvision <https://pytorch.org/docs/stable/torchvision/datasets.html>`__\n* `torchaudio <https://pytorch.org/audio/datasets.html>`__\n* `torchtext <https://pytorch.org/text/datasets.html>`__\n\nwith more to come.\nUsing the Yesno dataset from ``torchaudio.datasets.YESNO``, we will\ndemonstrate how to effectively and efficiently load data from a PyTorch\n``Dataset`` into a PyTorch ``DataLoader``.\n\nSetup\n-----\nBefore we begin, we need to install ``torchaudio`` to have access to the\ndataset.\n\n::\n\n pip install torchaudio\n\n\n\n",
"_____no_output_____"
],
[
"Steps\n-----\n\n1. Import all necessary libraries for loading our data\n2. Access the data in the dataset\n3. Loading the data\n4. Iterate over the data\n5. [Optional] Visualize the data\n\n\n1. Import necessary libraries for loading our data\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nFor this recipe, we will use ``torch`` and ``torchaudio``. Depending on\nwhat built-in datasets you use, you can also install and import\n``torchvision`` or ``torchtext``.\n\n\n",
"_____no_output_____"
]
],
[
[
"import torch\nimport torchaudio",
"_____no_output_____"
]
],
[
[
"2. Access the data in the dataset\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe Yesno dataset in ``torchaudio`` features sixty recordings of one\nindividual saying yes or no in Hebrew; with each recording being eight\nwords long (`read more here <https://www.openslr.org/1/>`__).\n\n``torchaudio.datasets.YESNO`` creates a dataset for YesNo.\n\n::\n\n torchaudio.datasets.YESNO(\n root,\n url='http://www.openslr.org/resources/1/waves_yesno.tar.gz',\n folder_in_archive='waves_yesno',\n download=False,\n transform=None,\n target_transform=None)\n\nEach item in the dataset is a tuple of the form: (waveform, sample_rate,\nlabels).\n\nYou must set a ``root`` for the Yesno dataset, which is where the\ntraining and testing dataset will exist. The other parameters are\noptional, with their default values shown. Here is some additional\nuseful info on the other parameters:\n\n",
"_____no_output_____"
]
],
[
[
"# * ``download``: If true, downloads the dataset from the internet and puts it in root directory. If dataset is already downloaded, it is not downloaded again.\n# * ``transform``: Using transforms on your data allows you to take it from its source state and transform it into data that’s joined together, de-normalized, and ready for training. Each library in PyTorch supports a growing list of transformations.\n# * ``target_transform``: A function/transform that takes in the target and transforms it.\n# \n# Let’s access our Yesno data:\n# \n\n# A data point in Yesno is a tuple (waveform, sample_rate, labels) where labels \n# is a list of integers with 1 for yes and 0 for no.\nyesno_data_trainset = torchaudio.datasets.YESNO('./', download=True)\n\n# Pick data point number 3 to see an example of the the yesno_data:\nn = 3\nwaveform, sample_rate, labels = yesno_data[n]\nprint(\"Waveform: {}\\nSample rate: {}\\nLabels: {}\".format(waveform, sample_rate, labels))",
"_____no_output_____"
]
],
[
[
"When using this data in practice, it is best practice to provision the\ndata into a “training” dataset and a “testing” dataset. This ensures\nthat you have out-of-sample data to test the performance of your model.\n\n3. Loading the data\n~~~~~~~~~~~~~~~~~~~~~~~\n\nNow that we have access to the dataset, we must pass it through\n``torch.utils.data.DataLoader``. The ``DataLoader`` combines the dataset\nand a sampler, returning an iterable over the dataset.\n\n\n",
"_____no_output_____"
]
],
[
[
"data_loader = torch.utils.data.DataLoader(yesno_data,\n batch_size=1,\n shuffle=True)",
"_____no_output_____"
]
],
[
[
"4. Iterate over the data\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nOur data is now iterable using the ``data_loader``. This will be\nnecessary when we begin training our model! You will notice that now\neach data entry in the ``data_loader`` object is converted to a tensor\ncontaining tensors representing our waveform, sample rate, and labels.\n\n\n",
"_____no_output_____"
]
],
[
[
"for data in data_loader:\n print(\"Data: \", data)\n print(\"Waveform: {}\\nSample rate: {}\\nLabels: {}\".format(data[0], data[1], data[2]))\n break",
"_____no_output_____"
]
],
[
[
"5. [Optional] Visualize the data\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nYou can optionally visualize your data to further understand the output\nfrom your ``DataLoader``.\n\n\n",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\n\nprint(data[0][0].numpy())\n\nplt.figure()\nplt.plot(waveform.t().numpy())",
"_____no_output_____"
]
],
[
[
"Congratulations! You have successfully loaded data in PyTorch.\n\nLearn More\n----------\n\nTake a look at these other recipes to continue your learning:\n\n- `Defining a Neural Network <https://pytorch.org/tutorials/recipes/recipes/defining_a_neural_network.html>`__\n- `What is a state_dict in PyTorch <https://pytorch.org/tutorials/recipes/recipes/what_is_state_dict.html>`__\n\n",
"_____no_output_____"
]
]
]
| [
"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"
]
]
|
cb5c764bbedc3db43a9e792893b23317d35ec5f0 | 13,029 | ipynb | Jupyter Notebook | tutorials/Large_Scale_Training.ipynb | stjordanis/vissl | 8800989f9bf073693b777c14ea01b585d4b306d6 | [
"MIT"
]
| 3 | 2021-07-08T15:06:49.000Z | 2021-08-13T18:55:02.000Z | tutorials/Large_Scale_Training.ipynb | stjordanis/vissl | 8800989f9bf073693b777c14ea01b585d4b306d6 | [
"MIT"
]
| 2 | 2021-07-25T15:46:07.000Z | 2021-08-11T10:08:53.000Z | tutorials/Large_Scale_Training.ipynb | stjordanis/vissl | 8800989f9bf073693b777c14ea01b585d4b306d6 | [
"MIT"
]
| 2 | 2021-07-08T15:15:55.000Z | 2021-08-25T14:16:01.000Z | 43.868687 | 312 | 0.598741 | [
[
[
"# Large Scale Training with VISSL Training (mixed precision, LARC, ZeRO etc)\n\nIn this tutorial, show configuration settings that users can set for training large models.\n\nYou can make a copy of this tutorial by `File -> Open in playground mode` and make changes there. DO NOT request access to this tutorial.",
"_____no_output_____"
],
[
"# Using LARC\n\nLARC (Large Batch Training of Convolutional Networks) is a technique proposed by **Yang You, Igor Gitman, Boris Ginsburg** in https://arxiv.org/abs/1708.03888 for improving the convergence of large batch size trainings.\nLARC uses the ratio between gradient and parameter magnitudes is used to calculate an adaptive local learning rate for each individual parameter.\n\nSee the [LARC paper](<https://arxiv.org/abs/1708.03888>) for calculation of learning rate. In practice, it modifies the gradients of parameters as a proxy\nfor modifying the learning rate of the parameters.\n\n\n",
"_____no_output_____"
],
[
"## How to enable LARC\n\nVISSL supports the LARC implementation from [NVIDIA's Apex LARC](https://github.com/NVIDIA/apex/blob/master/apex/parallel/LARC.py). To use LARC, users need to set config option\n:code:`OPTIMIZER.use_larc=True`. VISSL exposes LARC parameters that users can tune. Full list of LARC parameters exposed by VISSL:\n\n\n```yaml\nOPTIMIZER:\n name: \"sgd\"\n use_larc: False # supported for SGD only for now\n larc_config:\n clip: False\n eps: 1e-08\n trust_coefficient: 0.001\n```\n\n**NOTE:** LARC is currently supported for SGD optimizer only in VISSL.\n\n\n",
"_____no_output_____"
],
[
"# Using Apex\n\n\nIn order to use Apex, VISSL provides `anaconda` and `pip` packages of Apex (compiled with Optimzed C++ extensions/CUDA kernels). The Apex\npackages are provided for all versions of `CUDA (9.2, 10.0, 10.1, 10.2, 11.0), PyTorch >= 1.4 and Python >=3.6 and <=3.9`.\n\nFollow VISSL's instructions to [install apex in pip](https://github.com/facebookresearch/vissl/blob/master/INSTALL.md#step-2-install-pytorch-opencv-and-apex-pip) and instructions to [install apex in conda](https://github.com/facebookresearch/vissl/blob/master/INSTALL.md#step-3-install-apex-conda>).",
"_____no_output_____"
],
[
"# Using Mixed Precision\n\nMany self-supervised approaches leverage mixed precision training by default for better training speed and reducing the model memory requirement.\nFor this, we use [NVIDIA Apex Library with AMP](https://nvidia.github.io/apex/amp.html#o1-mixed-precision-recommended-for-typical-use).\n\nUsers can tune the AMP level to the levels supported by NVIDIA. See [this for details on Apex amp levels](https://nvidia.github.io/apex/amp.html#opt-levels).\n\nTo use Mixed precision training, one needs to set the following parameters in configuration file:\n\n\n```yaml\nMODEL:\n AMP_PARAMS:\n USE_AMP: True\n # Use O1 as it is robust and stable than O3. If you want to use O3, we recommend\n # the following setting:\n # {\"opt_level\": \"O3\", \"keep_batchnorm_fp32\": True, \"master_weights\": True, \"loss_scale\": \"dynamic\"}\n AMP_ARGS: {\"opt_level\": \"O1\"}\n```",
"_____no_output_____"
],
[
"# Using ZeRO\n\n**ZeRO: Memory Optimizations Toward Training Trillion Parameter Models** is a technique developed by **Samyam Rajbhandari, Jeff Rasley, Olatunji Ruwase, Yuxiong He** in [this paper](https://arxiv.org/abs/1910.02054).\nWhen training models with billions of parameters, GPU memory becomes a bottleneck. ZeRO can offer 4x to 8x memory reductions in memory thus allowing to fit larger models in memory.\n",
"_____no_output_____"
],
[
"## How ZeRO works?\n\n\nMemory requirement of a model can be broken down roughly into:\n\n1. activations memory\n2. model parameters\n3. parameters momentum buffers (optimizer state)\n4. parameters gradients\n\nZeRO *shards* the optimizer state and the parameter gradients onto different devices and reduces the memory needed per device.\n",
"_____no_output_____"
],
[
"## How to use ZeRO in VISSL?\n\nVISSL uses [FAIRScale](https://github.com/facebookresearch/fairscale)_ library which implements ZeRO in PyTorch.\nUsing VISSL in ZeRO involves no code changes and can simply be done by setting some configuration options in the yaml files.\n\nIn order to use ZeRO, user needs to set `OPTIMIZER.name=zero` and nest the desired optimizer (for example SGD) settings in `OPTIMIZER.base_optimizer`.\n\nAn example for using ZeRO with LARC and SGD optimization:\n```yaml\nOPTIMIZER:\n name: zero\n base_optimizer:\n name: sgd\n use_larc: False\n larc_config:\n clip: False\n trust_coefficient: 0.001\n eps: 0.00000001\n weight_decay: 0.000001\n momentum: 0.9\n nesterov: False\n```\n\n**NOTE**: ZeRO works seamlessly with LARC and mixed precision training. Using ZeRO with activation checkpointing is not yet enabled primarily due to manual gradient reduction need for activation checkpointing.\n",
"_____no_output_____"
],
[
"# Using Stateful Data Sampler",
"_____no_output_____"
],
[
"## Issue with PyTorch DataSampler for large data training\n\n\nPyTorch default [torch.utils.data.distributed.DistributedSampler](https://github.com/pytorch/pytorch/blob/master/torch/utils/data/distributed.py#L12) is the default sampler used for many trainings. However, it becomes limiting to use this sampler in case of large batch size trainings for 2 reasons:\n\n- Using PyTorch `DataSampler`, each trainer shuffles the full data (assuming shuffling is used) and then each trainer gets a view of this shuffled data. If the dataset is large (100 millions, 1 billion or more), generating very large permutation\non each trainer can lead to large CPU memory consumption per machine. Hence, it becomes difficult to use the PyTorch default `DataSampler` when user wants to train on large data and for several epochs (for example: 10 epochs of 100M images).\n\n- When using PyTorch `DataSampler` and the training is resumed, the sampler will serve the full dataset. However, in case of large data trainings (like 1 billion images or more), one mostly trains for 1 epoch only.\n In such cases, when the training resumes from the middle of the epoch, the sampler will serve the full 1 billion images which is not what we want.\n\n\nTo solve both the above issues, VISSL provides a custom samplier `StatefulDistributedSampler` which inherits from the PyTorch `DistributedSampler` and fixes the above issues in following manner:\n\n- Sampler creates the view of the data per trainer and then shuffles only the data that trainer is supposed to view. This keeps the CPU memory requirement expected.\n\n- Sampler adds a member `start_iter` which tracks what iteration number of the given epoch model is at. When the training is used, the `start_iter` will be properly set to the last iteration number and the sampler will serve only the remainder of data.\n\n",
"_____no_output_____"
],
[
"## How to use VISSL custom DataSampler\n\n\nUsing VISSL provided custom samplier `StatefulDistributedSampler` is extremely easy and involves simply setting the correct configuration options as below:\n\n\n```yaml\nDATA:\n TRAIN:\n USE_STATEFUL_DISTRIBUTED_SAMPLER: True\n TEST:\n USE_STATEFUL_DISTRIBUTED_SAMPLER: True\n```\n\n**NOTE**: Users can use `StatefulDistributedSampler` for only training dataset and use PyTorch default :code:`DataSampler` if desired i.e. it is not mandatory to use the same sampler type for all data splits.",
"_____no_output_____"
],
[
"# Activation Checkpointing\n\nActivation checkpointing is a very powerful technique to reduce the memory requirement of a model. This is especially useful when training very large models with billions of parameters.\n\n",
"_____no_output_____"
],
[
"## How it works?\n\nActivation checkpointing trades compute for memory. It discards intermediate activations during the forward pass, and recomputes them during the backward pass. In\nour experiments, using activation checkpointing, we observe negligible compute overhead in memory-bound settings while getting big memory savings.\n\nIn summary, This technique offers 2 benefits:\n\n- saves gpu memory that can be used to fit large models\n- allows increasing training batch size for a given model\n\nWe recommend users to read the documentation available [here](https://pytorch.org/docs/stable/checkpoint.html) for further details on activation checkpointing.\n",
"_____no_output_____"
],
[
"## How to use activation checkpointing in VISSL?\n\nVISSL integrates activation checkpointing implementation directly from PyTorch available [here](https://pytorch.org/docs/stable/checkpoint.html).\nUsing activation checkpointing in VISSL is extremely easy and doable with simple settings in the configuration file. The settings required are as below:\n\n```yaml\nMODEL:\n ACTIVATION_CHECKPOINTING:\n # whether to use activation checkpointing or not\n USE_ACTIVATION_CHECKPOINTING: True\n # how many times the model should be checkpointed. User should tune this parameter\n # and find the number that offers best memory saving and compute tradeoff.\n NUM_ACTIVATION_CHECKPOINTING_SPLITS: 8\nDISTRIBUTED:\n # if True, does the gradient reduction in DDP manually. This is useful during the\n # activation checkpointing and sometimes saving the memory from the pytorch gradient\n # buckets.\n MANUAL_GRADIENT_REDUCTION: True\n```",
"_____no_output_____"
]
]
]
| [
"markdown"
]
| [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
]
|
cb5c77100d091bcdf3d72df9ddd6743a50241d3f | 275,016 | ipynb | Jupyter Notebook | Neural Networks and Deep Learning/Week 2/Logistic Regression as a Neural Network/Logistic Regression with a Neural Network mindset v5.ipynb | hemisemidemiquaver/Deep-Learning-Coursera | a1b4e44e619db88899157faa6b795261137d13b0 | [
"MIT"
]
| null | null | null | Neural Networks and Deep Learning/Week 2/Logistic Regression as a Neural Network/Logistic Regression with a Neural Network mindset v5.ipynb | hemisemidemiquaver/Deep-Learning-Coursera | a1b4e44e619db88899157faa6b795261137d13b0 | [
"MIT"
]
| null | null | null | Neural Networks and Deep Learning/Week 2/Logistic Regression as a Neural Network/Logistic Regression with a Neural Network mindset v5.ipynb | hemisemidemiquaver/Deep-Learning-Coursera | a1b4e44e619db88899157faa6b795261137d13b0 | [
"MIT"
]
| null | null | null | 202.814159 | 142,456 | 0.89513 | [
[
[
"# Logistic Regression with a Neural Network mindset\n\nWelcome to your first (required) programming assignment! You will build a logistic regression classifier to recognize cats. This assignment will step you through how to do this with a Neural Network mindset, and so will also hone your intuitions about deep learning.\n\n**Instructions:**\n- Do not use loops (for/while) in your code, unless the instructions explicitly ask you to do so.\n\n**You will learn to:**\n- Build the general architecture of a learning algorithm, including:\n - Initializing parameters\n - Calculating the cost function and its gradient\n - Using an optimization algorithm (gradient descent) \n- Gather all three functions above into a main model function, in the right order.",
"_____no_output_____"
],
[
"## 1 - Packages ##\n\nFirst, let's run the cell below to import all the packages that you will need during this assignment. \n- [numpy](www.numpy.org) is the fundamental package for scientific computing with Python.\n- [h5py](http://www.h5py.org) is a common package to interact with a dataset that is stored on an H5 file.\n- [matplotlib](http://matplotlib.org) is a famous library to plot graphs in Python.\n- [PIL](http://www.pythonware.com/products/pil/) and [scipy](https://www.scipy.org/) are used here to test your model with your own picture at the end.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport h5py\nimport scipy\nimport imageio\n\nfrom PIL import Image\nfrom scipy import ndimage\nfrom lr_utils import load_dataset\nfrom skimage.transform import resize\n\n\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"## 2 - Overview of the Problem set ##\n\n**Problem Statement**: You are given a dataset (\"data.h5\") containing:\n - a training set of m_train images labeled as cat (y=1) or non-cat (y=0)\n - a test set of m_test images labeled as cat or non-cat\n - each image is of shape (num_px, num_px, 3) where 3 is for the 3 channels (RGB). Thus, each image is square (height = num_px) and (width = num_px).\n\nYou will build a simple image-recognition algorithm that can correctly classify pictures as cat or non-cat.\n\nLet's get more familiar with the dataset. Load the data by running the following code.",
"_____no_output_____"
]
],
[
[
"# Loading the data (cat/non-cat)\ntrain_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()",
"_____no_output_____"
]
],
[
[
"We added \"_orig\" at the end of image datasets (train and test) because we are going to preprocess them. After preprocessing, we will end up with train_set_x and test_set_x (the labels train_set_y and test_set_y don't need any preprocessing).\n\nEach line of your train_set_x_orig and test_set_x_orig is an array representing an image. You can visualize an example by running the following code. Feel free also to change the `index` value and re-run to see other images. ",
"_____no_output_____"
]
],
[
[
"# Example of a picture\nindex = 34\nplt.imshow(test_set_x_orig[index])\nprint (\"y = \" + str(test_set_y[:, index]) + \", it's a '\" + classes[np.squeeze(test_set_y[:, index])].decode(\"utf-8\") + \"' picture.\")",
"y = [0], it's a 'non-cat' picture.\n"
]
],
[
[
"Many software bugs in deep learning come from having matrix/vector dimensions that don't fit. If you can keep your matrix/vector dimensions straight you will go a long way toward eliminating many bugs. \n\n**Exercise:** Find the values for:\n - m_train (number of training examples)\n - m_test (number of test examples)\n - num_px (= height = width of a training image)\nRemember that `train_set_x_orig` is a numpy-array of shape (m_train, num_px, num_px, 3). For instance, you can access `m_train` by writing `train_set_x_orig.shape[0]`.",
"_____no_output_____"
]
],
[
[
"### START CODE HERE ### (≈ 3 lines of code)\nm_train = train_set_x_orig.shape[0]\nm_test = test_set_x_orig.shape[0]\nnum_px = train_set_x_orig.shape[1]\n\n\n### END CODE HERE ###\n\nprint (\"Number of training examples: m_train = \" + str(m_train))\nprint (\"Number of testing examples: m_test = \" + str(m_test))\nprint (\"Height/Width of each image: num_px = \" + str(num_px))\nprint (\"Each image is of size: (\" + str(num_px) + \", \" + str(num_px) + \", 3)\")\nprint (\"train_set_x shape: \" + str(train_set_x_orig.shape))\nprint (\"train_set_y shape: \" + str(train_set_y.shape))\nprint (\"test_set_x shape: \" + str(test_set_x_orig.shape))\nprint (\"test_set_y shape: \" + str(test_set_y.shape))",
"Number of training examples: m_train = 209\nNumber of testing examples: m_test = 50\nHeight/Width of each image: num_px = 64\nEach image is of size: (64, 64, 3)\ntrain_set_x shape: (209, 64, 64, 3)\ntrain_set_y shape: (1, 209)\ntest_set_x shape: (50, 64, 64, 3)\ntest_set_y shape: (1, 50)\n"
]
],
[
[
"**Expected Output for m_train, m_test and num_px**: \n<table style=\"width:15%\">\n <tr>\n <td>**m_train**</td>\n <td> 209 </td> \n </tr>\n \n <tr>\n <td>**m_test**</td>\n <td> 50 </td> \n </tr>\n \n <tr>\n <td>**num_px**</td>\n <td> 64 </td> \n </tr>\n \n</table>\n",
"_____no_output_____"
],
[
"For convenience, you should now reshape images of shape (num_px, num_px, 3) in a numpy-array of shape (num_px $*$ num_px $*$ 3, 1). After this, our training (and test) dataset is a numpy-array where each column represents a flattened image. There should be m_train (respectively m_test) columns.\n\n**Exercise:** Reshape the training and test data sets so that images of size (num_px, num_px, 3) are flattened into single vectors of shape (num\\_px $*$ num\\_px $*$ 3, 1).\n\nA trick when you want to flatten a matrix X of shape (a,b,c,d) to a matrix X_flatten of shape (b$*$c$*$d, a) is to use: \n```python\nX_flatten = X.reshape(X.shape[0], -1).T # X.T is the transpose of X\n```",
"_____no_output_____"
]
],
[
[
"# Reshape the training and test examples\n\n### START CODE HERE ### (≈ 2 lines of code)\n#train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[1] * train_set_x_orig.shape[2] * 3, train_set_x_orig.shape[0])\n#test_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[1] * test_set_x_orig.shape[2] * 3, test_set_x_orig.shape[0])\n\n\ntrain_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T\ntest_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T\n\n\n\n\n### END CODE HERE ###\n\nprint (\"train_set_x_flatten shape: \" + str(train_set_x_flatten.shape))\nprint (\"train_set_y shape: \" + str(train_set_y.shape))\nprint (\"test_set_x_flatten shape: \" + str(test_set_x_flatten.shape))\nprint (\"test_set_y shape: \" + str(test_set_y.shape))\nprint (\"sanity check after reshaping: \" + str(train_set_x_flatten[0:5,0]))",
"train_set_x_flatten shape: (12288, 209)\ntrain_set_y shape: (1, 209)\ntest_set_x_flatten shape: (12288, 50)\ntest_set_y shape: (1, 50)\nsanity check after reshaping: [17 31 56 22 33]\n"
]
],
[
[
"**Expected Output**: \n\n<table style=\"width:35%\">\n <tr>\n <td>**train_set_x_flatten shape**</td>\n <td> (12288, 209)</td> \n </tr>\n <tr>\n <td>**train_set_y shape**</td>\n <td>(1, 209)</td> \n </tr>\n <tr>\n <td>**test_set_x_flatten shape**</td>\n <td>(12288, 50)</td> \n </tr>\n <tr>\n <td>**test_set_y shape**</td>\n <td>(1, 50)</td> \n </tr>\n <tr>\n <td>**sanity check after reshaping**</td>\n <td>[17 31 56 22 33]</td> \n </tr>\n</table>",
"_____no_output_____"
],
[
"To represent color images, the red, green and blue channels (RGB) must be specified for each pixel, and so the pixel value is actually a vector of three numbers ranging from 0 to 255.\n\nOne common preprocessing step in machine learning is to center and standardize your dataset, meaning that you substract the mean of the whole numpy array from each example, and then divide each example by the standard deviation of the whole numpy array. But for picture datasets, it is simpler and more convenient and works almost as well to just divide every row of the dataset by 255 (the maximum value of a pixel channel).\n\n<!-- During the training of your model, you're going to multiply weights and add biases to some initial inputs in order to observe neuron activations. Then you backpropogate with the gradients to train the model. But, it is extremely important for each feature to have a similar range such that our gradients don't explode. You will see that more in detail later in the lectures. !--> \n\nLet's standardize our dataset.",
"_____no_output_____"
]
],
[
[
"train_set_x = train_set_x_flatten/255.\ntest_set_x = test_set_x_flatten/255.",
"_____no_output_____"
]
],
[
[
"<font color='blue'>\n**What you need to remember:**\n\nCommon steps for pre-processing a new dataset are:\n- Figure out the dimensions and shapes of the problem (m_train, m_test, num_px, ...)\n- Reshape the datasets such that each example is now a vector of size (num_px \\* num_px \\* 3, 1)\n- \"Standardize\" the data",
"_____no_output_____"
],
[
"## 3 - General Architecture of the learning algorithm ##\n\nIt's time to design a simple algorithm to distinguish cat images from non-cat images.\n\nYou will build a Logistic Regression, using a Neural Network mindset. The following Figure explains why **Logistic Regression is actually a very simple Neural Network!**\n\n<img src=\"images/LogReg_kiank.png\" style=\"width:650px;height:400px;\">\n\n**Mathematical expression of the algorithm**:\n\nFor one example $x^{(i)}$:\n$$z^{(i)} = w^T x^{(i)} + b \\tag{1}$$\n$$\\hat{y}^{(i)} = a^{(i)} = sigmoid(z^{(i)})\\tag{2}$$ \n$$ \\mathcal{L}(a^{(i)}, y^{(i)}) = - y^{(i)} \\log(a^{(i)}) - (1-y^{(i)} ) \\log(1-a^{(i)})\\tag{3}$$\n\nThe cost is then computed by summing over all training examples:\n$$ J = \\frac{1}{m} \\sum_{i=1}^m \\mathcal{L}(a^{(i)}, y^{(i)})\\tag{6}$$\n\n**Key steps**:\nIn this exercise, you will carry out the following steps: \n - Initialize the parameters of the model\n - Learn the parameters for the model by minimizing the cost \n - Use the learned parameters to make predictions (on the test set)\n - Analyse the results and conclude",
"_____no_output_____"
],
[
"## 4 - Building the parts of our algorithm ## \n\nThe main steps for building a Neural Network are:\n1. Define the model structure (such as number of input features) \n2. Initialize the model's parameters\n3. Loop:\n - Calculate current loss (forward propagation)\n - Calculate current gradient (backward propagation)\n - Update parameters (gradient descent)\n\nYou often build 1-3 separately and integrate them into one function we call `model()`.\n\n### 4.1 - Helper functions\n\n**Exercise**: Using your code from \"Python Basics\", implement `sigmoid()`. As you've seen in the figure above, you need to compute $sigmoid( w^T x + b) = \\frac{1}{1 + e^{-(w^T x + b)}}$ to make predictions. Use np.exp().",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: sigmoid\n\ndef sigmoid(z):\n \"\"\"\n Compute the sigmoid of z\n\n Arguments:\n z -- A scalar or numpy array of any size.\n\n Return:\n s -- sigmoid(z)\n \"\"\"\n\n ### START CODE HERE ### (≈ 1 line of code)\n s = 1 / (1 + np.exp(-z))\n ### END CODE HERE ###\n \n return s",
"_____no_output_____"
],
[
"print (\"sigmoid([0, 2]) = \" + str(sigmoid(np.array([0,2]))))",
"sigmoid([0, 2]) = [0.5 0.88079708]\n"
]
],
[
[
"**Expected Output**: \n\n<table>\n <tr>\n <td>**sigmoid([0, 2])**</td>\n <td> [ 0.5 0.88079708]</td> \n </tr>\n</table>",
"_____no_output_____"
],
[
"### 4.2 - Initializing parameters\n\n**Exercise:** Implement parameter initialization in the cell below. You have to initialize w as a vector of zeros. If you don't know what numpy function to use, look up np.zeros() in the Numpy library's documentation.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: initialize_with_zeros\n\ndef initialize_with_zeros(dim):\n \"\"\"\n This function creates a vector of zeros of shape (dim, 1) for w and initializes b to 0.\n \n Argument:\n dim -- size of the w vector we want (or number of parameters in this case)\n \n Returns:\n w -- initialized vector of shape (dim, 1)\n b -- initialized scalar (corresponds to the bias)\n \"\"\"\n \n ### START CODE HERE ### (≈ 1 line of code)\n w = np.zeros((dim, 1))\n b = 0\n ### END CODE HERE ###\n\n assert(w.shape == (dim, 1))\n assert(isinstance(b, float) or isinstance(b, int))\n \n return w, b",
"_____no_output_____"
],
[
"dim = 2\nw, b = initialize_with_zeros(dim)\nprint (\"w = \" + str(w))\nprint (\"b = \" + str(b))",
"w = [[0.]\n [0.]]\nb = 0\n"
]
],
[
[
"**Expected Output**: \n\n\n<table style=\"width:15%\">\n <tr>\n <td> ** w ** </td>\n <td> [[ 0.]\n [ 0.]] </td>\n </tr>\n <tr>\n <td> ** b ** </td>\n <td> 0 </td>\n </tr>\n</table>\n\nFor image inputs, w will be of shape (num_px $\\times$ num_px $\\times$ 3, 1).",
"_____no_output_____"
],
[
"### 4.3 - Forward and Backward propagation\n\nNow that your parameters are initialized, you can do the \"forward\" and \"backward\" propagation steps for learning the parameters.\n\n**Exercise:** Implement a function `propagate()` that computes the cost function and its gradient.\n\n**Hints**:\n\nForward Propagation:\n- You get X\n- You compute $A = \\sigma(w^T X + b) = (a^{(1)}, a^{(2)}, ..., a^{(m-1)}, a^{(m)})$\n- You calculate the cost function: $J = -\\frac{1}{m}\\sum_{i=1}^{m}y^{(i)}\\log(a^{(i)})+(1-y^{(i)})\\log(1-a^{(i)})$\n\nHere are the two formulas you will be using: \n\n$$ \\frac{\\partial J}{\\partial w} = \\frac{1}{m}X(A-Y)^T\\tag{7}$$\n$$ \\frac{\\partial J}{\\partial b} = \\frac{1}{m} \\sum_{i=1}^m (a^{(i)}-y^{(i)})\\tag{8}$$",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: propagate\n\ndef propagate(w, b, X, Y):\n \"\"\"\n Implement the cost function and its gradient for the propagation explained above\n\n Arguments:\n w -- weights, a numpy array of size (num_px * num_px * 3, 1)\n b -- bias, a scalar\n X -- data of size (num_px * num_px * 3, number of examples)\n Y -- true \"label\" vector (containing 0 if non-cat, 1 if cat) of size (1, number of examples)\n\n Variables:\n m = Number of training exampels\n \n Return:\n cost -- negative log-likelihood cost for logistic regression\n dw -- gradient of the loss with respect to w, thus same shape as w\n db -- gradient of the loss with respect to b, thus same shape as b\n \n Tips:\n - Write your code step by step for the propagation. np.log(), np.dot()\n \"\"\"\n \n m = X.shape[1]\n \n # FORWARD PROPAGATION (FROM X TO COST)\n ### START CODE HERE ### (≈ 2 lines of code)\n A = sigmoid(np.dot(w.T, X) + b)\n cost = - 1/m * np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A))\n ### END CODE HERE ###\n \n # BACKWARD PROPAGATION (TO FIND GRAD)\n ### START CODE HERE ### (≈ 2 lines of code)\n dw = 1 / m * np.dot(X, (A - Y).T)\n db = 1 / m * np.sum(A - Y)\n \n ### END CODE HERE ###\n assert(dw.shape == w.shape)\n assert(db.dtype == float)\n cost = np.squeeze(cost)\n assert(cost.shape == ())\n \n grads = {\"dw\": dw,\n \"db\": db}\n \n return grads, cost",
"_____no_output_____"
],
[
"w, b, X, Y = np.array([[1.],[2.]]), 2., np.array([[1.,2.,-1.],[3.,4.,-3.2]]), np.array([[1,0,1]])\ngrads, cost = propagate(w, b, X, Y)\nprint (\"dw = \" + str(grads[\"dw\"]))\nprint (\"db = \" + str(grads[\"db\"]))\nprint (\"cost = \" + str(cost))",
"dw = [[0.99845601]\n [2.39507239]]\ndb = 0.001455578136784208\ncost = 5.801545319394553\n"
]
],
[
[
"**Expected Output**:\n\n<table style=\"width:50%\">\n <tr>\n <td> ** dw ** </td>\n <td> [[ 0.99845601]\n [ 2.39507239]]</td>\n </tr>\n <tr>\n <td> ** db ** </td>\n <td> 0.00145557813678 </td>\n </tr>\n <tr>\n <td> ** cost ** </td>\n <td> 5.801545319394553 </td>\n </tr>\n\n</table>",
"_____no_output_____"
],
[
"### 4.4 - Optimization\n- You have initialized your parameters.\n- You are also able to compute a cost function and its gradient.\n- Now, you want to update the parameters using gradient descent.\n\n**Exercise:** Write down the optimization function. The goal is to learn $w$ and $b$ by minimizing the cost function $J$. For a parameter $\\theta$, the update rule is $ \\theta = \\theta - \\alpha \\text{ } d\\theta$, where $\\alpha$ is the learning rate.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: optimize\n\ndef optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False):\n \"\"\"\n This function optimizes w and b by running a gradient descent algorithm\n \n Arguments:\n w -- weights, a numpy array of size (num_px * num_px * 3, 1)\n b -- bias, a scalar\n X -- data of shape (num_px * num_px * 3, number of examples)\n Y -- true \"label\" vector (containing 0 if non-cat, 1 if cat), of shape (1, number of examples)\n num_iterations -- number of iterations of the optimization loop\n learning_rate -- learning rate of the gradient descent update rule\n print_cost -- True to print the loss every 100 steps\n \n Returns:\n params -- dictionary containing the weights w and bias b\n grads -- dictionary containing the gradients of the weights and bias with respect to the cost function\n costs -- list of all the costs computed during the optimization, this will be used to plot the learning curve.\n \n Tips:\n You basically need to write down two steps and iterate through them:\n 1) Calculate the cost and the gradient for the current parameters. Use propagate().\n 2) Update the parameters using gradient descent rule for w and b.\n \"\"\"\n \n costs = []\n \n for i in range(num_iterations):\n \n \n # Cost and gradient calculation (≈ 1-4 lines of code)\n ### START CODE HERE ### \n grads, cost = propagate(w, b, X, Y)\n \n ### END CODE HERE ###\n \n # Retrieve derivatives from grads\n dw = grads[\"dw\"]\n db = grads[\"db\"]\n \n # update rule (≈ 2 lines of code)\n ### START CODE HERE ###\n w = w - learning_rate * dw\n b = b - learning_rate * db\n \n ### END CODE HERE ###\n \n # Record the costs\n if i % 100 == 0:\n costs.append(cost)\n \n # Print the cost every 100 training iterations\n if print_cost and i % 100 == 0:\n print (\"Cost after iteration %i: %f\" %(i, cost))\n \n params = {\"w\": w,\n \"b\": b}\n \n grads = {\"dw\": dw,\n \"db\": db}\n \n return params, grads, costs",
"_____no_output_____"
],
[
"params, grads, costs = optimize(w, b, X, Y, num_iterations= 100, learning_rate = 0.009, print_cost = False)\n\nprint (\"w = \" + str(params[\"w\"]))\nprint (\"b = \" + str(params[\"b\"]))\nprint (\"dw = \" + str(grads[\"dw\"]))\nprint (\"db = \" + str(grads[\"db\"]))",
"w = [[0.19033591]\n [0.12259159]]\nb = 1.9253598300845747\ndw = [[0.67752042]\n [1.41625495]]\ndb = 0.21919450454067652\n"
]
],
[
[
"**Expected Output**: \n\n<table style=\"width:40%\">\n <tr>\n <td> **w** </td>\n <td>[[ 0.19033591] [ 0.12259159]] </td>\n </tr>\n <tr>\n <td> **b** </td>\n <td> 1.92535983008 </td>\n </tr>\n <tr>\n <td> **dw** </td>\n <td> [[ 0.67752042] [ 1.41625495]] </td>\n </tr>\n <tr>\n <td> **db** </td>\n <td> 0.219194504541 </td>\n </tr>\n\n</table>",
"_____no_output_____"
],
[
"**Exercise:** The previous function will output the learned w and b. We are able to use w and b to predict the labels for a dataset X. Implement the `predict()` function. There are two steps to computing predictions:\n\n1. Calculate $\\hat{Y} = A = \\sigma(w^T X + b)$\n\n2. Convert the entries of a into 0 (if activation <= 0.5) or 1 (if activation > 0.5), stores the predictions in a vector `Y_prediction`. If you wish, you can use an `if`/`else` statement in a `for` loop (though there is also a way to vectorize this). ",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: predict\n\ndef predict(w, b, X):\n '''\n Predict whether the label is 0 or 1 using learned logistic regression parameters (w, b)\n \n Arguments:\n w -- weights, a numpy array of size (num_px * num_px * 3, 1)\n b -- bias, a scalar\n X -- data of size (num_px * num_px * 3, number of examples)\n \n Returns:\n Y_prediction -- a numpy array (vector) containing all predictions (0/1) for the examples in X\n '''\n \n m = X.shape[1]\n Y_prediction = np.zeros((1,m))\n w = w.reshape(X.shape[0], 1)\n \n # Compute vector \"A\" predicting the probabilities of a cat being present in the picture\n ### START CODE HERE ### (≈ 1 line of code)\n A = sigmoid(np.dot(w.T, X) + b)\n ### END CODE HERE ###\n \n for i in range(A.shape[1]):\n \n # Convert probabilities A[0,i] to actual predictions p[0,i]\n ### START CODE HERE ### (≈ 4 lines of code)\n if A[0,i] > 0.5:\n Y_prediction[0][i] = 1\n else:\n Y_prediction[0][i] = 0\n ### END CODE HERE ###\n \n assert(Y_prediction.shape == (1, m))\n \n return Y_prediction",
"_____no_output_____"
],
[
"w = np.array([[0.1124579],[0.23106775]])\nb = -0.3\nX = np.array([[1.,-1.1,-3.2],[1.2,2.,0.1]])\nprint (\"predictions = \" + str(predict(w, b, X)))",
"predictions = [[1. 1. 0.]]\n"
]
],
[
[
"**Expected Output**: \n\n<table style=\"width:30%\">\n <tr>\n <td>\n **predictions**\n </td>\n <td>\n [[ 1. 1. 0.]]\n </td> \n </tr>\n\n</table>\n",
"_____no_output_____"
],
[
"<font color='blue'>\n**What to remember:**\nYou've implemented several functions that:\n- Initialize (w,b)\n- Optimize the loss iteratively to learn parameters (w,b):\n - computing the cost and its gradient \n - updating the parameters using gradient descent\n- Use the learned (w,b) to predict the labels for a given set of examples",
"_____no_output_____"
],
[
"## 5 - Merge all functions into a model ##\n\nYou will now see how the overall model is structured by putting together all the building blocks (functions implemented in the previous parts) together, in the right order.\n\n**Exercise:** Implement the model function. Use the following notation:\n - Y_prediction_test for your predictions on the test set\n - Y_prediction_train for your predictions on the train set\n - w, costs, grads for the outputs of optimize()",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: model\n\ndef model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False):\n \"\"\"\n Builds the logistic regression model by calling the function you've implemented previously\n \n Arguments:\n X_train -- training set represented by a numpy array of shape (num_px * num_px * 3, m_train)\n Y_train -- training labels represented by a numpy array (vector) of shape (1, m_train)\n X_test -- test set represented by a numpy array of shape (num_px * num_px * 3, m_test)\n Y_test -- test labels represented by a numpy array (vector) of shape (1, m_test)\n num_iterations -- hyperparameter representing the number of iterations to optimize the parameters\n learning_rate -- hyperparameter representing the learning rate used in the update rule of optimize()\n print_cost -- Set to true to print the cost every 100 iterations\n \n Returns:\n d -- dictionary containing information about the model.\n \"\"\"\n \n ### START CODE HERE ###\n \n \n \n \n #Intialize w, b; w.shape = (num_px * num_px * 3, 1)\n w, b = initialize_with_zeros(X_train.shape[0])\n \n #Use Transponsed Datasets -> shape: (m_train, num_px..) -> w.T * X in sigmoid functionw will work\n params, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost)\n w = params[\"w\"]\n b = params[\"b\"]\n Y_prediction_train = predict(w, b, X_train)\n Y_prediction_test = predict(w, b, X_test)\n \n\n ### END CODE HERE ###\n\n # Print train/test Errors\n print(\"train accuracy: {} %\".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100))\n print(\"test accuracy: {} %\".format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100))\n\n \n d = {\"costs\": costs,\n \"Y_prediction_test\": Y_prediction_test, \n \"Y_prediction_train\" : Y_prediction_train, \n \"w\" : w, \n \"b\" : b,\n \"learning_rate\" : learning_rate,\n \"num_iterations\": num_iterations}\n \n return d",
"_____no_output_____"
]
],
[
[
"Run the following cell to train your model.",
"_____no_output_____"
]
],
[
[
"d = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 2000, learning_rate = 0.005, print_cost = True)",
"Cost after iteration 0: 0.693147\nCost after iteration 100: 0.584508\nCost after iteration 200: 0.466949\nCost after iteration 300: 0.376007\nCost after iteration 400: 0.331463\nCost after iteration 500: 0.303273\nCost after iteration 600: 0.279880\nCost after iteration 700: 0.260042\nCost after iteration 800: 0.242941\nCost after iteration 900: 0.228004\nCost after iteration 1000: 0.214820\nCost after iteration 1100: 0.203078\nCost after iteration 1200: 0.192544\nCost after iteration 1300: 0.183033\nCost after iteration 1400: 0.174399\nCost after iteration 1500: 0.166521\nCost after iteration 1600: 0.159305\nCost after iteration 1700: 0.152667\nCost after iteration 1800: 0.146542\nCost after iteration 1900: 0.140872\ntrain accuracy: 99.04306220095694 %\ntest accuracy: 70.0 %\n"
]
],
[
[
"**Expected Output**: \n\n<table style=\"width:40%\"> \n\n <tr>\n <td> **Cost after iteration 0 ** </td> \n <td> 0.693147 </td>\n </tr>\n <tr>\n <td> <center> $\\vdots$ </center> </td> \n <td> <center> $\\vdots$ </center> </td> \n </tr> \n <tr>\n <td> **Train Accuracy** </td> \n <td> 99.04306220095694 % </td>\n </tr>\n\n <tr>\n <td>**Test Accuracy** </td> \n <td> 70.0 % </td>\n </tr>\n</table> \n\n\n",
"_____no_output_____"
],
[
"**Comment**: Training accuracy is close to 100%. This is a good sanity check: your model is working and has high enough capacity to fit the training data. Test error is 68%. It is actually not bad for this simple model, given the small dataset we used and that logistic regression is a linear classifier. But no worries, you'll build an even better classifier next week!\n\nAlso, you see that the model is clearly overfitting the training data. Later in this specialization you will learn how to reduce overfitting, for example by using regularization. Using the code below (and changing the `index` variable) you can look at predictions on pictures of the test set.",
"_____no_output_____"
]
],
[
[
"# Example of a picture that was wrongly classified.\nindex = 13\nplt.imshow(test_set_x[:,index].reshape((num_px, num_px, 3)))\nprint (\"y = \" + str(test_set_y[0,index]) + \", you predicted that it is a \\\"\" + classes[int(d[\"Y_prediction_test\"][0,index])].decode(\"utf-8\") + \"\\\" picture.\")\n#print (\"y = \" + str(test_set_y[0,index]) + \", you predicted that it is a \\\"\" + str(d[\"Y_prediction_test\"][0,index]) + \"\\\" picture.\")",
"y = 0, you predicted that it is a \"cat\" picture.\n"
]
],
[
[
"Let's also plot the cost function and the gradients.",
"_____no_output_____"
]
],
[
[
"# Plot learning curve (with costs)\ncosts = np.squeeze(d['costs'])\nplt.plot(costs)\nplt.ylabel('cost')\nplt.xlabel('iterations (per hundreds)')\nplt.title(\"Learning rate =\" + str(d[\"learning_rate\"]))\nplt.show()",
"_____no_output_____"
]
],
[
[
"**Interpretation**:\nYou can see the cost decreasing. It shows that the parameters are being learned. However, you see that you could train the model even more on the training set. Try to increase the number of iterations in the cell above and rerun the cells. You might see that the training set accuracy goes up, but the test set accuracy goes down. This is called overfitting. ",
"_____no_output_____"
],
[
"## 6 - Further analysis (optional/ungraded exercise) ##\n\nCongratulations on building your first image classification model. Let's analyze it further, and examine possible choices for the learning rate $\\alpha$. ",
"_____no_output_____"
],
[
"#### Choice of learning rate ####\n\n**Reminder**:\nIn order for Gradient Descent to work you must choose the learning rate wisely. The learning rate $\\alpha$ determines how rapidly we update the parameters. If the learning rate is too large we may \"overshoot\" the optimal value. Similarly, if it is too small we will need too many iterations to converge to the best values. That's why it is crucial to use a well-tuned learning rate.\n\nLet's compare the learning curve of our model with several choices of learning rates. Run the cell below. This should take about 1 minute. Feel free also to try different values than the three we have initialized the `learning_rates` variable to contain, and see what happens. ",
"_____no_output_____"
]
],
[
[
"learning_rates = [0.01, 0.001, 0.0001]\nmodels = {}\nfor i in learning_rates:\n print (\"learning rate is: \" + str(i))\n models[str(i)] = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 1500, learning_rate = i, print_cost = False)\n print ('\\n' + \"-------------------------------------------------------\" + '\\n')\n\nfor i in learning_rates:\n plt.plot(np.squeeze(models[str(i)][\"costs\"]), label= str(models[str(i)][\"learning_rate\"]))\n\nplt.ylabel('cost')\nplt.xlabel('iterations (hundreds)')\n\nlegend = plt.legend(loc='upper center', shadow=True)\nframe = legend.get_frame()\nframe.set_facecolor('0.90')\nplt.show()",
"learning rate is: 0.01\ntrain accuracy: 99.52153110047847 %\ntest accuracy: 68.0 %\n\n-------------------------------------------------------\n\nlearning rate is: 0.001\ntrain accuracy: 88.99521531100478 %\ntest accuracy: 64.0 %\n\n-------------------------------------------------------\n\nlearning rate is: 0.0001\ntrain accuracy: 68.42105263157895 %\ntest accuracy: 36.0 %\n\n-------------------------------------------------------\n\n"
]
],
[
[
"**Interpretation**: \n- Different learning rates give different costs and thus different predictions results.\n- If the learning rate is too large (0.01), the cost may oscillate up and down. It may even diverge (though in this example, using 0.01 still eventually ends up at a good value for the cost). \n- A lower cost doesn't mean a better model. You have to check if there is possibly overfitting. It happens when the training accuracy is a lot higher than the test accuracy.\n- In deep learning, we usually recommend that you: \n - Choose the learning rate that better minimizes the cost function.\n - If your model overfits, use other techniques to reduce overfitting. (We'll talk about this in later videos.) \n",
"_____no_output_____"
],
[
"## 7 - Test with your own image (optional/ungraded exercise) ##\n\nCongratulations on finishing this assignment. You can use your own image and see the output of your model. To do that:\n 1. Click on \"File\" in the upper bar of this notebook, then click \"Open\" to go on your Coursera Hub.\n 2. Add your image to this Jupyter Notebook's directory, in the \"images\" folder\n 3. Change your image's name in the following code\n 4. Run the code and check if the algorithm is right (1 = cat, 0 = non-cat)!",
"_____no_output_____"
]
],
[
[
"## START CODE HERE ## (PUT YOUR IMAGE NAME) \nmy_image = \"my_image4.jpg\" # change this to the name of your image file \n## END CODE HERE ##\n\n# We preprocess the image to fit your algorithm.\nfname = \"images/\" + my_image\nimage = np.array(imageio.imread(fname))\n\n\nprint(image.shape)\nmy_image = resize(image, (num_px,num_px)).reshape((1, num_px*num_px*3)).T\nmy_predicted_image = predict(d[\"w\"], d[\"b\"], my_image)\n\nplt.imshow(image)\nprint(\"y = \" + str(np.squeeze(my_predicted_image)) + \", your algorithm predicts a \\\"\" + classes[int(np.squeeze(my_predicted_image)),].decode(\"utf-8\") + \"\\\" picture.\")",
"(1024, 1024, 3)\ny = 1.0, your algorithm predicts a \"cat\" picture.\n"
]
],
[
[
"<font color='blue'>\n**What to remember from this assignment:**\n1. Preprocessing the dataset is important.\n2. You implemented each function separately: initialize(), propagate(), optimize(). Then you built a model().\n3. Tuning the learning rate (which is an example of a \"hyperparameter\") can make a big difference to the algorithm. You will see more examples of this later in this course!",
"_____no_output_____"
],
[
"Finally, if you'd like, we invite you to try different things on this Notebook. Make sure you submit before trying anything. Once you submit, things you can play with include:\n - Play with the learning rate and the number of iterations\n - Try different initialization methods and compare the results\n - Test other preprocessings (center the data, or divide each row by its standard deviation)",
"_____no_output_____"
],
[
"Bibliography:\n- http://www.wildml.com/2015/09/implementing-a-neural-network-from-scratch/\n- https://stats.stackexchange.com/questions/211436/why-do-we-normalize-images-by-subtracting-the-datasets-image-mean-and-not-the-c",
"_____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",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
]
]
|
cb5c8f0d1401e328356618f0ba001178b18b6c7d | 12,939 | ipynb | Jupyter Notebook | MaterialCursoPython/Fase 4 - Temas avanzados/Tema 15 - Funcionalidades avanzadas/Apuntes/Leccion 04 (Apuntes) - Funciones generadoras e iteradores.ipynb | mangrovex/CursoPython | 85b3d8a920f79a1f184b8508cf011fda238eada0 | [
"MIT"
]
| 105 | 2016-07-08T19:43:03.000Z | 2018-10-20T14:00:14.000Z | Fase 4 - Temas avanzados/Tema 15 - Funcionalidades avanzadas/Apuntes/Leccion 04 (Apuntes) - Funciones generadoras e iteradores.ipynb | ruben69695/python-course | a3d3532279510fa0315a7636c373016c7abe4f0a | [
"MIT"
]
| null | null | null | Fase 4 - Temas avanzados/Tema 15 - Funcionalidades avanzadas/Apuntes/Leccion 04 (Apuntes) - Funciones generadoras e iteradores.ipynb | ruben69695/python-course | a3d3532279510fa0315a7636c373016c7abe4f0a | [
"MIT"
]
| 145 | 2016-09-26T14:02:55.000Z | 2018-10-27T06:49:28.000Z | 29.207675 | 972 | 0.569982 | [
[
[
"# Funciones generadoras\nPor regla general, cuando queremos crear una lista de algún tipo, lo que hacemos es crear la lista vacía, y luego con un bucle varios elementos e ir añadiendolos a la lista si cumplen una condición:",
"_____no_output_____"
]
],
[
[
"[numero for numero in [0,1,2,3,4,5,6,7,8,9,10] if numero % 2 == 0 ] ",
"_____no_output_____"
]
],
[
[
"También vimos cómo era posible utilizar la función **range()** para generar dinámicamente la lista en la memoria, es decir, no teníamos que crearla en el propio código, sino que se interpretaba sobre la marcha:",
"_____no_output_____"
]
],
[
[
"[numero for numero in range(0,11) if numero % 2 == 0 ]",
"_____no_output_____"
]
],
[
[
"La verdad es que **range()** es una especie de función generadora. Por regla general las funciones devolvuelven un valor con **return**, pero la preculiaridad de los generadores es que van *cediendo* valores sobre la marcha, en tiempo de ejecución.\n\nLa función generadora **range(0,11)**, empieza cediendo el **0**, luego se procesa el for comprobando si es par y lo añade a la lista, en la siguiente iteración se cede el **1**, se procesa el for se comprueba si es par, en la siguiente se cede el **2**, etc. \n\nCon esto se logra ocupar el mínimo de espacio en la memoria y podemos generar listas de millones de elementos sin necesidad de almacenarlos previamente. \n\nVeamos a ver cómo crear una función generadora de pares:",
"_____no_output_____"
]
],
[
[
"def pares(n):\n for numero in range(n+1):\n if numero % 2 == 0:\n yield numero\n \npares(10)",
"_____no_output_____"
]
],
[
[
"Como vemos, en lugar de utilizar el **return**, la función generadora utiliza el **yield**, que significa ceder. Tomando un número busca todos los pares desde 0 hasta el número+1 sirviéndonos de un range(). \n\nSin embargo, fijaros que al imprimir el resultado, éste nos devuelve un objeto de tipo generador.\n\nDe la misma forma que recorremos un **range()** podemos utilizar el bucle for para recorrer todos los elementos que devuelve el generador:",
"_____no_output_____"
]
],
[
[
"for numero in pares(10):\n print(numero)",
"0\n2\n4\n6\n8\n10\n"
]
],
[
[
"Utilizando comprensión de listas también podemos crear una lista al vuelo:",
"_____no_output_____"
]
],
[
[
"[numero for numero in pares(10)]",
"_____no_output_____"
]
],
[
[
"Sin embargo el gran potencial de los generadores no es simplemente crear listas, de hecho como ya hemos visto, el propio resultado no es una lista en sí mismo, sino una secuencia iterable con un montón de características únicas.",
"_____no_output_____"
],
[
"## Iteradores\nPor tanto las funciones generadoras devuelven un objeto que suporta un protocolo de iteración. ¿Qué nos permite hacer? Pues evidentemente controlar el proceso de generación. Teniendo en cuenta que cada vez que la función generadora cede un elemento, queda suspendida y se retoma el control hasta que se le pide generar el siguiente valor. \n\nAsí que vamos a tomar nuestro ejemplo de pares desde otra perspectiva, como si fuera un iterador manual, así veremos exactamente a lo que me refiero:",
"_____no_output_____"
]
],
[
[
"pares = pares(3)",
"_____no_output_____"
]
],
[
[
"Bien, ahora tenemos un iterador de pares con todos los números pares entre el 0 y el 3. Vamos a conseguir el primer número par:",
"_____no_output_____"
]
],
[
[
"next(pares)",
"_____no_output_____"
]
],
[
[
"Como vemos la función integrada **next()** nos permite acceder al siguiente elemento de la secuencia. Pero no sólo eso, si volvemos a ejecutarla...",
"_____no_output_____"
]
],
[
[
"next(pares)",
"_____no_output_____"
]
],
[
[
"Ahora devuelve el segundo! ¿No os recuerdo esto al puntero de los ficheros? Cuando leíamos una línea, el puntero pasaba a la siguiente y así sucesivamente. Pues aquí igual. \n\n¿Y qué pasaría si intentamos acceder al siguiente, aún sabiendo que entre el 0 y el 3 sólo tenemos los pares 0 y 2?",
"_____no_output_____"
]
],
[
[
"next(pares)",
"_____no_output_____"
]
],
[
[
"Pues que nos da un error porque se ha acabado la secuencia, así que tomad nota y capturad la excepción si váis a utilizarlas sin saber exactamente cuantos elementos os devolverá el generador.\n\nAsí que la pregunta que nos queda es ¿sólo es posible iterar secuencias generadas al vuelo? Vamos a probar con una lista:",
"_____no_output_____"
]
],
[
[
"lista = [1,2,3,4,5]\nnext(lista)",
"_____no_output_____"
]
],
[
[
"¿Quizá con una cadena?",
"_____no_output_____"
]
],
[
[
"cadena = \"Hola\"\nnext(cadena)",
"_____no_output_____"
]
],
[
[
"Pues no, no podemos iterar ninguna colección como si fuera una secuencia. Sin embargo, hay una función muy interesante que nos permite covertir las cadenas y algunas colecciones a iteradores, la función **iter()**:",
"_____no_output_____"
]
],
[
[
"lista = [1,2,3,4,5]\nlista_iterable = iter(lista)\nprint( next(lista_iterable) )\nprint( next(lista_iterable) )\nprint( next(lista_iterable) )\nprint( next(lista_iterable) )\nprint( next(lista_iterable) )",
"1\n2\n3\n4\n5\n"
],
[
"cadena = \"Hola\"\ncadena_iterable = iter(cadena)\nprint( next(cadena_iterable) )\nprint( next(cadena_iterable) )\nprint( next(cadena_iterable) )\nprint( next(cadena_iterable) )",
"H\no\nl\na\n"
]
],
[
[
"Muy bien, ahora ya sabemos qué son las funciones generadores, cómo utilizarlas, y también como como convertir algunos objetos a iteradores. Os sugiero probar por vuestra cuenta más colecciones a ver si encontráis alguna más que se pueda iterar.",
"_____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"
],
[
"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"
]
]
|
cb5cafdf9517e9b06a14f11384584919399dbae1 | 12,225 | ipynb | Jupyter Notebook | appendix/teach_me_qiskit_2018/hadamard_action/Approach 2.ipynb | kardashin/qiskit-tutorial | 0deb92bbd89f29e8e9d94f4bf095cb0fbd83c41d | [
"Apache-2.0"
]
| 2 | 2018-09-13T05:40:53.000Z | 2019-05-12T15:00:58.000Z | appendix/teach_me_qiskit_2018/hadamard_action/Approach 2.ipynb | kardashin/qiskit-tutorial | 0deb92bbd89f29e8e9d94f4bf095cb0fbd83c41d | [
"Apache-2.0"
]
| null | null | null | appendix/teach_me_qiskit_2018/hadamard_action/Approach 2.ipynb | kardashin/qiskit-tutorial | 0deb92bbd89f29e8e9d94f4bf095cb0fbd83c41d | [
"Apache-2.0"
]
| null | null | null | 28.233256 | 556 | 0.493497 | [
[
[
"<img src=\"images/QISKit-c copy.gif\" alt=\"Note: In order for images to show up in this jupyter notebook you need to select File => Trusted Notebook\" width=\"250 px\" align=\"left\">",
"_____no_output_____"
],
[
"# Hadamard Action: Approach 2\n## Jupyter Notebook 2/3 for the Teach Me QISKIT Tutorial Competition\n- Connor Fieweger",
"_____no_output_____"
],
[
"<img src=\"images/hadamard_action.png\" alt=\"Note: In order for images to show up in this jupyter notebook you need to select File => Trusted Notebook\" width=\"750 px\" align=\"left\">",
"_____no_output_____"
],
[
"Another approach to showing equivalence of the presented circuit diagrams is to represent the operators on the qubits as matrices and the qubit states as column vectors. The output is found by applying the matrix that represents the action of the circuit onto the initial state column vector to find the final state column vector. Since the numpy library already enables making linear algebra computations such as these, we'll use that to employ classical programming in order to understand this quantum circuit.",
"_____no_output_____"
]
],
[
[
"import numpy as np",
"_____no_output_____"
]
],
[
[
"## Circuit i)\nFor i), the initial state of the input is represented by the tensor product of the two input qubits in the initial register. This is given by:\n\n$$\\Psi = \\psi_1 \\otimes \\psi_2$$\n\nWhere each $\\psi$ can be either 0 or 1\n\nThis results in the following input states for $\\Psi$: |00>, |01>, |10>, or |11>. Represented by column vectors, these are:\n\n$$\\text{|00>} = \\left(\\begin{array}{c}\n 1 \\\\\n 0 \\\\\n 0 \\\\\n 0\n\\end{array}\\right)$$\n$$\\text{|01>} = \\left(\\begin{array}{c}\n 0 \\\\\n 1 \\\\\n 0 \\\\\n 0\n\\end{array}\\right)$$\n$$\\text{|10>} = \\left(\\begin{array}{c}\n 0 \\\\\n 0 \\\\\n 1 \\\\\n 0\n\\end{array}\\right)$$\n$$\\text{|11>} = \\left(\\begin{array}{c}\n 0 \\\\\n 0 \\\\\n 0 \\\\\n 1\n\\end{array}\\right)$$\n",
"_____no_output_____"
]
],
[
[
"# These column vectors can be stored in numpy arrays so that we can operate \n# on them with the circuit diagram's corresponding matrix (which is to be evaluated)\n# as follows:\nzero_zero = np.array([[1],[0],[0],[0]])\nzero_one = np.array([[0],[1],[0],[0]])\none_zero = np.array([[0],[0],[1],[0]])\none_one = np.array([[0],[0],[0],[1]])\nPsi = {'zero_zero': zero_zero, 'zero_one': zero_one, 'one_zero': one_zero, 'one_one': one_one}\n# ^We can conveniently store all possible input states in a dictionary and then print to check the representations:\nfor key, val in Psi.items():\n print(key, ':', '\\n', val)",
"one_zero : \n [[0]\n [0]\n [1]\n [0]]\nzero_zero : \n [[1]\n [0]\n [0]\n [0]]\nzero_one : \n [[0]\n [1]\n [0]\n [0]]\none_one : \n [[0]\n [0]\n [0]\n [1]]\n"
]
],
[
[
"The action of the circuit gates on this state is simply the CNOT operator. For a control qubit on line 1 and a subject qubit on line 2, CNOT is given by the 4x4 matrix (as discussed in the appendix notebook): \n\n$$CNOT_1 = \\left[\\begin{array}{cccc}\n 1 & 0 & 0 & 0 \\\\\n 0 & 1 & 0 & 0 \\\\\n 0 & 0 & 0 & 1 \\\\\n 0 & 0 & 1 & 0\n\\end{array}\\right]$$\n\nThis matrix is the operator that describes the effect of the circuit on the initial state. By taking $CNOT_1$|$\\Psi$> = |$\\Psi$'>, then, the final state for i) can be found.",
"_____no_output_____"
]
],
[
[
"# storing CNOT as a numpy array:\nCNOT_1 = np.matrix([[1, 0, 0, 0],[0, 1, 0, 0],[0, 0, 0, 1],[0, 0, 1, 0]])\nprint(CNOT_1)",
"[[1 0 0 0]\n [0 1 0 0]\n [0 0 0 1]\n [0 0 1 0]]\n"
],
[
"print('FINAL STATE OF i):')\n#Apply CNOT to each possible state for |Psi> to find --> |Psi'>\nfor key, val in Psi.items():\n print(key, 'becomes..\\n', CNOT_1*val)",
"FINAL STATE OF i):\none_zero becomes..\n [[0]\n [0]\n [0]\n [1]]\nzero_zero becomes..\n [[1]\n [0]\n [0]\n [0]]\nzero_one becomes..\n [[0]\n [1]\n [0]\n [0]]\none_one becomes..\n [[0]\n [0]\n [1]\n [0]]\n"
]
],
[
[
"As one can see, the first set of two states (00, 01) has stayed the same, while the second (10, 11) has flipped to (11, 10). This is readily understood when considering the defining logic of the CNOT gate - the subject qubit on line 2 is flipped if the control qubit on line 1 in the state |1> (this is also referred to as the control qubit being 'on'). Summatively, then, the action of i) is given by: [|00>,|01>,|10>,|11>] --> [|00>,|01>,|11>,|10>].",
"_____no_output_____"
],
[
"## Circuit ii)\nFor ii), a similar examination of the input states and the result when the circuit operation matrix is applied to these states can be done. The input states are the same as those in i), so we can just use the variable 'Psi' that we stored earlier. In order to find the matrix representation of the circuit, a little more depth in considering the matrix that represents the gates is required as follows: ",
"_____no_output_____"
],
[
"First, consider the parallel application of the Hadamard gate 'H' to each wire. In order to represent this as an operator on the two-qubit-tensor-space state ('$\\Psi$'), one needs to take the tensor product of the single-qubit-space's ('$\\psi$') Hadamard with itself: $H \\otimes H = H^{\\otimes 2}$\n\nAs discussed in the appendix notebook, this is given by:\n$$\\text{H}^{\\otimes 2} = \\frac{1}{2}\\left[\\begin{array}{cccc}\n 1 & 1 & 1 & 1 \\\\\n 1 & -1 & 1 & -1 \\\\\n 1 & 1 & -1 & -1 \\\\\n 1 & -1 & -1 & 1\n\\end{array}\\right]$$\n\nThis is then the first matrix to consider when finding the matrix that represents the action of circuit ii).",
"_____no_output_____"
]
],
[
[
"# storing this in a numpy array:\nH_2 = .5*np.matrix([[1, 1, 1, 1],[1, -1, 1, -1],[1, 1, -1, -1],[1, -1, -1, 1]])\nprint('H_2:')\nprint(H_2)",
"H_2:\n[[ 0.5 0.5 0.5 0.5]\n [ 0.5 -0.5 0.5 -0.5]\n [ 0.5 0.5 -0.5 -0.5]\n [ 0.5 -0.5 -0.5 0.5]]\n"
]
],
[
[
"The next operation on the qubits is a CNOT controlled by line 2. This is given by the 4x4 matrix (also in the appendix notebook): \n\n$$CNOT_2 = \\left[\\begin{array}{cccc}\n 1 & 0 & 0 & 0 \\\\\n 0 & 0 & 0 & 1 \\\\\n 0 & 0 & 1 & 0 \\\\\n 0 & 1 & 0 & 0\n\\end{array}\\right]$$\n\nThis is then the second matrix to consider in finding the matrix that represents the action of circuit ii).",
"_____no_output_____"
]
],
[
[
"# storing this in a numpy array:\nCNOT_2 = np.matrix([[1, 0, 0, 0],[0, 0, 0, 1],[0, 0, 1, 0],[0, 1, 0, 0]])",
"_____no_output_____"
]
],
[
[
"Finally, the set of parallel hadamard matrices as given by $H^{\\otimes 2}$ is again applied to the two-qubit-space. With this, all matrices that contribute to the circuit's action have been found. Applying each operator to the state as one reads the circuit diagram from left to right, one finds: $(H^{\\otimes 2})(CNOT_2)(H^{\\otimes} 2)\\Psi$ = $\\Psi$ '. The $(H^{\\otimes 2})(CNOT_2)(H^{\\otimes} 2)$ term can be evaluated through matrix multiplication to a single 4x4 matrix that represents the entire circuit as an operator, let's call it 'A'.",
"_____no_output_____"
]
],
[
[
"A = H_2*CNOT_2*H_2",
"_____no_output_____"
],
[
"print(A)",
"[[1. 0. 0. 0.]\n [0. 1. 0. 0.]\n [0. 0. 0. 1.]\n [0. 0. 1. 0.]]\n"
]
],
[
[
"This representation should look familiar, no? ",
"_____no_output_____"
]
],
[
[
"print(CNOT_1)",
"[[1 0 0 0]\n [0 1 0 0]\n [0 0 0 1]\n [0 0 1 0]]\n"
]
],
[
[
"Just to double check,;",
"_____no_output_____"
]
],
[
[
"for key, val in Psi.items():\n print(key, 'becomes...\\n', A*val)",
"one_zero becomes...\n [[0.]\n [0.]\n [0.]\n [1.]]\nzero_zero becomes...\n [[1.]\n [0.]\n [0.]\n [0.]]\nzero_one becomes...\n [[0.]\n [1.]\n [0.]\n [0.]]\none_one becomes...\n [[0.]\n [0.]\n [1.]\n [0.]]\n"
]
],
[
[
"The action of i) and ii) are evidently the same then $\\square$.",
"_____no_output_____"
]
]
]
| [
"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",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
]
|
cb5cb29cd3b5593dd827af5d6d59eaf7c862e144 | 73,100 | ipynb | Jupyter Notebook | Chapter01/Chapter1.ipynb | cutillav/PyTorch-Computer-Vision-Cookbook | 7340a9b59491b5f6715e76304ec6d10e804917d3 | [
"MIT"
]
| null | null | null | Chapter01/Chapter1.ipynb | cutillav/PyTorch-Computer-Vision-Cookbook | 7340a9b59491b5f6715e76304ec6d10e804917d3 | [
"MIT"
]
| null | null | null | Chapter01/Chapter1.ipynb | cutillav/PyTorch-Computer-Vision-Cookbook | 7340a9b59491b5f6715e76304ec6d10e804917d3 | [
"MIT"
]
| null | null | null | 59.430894 | 32,492 | 0.780451 | [
[
[
"### Verify Installation",
"_____no_output_____"
]
],
[
[
"import torch\n\n# get Pytorch version\ntorch.__version__",
"_____no_output_____"
],
[
"# import torchvision\nimport torchvision\n\n# get torchvision version\ntorchvision.__version__",
"_____no_output_____"
],
[
"# checking if cuda is available\ntorch.cuda.is_available()",
"_____no_output_____"
],
[
"# get number of cuda/gpu devices\ntorch.cuda.device_count()",
"_____no_output_____"
],
[
"# get cuda/gpu device id\ntorch.cuda.current_device()\n\n# get cuda/gpu device name\ntorch.cuda.get_device_name(0)",
"_____no_output_____"
]
],
[
[
"### Tesnor Data Type",
"_____no_output_____"
]
],
[
[
"# define a tensor with default data type\nx = torch.ones(2, 2)\nprint(x)\nprint(x.dtype)\n",
"tensor([[1., 1.],\n [1., 1.]])\ntorch.float32\n"
]
],
[
[
"### Specify Data Type",
"_____no_output_____"
]
],
[
[
"# define a tensor\nx = torch.ones(2, 2, dtype=torch.int8)\nprint(x)\nprint(x.dtype)",
"tensor([[1, 1],\n [1, 1]], dtype=torch.int8)\ntorch.int8\n"
]
],
[
[
"### Change Tensor data type",
"_____no_output_____"
]
],
[
[
"# define a tensor with type torch.uint8\nx=torch.ones(1,dtype=torch.uint8)\n\nprint(x.dtype)\n# change a tesnor data type\nx=x.type(torch.float)\nprint(x.dtype)",
"torch.uint8\ntorch.float32\n"
]
],
[
[
"### Converting Tensors to NumPy arrays",
"_____no_output_____"
]
],
[
[
"# define a tensor\nx=torch.rand(2,2)\nprint(x)\nprint(x.dtype)\n\n# convert tensor to numpy array\ny=x.numpy()\nprint(y)\nprint(y.dtype)",
"tensor([[0.0805, 0.8540],\n [0.2553, 0.2066]])\ntorch.float32\n[[0.08054882 0.8540349 ]\n [0.25528336 0.20658517]]\nfloat32\n"
]
],
[
[
"### Converting NumPy arrays to Tensors",
"_____no_output_____"
]
],
[
[
"# import NumPy\nimport numpy as np\n\n# define a NumPy array\nx=np.zeros((2,2),dtype=np.float32)\nprint(x)\nprint(x.dtype)\n\n# convert array to PyTorch Tensor\ny=torch.from_numpy(x)\nprint(y)\nprint(y.dtype)",
"[[0. 0.]\n [0. 0.]]\nfloat32\ntensor([[0., 0.],\n [0., 0.]])\ntorch.float32\n"
]
],
[
[
"### Move Tensors between devices",
"_____no_output_____"
]
],
[
[
"# define a tensor\nx=torch.tensor([1.5, 2])\nprint(x)\n\nprint(x.device)",
"tensor([1.5000, 2.0000])\ncpu\n"
],
[
"# move tensor onto GPU\n# define a cuda/gpu device\ndevice = torch.device(\"cuda:0\")\nx = x.to(device)\nprint(x)\nprint(x.device)",
"tensor([1.5000, 2.0000], device='cuda:0')\ncuda:0\n"
],
[
"# move tensor onto cpu\n# define a cpu device\ndevice = torch.device(\"cpu\")\nx = x.to(device)\nprint(x)\nprint(x.device)",
"tensor([1.5000, 2.0000])\ncpu\n"
],
[
"# define a tensor on device\ndevice = torch.device(\"cuda:0\")\nx = torch.ones(2,2, device=device)\nprint(x)",
"tensor([[1., 1.],\n [1., 1.]], device='cuda:0')\n"
]
],
[
[
"## Loading and Processing Data",
"_____no_output_____"
]
],
[
[
"from torchvision import datasets\n\n# path to store data and/or load from\npath2data=\"./data\"\n\n# loading training data\ntrain_data=datasets.MNIST(path2data, train=True, download=True)\n\n# extract data and targets\nx_train, y_train=train_data.data,train_data.targets\nprint(x_train.shape)\nprint(y_train.shape)\n\n# loading validation data\nval_data=datasets.MNIST(path2data, train=False, download=True)\n\n# extract data and targets\nx_val,y_val=val_data.data, val_data.targets\nprint(x_val.shape)\nprint(y_val.shape)\n",
"torch.Size([60000, 28, 28])\ntorch.Size([60000])\ntorch.Size([10000, 28, 28])\ntorch.Size([10000])\n"
]
],
[
[
"### Display images",
"_____no_output_____"
]
],
[
[
"from torchvision import utils\nimport matplotlib.pyplot as plt\nimport numpy as np\n%matplotlib inline\n\n# First, add a dimension to tensor to become B*C*H*W\nif len(x_train.shape)==3:\n x_train=x_train.unsqueeze(1)\nprint(x_train.shape)\n\nif len(x_val.shape)==3:\n x_val=x_val.unsqueeze(1)\n\n# make a grid of 40 images, 8 images per row\nx_grid=utils.make_grid(x_train[:40], nrow=8, padding=2)\nprint(x_grid.shape)\n\n# helper function to display images\ndef show(img):\n # convert tensor to numpy array\n npimg = img.numpy()\n \n # Convert to H*W*C shape\n npimg_tr=np.transpose(npimg, (1,2,0))\n \n # display images\n plt.imshow(npimg_tr,interpolation='nearest')\n\n# call helper function\nshow(x_grid)",
"torch.Size([60000, 1, 28, 28])\ntorch.Size([3, 152, 242])\n"
]
],
[
[
"### Transform Data",
"_____no_output_____"
]
],
[
[
"from torchvision import transforms\n\n# loading MNIST training dataset\ntrain_data=datasets.MNIST(path2data, train=True, download=True)\n\n# define transformations\ndata_transform = transforms.Compose([transforms.RandomHorizontalFlip(p=1),\n transforms.RandomVerticalFlip(p=1),\n transforms.ToTensor(),\n ])\n\n",
"_____no_output_____"
],
[
"# get a sample image from training dataset\nimg = train_data[0][0]\n\n# tranform sample image\nimg_tr=data_transform(img)\n\n# convert tensor to numpy array\nimg_tr_np=img_tr.numpy()\n\n# show original and transformed images\nplt.subplot(1,2,1)\nplt.imshow(img,cmap=\"gray\")\nplt.title(\"original\")\nplt.subplot(1,2,2)\nplt.imshow(img_tr_np[0],cmap=\"gray\");\nplt.title(\"transformed\")",
"_____no_output_____"
],
[
"# define transformations\ndata_transform = transforms.Compose([\n transforms.RandomHorizontalFlip(1),\n transforms.RandomVerticalFlip(1),\n transforms.ToTensor(),])\n\n# Loading MNIST training data with on-the-fly transformations\ntrain_data=datasets.MNIST(path2data, train=True, download=True,\ntransform=data_transform )",
"_____no_output_____"
]
],
[
[
"### Wrap Tensors into Dataset",
"_____no_output_____"
]
],
[
[
"from torch.utils.data import TensorDataset\n\n# wrap tensors into a dataset\ntrain_ds = TensorDataset(x_train, y_train)\nval_ds = TensorDataset(x_val, y_val)\n\nfor x,y in train_ds:\n print(x.shape,y.item())\n break",
"torch.Size([1, 28, 28]) 5\n"
]
],
[
[
"### Iterate Over Dataset",
"_____no_output_____"
]
],
[
[
"from torch.utils.data import DataLoader\n\n# create a data loader from dataset\ntrain_dl = DataLoader(train_ds, batch_size=8)\nval_dl = DataLoader(val_ds, batch_size=8)\n\n# iterate over batches\nfor xb,yb in train_dl:\n print(xb.shape)\n print(yb.shape)\n break\n # your training code will be here!",
"torch.Size([8, 1, 28, 28])\ntorch.Size([8])\n"
]
],
[
[
"## Building Models",
"_____no_output_____"
]
],
[
[
"from torch import nn\n\n# input tensor dimension 64*1000\ninput_tensor = torch.randn(64, 1000)\n\n# linear layer with 1000 inputs and 100 outputs\nlinear_layer = nn.Linear(1000, 100)\n\n# output of the linear layer\noutput = linear_layer(input_tensor)\nprint(output.size())",
"torch.Size([64, 100])\n"
]
],
[
[
"### Define models using nn.Sequential",
"_____no_output_____"
]
],
[
[
"from torch import nn\n\n# define a two-layer model\nmodel = nn.Sequential(\n nn.Linear(4, 5),\n nn.ReLU(), # relu is not shown in the figure.\n nn.Linear(5, 1),)\nprint(model)",
"Sequential(\n (0): Linear(in_features=4, out_features=5, bias=True)\n (1): ReLU()\n (2): Linear(in_features=5, out_features=1, bias=True)\n)\n"
]
],
[
[
"## Define models using nn.Module",
"_____no_output_____"
]
],
[
[
"import torch.nn.functional as F\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(1, 8, 5, 1)\n self.conv2 = nn.Conv2d(8, 16, 5, 1)\n self.fc1 = nn.Linear(4*4*16, 100)\n self.fc2 = nn.Linear(100, 10)\n\n def forward(self, x):\n x = F.relu(self.conv1(x))\n x = F.max_pool2d(x, 2, 2)\n x = F.relu(self.conv2(x))\n x = F.max_pool2d(x, 2, 2)\n x = x.view(-1, 4*4*16)\n x = F.relu(self.fc1(x))\n x = self.fc2(x)\n return F.log_softmax(x, dim=1)\n\nmodel = Net()\nprint(model)\n",
"Net(\n (conv1): Conv2d(1, 8, kernel_size=(5, 5), stride=(1, 1))\n (conv2): Conv2d(8, 16, kernel_size=(5, 5), stride=(1, 1))\n (fc1): Linear(in_features=256, out_features=100, bias=True)\n (fc2): Linear(in_features=100, out_features=10, bias=True)\n)\n"
]
],
[
[
"### Move Model to Device",
"_____no_output_____"
]
],
[
[
"print(next(model.parameters()).device)",
"cpu\n"
],
[
"device = torch.device(\"cuda:0\")\nmodel.to(device)\nprint(next(model.parameters()).device)",
"cuda:0\n"
]
],
[
[
"### Show model summary",
"_____no_output_____"
]
],
[
[
"from torchsummary import summary\n\nsummary(model, input_size=(1, 28, 28))",
"----------------------------------------------------------------\n Layer (type) Output Shape Param #\n================================================================\n Conv2d-1 [-1, 8, 24, 24] 208\n Conv2d-2 [-1, 16, 8, 8] 3,216\n Linear-3 [-1, 100] 25,700\n Linear-4 [-1, 10] 1,010\n================================================================\nTotal params: 30,134\nTrainable params: 30,134\nNon-trainable params: 0\n----------------------------------------------------------------\nInput size (MB): 0.00\nForward/backward pass size (MB): 0.04\nParams size (MB): 0.11\nEstimated Total Size (MB): 0.16\n----------------------------------------------------------------\n"
]
],
[
[
"## Loss Function",
"_____no_output_____"
]
],
[
[
"# define the negative log likelihood loss\nloss_func = nn.NLLLoss(reduction=\"sum\")\n\nfor xb, yb in train_dl:\n # move batch to cuda device\n xb=xb.type(torch.float).to(device)\n yb=yb.to(device)\n # get model output\n out=model(xb)\n # calculate loss value\n loss = loss_func(out, yb)\n print (loss.item())\n break",
"69.37257385253906\n"
],
[
"# compute gradients\nloss.backward()",
"_____no_output_____"
]
],
[
[
"## Optimizer",
"_____no_output_____"
]
],
[
[
"from torch import optim\n\n# define Adam optimizer\nopt = optim.Adam(model.parameters(), lr=1e-4)\n\n# update model parameters\nopt.step()\n\n# set gradients to zero\nopt.zero_grad()",
"_____no_output_____"
]
],
[
[
"## Training and Validation",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\ndef metrics_batch(target, output):\n # obtain output class\n pred = output.argmax(dim=1, keepdim=True)\n \n # compare output class with target class\n corrects=pred.eq(target.view_as(pred)).sum().item()\n return corrects\n\ndef loss_batch(loss_func, xb, yb,yb_h, opt=None):\n \n # obtain loss\n loss = loss_func(yb_h, yb)\n \n # obtain performance metric\n metric_b = metrics_batch(yb,yb_h)\n \n if opt is not None:\n loss.backward()\n opt.step()\n opt.zero_grad()\n\n return loss.item(), metric_b\n\n\ndef loss_epoch(model,loss_func,dataset_dl,opt=None):\n loss=0.0\n metric=0.0\n len_data=len(dataset_dl.dataset)\n for xb, yb in dataset_dl:\n xb=xb.type(torch.float).to(device)\n yb=yb.to(device)\n \n # obtain model output\n yb_h=model(xb)\n\n loss_b,metric_b=loss_batch(loss_func, xb, yb,yb_h, opt)\n loss+=loss_b\n if metric_b is not None:\n metric+=metric_b\n loss/=len_data\n metric/=len_data\n return loss, metric\n\n\n\ndef train_val(epochs, model, loss_func, opt, train_dl, val_dl):\n for epoch in range(epochs):\n model.train()\n train_loss, train_metric=loss_epoch(model,loss_func,train_dl,opt)\n \n \n model.eval()\n with torch.no_grad():\n val_loss, val_metric=loss_epoch(model,loss_func,val_dl)\n \n accuracy=100*val_metric\n\n print(\"epoch: %d, train loss: %.6f, val loss: %.6f, accuracy: %.2f\" %(epoch, train_loss,val_loss,accuracy))",
"_____no_output_____"
],
[
"import numpy as np\n\n\n# call train_val function\nnum_epochs=5\ntrain_val(num_epochs, model, loss_func, opt, train_dl, val_dl)",
"epoch: 0, train loss: 0.294502, val loss: 0.093089, accuracy: 96.94\nepoch: 1, train loss: 0.080617, val loss: 0.061121, accuracy: 98.06\nepoch: 2, train loss: 0.050562, val loss: 0.049555, accuracy: 98.49\nepoch: 3, train loss: 0.035071, val loss: 0.049693, accuracy: 98.45\nepoch: 4, train loss: 0.025703, val loss: 0.050179, accuracy: 98.49\n"
]
],
[
[
"## Store and Load Models",
"_____no_output_____"
]
],
[
[
"import torch\n\n# define path2weights\npath2weights=\"./models/weights.pt\"\n\n# store state_dict to file\ntorch.save(model.state_dict(), path2weights)",
"_____no_output_____"
]
],
[
[
"### Method 1",
"_____no_output_____"
]
],
[
[
"# define model: weights are randomly initiated\n_model = Net()\n\n# load weights from file\nweights=torch.load(path2weights)\n\n# set weights to model: weights are set with the store values\n_model.load_state_dict(weights)\n\n# set model in eval mode for deployment\n_model.eval()\n\n# model model to cuda device for accelerated computation\n_model.to(device)",
"_____no_output_____"
]
],
[
[
"### Method 2",
"_____no_output_____"
]
],
[
[
"# define a path2model\npath2model=\"./models/model.pt\"\n# store model and weights into local file\ntorch.save(model,path2model)",
"/home/ai1/anaconda2/envs/conda-pytorch/lib/python3.6/site-packages/torch/serialization.py:251: UserWarning: Couldn't retrieve source code for container of type Net. It won't be checked for correctness upon loading.\n \"type \" + obj.__name__ + \". It won't be checked \"\n"
],
[
"# define model: weights are randomly initiated\n_model = Net()\n# load model and weights from local file\n_model=torch.load(path2model)\n\n# set model in eval mode for deployment\n_model.eval()\n# move model to cuda device for accelerated computation\n_model.to(device)",
"_____no_output_____"
]
],
[
[
"## Deploy Models",
"_____no_output_____"
]
],
[
[
"# x is a data point with C*H*W shape\nn=100\nx= x_val[n]\ny=y_val[n]\nprint(x.shape)\nplt.imshow(x.numpy()[0],cmap=\"gray\")\n\n# we use unsqueeze to expand dimensions to 1*C*H*W\nx= x.unsqueeze(0)\n\n# convert to torch.float32\nx=x.type(torch.float)\n\n# move to cuda device\nx=x.to(device)\n\n# get model output\noutput=_model(x)\n\n# get predicted class\npred = output.argmax(dim=1, keepdim=True)\nprint (pred.item(),y.item())",
"torch.Size([1, 28, 28])\n6 6\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",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"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"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
]
|
cb5cb9539b037434eb840cb88374c44e3a9c1ea9 | 15,106 | ipynb | Jupyter Notebook | python-basics.ipynb | dwcaraway/intro-to-python-talk | 7009e07e1dc68fc4d5489ccf0842c01fbcc3e773 | [
"Unlicense"
]
| 1 | 2018-09-25T01:41:37.000Z | 2018-09-25T01:41:37.000Z | python-basics.ipynb | dwcaraway/intro-to-python-talk | 7009e07e1dc68fc4d5489ccf0842c01fbcc3e773 | [
"Unlicense"
]
| null | null | null | python-basics.ipynb | dwcaraway/intro-to-python-talk | 7009e07e1dc68fc4d5489ccf0842c01fbcc3e773 | [
"Unlicense"
]
| 1 | 2019-10-06T02:57:44.000Z | 2019-10-06T02:57:44.000Z | 21.924528 | 267 | 0.464451 | [
[
[
"# Introduction to Python\n\nAn introduction to Python for middle and high school students using Python 3 syntax.\n\n",
"_____no_output_____"
],
[
"## Getting started\n\nWe're assuming that you already have Python 3.6 or higher installed. If not, go to Python.org to download the latest for your operating system. Verify that you have the correct version by opening a terminal or command prompt and running\n\n```\n$ python --version\nPython 3.6.0\n```",
"_____no_output_____"
],
[
"# Your First Program: Hello, World!\n\nOpen the Interactive DeveLopment Environment (IDLE) and write the famous Hello World program. Open IDLE and you'll be in an interactive shell.",
"_____no_output_____"
]
],
[
[
"print('Hello, World!')",
"_____no_output_____"
]
],
[
[
"Choose *File > New Window*. An empty window will appear with *Untitled* in the menu bar. Enter the following code into the new shell window. Choose *File > Save*. Save as `hello.py`, which is known as a python `module`. Choose *Run > Run module* to run the file",
"_____no_output_____"
],
[
"## Calculating with Python\n\nMathematical operators:\n\n* Addition: +\n* Subtraction: -\n* Multiplication: *\n\nTry these\n* `3 * 4`",
"_____no_output_____"
]
],
[
[
"3*4",
"_____no_output_____"
]
],
[
[
"Division:\n * Floating point `/`\n * Integer `//`\n\nTry these:\n* `5/4`\n* `1/0`\n* `3//4`\n* `5//4`",
"_____no_output_____"
]
],
[
[
"3//4",
"_____no_output_____"
],
[
"# Exponents\n2**3",
"_____no_output_____"
],
[
"# Modulus\n5%4",
"_____no_output_____"
]
],
[
[
"### Type function\n\nTheres lots more available via the standard library and third party packages. To see the type of the result, use the *type* function. For example `type(3//4))` returns `int`",
"_____no_output_____"
],
[
"## Order of Operations\nPython reads left to right. Higher precedence operators are applied before lower precedence operators. Operators below are listed lowest precedence at the top. \n\n| Operator | Description |\n|----------------------------------------------|-----------------------------------------------------------|\n| or | Boolean OR |\n| and | Boolean AND |\n| not | Boolean NOT |\n| in, not in, is, is not, `<`, `<=`, `>`, `>=`, `!=`, `==` | Comparison, including membership tests and identity tests |\n| `+`, `-` | Addition and Subtraction |\n| `*`, `/`, `//`, `%` | Multiplication, division, integer division, remainder |\n| `**` | Exponentiation |\n\nCalculate the result of `5 + 1 * 4`.\n\nWe override the precendence using parenthesis which are evaluated from the innermost out.\n\nCalculate the result of `(5+1) * 4`.\n\n> Remember that multiplication and division always go before\naddition and subtraction, unless parentheses are used to control\nthe order of operations.",
"_____no_output_____"
]
],
[
[
"(2 + 2) ** 3",
"_____no_output_____"
]
],
[
[
"## Variables\nVariables are like labels so that we can refer to things by a recognizable name.",
"_____no_output_____"
]
],
[
[
"fred = 10 + 5\n\ntype(fred)",
"_____no_output_____"
],
[
"fred = 10 / 5\ntype(fred)",
"_____no_output_____"
],
[
"fred * 55 + fred",
"_____no_output_____"
],
[
"joe = fred * 55\njoe",
"_____no_output_____"
],
[
"joe",
"_____no_output_____"
],
[
"fred",
"_____no_output_____"
],
[
"joe = fred\nfred = joe",
"_____no_output_____"
]
],
[
[
"### Valid varible names\n\nVariables begin with a letter followed by container letters, numbers and underscores\n\n* `jim`\n* `other_jim`\n* `other_jim99`\n\n### Invalid variable names: don't meet requiremenets\n* `symbol$notallowed`\n* `5startswithnumber`\n\n\n### Invalid variable names: reserved words\n\n| Reserved words | | | | |\n|----------------|----------|--------|----------|-------|\n| None | continue | for | lambda | try |\n| True | def | from | nonlocal | while |\n| and | del | global | not | with |\n| as | elif | if | or | yield |\n| break | except | in | raise | | \n\n\n### Referring to a previous result\nYou can use the `_` variable to refer to the result of a previous calculation when working in the shell.\n",
"_____no_output_____"
]
],
[
[
"ends_with_9 = 9\n\na = 6\nb = 4",
"_____no_output_____"
],
[
"my_var = 7",
"_____no_output_____"
],
[
"num_apples * 65",
"_____no_output_____"
],
[
"doesntexist",
"_____no_output_____"
]
],
[
[
"## User Input\nWe can get keyboard input using the `input` function",
"_____no_output_____"
]
],
[
[
"name = input(\"What's your name? \")\nprint(\"Hi \", name)",
"_____no_output_____"
]
],
[
[
"## Strings\n* Strings are immutable objects in python, meaning they can't be modified once created, but they can be used to create new strings.\n* Strings should be surrounded with a single quote `'` or double quote `\"`. The general rule is to use the single quote unless you plan to use something called *interpolation*\n\n### Formatting\n\nStrings support templating and formatting. ",
"_____no_output_____"
]
],
[
[
"id(\"bar\")\n",
"_____no_output_____"
],
[
"fred = \"bar\"\nid(fred)",
"_____no_output_____"
],
[
"\"this string is %s\" % ('formatted')",
"_____no_output_____"
],
[
"\"this string is also {message}. The message='{message}' can be used more than once\".format(message='formatted')",
"_____no_output_____"
],
[
"# Called string concatenation\n\"this string is \"+ 'concatenated'",
"_____no_output_____"
],
[
"## Conditionals\n\n`if (condition):`\n\n`elif (condition):`\n \n`else (optional condition):`\n",
"_____no_output_____"
],
[
"aa = False\n\nif aa:\n print('a is true')\nelse:\n print ('aa is not true')",
"_____no_output_____"
],
[
"aa = 'wasdf'\n\nif aa == 'aa':\n print('first condition')\nelif aa == 'bb':\n print('second condition')\nelse:\n print('default condition')",
"_____no_output_____"
]
],
[
[
"## Data Structures\n\n* Lists `[]`\n\nLists are orderings of things where each thing corresponds to an index starting at 0. \n\nExample `[1, 2, 3]` where 1 is at index 0, 2 is at index 1 and 3 is at index 2.\n\n\n* Tuples `()`\n\nTuples are like lists, only you can't \n\n\n* Dictionaries `{}`\n\nkey value pairs\n",
"_____no_output_____"
],
[
"## Comprehension\n\nLists can be constructed using comprehension logic",
"_____no_output_____"
]
],
[
[
"[(a, a*2) for a in range(10)]",
"_____no_output_____"
]
],
[
[
"We can use conditionals as well",
"_____no_output_____"
]
],
[
[
"[(a, a*2) for a in range(10) if a < 8]",
"_____no_output_____"
]
],
[
[
"Additional topics\n* python modules and packages\n* functions\n* classes and methods\n* generators\n* pip and the python packaging land\n* virtualenvs",
"_____no_output_____"
]
]
]
| [
"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",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
]
|
cb5cc0e31ff505803830ca49ebc2ba76d1e267a2 | 16,088 | ipynb | Jupyter Notebook | math_fun/Fun_with_Car_Plate_Numbers!.ipynb | nadiaalee/cp4all | f1895ec2361355b05b18d0dc3e2216af875ef2ee | [
"CC0-1.0"
]
| 8 | 2020-10-08T08:19:15.000Z | 2020-12-02T06:23:12.000Z | math_fun/Fun_with_Car_Plate_Numbers!.ipynb | nadiaalee/cp4all | f1895ec2361355b05b18d0dc3e2216af875ef2ee | [
"CC0-1.0"
]
| 214 | 2020-10-08T01:59:41.000Z | 2022-01-20T20:04:41.000Z | math_fun/Fun_with_Car_Plate_Numbers!.ipynb | nadiaalee/cp4all | f1895ec2361355b05b18d0dc3e2216af875ef2ee | [
"CC0-1.0"
]
| 341 | 2020-10-08T01:39:31.000Z | 2021-10-18T13:23:59.000Z | 49.349693 | 4,744 | 0.59274 | [
[
[
"Good morning! You have completed the math trail on car plate numbers in a somewhat (semi-)automated way.\n\nCan you actually solve the same tasks with code? Read on and you will be amazed how empowering programming can be to help make mathematics learning more efficient and productive! :)",
"_____no_output_____"
],
[
"# Task\n\nGiven the incomplete car plate number `SLA9??2H`\n\nFind the missing ?? numbers.\n\n",
"_____no_output_____"
],
[
"A valid Singapore car plate number typically starts with 3 letters, followed by 4 digits and ending with a 'check' letter. \n\nFor example, for the valid car plate number is 'SDG6136T',\n\n- The first letter is 'S' for Singapore. \n- The next two letters and the digits are used to compute the check letter, using the following steps:\n - Ignoring the first letter 'S', the letters are converted to their positions in the alphabet. For example, 'D' is 4, 'G' is 7 and 'M' is 13. \n - The converted letters and the digits form a sequence of 6 numbers. For example, 'DG6136' will give (4, 7, 6, 1, 3, 6).\n - The sequence of 6 numbers is multiplied term by term by the sequence of 6 weights (9, 4, 5, 4, 3, 2) respectively, summed up and then divided by 19 to obtain the remainder. \n - For example, '476136' will give 4x9 + 7x4 + 6x5 + 1x4 + 3x3 + 6x2 = 119, and this leaves a remainder of 5 after dividing by 19.\n - The 'check' letter is obtained by referring to the following table. Thus the check letter corresponding to remainder 5 is T.\n``` \n| Remainder | 'check' letter | Remainder | 'check' letter | Remainder | 'check' letter |\n| 0 | A | 7 | R | 13 | H |\n| 1 | Z | 8 | P | 14 | G |\n| 2 | Y | 9 | M | 15 | E |\n| 3 | X | 10 | L | 16 | D |\n| 4 | U | 11 | K | 17 | C |\n| 5 | T | 12 | J | 18 | B |\n| 6 | S | | | | |\n```\nReference: https://sgwiki.com/wiki/Vehicle_Checksum_Formula",
"_____no_output_____"
],
[
"Pseudocode\n```\nFOR i = 0 to 99\n Car_Plate = 'SJT9' + str(i) + '2H'\n IF Check_Letter(Car_Plate) is True\n print (Car_Plate) on screen\n ENDIF\n NEXT\n```\n",
"_____no_output_____"
]
],
[
[
"# we need to store the mapping from A to 1, B to 2, etc. \n# for the letters part of the car plate number\n# a dictionary is good for this purpose\nletter_map = {}\nfor i in range(27): # 26 alphabets\n char = chr(ord('A') + i)\n letter_map[char] = i + 1\n#print(letter_map) # this will output {'A':1, 'B':2, 'C':3, ..., 'Z':26}\n\n# we also need to store the mapping from remainders to the check letter\n# and we can also use a dictionary! :)\ncheck_map = {0:'A', 1:'Z', 2:'Y', 3:'X', 4:'U', 5:'T', 6:'S', 7:'R', 8:'P',\t\\\n 9:'M', 10:'L', 11:'K',\t12:'J', 13:'H', 14:'G', 15:'E',\t16:'D',\t\\\n 17:'C', 18:'B'}\n\n# we define a reusable Boolean function to generate the check letter and\n# check if it matches the last letter of the car plate number\ndef check_letter(car_plate):\n weights = [9, 4, 5, 4, 3, 2]\n total = 0\n for i in range(len(car_plate)-1):\n if i < 2: # letters\n num = letter_map[car_plate[i]]\n else: # digits\n num = int(car_plate[i])\n total += num * weights[i]\n remainder = total % 19\n return check_map[remainder] == car_plate[-1]\n\n#main\ncar_plate = 'DG6136T' # you can use this to verify the given example\nif check_letter(car_plate):\n print('S' + car_plate, car_plate[3:5])\nprint()\nfor i in range(100): # this loop repeats 100 times for you! :)\n car_plate = 'LA9' + str(i).zfill(2) + '2H' # 'LA9002H', 'LA9012H', ...\n if check_letter(car_plate):\n print('S' + car_plate, car_plate[3:5])",
"SDG6136T 13\n\nSLA9102H 10\nSLA9252H 25\nSLA9512H 51\nSLA9662H 66\nSLA9922H 92\n"
],
[
"#main\nfor i in range(100):\n car_plate = 'LA' + str(i).zfill(2) + '68Y'\n if check_letter(car_plate):\n print('S' + car_plate, car_plate[2:4])",
"_____no_output_____"
],
[
"'0'.zfill(2)",
"_____no_output_____"
]
],
[
[
"# Challenge\n- How many car_plate numbers start with SMV and end with D?",
"_____no_output_____"
]
],
[
[
"#main\ncount = 0\nfor i in range(10000):\n car_plate = 'MV' + str(i).zfill(4) + 'D'\n if check_letter(car_plate):\n count += 1\nprint(count)",
"525\n"
],
[
"#main\nwanted = []\nfor i in range(10000):\n car_plate = 'MV' + str(i).zfill(4) + 'D'\n if check_letter(car_plate):\n print('S' + car_plate, end=' ')\n wanted.append('S' + car_plate)\nprint(len(wanted))",
"SMV0027D SMV0044D SMV0061D SMV0079D SMV0096D SMV0108D SMV0125D SMV0142D SMV0177D SMV0194D SMV0206D SMV0223D SMV0240D SMV0258D SMV0275D SMV0292D SMV0304D SMV0321D SMV0339D SMV0356D SMV0373D SMV0390D SMV0402D SMV0437D SMV0454D SMV0471D SMV0489D SMV0500D SMV0518D SMV0535D SMV0552D SMV0587D SMV0616D SMV0633D SMV0650D SMV0668D SMV0685D SMV0714D SMV0731D SMV0749D SMV0766D SMV0783D SMV0812D SMV0847D SMV0864D SMV0881D SMV0899D SMV0910D SMV0928D SMV0945D SMV0962D SMV0997D SMV1016D SMV1033D SMV1050D SMV1068D SMV1085D SMV1114D SMV1131D SMV1149D SMV1166D SMV1183D SMV1212D SMV1247D SMV1264D SMV1281D SMV1299D SMV1310D SMV1328D SMV1345D SMV1362D SMV1397D SMV1409D SMV1426D SMV1443D SMV1460D SMV1478D SMV1495D SMV1507D SMV1524D SMV1541D SMV1559D SMV1576D SMV1593D SMV1605D SMV1622D SMV1657D SMV1674D SMV1691D SMV1703D SMV1720D SMV1738D SMV1755D SMV1772D SMV1801D SMV1819D SMV1836D SMV1853D SMV1870D SMV1888D SMV1917D SMV1934D SMV1951D SMV1969D SMV1986D SMV2005D SMV2022D SMV2057D SMV2074D SMV2091D SMV2103D SMV2120D SMV2138D SMV2155D SMV2172D SMV2201D SMV2219D SMV2236D SMV2253D SMV2270D SMV2288D SMV2317D SMV2334D SMV2351D SMV2369D SMV2386D SMV2415D SMV2432D SMV2467D SMV2484D SMV2513D SMV2530D SMV2548D SMV2565D SMV2582D SMV2611D SMV2629D SMV2646D SMV2663D SMV2680D SMV2698D SMV2727D SMV2744D SMV2761D SMV2779D SMV2796D SMV2808D SMV2825D SMV2842D SMV2877D SMV2894D SMV2906D SMV2923D SMV2940D SMV2958D SMV2975D SMV2992D SMV3011D SMV3029D SMV3046D SMV3063D SMV3080D SMV3098D SMV3127D SMV3144D SMV3161D SMV3179D SMV3196D SMV3208D SMV3225D SMV3242D SMV3277D SMV3294D SMV3306D SMV3323D SMV3340D SMV3358D SMV3375D SMV3392D SMV3404D SMV3421D SMV3439D SMV3456D SMV3473D SMV3490D SMV3502D SMV3537D SMV3554D SMV3571D SMV3589D SMV3600D SMV3618D SMV3635D SMV3652D SMV3687D SMV3716D SMV3733D SMV3750D SMV3768D SMV3785D SMV3814D SMV3831D SMV3849D SMV3866D SMV3883D SMV3912D SMV3947D SMV3964D SMV3981D SMV3999D SMV4000D SMV4018D SMV4035D SMV4052D SMV4087D SMV4116D SMV4133D SMV4150D SMV4168D SMV4185D SMV4214D SMV4231D SMV4249D SMV4266D SMV4283D SMV4312D SMV4347D SMV4364D SMV4381D SMV4399D SMV4410D SMV4428D SMV4445D SMV4462D SMV4497D SMV4509D SMV4526D SMV4543D SMV4560D SMV4578D SMV4595D SMV4607D SMV4624D SMV4641D SMV4659D SMV4676D SMV4693D SMV4705D SMV4722D SMV4757D SMV4774D SMV4791D SMV4803D SMV4820D SMV4838D SMV4855D SMV4872D SMV4901D SMV4919D SMV4936D SMV4953D SMV4970D SMV4988D SMV5007D SMV5024D SMV5041D SMV5059D SMV5076D SMV5093D SMV5105D SMV5122D SMV5157D SMV5174D SMV5191D SMV5203D SMV5220D SMV5238D SMV5255D SMV5272D SMV5301D SMV5319D SMV5336D SMV5353D SMV5370D SMV5388D SMV5417D SMV5434D SMV5451D SMV5469D SMV5486D SMV5515D SMV5532D SMV5567D SMV5584D SMV5613D SMV5630D SMV5648D SMV5665D SMV5682D SMV5711D SMV5729D SMV5746D SMV5763D SMV5780D SMV5798D SMV5827D SMV5844D SMV5861D SMV5879D SMV5896D SMV5908D SMV5925D SMV5942D SMV5977D SMV5994D SMV6013D SMV6030D SMV6048D SMV6065D SMV6082D SMV6111D SMV6129D SMV6146D SMV6163D SMV6180D SMV6198D SMV6227D SMV6244D SMV6261D SMV6279D SMV6296D SMV6308D SMV6325D SMV6342D SMV6377D SMV6394D SMV6406D SMV6423D SMV6440D SMV6458D SMV6475D SMV6492D SMV6504D SMV6521D SMV6539D SMV6556D SMV6573D SMV6590D SMV6602D SMV6637D SMV6654D SMV6671D SMV6689D SMV6700D SMV6718D SMV6735D SMV6752D SMV6787D SMV6816D SMV6833D SMV6850D SMV6868D SMV6885D SMV6914D SMV6931D SMV6949D SMV6966D SMV6983D SMV7002D SMV7037D SMV7054D SMV7071D SMV7089D SMV7100D SMV7118D SMV7135D SMV7152D SMV7187D SMV7216D SMV7233D SMV7250D SMV7268D SMV7285D SMV7314D SMV7331D SMV7349D SMV7366D SMV7383D SMV7412D SMV7447D SMV7464D SMV7481D SMV7499D SMV7510D SMV7528D SMV7545D SMV7562D SMV7597D SMV7609D SMV7626D SMV7643D SMV7660D SMV7678D SMV7695D SMV7707D SMV7724D SMV7741D SMV7759D SMV7776D SMV7793D SMV7805D SMV7822D SMV7857D SMV7874D SMV7891D SMV7903D SMV7920D SMV7938D SMV7955D SMV7972D SMV8009D SMV8026D SMV8043D SMV8060D SMV8078D SMV8095D SMV8107D SMV8124D SMV8141D SMV8159D SMV8176D SMV8193D SMV8205D SMV8222D SMV8257D SMV8274D SMV8291D SMV8303D SMV8320D SMV8338D SMV8355D SMV8372D SMV8401D SMV8419D SMV8436D SMV8453D SMV8470D SMV8488D SMV8517D SMV8534D SMV8551D SMV8569D SMV8586D SMV8615D SMV8632D SMV8667D SMV8684D SMV8713D SMV8730D SMV8748D SMV8765D SMV8782D SMV8811D SMV8829D SMV8846D SMV8863D SMV8880D SMV8898D SMV8927D SMV8944D SMV8961D SMV8979D SMV8996D SMV9015D SMV9032D SMV9067D SMV9084D SMV9113D SMV9130D SMV9148D SMV9165D SMV9182D SMV9211D SMV9229D SMV9246D SMV9263D SMV9280D SMV9298D SMV9327D SMV9344D SMV9361D SMV9379D SMV9396D SMV9408D SMV9425D SMV9442D SMV9477D SMV9494D SMV9506D SMV9523D SMV9540D SMV9558D SMV9575D SMV9592D SMV9604D SMV9621D SMV9639D SMV9656D SMV9673D SMV9690D SMV9702D SMV9737D SMV9754D SMV9771D SMV9789D SMV9800D SMV9818D SMV9835D SMV9852D SMV9887D SMV9916D SMV9933D SMV9950D SMV9968D SMV9985D 525\n"
]
],
[
[
"# More challenges!\n\nSuggest one or more variations of problems you can solve with car plate numbers using the power of Python programming. Some ideas include:\n* Check if a given car plate number is valid\n* Which valid car plate numbers have a special property (eg prime number, contains at least two '8' digits, does not contain the lucky number 13, etc.)\n* If there are the same number of available car plate numbers each series (eg SMV and SMW)\n* (your idea here)\n\nSubmit a pull request with your ideas and/or code to contribute to learning Mathematics using programming to benefit the world! :)",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"# This is really more than car plate numbers!\n\nYou have just learned an application of mathematics called modulus arithmetic in generating check letters/digits. Do you know that actually the following are also applications of modulus arithmetic?\n* Singapore NRIC numbers (http://www.ngiam.net/NRIC/NRIC_numbers.ppt)\n* international ISBNs (https://en.wikipedia.org/wiki/International_Standard_Book_Number)\n* credit card numbers (https://en.wikipedia.org/wiki/Luhn_algorithm)\n* universal product codes (https://en.wikipedia.org/wiki/Universal_Product_Code)\n\nCan you research on other applications modulus arithmetic has? Better still, contribute by submitting Python code to unleash the power of automation!\n\nYou can submit a pull request by doing one of the following:\n- suggesting a new application for modulus arithmetic\n- creating a new .py file\n- uploading an existing .py file\n\nWe look forward to your pull requests! :)",
"_____no_output_____"
]
]
]
| [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
]
| [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
]
|
cb5cc59de7c542d82d6feecac845394ce7bc41a0 | 52,944 | ipynb | Jupyter Notebook | notebooks/New_fitness_functions_and_acquisition_functions.ipynb | georgedeath/egreedy | 4ab1a991e46162eafb3e51575a47fbcda578a5f5 | [
"MIT"
]
| 3 | 2020-01-30T17:13:44.000Z | 2021-03-01T15:05:48.000Z | notebooks/New_fitness_functions_and_acquisition_functions.ipynb | georgedeath/egreedy | 4ab1a991e46162eafb3e51575a47fbcda578a5f5 | [
"MIT"
]
| null | null | null | notebooks/New_fitness_functions_and_acquisition_functions.ipynb | georgedeath/egreedy | 4ab1a991e46162eafb3e51575a47fbcda578a5f5 | [
"MIT"
]
| 1 | 2021-11-08T14:36:16.000Z | 2021-11-08T14:36:16.000Z | 73.944134 | 13,804 | 0.765299 | [
[
[
"# Using a new function to evaluate or evaluating a new acquisition function",
"_____no_output_____"
],
[
"In this notebook we describe how to integrate a new fitness function to the testing framework as well as how to integrate a new acquisition function.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\n\n# add the egreedy module to the path (one directory up from this)\nimport sys, os\nsys.path.append(os.path.realpath(os.path.pardir))",
"_____no_output_____"
]
],
[
[
"## New fitness function",
"_____no_output_____"
],
[
"The `perform_experiment` function in the `optimizer` class, used to carry out the optimisation runs (see its docstring and `run_all_experiments.py` for usage examples), imports a fitness **class**. This class, when instantiated is also callable. The class is imported from the `test_problems` module. Therefore, the easiest way to incorporate your own fitness function is to add it to the `test_problems` module by creating a python file in the `egreedy/test_problems/` directory and adding a line importing it into the namespace (see `egreedy/test_problems/__init__.py` for examples) so that it can be directly imported from `test_problems`.\n\nIf, for example, your fitness class is called `xSquared` and is located in the file `xs.py`, you would place the python file in the directory `egreedy/test_problems` and add the line:\n```\nfrom .xs import xSquared\n```\nto the `egreedy/test_problems/__init__.py` file.\n\nWe will now detail how to structure your fitness class and show the required class methods by creating a new fitness class for the function\n\\begin{equation}\nf( \\mathbf{x} ) = \\sum_{i=1}^2 x_i^2,\n\\end{equation}\nwhere $\\mathbf{x} \\in [-5, 5]^2.$",
"_____no_output_____"
]
],
[
[
"class xSquared:\n \"\"\"Example fitness class.\n \n .. math::\n f(x) = \\sum_{i=1}^2 x_i^2\n \n This demonstration class shows all the required attributes and \n functionality of the fitness function class.\n \"\"\"\n \n def __init__(self):\n \"\"\"Initialisation function.\n \n This is called when the class is instantiated and sets up its\n attributes as well as any other internal variables that may\n be needed.\n \"\"\"\n # problem dimensionality\n self.dim = 2\n \n # lower and upper bounds for each dimension (must be numpy.ndarray)\n self.lb = np.array([-5., -5.])\n self.ub = np.array([5., 5.])\n \n # location(s) of the optima (optional - not always known)\n self.xopt = np.array([0.])\n \n # its/thier fitness value(s)\n self.yopt = np.array([0.])\n \n # callable constraint function for the problem - should return\n # True if the argument value is **valid** - if no constraint function\n # is required then this can take the value of None\n self.cf = None\n \n def __call__(self, x):\n \"\"\"Main callable function.\n \n This is called after the class is instantiated, e.g.\n >>> f = xSquared()\n >>> f(np.array([2., 2.]))\n array([8.])\n \n Note that it is useful to have a function that is able deal with\n multiple inputs, which should a numpy.ndarray of shape (N, dim)\n \"\"\"\n # ensure the input is at least 2d, this will cause one-dimensional\n # vectors to be reshaped to shape (1, dim)\n x = np.atleast_2d(x)\n \n # evaluate the function\n val = np.sum(np.square(x), axis=1)\n \n # return the evaluations\n return val",
"_____no_output_____"
]
],
[
[
"This class can then either be placed in the directories discussed above and used for evaluating multiple techniques on it or used for testing purposes.",
"_____no_output_____"
],
[
"### Optimising the new test function with an acquistion function",
"_____no_output_____"
],
[
"The following code outlines how to optimise your newly created test function with the $\\epsilon$-greedy with Pareto front selection ($\\epsilon$-PF) algorithm.",
"_____no_output_____"
]
],
[
[
"from pyDOE2 import lhs\nfrom egreedy.optimizer import perform_BO_iteration\n\n# ---- instantiate the test problem\nf = xSquared()\n\n# ---- Generate testing data by Latin hypercube sampling across the domain\nn_training = 2 * f.dim\n\n# LHS sample in [0, 1]^2 and rescale to problem domain\nXtr = lhs(f.dim, n_training, criterion='maximin')\nXtr = (f.ub - f.lb) * Xtr + f.lb\n\n# expensively evaluate and ensure shape is (n_training, 1)\nYtr = np.reshape(f(Xtr), (n_training, 1))\n\n# ---- Select an acquistion function with optimiser.\n# In this case we select e-greedy with Pareto front selection (e-PF)\n# known as eFront.\n#\n# All the acqusition functions have the same parameters:\n# lb : lower-bound constraints (numpy.ndarray)\n# ub : upper-bound constraints (numpy.ndarray)\n# acq_budget : max number of calls to the GP model\n# cf : callable function constraint function that returns True if\n# the argument vector is VALID. Optional, has a value of None\n# if not used\n# acquisition_args : optional dictionary containing key:value pairs\n# of arguments to a specific acqutision function.\n# e.g. for an e-greedy method then the dict\n# {'epsilon': 0.1} would dictate the epsilon value.\n\n# e-greedy with Pareto front selection (e-PF), known as eFront\nfrom egreedy.acquisition_functions import eFront\n\n# instantiate the optimiser with a budget of 5000d and epsilon = 0.1\nacq_budget = 5000 * f.dim\nacquisition_args = {'epsilon': 0.1}\n\nacq_func = eFront(lb=f.lb, ub=f.ub, cf=None, acq_budget=acq_budget,\n acquisition_args=acquisition_args)\n\n# ---- Perform the bayesian optimisation loop for a total budget of 20\n# function evaluations (including those used for LHS sampling)\ntotal_budget = 20\n\nwhile Xtr.shape[0] < total_budget:\n # perform one iteration of BO:\n # this returns the new location and function value (Xtr, Ynew) as well\n # as the trained model used to select the new location\n Xnew, Ynew, model = perform_BO_iteration(Xtr, Ytr,f, acq_func, verbose=True)\n \n # augment the training data and repeat\n Xtr = np.concatenate((Xtr, np.atleast_2d(Xnew)))\n Ytr = np.concatenate((Ytr, np.atleast_2d(Ynew)))\n \n print('Best function value so far: {:g}'.format(np.min(Ytr)))\n print()",
"Training a GP model with 4 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [2.74739209 1.85140059]\nFunction value: 10.9758\nBest function value so far: 2.34029\n\nTraining a GP model with 5 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [0.8734869 0.23262576]\nFunction value: 0.817094\nBest function value so far: 0.817094\n\nTraining a GP model with 6 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [0.48106594 0.1616895 ]\nFunction value: 0.257568\nBest function value so far: 0.257568\n\nTraining a GP model with 7 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [0.18353004 0.31916069]\nFunction value: 0.135547\nBest function value so far: 0.135547\n\nTraining a GP model with 8 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [0.13640659 0.16686483]\nFunction value: 0.0464506\nBest function value so far: 0.0464506\n\nTraining a GP model with 9 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [0.01887471 0.03552285]\nFunction value: 0.00161813\nBest function value so far: 0.00161813\n\nTraining a GP model with 10 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [-0.00498028 0.00452991]\nFunction value: 4.53233e-05\nBest function value so far: 4.53233e-05\n\nTraining a GP model with 11 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [-0.00296791 0.01886975]\nFunction value: 0.000364876\nBest function value so far: 4.53233e-05\n\nTraining a GP model with 12 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [-0.00228287 -0.0035852 ]\nFunction value: 1.80651e-05\nBest function value so far: 1.80651e-05\n\nTraining a GP model with 13 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [-0.00136503 0.01035887]\nFunction value: 0.00010917\nBest function value so far: 1.80651e-05\n\nTraining a GP model with 14 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [-0.00031969 -0.00034095]\nFunction value: 2.18449e-07\nBest function value so far: 2.18449e-07\n\nTraining a GP model with 15 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [0.0022843 0.00156171]\nFunction value: 7.65699e-06\nBest function value so far: 2.18449e-07\n\nTraining a GP model with 16 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [0.00435965 0.00438578]\nFunction value: 3.82417e-05\nBest function value so far: 2.18449e-07\n\nTraining a GP model with 17 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [-0.0038385 -0.01013353]\nFunction value: 0.000117422\nBest function value so far: 2.18449e-07\n\nTraining a GP model with 18 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [0.01889642 0.02033263]\nFunction value: 0.000770491\nBest function value so far: 2.18449e-07\n\nTraining a GP model with 19 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [ 0.00050108 -0.02413065]\nFunction value: 0.000582539\nBest function value so far: 2.18449e-07\n\n"
]
],
[
[
"The plot below shows the difference between the best seen function value and the true minimum, i.e. $|f^\\star - f_{min}|$, over each iteration.",
"_____no_output_____"
]
],
[
[
"fig, ax = plt.subplots(1, 1, figsize=(8, 4))\nax.semilogy(np.minimum.accumulate(np.abs(Ytr - f.yopt)))\nax.set_xlabel('Iteration', fontsize=15)\nax.set_ylabel('$|f^\\star - f_{min}|$', fontsize=15)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## New acquisition function",
"_____no_output_____"
],
[
"We now detail how to create your own acquisition function class and integrate it into the testing suite.\n\nIn a similar manner to the fitness function classes, the acquisition function classes are imported from the `egreedy.acquisition_functions` module, with the specific classes available determined by the `__ini__.py` file in the same module. \n\nIf, for example, your acquisition function class is called `greed` and is located in the file `gr.py`, you would place the python file in the directory `egreedy/acquisition_functions` and add the line:\n```\nfrom .gr import greed\n```\nto the `egreedy/acquisition_functions/__init__.py` file.\n\nThe python file `egreedy/acquisition_functions/acq_func_optimisers.py` contains base classes for the acquisition function classes. We will now demonstrate how to implement two simple acquisition functions and then show how to optimise one of the test functions included in the suite.",
"_____no_output_____"
],
[
"The `BaseOptimiser` class is the base acquisition function class that implements the standard interface for acquisition function optimizers. It only contains an initialisation function with several arguments:\n\n- lb: lower-bound constraint\n- ub: upper-bound constraint\n- acq_budget : maximum number of calls to the Gaussian Process\n- cf : callable constraint function that returns True if the argument decision vector is VALID (optional, default value: None)\n- acquisition_args : Optional dictionary containing additional arguments that are unpacked into key=value arguments for an internal acquisition function; e.g. {'epsilon':0.1}.\n\nThe `ParetoFrontOptimiser` class implements the base class as well as an additional function named `get_front(model)` that takes in a GPRegression model from GPy and approximates its Pareto front of model prediction and uncertainty. It returns the decision vectors belonging to the members of the front, an array containing corresponding their predicted value, and an array containing the prediction uncertainty.\n\nWe first create a simple acquisition function, extending the base class, that generates uniform samples in space and uses the Gaussian Process's mean prediction to select the best (lowest value) predicted location.",
"_____no_output_____"
]
],
[
[
"from egreedy.acquisition_functions.acq_func_optimisers import BaseOptimiser\n\nclass greedy_sample(BaseOptimiser):\n \"\"\"Greedy function that uniformly samples the GP posterior\n and returns the location with the best (lowest) mean predicted value.\n \"\"\"\n \n # note we do not need to implement an __init__ method because the\n # base class already does this. Here we will include a commented\n # version for clarity.\n# def __init__(self, lb, ub, acq_budget, cf=None, acquisition_args={}):\n# self.lb = lb\n# self.ub = ub\n# self.cf = cf\n# self.acquisition_args = acquisition_args\n# self.acq_budget = acq_budget\n\n def __call__(self, model):\n \"\"\"Returns the location with the best (lowest) predicted value\n after uniformly sampling decision space.\n \"\"\"\n \n # generate samples\n X = np.random.uniform(self.lb, self.ub,\n size=(acq_budget, self.lb.size))\n \n # evaluate them with the gp\n mu, sigmasqr = model.predict(X, full_cov=False)\n \n # find the index of the best value\n argmin = np.argmin(mu.flat)\n \n # return the best found value\n return X[argmin, :]",
"_____no_output_____"
],
[
"from egreedy.acquisition_functions.acq_func_optimisers import ParetoFrontOptimiser\n\n\nclass greedy_pfront(ParetoFrontOptimiser):\n \"\"\"Exploitative method that calculates the approximate Pareto front\n of a GP model and returns the Pareto set member that has the best\n (lowest) predicted value.\n \"\"\"\n \n # again here we do not need to implement an __init__ method.\n \n def __call__(self, model):\n \"\"\"Returns the location with the best (lowest) predicted value\n from the approximate Pareto set of the GP's predicted value and\n its corresponding uncertainty.\n \"\"\"\n \n # approximate the pareto set; here X are the locations of the\n # members of the set and mu and sigma are their predicted values\n # and uncertainty\n X, mu, sigma = self.get_front(model)\n \n # find the index of the best value\n argmin = np.argmin(mu.flat)\n \n # return the best found value\n return X[argmin, :]",
"_____no_output_____"
]
],
[
[
"We now create a similar script to the one used above in the function example. This time we will optimise the `push4` function included in the test suite and load the training data associated with the first run all techniques evaluated in the paper carried out. \n\nNote that in this case the training data contains arguments to be passed into the function during instantiation. This is because the `push4` runs are evaluated on a *problem instance* basis.",
"_____no_output_____"
]
],
[
[
"from egreedy.optimizer import perform_BO_iteration\nfrom egreedy import test_problems\n\n# ---- optimisation run details\nproblem_name = 'push4'\nrun_no = 1\nacq_budget = 5000 * 4 # because the problem dimensionality is 4\n\ntotal_budget = 25\n\n# ---- load the training data\ndata_file = f'../training_data/{problem_name:}_{run_no:}.npz'\n\nwith np.load(data_file, allow_pickle=True) as data:\n Xtr = data['arr_0']\n Ytr = data['arr_1']\n \n if 'arr_2' in data:\n f_optional_arguments = data['arr_2'].item()\n else:\n f_optional_arguments = {}\n \n# ---- instantiate the test problem\nf_class = getattr(test_problems, problem_name)\nf = f_class(**f_optional_arguments)\n\n\n# ---- instantiate the acquistion function we created earlier\nacq_func = greedy_sample(lb=f.lb, ub=f.ub, cf=None, acq_budget=acq_budget,\n acquisition_args=acquisition_args)\n\nwhile Xtr.shape[0] < total_budget:\n # perform one iteration of BO:\n # this returns the new location and function value (Xtr, Ynew) as well\n # as the trained model used to select the new location\n Xnew, Ynew, model = perform_BO_iteration(Xtr, Ytr, f, acq_func, verbose=True)\n\n # augment the training data and repeat\n Xtr = np.concatenate((Xtr, np.atleast_2d(Xnew)))\n Ytr = np.concatenate((Ytr, np.atleast_2d(Ynew)))\n \n print('Best function value so far: {:g}'.format(np.min(Ytr)))\n print()",
"Training a GP model with 8 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [0.99363897 0.49599772 0.99868045 0.97496078]\nFunction value: 8.38627\nBest function value so far: 2.01458\n\nTraining a GP model with 9 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [0.99735174 0.05688416 0.95975881 0.09915249]\nFunction value: 6.39738\nBest function value so far: 2.01458\n\nTraining a GP model with 10 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [0.99426994 0.48176988 0.04539143 0.52413627]\nFunction value: 4.30593\nBest function value so far: 2.01458\n\nTraining a GP model with 11 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [0.97676317 0.20990921 0.03083971 0.94382162]\nFunction value: 4.32446\nBest function value so far: 2.01458\n\nTraining a GP model with 12 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [0.98233984 0.45681325 0.32258875 0.65155143]\nFunction value: 1.9939\nBest function value so far: 1.9939\n\nTraining a GP model with 13 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [0.98055465 0.40088946 0.31056256 0.72057199]\nFunction value: 2.33662\nBest function value so far: 1.9939\n\nTraining a GP model with 14 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [0.87735007 0.4604941 0.26450847 0.67341351]\nFunction value: 0.679518\nBest function value so far: 0.679518\n\nTraining a GP model with 15 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [0.77766143 0.49442689 0.30924655 0.68061374]\nFunction value: 1.68864\nBest function value so far: 0.679518\n\nTraining a GP model with 16 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [0.86687143 0.5127836 0.19990311 0.69685941]\nFunction value: 0.951315\nBest function value so far: 0.679518\n\nTraining a GP model with 17 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [0.85716692 0.48996299 0.19234286 0.6498631 ]\nFunction value: 2.24849\nBest function value so far: 0.679518\n\nTraining a GP model with 18 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [0.87333699 0.56790019 0.27448691 0.80146525]\nFunction value: 1.56872\nBest function value so far: 0.679518\n\nTraining a GP model with 19 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [0.88507765 0.4508956 0.22725763 0.75254124]\nFunction value: 1.00578\nBest function value so far: 0.679518\n\nTraining a GP model with 20 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [0.90001785 0.5103195 0.25189873 0.67868624]\nFunction value: 2.1292\nBest function value so far: 0.679518\n\nTraining a GP model with 21 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [0.82927784 0.53929787 0.12721344 0.76115955]\nFunction value: 1.65907\nBest function value so far: 0.679518\n\nTraining a GP model with 22 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [0.88407381 0.3162302 0.39928955 0.58348638]\nFunction value: 1.58757\nBest function value so far: 0.679518\n\nTraining a GP model with 23 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [0.02661341 0.95209027 0.97135965 0.98684695]\nFunction value: 7.67696\nBest function value so far: 0.679518\n\nTraining a GP model with 24 data points.\nOptimising the acquisition function.\nExpensively evaluating the new selected location.\nNew location : [0.89053271 0.37854249 0.30893649 0.67180526]\nFunction value: 3.55493\nBest function value so far: 0.679518\n\n"
],
[
"fig, ax = plt.subplots(1, 1, figsize=(8, 4))\nax.plot(np.minimum.accumulate(np.abs(Ytr - f.yopt)))\nax.set_xlabel('Iteration', fontsize=15)\nax.set_ylabel('$|f^\\star - f_{min}|$', fontsize=15)\nplt.show()",
"_____no_output_____"
]
]
]
| [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
]
| [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
]
|
cb5cc7fdebf7846603f0f822181d372e366faab9 | 308,690 | ipynb | Jupyter Notebook | demo/non_Gaussian_likelihood.ipynb | mingdeyu/DGP | fcc630896d45175d1aa72219607178ca7648cffb | [
"MIT"
]
| 12 | 2021-07-06T07:49:42.000Z | 2022-03-10T09:49:04.000Z | demo/non_Gaussian_likelihood.ipynb | mingdeyu/DGP | fcc630896d45175d1aa72219607178ca7648cffb | [
"MIT"
]
| 5 | 2021-09-21T02:16:58.000Z | 2022-01-20T05:16:52.000Z | demo/non_Gaussian_likelihood.ipynb | mingdeyu/DGP | fcc630896d45175d1aa72219607178ca7648cffb | [
"MIT"
]
| 3 | 2021-07-19T13:54:38.000Z | 2021-10-13T19:55:27.000Z | 413.793566 | 57,290 | 0.936995 | [
[
[
"from dgpsi import dgp, kernel, combine, lgp, path, emulator, Poisson, Hetero, NegBin\nimport numpy as np\nimport matplotlib.pyplot as plt",
"_____no_output_____"
]
],
[
[
"# Example 1 on heteroskedastic Gaussian likelihood",
"_____no_output_____"
]
],
[
[
"n=12\nX=np.linspace(0,1,n)[:,None]\n#Create some replications of input positions so that each input position will six different outputs. Note that SI has linear complexity with number of replications. \nfor i in range(5):\n X=np.concatenate((X,np.linspace(0,1,n)[:,None]),axis=0)\nf1= lambda x: -1. if x<0.5 else 1. #True mean function, which is a step function\nf2= lambda x: np.exp(1.5*np.sin((x-0.3)*7.)-6.5) #True variance function, which has higher values around 0.5 but low values around boundaries\nY=np.array([np.random.normal(f1(x),np.sqrt(f2(x))) for x in X]) #Generate stochastic outputs according to f1 and f2\nz=np.linspace(0,1.,200)[:,None]\nYz=np.array([f1(x) for x in z]).flatten()\nplt.plot(z,Yz) #Plot true mean function\nplt.scatter(X,Y,color='r')",
"_____no_output_____"
],
[
"#Create a 2-layered DGP + Hetero model\nlayer1=[kernel(length=np.array([0.5]),name='matern2.5')]\nlayer2=[kernel(length=np.array([0.2]),name='matern2.5',scale_est=1,connect=np.arange(1)),\nkernel(length=np.array([0.2]),name='matern2.5',scale_est=1,connect=np.arange(1))]\nlayer3=[Hetero()]",
"_____no_output_____"
],
[
"#Construct the DGP + Hetero model\nall_layer=combine(layer1,layer2,layer3)\nm=dgp(X,[Y],all_layer)",
"_____no_output_____"
],
[
"#Train the model\nm.train(N=500)",
"Iteration 500: Layer 3: 100%|██████████| 500/500 [00:32<00:00, 15.57it/s]\n"
],
[
"#Construct the emulator\nfinal_layer_obj=m.estimate()\nemu=emulator(final_layer_obj)",
"_____no_output_____"
],
[
"#Make predictions across all layers so we can extract predictions for the mean and variance functions\nmu,var=emu.predict(z, method='mean_var',full_layer=True)",
"_____no_output_____"
],
[
"#Visualize the overall model prediction\ns=np.sqrt(var[-1])\nu=mu[-1]+2*s\nl=mu[-1]-2*s\np=plt.plot(z,mu[-1],color='r',alpha=1,lw=1)\np1=plt.plot(z,u,'--',color='g',lw=1)\np1=plt.plot(z,l,'--',color='g',lw=1)\nplt.scatter(X,Y,color='black')\nplt.plot(z,Yz)",
"_____no_output_____"
],
[
"#Visualize the prediction for the mean function\nmu_mean=mu[-2][:,0]\nvar_mean=var[-2][:,0]\ns=np.sqrt(var_mean)\nu=mu_mean+2*s\nl=mu_mean-2*s\np=plt.plot(z,mu_mean,color='r',alpha=1,lw=1)\np1=plt.plot(z,u,'--',color='g',lw=1)\np1=plt.plot(z,l,'--',color='g',lw=1)\nplt.plot(z,Yz,color='black',lw=1)",
"_____no_output_____"
],
[
"#Visualize the prediction for the log(variance) function\nmu_var=mu[-2][:,1]\nvar_var=var[-2][:,1]\ns=np.sqrt(var_var)\nu=mu_var+2*s\nl=mu_var-2*s\np=plt.plot(z,mu_var,color='r',alpha=1,lw=1)\np1=plt.plot(z,u,'--',color='g',lw=1)\np1=plt.plot(z,l,'--',color='g',lw=1)\nplt.plot(z,np.array([np.log(f2(x)) for x in z]).reshape(-1,1),color='black',lw=1)",
"_____no_output_____"
]
],
[
[
"# Example 2 on heteroskedastic Gaussian likelihood",
"_____no_output_____"
]
],
[
[
"#Load and visualize the motorcycle dataset\nX=np.loadtxt('./mc_input.txt').reshape(-1,1)\nY=np.loadtxt('./mc_output.txt').reshape(-1,1)\nX=(X-np.min(X))/(np.max(X)-np.min(X))\nY=(Y-Y.mean())/Y.std()\nplt.scatter(X,Y)",
"_____no_output_____"
],
[
"#Construct a 2-layered DGP + Hetero model\nlayer1=[kernel(length=np.array([0.5]),name='sexp')]\nlayer2=[]\nfor _ in range(2):\n k=kernel(length=np.array([0.2]),name='sexp',scale_est=1,connect=np.arange(1))\n layer2.append(k)\nlayer3=[Hetero()]\n\nall_layer=combine(layer1,layer2,layer3)\nm=dgp(X,[Y],all_layer)",
"_____no_output_____"
],
[
"#Train the model\nm.train(N=500)",
"Iteration 500: Layer 3: 100%|██████████| 500/500 [04:26<00:00, 1.87it/s]\n"
],
[
"#Construct the emulator\nfinal_layer_obj=m.estimate()\nemu=emulator(final_layer_obj)",
"_____no_output_____"
],
[
"#Make predictions over [0,1]\nz=np.linspace(0,1,100)[:,None]\nmu,var=emu.predict(z, method='mean_var')",
"_____no_output_____"
],
[
"#Visualize the predictions\ns=np.sqrt(var)\nu=mu+2*s\nl=mu-2*s\np=plt.plot(z,mu,color='r',alpha=1,lw=1)\np1=plt.plot(z,u,'--',color='g',lw=1)\np1=plt.plot(z,l,'--',color='g',lw=1)\nplt.scatter(X,Y,color='black')",
"_____no_output_____"
]
],
[
[
"# Example 3 on Poisson likelihood",
"_____no_output_____"
]
],
[
[
"#Generate some data with replications\nn=10\nX=np.linspace(0,.3,n)[:,None]\nfor _ in range(4):\n X=np.concatenate((X,np.linspace(0,.3,n)[:,None]),axis=0)\n X=np.concatenate((X,np.linspace(0.35,1,n)[:,None]),axis=0)\nf= lambda x: np.exp(np.exp(-1.5*np.sin(1/((0.7*0.8*(1.5*x+0.1)+0.3)**2))))\nY=np.array([np.random.poisson(f(x)) for x in X]).reshape(-1,1)\nz=np.linspace(0,1.,200)[:,None]\nYz=np.array([f(x) for x in z]).flatten()\ntest_Yz=np.array([np.random.poisson(f(x)) for x in z]).reshape(-1,1) #generate some testing output data\nplt.plot(z,Yz)\nplt.scatter(X,Y,color='r')\n",
"_____no_output_____"
],
[
"#Train a GP + Poisson model\nlayer1=[kernel(length=np.array([0.5]),name='matern2.5',scale_est=1)]\nlayer2=[Poisson()]\nall_layer=combine(layer1,layer2)\nm=dgp(X,[Y],all_layer)\nm.train(N=500)",
"Iteration 500: Layer 2: 100%|██████████| 500/500 [00:10<00:00, 49.89it/s]\n"
],
[
"#Visualize the results\nfinal_layer_obj=m.estimate()\nemu=emulator(final_layer_obj)\nmu,var=emu.predict(z, method='mean_var',full_layer=True) #Make mean-variance prediction\nsamp=emu.predict(z, method='sampling') #Draw some samples to obtain the quantiles of the overall model\nquant=np.quantile(np.squeeze(samp), [0.05,0.5,0.95],axis=1) #Compute sample-based quantiles\nfig, (ax1, ax2) = plt.subplots(1,2, figsize=(15,4))\nax1.set_title('Predicted and True Poisson Mean')\nax1.plot(z,Yz,color='black')\nax1.plot(z,mu[-1],'--',color='red',alpha=0.8,lw=3)\nax1.plot(z,quant[0,:],'--',color='b',lw=1)\nax1.plot(z,quant[1,:],'--',color='b',lw=1)\nax1.plot(z,quant[2,:],'--',color='b',lw=1)\nmu_gp, var_gp=mu[-2], var[-2]\ns=np.sqrt(var_gp)\nu,l =mu_gp+2*s, mu_gp-2*s\nax2.set_title('Predicted and True logged Poisson Mean')\nax2.plot(z,mu_gp,color='r',alpha=1,lw=1)\nax2.plot(z,u,'--',color='g',lw=1)\nax2.plot(z,l,'--',color='g',lw=1)\nax2.plot(z,np.log(Yz),color='black',lw=1)\nprint('The negative log-likelihood of predictions is', emu.nllik(z,test_Yz)[0])",
"The negative log-likelihood of predictions is 1.827381042590187\n"
],
[
"#Train a 2-layered DGP + Poisson model\nlayer1=[kernel(length=np.array([0.5]),name='matern2.5')]\nlayer2=[kernel(length=np.array([0.1]),name='matern2.5',scale_est=1,connect=np.arange(1))]\nlayer3=[Poisson()]\nall_layer=combine(layer1,layer2,layer3)\nm=dgp(X,[Y],all_layer)\nm.train(N=500)",
"Iteration 500: Layer 3: 100%|██████████| 500/500 [00:23<00:00, 21.71it/s]\n"
],
[
"#Visualize the results\nfinal_layer_obj=m.estimate()\nemu=emulator(final_layer_obj)\nmu,var=emu.predict(z, method='mean_var',full_layer=True) #Make mean-variance prediction\nsamp=emu.predict(z, method='sampling') #Draw some samples to obtain the quantiles of the overall model\nquant=np.quantile(np.squeeze(samp), [0.05,0.5,0.95],axis=1) #Compute sample-based quantiles\nfig, (ax1, ax2) = plt.subplots(1,2, figsize=(15,4))\nax1.set_title('Predicted and True Poisson Mean')\nax1.plot(z,Yz,color='black')\nax1.plot(z,mu[-1],'--',color='red',alpha=0.8,lw=3)\nax1.plot(z,quant[0,:],'--',color='b',lw=1)\nax1.plot(z,quant[1,:],'--',color='b',lw=1)\nax1.plot(z,quant[2,:],'--',color='b',lw=1)\nmu_gp, var_gp=mu[-2], var[-2]\ns=np.sqrt(var_gp)\nu,l =mu_gp+2*s, mu_gp-2*s\nax2.set_title('Predicted and True logged Poisson Mean')\nax2.plot(z,mu_gp,color='r',alpha=1,lw=1)\nax2.plot(z,u,'--',color='g',lw=1)\nax2.plot(z,l,'--',color='g',lw=1)\nax2.plot(z,np.log(Yz),color='black',lw=1)\nprint('The negative log-likelihood of predictions is', emu.nllik(z,test_Yz)[0])",
"The negative log-likelihood of predictions is 1.7790101014101791\n"
]
],
[
[
"# Example 4 on Negative Binomial likelihood\nThe Negative Binomial pmf in dgpsi is defined by\n$$p_Y(y;\\mu,\\sigma)=\\frac{\\Gamma(y+\\frac{1}{\\sigma})}{\\Gamma(1/{\\sigma})\\Gamma(y+1)}\\left(\\frac{\\sigma\\mu}{1+\\sigma\\mu}\\right)^y\\left(\\frac{1}{1+\\sigma\\mu}\\right)^{1/{\\sigma}}$$\nwith mean $0<\\mu<\\infty$ and dispersion $0<\\sigma<\\infty$, which correspond to numpy's negative binomial parameters $n$ and $p$ via $n=1/\\sigma$ and $p=1/(1+\\mu\\sigma)$.",
"_____no_output_____"
]
],
[
[
"#Generate some data from the Negative Binomial distribution.\nn=30\nX=np.linspace(0,1,n)[:,None]\nfor _ in range(5):\n X=np.concatenate((X,np.linspace(0,1,n)[:,None]),axis=0)\nf1= lambda x: 1/np.exp(2) if x<0.5 else np.exp(2) #True mean function\nf2= lambda x: np.exp(6*x**2-3) #True dispersion function\nY=np.array([np.random.negative_binomial(1/f2(x),1/(1+f1(x)*f2(x))) for x in X]).reshape(-1,1)\nXt=np.linspace(0,1.,200)[:,None]\nYt=np.array([f1(x) for x in Xt]).flatten()\nplt.plot(Xt,Yt)\nplt.scatter(X,Y,color='r')",
"_____no_output_____"
],
[
"#Train a 2-layered DGP (one GP in the first layer and two in the second corresponding to the mean and dispersion parameters) + NegBin model\nlayer1=[kernel(length=np.array([0.5]),name='matern2.5')]\nlayer2=[kernel(length=np.array([0.02]),name='matern2.5',scale_est=1,connect=np.arange(1)),\nkernel(length=np.array([0.02]),name='matern2.5',scale_est=1,connect=np.arange(1))]\nlayer3=[NegBin()]\nall_layer=combine(layer1,layer2,layer3)\nm=dgp(X,[Y],all_layer)\nm.train(N=500)",
"Iteration 500: Layer 3: 100%|██████████| 500/500 [01:10<00:00, 7.13it/s]\n"
],
[
"#Visualize the results\nfinal_layer_obj=m.estimate()\nemu=emulator(final_layer_obj)\nmu,var=emu.predict(Xt, method='mean_var',full_layer=True) #Make mean-variance prediction\nsamp=emu.predict(Xt, method='sampling') #Draw some samples to obtain the quantiles of the overall model\nquant=np.quantile(np.squeeze(samp), [0.05,0.5,0.95],axis=1) #Compute sample-based quantiles\nfig, (ax1, ax2, ax3) = plt.subplots(1,3, figsize=(15,4))\nax1.set_title('Predicted and True NegBin Mean')\nax1.plot(Xt,Yt,color='black')\nax1.plot(Xt,mu[-1],'--',color='red',alpha=0.8,lw=3)\nax1.plot(Xt,quant[0,:],'--',color='b',lw=1)\nax1.plot(Xt,quant[1,:],'--',color='b',lw=1)\nax1.plot(Xt,quant[2,:],'--',color='b',lw=1)\nmu_gp, var_gp=mu[-2][:,0], var[-2][:,0]\ns=np.sqrt(var_gp)\nu,l =mu_gp+2*s, mu_gp-2*s\nax2.set_title('Predicted and True logged NegBin Mean')\nax2.plot(Xt,mu_gp,color='r',alpha=1,lw=1)\nax2.plot(Xt,u,'--',color='g',lw=1)\nax2.plot(Xt,l,'--',color='g',lw=1)\nax2.plot(Xt,np.log(Yt),color='black',lw=1)\nmu_gp, var_gp=mu[-2][:,1], var[-2][:,1]\ns=np.sqrt(var_gp)\nu,l =mu_gp+2*s, mu_gp-2*s\nax3.set_title('Predicted and True logged NegBin Dispersion')\nax3.plot(Xt,mu_gp,color='r',alpha=1,lw=1)\nax3.plot(Xt,u,'--',color='g',lw=1)\nax3.plot(Xt,l,'--',color='g',lw=1)\nax3.plot(Xt,np.array([np.log(f2(x)) for x in Xt]).reshape(-1,1),color='black',lw=1)",
"_____no_output_____"
]
]
]
| [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
]
| [
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
]
|
cb5ccfb36e235499960d4d22c49fd97b30eb5b8a | 39,449 | ipynb | Jupyter Notebook | Classification Experiments 01.ipynb | abishek/notebooks | 95b4df809b50e96610a0cf22e748d463465359c1 | [
"MIT"
]
| null | null | null | Classification Experiments 01.ipynb | abishek/notebooks | 95b4df809b50e96610a0cf22e748d463465359c1 | [
"MIT"
]
| null | null | null | Classification Experiments 01.ipynb | abishek/notebooks | 95b4df809b50e96610a0cf22e748d463465359c1 | [
"MIT"
]
| null | null | null | 38.449318 | 400 | 0.421278 | [
[
[
"## Sentiment Analysis - Tweets\n\nI have a dataset downloaded with some tweets from analytics vidhya. I'll be implementing my own sentiment analysis trainer using this dataset and a bunch of tools that I learnt recently.",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport spacy\nimport numpy as np\n\nnlp = spacy.load('en_core_web_md')",
"_____no_output_____"
],
[
"dataset = 'datasets/tweets.csv'\ndataframe = pd.read_csv(dataset)\ndataframe.head()",
"_____no_output_____"
]
],
[
[
"Let's just use spacy to tokenize, remove stop words and generate vectors for the rest",
"_____no_output_____"
]
],
[
[
"def tokenize(text):\n \n doc = nlp(text)\n tokens = []\n for token in doc:\n if token.is_stop:\n continue\n if token.is_punct:\n continue\n if token.is_digit:\n continue\n if token.is_space:\n continue\n if token.is_oov:\n continue\n tokens.append(token)\n if len(tokens) == 0:\n return None\n return tokens\n\ndataframe[\"tokens\"] = dataframe[\"text\"].apply(tokenize)\ndataframe[\"tokens\"]",
"_____no_output_____"
],
[
"dataframe = dataframe[dataframe[\"tokens\"].notna()]\ndataframe",
"_____no_output_____"
],
[
"from sklearn.preprocessing import LabelEncoder\ntarget = LabelEncoder().fit_transform(dataframe[\"airline_sentiment\"])\ntarget.shape",
"_____no_output_____"
]
],
[
[
"## Spacy Vectors\n\nI am going to try two approaches to generating vectors. The first is a lazy approach. I'll just assume the tweet is a valid english sentence (which it certainly is not) and generate a vector using spacy. The second is where I will clean up the tweet and take the mean of the vectors for each remnant token.",
"_____no_output_____"
]
],
[
[
"def vectorise(text):\n doc = nlp(text)\n return doc.vector\n\ndataframe[\"vectors\"] = dataframe[\"text\"].apply(vectorise)",
"_____no_output_____"
],
[
"def mean_vector_for_tokens(list_of_tokens):\n vectors = []\n for token in list_of_tokens:\n vectors.append(token.vector)\n if len(vectors) == 0:\n return None\n mv = np.mean(vectors, axis=0)\n return mv\n\ndataframe[\"mv\"] = dataframe[\"tokens\"].apply(mean_vector_for_tokens)\n",
"_____no_output_____"
],
[
"train_set = dataframe[\"mv\"].apply(pd.Series)\ntrain_set.shape",
"_____no_output_____"
],
[
"train_set_2 = dataframe[\"vectors\"].apply(pd.Series)\ntrain_set_2.shape",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split\n\nx_train, x_valid, y_train, y_valid = train_test_split(train_set, target, random_state=20, stratify=target)\nprint(x_train.shape, y_train.shape)\nprint(x_valid.shape, y_valid.shape)\n\nx_train2, x_valid2, y_train2, y_valid2 = train_test_split(train_set_2, target, random_state=20, stratify=target)\nprint(x_train2.shape, y_train2.shape)\nprint(x_valid2.shape, y_valid2.shape)",
"(10914, 300) (10914,)\n(3638, 300) (3638,)\n(10914, 300) (10914,)\n(3638, 300) (3638,)\n"
]
],
[
[
"## Classifier Approaches\n\nI am going to try three different classifier models with the above two vectors and see how they perform.\n1. Logistic Regression\n2. Decision Tree Classifier\n3. Simple SVM Classifier\n",
"_____no_output_____"
]
],
[
[
"from sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score\n\nlgmodel1 = LogisticRegression(max_iter=1000)\nlgmodel1.fit(x_train, y_train)\n\nlgmodel2 = LogisticRegression(max_iter=1000)\nlgmodel2.fit(x_train2, y_train2)\n\npredictions = {\n \"train1\": lgmodel1.predict(x_train),\n \"valid1\": lgmodel1.predict(x_valid),\n \"train2\": lgmodel2.predict(x_train2),\n \"valid2\": lgmodel2.predict(x_valid2),\n}\n\naccuracy_lg = {\n \"train1\": accuracy_score(y_train, predictions[\"train1\"]),\n \"valid1\": accuracy_score(y_valid, predictions[\"valid1\"]),\n \"train2\": accuracy_score(y_train2, predictions[\"train2\"]),\n \"valid2\": accuracy_score(y_valid2, predictions[\"valid2\"])\n}\n\naccuracy_lg",
"_____no_output_____"
],
[
"from sklearn.tree import DecisionTreeClassifier\n\ndtcmodel1 = DecisionTreeClassifier()\ndtcmodel1.fit(x_train, y_train)\n\ndtcmodel2 = DecisionTreeClassifier()\ndtcmodel2.fit(x_train2, y_train2)\n\n\npredictions = {\n \"train1\": dtcmodel1.predict(x_train),\n \"valid1\": dtcmodel1.predict(x_valid),\n \"train2\": dtcmodel2.predict(x_train2),\n \"valid2\": dtcmodel2.predict(x_valid2),\n}\n\naccuracy_dtc = {\n \"train1\": accuracy_score(y_train, predictions[\"train1\"]),\n \"valid1\": accuracy_score(y_valid, predictions[\"valid1\"]),\n \"train2\": accuracy_score(y_train2, predictions[\"train2\"]),\n \"valid2\": accuracy_score(y_valid2, predictions[\"valid2\"])\n}\n\naccuracy_dtc",
"_____no_output_____"
],
[
"from sklearn import svm\n\nsvcmodel1 = svm.SVC()\nsvcmodel1.fit(x_train, y_train)\n\nsvcmodel2 = svm.SVC()\nsvcmodel2.fit(x_train2, y_train2)\n\npredictions = {\n \"train1\": svcmodel1.predict(x_train),\n \"valid1\": svcmodel1.predict(x_valid),\n \"train2\": svcmodel2.predict(x_train2),\n \"valid2\": svcmodel2.predict(x_valid2),\n}\n\naccuracy_svc = {\n \"train1\": accuracy_score(y_train, predictions[\"train1\"]),\n \"valid1\": accuracy_score(y_valid, predictions[\"valid1\"]),\n \"train2\": accuracy_score(y_train2, predictions[\"train2\"]),\n \"valid2\": accuracy_score(y_valid2, predictions[\"valid2\"])\n}\n\naccuracy_svc",
"_____no_output_____"
]
],
[
[
"## Results\n\nFrom the above runs, we see that the best case performance is only about 80% accurate. Decision Tree seems to overfit based on how well it performs on the training data. On the other hand, I don't really know if I need to pass other parameters to improve its performance at this time. I'll park that for later.\n\nWe know that we have taken an extremely simple approach here. The vector generation is actually in vain. It removes quite a bit of information from the tweet text itself and doesn't take the meta data into account. But before exploring meta data, I am going to repeat this with a simple Tf-IDf vectoriser and then again with Word2Vec to see how they perform given just the above information.\n\n### Summary of the experiment so far\n\n\nApproach |Logistic Regression | Decision Tree | SVM \n----------------|-------|-------|-----------------------\nTweet as Vector | 76.5% | 63.8% | 77.9% \nTokens Vector | 79.7% | 63.9% | 80%\n",
"_____no_output_____"
]
]
]
| [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
]
| [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
]
]
|
cb5cd9a5670e0992389cdd505ba9f9681afdda99 | 57,053 | ipynb | Jupyter Notebook | Notebooks/02_backprop_full_colab.ipynb | lasofivec/dataflowr | 68697f57968c4b8bc2669375f257a55057125f96 | [
"Apache-2.0"
]
| null | null | null | Notebooks/02_backprop_full_colab.ipynb | lasofivec/dataflowr | 68697f57968c4b8bc2669375f257a55057125f96 | [
"Apache-2.0"
]
| null | null | null | Notebooks/02_backprop_full_colab.ipynb | lasofivec/dataflowr | 68697f57968c4b8bc2669375f257a55057125f96 | [
"Apache-2.0"
]
| null | null | null | 116.672802 | 12,862 | 0.828493 | [
[
[
"<a href=\"https://colab.research.google.com/github/mlelarge/dataflowr/blob/master/Notebooks/02_backprop_full_colab.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Simple implementation of backprop\n\nHere we implement a simple backpropagation algorithm with `numpy` for the following problem:\n\nWe generate points $(x_i,y_i)$ where $y_i= \\exp(w^*x_i+b^*)$, i.e $y^*_i$ is obtained by applying a deterministic function to $x_i$ with parameters $w^*$ and $b^*$. Our goal is to recover the parameters $w^*$ and $b^*$ from the observations $(x_i,y_i)$.\n\nTo do this, we use SGD to minimize $\\sum_i(y^i - \\exp(w x_i+b))^2$ with respect to $w$ and $b$.\n",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"w, b = 0.5, 2\nxx = np.arange(0,1,.01)\nyy = np.exp(w*xx+b)",
"_____no_output_____"
],
[
"plt.plot(yy)",
"_____no_output_____"
]
],
[
[
"Following what we just saw in the course, you need to implement each of the basic operations: `(.*w), (.+b), exp(.)` with a forward method, a backward method and a step method.",
"_____no_output_____"
]
],
[
[
"class add_bias(object):\n def __init__(self,b):\n # initialize with a bias b\n self.b = b\n \n def forward(self, x):\n # return the result of adding the bias\n return x+self.b\n \n def backward(self,grad):\n # save the gradient (to update the bias in the step method) and return the gradient backward\n self.grad = grad\n return self.grad\n \n def step(self, learning_rate):\n # update the bias\n self.b -= learning_rate*self.grad\n \nclass multiplication_weight(object):\n def __init__(self, w):\n # initialize with a weight w\n self.w = w\n \n def forward(self, x):\n # return the result of multiplying by weight\n self.saved_x = x\n return self.w*x\n \n def backward(self,grad):\n # save the gradient and return the gradient backward\n self.grad = self.saved_x*grad\n return self.grad\n \n def step(self, learning_rate):\n # update the weight\n self.w -= learning_rate*self.grad\n\nclass my_exp(object):\n # no parameter\n def forward(self, x):\n # return exp(x)\n self.saved_exp = np.exp(x)\n return np.exp(x)\n \n def backward(self,grad):\n # return the gradient backward\n return self.saved_exp*grad\n \n def step(self, learning_rate):\n # any parameter to update?\n pass",
"_____no_output_____"
]
],
[
[
"Now, you will need to compose sequentially these operations and here you need to code a class composing operations. This class will have a forward, a backward and a step method and also a compute_loss method.",
"_____no_output_____"
]
],
[
[
"class my_composition(object):\n def __init__(self, layers):\n # initialize with all the operations (called layers here!) in the right order...\n self.layers = layers\n \n def forward(self, x):\n # apply the forward method of each layer\n for layer in self.layers:\n x = layer.forward(x)\n return x\n \n def compute_loss(self,y, y_est):\n # use the L2 loss\n # return the loss and save the gradient of the loss\n self.loss_grad = 2*(y-y_est)\n return (y-y_est)**2\n \n def backward(self):\n # apply backprop sequentially, starting from the gradient of the loss\n current_grad = self.loss_grad\n for layer in reversed(self.layers):\n current_grad = layer.backward(current_grad)\n \n def step(self, learning_rate):\n # apply the step method of each layer\n for layer in self.layers:\n layer.step(learning_rate)",
"_____no_output_____"
]
],
[
[
"Now you need to code the 'training' loop. Keep track of the loss, weight and bias computed at each epoch.",
"_____no_output_____"
]
],
[
[
"my_fit = my_composition([multiplication_weight(1),add_bias(1), my_exp()])\nlearning_rate = 1e-4\nlosses =[]\nws = []\nbs = []\nfor i in range(5000):\n # take a random indice\n j = np.random.randint(1, len(xx))\n # you can compare with\n #j = i % len(xx)\n # compute the estimated value of y with the current values of the parameters\n y_est = my_fit.forward(xx[j])\n # compute the loss and save it\n loss = my_fit.compute_loss(y_est,yy[j])\n losses.append(loss)\n # update the parameters and save them\n my_fit.backward()\n my_fit.step(learning_rate)\n ws.append(my_fit.layers[0].w)\n bs.append(my_fit.layers[1].b)",
"_____no_output_____"
],
[
"my_fit.layers[0].w",
"_____no_output_____"
],
[
"my_fit.layers[1].b",
"_____no_output_____"
],
[
"plt.plot(losses)",
"_____no_output_____"
],
[
"plt.plot(bs)",
"_____no_output_____"
],
[
"plt.plot(ws)",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
]
| [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
]
| [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
]
|
cb5cec6f73db60428711ea9bce6448f09083ee9b | 21,315 | ipynb | Jupyter Notebook | scripts/2-scraping-javascript-selenium/5-construyendo-funciones/construyendo-funciones.ipynb | OscarPalominoC/CursoWebScrapingExtraccionDatosWeb | d1664f3f4336fac57340a36479c977fd5aee2777 | [
"MIT"
]
| null | null | null | scripts/2-scraping-javascript-selenium/5-construyendo-funciones/construyendo-funciones.ipynb | OscarPalominoC/CursoWebScrapingExtraccionDatosWeb | d1664f3f4336fac57340a36479c977fd5aee2777 | [
"MIT"
]
| null | null | null | scripts/2-scraping-javascript-selenium/5-construyendo-funciones/construyendo-funciones.ipynb | OscarPalominoC/CursoWebScrapingExtraccionDatosWeb | d1664f3f4336fac57340a36479c977fd5aee2777 | [
"MIT"
]
| null | null | null | 31.071429 | 1,671 | 0.577574 | [
[
[
"# Sitios dinámicos y Selenium",
"_____no_output_____"
]
],
[
[
"import requests\nfrom bs4 import BeautifulSoup",
"_____no_output_____"
],
[
"url = 'https://www.latam.com/es_co/apps/personas/booking?fecha1_dia=13&fecha1_anomes=2020-10&auAvailability=1&ida_vuelta=ida&vuelos_origen=Bogot%C3%A1&from_city1=BOG&vuelos_destino=Miami&to_city1=BUE&flex=1&vuelos_fecha_salida_ddmmaaaa=06/09/2020&cabina=Y&nadults=1&nchildren=0&ninfants=0&cod_promo=&stopover_outbound_days=0&stopover_inbound_days=0&application=#/'",
"_____no_output_____"
],
[
"r = requests.get(url)",
"_____no_output_____"
],
[
"r.status_code",
"_____no_output_____"
],
[
"s = BeautifulSoup(r.text, 'lxml')\nprint(s.prettify())",
"<html>\n <head>\n <title>\n Access Denied\n </title>\n </head>\n <body>\n <h1>\n Access Denied\n </h1>\n You don't have permission to access \"http://www.latam.com/es_co/apps/personas/booking?\" on this server.\n <p>\n Reference #18.9c03f8be.1600134096.4c2fd9a\n </p>\n </body>\n</html>\n\n"
]
],
[
[
"Vemos que la respuesta de la página no contiene la información que necesitamos, ya que la misma aparece después de ejecutar código JS que está en la respuesta.",
"_____no_output_____"
],
[
"# SELENIUM",
"_____no_output_____"
],
[
"Selenium es una herramienta que nos permitirá controlar un navegador y podremos utilizar las funcionalidades del motor de JS para cargar el contenido que no viene en el HTML de la página. Para esto necesitamos el módulo `webdriver`.",
"_____no_output_____"
]
],
[
[
"from selenium import webdriver",
"_____no_output_____"
]
],
[
[
"## Paso 1: Instanciar un **driver** del navegador",
"_____no_output_____"
]
],
[
[
"# Opciones de navegación\noptions = webdriver.ChromeOptions()\noptions.add_argument('--incognito')\ndriver = webdriver.Chrome(executable_path='../chrome-driver/chromedriver', options=options)",
"_____no_output_____"
],
[
"driver",
"_____no_output_____"
]
],
[
[
"## Paso 2: Hacer que el navegador cargue la página web.",
"_____no_output_____"
]
],
[
[
"driver.get(url)",
"_____no_output_____"
]
],
[
[
"## Paso 3: Extraer la información de la página.",
"_____no_output_____"
]
],
[
[
"vuelos = driver.find_elements_by_xpath('//li[@class=\"flight\"]')\nvuelos",
"_____no_output_____"
],
[
"vuelo = vuelos[0]\nvuelo",
"_____no_output_____"
],
[
"# Hora de salida\nvuelo.find_element_by_xpath('.//div[@class=\"departure\"]/time').get_attribute('datetime')",
"_____no_output_____"
],
[
"# Hora de llegada\nvuelo.find_element_by_xpath('.//div[@class=\"arrival\"]/time').get_attribute('datetime')",
"_____no_output_____"
],
[
"# Duración del vuelo\nvuelo.find_element_by_xpath('.//span[@class=\"duration\"]/time').text",
"_____no_output_____"
],
[
"# Como lo hizo el profesor\nvuelo.find_element_by_xpath('.//span[@class=\"duration\"]/time').get_attribute('datetime')",
"_____no_output_____"
]
],
[
[
"### Interactuando con Elementos",
"_____no_output_____"
]
],
[
[
"boton_escalas = vuelo.find_element_by_xpath('.//div[@class=\"flight-summary-stops-description\"]/button')",
"_____no_output_____"
],
[
"boton_escalas",
"_____no_output_____"
],
[
"# Simulamos el clic sobre el botón\nboton_escalas.click()",
"_____no_output_____"
],
[
"# Seleccionamos los segmentos\nsegmentos = vuelo.find_elements_by_xpath('//div[@class=\"sc-hZSUBg gfeULV\"]/div[@class=\"sc-cLQEGU hyoued\"]')\nsegmentos",
"_____no_output_____"
],
[
"escalas = len(segmentos) - 1\nescalas",
"_____no_output_____"
]
],
[
[
"### Scrapeando escalas y tarifas",
"_____no_output_____"
]
],
[
[
"segmento = segmentos[0]\nsegmento",
"_____no_output_____"
],
[
"# Obteniendo la ciudad de llegada y salida\nciudades = segmento.find_elements_by_xpath('.//div[@class=\"sc-bwCtUz iybVbT\"]/abbr[@class=\"sc-hrWEMg hlCkST\"]')\nprint(f'Ciudad de salida: {ciudades[0].text}')\nprint(f'Ciudad de escala: {ciudades[1].text}')",
"Ciudad de salida: BOG\nCiudad de escala: SCL\n"
],
[
"# Obteniendo la hora de llegada a la escala y salida de la escala\nhoras = segmento.find_elements_by_xpath('.//div[@class=\"sc-bwCtUz iybVbT\"]/time[@class=\"sc-RefOD libzvk\"]')\nprint(f'Hora de salida ciudad inicial: {horas[0].text}')\nprint(f'Hora de salida ciudad escala: {horas[1].text}')",
"Hora de salida ciudad inicial: 23:10\nHora de salida ciudad escala: 06:55+1\n"
],
[
"# Obteniendo nombre del Aeropuerto de salida y escala\naeropuertos = segmento.find_elements_by_xpath('.//span[@class=\"sc-eTuwsz eumCTU\"]/span[@class=\"sc-hXRMBi gVvErD\"]')\nprint(f'Aeropuerto de salida: {aeropuertos[0].text}')\nprint(f'Aeropuerto de escala: {aeropuertos[1].text}')",
"Aeropuerto de salida: El Dorado Intl.\nAeropuerto de escala: A. Merino Benítez Intl.\n"
],
[
"# Cerrando el modal\ndriver.find_element_by_xpath('//div[@class=\"modal-content sc-iwsKbI eHVGAN\"]//button[@class=\"close\"]').click()",
"_____no_output_____"
],
[
"# Obteniendo las tarifas\nvuelo.click()\ncontenido = driver.find_element_by_xpath('//div[@class=\"ReactCollapse--content\"]')\ntarifas = contenido.find_elements_by_xpath('.//table[@class=\"fare-options-table\"]/tfoot/tr/td[contains(@class, \"fare-\")]')\nprecios = []\nfor tarifa in tarifas:\n nombre = tarifa.find_element_by_xpath('.//label').get_attribute('for')\n moneda = tarifa.find_element_by_xpath('.//label/span[@class=\"price\"]/span[@class=\"currency-symbol\"]').text\n valor = tarifa.find_element_by_xpath('.//label/span[@class=\"price\"]/span[@class=\"value\"]').text\n dict_tarifa = {nombre:{'moneda':moneda, 'valor':valor}}\n precios.append(dict_tarifa)\nprecios",
"_____no_output_____"
]
],
[
[
"### Construyendo funciones",
"_____no_output_____"
]
],
[
[
"def obtener_precios(vuelo):\n \"\"\"\n Función que retorna un diccionario con las distintas tarifas\n \"\"\"\n tarifas = contenido.find_elements_by_xpath('.//table[@class=\"fare-options-table\"]/tfoot/tr/td[contains(@class, \"fare-\")]')\n precios = []\n for tarifa in tarifas:\n nombre = tarifa.find_element_by_xpath('.//label').get_attribute('for')\n moneda = tarifa.find_element_by_xpath('.//label/span[@class=\"price\"]/span[@class=\"currency-symbol\"]').text\n valor = tarifa.find_element_by_xpath('.//label/span[@class=\"price\"]/span[@class=\"value\"]').text\n dict_tarifa = {nombre:{'moneda':moneda, 'valor':valor}}\n precios.append(dict_tarifa)\n return precios",
"_____no_output_____"
],
[
"def obtener_datos_escalas(vuelo):\n \"\"\"\n Función que retorna una lista de diccionarios con la información de las escalas de cada vuelo\n \"\"\"\n # Abriendo el modal\n vuelo.find_element_by_xpath('//div[@class=\"flight\"]//button[@class=\"sc-bdVaJa fuucJY\"]').click()\n \n segmentos = vuelo.find_elements_by_xpath('//div[@class=\"sc-hZSUBg gfeULV\"]/div[@class=\"sc-cLQEGU hyoued\"]')\n info_escalas[]\n for segmento in segmentos:\n # Obteniendo la ciudad de llegada y salida\n ciudades = segmento.find_elements_by_xpath('.//div[@class=\"sc-bwCtUz iybVbT\"]/abbr[@class=\"sc-hrWEMg hlCkST\"]')\n origen = ciudades[0].text\n escala = ciudades[1].text\n \n \n #Cerrando el modal\n driver.find_element_by_xpath('//div[@class=\"modal-component\"]//button[@class=\"close\"]').click()\n return info_escalas",
"_____no_output_____"
],
[
"segmentos = vuelo.find_elements_by_xpath('//div[@class=\"sc-hZSUBg gfeULV\"]/div[@class=\"sc-cLQEGU hyoued\"]')\n\nfor segmento in segmentos:\n # Obteniendo la ciudad de llegada y salida\n ciudades = segmento.find_elements_by_xpath('.//div[@class=\"sc-bwCtUz iybVbT\"]/abbr[@class=\"sc-hrWEMg hlCkST\"]')\nciudades[1].text",
"_____no_output_____"
]
],
[
[
"## Paso 4: Cerrar el navegador.",
"_____no_output_____"
]
],
[
[
"driver.close()",
"_____no_output_____"
]
]
]
| [
"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",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
]
|
cb5d094af158777b46ce59750db7848f909eb4f1 | 69,639 | ipynb | Jupyter Notebook | intro-to-tensorflow/intro_to_tensorflow.ipynb | anoff/nd101 | d06773d1eab54c88220340faf273bdb727a61bc6 | [
"MIT"
]
| 3 | 2018-04-23T22:18:30.000Z | 2020-02-13T19:55:02.000Z | intro-to-tensorflow/intro_to_tensorflow.ipynb | anoff/nd101 | d06773d1eab54c88220340faf273bdb727a61bc6 | [
"MIT"
]
| null | null | null | intro-to-tensorflow/intro_to_tensorflow.ipynb | anoff/nd101 | d06773d1eab54c88220340faf273bdb727a61bc6 | [
"MIT"
]
| 3 | 2017-08-14T16:18:12.000Z | 2019-02-17T12:42:06.000Z | 87.596226 | 41,120 | 0.797714 | [
[
[
"<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 different fonts.\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:37<00:00, 5659.30files/s]\n100%|██████████| 10001/10001 [00:01<00:00, 5957.25files/s]\n"
]
],
[
[
"<img src=\"image/Mean_Variance_Image.png\" style=\"height: 75%;width: 75%; position: relative; right: 5%\">\n## Problem 1\nThe first problem involves normalizing the features for your training and test data.\n\nImplement Min-Max scaling in the `normalize_grayscale()` 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/deep-learning/blob/master/intro-to-tensorflow/intro_to_tensorflow_solution.ipynb).*",
"_____no_output_____"
]
],
[
[
"# 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 min_val = 0.1\n max_val = 0.9\n # normalize to 0..1\n x0 = (image_data - np.min(image_data)) / (np.max(image_data) - np.min(image_data))\n \n return min_val + x0 * (max_val - min_val)\n\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.')",
"Saving data to pickle file...\nData 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\nprint('Data and modules loaded.')",
"/Users/anoff/anaconda3/envs/dlnd-tf-lab/lib/python3.5/site-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.\n warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')\n/Users/anoff/anaconda3/envs/dlnd-tf-lab/lib/python3.5/site-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.\n warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')\n"
]
],
[
[
"\n## Problem 2\n\nNow it's time to build a simple neural network using TensorFlow. Here, your network will be just an input layer and an output layer.\n\n<img src=\"image/network_diagram.png\" style=\"height: 40%;width: 40%; position: relative; right: 10%\">\n\nFor the input here the images have been flattened into a vector of $28 \\times 28 = 784$ features. Then, we're trying to predict the image digit so there are 10 output units, one for each label. Of course, feel free to add hidden layers if you want, but this notebook is built to guide you through a single layer network. \n\nFor the neural network to train on your data, you need the following <a href=\"https://www.tensorflow.org/resources/dims_types.html#data-types\">float32</a> tensors:\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/constant_op.html#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/constant_op.html#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](intro_to_tensorflow_solution.ipynb).*",
"_____no_output_____"
]
],
[
[
"# All the pixels in the image (28 * 28 = 784)\nfeatures_count = 784\n# All the labels\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], seed=23))\nbiases = tf.Variable(tf.zeros([10]))\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), reduction_indices=1)\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_Image.png\" style=\"height: 70%;width: 70%\">\n## Problem 3\nBelow are 2 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* **Learning Rate:**\n * 0.8 (0.09)\n * 0.5 (0.78)\n * 0.1 (0.74)\n * 0.05 (0.72)\n * 0.01 (0.58)\n\nConfiguration 2\n* **Epochs:**\n * 1 (0.76)\n * 2 (0.77)\n * 3 (0.78)\n * 4 (0.78)\n * 5 (0.79)\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](intro_to_tensorflow_solution.ipynb).*",
"_____no_output_____"
]
],
[
[
"# Change if you have memory restrictions\nbatch_size = 128\n\n# TODO: Find the best parameters for each configuration\nepochs = 5\nlearning_rate = .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/5: 100%|██████████| 1114/1114 [00:11<00:00, 95.83batches/s]\nEpoch 2/5: 100%|██████████| 1114/1114 [00:11<00:00, 95.85batches/s]\nEpoch 3/5: 100%|██████████| 1114/1114 [00:11<00:00, 95.22batches/s]\nEpoch 4/5: 100%|██████████| 1114/1114 [00:11<00:00, 93.57batches/s]\nEpoch 5/5: 100%|██████████| 1114/1114 [00:12<00:00, 91.81batches/s]\n"
]
],
[
[
"## Test\nYou'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_____"
]
],
[
[
"### 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/5: 100%|██████████| 1114/1114 [00:00<00:00, 1325.60batches/s]\nEpoch 2/5: 100%|██████████| 1114/1114 [00:00<00:00, 1339.85batches/s]"
]
],
[
[
"# Multiple layers\nGood job! You built a one layer TensorFlow network! However, you might 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"
]
]
|
cb5d0e1ad36da5c6e97bc9b561f8d49cbb510485 | 102,244 | ipynb | Jupyter Notebook | Assignment 3/From Scratch Implementation/_CAP5625_Assignment3_scratch_LogisticRidgeRegresion.ipynb | shaungt1/CAP-5625-Computational-Foundations-of-Artificial-Intelligence | 2250e68e40a60ef20fbb1b2a59a7be858eeed59e | [
"MIT"
]
| null | null | null | Assignment 3/From Scratch Implementation/_CAP5625_Assignment3_scratch_LogisticRidgeRegresion.ipynb | shaungt1/CAP-5625-Computational-Foundations-of-Artificial-Intelligence | 2250e68e40a60ef20fbb1b2a59a7be858eeed59e | [
"MIT"
]
| null | null | null | Assignment 3/From Scratch Implementation/_CAP5625_Assignment3_scratch_LogisticRidgeRegresion.ipynb | shaungt1/CAP-5625-Computational-Foundations-of-Artificial-Intelligence | 2250e68e40a60ef20fbb1b2a59a7be858eeed59e | [
"MIT"
]
| null | null | null | 94.934076 | 21,914 | 0.821349 | [
[
[
"# **Assignment 3 (From Scratch)**",
"_____no_output_____"
],
[
"## **Penalized Logistic Ridge Regression CV with Batch Gradient Decent**",
"_____no_output_____"
],
[
"- **Programmers:**\n - Shaun Pritchard\n - Ismael A Lopez\n- **Date:** 11-15-2021\n- **Assignment:** 3\n- **Prof:** M.DeGiorgio\n\n<hr>\n\n### **Overview: Assignment 3**\n\n- In this assignment you will still be analyzing human genetic data from 𝑁 = 183 training\nobservations (individuals) sampled across the world. The goal is to fit a model that can predict\n(classify) an individual’s ancestry from their genetic data that has been projected along 𝑝 = 10\ntop principal components (proportion of variance explained is 0.2416) that we use as features\nrather than the raw genetic data\n\n- Using ridge regression, fit a penalized (regularized) logistic (multinomial) regression with model parameters obtained by batch gradient descent. Based on K = 5 continental ancestries (African, European, East Asian, Oceanian, or Native American), predictions will be made. Ridge regression will permit parameter shrinkage (tuning parameter 𝜆 ≥ 0) to mitigate overfitting. In order to infer the bestfit model parameters on the training dataset, the tuning parameter will be selected using five-fold cross validation. After training, the model will be used to predict new test data points.\n\n",
"_____no_output_____"
],
[
"## **Imports**\n\n> Import libaries and data",
"_____no_output_____"
]
],
[
[
"#Math libs\nfrom math import sqrt\nfrom scipy import stats\nfrom numpy import median\nfrom decimal import *\nimport os\n# Data Science libs\nimport numpy as np\nimport pandas as pd\n# Graphics libs\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n%matplotlib inline\n#Timers\n# !pip install pytictoc\n# from pytictoc import TicToc",
"_____no_output_____"
],
[
"# Import training and test datasets\ntrain_df = pd.read_csv('TrainingData_N183_p10.csv')\ntest_df = pd.read_csv('TestData_N111_p10.csv')",
"_____no_output_____"
],
[
"# Validate traning data import correclty\ntrain_df.head(2)",
"_____no_output_____"
],
[
"# Validate testing data import correclty\ntest_df.head(2)",
"_____no_output_____"
]
],
[
[
"## **Data Pre-Proccessing**\n\n- Pre-proccess test and training datasets\n- Impute categorical variables in features\n- Validate correct output of test data",
"_____no_output_____"
]
],
[
[
"# recode the categories\ndata = train_df['Ancestry'].unique().tolist()\nnum_features = len(data)\ntrain_df['Ancestry2'] = train_df['Ancestry'].apply(lambda x: data.index(x))\n",
"_____no_output_____"
],
[
"# Validate training data set\ntrain_df.head(2)",
"_____no_output_____"
],
[
"# Shape trianing data\ntrain_df.shape",
"_____no_output_____"
]
],
[
[
"## **Seperate X Y Predictors and Responses**\n - Seperate predictors from responses\n - Validate correct output",
"_____no_output_____"
]
],
[
[
"# Seperate dependant categorical feature data for training and test data set for later use\nY_train_names = train_df['Ancestry'].tolist()\nY_test_names = test_df['Ancestry'].tolist()",
"_____no_output_____"
],
[
"# Separate training feature predictors from responses\nX_train = np.float32(train_df.to_numpy()[:, :-2])\nY_train = train_df['Ancestry2'].to_numpy()",
"_____no_output_____"
],
[
"# Separate test feature predictors from responses\nX_test = np.float32(test_df.to_numpy()[:, :-1])",
"_____no_output_____"
],
[
"X_train.shape",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"## **Set Global Vairibles**\n- λ = tunning parameters\n- α = learning rate\n- k = number of folds\n- n_itters = nu mber of itterations\n- X_p = predictor vlaues from training data\n- Y_p = response values from training data",
"_____no_output_____"
]
],
[
[
"# Set local variables\n\n# Tuning Parms\nλ = 10 ** np.arange(-4., 4.)\n\n# learning rate\nα = 1e-4\n\n# K-folds\nk = 5\n\n\n# Itterations\nn_iters = 10000 \n\n# Set n x m matrix predictor variable\nX_p = X_train\n\n# Set n vector response variable\nY_p = Y_train",
"_____no_output_____"
]
],
[
[
"## **Instantiate Data**\n- Handle logic and set variables needed for calculating ridge logistic regression\n- Handle logic and set variables for batch gradient descent\n- Handle logic and set variables for cross-validation",
"_____no_output_____"
]
],
[
[
"# Encode response variable from CV design matrix for cross vlaidation\ndef imputeResponse(response_vector, num_features):\n response_vector = np.int64(response_vector)\n X1 = response_vector.shape[0]\n response_mat = np.zeros([X1, num_features])\n response_mat[np.arange(X1), response_vector] = 1\n return response_mat",
"_____no_output_____"
],
[
"# Method to handle randomization of training data predictors and responses\ndef randomizeData(X_p, Y_p):\n data = np.concatenate((X_p, Y_p[:, None]), 1)\n np.random.shuffle(data)\n return data[:, :-1], data[:, -1]",
"_____no_output_____"
],
[
"# Randomize predictors and responses into new vairables\nx, y = randomizeData(X_p, Y_p)",
"_____no_output_____"
],
[
"# Set Global variable for samples and number of X = N X M features\nX1 = x.shape[0]\nX2 = x.shape[1] ",
"_____no_output_____"
],
[
"# Get number of training feature classes = 5\nnum_features = np.unique(y).size",
"_____no_output_____"
],
[
" # Call method imputation method on training response variables\n y = imputeResponse(y, num_features) ",
"_____no_output_____"
],
[
"# Store 5 K-fold cross validation results in symetric matrices\nCV = np.zeros([k, len(λ)])",
"_____no_output_____"
],
[
"# Number of validation sample index values based on k-folds \nval_samples = int(np.ceil(X1 / k)) \ntest_i = list(range(0, X1, val_samples))",
"_____no_output_____"
],
[
"# Create a 𝛽 zero matrix to store the trained predictors \n𝛽 = np.zeros([k, len(λ), X2 + 1, num_features])",
"_____no_output_____"
]
],
[
[
"## **Implement logic**\n- Main functions to handle logic within the preceding algorithms",
"_____no_output_____"
]
],
[
[
"# Standardize X coefficients\ndef standardize(x, mean_x, std_x):\n return (x - mean_x) / std_x ",
"_____no_output_____"
],
[
"# Concatenate ones column matrix with X coefficiants\ndef intercept(x):\n col = np.ones([x.shape[0], 1])\n return np.concatenate((col, x), 1)",
"_____no_output_____"
],
[
"# Predict standardize expotential X values from intercepts\ndef predict(x):\n x = standardize(x, mean_x, std_x)\n x = intercept(x)\n\n X_p = np.exp(np.matmul(x, 𝛽x))\n return X_p / np.sum(X_p, 1)[:, None]",
"_____no_output_____"
],
[
"# Splitting the data into k groups resampling method\ndef cv_folds(i_test):\n if i_test + val_samples <= X1:\n i_tests = np.arange(i_test, i_test + val_samples)\n else:\n i_tests = np.arange(i_test, X1)\n \n x_test = x[i_tests]\n x_train = np.delete(x, i_tests, axis = 0)\n\n \n y_test = y[i_tests]\n y_train = np.delete(y, i_tests, axis = 0)\n return x_train, x_test, y_train, y_test",
"_____no_output_____"
],
[
"# Calculate model CV score \ndef score(x, y, 𝛽x):\n # Compute exponent values of X coef and BGD unnormilized probality matrix\n U = np.exp(np.matmul(x, 𝛽x))\n # Calculate sum unnormilized probality / sum unnormilized matrix by 1\n P = U / np.sum(U, 1)[:, None]\n # Calulate to cost error score\n err = -(1 / x.shape[0]) * np.sum(np.sum(y * np.log10(P), 1))\n return err",
"_____no_output_____"
]
],
[
[
"## **Batch Gradient Descent**\n> Alorithm 1 used for this computation\n\n\n",
"_____no_output_____"
]
],
[
[
"\ndef BGD(x, y, 𝛽x, lamb):\n # Unormalized class probability matrix\n U = np.exp(np.dot(x, 𝛽x))\n # Normalized class probability matrix\n P = U / np.sum(U, 1)[:, None]\n # K intercept matrix\n Z = 𝛽x.copy()\n Z[1:] = 0\n # Update parameter matrix\n 𝛽x = 𝛽x + α * (np.matmul(np.transpose(x), y - P) - 2 * lamb * (𝛽x - Z))\n return 𝛽x",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"## **CV Ridge Penlized Logistic Regression**\n> - Compute ridge-penalized logistic regression with cross vlaidation\n- Performing a ridge-penalized logistic regression fit to training data\n{(𝑥1, 𝑦1), (𝑥2, 𝑦2), … , (𝑥𝑁, 𝑦𝑁)} is to minimize the cost function\n",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"# Compute ridge-penalized logistic regression with cross vlaidation\nfor i_lambda, lamb in enumerate(λ):\n for i_fold, i_test in zip(range(k), test_i):\n \n # Validates and trains the CV iteration based on the validation and training sets.\n x_train, x_test, y_train, y_test = cv_folds(i_test)\n\n # Standardize x and center y 5 K-fold trianing and test data\n mean_x, std_x = np.mean(x_train, 0), np.std(x_train, 0)\n \n # implement standardize X training and test sets\n x_train = standardize(x_train, mean_x, std_x)\n x_test = standardize(x_test, mean_x, std_x)\n \n # Add training and test intercept column to the design matrix\n x_train = intercept(x_train)\n x_test = intercept(x_test)\n\n # initialize Beta coef for lambdas and fold\n 𝛽x = np.zeros([X2 + 1, num_features])\n \n # Loop through beta and lambdas with batch gradient decent\n for iter in range(n_iters):\n 𝛽x = BGD(x_train, y_train, 𝛽x, lamb)\n\n # Score CV cost error tp the model and store the values \n CV[i_fold, i_lambda] = score(x_test, y_test, 𝛽x)\n \n # Save the updated coefficient vectors 𝛽x\n 𝛽[i_fold, i_lambda] = 𝛽x",
"_____no_output_____"
]
],
[
[
"## **Deliverable 1**\n> Illustrate the effect of the tuning parameter on the inferred ridge regression\ncoefficients by generating five plots (one for each of the 𝐾 = 5 ancestry classes) of 10 lines\n(one for each of the 𝑝 = 10 features)",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"# Plot tuning parameter on the inferred ridge regression coefficients\n𝛽μ = np.mean(𝛽, 0)\nsns.set(rc = {'figure.figsize':(15,8)})\nfor i, c in enumerate(data):\n 𝛽μk = 𝛽μ[..., i]\n sns.set_theme(style=\"whitegrid\")\n sns.set_palette(\"mako\")\n for j in range(1, 1 + X2):\n sns.lineplot( x=λ, y=𝛽μk[:, j], palette='mako', label = 'PC{}'.format(j) )\n sns.set()\n plt.xscale('log')\n plt.legend(bbox_to_anchor=(1.09, 1), loc='upper left')\n plt.xlabel('Log Lambda')\n plt.ylabel('Coefficient Values')\n plt.suptitle('Inferred Ridge Regression Coefficient Tuning Parameters of' + ' ' + c + ' ' + 'Class')\n for l in range(i):\n # Output Deliverable 1\n plt.savefig(\"Assignment3_Deliverable1.{}.png\".format(l))\n plt.show()\n \n \n \n ",
"_____no_output_____"
]
],
[
[
"## **Deliverable 2**\n> Illustrate the effect of the tuning parameter on the cross validation error by generating a plot with the 𝑦-axis as CV(5) error, and the 𝑥-axis the corresponding log-scaled\ntuning parameter value log10(𝜆) that generated the particular CV(5) error.",
"_____no_output_____"
]
],
[
[
"# Compute tuning parameter on the cross validation error\nerr = np.std(CV, 0) / np.sqrt(CV.shape[0])\nsns.set(rc = {'figure.figsize':(15,8)})\nsns.set_theme(style=\"whitegrid\")\nsns.set_palette(\"icefire\")\nsns.pointplot(x=λ, y=np.mean(CV, 0),yerr = err)\nsns.set()\nplt.xlabel('log10(lambda)')\nplt.ylabel('CV(5) error')\nplt.xscale('log')\nplt.yscale('log')\nplt.suptitle('Effect of the uning parameter on the cross validation error log10(lambda)')\nplt.savefig(\"Assignment3_Deliverable2.png\")\nplt.show()\n",
"_____no_output_____"
]
],
[
[
"### **Retrain model with best lambda**",
"_____no_output_____"
]
],
[
[
"# Set array of indices into the best lambda\nbest_λ = λ[np.argmin(np.mean(CV, 0))]",
"_____no_output_____"
],
[
"# Set standaridzed variables\nmean_x, std_x = np.mean(x, 0), np.std(x, 0)",
"_____no_output_____"
],
[
"# Implement standarization of predictors and copy response variables\nx = standardize(x, mean_x, std_x)\nx = intercept(x)\ny = y.copy()",
"_____no_output_____"
],
[
"# Set zeros matrix to coef and retiran model on batch gradient decent\n𝛽x = np.zeros([X2 + 1, num_features])\nfor iter in range(n_iters):\n 𝛽x = BGD(x, y, 𝛽x, best_λ)",
"_____no_output_____"
]
],
[
[
"## **Deliverable 3**\n> Indicate the value of 𝜆 value that generated the smallest CV(5) error",
"_____no_output_____"
],
[
"**Optimal lambda**",
"_____no_output_____"
]
],
[
[
"# Plot lowest optimal lambda\npalette = sns.color_palette('mako')\nsns.set(rc = {'figure.figsize':(15,8)})\nsns.set_theme(style=\"whitegrid\")\nak = Decimal(best_λ)\nplt.plot(λ)\nsns.set_palette(\"icefire\")\nsns.countplot(data=λ)\nplt.xscale('log')\nplt.yscale('log')\nplt.xlabel('log10(lambda)')\nplt.ylabel('Best Lambda')\nplt.suptitle('Lowest optimal Lamda value:= log_1e{:.1f} = {}'.format(ak.log10(), best_λ))\nprint('Optimal lambda value:= {}'.format(best_λ))\nplt.savefig(\"Assignment3_Deliverable3-1.png\")",
"_____no_output_____"
]
],
[
[
"**Accuracy on training classifier**",
"_____no_output_____"
]
],
[
[
"\n#Implement Prediction function\nŷ_p = predict(X_train)\n# Return the maximum value along a given y axis\nŷ0 = np.argmax(ŷ_p, 1)\n# Return mean traning accuaracy \nμ = np.mean(ŷ0 == Y_train)\nsns.set(rc = {'figure.figsize':(15,8)})\nsns.set_theme(style=\"whitegrid\")\nplt.plot(ŷ0)\nsns.set_palette(\"icefire\")\nsns.boxplot(data=ŷ0 -μ**2)\nplt.xscale('log')\nplt.xlabel('log10(lambda)')\nplt.ylabel('Best Lambda')\nplt.suptitle('Classifier Training Accuracy:= {}'.format(μ))\nplt.savefig(\"Assignment3_Deliverable3-2.png\")\n# print('Classifier Training Accuracy: {}'.format(μ))",
"_____no_output_____"
]
],
[
[
"## **Retrain model on the entire dataset for optimal 𝜆**\n> - Given the optimal 𝜆, retrain your model on the entire dataset of 𝑁 = 183 observations to obtain an estimate of the (𝑝 + 1) × 𝐾 model parameter matrix as 𝐁̂ and make predictions of the probability for each of the 𝐾 = 5 classes for the 111 test individuals located in TestData_N111_p10.csv.\n- Add probability predictions to the test dataframe",
"_____no_output_____"
]
],
[
[
"# Create new test predicotr and response variables ŷ\nŷ_test = predict(X_test)\nY_class = np.argmax(ŷ_test, 1)",
"_____no_output_____"
],
[
"# Re-lable feature headers and add new class prediction index column\nnew_colNames = ['{}_Probability'.format(c_name) for c_name in data] + ['ClassPredInd']",
"_____no_output_____"
],
[
"# Implemnt index array of probabilities\ni_prob = np.concatenate((ŷ_test, Y_class[:, None]), 1)",
"_____no_output_____"
],
[
"# Create New dataframe for probality indeces\ndf2 = pd.DataFrame(i_prob, columns = new_colNames)",
"_____no_output_____"
],
[
"# Concat dependant Ancestory features to dataframe\ndep_preds = pd.concat([test_df['Ancestry'], df2], axis = 1)",
"_____no_output_____"
],
[
"# Add new \ndep_preds['ClassPredName'] = dep_preds['ClassPredInd'].apply(lambda x: data[int(x)])",
"_____no_output_____"
],
[
"# Validate Probability predictions dataframe\ndep_preds.head()",
"_____no_output_____"
],
[
"# Slice prediction and set new feature vector column variable\nprob_1 = dep_preds.loc[:, 'Ancestry':'NativeAmerican_Probability']",
"_____no_output_____"
],
[
"# Unpivot convert dataFrame to long format\nprob_2 = pd.melt(prob_1, id_vars = ['Ancestry'], var_name = 'Ancestry_Predictions', value_name = 'Probability')",
"_____no_output_____"
],
[
"# Test for true probability\nprob_2['Ancestry_Predictions'] = prob_2['Ancestry_Predictions'].apply(lambda x: x.split('Prob')[0])",
"_____no_output_____"
],
[
"# Validate dataframe\nprob_2.head(5)",
"_____no_output_____"
],
[
"# Validate dataframe features\nprint('Describe Columns:=', prob_2.columns, '\\n')\nprint('Data Index values:=', prob_2.index, '\\n')\nprint('Describe data:=', prob_2.describe(), '\\n')",
"_____no_output_____"
]
],
[
[
"## **Deliverable 4**\n> Given the optimal 𝜆, retrain your model on the entire dataset of 𝑁 = 183 observations to obtain an estimate of the (𝑝 + 1) × 𝐾 model parameter matrix as 𝐁̂ and make predictions of the probability for each of the 𝐾 = 5 classes for the 111 test individuals located in TestData_N111_p10.csv. \n\n",
"_____no_output_____"
]
],
[
[
"# Plot Probality prediction matrix\nsns.set(rc = {'figure.figsize':(15,8)})\nsns.set_theme(style=\"whitegrid\")\nfig, ax = plt.subplots()\nsns.barplot(data = prob_2[prob_2['Ancestry'] != 'Unknown'],color = 'r', x = 'Ancestry', y = 'Probability', hue = 'Ancestry_Predictions', palette = 'mako')\nplt.xlabel('Ancestory Classes')\nplt.ylabel('Probability')\nplt.suptitle('Probabilty of Ancestor classes')\nplt.savefig(\"Assignment3_Deliverable4.png\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"## **Deliverable 5**\n**How do the class label probabilities differ for the Mexican and African American samples when compared to the class label probabilities for the unknown samples?**\n\n> In comparison to the class label probabilities for the unknown samples, those with unknown ancestry show a probability close to or equal to one while the other classes show a probability close to zero or less than one. African American samples showed similar results. The model assigned high probabilities to the African ancestry class for each of these samples. However, both Native American and European ancestry contribute high probabilities to the Mexican population on average with Native American slightly higher than European. ",
"_____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"
]
| [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
]
|
cb5d180f1f99aafad35d9dba8674b522868363b8 | 698,197 | ipynb | Jupyter Notebook | alghoritms.ipynb | Sergey-Baranenkov/audio_recognition_system | 4472a76e495fe6a679ffbd4dd3706ce971540e79 | [
"Apache-2.0"
]
| null | null | null | alghoritms.ipynb | Sergey-Baranenkov/audio_recognition_system | 4472a76e495fe6a679ffbd4dd3706ce971540e79 | [
"Apache-2.0"
]
| null | null | null | alghoritms.ipynb | Sergey-Baranenkov/audio_recognition_system | 4472a76e495fe6a679ffbd4dd3706ce971540e79 | [
"Apache-2.0"
]
| null | null | null | 806.232102 | 61,443 | 0.956219 | [
[
[
"## Тестирование даунсемплинга, низкочастотных фильтров и параметров синусоидальных волн",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom matplotlib import pyplot as plt\nfrom pydub import AudioSegment\nfrom scipy.fft import rfft, rfftfreq, irfft",
"_____no_output_____"
],
[
"plt.rcParams[\"figure.figsize\"] = (20,5)",
"_____no_output_____"
],
[
"# Парсим pydub AudioSegment в numpy массив уровней квантизации. Массив может состоять из 1 стобца(канала) при моно звуке и из 2 столбцов(каналов) при стерео\ndef pydub_to_np(audio: AudioSegment) -> np.ndarray:\n return np.array(audio.get_array_of_samples(), dtype=np.float32).reshape((-1, audio.channels))",
"_____no_output_____"
],
[
"# Трансформирует стерео звук в моно, вычисляя среднее между левым и правым каналом. dtype = int чтобы округлить до нижнего уровня\ndef stereo_to_mono(stereo: np.ndarray) -> np.ndarray:\n return np.mean(stereo, axis = 1, dtype=int)",
"_____no_output_____"
],
[
"# Нормализирует массив уровней квантизации к [-1, 1] интервалам\ndef normalize_mono(mono_sound: np.ndarray, sample_width: int) -> np.ndarray:\n bitrate = 1 << (8 * sample_width - 1)\n return mono_sound / bitrate",
"_____no_output_____"
],
[
"# Денормализирует массив уровней квантизации обратно к исходному интервалу\ndef denormalize_mono(mono_sound: np.ndarray, sample_width: int) -> np.ndarray:\n bitrate = 1 << (8 * sample_width - 1)\n res = mono_sound * bitrate\n return res.astype('int')",
"_____no_output_____"
],
[
"amplitude = 1\ndiscr = 1024\n\nfunc = lambda x: amplitude * np.sin(2 * np.pi * x * 2) \\\n + 0.5 * amplitude * np.sin(2 * np.pi * x * 3) \\\n + 0.1 * amplitude * np.sin(2 * np.pi * x * 7)",
"_____no_output_____"
],
[
"X = np.arange(0, 1, 1 / discr)\nY = func(X)",
"_____no_output_____"
],
[
"plt.plot(X, Y)\nplt.xlabel('Время в секундах')\nplt.ylabel('Нормализованная амплитуда')",
"_____no_output_____"
],
[
"fftY = rfft(Y)\nx_freq = rfftfreq(len(Y), d = 1 / discr)\ny_freq = (2 / len(Y)) * np.abs(fftY)",
"_____no_output_____"
],
[
"fig, (ax1, ax2) = plt.subplots(1, 2)\nax1.plot(x_freq, y_freq)\nax2.plot(x_freq[:10], y_freq[:10])\n\nfig.add_subplot(111, frameon= False)\nplt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)\n\nplt.xlabel(\"Частота дискретизации в Гц\")\nplt.ylabel(\"Амплитуда\")",
"_____no_output_____"
],
[
"y_from_fft = irfft(fftY)\nplt.plot(X, y_from_fft)",
"_____no_output_____"
],
[
"f1 = lambda x: amplitude * np.sin(2 * np.pi * x * 2)\nf2 = lambda x: amplitude * 0.5 * np.sin(2 * np.pi * x * 3)\nf3 = lambda x: amplitude * 0.3 * np.sin(2 * np.pi * x * 10)\ndiscr = 1024",
"_____no_output_____"
],
[
"X = np.arange(0, 3, 1 / discr)",
"_____no_output_____"
],
[
"Y = np.asarray([f1(x) for x in X[:1024 * 1]] + \\\n [f2(x) for x in X[1024 * 1:1024 * 2]] + \\\n [f3(x) for x in X[1024 * 2:1024 * 3]])",
"_____no_output_____"
],
[
"plt.plot(X, Y)\nplt.xlabel('Время в секундах')\nplt.ylabel('Нормализованная амплитуда')",
"_____no_output_____"
],
[
"# Генератор, возвращает чанк из n элементов\ndef chunks(lst, n):\n for i in range(0, len(lst), n):\n yield lst[i:i + n]",
"_____no_output_____"
],
[
"sample_size = 1024",
"_____no_output_____"
],
[
"def plot_example(X, Y, sample_size = 1024):\n for chunkX, chunkY in zip(chunks(X, sample_size), chunks(Y, sample_size)):\n plt.plot(chunkX, chunkY)\n plt.xlabel('Время в секундах')\n plt.ylabel('Нормализованная амплитуда')\n\n for chunkY in chunks(Y, sample_size):\n fftY = rfft(chunkY)\n x_freq = rfftfreq(len(chunkY), d = 1 / discr)\n y_freq = (2 / len(chunkY)) * np.abs(fftY)\n fig, (ax1, ax2) = plt.subplots(1, 2)\n ax1.plot(x_freq, y_freq)\n ax2.plot(x_freq[:20], y_freq[:20])\n\n fig.add_subplot(111, frameon= False)\n plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)\n\n plt.xlabel(\"Частота дискретизации в Гц\")\n plt.ylabel(\"Амплитуда\")",
"_____no_output_____"
],
[
"plot_example(X,Y, sample_size)",
"_____no_output_____"
],
[
"plot_example(X,Y, 1256)",
"_____no_output_____"
]
],
[
[
"Фильтры",
"_____no_output_____"
]
],
[
[
"func = lambda x: amplitude * np.sin(2 * np.pi * x * 1) \\\n + amplitude * np.sin(2 * np.pi * x * 3) \\\n + amplitude * np.sin(2 * np.pi * x * 5)\n\nX = np.arange(0, 2, 1 / 1024)\nY = func(X)",
"_____no_output_____"
],
[
"plot_example(X,Y, len(Y))",
"_____no_output_____"
],
[
"from scipy.signal import filtfilt, butter, freqz",
"_____no_output_____"
],
[
"def butter_lowpass(cutoff, discr, order=5):\n nyq = 0.5 * discr\n normal_cutoff = cutoff / nyq\n b, a = butter(order, normal_cutoff, btype='low', analog=False)\n return b, a\n\ndef butter_lowpass_filter(data, cutoff, discr, order=5):\n b, a = butter_lowpass(cutoff, discr, order=order)\n return filtfilt(b, a, data).astype(np.short)\n\ndef plot_butter_filter(discr, cutoff, order, xlim):\n b, a = butter_lowpass(cutoff, discr, order)\n w, h = freqz(b, a, worN=8000)\n plt.plot(0.5 * discr * w / np.pi, np.abs(h), 'b')\n\n plt.plot(cutoff, 0.5 * np.sqrt(2), 'ko')\n plt.axvline(cutoff, color='k')\n\n plt.xlim(0, xlim)\n\n plt.grid()\n plt.xlabel(\"Lowpass Filter Frequency Response\")\n plt.ylabel(\"Frequency [Hz]\")\n",
"_____no_output_____"
],
[
"order = 3\ndiscr = 1024\ncutoff = 3\n\nplot_butter_filter(discr, cutoff, order, 0.01 * discr)\n\norder = 5\ndiscr = 1024\ncutoff = 3\n\nplot_butter_filter(discr, cutoff, order, 0.01 * discr)",
"_____no_output_____"
],
[
"order = 3\ndiscr = 1024\ncutoff = 3\n\nb, a = butter_lowpass(cutoff, discr, order)\ny = butter_lowpass_filter(Y, cutoff, discr, order)",
"_____no_output_____"
],
[
"plot_example(X, y, len(y))",
"_____no_output_____"
],
[
"def downsampling(data, by: int = 4):\n return data[::by]",
"_____no_output_____"
],
[
"len(Y)",
"_____no_output_____"
],
[
"downsampled = downsampling(Y)\nlen(downsampled)",
"_____no_output_____"
],
[
"discr = discr / 4",
"_____no_output_____"
],
[
"plot_example(downsampling(X), downsampled, len(downsampled))",
"_____no_output_____"
]
]
]
| [
"markdown",
"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"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
]
|
cb5d2b2981cf474caa2ff20ac657413d2d115e57 | 975,361 | ipynb | Jupyter Notebook | tools/dsp/notebooks/classify_ds3.ipynb | williampierce/cc | 26608f1e5008fb6809066d7779e1b91391c33bd4 | [
"MIT"
]
| 1 | 2015-03-09T18:33:20.000Z | 2015-03-09T18:33:20.000Z | tools/dsp/notebooks/classify_ds3.ipynb | williampierce/cc | 26608f1e5008fb6809066d7779e1b91391c33bd4 | [
"MIT"
]
| null | null | null | tools/dsp/notebooks/classify_ds3.ipynb | williampierce/cc | 26608f1e5008fb6809066d7779e1b91391c33bd4 | [
"MIT"
]
| null | null | null | 2,438.4025 | 513,647 | 0.949174 | [
[
[
"empty"
]
]
]
| [
"empty"
]
| [
[
"empty"
]
]
|
cb5d2c5aa1d48f7586ddf99a430392fb95a83a16 | 500,315 | ipynb | Jupyter Notebook | doc/nb/elg-properties-dr7.1.ipynb | jinyiY/desitarget | 546a85a3feb9754a2406ebfb2b9890514f47b3bf | [
"BSD-3-Clause"
]
| 13 | 2016-02-02T00:26:21.000Z | 2022-01-14T07:31:59.000Z | doc/nb/elg-properties-dr7.1.ipynb | jinyiY/desitarget | 546a85a3feb9754a2406ebfb2b9890514f47b3bf | [
"BSD-3-Clause"
]
| 674 | 2015-09-15T15:02:06.000Z | 2022-02-23T18:39:02.000Z | doc/nb/elg-properties-dr7.1.ipynb | jinyiY/desitarget | 546a85a3feb9754a2406ebfb2b9890514f47b3bf | [
"BSD-3-Clause"
]
| 29 | 2015-06-09T13:51:48.000Z | 2021-06-05T06:03:18.000Z | 1,073.637339 | 111,928 | 0.952154 | [
[
[
"# Properties of ELGs in DR7 Imaging\n\nThe purpose of this notebook is to quantify the observed properties (particulary size and ellipticity) of ELGs using DR7 catalogs of the COSMOS region. We use the HST/ACS imaging of objects in this region as \"truth.\"\n\nJ. Moustakas \n2018 Aug 15",
"_____no_output_____"
]
],
[
[
"import os, warnings, pdb\nimport numpy as np\nimport fitsio\nfrom astropy.table import Table\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"import seaborn as sns\nrc = {'font.family': 'serif'}#, 'text.usetex': True}\nsns.set(style='ticks', font_scale=1.5, palette='Set2', rc=rc)",
"_____no_output_____"
],
[
"%matplotlib inline",
"_____no_output_____"
]
],
[
[
"#### Read the HST/ACS parent (truth) catalog.",
"_____no_output_____"
]
],
[
[
"acsfile = os.path.join(os.getenv('DESI_ROOT'), 'target', 'analysis', 'truth', 'parent', 'cosmos-acs.fits.gz')\nallacs = Table(fitsio.read(acsfile, ext=1, upper=True))\nprint('Read {} objects from {}'.format(len(allacs), acsfile))",
"Read 1177274 objects from /global/project/projectdirs/desi/target/analysis/truth/parent/cosmos-acs.fits.gz\n"
]
],
[
[
"#### Assemble all the functions we'll need.",
"_____no_output_____"
]
],
[
[
"def read_tractor(subset='0'):\n \"\"\"Read the Tractor catalogs for a given cosmos subsest and cross-match \n with the ACS catalog.\n \n \"\"\"\n from glob import glob\n from astropy.table import vstack\n from astrometry.libkd.spherematch import match_radec \n \n tractordir = '/global/cscratch1/sd/dstn/cosmos-dr7-7{}/tractor'.format(subset)\n tractorfiles = glob('{}/???/tractor-*.fits'.format(tractordir))\n \n alldr7 = []\n for ii, tractorfile in enumerate(tractorfiles):\n #if (ii % 10) == 0:\n # print('Read {:02d} / {:02d} Tractor catalogs from subset {}.'.format(ii, len(tractorfiles), subset))\n alldr7.append(Table(fitsio.read(tractorfile, ext=1, upper=True)))\n alldr7 = vstack(alldr7)\n alldr7 = alldr7[alldr7['BRICK_PRIMARY']]\n \n # Cross-match\n m1, m2, d12 = match_radec(allacs['RA'], allacs['DEC'], alldr7['RA'], \n alldr7['DEC'], 1./3600.0, nearest=True)\n print('Read {} objects with HST/ACS and DR7 photometry'.format(len(m1)))\n \n return allacs[m1], alldr7[m2]",
"_____no_output_____"
],
[
"def select_ELGs(acs, dr7):\n from desitarget.cuts import isELG_south\n \n def unextinct_fluxes(cat):\n \"\"\"We need to unextinct the fluxes ourselves rather than using desitarget.cuts.unextinct_fluxes\n because the Tractor catalogs don't have forced WISE photometry.\n \n \"\"\"\n res = np.zeros(len(cat), dtype=[('GFLUX', 'f4'), ('RFLUX', 'f4'), ('ZFLUX', 'f4')])\n for band in ('G', 'R', 'Z'):\n res['{}FLUX'.format(band)] = ( cat['FLUX_{}'.format(band)] / \n cat['MW_TRANSMISSION_{}'.format(band)] )\n return Table(res)\n \n fluxes = unextinct_fluxes(dr7)\n gflux, rflux, zflux = fluxes['GFLUX'], fluxes['RFLUX'], fluxes['ZFLUX']\n ielg = isELG_south(gflux=fluxes['GFLUX'], rflux=fluxes['RFLUX'], \n zflux=fluxes['ZFLUX'])#, gallmask=alltarg['ALLMASK_G'],\n #rallmask=alltarg['ALLMASK_R'], zallmask=alltarg['ALLMASK_Z'])\n print('Selected {} / {} ELGs'.format(np.sum(ielg), len(acs)))\n return acs[ielg], dr7[ielg]",
"_____no_output_____"
],
[
"def get_mag(cat, band='R'):\n return 22.5 - 2.5 * np.log10(cat['FLUX_{}'.format(band)])\n\ndef get_reff_acs(cat):\n \"\"\"Convert SExtractor's flux_radius to half-light radius \n using the relation (derived from simulations) in Sec 4.2 \n of Griffith et al. 2012.\n \"\"\"\n with warnings.catch_warnings():\n warnings.simplefilter('ignore')\n reff = np.log10(0.03 * 0.162 * cat['FLUX_RADIUS']**1.87)\n return reff\n\ndef get_reff_tractor(cat):\n fracdev = cat['FRACDEV']\n reff = np.log10(fracdev * cat['SHAPEDEV_R'] + (1 - fracdev) * cat['SHAPEEXP_R'])\n return reff \n\ndef get_ell_acs(cat):\n ell = 1 - cat['B_IMAGE'] / cat['A_IMAGE']\n return ell\n\ndef get_ell_tractor(cat):\n fracdev = cat['FRACDEV']\n ell_exp = np.hypot(cat['SHAPEEXP_E1'], cat['SHAPEEXP_E2'])\n ell_dev = np.hypot(cat['SHAPEDEV_E1'], cat['SHAPEDEV_E2'])\n ell = fracdev * ell_dev + (1 - fracdev) * ell_exp\n return ell",
"_____no_output_____"
],
[
"def qa_true_properties(acs, dr7, subsetlabel='0', noplots=False, \n pngsize=None, pngellipticity=None):\n \"\"\"Use HST to characterize the *true* ELG size and ellipticity \n distributions.\n \n \"\"\"\n istar = acs['CLASS_STAR'] > 0.9\n igal = ~istar\n nstar, ngal, nobj = np.sum(istar), np.sum(igal), len(acs)\n \n print('True galaxies, N={} ({:.2f}%):'.format(ngal, 100*ngal/nobj))\n for tt in ('PSF ', 'REX ', 'EXP ', 'DEV ', 'COMP'):\n nn = np.sum(dr7['TYPE'][igal] == tt)\n frac = 100 * nn / ngal\n print(' {}: {} ({:.2f}%)'.format(tt, nn, frac))\n\n print('True stars, N={} ({:.2f}%):'.format(nstar, 100*nstar/nobj))\n for tt in ('PSF ', 'REX ', 'EXP ', 'DEV ', 'COMP'):\n nn = np.sum(dr7['TYPE'][istar] == tt)\n frac = 100 * nn / nstar\n print(' {}: {} ({:.2f}%)'.format(tt, nn, frac))\n \n if noplots:\n return\n \n rmag = get_mag(dr7)\n reff = get_reff_acs(acs)\n ell = get_ell_acs(acs)\n \n # Size\n j = sns.jointplot(rmag[igal], reff[igal], kind='hex', space=0, alpha=0.7,\n stat_func=None, cmap='viridis', mincnt=3)\n j.set_axis_labels('DECaLS $r$ (AB mag)', r'$\\log_{10}$ (HST/ACS Half-light radius) (arcsec)')\n j.fig.set_figwidth(10)\n j.fig.set_figheight(7)\n j.ax_joint.axhline(y=np.log10(0.45), color='k', ls='--')\n j.ax_joint.scatter(rmag[istar], reff[istar], marker='s', color='orange', s=10)\n j.ax_joint.text(20.8, np.log10(0.45)+0.1, r'$r_{eff}=0.45$ arcsec', ha='left', va='center', \n fontsize=14)\n j.ax_joint.text(0.15, 0.2, 'HST Stars', ha='left', va='center', \n fontsize=14, transform=j.ax_joint.transAxes)\n j.ax_joint.text(0.05, 0.9, '{}'.format(subsetlabel), ha='left', va='center', \n fontsize=16, transform=j.ax_joint.transAxes)\n if pngsize:\n plt.savefig(pngsize)\n \n # Ellipticity\n j = sns.jointplot(rmag[igal], ell[igal], kind='hex', space=0, alpha=0.7,\n stat_func=None, cmap='viridis', mincnt=3)\n j.set_axis_labels('DECaLS $r$ (AB mag)', 'HST/ACS Ellipticity')\n j.fig.set_figwidth(10)\n j.fig.set_figheight(7)\n j.ax_joint.scatter(rmag[istar], ell[istar], marker='s', color='orange', s=10)\n j.ax_joint.text(0.15, 0.2, 'HST Stars', ha='left', va='center', \n fontsize=14, transform=j.ax_joint.transAxes)\n j.ax_joint.text(0.05, 0.9, '{}'.format(subsetlabel), ha='left', va='center', \n fontsize=16, transform=j.ax_joint.transAxes)\n if pngellipticity:\n plt.savefig(pngellipticity) ",
"_____no_output_____"
],
[
"def qa_compare_radii(acs, dr7, subsetlabel='0', seeing=None, png=None):\n \"\"\"Compare the HST and Tractor sizes.\"\"\"\n igal = dr7['TYPE'] != 'PSF '\n \n reff_acs = get_reff_acs(acs[igal])\n reff_tractor = get_reff_tractor(dr7[igal])\n sizelim = (-1.5, 1)\n \n j = sns.jointplot(reff_acs, reff_tractor, kind='hex', space=0, alpha=0.7,\n stat_func=None, cmap='viridis', mincnt=3,\n xlim=sizelim, ylim=sizelim)\n j.set_axis_labels(r'$\\log_{10}$ (HST/ACS Half-light radius) (arcsec)', \n r'$\\log_{10}$ (Tractor/DR7 Half-light radius) (arcsec)')\n j.fig.set_figwidth(10)\n j.fig.set_figheight(7)\n j.ax_joint.plot([-2, 2], [-2, 2], color='k') \n if seeing:\n j.ax_joint.axhline(y=np.log10(seeing), ls='--', color='k')\n j.ax_joint.text(0.05, 0.9, '{}'.format(subsetlabel), ha='left', va='center', \n fontsize=16, transform=j.ax_joint.transAxes)\n if png:\n plt.savefig(png)",
"_____no_output_____"
]
],
[
[
"### Use subset 0 to characterize the \"true\" ELG properties.",
"_____no_output_____"
]
],
[
[
"subset = '0'\nallacs, alldr7 = read_tractor(subset=subset)\nacs, dr7 = select_ELGs(allacs, alldr7)\nsubsetlabel = 'Subset {}\\n{:.3f}\" seeing'.format(subset, np.median(alldr7['PSFSIZE_R']))\nqa_true_properties(acs, dr7, subsetlabel=subsetlabel, pngsize='truesize.png', pngellipticity='trueell.png')",
"Read 40339 objects with HST/ACS and DR7 photometry\nSelected 3057 / 40339 ELGs\nTrue galaxies, N=2955 (96.66%):\n PSF : 180 (6.09%)\n REX : 2492 (84.33%)\n EXP : 233 (7.88%)\n DEV : 49 (1.66%)\n COMP: 1 (0.03%)\nTrue stars, N=102 (3.34%):\n PSF : 75 (73.53%)\n REX : 22 (21.57%)\n EXP : 3 (2.94%)\n DEV : 2 (1.96%)\n COMP: 0 (0.00%)\n"
]
],
[
[
"### Compare radii measured in three subsets of increasingly poor seeing (but same nominal depth).",
"_____no_output_____"
]
],
[
[
"for subset in ('0', '4', '9'):\n allacs, alldr7 = read_tractor(subset=subset)\n acs, dr7 = select_ELGs(allacs, alldr7)\n medseeing = np.median(alldr7['PSFSIZE_R'])\n subsetlabel = 'Subset {}\\n{:.3f}\" seeing'.format(subset, medseeing)\n qa_compare_radii(acs, dr7, subsetlabel=subsetlabel, png='size_compare_subset{}.png'.format(subset))",
"Read 40339 objects with HST/ACS and DR7 photometry\nSelected 3057 / 40339 ELGs\nRead 40339 objects with HST/ACS and DR7 photometry\nSelected 3150 / 40339 ELGs\nRead 40339 objects with HST/ACS and DR7 photometry\nSelected 3282 / 40339 ELGs\n"
],
[
"subset = '9'\nallacs, alldr7 = read_tractor(subset=subset)\nacs, dr7 = select_ELGs(allacs, alldr7)\nsubsetlabel = 'Subset {}\\n{:.3f}\" seeing'.format(subset, np.median(alldr7['PSFSIZE_R']))\nqa_true_properties(acs, dr7, subsetlabel=subsetlabel, noplots=True)",
"Read 40339 objects with HST/ACS and DR7 photometry\nSelected 3282 / 40339 ELGs\nTrue galaxies, N=3146 (95.86%):\n PSF : 758 (24.09%)\n REX : 2225 (70.72%)\n EXP : 120 (3.81%)\n DEV : 43 (1.37%)\n COMP: 0 (0.00%)\nTrue stars, N=136 (4.14%):\n PSF : 99 (72.79%)\n REX : 31 (22.79%)\n EXP : 3 (2.21%)\n DEV : 3 (2.21%)\n COMP: 0 (0.00%)\n"
]
]
]
| [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
]
| [
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
]
|
cb5d3af21a23e5f726985de1ca3aec50fcc2dcdb | 26,704 | ipynb | Jupyter Notebook | 00_core.ipynb | Living-with-machines/hmd_newspaper_dl | 58cf1391d39b325b691d5add84e34453cba2d3ea | [
"MIT"
]
| 2 | 2021-10-21T07:48:20.000Z | 2022-01-06T10:52:18.000Z | 00_core.ipynb | Living-with-machines/hmd_newspaper_dl | 58cf1391d39b325b691d5add84e34453cba2d3ea | [
"MIT"
]
| 3 | 2022-01-06T16:06:43.000Z | 2022-02-03T14:48:15.000Z | 00_core.ipynb | Living-with-machines/hmd_newspaper_dl | 58cf1391d39b325b691d5add84e34453cba2d3ea | [
"MIT"
]
| null | null | null | 33.931385 | 380 | 0.55164 | [
[
[
"# default_exp core",
"_____no_output_____"
]
],
[
[
"# hmd_newspaper_dl\n> Download Heritage made Digital Newspaper from the BL repository ",
"_____no_output_____"
],
[
"The aim of this code is to make it easier to download all of the [Heritage Made Digital Newspapers](https://bl.iro.bl.uk/collections/353c908d-b495-4413-b047-87236d2573e3?locale=en) from the British Library's [Research Repository](bl.iro.bl.uk/). ",
"_____no_output_____"
]
],
[
[
"# export\nimport concurrent\nimport itertools\nimport json\nfrom requests.adapters import HTTPAdapter\nfrom requests.packages.urllib3.util.retry import Retry\nimport random\nimport sys\nimport time\nfrom collections import namedtuple\nfrom functools import lru_cache\nfrom operator import itemgetter\n\n# from os import umask\nimport os\nfrom pathlib import Path\nfrom typing import List, Optional, Union\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom fastcore.script import *\nfrom fastcore.test import *\nfrom fastcore.net import urlvalid\nfrom loguru import logger\nfrom nbdev.showdoc import *\nfrom tqdm import tqdm",
"_____no_output_____"
]
],
[
[
"## Getting newspaper links\n \nThe Newspapers are currently organised by newspaper title under a collection:\n\n\n\nUnder each titles you can download a zip file representing a year for that particular newspaper title \n\n\n\nIf we only want a subset of year or titles we could download these manually but if we're interested in using computational methods it's a bit slow. What we need to do is grab all of the URL's for each title so we can bulk download them all. ",
"_____no_output_____"
]
],
[
[
"# export\ndef _get_link(x: str):\n end = x.split(\"/\")[-1]\n return \"https://bl.iro.bl.uk/concern/datasets/\" + end",
"_____no_output_____"
]
],
[
[
"This is a smaller helper function that will generate the correct url once we have got an ID for a title.",
"_____no_output_____"
]
],
[
[
"# export\n@lru_cache(256)\ndef get_newspaper_links():\n \"\"\"Returns titles from the Newspaper Collection\"\"\"\n urls = [\n f\"https://bl.iro.bl.uk/collections/9a6a4cdd-2bfe-47bb-8c14-c0a5d100501f?locale=en&page={page}\"\n for page in range(1, 3)\n ]\n link_tuples = []\n for url in urls:\n r = requests.get(url)\n r.raise_for_status()\n soup = BeautifulSoup(r.text, \"lxml\")\n links = soup.select(\".hyc-container > .hyc-bl-results a[id*=src_copy_link]\")\n \n for link in links:\n url = link[\"href\"]\n if url:\n t = (link.text, _get_link(url))\n link_tuples.append(t)\n return link_tuples",
"_____no_output_____"
]
],
[
[
"This function starts from the Newspaper collection and then uses BeatifulSoup to scrape all of the URLs which link to a newspaper title. We have a hard coded URL here which isn't very good practice but since we're writing this code for a fairly narrow purpose we'll not worry about that here. \n\nIf we call this function we get a bunch of links back. ",
"_____no_output_____"
]
],
[
[
"links = get_newspaper_links()\nlinks",
"_____no_output_____"
],
[
"len(links)",
"_____no_output_____"
]
],
[
[
"Although this is code has fairly narrow scope, we might still want some tests to check we're not completely off. `nbdev` makes this super easy. Here we get that the we get back what we expect in terms of tuple length and that our urls look like urls. ",
"_____no_output_____"
]
],
[
[
"assert len(links[0]) == 2 # test tuple len\nassert (\n next(iter(set(map(urlvalid, map(itemgetter(1), links))))) == True\n) # check second item valid url",
"_____no_output_____"
],
[
"assert len(links) == 10\nassert type(links[0]) == tuple\nassert (list(map(itemgetter(1), links))[-1]).startswith(\"https://\")",
"_____no_output_____"
],
[
"# export\n@lru_cache(256)\ndef get_download_urls(url: str) -> list:\n \"\"\"Given a dataset page on the IRO repo return all download links for that page\"\"\"\n data, urls = None, None\n try:\n r = requests.get(url, timeout=30)\n except requests.exceptions.MissingSchema as E:\n print(E)\n\n soup = BeautifulSoup(r.text, \"lxml\")\n link_ends = soup.find_all(\"a\", id=\"file_download\")\n urls = [\"https://bl.iro.bl.uk\" + link[\"href\"] for link in link_ends]\n # data = json.loads(soup.find(\"script\", type=\"application/ld+json\").string)\n # except AttributeError as E:\n # print(E)\n # if data:\n # #data = data[\"distribution\"]\n # #urls = [item[\"contentUrl\"] for item in data]\n return list(set(urls))",
"_____no_output_____"
]
],
[
[
"`get_download_urls` takes a 'title' URL and then grabs all of the URLs for the zip files related to that title. ",
"_____no_output_____"
]
],
[
[
"test_link = links[0][1]\ntest_link",
"_____no_output_____"
],
[
"get_download_urls(test_link)",
"_____no_output_____"
],
[
"# export\ndef create_session() -> requests.sessions.Session:\n \"\"\"returns a requests session\"\"\"\n retry_strategy = Retry(total=60)\n adapter = HTTPAdapter(max_retries=retry_strategy)\n session = requests.Session()\n session.mount(\"https://\", adapter)\n session.mount(\"http://\", adapter)\n return session",
"_____no_output_____"
]
],
[
[
"`create_session` just adds some extra things to our `Requests` session to try and make it a little more robust. This is probably not necessary here but it can be useful to bump up the number of retries ",
"_____no_output_____"
]
],
[
[
"# export\ndef _download(url: str, dir: Union[str, Path]):\n time.sleep(10)\n fname = None\n s = create_session()\n try:\n r = s.get(url, stream=True, timeout=(30))\n r.raise_for_status()\n # fname = r.headers[\"Content-Disposition\"].split('_')[1]\n fname = \"_\".join(r.headers[\"Content-Disposition\"].split('\"')[1].split(\"_\")[0:5])\n if fname:\n with open(f\"{dir}/{fname}\", \"wb\") as f:\n for chunk in r.iter_content(chunk_size=8192):\n f.write(chunk)\n except KeyError:\n pass\n except requests.exceptions.RequestException as request_exception:\n logger.error(request_exception)\n return fname",
"_____no_output_____"
],
[
"# for url in get_download_urls(\"https://bl.iro.bl.uk/concern/datasets/93ec8ab4-3348-409c-bf6d-a9537156f654\"):\n# s = create_session()\n# r = s.get(url, stream=True, timeout=(30))\n# print(\"_\".join(r.headers[\"Content-Disposition\"].split('\"')[1].split(\"_\")[0:5]))",
"_____no_output_____"
],
[
"# s = create_session()\n# r = s.get(test_url, stream=True, timeout=(30))\n# \"_\".join(r.headers[\"Content-Disposition\"].split('\"')[1].split(\"_\")[0:5])",
"_____no_output_____"
]
],
[
[
"This downloads a file and logs an exception if something goes wrong. Again we do a little test.",
"_____no_output_____"
]
],
[
[
"# slow\ntest_url = (\n \"https://bl.iro.bl.uk/downloads/0ea7aa1f-3b4f-4972-bc12-b7559769471f?locale=en\"\n)\nPath(\"test_dir\").mkdir()\ntest_dir = Path(\"test_dir\")\n_download(test_url, test_dir)",
"_____no_output_____"
],
[
"# slow\nassert list(test_dir.iterdir())[0].suffix == \".zip\"\nassert len(list(test_dir.iterdir())) == 1\n# tidy up\n[f.unlink() for f in test_dir.iterdir()]\ntest_dir.rmdir()",
"_____no_output_____"
],
[
"# basic test to check bad urls won't raise unhandled exceptions\nbad_link = \"https://bl.oar.bl.uk/fail_uploads/download_file?fileset_id=0ea7aa1-3b4f-4972-bc12-b75597694f\"\n_download(bad_link, \"test_dir\")",
"2022-02-03 14:19:37.855 | ERROR | __main__:_download:18 - HTTPSConnectionPool(host='bl.oar.bl.uk', port=443): Max retries exceeded with url: /fail_uploads/download_file?fileset_id=0ea7aa1-3b4f-4972-bc12-b75597694f (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1091)')))\n"
],
[
"# export\ndef download_from_urls(urls: List[str], save_dir: Union[str, Path], n_threads: int = 4):\n \"\"\"Downloads from an input lists of `urls` and saves to `save_dir`, option to set `n_threads` default = 8\"\"\"\n download_count = 0\n tic = time.perf_counter()\n Path(save_dir).mkdir(exist_ok=True)\n logger.remove()\n logger.add(lambda msg: tqdm.write(msg, end=\"\"))\n with tqdm(total=len(urls)) as progress:\n with concurrent.futures.ThreadPoolExecutor(max_workers=n_threads) as executor:\n future_to_url = {\n executor.submit(_download, url, save_dir): url for url in urls\n }\n for future in future_to_url:\n future.add_done_callback(lambda p: progress.update(1))\n for future in concurrent.futures.as_completed(future_to_url):\n url = future_to_url[future]\n try:\n data = future.result()\n except Exception as e:\n logger.error(\"%r generated an exception: %s\" % (url, e))\n else:\n if data:\n logger.info(f\"{url} downloaded to {data}\")\n download_count += 1\n toc = time.perf_counter()\n logger.remove()\n logger.info(f\"Downloads completed in {toc - tic:0.4f} seconds\")\n return download_count",
"_____no_output_____"
]
],
[
[
"`download_from_urls` takes a list of urls and downloads it to a specified directory ",
"_____no_output_____"
]
],
[
[
"test_links = [\n \"https://bl.iro.bl.uk/downloads/0ea7aa1f-3b4f-4972-bc12-b7559769471f?locale=en\",\n \"https://bl.iro.bl.uk/downloads/80708825-d96a-4301-9496-9598932520f4?locale=en\",\n]",
"_____no_output_____"
],
[
"download_from_urls(test_links, \"test_dir\")",
" 50%|████████████████████████████████████████████████ | 1/2 [00:36<00:36, 36.91s/it]"
],
[
"# slow\nassert len(test_links) == len(os.listdir(\"test_dir\"))\ntest_dir = Path(\"test_dir\")\n[f.unlink() for f in test_dir.iterdir()]\ntest_dir.rmdir()",
"_____no_output_____"
],
[
"# slow\ntest_some_bad_links = [\n \"https://bl.oar.bl.uk/fail_uploads/download_file?fileset_id=0ea7aa1f-3b4f-4972-bc12-b7559769471f\",\n \"https://bl.oar.bl.uk/fail_uploads/download_file?fileset_id=7ac7a0cb-29a2-4172-8b79-4952e2c9b\",\n]\ndownload_from_urls(test_some_bad_links, \"test_dir\")",
" 50%|████████████████████████████████████████████████ | 1/2 [00:15<00:15, 15.73s/it]"
],
[
"# slow\ntest_dir = Path(\"test_dir\")\n[f.unlink() for f in test_dir.iterdir()]\ntest_dir.rmdir()",
"_____no_output_____"
],
[
"# export\n@call_parse\ndef cli(\n save_dir: Param(\"Output Directory\", str),\n n_threads: Param(\"Number threads to use\") = 8,\n subset: Param(\"Download subset of HMD\", int, opt=True) = None,\n url: Param(\"Download from a specific URL\", str, opt=True) = None,\n):\n \"Download HMD newspaper from iro to `save_dir` using `n_threads`\"\n if url is not None:\n logger.info(f\"Getting zip download file urls for {url}\")\n try:\n zip_urls = get_download_urls(url)\n print(zip_urls)\n except Exception as e:\n logger.error(e)\n download_count = download_from_urls(zip_urls, save_dir, n_threads=n_threads)\n else:\n logger.info(\"Getting title urls\")\n title_urls = get_newspaper_links()\n logger.info(f\"Found {len(title_urls)} title urls\")\n all_urls = []\n print(title_urls)\n for url in title_urls:\n logger.info(f\"Getting zip download file urls for {url}\")\n try:\n zip_urls = get_download_urls(url[1])\n all_urls.append(zip_urls)\n except Exception as e:\n logger.error(e)\n all_urls = list(itertools.chain(*all_urls))\n if subset:\n if len(all_urls) < subset:\n raise ValueError(\n f\"Size of requested sample {subset} is larger than total number of urls:{all_urls}\"\n )\n all_urls = random.sample(all_urls, subset)\n print(all_urls)\n download_count = download_from_urls(all_urls, save_dir, n_threads=n_threads)\n request_url_count = len(all_urls)\n if request_url_count == download_count:\n logger.info(\n f\"\\U0001F600 Requested count of urls: {request_url_count} matches number downloaded: {download_count}\"\n )\n if request_url_count > download_count:\n logger.warning(\n f\"\\U0001F622 Requested count of urls: {request_url_count} higher than number downloaded: {download_count}\"\n )\n if request_url_count < download_count:\n logger.warning(\n f\"\\U0001F937 Requested count of urls: {request_url_count} lower than number downloaded: {download_count}\"\n )",
"_____no_output_____"
]
],
[
[
"We finally use `fastcore` to make a little CLI that we can use to download all of our files. We even get a little help flag for free 😀. We can either call this as a python function, or when we install the python package it gets registered as a `console_scripts` and can be used like other command line tools. ",
"_____no_output_____"
]
],
[
[
"# cli(\"test_dir\", subset=2)",
"_____no_output_____"
],
[
"# assert all([f.suffix == '.zip' for f in Path(\"test_dir\").iterdir()])\n# assert len(list(Path(\"test_dir\").iterdir())) == 2",
"_____no_output_____"
],
[
"from nbdev.export import notebook2script\n\nnotebook2script()",
"Converted 00_core.ipynb.\nConverted index.ipynb.\n"
],
[
"# test_dir = Path(\"test_dir\")\n# [f.unlink() for f in test_dir.iterdir()]\n# test_dir.rmdir()",
"_____no_output_____"
]
]
]
| [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
]
| [
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
]
|
cb5d3cb9e99588c9a6b8cbf3d0e7a060eae01b00 | 27,301 | ipynb | Jupyter Notebook | Conditionals/Conditions.ipynb | Center-for-Health-Data-Science/teaching | d9be34af796fb07b3a51e415b1052e0d7fdc75af | [
"MIT"
]
| 7 | 2021-04-20T08:41:28.000Z | 2021-11-08T10:31:05.000Z | Conditionals/Conditions.ipynb | Center-for-Health-Data-Science/teaching | d9be34af796fb07b3a51e415b1052e0d7fdc75af | [
"MIT"
]
| 11 | 2021-04-21T07:48:49.000Z | 2021-11-01T10:21:29.000Z | Conditionals/Conditions.ipynb | Center-for-Health-Data-Science/teaching | d9be34af796fb07b3a51e415b1052e0d7fdc75af | [
"MIT"
]
| 5 | 2021-04-16T18:15:08.000Z | 2021-06-11T07:53:55.000Z | 22.712978 | 302 | 0.513644 | [
[
[
"<img src=\"../figures/HeaDS_logo_large_withTitle.png\" width=\"300\">\n\n<img src=\"../figures/tsunami_logo.PNG\" width=\"600\">\n\n[](https://colab.research.google.com/github/Center-for-Health-Data-Science/PythonTsunami/blob/fall2021/Conditionals/Conditions.ipynb)",
"_____no_output_____"
],
[
"# Boolean and Conditional logic\n\n*prepared by [Katarina Nastou](https://www.cpr.ku.dk/staff/?pure=en/persons/672471) and [Rita Colaço](https://www.cpr.ku.dk/staff/?id=621366&vis=medarbejder)*",
"_____no_output_____"
],
[
"## Objectives\n\n- Understand boolean operators and how variables can relate\n- Learn about \"Truthiness\"\n- Learn how to write conditional statements and use proper indentation\n- Learn how to use comparison operators to make a basic programs\n\n",
"_____no_output_____"
],
[
"## User Input\nThere is a built-in function in Python called \"input\" that will prompt the user and store the result to a variable.\n",
"_____no_output_____"
]
],
[
[
"name = input(\"Enter your name here: \")",
"_____no_output_____"
],
[
"print(name)",
"_____no_output_____"
]
],
[
[
"## Booleans",
"_____no_output_____"
]
],
[
[
"x = True\nprint(x)",
"_____no_output_____"
],
[
"print(type(x))",
"_____no_output_____"
]
],
[
[
"## Comparison Operators",
"_____no_output_____"
],
[
"Comparison operators can tell how two Python values relate, resulting in a boolean. They answer yes/no questions.\n\nIn the example `a = 2` and `b = 2`, i.e. we are comparing integers (`int`)\n\n\noperator | Description | Result | Example (`a, b = 2, 2`)\n--- | --- |--- | ---\n`==` | **a** equal to **b** | True if **a** has the same value as **b** | `a == b # True`\n`!=` |\t**a** not equal to **b** | True if **a** does NOT have the same value as **b** | `a != b # False`\n`>` | **a** greater than **b** | True if **a** is greater than **b** | `a > b # False`\n`<` | **a** less than **b** | True if **a** is less than be **b** | `a < b # False`\n`>=` | **a** greater than or equal to **b** | True if **a** is greater than or equal to **b** | `a >= b # True`\n`<=` | **a** less than or equal to **b** | True if **a** is less than or equal to **b** | `a <= b # True`\n\n> Hint: The result of a comparison is defined by the type of **a** and **b**, and the **operator** used",
"_____no_output_____"
],
[
"### Numeric comparisons",
"_____no_output_____"
]
],
[
[
"a, b = 2, 2\na >= b",
"_____no_output_____"
]
],
[
[
"### String comparisons",
"_____no_output_____"
]
],
[
[
"\"carl\" < \"chris\"",
"_____no_output_____"
]
],
[
[
"### Quiz\n\n**Question 1**: What will be the result of this comparison?\n\n```python\n x = 2\n y = \"Anthony\"\n x < y\n```\n\n1. True\n2. False\n3. Error",
"_____no_output_____"
],
[
"**Question 2**: What about this comparison?\n\n```python\n x = 12.99\n y = 12\n x >= y\n```\n\n1. True\n2. False\n3. Error",
"_____no_output_____"
],
[
"**Question 3**: And this comparison?\n\n```python\n x = 5\n y = \"Hanna\"\n x == y\n```\n\n1. True\n2. False\n3. Error",
"_____no_output_____"
],
[
"## Truthiness",
"_____no_output_____"
],
[
"In Python, all conditional checks resolve to `True` or `False`.\n\n```python\nx = 1\nx == 1 # True\nx == 0 # False\n```\n\nBesides false conditional checks, other things that are naturally \"falsy\" include: empty lists/tuples/arrays, empty strings, None, and zero (and non-empty things are normally `True`).\n\n\n> \"Although Python has a bool type, it accepts any object in a boolean context, such as the\n> expression controlling an **if** or **while** statement, or as operands to **and**, **or**, and **not**. \n> To determine whether a value **x** is _truthy_ or _falsy_, Python applies `bool(x)`, which always returns True or False. \n> \n> (...) Basically, `bool(x)` calls `x.__bool__()` and uses the result. \n> If `__bool__` is not implemented, Python tries to invoke `x.__len__()`, and if that returns zero, bool returns `False`. \n> Otherwise bool returns `True`.\" (Ramalho 2016: Fluent Python, p. 12)\n",
"_____no_output_____"
]
],
[
[
"a = []\nbool(a)",
"_____no_output_____"
],
[
"a = ''\nbool(a)",
"_____no_output_____"
],
[
"a = None\nbool(a)",
"_____no_output_____"
],
[
"a = 0\nb = 1\n\nprint(bool(a))\nprint(bool(b))",
"_____no_output_____"
]
],
[
[
"## Logical Operators or \"How to combine boolean values\"",
"_____no_output_____"
],
[
"In Python, the following operators can be used to make Boolean Logic comparisons. The three most common ones are `and`, `or` and `not`.",
"_____no_output_____"
],
[
"`and`, True if both **a** AND **b** are true (logical conjunction)\n\n```python\ncats_are_cute = True\ndogs_are_cute = True\n\ncats_are_cute and dogs_are_cute # True\n```\n\n> But `True and False`, `False and True` and `False and False` all evaluate to `False`.",
"_____no_output_____"
]
],
[
[
"x = 134\nx > 49 and x < 155",
"_____no_output_____"
]
],
[
[
"`or`, True if either **a** OR **b** are true (logical disjunction) \n```python\nam_tired = True\nis_bedtime = False\n\nam_tired or is_bedtime # True\n```\n\n> `True or True`, `False or True` and `True or False` evaluate to `True`.\n\n> Only `False or False` results in `False`.",
"_____no_output_____"
]
],
[
[
"x = 5\nx < 7 or x > 11",
"_____no_output_____"
]
],
[
[
"`not`, True if the opposite of **a** is true (logical negation)\n```python\nis_weekend = True\n\nnot is_weekend # False\n```\n\n> `not True` -> False\n\n> `not False` -> True",
"_____no_output_____"
],
[
"### Order of precedence",
"_____no_output_____"
],
[
"Can you guess the result of this expression?\n\n```python\nTrue or True and False\n```\n\n1. True\n2. False\n3. Error",
"_____no_output_____"
]
],
[
[
"# True or True and False",
"_____no_output_____"
]
],
[
[
"Instead of memorizing the [order of precedence](https://docs.python.org/3/reference/expressions.html#operator-precedence), we can use parentheses to define the order in which operations are performed.\n\n- Helps prevent bugs\n- Makes your intentions clearer to whomever reads your code",
"_____no_output_____"
]
],
[
[
"# (True or True) and False",
"_____no_output_____"
]
],
[
[
"## Special operators\n\n### Identity operators",
"_____no_output_____"
],
[
"Operator | Description |Example (`a, b = 2, 3`)\n--- | --- |---\n`is` | True if the operands are identical (refer to the same object) | `a is 2 # True`\n`is not` | True if the operands are not identical (do not refer to the same object) | `a is not b # False`",
"_____no_output_____"
],
[
"In python, `==` and `is` are very similar operators, however they are NOT the same.\n\n`==` compares **equality**, while `is` compares by checking for the **identity**.",
"_____no_output_____"
],
[
"Example 1:",
"_____no_output_____"
]
],
[
[
"a = 1\nprint(a == 1)\nprint(a is 1)",
"_____no_output_____"
]
],
[
[
"Example 2:",
"_____no_output_____"
]
],
[
[
"a = [1, 2, 3]\nb = [1, 2, 3]\nprint(a == b)\nprint(a is b)",
"_____no_output_____"
]
],
[
[
"**`is`** comparisons only return `True` if the variables reference the same item *in memory*. It is recommendend to [test Singletons with `is`](https://www.python.org/dev/peps/pep-0008/#programming-recommendations) and not `==`, e.g. `None`, `True`, `False`.\n",
"_____no_output_____"
],
[
"### Membership operators",
"_____no_output_____"
],
[
"Operator | Description |Example (`a = [1, 2, 3]`)\n--- | --- |---\n`in` | True if value/variable is found in the sequence | `2 in a # True`\n`not in` | True if value/variable is not found in the sequence | `5 not in a # False`",
"_____no_output_____"
]
],
[
[
"aa = ['alanine', 'glycine', 'tyrosine']\n\n'alanine' in aa",
"_____no_output_____"
],
[
"'gly' in aa[0]",
"_____no_output_____"
]
],
[
[
"## Quiz\n\n**Question 1**: What is truthiness?\n\n1. Statements or facts that seem \"kind of true\" even if they aren't true necessarily\n2. Statements or expressions that result to a True value\n3. Code that never lies\n4. Computers have the tendency to believe things are True until proven False",
"_____no_output_____"
],
[
"**Question 2**: Is the following expression True or False?\n\n```python\n x = 15\n y = 0\n bool(x or y) # this expression\n```",
"_____no_output_____"
],
[
"**Question 3**: Is the following expression True or False?\n\n```python\n x = 0\n y = None\n bool(x or y) # this expression\n```",
"_____no_output_____"
],
[
"**Question 4**: (Hard) What is the result of the following expression?\n\n```python\n x = 233\n y = 0\n z = None\n x or y or z # this expression\n```",
"_____no_output_____"
],
[
"**Question 5**: Hardest question! Add parentheses to the expression, so that it shows the order of precedence explicitely?\n\n```python\n x = 0\n y = -1\n x or y and x - 1 == y and y + 1 == x\n```\n> Tip: check the [order of precedence](https://docs.python.org/3/reference/expressions.html#operator-precedence).",
"_____no_output_____"
],
[
"## Conditional Statements",
"_____no_output_____"
],
[
"[Conditional statements](https://docs.python.org/3/tutorial/controlflow.html#if-statements), use the keywords `if`, `elif` and `else`, and they let you control what pieces of code are run based on the value of some Boolean condition.\n\n```python\nif some condition is True:\n do something\nelif some other condition is True:\n do something\nelse:\n do something\n```\n\n> Recipe: if condition, execute expression\n\n> If condition always finishes with `:` (colon)\n\n> Expression to be executed if condition succeeds always needs to be indented (spaces or tab, depending on the editor you are using)",
"_____no_output_____"
]
],
[
[
"cats_are_cute = True\ndogs_are_cute = True\n\nif cats_are_cute and dogs_are_cute:\n print(\"Pets are cute!\")",
"_____no_output_____"
]
],
[
[
"> Here the `if` statement automatically calls `bool` on the expression, e.g. `bool(cats_are_cute and dogs_are_cute)`.",
"_____no_output_____"
],
[
"Adding the `else` statement:",
"_____no_output_____"
]
],
[
[
"is_weekend = True\n\nif not is_weekend:\n print(\"It's Monday.\")\n print(\"Go to work.\")\nelse:\n print(\"Sleep in and enjoy the beach.\")\n ",
"_____no_output_____"
]
],
[
[
"For more customized behavior, use `elif`:",
"_____no_output_____"
]
],
[
[
"am_tired = True\nis_bedtime = True\n\nif not am_tired:\n print(\"One more episode.\") \nelif am_tired and is_bedtime:\n print(\"Go to sleep.\")\nelse:\n print(\"Go to sleep anyways.\")\n",
"_____no_output_____"
]
],
[
[
"### Quiz:\n**Question 1**: If you set the name variable to \"Gandalf\" and run the script below, what will be the output?",
"_____no_output_____"
]
],
[
[
"name = input(\"Enter your name here: \")\nif name == \"Gandalf\":\n print(\"Run, you fools!\")\nelif name == \"Aragorn\":\n print(\"There is always hope.\")\nelse:\n print(\"Move on then!\")",
"_____no_output_____"
]
],
[
[
"**Question 2**: Why do we use `==` and not `is` in the code above?",
"_____no_output_____"
],
[
"## Group exercises",
"_____no_output_____"
],
[
"### Exercise 1\nAt the next code block there is some code that randomly picks a number from 1 to 10. \nWrite a conditional statement to check if `choice` is 5 and print `\"Five it is!\"` and in any other case print `\"Well that's not a 5!\"`.",
"_____no_output_____"
]
],
[
[
"from random import randint\nchoice = randint(1,10)\n\n# YOUR CODE GOES HERE vvvvvv\n",
"_____no_output_____"
]
],
[
[
"### Exercise 2\nAt the next code block there is some code that randomly picks a number from 1 to 1000. Use a conditional statement to check if the number is odd and print `\"odd\"`, otherwise print `\"even\"`.\n\n> *Hint*: Remember the numerical operators we saw before in [Numbers_and_operators.ipynb](https://colab.research.google.com/github/Center-for-Health-Data-Science/PythonTsunami/blob/fall2021/Numbers_and_operators/Numbers_and_operators.ipynb) and think of which one can help you find an odd number.",
"_____no_output_____"
]
],
[
[
"from random import randint\nnum = randint(1, 1000) #picks random number from 1-1000\n\n# YOUR CODE GOES HERE vvvvvvv\n",
"_____no_output_____"
]
],
[
[
"### Exercise 3 \n\nCreate a variable and assign an integer as value, then build a conditional to test it:\n- If the value is below 0, print \"The value is negative\"\n- If the value is between 0 and 20 (including 0 and 20), print the value\n- Otherwise, print \"Out of scope\"\n\nTest it by changing the value of the variable",
"_____no_output_____"
],
[
"### Exercise 4\n\nRead the file 'data/samples.txt' following the notebook [Importing data](https://colab.research.google.com/github/Center-for-Health-Data-Science/PythonTsunami/blob/fall2021/Importing_data/Importing_data.ipynb) and check if Denmark is among the countries in this file.",
"_____no_output_____"
],
[
"## Recap\n",
"_____no_output_____"
],
[
"- Conditional logic can control the flow of a program\n\n- We can use comparison and logical operators to make conditional if statements\n\n- In general, always make sure you make comparisons between objects of the same type (integers and floats are the exceptions)\n\n- Conditional logic evaluates whether statements are true or false\n\n\n\n\n\n",
"_____no_output_____"
],
[
"*Note: This notebook's content structure has been adapted from Colt Steele's slides used in [Modern Python 3 Bootcamp Course](https://www.udemy.com/course/the-modern-python3-bootcamp/) on Udemy*",
"_____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",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
]
|
cb5d3e4704d779c2f0a635b1f1f9ccb1bdc1b85c | 35,003 | ipynb | Jupyter Notebook | 1.4 R Lists/de-DE/.ipynb_checkpoints/1.4.22 R - Lists-checkpoint.ipynb | softfactories/r_train_2 | ffa0530ba13c7b43f5f33a4141b1690647603141 | [
"MIT"
]
| null | null | null | 1.4 R Lists/de-DE/.ipynb_checkpoints/1.4.22 R - Lists-checkpoint.ipynb | softfactories/r_train_2 | ffa0530ba13c7b43f5f33a4141b1690647603141 | [
"MIT"
]
| null | null | null | 1.4 R Lists/de-DE/.ipynb_checkpoints/1.4.22 R - Lists-checkpoint.ipynb | softfactories/r_train_2 | ffa0530ba13c7b43f5f33a4141b1690647603141 | [
"MIT"
]
| null | null | null | 24.511905 | 212 | 0.344485 | [
[
[
"# Tag 1. Kapitel 4. Listen (Lists)\n\n## Lektion 22. R Listen Grundlagen\n\nWir kennen nun Vektoren, Matrizen und Data Frames. Als letztes im Kapitel der R Grundlagen können wir uns nun die eingebaute Daten Struktur \"Liste\" anschauen.\n\nListen erlauben es uns eine Vielzahl an Daten Strukturen innerhalb einer einzigen Variable zu speichern. Das heißt, einen Vektor, eine Matrix und/oder einen Data Frame; alles innerhalb einer einzigen Liste.",
"_____no_output_____"
]
],
[
[
"# Vektor erstellen\nv <- c(1,2,3,4,5)\n\n# Matrix erstellen\nm <- matrix(1:10,nrow=2)\n\n# Data Frame erstellen\ndf <- women",
"_____no_output_____"
],
[
"v",
"_____no_output_____"
],
[
"m",
"_____no_output_____"
],
[
"df",
"_____no_output_____"
]
],
[
[
"## Die Nutzung von list()\n\nWir können nun die `list()` Funktion verwenden, um alle Datenstrukturen zu kombinieren:",
"_____no_output_____"
]
],
[
[
"li <- list(v,m,df)",
"_____no_output_____"
],
[
"li",
"_____no_output_____"
]
],
[
[
"Dabei fällt auf, dass `list()` allen Objekten in der Liste eine Nummer zugeordnet hat. Diese Nummern können wir wie folgt durch Namen ersetzen:",
"_____no_output_____"
]
],
[
[
"li <- list(beispiel_vek = v,beispiel_mat = m, beispiel_df = df)",
"_____no_output_____"
],
[
"li",
"_____no_output_____"
]
],
[
[
"### Objekte aus Listen auswählen\n\nWir können die Klammern-Notation nutzen, um Objekte aus einer Liste anzuzeigen. Und doppelte Klammern, um den tatsächlichen Inhalt des Objektes zu erhalten. Schauen wir uns das beispielhaft an:",
"_____no_output_____"
]
],
[
[
"# Einfache Klammern\nli[1] # Nach Index",
"_____no_output_____"
],
[
"# Nach Namen\nli['beispiel_vek']",
"_____no_output_____"
],
[
"# Beachtete den Typ\nclass(li['beispiel_vek'])",
"_____no_output_____"
],
[
"# Doppelte Klammern um den tatsächlichen Inhalt eines Objektes zu erhalten\nli[['beispiel_vek']]",
"_____no_output_____"
],
[
"# Wir können auch die $ Notation verwenden\nli$beispiel_vek",
"_____no_output_____"
]
],
[
[
"Zusätzlich können wir indexieren, sobald wir ein Objekt aus der Liste ausgewählt haben.",
"_____no_output_____"
]
],
[
[
"li[['beispiel_vek']][1]",
"_____no_output_____"
],
[
"li[['beispiel_mat']]",
"_____no_output_____"
],
[
"li[['beispiel_mat']][1,]",
"_____no_output_____"
],
[
"li[['beispiel_mat']][1:2,1:2]",
"_____no_output_____"
],
[
"li[['beispiel_df']]['height']",
"_____no_output_____"
]
],
[
[
"# Listen kombinieren\n\nListen können außerdem auch andere Listen beinhalten. Wir können Listen durch die bereits bekannte Funktion `c()` kombinieren:",
"_____no_output_____"
]
],
[
[
"doppelte_liste <- c(li,li)",
"_____no_output_____"
],
[
"doppelte_liste",
"_____no_output_____"
],
[
"str(doppelte_liste)",
"List of 6\n $ beispiel_vek: num [1:5] 1 2 3 4 5\n $ beispiel_mat: int [1:2, 1:5] 1 2 3 4 5 6 7 8 9 10\n $ beispiel_df :'data.frame':\t15 obs. of 2 variables:\n ..$ height: num [1:15] 58 59 60 61 62 63 64 65 66 67 ...\n ..$ weight: num [1:15] 115 117 120 123 126 129 132 135 139 142 ...\n $ beispiel_vek: num [1:5] 1 2 3 4 5\n $ beispiel_mat: int [1:2, 1:5] 1 2 3 4 5 6 7 8 9 10\n $ beispiel_df :'data.frame':\t15 obs. of 2 variables:\n ..$ height: num [1:15] 58 59 60 61 62 63 64 65 66 67 ...\n ..$ weight: num [1:15] 115 117 120 123 126 129 132 135 139 142 ...\n"
]
],
[
[
"Herzlichen Glückwunsch! Sie sind mit Lektion 22 fertig!",
"_____no_output_____"
]
]
]
| [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
]
| [
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
]
]
|
cb5d431820e8de8cbdad6d00839c37167c0c2552 | 1,771 | ipynb | Jupyter Notebook | preprocessing.ipynb | Karmantez/Titanic_Survivor_Prediction | 1dc49f9e27009e09cb2d4a7f2f5cf86a287dd45c | [
"MIT"
]
| null | null | null | preprocessing.ipynb | Karmantez/Titanic_Survivor_Prediction | 1dc49f9e27009e09cb2d4a7f2f5cf86a287dd45c | [
"MIT"
]
| null | null | null | preprocessing.ipynb | Karmantez/Titanic_Survivor_Prediction | 1dc49f9e27009e09cb2d4a7f2f5cf86a287dd45c | [
"MIT"
]
| null | null | null | 22.705128 | 67 | 0.519481 | [
[
[
"import numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder",
"_____no_output_____"
],
[
"def process_null_data(df):\n df['Age'].fillna(df['Age'].mean(), inplace=True)\n df['Cabin'].fillna('N', inplace=True)\n df['Embarked'].fillna('N', inplace=True)\n df['Fare'].fillna(0, inplace=True)\n return df",
"_____no_output_____"
],
[
"def drop_unnecessary_features(df):\n df.drop(['Name','Ticket'],axis=1,inplace=True)\n return df",
"_____no_output_____"
],
[
"def process_label_encoding(df):\n df['Cabin'] = df['Cabin'].str[:1]\n \n for feature in ['Cabin','Sex','Embarked']:\n label_encoder = LabelEncoder()\n label_encoder = label_encoder.fit(df[feature])\n df[feature] = label_encoder.transform(df[feature])\n return df ",
"_____no_output_____"
]
]
]
| [
"code"
]
| [
[
"code",
"code",
"code",
"code"
]
]
|
cb5d4607917c6aad0f441df309adf63070ce276b | 11,277 | ipynb | Jupyter Notebook | module3/s9_gensim.ipynb | BamBalaam/tac | 340f6ac3b747eb9ea5f035f0b01638eb09c99f03 | [
"MIT"
]
| 1 | 2020-11-07T17:18:55.000Z | 2020-11-07T17:18:55.000Z | module3/s9_gensim.ipynb | BamBalaam/tac | 340f6ac3b747eb9ea5f035f0b01638eb09c99f03 | [
"MIT"
]
| null | null | null | module3/s9_gensim.ipynb | BamBalaam/tac | 340f6ac3b747eb9ea5f035f0b01638eb09c99f03 | [
"MIT"
]
| null | null | null | 46.217213 | 1,038 | 0.66915 | [
[
[
" # Getting Started with gensim",
"_____no_output_____"
],
[
"This section introduces the basic concepts and terms needed to understand and use `gensim` and provides a simple usage example.\n\n## Core Concepts and Simple Example\n\nAt a very high-level, `gensim` is a tool for discovering the semantic structure of documents by examining the patterns of words (or higher-level structures such as entire sentences or documents). `gensim` accomplishes this by taking a *corpus*, a collection of text documents, and producing a *vector* representation of the text in the corpus. The vector representation can then be used to train a *model*, which is an algorithms to create different representations of the data, which are usually more semantic. These three concepts are key to understanding how `gensim` works so let's take a moment to explain what each of them means. At the same time, we'll work through a simple example that illustrates each of them.\n\n### Corpus\n\nA *corpus* is a collection of digital documents. This collection is the input to `gensim` from which it will infer the structure of the documents, their topics, etc. The latent structure inferred from the corpus can later be used to assign topics to new documents which were not present in the training corpus. For this reason, we also refer to this collection as the *training corpus*. No human intervention (such as tagging the documents by hand) is required - the topic classification is [unsupervised](https://en.wikipedia.org/wiki/Unsupervised_learning).\n\nFor our corpus, we'll use a list of 9 strings, each consisting of only a single sentence.",
"_____no_output_____"
]
],
[
[
"raw_corpus = [\"Human machine interface for lab abc computer applications\",\n \"A survey of user opinion of computer system response time\",\n \"The EPS user interface management system\",\n \"System and human system engineering testing of EPS\", \n \"Relation of user perceived response time to error measurement\",\n \"The generation of random binary unordered trees\",\n \"The intersection graph of paths in trees\",\n \"Graph minors IV Widths of trees and well quasi ordering\",\n \"Graph minors A survey\"]",
"_____no_output_____"
]
],
[
[
"This is a particularly small example of a corpus for illustration purposes. Another example could be a list of all the plays written by Shakespeare, list of all wikipedia articles, or all tweets by a particular person of interest.\n\nAfter collecting our corpus, there are typically a number of preprocessing steps we want to undertake. We'll keep it simple and just remove some commonly used English words (such as 'the') and words that occur only once in the corpus. In the process of doing so, we'll [tokenise][1] our data. Tokenization breaks up the documents into words (in this case using space as a delimiter).\n[1]: https://en.wikipedia.org/wiki/Tokenization_(lexical_analysis)",
"_____no_output_____"
]
],
[
[
"# Create a set of frequent words\nstoplist = set('for a of the and to in'.split(' '))\n# Lowercase each document, split it by white space and filter out stopwords\ntexts = [[word for word in document.lower().split() if word not in stoplist]\n for document in raw_corpus]\n\n# Count word frequencies\nfrom collections import defaultdict\nfrequency = defaultdict(int)\nfor text in texts:\n for token in text:\n frequency[token] += 1\n\n# Only keep words that appear more than once\nprocessed_corpus = [[token for token in text if frequency[token] > 1] for text in texts]\nprocessed_corpus",
"_____no_output_____"
]
],
[
[
"Before proceeding, we want to associate each word in the corpus with a unique integer ID. We can do this using the `gensim.corpora.Dictionary` class. This dictionary defines the vocabulary of all words that our processing knows about.",
"_____no_output_____"
]
],
[
[
"from gensim import corpora\n\ndictionary = corpora.Dictionary(processed_corpus)\nprint(dictionary)",
"_____no_output_____"
]
],
[
[
"Because our corpus is small, there are only 12 different tokens in this `Dictionary`. For larger corpuses, dictionaries that contains hundreds of thousands of tokens are quite common.",
"_____no_output_____"
],
[
"### Vector\n\nTo infer the latent structure in our corpus we need a way to represent documents that we can manipulate mathematically. One approach is to represent each document as a vector. There are various approaches for creating a vector representation of a document but a simple example is the *bag-of-words model*. Under the bag-of-words model each document is represented by a vector containing the frequency counts of each word in the dictionary. For example, given a dictionary containing the words `['coffee', 'milk', 'sugar', 'spoon']` a document consisting of the string `\"coffee milk coffee\"` could be represented by the vector `[2, 1, 0, 0]` where the entries of the vector are (in order) the occurrences of \"coffee\", \"milk\", \"sugar\" and \"spoon\" in the document. The length of the vector is the number of entries in the dictionary. One of the main properties of the bag-of-words model is that it completely ignores the order of the tokens in the document that is encoded, which is where the name bag-of-words comes from.\n\nOur processed corpus has 12 unique words in it, which means that each document will be represented by a 12-dimensional vector under the bag-of-words model. We can use the dictionary to turn tokenized documents into these 12-dimensional vectors. We can see what these IDs correspond to:",
"_____no_output_____"
]
],
[
[
"print(dictionary.token2id)",
"_____no_output_____"
]
],
[
[
"For example, suppose we wanted to vectorize the phrase \"Human computer interaction\" (note that this phrase was not in our original corpus). We can create the bag-of-word representation for a document using the `doc2bow` method of the dictionary, which returns a sparse representation of the word counts:",
"_____no_output_____"
]
],
[
[
"new_doc = \"Human computer interaction\"\nnew_vec = dictionary.doc2bow(new_doc.lower().split())\nnew_vec",
"_____no_output_____"
]
],
[
[
"The first entry in each tuple corresponds to the ID of the token in the dictionary, the second corresponds to the count of this token.",
"_____no_output_____"
],
[
"Note that \"interaction\" did not occur in the original corpus and so it was not included in the vectorization. Also note that this vector only contains entries for words that actually appeared in the document. Because any given document will only contain a few words out of the many words in the dictionary, words that do not appear in the vectorization are represented as implicitly zero as a space saving measure.\n\nWe can convert our entire original corpus to a list of vectors:",
"_____no_output_____"
]
],
[
[
"bow_corpus = [dictionary.doc2bow(text) for text in processed_corpus]\nbow_corpus",
"_____no_output_____"
]
],
[
[
"Note that while this list lives entirely in memory, in most applications you will want a more scalable solution. Luckily, `gensim` allows you to use any iterator that returns a single document vector at a time. See the documentation for more details.\n\n### Model\n\nNow that we have vectorized our corpus we can begin to transform it using *models*. We use model as an abstract term referring to a transformation from one document representation to another. In `gensim` documents are represented as vectors so a model can be thought of as a transformation between two vector spaces. The details of this transformation are learned from the training corpus.\n\nOne simple example of a model is [tf-idf](https://en.wikipedia.org/wiki/Tf%E2%80%93idf). The tf-idf model transforms vectors from the bag-of-words representation to a vector space where the frequency counts are weighted according to the relative rarity of each word in the corpus.\n\nHere's a simple example. Let's initialize the tf-idf model, training it on our corpus and transforming the string \"system minors\":",
"_____no_output_____"
]
],
[
[
"from gensim import models\n# train the model\ntfidf = models.TfidfModel(bow_corpus)\n# transform the \"system minors\" string\ntfidf[dictionary.doc2bow(\"system minors\".lower().split())]",
"_____no_output_____"
]
],
[
[
"The `tfidf` model again returns a list of tuples, where the first entry is the token ID and the second entry is the tf-idf weighting. Note that the ID corresponding to \"system\" (which occurred 4 times in the original corpus) has been weighted lower than the ID corresponding to \"minors\" (which only occurred twice).\n\n`gensim` offers a number of different models/transformations. See [Transformations and Topics](Topics_and_Transformations.ipynb) for details.",
"_____no_output_____"
]
]
]
| [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
]
| [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
]
|
cb5d4adc877dd22c03b2dbaff530302d7eea4d12 | 362,133 | ipynb | Jupyter Notebook | notebooks/VGG_Net.ipynb | yassersouri/omgh | f4ae38d84b8c1a32d034d292d75f3fa2c49ec817 | [
"MIT"
]
| 17 | 2015-01-26T08:02:07.000Z | 2019-02-21T11:54:28.000Z | notebooks/VGG_Net.ipynb | yassersouri/omgh | f4ae38d84b8c1a32d034d292d75f3fa2c49ec817 | [
"MIT"
]
| 4 | 2015-02-25T03:27:07.000Z | 2015-02-25T03:27:07.000Z | notebooks/VGG_Net.ipynb | yassersouri/omgh | f4ae38d84b8c1a32d034d292d75f3fa2c49ec817 | [
"MIT"
]
| 21 | 2015-02-16T20:22:53.000Z | 2021-05-22T12:34:05.000Z | 1,316.847273 | 195,963 | 0.946829 | [
[
[
"empty"
]
]
]
| [
"empty"
]
| [
[
"empty"
]
]
|
cb5d6ea78ac9a89b0bf891f757250799a91bcbd9 | 18,970 | ipynb | Jupyter Notebook | chapter01/chapter01.ipynb | will-i-amv-books/getting-clojure | 66b3b4672fd0fab4ca3e9838a79ab00c0fbfda30 | [
"MIT"
]
| null | null | null | chapter01/chapter01.ipynb | will-i-amv-books/getting-clojure | 66b3b4672fd0fab4ca3e9838a79ab00c0fbfda30 | [
"MIT"
]
| null | null | null | chapter01/chapter01.ipynb | will-i-amv-books/getting-clojure | 66b3b4672fd0fab4ca3e9838a79ab00c0fbfda30 | [
"MIT"
]
| null | null | null | 20.052854 | 100 | 0.478387 | [
[
[
"# Hello, Clojure\n",
"_____no_output_____"
],
[
"Hello World",
"_____no_output_____"
]
],
[
[
"(println \"Hello, world!\") ; Say hi",
"_____no_output_____"
],
[
";; Double semicolons are used if the comment is all alone on its own line\n\n(println \"Hello, world!\") ; A single semicolon is used at the end of a line with some code\n",
"Hello, world!\n"
]
],
[
[
"Basic string manipulation",
"_____no_output_____"
]
],
[
[
";; Concat strings\n\n(str \"Clo\" \"jure\") ",
"Hello, world!\n"
],
[
";; Concat strings oand numbers\n\n(str 3 \" \" 2 \" \" 1 \" Blast off!\")\n",
"_____no_output_____"
],
[
";; Count the number of characters of a string\n\n(count \"Hello, world\")\n",
"_____no_output_____"
]
],
[
[
"Booleans",
"_____no_output_____"
]
],
[
[
"(println true) ; Prints true...\n",
"true\n"
],
[
"(println false) ; ...and prints false.\n",
"false\n"
]
],
[
[
"Nil",
"_____no_output_____"
]
],
[
[
"(println \"Nobody's home:\" nil) ; Prints Nobody's home: nil\n",
"Nobody's home: nil\n"
],
[
"(println \"We can print many things:\" true false nil)\n",
"We can print many things: true false nil\n"
]
],
[
[
"Basic Arithmetic operations",
"_____no_output_____"
]
],
[
[
";; A simple sum example\n\n(+ 1900 84)",
"_____no_output_____"
],
[
";; A simple product example\n\n(* 16 124) \n",
"_____no_output_____"
],
[
";; A simple substraction example\n\n(- 2000 16) ; 1984 again.\n",
"_____no_output_____"
],
[
";; A simple division example\n\n(/ 25792 13)",
"_____no_output_____"
],
[
";; A simple average example\n\n(/ (+ 1984 2010) 2)\n",
"_____no_output_____"
],
[
";; EVERYTHING in clojure is evaluated as follows\n\n\"\"\"\n(verb argument argument argument...)\n\"\"\"",
"_____no_output_____"
],
[
";; The math operators take an arbitrary number of args\n\n(+ 1000 500 500 1) ; Evaluates to 2001.\n",
"_____no_output_____"
],
[
";; The average of 2 numbers using floating-point numbers\n\n(/ (+ 1984.0 2010.0) 2.0)\n",
"_____no_output_____"
],
[
";; Adding an integer to a float returns a float\n\n(+ 1984 2010.0)",
"_____no_output_____"
]
],
[
[
"Not Variable Assignment, but Close",
"_____no_output_____"
]
],
[
[
";; Binding a symbol (first-name) to a value (\"Russ\")\n\n(def first-name \"Russ\")\n",
"_____no_output_____"
],
[
";; 'def' can accept any expression\n\n(def the-average (/ (+ 20 40.0) 2.0))\n",
"_____no_output_____"
]
],
[
[
"Basic function definitions\n",
"_____no_output_____"
]
],
[
[
";; A simple function without args\n\n(defn hello-world [] \n (println \"Hello, world!\"))\n\n(hello-world)",
"Hello, world!\n"
],
[
";; A function with 1 arg\n\n(defn say-welcome [what]\n (println \"Welcome to\" what))\n\n(say-welcome \"Clojure\")\n",
"Welcome to Clojure\n"
],
[
";; A simple average function\n\n(defn average [a b] ; No commas between args\n (/ (+ a b) 2.0))\n\n(average 5.0 10.0)\n",
"_____no_output_____"
],
[
";; A more verbose average function\n\n(defn chatty-average [a b]\n (println \"chatty-average function called\")\n (println \"** first argument:\" a)\n (println \"** second argument:\" b)\n (/ (+ a b) 2.0))\n\n(chatty-average 10 20)\n",
"chatty-average function called\n** first argument: 10\n** second argument: 20\n"
]
],
[
[
"Introduction to Leiningen",
"_____no_output_____"
]
],
[
[
";; Execute the following command to start a new Clojure project skeleton\n\n\"\"\"\n!lein new app blottsbooks\n\"\"\"",
"_____no_output_____"
],
[
";; Add the following code to core.clj, located at ./blottsbooks/src/blottsbooks/core.clj\n\n(ns blottsbooks.core ; :gen-class instructs that the namespace should be compiled\n (:gen-class))\n\n(defn say-welcome [what]\n (println \"Welcome to\" what \"!\"))\n\n(defn -main [] ; The main function\n (say-welcome \"Blotts Books\"))\n",
"_____no_output_____"
],
[
";; Execute the following command to execute the last snippet\n\n\"\"\"\n!cd ./blottsbooks \n!lein run\n\"\"\"",
"_____no_output_____"
],
[
"(ns user)",
"_____no_output_____"
]
],
[
[
"Common Clojure errors",
"_____no_output_____"
]
],
[
[
";; Division by zero\n\n(/ 100 0)\n",
"Execution error (ArithmeticException) at user/eval4169 (REPL:3).\nDivide by zero\n"
],
[
";; Typo when calling a function\n\n(catty-average)\n",
"Syntax error compiling at (REPL:3:1).\nUnable to resolve symbol: catty-average in this context\n"
],
[
";; Too many parentheses\n\n(+ (* 2 2) 10))\n",
"Syntax error reading source at (REPL:3:16).\nUnmatched delimiter: )\n"
],
[
";; Too few parentheses\n\n(+ (* 2 2) 10",
"Syntax error reading source at (REPL:3:1).\nEOF while reading, starting at line 3\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"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
]
|
cb5d75fa13edb4822777316c889a586bdbe31242 | 27,436 | ipynb | Jupyter Notebook | Regression/Test-Train Split.ipynb | DiptoChakrabarty/Data-Science-with-Ml | 7fad91eec275935e26edc171c6a2169b79c44f42 | [
"MIT"
]
| 4 | 2019-03-11T05:30:32.000Z | 2019-04-04T08:31:36.000Z | Regression/Test-Train Split.ipynb | DiptoChakrabarty/Data-Science-with-Ml | 7fad91eec275935e26edc171c6a2169b79c44f42 | [
"MIT"
]
| null | null | null | Regression/Test-Train Split.ipynb | DiptoChakrabarty/Data-Science-with-Ml | 7fad91eec275935e26edc171c6a2169b79c44f42 | [
"MIT"
]
| null | null | null | 68.934673 | 12,232 | 0.82348 | [
[
[
"import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"data=pd.read_csv(\"Salary_Data.csv\")",
"_____no_output_____"
]
],
[
[
"# Splitting the dataset",
"_____no_output_____"
]
],
[
[
"X=data.iloc[:,0:1]\ny=data.iloc[:,1]",
"_____no_output_____"
],
[
"X.shape",
"_____no_output_____"
],
[
"y.shape",
"_____no_output_____"
]
],
[
[
"##SPLITTING DATASET INTO TRAIN AND TEST PARTS",
"_____no_output_____"
]
],
[
[
"#This splits dataset into train:test= 70:30 part and selects data randomly\nX_train,X_test,Y_train,Y_test=train_test_split(X,y,test_size=0.30,random_state=42)",
"_____no_output_____"
],
[
"print(\"Training Shapes of X and y \",X_train.shape,Y_train.shape)\nprint(\"\\n\")\nprint(\"Testing Shapes of X and y \",X_test.shape,Y_test.shape)",
"Training Shapes of X and y (21, 1) (21,)\n\n\nTesting Shapes of X and y (9, 1) (9,)\n"
]
],
[
[
"# Training the model",
"_____no_output_____"
]
],
[
[
"model=LinearRegression()",
"_____no_output_____"
],
[
"model.fit(X_train,Y_train)",
"_____no_output_____"
]
],
[
[
"# Predicting the values ",
"_____no_output_____"
]
],
[
[
"predictions=model.predict(X_test)",
"_____no_output_____"
],
[
"predictions.shape",
"_____no_output_____"
],
[
"predictions",
"_____no_output_____"
],
[
"final=pd.DataFrame(predictions)",
"_____no_output_____"
],
[
"final.head()",
"_____no_output_____"
]
],
[
[
"# Plotting the predictions vs original result",
"_____no_output_____"
]
],
[
[
"plt.scatter(X_train,Y_train)",
"_____no_output_____"
],
[
"plt.plot(X_test,predictions ,color='red')\nplt.scatter(X_test,Y_test,color='green')",
"_____no_output_____"
]
]
]
| [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
]
| [
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
]
|
cb5d8791d910fe5817ece6abf6cf6e778b772a16 | 11,439 | ipynb | Jupyter Notebook | Sqrt_Numpy-Numba.ipynb | prisae/tmp-share | c09713f6860106cdf203b0644077ed276a9412ca | [
"MIT"
]
| 9 | 2018-08-06T18:03:27.000Z | 2019-05-10T16:51:10.000Z | Sqrt_Numpy-Numba.ipynb | prisae/tmp-share | c09713f6860106cdf203b0644077ed276a9412ca | [
"MIT"
]
| null | null | null | Sqrt_Numpy-Numba.ipynb | prisae/tmp-share | c09713f6860106cdf203b0644077ed276a9412ca | [
"MIT"
]
| 4 | 2018-09-27T13:53:18.000Z | 2020-02-13T07:14:28.000Z | 35.746875 | 224 | 0.508261 | [
[
[
"# Simple Test between NumPy and Numba\n\n$$\n\\Gamma = \\sqrt{\\frac{\\eta_H}{\\eta_V} \\kappa^2 + \\eta_H \\zeta_H}\n$$",
"_____no_output_____"
]
],
[
[
"import numba\nimport cython\nimport numexpr\nimport numpy as np\n\n%load_ext cython",
"_____no_output_____"
],
[
"# Used cores by numba can be shown with (xy default all cores are used):\n#print(numba.config.NUMBA_DEFAULT_NUM_THREADS)\n\n# This can be changed with the following line\n#numba.config.NUMBA_NUM_THREADS = 4",
"_____no_output_____"
],
[
"from empymod import filters\nfrom scipy.constants import mu_0 # Magn. permeability of free space [H/m]\nfrom scipy.constants import epsilon_0 # Elec. permittivity of free space [F/m]\n\nres = np.array([2e14, 0.3, 1, 50, 1]) # nlay\nfreq = np.arange(1, 201)/20. # nfre\noff = np.arange(1, 101)*1000 # noff\nlambd = filters.key_201_2009().base/off[:, None] # nwav\n\naniso = np.array([1, 1, 1.5, 2, 1])\nepermH = np.array([1, 80, 9, 20, 1])\nepermV = np.array([1, 40, 9, 10, 1])\nmpermH = np.array([1, 1, 3, 5, 1])\n\netaH = 1/res + np.outer(2j*np.pi*freq, epermH*epsilon_0)\netaV = 1/(res*aniso*aniso) + np.outer(2j*np.pi*freq, epermV*epsilon_0)\nzetaH = np.outer(2j*np.pi*freq, mpermH*mu_0)",
"_____no_output_____"
]
],
[
[
"## NumPy\n\nNumpy version to check result and compare times",
"_____no_output_____"
]
],
[
[
"def test_numpy(eH, eV, zH, l):\n return np.sqrt((eH/eV) * (l*l) + (zH*eH))",
"_____no_output_____"
]
],
[
[
"## Numba @vectorize\n\nThis is exactly the same function as with NumPy, just added the @vectorize decorater.",
"_____no_output_____"
]
],
[
[
"@numba.vectorize('c16(c16, c16, c16, f8)')\ndef test_numba_vnp(eH, eV, zH, l):\n return np.sqrt((eH/eV) * (l*l) + (zH*eH))\n\[email protected]('c16(c16, c16, c16, f8)', target='parallel')\ndef test_numba_v(eH, eV, zH, l):\n return np.sqrt((eH/eV) * (l*l) + (zH*eH))",
"_____no_output_____"
]
],
[
[
"## Numba @njit",
"_____no_output_____"
]
],
[
[
"@numba.njit\ndef test_numba_nnp(eH, eV, zH, l):\n o1, o3 = eH.shape \n o2, o4 = l.shape \n out = np.empty((o1, o2, o3, o4), dtype=numba.complex128)\n for nf in numba.prange(o1):\n for nl in numba.prange(o3):\n ieH = eH[nf, nl]\n ieV = eV[nf, nl]\n izH = zH[nf, nl]\n for no in numba.prange(o2):\n for ni in numba.prange(o4):\n il = l[no, ni]\n out[nf, no, nl, ni] = np.sqrt(ieH/ieV * il*il + izH*ieH)\n return out\n \[email protected](nogil=True, parallel=True)\ndef test_numba_n(eH, eV, zH, l):\n o1, o3 = eH.shape \n o2, o4 = l.shape \n out = np.empty((o1, o2, o3, o4), dtype=numba.complex128)\n for nf in numba.prange(o1):\n for nl in numba.prange(o3):\n ieH = eH[nf, nl]\n ieV = eV[nf, nl]\n izH = zH[nf, nl]\n for no in numba.prange(o2):\n for ni in numba.prange(o4):\n il = l[no, ni]\n out[nf, no, nl, ni] = np.sqrt(ieH/ieV * il*il + izH*ieH)\n return out",
"_____no_output_____"
]
],
[
[
"## Run comparison for a small and a big matrix",
"_____no_output_____"
]
],
[
[
"eH = etaH[:, None, :, None]\neV = etaV[:, None, :, None]\nzH = zetaH[:, None, :, None]\nl = lambd[None, :, None, :]\n\n# Output shape\nout_shape = (freq.size, off.size, res.size, filters.key_201_2009().base.size)\n\nprint(' Shape Test Matrix ::', out_shape, '; total # elements:: '+str(freq.size*off.size*res.size*filters.key_201_2009().base.size))\nprint('------------------------------------------------------------------------------------------')\n\nprint(' NumPy :: ', end='')\n# Get NumPy result for comparison\nnumpy_result = test_numpy(eH, eV, zH, l)\n# Get runtime\n%timeit test_numpy(eH, eV, zH, l)\n\nprint(' Numba @vectorize :: ', end='')\n# Ensure it agrees with NumPy\nnumba_vnp_result = test_numba_vnp(eH, eV, zH, l)\nif not np.allclose(numpy_result, numba_vnp_result, atol=0, rtol=1e-10):\n print(' * FAIL, DOES NOT AGREE WITH NumPy RESULT!')\n# Get runtime\n%timeit test_numba_vnp(eH, eV, zH, l)\n\nprint(' Numba @vectorize par :: ', end='')\n# Ensure it agrees with NumPy\nnumba_v_result = test_numba_v(eH, eV, zH, l)\nif not np.allclose(numpy_result, numba_v_result, atol=0, rtol=1e-10):\n print(' * FAIL, DOES NOT AGREE WITH NumPy RESULT!')\n# Get runtime\n%timeit test_numba_v(eH, eV, zH, l)\n\nprint(' Numba @njit :: ', end='')\n# Ensure it agrees with NumPy\nnumba_nnp_result = test_numba_nnp(etaH, etaV, zetaH, lambd)\nif not np.allclose(numpy_result, numba_nnp_result, atol=0, rtol=1e-10):\n print(' * FAIL, DOES NOT AGREE WITH NumPy RESULT!')\n# Get runtime\n%timeit test_numba_nnp(etaH, etaV, zetaH, lambd)\n\nprint(' Numba @njit par :: ', end='')\n# Ensure it agrees with NumPy\nnumba_n_result = test_numba_n(etaH, etaV, zetaH, lambd)\nif not np.allclose(numpy_result, numba_n_result, atol=0, rtol=1e-10):\n print(' * FAIL, DOES NOT AGREE WITH NumPy RESULT!')\n# Get runtime\n%timeit test_numba_n(etaH, etaV, zetaH, lambd)",
" Shape Test Matrix :: (200, 100, 5, 201) ; total # elements:: 20100000\n------------------------------------------------------------------------------------------\n NumPy :: 1.02 s ± 27.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n Numba @vectorize :: 966 ms ± 12 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n Numba @vectorize par :: 781 ms ± 12 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n Numba @njit :: 688 ms ± 12.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n Numba @njit par :: 368 ms ± 16.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
],
[
"from empymod import versions\nversions('HTML', add_pckg=[cython, numba], ncol=5)",
"_____no_output_____"
]
]
]
| [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
]
| [
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
]
|
cb5da2d95002f275842e89809491a015f461a7ce | 102,390 | ipynb | Jupyter Notebook | Data Visualization/Histograms.ipynb | SabinoGs/DataAnalysisEducation | e66740afa286589309bdadb657397270d0b7a320 | [
"MIT"
]
| null | null | null | Data Visualization/Histograms.ipynb | SabinoGs/DataAnalysisEducation | e66740afa286589309bdadb657397270d0b7a320 | [
"MIT"
]
| 5 | 2020-02-24T18:10:35.000Z | 2021-02-02T21:46:00.000Z | Data Visualization/Histograms.ipynb | SabinoGs/DataAnalysisEducation | e66740afa286589309bdadb657397270d0b7a320 | [
"MIT"
]
| null | null | null | 407.928287 | 49,392 | 0.931077 | [
[
[
"import seaborn as sns\nimport numpy as np\nimport pandas as pd\nfrom numpy.random import randn\nfrom scipy import stats\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
],
[
"data_set_1 = randn(100)",
"_____no_output_____"
],
[
"plt.hist(data_set_1)",
"_____no_output_____"
],
[
"\"\"\"\nMais informações sobre os argumentos de plt.hist:\nhttps://matplotlib.org/devdocs/api/_as_gen/matplotlib.pyplot.hist.html\n\n\"\"\"\ndata_set_2 = randn(80)\nplt.hist(data_set_2,color='indianred')",
"_____no_output_____"
],
[
"\"\"\"\nComo juntar os 2 histogramas acima?\n\nPrecisamos somente chamar 2 vezes o plot. \n\"\"\"\nplt.hist(data_set_1,normed=True,color='indianred',alpha=0.5,bins=20)\nplt.hist(data_set_2,normed=True,color='blue',alpha=0.5,bins=20)",
"_____no_output_____"
],
[
"data1 = randn(1000)\ndata2 = randn(1000)",
"_____no_output_____"
],
[
"sns.jointplot(data1,data2)",
"_____no_output_____"
],
[
"\"\"\"\nhttps://seaborn.pydata.org/generated/seaborn.jointplot.html\n\"\"\"\n\nsns.jointplot(data1,data2,kind='hex')",
"_____no_output_____"
]
]
]
| [
"code"
]
| [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
]
|
cb5da967868ba0433ad9dfaabe5d7669b93a4c69 | 19,794 | ipynb | Jupyter Notebook | final-project/Pyspark Linear Regression.ipynb | Andre-Williams22/Data-Science-In-Production | 80b1c68361101116929460521a0dbee59cd1c6a2 | [
"MIT"
]
| null | null | null | final-project/Pyspark Linear Regression.ipynb | Andre-Williams22/Data-Science-In-Production | 80b1c68361101116929460521a0dbee59cd1c6a2 | [
"MIT"
]
| null | null | null | final-project/Pyspark Linear Regression.ipynb | Andre-Williams22/Data-Science-In-Production | 80b1c68361101116929460521a0dbee59cd1c6a2 | [
"MIT"
]
| null | null | null | 38.811765 | 183 | 0.490603 | [
[
[
"## Import Libraries",
"_____no_output_____"
]
],
[
[
"from pyspark.sql import SparkSession\nspark= SparkSession.builder.appName('Customers').getOrCreate()",
"_____no_output_____"
],
[
"from pyspark.ml.regression import LinearRegression\n",
"_____no_output_____"
],
[
"dataset=spark.read.csv(\"Ecommerce_Customers.csv\",inferSchema=True,header=True)",
"_____no_output_____"
]
],
[
[
"## Perform EDA",
"_____no_output_____"
]
],
[
[
"dataset",
"_____no_output_____"
],
[
"dataset.show()",
"+--------------------+--------------------+------------------+-----------+---------------+--------------------+-------------------+\n| Email| Address|Avg Session Length|Time on App|Time on Website|Length of Membership|Yearly Amount Spent|\n+--------------------+--------------------+------------------+-----------+---------------+--------------------+-------------------+\n|mstephenson@ferna...|835 Frank TunnelW...| 34.49726773|12.65565115| 39.57766802| 4.082620633| 587.951054|\n| [email protected]|4547 Archer Commo...| 31.92627203|11.10946073| 37.26895887| 2.664034182| 392.2049334|\n| [email protected]|24645 Valerie Uni...| 33.00091476|11.33027806| 37.11059744| 4.104543202| 487.5475049|\n|riverarebecca@gma...|1414 David Throug...| 34.30555663|13.71751367| 36.72128268| 3.120178783| 581.852344|\n|mstephens@davidso...|14023 Rodriguez P...| 33.33067252|12.79518855| 37.5366533| 4.446308318| 599.406092|\n|alvareznancy@luca...|645 Martha Park A...| 33.87103788|12.02692534| 34.47687763| 5.493507201| 637.1024479|\n|katherine20@yahoo...|68388 Reyes Light...| 32.0215955|11.36634831| 36.68377615| 4.685017247| 521.5721748|\n| [email protected]|Unit 6538 Box 898...| 32.73914294|12.35195897| 37.37335886| 4.434273435| 549.9041461|\n|vchurch@walter-ma...|860 Lee KeyWest D...| 33.9877729|13.38623528| 37.53449734| 3.273433578| 570.200409|\n| [email protected]|PSC 2734, Box 525...| 31.93654862|11.81412829| 37.14516822| 3.202806072| 427.1993849|\n|andrew06@peterson...|26104 Alexander G...| 33.99257277|13.33897545| 37.22580613| 2.482607771| 492.6060127|\n|ryanwerner@freema...|Unit 2413 Box 034...| 33.87936082| 11.584783| 37.08792607| 3.713209203| 522.3374046|\n| [email protected]|6705 Miller Orcha...| 29.53242897| 10.9612984| 37.42021558| 4.046423164| 408.6403511|\n|wrightpeter@yahoo...|05302 Dunlap Ferr...| 33.19033404|12.95922609| 36.1446667| 3.918541839| 573.4158673|\n|taylormason@gmail...|7773 Powell Sprin...| 32.38797585|13.14872569| 36.61995708| 2.494543647| 470.4527333|\n| [email protected]|49558 Ramirez Roa...| 30.73772037|12.63660605| 36.21376309| 3.357846842| 461.7807422|\n| [email protected]|6362 Wilson Mount...| 32.1253869|11.73386169| 34.89409275| 3.136132716| 457.8476959|\n|rebecca45@hale-ba...|8982 Burton RowWi...| 32.33889932|12.01319469| 38.38513659| 2.420806161| 407.7045475|\n|alejandro75@hotma...|64475 Andre Club ...| 32.18781205|14.71538754| 38.24411459| 1.516575581| 452.3156755|\n|samuel46@love-wes...|544 Alexander Hei...| 32.61785606|13.98959256| 37.1905038| 4.06454855| 605.0610388|\n+--------------------+--------------------+------------------+-----------+---------------+--------------------+-------------------+\nonly showing top 20 rows\n\n"
],
[
"dataset.printSchema()",
"root\n |-- Email: string (nullable = true)\n |-- Address: string (nullable = true)\n |-- Avg Session Length: double (nullable = true)\n |-- Time on App: double (nullable = true)\n |-- Time on Website: double (nullable = true)\n |-- Length of Membership: double (nullable = true)\n |-- Yearly Amount Spent: double (nullable = true)\n\n"
],
[
"sklearn\n\nx1,X2,X3,X4,X5 Y1 ---->model-->prediction\n\n[X1,X2,X3,X4,X5] Y1---->model--->prediction",
"_____no_output_____"
],
[
"from pyspark.ml.linalg import Vectors\nfrom pyspark.ml.feature import VectorAssembler",
"_____no_output_____"
],
[
"featureassembler=VectorAssembler(inputCols=[\"Avg Session Length\",\"Time on App\",\"Time on Website\",\"Length of Membership\"],outputCol=\"Independent Features\")",
"_____no_output_____"
],
[
"output=featureassembler.transform(dataset)",
"_____no_output_____"
],
[
"output.show()",
"+--------------------+--------------------+------------------+-----------+---------------+--------------------+-------------------+--------------------+\n| Email| Address|Avg Session Length|Time on App|Time on Website|Length of Membership|Yearly Amount Spent|Independent Features|\n+--------------------+--------------------+------------------+-----------+---------------+--------------------+-------------------+--------------------+\n|mstephenson@ferna...|835 Frank TunnelW...| 34.49726773|12.65565115| 39.57766802| 4.082620633| 587.951054|[34.49726773,12.6...|\n| [email protected]|4547 Archer Commo...| 31.92627203|11.10946073| 37.26895887| 2.664034182| 392.2049334|[31.92627203,11.1...|\n| [email protected]|24645 Valerie Uni...| 33.00091476|11.33027806| 37.11059744| 4.104543202| 487.5475049|[33.00091476,11.3...|\n|riverarebecca@gma...|1414 David Throug...| 34.30555663|13.71751367| 36.72128268| 3.120178783| 581.852344|[34.30555663,13.7...|\n|mstephens@davidso...|14023 Rodriguez P...| 33.33067252|12.79518855| 37.5366533| 4.446308318| 599.406092|[33.33067252,12.7...|\n|alvareznancy@luca...|645 Martha Park A...| 33.87103788|12.02692534| 34.47687763| 5.493507201| 637.1024479|[33.87103788,12.0...|\n|katherine20@yahoo...|68388 Reyes Light...| 32.0215955|11.36634831| 36.68377615| 4.685017247| 521.5721748|[32.0215955,11.36...|\n| [email protected]|Unit 6538 Box 898...| 32.73914294|12.35195897| 37.37335886| 4.434273435| 549.9041461|[32.73914294,12.3...|\n|vchurch@walter-ma...|860 Lee KeyWest D...| 33.9877729|13.38623528| 37.53449734| 3.273433578| 570.200409|[33.9877729,13.38...|\n| [email protected]|PSC 2734, Box 525...| 31.93654862|11.81412829| 37.14516822| 3.202806072| 427.1993849|[31.93654862,11.8...|\n|andrew06@peterson...|26104 Alexander G...| 33.99257277|13.33897545| 37.22580613| 2.482607771| 492.6060127|[33.99257277,13.3...|\n|ryanwerner@freema...|Unit 2413 Box 034...| 33.87936082| 11.584783| 37.08792607| 3.713209203| 522.3374046|[33.87936082,11.5...|\n| [email protected]|6705 Miller Orcha...| 29.53242897| 10.9612984| 37.42021558| 4.046423164| 408.6403511|[29.53242897,10.9...|\n|wrightpeter@yahoo...|05302 Dunlap Ferr...| 33.19033404|12.95922609| 36.1446667| 3.918541839| 573.4158673|[33.19033404,12.9...|\n|taylormason@gmail...|7773 Powell Sprin...| 32.38797585|13.14872569| 36.61995708| 2.494543647| 470.4527333|[32.38797585,13.1...|\n| [email protected]|49558 Ramirez Roa...| 30.73772037|12.63660605| 36.21376309| 3.357846842| 461.7807422|[30.73772037,12.6...|\n| [email protected]|6362 Wilson Mount...| 32.1253869|11.73386169| 34.89409275| 3.136132716| 457.8476959|[32.1253869,11.73...|\n|rebecca45@hale-ba...|8982 Burton RowWi...| 32.33889932|12.01319469| 38.38513659| 2.420806161| 407.7045475|[32.33889932,12.0...|\n|alejandro75@hotma...|64475 Andre Club ...| 32.18781205|14.71538754| 38.24411459| 1.516575581| 452.3156755|[32.18781205,14.7...|\n|samuel46@love-wes...|544 Alexander Hei...| 32.61785606|13.98959256| 37.1905038| 4.06454855| 605.0610388|[32.61785606,13.9...|\n+--------------------+--------------------+------------------+-----------+---------------+--------------------+-------------------+--------------------+\nonly showing top 20 rows\n\n"
],
[
"output.select(\"Independent Features\").show()",
"+--------------------+\n|Independent Features|\n+--------------------+\n|[34.49726773,12.6...|\n|[31.92627203,11.1...|\n|[33.00091476,11.3...|\n|[34.30555663,13.7...|\n|[33.33067252,12.7...|\n|[33.87103788,12.0...|\n|[32.0215955,11.36...|\n|[32.73914294,12.3...|\n|[33.9877729,13.38...|\n|[31.93654862,11.8...|\n|[33.99257277,13.3...|\n|[33.87936082,11.5...|\n|[29.53242897,10.9...|\n|[33.19033404,12.9...|\n|[32.38797585,13.1...|\n|[30.73772037,12.6...|\n|[32.1253869,11.73...|\n|[32.33889932,12.0...|\n|[32.18781205,14.7...|\n|[32.61785606,13.9...|\n+--------------------+\nonly showing top 20 rows\n\n"
],
[
"output.columns",
"_____no_output_____"
],
[
"finalized_data=output.select(\"Independent Features\",\"Yearly Amount Spent\")",
"_____no_output_____"
],
[
"finalized_data.show()",
"+--------------------+-------------------+\n|Independent Features|Yearly Amount Spent|\n+--------------------+-------------------+\n|[34.49726773,12.6...| 587.951054|\n|[31.92627203,11.1...| 392.2049334|\n|[33.00091476,11.3...| 487.5475049|\n|[34.30555663,13.7...| 581.852344|\n|[33.33067252,12.7...| 599.406092|\n|[33.87103788,12.0...| 637.1024479|\n|[32.0215955,11.36...| 521.5721748|\n|[32.73914294,12.3...| 549.9041461|\n|[33.9877729,13.38...| 570.200409|\n|[31.93654862,11.8...| 427.1993849|\n|[33.99257277,13.3...| 492.6060127|\n|[33.87936082,11.5...| 522.3374046|\n|[29.53242897,10.9...| 408.6403511|\n|[33.19033404,12.9...| 573.4158673|\n|[32.38797585,13.1...| 470.4527333|\n|[30.73772037,12.6...| 461.7807422|\n|[32.1253869,11.73...| 457.8476959|\n|[32.33889932,12.0...| 407.7045475|\n|[32.18781205,14.7...| 452.3156755|\n|[32.61785606,13.9...| 605.0610388|\n+--------------------+-------------------+\nonly showing top 20 rows\n\n"
]
],
[
[
"## Create Model ",
"_____no_output_____"
]
],
[
[
"train_data,test_data=finalized_data.randomSplit([0.75,0.25])",
"_____no_output_____"
],
[
"regressor=LinearRegression(featuresCol='Independent Features', labelCol='Yearly Amount Spent')\n# fit the model\nregressor=regressor.fit(train_data)",
"_____no_output_____"
],
[
"regressor.coefficients",
"_____no_output_____"
],
[
"regressor.intercept",
"_____no_output_____"
]
],
[
[
"## Evaluate the model",
"_____no_output_____"
]
],
[
[
"pred_results=regressor.evaluate(test_data)",
"_____no_output_____"
],
[
"pred_results.predictions.show(40)",
"+--------------------+-------------------+------------------+\n|Independent Features|Yearly Amount Spent| prediction|\n+--------------------+-------------------+------------------+\n|[29.53242897,10.9...| 408.6403511| 397.7314622481499|\n|[30.39318454,11.8...| 319.9288698| 331.4354817055371|\n|[30.73772037,12.6...| 461.7807422|451.00378856214934|\n|[30.83643267,13.1...| 467.5019004| 471.6315593383845|\n|[31.04722214,11.1...| 392.4973992| 387.6961791855133|\n|[31.06621816,11.7...| 448.9332932|461.71709673379814|\n|[31.35847719,12.8...| 495.1759504|491.12482994053585|\n|[31.38958548,10.9...| 410.0696111| 409.3081755667929|\n|[31.42522688,13.2...| 530.7667187| 534.6343118465913|\n|[31.5261979,12.04...| 409.0945262|417.94636309938346|\n|[31.53160448,13.3...| 436.5156057| 432.7242184024992|\n|[31.57020083,13.3...| 545.9454921| 563.5592281627285|\n|[31.62536013,13.1...| 376.3369008|380.96043463635397|\n|[31.65480968,13.0...| 475.2634237| 468.5507644073118|\n|[31.7207699,11.75...| 538.7749335| 545.5799494248888|\n|[31.72420252,13.1...| 503.3878873| 509.5844377330677|\n|[31.73663569,10.7...| 496.9334463|494.49593917588913|\n|[31.82934646,11.2...| 385.152338|384.13548659460844|\n|[31.86274111,14.0...| 556.2981412| 558.1705675935309|\n|[31.86483255,13.4...| 439.8912805|450.32554539094735|\n|[32.04781463,12.4...| 497.3895578|480.92538992642835|\n|[32.05426185,13.1...| 561.8746577| 557.0238791456106|\n|[32.0609144,12.62...| 627.6033187| 611.0063849335909|\n|[32.07759004,10.3...| 401.0331352|402.78394552838677|\n|[32.07894758,12.7...| 357.8637186|352.75949417674406|\n|[32.08838063,11.9...| 512.1658664| 518.4098285688285|\n|[32.11511907,11.9...| 350.0582002| 342.1792296532319|\n|[32.1253869,11.73...| 457.8476959|437.83757808411997|\n|[32.20465465,12.4...| 478.584286| 478.6402993700408|\n|[32.21292383,11.7...| 513.1531119| 513.9194131613392|\n|[32.21552742,12.2...| 438.417742| 445.7372873723375|\n|[32.22729914,13.7...| 613.5993234| 621.4052644522508|\n|[32.2559012,10.48...| 479.7319376| 478.3541922043364|\n|[32.25997327,14.1...| 571.2160048| 573.522899819732|\n|[32.29964716,12.1...| 547.1109824| 537.9549823334594|\n|[32.37798966,11.9...| 408.2169018|435.56382374750706|\n|[32.38696867,12.7...| 508.7719067|504.03454410803056|\n|[32.39742194,12.0...| 483.7965221|481.15732246538573|\n|[32.52976873,11.7...| 298.7620079| 305.9121405291926|\n|[32.53379686,12.2...| 485.9231305| 500.660049606902|\n+--------------------+-------------------+------------------+\nonly showing top 40 rows\n\n"
]
]
]
| [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
]
| [
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
]
|
cb5dac3a7a0d15a407094f34728a17de01764eb1 | 34,576 | ipynb | Jupyter Notebook | docs/experiments/mlp_experiment/1/Practico DL.ipynb | alessiobocco/AprendizajeProfundo | 180e09db1843ed383dccb8665905af20ec144f84 | [
"MIT"
]
| null | null | null | docs/experiments/mlp_experiment/1/Practico DL.ipynb | alessiobocco/AprendizajeProfundo | 180e09db1843ed383dccb8665905af20ec144f84 | [
"MIT"
]
| null | null | null | docs/experiments/mlp_experiment/1/Practico DL.ipynb | alessiobocco/AprendizajeProfundo | 180e09db1843ed383dccb8665905af20ec144f84 | [
"MIT"
]
| null | null | null | 162.328638 | 2,881 | 0.694557 | [
[
[
"## Preparando los dataset\n\n#### meli-challange-2019\nCreamos la carpeta data en la raiz del proyecto, con los archivos de meli-challange-2019\nNo es necesario correrlo si ya existe el file\n\n<code>%%bash\n\nmkdir -p data\ncurl -L https://cs.famaf.unc.edu.ar/\\~ccardellino/resources/diplodatos/meli-challenge-2019.tar.bz2 -o ./data/meli-challenge-2019.tar.bz2\ntar jxvf ./data/meli-challenge-2019.tar.bz2 -C ./data/</code>\n\n\n#### SBW-vectors\nDentro de la carpeta data anteriormente creada, subimos los files de SBW-vectors\n\n<code>%%bash\n\ncurl -L http://cs.famaf.unc.edu.ar/\\~ccardellino/SBWCE/SBW-vectors-300-min5.txt.bz2 -o ./data/SBW-vectors-300-min5.txt.bz2\nbunzip2 ./data/SBW-vectors-300-min5.txt.bz2</code>\n",
"_____no_output_____"
],
[
"## Validamos que los files existan y sean accesibles.",
"_____no_output_____"
]
],
[
[
"%%bash\n\nzcat ./data/meli-challenge-2019/spanish.train.jsonl.gz | wc -l",
"4895280\n"
],
[
"!zcat ./data/meli-challenge-2019/spanish.train.jsonl.gz | head",
"{\"language\":\"spanish\",\"label_quality\":\"reliable\",\"title\":\"Casita Mu\\u00f1ecas Barbies Pintadas\",\"category\":\"DOLLHOUSES\",\"split\":\"train\",\"tokenized_title\":[\"casita\",\"mu\\u00f1ecas\",\"barbies\",\"pintadas\"],\"data\":[50001,2,50000,3],\"target\":0,\"n_labels\":632,\"size\":4895280}\r\n{\"language\":\"spanish\",\"label_quality\":\"unreliable\",\"title\":\"Neceser Cromado Hologr\\u00e1fico \",\"category\":\"TOILETRY_BAGS\",\"split\":\"train\",\"tokenized_title\":[\"neceser\",\"cromado\",\"hologr\\u00e1fico\"],\"data\":[6,4,5],\"target\":1,\"n_labels\":632,\"size\":4895280}\r\n{\"language\":\"spanish\",\"label_quality\":\"unreliable\",\"title\":\"Funda Asiento A Medida D20 Chevrolet\",\"category\":\"CAR_SEAT_COVERS\",\"split\":\"train\",\"tokenized_title\":[\"funda\",\"asiento\",\"medida\",\"chevrolet\"],\"data\":[9,7,10,8],\"target\":2,\"n_labels\":632,\"size\":4895280}\r\n{\"language\":\"spanish\",\"label_quality\":\"unreliable\",\"title\":\"Embrague Ford Focus One 1.8 8v Td (90cv) Desde 01-99\",\"category\":\"AUTOMOTIVE_CLUTCH_KITS\",\"split\":\"train\",\"tokenized_title\":[\"embrague\",\"ford\",\"focus\",\"one\"],\"data\":[11,13,12,14],\"target\":3,\"n_labels\":632,\"size\":4895280}\r\n{\"language\":\"spanish\",\"label_quality\":\"unreliable\",\"title\":\"Bateria Panasonic Dmwbcf10 Lumix Dmc-fx60n Dmcfx60n Fx60n\",\"category\":\"CAMERA_BATTERIES\",\"split\":\"train\",\"tokenized_title\":[\"bateria\",\"panasonic\",\"dmwbcf\",\"lumix\",\"dmc\",\"fxn\",\"dmcfxn\",\"fxn\"],\"data\":[15,19,17,18,16,1,1,1],\"target\":4,\"n_labels\":632,\"size\":4895280}\r\n{\"language\":\"spanish\",\"label_quality\":\"unreliable\",\"title\":\"Gurgel Br 800\",\"category\":\"CLASSIC_CARS\",\"split\":\"train\",\"tokenized_title\":[\"gurgel\"],\"data\":[1],\"target\":5,\"n_labels\":632,\"size\":4895280}\r\n{\"language\":\"spanish\",\"label_quality\":\"unreliable\",\"title\":\"Harman Kardon Hk 3700 2ch Network Receiver _h\",\"category\":\"AV_RECEIVERS\",\"split\":\"train\",\"tokenized_title\":[\"harman\",\"kardon\",\"network\",\"receiver\"],\"data\":[20,21,22,23],\"target\":6,\"n_labels\":632,\"size\":4895280}\r\n{\"language\":\"spanish\",\"label_quality\":\"unreliable\",\"title\":\"Pack Netbook\\u00b4s\",\"category\":\"POWER_GRINDERS\",\"split\":\"train\",\"tokenized_title\":[\"pack\",\"netbook\\u00b4s\"],\"data\":[24,1],\"target\":7,\"n_labels\":632,\"size\":4895280}\r\n{\"language\":\"spanish\",\"label_quality\":\"unreliable\",\"title\":\"Olla Essen Duo\",\"category\":\"KITCHEN_POTS\",\"split\":\"train\",\"tokenized_title\":[\"olla\",\"essen\",\"duo\"],\"data\":[27,26,25],\"target\":8,\"n_labels\":632,\"size\":4895280}\r\n{\"language\":\"spanish\",\"label_quality\":\"unreliable\",\"title\":\"Teclado Mini Bluetooth\",\"category\":\"PC_KEYBOARDS\",\"split\":\"train\",\"tokenized_title\":[\"teclado\",\"mini\",\"bluetooth\"],\"data\":[30,29,28],\"target\":9,\"n_labels\":632,\"size\":4895280}\r\n\r\ngzip: stdout: Broken pipe\r\n"
]
],
[
[
"## El modelo de clasificación\nPara clasificación utilizaremos un perceptrón multicapa de dos capas ocultas. Claramente este modelo es naive y prácticamente todo lo que está hardcodeado (e.g. los tamaños de las capas o la cantidad de capas) podría ser parte de los parámetros del modelo. En particular, tenemos la capa de Embeddings que es rellenada con los valores de embeddings preentrenados (los de Glove en este caso).",
"_____no_output_____"
]
],
[
[
"!head ./data/SBW-vectors-300-min5.txt ",
"1000653 300\r\nde -0.029648 0.011336 0.019949 -0.088832 -0.025225 0.056844 0.025473 0.014068 0.163694 -0.067154 0.014738 0.027134 0.066443 -0.044846 -0.044987 -0.040898 0.030311 0.034196 -0.049240 0.008537 -0.068091 -0.087938 0.035300 0.149385 -0.012350 0.012613 0.029350 0.069596 0.039111 0.057652 0.069954 -0.066217 -0.041784 0.028623 0.026772 -0.066392 0.002953 -0.012188 -0.030363 0.040222 0.034858 0.027469 -0.029034 -0.048748 -0.038582 -0.051553 -0.033501 -0.019008 0.003043 0.110712 -0.025096 0.111082 0.035244 0.114207 0.010195 0.051511 -0.040649 -0.113944 0.044873 0.052011 0.067360 0.049054 -0.127085 -0.031846 0.032848 0.040825 -0.084873 0.059801 -0.067424 0.016531 -0.084565 0.057024 0.083288 -0.010136 -0.048508 0.051757 0.046664 0.018102 -0.052320 -0.000765 0.053662 -0.009967 0.082858 0.009068 0.054575 -0.003466 -0.023376 0.023069 0.088513 0.018504 -0.039503 -0.032980 -0.002139 0.000010 -0.107627 0.007699 0.046351 -0.003062 0.030500 0.113650 0.032536 -0.097301 -0.013734 0.098345 0.080898 -0.064173 -0.008874 -0.144751 0.037585 0.013290 0.059674 0.006163 0.007318 0.000053 -0.060292 -0.059135 0.049497 -0.011438 -0.095108 -0.043465 0.048567 -0.043990 -0.030774 0.005092 -0.032265 0.009392 0.018503 0.084857 0.109709 -0.020662 0.017696 0.026699 -0.076638 -0.014106 -0.035155 0.046999 -0.003727 -0.047805 0.044270 0.011314 0.036524 -0.069505 -0.014850 -0.003538 -0.047049 0.029349 0.034521 -0.032199 0.116497 -0.077610 0.068234 -0.016126 -0.066454 -0.079914 -0.020723 -0.064905 0.069560 0.021368 -0.049497 -0.046599 0.067663 -0.069035 0.118015 0.027463 -0.006176 -0.034514 -0.026515 0.040308 0.091113 -0.080539 0.132408 -0.070958 0.019730 0.033399 0.003489 -0.159659 -0.004230 0.004888 -0.056615 0.061021 0.025117 0.099613 0.063876 -0.006202 -0.049316 -0.020530 0.008522 -0.094168 -0.009451 -0.034682 -0.026801 0.065383 0.042528 -0.013688 0.035068 0.119803 -0.020278 0.111882 -0.068336 0.050245 -0.123240 0.002248 0.010229 -0.062540 -0.017837 -0.115210 0.051036 0.026920 0.083457 0.062902 0.003083 -0.037112 -0.015425 0.001716 0.018002 0.101100 0.019446 0.074839 0.059951 0.072243 -0.025459 -0.039853 0.077950 0.060199 -0.070603 0.060652 0.023855 -0.035858 -0.058043 -0.075130 0.000670 0.082828 -0.013141 0.144692 -0.105775 0.087624 0.047030 -0.015700 -0.042360 0.026337 0.144966 0.021922 0.012097 -0.011443 -0.110208 0.009333 -0.081423 -0.027137 0.000827 0.085389 0.034464 0.032338 -0.015040 0.009954 -0.011759 -0.042395 -0.000467 0.055047 -0.049710 -0.104978 0.031742 0.037020 -0.007016 -0.049712 0.041684 0.018348 -0.001201 0.019282 0.005763 0.074952 -0.018588 0.016055 0.119526 -0.014613 0.020598 0.027312 0.024252 -0.024044 -0.026332 -0.063152 -0.095363 -0.034335 -0.062552 -0.035730 0.091165 0.009686 0.020341 -0.012004 0.011826 -0.084301 0.011144 0.074969 -0.004862 -0.014076 0.025692 -0.077322 -0.022998 -0.128057 -0.004917 0.062628\r\nDIGITO -0.013002 -0.000781 0.032629 -0.088482 0.021298 0.039986 0.068380 0.006264 0.091135 0.000434 0.009331 0.028423 0.020692 -0.013583 -0.032420 0.024689 0.033696 -0.023145 -0.035633 -0.010274 -0.081628 -0.053617 0.051587 0.091048 -0.016919 0.033980 0.073040 0.100553 0.027454 0.053528 -0.013338 -0.055065 -0.045165 0.053637 0.017824 -0.010603 0.013005 -0.002873 -0.069372 0.008059 -0.001416 0.012431 -0.080941 -0.065539 0.007878 -0.021076 -0.035602 -0.049555 0.048422 0.104744 -0.054366 0.018188 0.031350 0.098584 0.094406 0.019084 -0.033111 -0.092422 0.058111 0.042169 0.009418 0.052326 -0.076443 -0.065708 0.039609 0.070779 -0.104470 0.016466 -0.100397 -0.012615 -0.062208 0.044405 0.040897 0.047476 -0.010739 0.005267 0.081850 0.034962 -0.094599 0.015806 0.040549 -0.003756 0.036048 0.022974 0.035902 0.023096 0.039259 -0.016199 0.043539 0.014725 -0.006119 -0.018587 -0.014097 -0.002395 -0.134557 0.041796 0.001652 0.058954 0.078891 0.114630 0.105141 -0.128402 -0.066549 0.079760 0.024396 -0.113124 -0.001198 -0.135299 0.037189 -0.035586 0.094150 0.018785 -0.005085 -0.018881 -0.115887 -0.082005 0.024251 -0.033302 -0.078087 -0.022660 0.007569 -0.096935 -0.023436 -0.023365 -0.026818 -0.023903 0.046716 0.047488 0.067228 -0.033471 0.038515 0.023762 -0.125687 0.042650 -0.000855 0.001957 -0.052234 -0.066039 0.082063 0.001344 -0.009984 -0.117670 -0.004480 -0.006035 -0.006549 0.032035 -0.021916 -0.028900 0.087054 -0.103109 0.033930 -0.036428 0.002393 -0.009741 -0.069586 -0.020493 0.001128 -0.067282 -0.043965 -0.075068 0.099662 -0.017608 0.066231 -0.015208 0.031142 -0.027223 -0.033040 0.053951 0.046496 -0.131409 0.131169 -0.007959 -0.011152 0.000514 -0.028036 -0.168291 -0.022996 -0.032068 -0.039740 0.016381 0.005333 0.099232 0.051381 -0.000236 -0.073249 0.012495 -0.015802 -0.091128 -0.003723 -0.022181 -0.046669 0.059063 0.064704 0.028548 0.011399 0.117871 -0.028101 0.068917 0.008404 0.030469 -0.104959 0.002380 -0.040827 0.041906 -0.024125 -0.046123 0.006722 0.074472 0.107256 0.066871 -0.017771 -0.007295 -0.007886 -0.031781 0.050508 0.043651 -0.043853 0.119111 0.048094 0.027306 -0.012738 -0.055844 0.000362 0.073290 -0.094030 0.088980 0.033241 -0.082521 -0.114527 -0.077395 -0.057670 0.046407 0.032855 0.090644 -0.084556 0.130570 0.046755 -0.000518 -0.062754 0.003713 0.142896 -0.000069 0.012594 -0.018961 -0.071201 -0.050190 -0.107127 -0.011871 0.030770 0.038137 0.023721 0.028529 0.065621 0.018548 0.044810 -0.023708 0.028006 0.028420 0.000359 -0.051305 0.035992 0.077839 -0.046144 -0.010108 0.056583 0.040588 0.106301 0.046546 -0.028884 0.031776 -0.023081 0.011159 0.058000 -0.002292 -0.021265 0.030547 -0.046024 0.021797 0.090825 -0.097326 -0.077190 0.060535 -0.078626 -0.108777 0.048595 -0.039361 0.022155 -0.015696 0.007409 -0.130169 0.048188 0.095554 -0.007935 -0.010960 0.009057 -0.055717 -0.016302 -0.132496 0.029352 0.063434\r\nla -0.022313 0.022251 0.036704 -0.096540 -0.052861 0.024058 0.011043 0.002622 0.156215 -0.042965 0.039763 -0.003066 0.038801 -0.053368 -0.041667 -0.030635 -0.007328 0.003714 -0.114164 -0.025042 -0.051972 -0.055420 0.042268 0.105376 -0.060363 -0.019926 -0.001696 0.102281 0.040454 0.088647 0.088293 -0.019142 0.003859 -0.027580 0.018365 -0.088503 -0.011589 -0.052447 -0.008289 -0.020715 0.009673 0.012709 -0.082492 -0.040010 -0.057307 -0.087804 -0.020654 0.018062 0.034962 0.131913 -0.033211 0.130602 0.014101 0.057181 0.005193 0.058847 -0.062297 -0.131932 0.017364 0.088293 0.053714 0.019530 -0.121452 0.018164 0.060706 0.088240 -0.059637 0.037769 -0.052032 0.079613 -0.133862 -0.006583 0.068153 0.041149 -0.059254 0.057758 0.010501 0.058813 -0.026589 -0.078938 0.032387 -0.010713 0.054048 0.016489 0.052541 0.019058 -0.035579 0.035734 0.079074 0.027151 -0.034716 -0.041740 0.027742 0.038502 -0.131790 0.000054 0.023742 -0.015529 -0.016263 0.074132 -0.034666 -0.074852 0.005035 0.113395 0.032837 0.004166 0.004269 -0.135889 0.062360 0.051681 0.044063 0.054768 0.067986 0.032836 -0.095447 -0.072281 0.028622 0.029793 -0.057763 -0.034192 0.001806 -0.043905 -0.044698 0.007713 -0.047600 0.014539 -0.004542 0.047801 0.049999 -0.044603 0.038886 0.022660 -0.053500 -0.062190 -0.085413 0.072058 0.029248 -0.031418 -0.055516 0.025744 0.060207 -0.014266 -0.022034 0.018754 -0.015960 -0.001577 0.020190 -0.069271 0.138597 -0.101960 0.043598 0.005266 -0.075013 -0.063113 0.049575 -0.053393 0.043651 0.012303 -0.034139 0.024200 0.055642 -0.030245 0.100529 -0.017504 -0.060918 -0.100398 -0.043245 0.047509 0.040789 -0.048056 0.107280 -0.079895 0.049304 0.028526 0.040193 -0.097320 -0.000557 0.004501 -0.000329 0.006951 0.037162 0.053592 0.071350 0.025196 -0.031765 -0.000354 -0.013615 -0.080432 0.026182 -0.030302 -0.028832 -0.002504 0.071907 -0.027518 0.008791 0.142758 0.008447 0.099430 -0.051668 0.107455 -0.098141 -0.060972 -0.013618 -0.041751 0.039856 -0.068698 0.027978 -0.026681 0.034578 0.036537 -0.019795 0.007946 0.014677 -0.028922 0.026407 0.100824 0.024597 0.057108 0.026002 0.004507 0.008445 -0.070869 0.119097 0.036694 0.017460 0.024830 0.049018 -0.042634 -0.075510 -0.044751 0.038456 0.074046 -0.046579 0.143879 -0.062126 0.027630 0.072420 -0.044438 -0.066515 0.036794 0.196606 0.001752 0.048581 0.016231 -0.133789 0.010679 -0.072775 -0.007094 -0.010939 0.084204 0.018636 0.107546 -0.044642 0.017310 -0.013498 0.008038 0.006861 0.067795 -0.064582 -0.110481 0.034113 0.054558 -0.020856 -0.100647 0.049993 0.001914 -0.059515 0.010465 0.000765 0.135641 -0.019326 0.037263 0.065312 0.008730 0.007405 0.044418 0.038109 -0.022185 -0.045651 -0.064789 -0.119470 0.002855 -0.037815 -0.011621 0.034758 0.026737 0.077853 -0.000177 -0.009866 -0.037531 0.018481 0.067658 0.005637 -0.034123 0.003338 -0.062329 -0.016266 -0.087151 -0.020682 0.033452\r\nen 0.026581 -0.015241 0.076188 -0.033951 -0.005532 0.040253 0.014638 -0.026969 0.174926 -0.088551 0.030411 0.033171 0.035247 -0.053153 0.034791 -0.043782 0.021706 -0.001933 -0.030657 0.056735 -0.096816 -0.006083 0.023477 0.129903 -0.089923 -0.012156 0.023389 0.076864 0.075134 0.061423 -0.033565 -0.045924 -0.083673 -0.004397 0.049242 -0.100869 0.010767 0.014354 -0.034536 0.006054 0.009703 0.028443 0.024843 -0.085018 -0.013708 -0.019241 -0.018230 -0.026206 0.021970 0.041291 -0.083791 0.088205 0.029461 0.129968 -0.035930 0.045489 0.000100 -0.036779 0.058822 0.096341 -0.068487 0.093272 -0.054641 -0.054127 0.049860 0.047078 -0.081942 0.131879 -0.056536 0.035574 -0.161969 -0.015891 0.072931 0.002060 -0.062984 0.037286 -0.021168 0.058015 0.000511 -0.088004 0.025141 -0.032483 0.043571 -0.014221 0.059971 0.017288 0.009931 -0.003049 0.045414 0.030266 -0.041036 -0.038548 0.055262 -0.010400 -0.109452 0.040224 0.049651 -0.005717 0.069147 0.079641 0.037132 -0.083692 -0.032963 0.086437 0.042587 -0.088681 0.004317 -0.112368 0.047439 0.046220 0.047233 0.052244 0.040376 0.043803 0.003122 -0.049596 0.105030 0.051798 -0.089496 -0.061939 0.064500 -0.006850 -0.033281 -0.007044 -0.059802 0.001478 0.061763 -0.005635 0.072320 0.026220 0.038630 0.061924 -0.040747 0.001671 -0.076976 0.062713 -0.003883 -0.075068 0.037281 -0.001749 -0.015784 -0.073255 -0.041658 -0.015254 -0.083932 0.019675 0.023857 0.011877 0.110891 -0.126212 0.008916 0.022912 -0.086664 -0.052335 -0.025554 -0.082052 0.059955 0.010351 -0.052768 -0.022825 0.066495 -0.018831 0.036371 -0.010668 -0.001757 -0.043319 -0.002546 0.014011 0.065008 -0.063852 0.143000 -0.017950 -0.012133 0.034645 0.019249 -0.120813 -0.028476 -0.027132 -0.052217 0.034275 0.056875 0.091684 0.104272 0.047259 -0.076129 0.012061 0.001202 -0.066170 -0.023275 -0.037404 -0.039282 0.047298 0.018953 -0.063144 0.013522 0.151888 0.036871 0.059711 -0.048100 0.068195 -0.123619 -0.022605 -0.037766 0.001217 -0.011442 -0.072790 0.090778 -0.003909 0.109163 0.001483 -0.010494 -0.035323 -0.089491 0.032565 0.064478 0.099495 -0.004145 0.062221 -0.002344 0.075857 0.025798 -0.058230 0.106080 -0.037642 -0.098980 0.040896 0.050060 -0.025803 -0.076346 -0.031277 -0.016458 0.074173 -0.017541 0.117265 -0.054809 0.071285 0.034627 0.018742 0.003090 -0.022064 0.079526 -0.036521 0.059427 0.023826 -0.088483 -0.053345 -0.031825 -0.091163 -0.000318 0.097550 0.039705 0.068879 0.009346 -0.005831 -0.020445 -0.037551 -0.030627 0.042611 -0.060933 -0.061835 -0.025218 0.054502 0.007813 0.007886 -0.096371 0.032693 -0.074697 -0.022726 0.027068 0.093267 0.027991 0.016513 0.021966 -0.001403 0.004168 0.007359 0.020973 -0.011663 -0.058841 -0.039689 -0.021151 0.001391 0.017551 -0.019631 0.078555 0.038571 0.063819 -0.028779 -0.015407 -0.119639 0.054226 0.097685 -0.000983 0.013433 0.002072 -0.135137 0.039641 -0.113613 -0.082998 0.001794\r\nel -0.019094 -0.054838 0.061867 -0.032082 -0.005957 0.057351 0.028500 -0.043159 0.151103 -0.047987 -0.065501 0.019325 0.045845 -0.052837 0.039334 -0.029077 -0.035610 0.005154 0.007917 0.039476 -0.063586 -0.041226 0.022597 0.088539 -0.047592 0.006095 0.068421 0.040141 0.071777 0.052399 0.018608 -0.104608 -0.065750 0.057864 0.026319 -0.014900 -0.030556 -0.020601 -0.048309 0.018427 0.027275 -0.011767 -0.054502 -0.074528 -0.051803 -0.087762 -0.006023 -0.003563 0.068748 0.039145 -0.043258 0.041879 0.057915 0.095341 0.018489 -0.001705 -0.028376 -0.071598 0.083582 0.060199 0.007671 0.059488 -0.004180 -0.009021 0.029272 0.041644 -0.096565 0.086306 -0.086528 -0.047175 -0.090746 0.050310 0.041464 0.022899 -0.048404 0.051755 0.018348 0.000737 -0.072073 0.000742 0.045431 0.031756 0.056730 -0.002922 -0.029613 -0.064712 0.031082 -0.054350 0.015172 0.038507 0.005052 0.041152 0.017918 0.000021 -0.140041 -0.032220 0.045753 -0.001662 0.107630 0.056159 0.031969 -0.061976 -0.125508 0.099241 0.072667 -0.111275 -0.037890 -0.098337 0.009009 0.032999 0.108232 0.001456 -0.019507 0.021065 -0.070871 -0.067959 0.087397 -0.017634 -0.071713 -0.068235 0.021910 -0.036611 -0.056015 0.002406 -0.000682 0.002840 -0.004956 0.051061 0.039282 -0.004243 0.068350 0.078494 -0.111187 0.001789 -0.050798 0.043564 0.022463 -0.079984 0.083845 -0.039942 -0.002670 -0.105963 -0.045711 -0.070839 -0.071386 0.018530 0.030352 -0.022617 0.052608 -0.076264 0.054236 0.038974 -0.065505 -0.016966 -0.054466 -0.047889 0.059159 -0.038347 -0.046825 -0.067137 0.054917 -0.048225 0.112417 -0.059300 0.042382 0.061968 -0.016934 -0.006549 0.058622 -0.070197 0.136546 -0.029121 -0.021011 0.032252 0.013837 -0.144404 -0.032138 0.016345 0.003643 0.095301 0.035812 0.078058 0.078509 0.010083 -0.038933 0.017821 0.012711 -0.035441 -0.045516 -0.031174 -0.020619 0.071923 0.066945 -0.024285 0.008731 0.103420 -0.026585 0.086919 0.023265 0.087532 -0.169808 0.010314 -0.009849 -0.010514 -0.061712 -0.096139 0.056519 0.031146 0.120540 0.121889 -0.001435 -0.050902 -0.057896 0.043951 0.011844 0.071470 -0.034592 0.100551 0.028934 0.082797 -0.004083 -0.063326 0.057935 0.049082 -0.086728 0.055341 0.046598 -0.037046 -0.078920 -0.088477 -0.012546 0.063808 0.001957 0.098891 -0.114209 0.085782 0.031362 0.005591 -0.011783 0.052346 0.146943 -0.034617 -0.000501 -0.072018 -0.076500 -0.018684 -0.048509 -0.055089 0.008249 0.056943 0.080161 0.038735 0.055476 -0.023171 0.018044 -0.076114 0.039769 0.004626 -0.057135 -0.057441 0.029075 0.029289 0.001732 -0.040982 -0.019653 -0.000673 0.052067 0.025087 -0.015553 0.031290 -0.015537 0.026309 0.040171 0.015795 -0.004143 0.009772 0.017129 0.007851 -0.024184 -0.079634 -0.091227 0.027483 -0.015121 -0.004996 0.076148 -0.001744 0.029846 -0.000951 -0.032178 -0.145940 -0.009878 0.118325 0.003628 -0.082544 -0.026749 -0.075919 -0.043725 -0.132087 -0.024071 0.061029\r\ny -0.042121 -0.037836 0.036679 -0.084050 0.006515 0.099305 0.045928 0.016368 0.134327 -0.011844 0.010659 0.034676 0.077137 -0.029783 -0.037907 -0.013795 -0.006836 0.011500 -0.076058 0.024434 -0.001108 -0.066514 0.038872 0.112885 -0.029406 0.007112 0.051488 0.107979 0.017522 0.092438 0.023222 -0.085683 -0.027921 0.007972 -0.025705 -0.028533 -0.024607 0.021877 -0.012343 0.042430 -0.007043 -0.024389 -0.024505 -0.033911 -0.057083 -0.084533 0.016485 -0.036139 -0.016978 0.102030 0.009303 0.075448 0.002156 0.139538 0.030210 0.044145 0.018690 -0.052760 0.077810 -0.005391 0.002815 0.053274 -0.115534 -0.051825 0.087068 0.077077 -0.135340 0.059492 -0.101219 -0.022589 -0.096890 0.007034 0.100118 -0.027093 -0.035940 0.036322 0.068001 0.009856 -0.060712 0.009975 0.052419 0.007922 0.040131 -0.043593 0.044140 -0.070362 -0.023544 0.007764 0.046340 -0.002144 -0.032538 -0.036125 0.072541 0.031860 -0.079002 -0.008596 0.030342 0.031109 0.049772 0.098390 0.028766 -0.087979 -0.026243 0.101731 0.096011 -0.098713 -0.028484 -0.124418 0.012567 0.059454 0.058859 0.045594 0.042404 0.058988 -0.027370 -0.039773 0.079016 0.075955 -0.081528 -0.040563 0.003863 -0.025793 -0.064998 -0.012341 -0.044403 0.032571 0.032722 0.063099 0.043915 0.008649 0.011968 -0.003642 -0.048209 -0.004967 -0.009467 0.047431 -0.039778 -0.087145 0.067849 0.015591 0.042563 -0.063274 -0.016025 -0.012975 -0.007136 0.003320 0.031884 -0.025658 0.170790 -0.064511 0.087716 -0.012953 -0.089275 -0.078927 -0.040504 -0.049050 0.046049 -0.073238 -0.034384 -0.029562 0.058786 -0.048790 0.104966 0.006574 0.024187 -0.034967 -0.042244 0.044918 0.033789 -0.087381 0.144220 -0.079357 -0.044999 0.041973 0.063769 -0.131122 -0.035932 0.019795 -0.015165 0.060755 0.067912 0.072251 0.045235 -0.050696 -0.032275 -0.042132 0.039258 -0.105867 0.026290 -0.035994 -0.017492 0.051305 0.026117 -0.010991 0.022200 0.092220 0.005362 0.100001 -0.069541 0.028063 -0.072846 -0.025222 -0.052707 -0.013893 0.016668 -0.090094 0.079421 0.010554 0.104492 0.043973 -0.047725 -0.053228 -0.038448 0.047978 0.009977 0.071996 0.051516 0.056524 0.044401 -0.007176 -0.012876 -0.036896 0.107779 0.057859 -0.027401 0.059532 0.055896 -0.036159 -0.130574 -0.082946 -0.010875 0.065847 -0.037720 0.049972 -0.087733 0.099261 0.010922 -0.069056 -0.063673 0.045537 0.156079 -0.001204 -0.002200 -0.049615 -0.124501 -0.003060 -0.039126 -0.057013 0.002022 0.077750 0.057647 -0.002259 0.032134 0.039760 -0.044032 -0.016928 0.031718 0.030675 -0.045675 -0.062055 0.074004 0.091850 -0.008636 -0.047515 0.042973 -0.022288 0.069358 0.024483 -0.063722 0.062641 -0.050236 0.056393 0.043446 0.026321 -0.001066 -0.005073 0.049178 -0.005089 -0.002601 -0.024335 -0.103959 -0.028944 -0.074412 0.000756 0.073722 -0.009733 -0.024274 0.032052 -0.010659 -0.116662 -0.022428 0.087131 -0.009682 -0.027912 -0.000686 -0.100404 0.039308 -0.109681 0.018647 0.034145\r\nque -0.002689 -0.063456 0.009619 -0.075912 0.002579 0.025287 -0.051774 -0.015810 0.161642 -0.062808 -0.013864 -0.009856 0.045704 -0.074680 0.051135 -0.017151 -0.003561 -0.001276 -0.077127 0.016603 0.011733 -0.048739 0.039748 0.054235 -0.036468 -0.052945 -0.006031 0.099651 -0.028718 0.075966 0.054379 -0.039412 -0.027434 -0.010707 0.029061 -0.011958 -0.027064 -0.033164 -0.091794 -0.039789 0.047586 0.037241 -0.009755 -0.005757 -0.060044 -0.005748 0.017914 0.022921 0.056237 0.094185 -0.056646 0.050965 -0.003328 0.137955 -0.024645 0.003999 -0.013210 -0.094191 0.029361 0.065217 -0.015854 0.050067 -0.016534 -0.014519 0.032965 0.030408 -0.115367 0.026486 -0.080514 -0.019257 -0.096709 -0.077588 0.060865 0.094164 -0.099619 0.132228 -0.083935 -0.011013 -0.068265 -0.014002 0.050748 0.036933 0.041567 -0.024340 -0.015914 -0.017347 0.029209 0.047102 0.070173 0.015551 -0.009812 -0.013571 0.127878 -0.032161 -0.074046 -0.092937 0.006629 0.002188 0.013948 0.083105 -0.054561 -0.098746 -0.050451 0.074982 0.071701 -0.027987 0.034169 -0.070208 0.024198 0.099134 0.083352 0.052365 0.074382 0.032819 -0.045973 -0.024529 0.080065 0.010117 -0.016776 -0.100084 -0.035398 0.066112 -0.072628 -0.007483 -0.120063 0.094598 -0.018094 -0.057935 0.061705 0.004589 0.074878 0.000203 -0.064027 -0.092381 -0.052254 0.102206 0.026677 -0.099442 0.030952 0.029867 0.026049 0.008899 -0.025673 -0.044990 0.005295 -0.016670 -0.010131 -0.047413 0.022243 -0.035623 -0.002019 0.009365 -0.062364 -0.056982 -0.020327 -0.031840 0.103263 0.026027 -0.033970 -0.000850 -0.055312 -0.024188 0.089656 -0.068503 0.014380 -0.008165 0.016037 0.025563 0.081804 -0.003454 0.157332 -0.132477 -0.000092 -0.019525 0.041020 -0.087384 -0.077959 -0.016578 0.014818 0.071696 0.093232 0.106681 0.075612 -0.053004 -0.030074 -0.039739 0.021461 -0.106232 0.007007 -0.021070 -0.057630 -0.024995 0.041227 -0.047074 -0.021664 0.055596 0.021923 0.076737 -0.019297 -0.090034 -0.123045 -0.000816 -0.086728 -0.014518 -0.005784 -0.063479 0.027065 0.002798 -0.011823 0.076236 -0.060856 -0.009606 -0.043855 -0.018248 0.008788 0.109807 -0.000731 0.119774 -0.064890 0.011259 -0.025940 0.010084 0.047275 0.039871 -0.079974 0.006294 0.047295 -0.022516 -0.123771 -0.043215 0.020200 -0.005444 0.022062 0.041229 -0.054759 0.028675 -0.016499 -0.066043 -0.067645 0.046606 0.174002 -0.046577 -0.034094 -0.016998 -0.127203 -0.015287 -0.048483 -0.063370 0.018057 0.067036 0.038760 -0.014682 0.003502 0.074684 -0.004579 0.012645 0.060375 0.011071 -0.104448 -0.023500 0.129327 0.108149 0.017028 -0.023761 0.013200 -0.106190 -0.081396 -0.000015 -0.073123 0.051081 0.000019 0.112538 -0.109238 0.037213 -0.006113 0.016891 0.071667 -0.012543 -0.043288 -0.030091 -0.005994 -0.042346 -0.055406 0.056610 0.022521 0.033848 0.024308 0.042734 -0.018096 -0.089446 -0.015459 0.061343 -0.036983 -0.013618 -0.024007 -0.111448 0.003092 -0.039190 0.026918 0.007546\r\na -0.085708 -0.014221 -0.028402 -0.041660 0.000841 0.026713 -0.070521 -0.020635 0.151278 -0.043035 0.022053 0.060899 0.027153 -0.020045 0.016947 -0.006727 -0.048576 0.028197 -0.077388 -0.012958 -0.032999 -0.085236 0.033298 0.048615 -0.062863 -0.086112 0.078298 0.099283 -0.029768 0.097277 0.035398 0.010830 0.036246 0.024329 0.000256 -0.053414 -0.051688 0.017490 0.033324 0.003499 0.060596 0.025377 -0.038630 0.003894 -0.061409 -0.050302 0.031621 -0.057430 0.021222 0.094447 -0.038353 0.095174 -0.028562 0.129691 0.016649 0.065995 0.017320 -0.112592 0.052304 0.015935 -0.013187 0.027251 -0.043155 0.004700 0.046635 0.035095 -0.106708 0.109668 -0.034918 -0.022885 -0.078081 -0.008696 0.087973 -0.021335 -0.038379 0.085882 0.074952 -0.031077 -0.032370 -0.024936 -0.064589 0.023546 0.056268 0.089660 0.048147 -0.001469 0.045662 0.114295 0.041474 0.009460 0.030381 -0.042455 0.094784 0.004791 -0.054252 -0.005596 0.077166 0.004340 0.032954 0.095851 -0.055361 -0.053738 0.025474 0.088548 0.048974 -0.012645 0.021798 -0.160509 -0.071003 0.078340 0.024732 0.044401 0.023484 0.014640 -0.105357 -0.072310 0.051115 -0.013979 -0.104898 -0.049686 -0.074997 -0.024003 0.002897 -0.016695 -0.005288 0.070059 0.042156 -0.026912 0.055670 -0.012965 0.023968 -0.028007 -0.098136 -0.066733 -0.033063 0.090629 0.050029 -0.036112 0.008000 -0.019124 0.001585 -0.050867 -0.057871 0.012271 0.054926 -0.073830 0.016126 -0.017341 0.162786 -0.051869 0.048271 -0.007905 -0.044899 -0.060555 -0.032798 -0.042563 0.007000 -0.041733 0.077264 -0.028744 0.041560 -0.043970 0.102608 -0.063534 -0.030251 -0.085311 -0.070170 0.032403 0.050852 -0.029692 0.204252 -0.081406 -0.014004 -0.027134 0.046173 -0.096796 -0.011267 -0.030390 -0.039823 0.016193 0.072762 0.002904 0.053425 -0.007085 -0.057839 -0.028737 0.005004 -0.108273 -0.028901 -0.014450 -0.011476 -0.047680 0.042957 -0.028786 -0.051833 0.174963 0.056555 0.066884 -0.012178 -0.079719 -0.134066 -0.003384 -0.059435 -0.041294 -0.016674 -0.065865 0.046402 0.054264 0.041868 0.019971 -0.049754 -0.066999 -0.010109 -0.018221 -0.007654 0.079747 0.059242 0.047878 -0.004967 0.016677 -0.033916 0.003234 0.063001 0.059698 -0.088501 0.090181 0.006319 -0.019144 -0.121754 -0.078249 0.030398 -0.024264 0.043136 -0.000854 -0.077675 0.086028 -0.010723 -0.096656 -0.013100 0.037266 0.169945 -0.026870 -0.013890 -0.032570 -0.088369 -0.025112 -0.031090 -0.023369 0.078204 0.026516 0.064645 0.065211 0.072346 0.016042 0.046019 -0.025140 -0.018420 0.004399 0.053585 -0.003360 0.045258 0.080729 0.021974 -0.083316 0.053740 0.004446 0.078119 -0.003585 -0.048441 0.038877 0.014348 0.064513 0.014956 -0.020856 0.001713 0.031545 0.040790 0.014643 -0.057416 0.017689 -0.084654 -0.092191 -0.033100 0.035180 -0.004986 -0.014108 -0.029003 0.028466 0.001388 -0.122391 -0.035286 -0.007954 0.007977 -0.062431 -0.016400 -0.084379 0.042604 -0.115474 -0.021421 0.056566\r\nlos -0.018489 0.036911 0.045592 -0.006009 0.009740 0.062708 -0.017418 0.000362 0.136461 -0.123914 0.004111 0.012575 0.051185 -0.015960 -0.007032 -0.060143 -0.086755 -0.001579 -0.072407 -0.001173 0.030028 -0.120873 -0.011749 0.103469 -0.095740 0.016945 -0.052293 0.100694 0.026250 0.051805 0.050285 0.007062 0.019713 0.007554 0.003000 -0.007825 0.031388 -0.053674 -0.070242 0.014803 0.031444 -0.015814 0.005966 -0.035825 -0.056899 -0.066460 -0.031974 -0.094435 0.044974 0.109062 -0.010704 0.083039 -0.007427 0.055845 0.072120 0.040261 -0.072686 -0.086832 0.128521 0.062262 0.005739 0.067721 -0.113566 0.034305 0.041693 0.072097 -0.079644 0.062137 -0.035381 0.021093 -0.122759 -0.002234 0.097428 0.017932 -0.095214 0.080814 0.048575 -0.002102 -0.046335 -0.005699 -0.059984 0.031422 0.061613 0.030816 0.026701 -0.068000 0.067893 -0.032332 0.077142 0.013572 -0.053096 -0.071081 0.125338 -0.021719 -0.113427 0.020651 0.011522 0.018410 0.005999 0.108815 -0.081018 -0.031712 -0.030261 0.104312 0.036996 -0.031590 -0.045709 -0.118326 -0.037217 0.066981 0.054778 0.082154 0.015319 0.039584 -0.004972 -0.059101 0.059792 0.038955 -0.029077 -0.059071 -0.062213 0.017934 -0.033466 0.007342 -0.096879 0.091667 0.032268 0.007647 -0.046322 -0.036875 0.071908 0.011096 -0.063519 -0.037783 -0.027381 0.077523 -0.041995 -0.110935 0.080467 -0.030527 -0.063902 -0.096758 0.026814 0.024715 -0.056444 0.002252 -0.038416 -0.075330 0.110978 -0.131945 -0.017590 -0.022661 -0.105336 -0.058229 -0.031346 -0.033111 0.068825 -0.005905 -0.013079 -0.078876 0.117026 -0.049613 0.081184 -0.047651 -0.006850 0.026761 -0.015042 0.040951 0.031432 -0.046367 0.082599 -0.087242 0.054085 0.010322 0.015893 -0.068361 -0.051342 -0.045214 0.012072 0.041920 0.056213 0.004658 0.074050 0.015432 -0.012290 0.062163 -0.001665 -0.170216 0.015962 -0.020238 -0.048876 0.023480 0.016153 -0.027302 -0.005531 0.012621 -0.002982 0.037035 -0.040416 0.029351 -0.088106 -0.107750 0.024803 -0.050490 -0.033057 -0.055477 0.083738 0.056245 0.051557 0.056413 -0.003753 -0.014272 -0.025381 -0.018004 -0.008878 0.067367 0.000718 0.038998 -0.004634 -0.003219 -0.026742 0.036714 0.025285 0.055854 -0.072501 0.044095 0.052553 0.014116 -0.062374 -0.056877 0.002491 0.014094 -0.060129 0.054998 -0.061254 0.071453 0.003723 -0.036329 -0.027158 0.003534 0.093185 0.007992 -0.097294 -0.036056 -0.102298 -0.041867 -0.141788 -0.068675 0.008443 0.075905 0.054666 -0.019575 0.066365 0.044702 -0.065557 0.021451 0.062475 0.099107 -0.039205 -0.115370 0.040057 0.140246 0.054609 -0.027473 -0.026007 -0.037904 0.008885 0.011040 -0.034092 0.068014 -0.005894 0.070370 0.054927 -0.000015 0.091078 0.005293 0.065675 0.013272 0.025433 0.014886 -0.078631 -0.010623 -0.032067 0.011527 0.052344 0.038192 -0.032623 -0.011271 -0.040584 -0.032548 -0.038051 0.079366 0.045388 -0.066945 -0.042741 -0.073721 -0.011892 -0.114976 0.025161 0.012087\r\n"
],
[
"hidden_layers = [256, 128, 64, 32]\nlist(zip(hidden_layers[:-1], hidden_layers[1:]))",
"_____no_output_____"
]
]
]
| [
"markdown",
"code",
"markdown",
"code"
]
| [
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
]
|
cb5db31d06c9bb84a3703b4bff21cac4c34ac161 | 308,689 | ipynb | Jupyter Notebook | code/.ipynb_checkpoints/14.millionsong-checkpoint.ipynb | nju-teaching/computational-communication | b95bca72bcfbe412fef15df9f3f057e398be7e34 | [
"MIT"
]
| 7 | 2016-03-16T12:11:39.000Z | 2018-05-03T16:42:08.000Z | code/.ipynb_checkpoints/14.millionsong-checkpoint.ipynb | nju-teaching/computational-communication | b95bca72bcfbe412fef15df9f3f057e398be7e34 | [
"MIT"
]
| 5 | 2016-03-18T02:03:35.000Z | 2016-05-04T10:20:52.000Z | code/.ipynb_checkpoints/14.millionsong-checkpoint.ipynb | nju-teaching/computational-communication | b95bca72bcfbe412fef15df9f3f057e398be7e34 | [
"MIT"
]
| 12 | 2016-03-16T12:12:13.000Z | 2017-04-03T09:25:39.000Z | 495.487961 | 248,211 | 0.666017 | [
[
[
"import graphlab as gl\n# set canvas to show sframes and sgraphs in ipython notebook\ngl.canvas.set_target('ipynb')\nimport matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
],
[
"#train_file = 'http://s3.amazonaws.com/dato-datasets/millionsong/10000.txt'\ntrain_file = '/Users/chengjun/bigdata/millionsong/song_usage_10000.txt'\nsf = gl.SFrame.read_csv(train_file, header=False, delimiter='\\t', verbose=False)\nsf.rename({'X1':'user_id', 'X2':'music_id', 'X3':'rating'}).show()",
"------------------------------------------------------\nInferred types from first line of file as \ncolumn_type_hints=[str,str,int]\nIf parsing fails due to incorrect types, you can correct\nthe inferred type list above and pass it to read_csv in\nthe column_type_hints argument\n------------------------------------------------------\nPROGRESS: Read 844838 lines. Lines per second: 810295\nPROGRESS: Finished parsing file /Users/chengjun/bigdata/millionsong/song_usage_10000.txt\nPROGRESS: Parsing completed. Parsed 2000000 lines in 1.59616 secs.\n"
],
[
"(train_set, test_set) = sf.random_split(0.8, seed=1)",
"_____no_output_____"
],
[
"popularity_model = gl.popularity_recommender.create(train_set, 'user_id', 'music_id', target = 'rating')",
"PROGRESS: Recsys training: model = popularity\nPROGRESS: Preparing data set.\nPROGRESS: Data has 1599753 observations with 76085 users and 10000 items.\nPROGRESS: Data prepared in: 1.23558s\nPROGRESS: 1599753 observations to process; with 10000 unique items.\n"
],
[
"item_sim_model = gl.item_similarity_recommender.create(train_set, 'user_id', 'music_id', target = 'rating', \n similarity_type='cosine')",
"PROGRESS: Recsys training: model = item_similarity\nPROGRESS: Preparing data set.\nPROGRESS: Data has 1599753 observations with 76085 users and 10000 items.\nPROGRESS: Data prepared in: 1.34152s\nPROGRESS: Computing item similarity statistics:\nPROGRESS: Computing most similar items for 10000 items:\nPROGRESS: +-----------------+-----------------+\nPROGRESS: | Number of items | Elapsed Time |\nPROGRESS: +-----------------+-----------------+\nPROGRESS: | 1000 | 1.67234 |\nPROGRESS: | 2000 | 1.70878 |\nPROGRESS: | 3000 | 1.74289 |\nPROGRESS: | 4000 | 1.77751 |\nPROGRESS: | 5000 | 1.81794 |\nPROGRESS: | 6000 | 1.85361 |\nPROGRESS: | 7000 | 1.88976 |\nPROGRESS: | 8000 | 1.92744 |\nPROGRESS: | 9000 | 1.96709 |\nPROGRESS: | 10000 | 2.08439 |\nPROGRESS: +-----------------+-----------------+\nPROGRESS: Finished training in 2.50669s\nPROGRESS: Finished prediction in 0.734376s\n"
],
[
"factorization_machine_model = gl.recommender.factorization_recommender.create(train_set, 'user_id', 'music_id',\n target='rating')",
"PROGRESS: Recsys training: model = factorization_recommender\nPROGRESS: Preparing data set.\nPROGRESS: Data has 1599753 observations with 76085 users and 10000 items.\nPROGRESS: Data prepared in: 1.31298s\nPROGRESS: Training factorization_recommender for recommendations.\nPROGRESS: +--------------------------------+--------------------------------------------------+----------+\nPROGRESS: | Parameter | Description | Value |\nPROGRESS: +--------------------------------+--------------------------------------------------+----------+\nPROGRESS: | num_factors | Factor Dimension | 8 |\nPROGRESS: | regularization | L2 Regularization on Factors | 1e-08 |\nPROGRESS: | solver | Solver used for training | sgd |\nPROGRESS: | linear_regularization | L2 Regularization on Linear Coefficients | 1e-10 |\nPROGRESS: | max_iterations | Maximum Number of Iterations | 50 |\nPROGRESS: +--------------------------------+--------------------------------------------------+----------+\nPROGRESS: Optimizing model using SGD; tuning step size.\nPROGRESS: Using 199969 / 1599753 points for tuning the step size.\nPROGRESS: +---------+-------------------+------------------------------------------+\nPROGRESS: | Attempt | Initial Step Size | Estimated Objective Value |\nPROGRESS: +---------+-------------------+------------------------------------------+\nPROGRESS: | 0 | 25 | No Decrease (234.956 >= 45.6461) |\nPROGRESS: | 1 | 6.25 | No Decrease (222.818 >= 45.6461) |\nPROGRESS: | 2 | 1.5625 | No Decrease (193.879 >= 45.6461) |\nPROGRESS: | 3 | 0.390625 | No Decrease (93.6001 >= 45.6461) |\nPROGRESS: | 4 | 0.0976562 | 18.1929 |\nPROGRESS: | 5 | 0.0488281 | 12.7349 |\nPROGRESS: | 6 | 0.0244141 | 27.6064 |\nPROGRESS: +---------+-------------------+------------------------------------------+\nPROGRESS: | Final | 0.0488281 | 12.7349 |\nPROGRESS: +---------+-------------------+------------------------------------------+\nPROGRESS: Starting Optimization.\nPROGRESS: +---------+--------------+-------------------+-----------------------+-------------+\nPROGRESS: | Iter. | Elapsed Time | Approx. Objective | Approx. Training RMSE | Step Size |\nPROGRESS: +---------+--------------+-------------------+-----------------------+-------------+\nPROGRESS: | Initial | 388us | 43.795 | 6.61778 | |\nPROGRESS: +---------+--------------+-------------------+-----------------------+-------------+\nPROGRESS: | 1 | 242.781ms | 43.525 | 6.59695 | 0.0488281 |\nPROGRESS: | 2 | 369.391ms | 40.9211 | 6.3966 | 0.0290334 |\nPROGRESS: | 3 | 491.657ms | 37.9834 | 6.1627 | 0.0214205 |\nPROGRESS: | 4 | 603.858ms | 35.2255 | 5.93471 | 0.0172633 |\nPROGRESS: | 5 | 743.824ms | 32.7566 | 5.7229 | 0.014603 |\nPROGRESS: | 6 | 861.2ms | 30.8412 | 5.553 | 0.0127367 |\nPROGRESS: | 10 | 1.39s | 24.7548 | 4.97477 | 0.008683 |\nPROGRESS: | 11 | 1.53s | 23.5887 | 4.85613 | 0.00808399 |\nPROGRESS: | 20 | 2.76s | 17.6337 | 4.19832 | 0.00516295 |\nPROGRESS: | 30 | 3.96s | 14.4135 | 3.79539 | 0.00380916 |\nPROGRESS: | 40 | 5.17s | 12.5212 | 3.53725 | 0.00306991 |\nPROGRESS: | 50 | 6.39s | 9.83216 | 3.13412 | 0.00154408 |\nPROGRESS: +---------+--------------+-------------------+-----------------------+-------------+\nPROGRESS: Optimization Complete: Maximum number of passes through the data reached.\nPROGRESS: Computing final objective value and training RMSE.\nPROGRESS: Final objective value: 8.86198\nPROGRESS: Final training RMSE: 2.97532\n"
],
[
"result = gl.recommender.util.compare_models(test_set, [popularity_model, item_sim_model, factorization_machine_model],\n user_sample=.1, skip_set=train_set)",
"compare_models: using 6871 users to estimate model performance\nPROGRESS: Evaluate model M0\nPROGRESS: recommendations finished on 1000/6871 queries. users per second: 12410\nPROGRESS: recommendations finished on 2000/6871 queries. users per second: 14958.4\nPROGRESS: recommendations finished on 3000/6871 queries. users per second: 15825.3\nPROGRESS: recommendations finished on 4000/6871 queries. users per second: 16808.7\nPROGRESS: recommendations finished on 5000/6871 queries. users per second: 17280.5\nPROGRESS: recommendations finished on 6000/6871 queries. users per second: 17228\n\nPrecision and recall summary statistics by cutoff\n+--------+-------------------+-------------------+\n| cutoff | mean_precision | mean_recall |\n+--------+-------------------+-------------------+\n| 2 | 0.000363848057051 | 0.000222530101733 |\n| 4 | 0.000509387279872 | 0.000644168294629 |\n| 6 | 0.000460874205598 | 0.000838220591723 |\n| 8 | 0.000418425265609 | 0.000983759814544 |\n| 10 | 0.000465725513026 | 0.00128720279373 |\n| 12 | 0.000412361131325 | 0.00132237477257 |\n| 14 | 0.000457408986007 | 0.00161781917277 |\n| 16 | 0.000491194877019 | 0.00189451695711 |\n| 18 | 0.000468959717977 | 0.00196078928179 |\n| 20 | 0.000480279435308 | 0.00211815339109 |\n+--------+-------------------+-------------------+\n[10 rows x 3 columns]\n\n\nOverall RMSE: 5.79840126177\n\nPer User RMSE (best)\n+-------------------------------+-------+-----------------+\n| user_id | count | rmse |\n+-------------------------------+-------+-----------------+\n| 907f83008d1b7a7958766544a0... | 1 | 0.0160085378869 |\n+-------------------------------+-------+-----------------+\n[1 rows x 3 columns]\n\n\nPer User RMSE (worst)\n+-------------------------------+-------+---------------+\n| user_id | count | rmse |\n+-------------------------------+-------+---------------+\n| 2c263b458bb317ee91c346ae90... | 4 | 172.795342779 |\n+-------------------------------+-------+---------------+\n[1 rows x 3 columns]\n\n\nPer Item RMSE (best)\n+--------------------+-------+------+\n| music_id | count | rmse |\n+--------------------+-------+------+\n| SOZWCBD12AB01848DD | 1 | 0.0 |\n+--------------------+-------+------+\n[1 rows x 3 columns]\n\n\nPer Item RMSE (worst)\n+--------------------+-------+---------------+\n| music_id | count | rmse |\n+--------------------+-------+---------------+\n| SOTGIKV12AB0182176 | 1 | 173.804878049 |\n+--------------------+-------+---------------+\n[1 rows x 3 columns]\n\nPROGRESS: Evaluate model M1\nPROGRESS: recommendations finished on 1000/6871 queries. users per second: 1291.91\nPROGRESS: recommendations finished on 2000/6871 queries. users per second: 1303.24\nPROGRESS: recommendations finished on 3000/6871 queries. users per second: 1303.16\nPROGRESS: recommendations finished on 4000/6871 queries. users per second: 1309.34\nPROGRESS: recommendations finished on 5000/6871 queries. users per second: 1309.57\nPROGRESS: recommendations finished on 6000/6871 queries. users per second: 1318.84\n\nPrecision and recall summary statistics by cutoff\n+--------+-------------------+-------------------+\n| cutoff | mean_precision | mean_recall |\n+--------+-------------------+-------------------+\n| 2 | 0.000509387279872 | 0.000106894612147 |\n| 4 | 0.000509387279872 | 0.00041709974353 |\n| 6 | 0.000557900354145 | 0.000741928943341 |\n| 8 | 0.000491194877019 | 0.000896131215139 |\n| 10 | 0.000509387279872 | 0.0010508900222 |\n| 12 | 0.000533643817009 | 0.00124220214402 |\n| 14 | 0.000509387279872 | 0.00144984014027 |\n| 16 | 0.000491194877019 | 0.00164649135206 |\n| 18 | 0.000517472792251 | 0.00213570216873 |\n| 20 | 0.000509387279872 | 0.00236702556808 |\n+--------+-------------------+-------------------+\n[10 rows x 3 columns]\n\nPROGRESS: Finished prediction in 0.226961s\n\nOverall RMSE: 6.09897586494\n\nPer User RMSE (best)\n+-------------------------------+-------+------+\n| user_id | count | rmse |\n+-------------------------------+-------+------+\n| 91e5266cafbdd11964d70fb1d8... | 1 | 0.0 |\n+-------------------------------+-------+------+\n[1 rows x 3 columns]\n\n\nPer User RMSE (worst)\n+-------------------------------+-------+---------------+\n| user_id | count | rmse |\n+-------------------------------+-------+---------------+\n| 2c263b458bb317ee91c346ae90... | 4 | 161.518485703 |\n+-------------------------------+-------+---------------+\n[1 rows x 3 columns]\n\n\nPer Item RMSE (best)\n+--------------------+-------+------+\n| music_id | count | rmse |\n+--------------------+-------+------+\n| SOOIQZC12A6701FEA1 | 2 | 0.0 |\n+--------------------+-------+------+\n[1 rows x 3 columns]\n\n\nPer Item RMSE (worst)\n+--------------------+-------+-------+\n| music_id | count | rmse |\n+--------------------+-------+-------+\n| SOTGIKV12AB0182176 | 1 | 172.0 |\n+--------------------+-------+-------+\n[1 rows x 3 columns]\n\nPROGRESS: Evaluate model M2\nPROGRESS: recommendations finished on 1000/6871 queries. users per second: 10178.8\nPROGRESS: recommendations finished on 2000/6871 queries. users per second: 11326.8\nPROGRESS: recommendations finished on 3000/6871 queries. users per second: 12072.2\nPROGRESS: recommendations finished on 4000/6871 queries. users per second: 12724.1\nPROGRESS: recommendations finished on 5000/6871 queries. users per second: 12371.5\nPROGRESS: recommendations finished on 6000/6871 queries. users per second: 12328.1\n\nPrecision and recall summary statistics by cutoff\n+--------+-------------------+-------------------+\n| cutoff | mean_precision | mean_recall |\n+--------+-------------------+-------------------+\n| 2 | 0.000291078445641 | 0.000204967738806 |\n| 4 | 0.000291078445641 | 0.000321852261162 |\n| 6 | 0.000315334982778 | 0.000400252854408 |\n| 8 | 0.000382040459904 | 0.000704556888155 |\n| 10 | 0.000480279435308 | 0.00107200975662 |\n| 12 | 0.000533643817009 | 0.00138531272247 |\n| 14 | 0.000550969914964 | 0.0016547624225 |\n| 16 | 0.000591253092708 | 0.00185731432805 |\n| 18 | 0.000582156891282 | 0.00207921438986 |\n| 20 | 0.000574879930141 | 0.00223034316254 |\n+--------+-------------------+-------------------+\n[10 rows x 3 columns]\n\n\nOverall RMSE: 7.66449264849\n\nPer User RMSE (best)\n+-------------------------------+-------+-------------------+\n| user_id | count | rmse |\n+-------------------------------+-------+-------------------+\n| ac810151e32857e9f4200e8fa7... | 1 | 0.000812624627255 |\n+-------------------------------+-------+-------------------+\n[1 rows x 3 columns]\n\n\nPer User RMSE (worst)\n+-------------------------------+-------+---------------+\n| user_id | count | rmse |\n+-------------------------------+-------+---------------+\n| 2c263b458bb317ee91c346ae90... | 4 | 182.725743431 |\n+-------------------------------+-------+---------------+\n[1 rows x 3 columns]\n\n\nPer Item RMSE (best)\n+--------------------+-------+-------------------+\n| music_id | count | rmse |\n+--------------------+-------+-------------------+\n| SOJWIJT12A8C136100 | 1 | 0.000881766015195 |\n+--------------------+-------+-------------------+\n[1 rows x 3 columns]\n\n\nPer Item RMSE (worst)\n+--------------------+-------+--------------+\n| music_id | count | rmse |\n+--------------------+-------+--------------+\n| SOTGIKV12AB0182176 | 1 | 236.91250578 |\n+--------------------+-------+--------------+\n[1 rows x 3 columns]\n\n"
],
[
"K = 10\nusers = gl.SArray(sf['user_id'].unique().head(100))",
"_____no_output_____"
],
[
"recs = item_sim_model.recommend(users=users, k=K)\nrecs.head()",
"_____no_output_____"
]
]
]
| [
"code"
]
| [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
]
|
cb5dbc4e33fb2244722b46afe6b59c2779cd56ea | 534,190 | ipynb | Jupyter Notebook | _notebooks/2022-03-14-dh140Final.ipynb | matty-tran/test-blog | b98dfca31c3ba0e7bd4c4371820a5ffaf8b36f47 | [
"Apache-2.0"
]
| null | null | null | _notebooks/2022-03-14-dh140Final.ipynb | matty-tran/test-blog | b98dfca31c3ba0e7bd4c4371820a5ffaf8b36f47 | [
"Apache-2.0"
]
| null | null | null | _notebooks/2022-03-14-dh140Final.ipynb | matty-tran/test-blog | b98dfca31c3ba0e7bd4c4371820a5ffaf8b36f47 | [
"Apache-2.0"
]
| null | null | null | 156.104617 | 103,660 | 0.836964 | [
[
[
"# **G.G.: Good Game?** by Matthew Tran ",
"_____no_output_____"
],
[
"## March 14, 2022",
"_____no_output_____"
],
[
"## **Introduction** ",
"_____no_output_____"
],
[
"In the modern age, video games have become a modern past time enjoyed by many people of various ages. A now lucrative industry, video games come in a variety of genres, experiences, and platforms. When asked about successful video games, a handful of titles might come to mind. Ones that are iconic because of their characters, revolutionary because of the way they engage with storytelling, or perhaps nostalgic because of how long they have been around. \n\nThis project seeks to define top performing video games and the traits that may have contributed to the success of these titles. Subsequently, I would like to conduct a more qualitative investigation on these titles, mainly examining reviews to paint a clearer picture of what consumers like about top games. ",
"_____no_output_____"
],
[
"## **The Data**",
"_____no_output_____"
],
[
"Initial exploration of defining what makes a good game will be conducted using the Video Games CORGIS dataset which can be accessed [here.](https://corgis-edu.github.io/corgis/python/video_games/) This data was originally collected by Dr. Joe Cox who conducted an empirical investigation of U.S. sales data of video games. Dr. Cox concluded that the major factors that predict for a title's ability to attain \"blockbuster\" status were threefold: the company that produced the title, the console, and the critic reviews. \n\nI would like to use the data that Dr. Cox collected, which spans thousands of titles that were released between 2004 and 2010, and conduct my own analysis agnostic to his fidnings. \n\nThe categoies that I am interested in and their possible effects on the success of a game are: \n1. Maximum number of players: how many people can play this game at one time? \n2. Online Features: does the game support online play? \n3. Genre: what genre does this game belong to? \n\nWithin these categories, I would like to measure success of a game using: \n1. Review score: the typical review score out of 100 \n2. Sales: the total sales made on the game measured in millions of dollars \n3. Completionist: players reported completing everything in the game \n\n",
"_____no_output_____"
],
[
"## **Data Exploration**",
"_____no_output_____"
]
],
[
[
"#hide\nimport pandas as pd \nimport seaborn as sns",
"_____no_output_____"
],
[
"#hide\nimport video_games",
"_____no_output_____"
],
[
"#hide\nvideo_game = video_games.get_video_game()",
"_____no_output_____"
],
[
"#hide\ndf = pd.read_csv('video_games.csv')",
"_____no_output_____"
],
[
"#hide-input\ndf.head()",
"_____no_output_____"
]
],
[
[
"### 1. What are the top games by critic reviews? ",
"_____no_output_____"
]
],
[
[
"#hide-input\ndf[['Title','Metrics.Review Score']].sort_values('Metrics.Review Score', ascending = False )",
"_____no_output_____"
]
],
[
[
"### 2. What are the top games by sales? ",
"_____no_output_____"
]
],
[
[
"#hide-input\ndf[['Title', 'Metrics.Sales']].sort_values('Metrics.Sales', ascending = False) ",
"_____no_output_____"
]
],
[
[
"### 3. What games have the most number of people who report completing the game? \n * will be skewed based on how many people played the game ",
"_____no_output_____"
]
],
[
[
"#hide-input\ndf[['Title', 'Length.Completionists.Polled']].sort_values ('Length.Completionists.Polled', ascending = False) ",
"_____no_output_____"
]
],
[
[
"### 4. What genre of game was popular on the market during this time period (2004-2010)? ",
"_____no_output_____"
]
],
[
[
"#collapse-output\ndf['Metadata.Genres'].value_counts()",
"_____no_output_____"
]
],
[
[
"### I would like to take the \"top games\" from questions 1-3 and get a closer look at these titles, since they are considered \"top performing\" in their respective categories. ",
"_____no_output_____"
]
],
[
[
"#collapse-output\ndf.iloc[837]",
"_____no_output_____"
],
[
"#collapse-output\ndf.iloc[156]",
"_____no_output_____"
],
[
"#collapse-output\ndf.iloc[442]",
"_____no_output_____"
],
[
"#hide-input\ndf.iloc[[837,156,442]]",
"_____no_output_____"
]
],
[
[
"Observed similarities and differences: \n 1. Action as one of the genres, though none fall exclusively into action only. \n 2. All 3 were a sequel of some kind, and based off of a previously licensed entity. \n 3. Max players do not go above 2, two of the three games are only single-player. \n 4. All games came from different publishers. \n 5. All released for different consoles. ",
"_____no_output_____"
],
[
"Because I am interested in the intersection of video games and pedagogy, I wanted to see the games that were considered \"Educational.\" \n * These were only the titles exclusively listed as 'Educational' as the genre",
"_____no_output_____"
]
],
[
[
"#hide-input\ndf[df['Metadata.Genres'] == 'Educational']",
"_____no_output_____"
],
[
"#collapse-output\ndf.iloc[549]",
"_____no_output_____"
],
[
"#collapse-output\ndf.iloc[1000]",
"_____no_output_____"
]
],
[
[
"Takeaways from initial data exploration: \n1. Because of the saturation of Action games, I would like to take a closer look at the metrics for success in that specific genre, as well as the other genres that are well-represented in the market. \n2. Because the games that were successful in these categories were all sequels of some kind, I think it would be interested to investigate if there are any titles that were successful without being a sequel, which would speak to the degree to which a factor like nostalgia or investment in a story/ universe contribute to a title's success. \n3. Because these three games did not have a max player capacity above 2, are there any titles that support multiplayer that are also finding success? \n4. Are there certain publishers or consoles that are finding more general success with their titles than others? ",
"_____no_output_____"
],
[
"## **Further Exploration** ",
"_____no_output_____"
],
[
"Based on the preliminary findings from my first data exploration, I would like to take a closer look at the data in certain places. ",
"_____no_output_____"
],
[
"### Defining Success \nUsing the metrics I established previously, I would like to examine the top-performing games in the categories of critic reviews, sales, and number of completionists. ",
"_____no_output_____"
],
[
"### 1. Critic Reviews ",
"_____no_output_____"
]
],
[
[
"#hide\ndf_reviews = df[['Title','Metrics.Review Score']]",
"_____no_output_____"
],
[
"#hide\ndf_reviews_top = df_reviews[df_reviews['Metrics.Review Score'] > 90].sort_values('Metrics.Review Score', ascending = False)",
"_____no_output_____"
],
[
"#hide\ndf_reviews_top.index",
"_____no_output_____"
],
[
"#hide\ndf2 = df.iloc[df_reviews_top.index]",
"_____no_output_____"
],
[
"#hide-input\nsns.regplot(x = df2['Metrics.Review Score'], y = df2['Metrics.Sales'])",
"_____no_output_____"
]
],
[
[
"Here, a sucessful game by critic review was defined as having a critic review score of over 90, of which there were 29 games. It does not seem to be the case, however, that a high critic score correlates very strongly to commercial success in sales. In fact, the games that received the highest critic scores were not the ones which had the most number of sales, with a handfull of games receiving more commercial sucess, and the highest seller (in this group) having the lowest critics score... ",
"_____no_output_____"
]
],
[
[
"#hide-input\nsns.regplot(x = df2['Metrics.Review Score'], y = df2['Length.Completionists.Polled'])",
"_____no_output_____"
]
],
[
[
"I observed an even weaker relationship between critic review scores and number of completionists in for the games. \n \nThis could however be because the games which received the highest critic review scores, such as Grand Theft Auto IV, are known for being \"open-world\" games in which the player can freely navigate the world without the story being a main part of interacting with the game. ",
"_____no_output_____"
]
],
[
[
"#collapse-output\ndf2[['Title', 'Metrics.Review Score', 'Metrics.Sales', 'Length.Completionists.Polled', 'Metadata.Genres']].sort_values('Metrics.Sales', ascending = False)",
"_____no_output_____"
]
],
[
[
"Notably, 27 out of the 29 titles that were considered top-performers as described by their critic review scores had Action as one of their genre descriptors. The two games that did not belong to this genre were considered as Role-Playing and Racing/ Driving games. ",
"_____no_output_____"
],
[
"### 2. Commercial Sales ",
"_____no_output_____"
]
],
[
[
"#hide\ndf_sales = df[['Title', 'Metrics.Sales']]",
"_____no_output_____"
],
[
"#hide\ndf['Metrics.Sales'].mean",
"_____no_output_____"
],
[
"#hide\ndf_sales_top = df_sales[df_sales['Metrics.Sales'] > 4.69]",
"_____no_output_____"
],
[
"#hide\nlen(df_sales_top.index)",
"_____no_output_____"
],
[
"#hide\ndf3 = df.iloc[df_sales_top.index]",
"_____no_output_____"
],
[
"#hide-input\nsns.regplot(x = df3['Metrics.Sales'], y =df3['Metrics.Review Score'] )",
"_____no_output_____"
]
],
[
[
"Very interestingly, for the top-performing games in terms if sales, being 14 games, there was actually a negative correlation between sales and critic scores. Shockingly, the game with the most sales had the lowest (sub-60) score of the group of games! However, the games with the highest critic scores in this set still had sales that were above the mean of the entire set, so these games were by no means unsuccessful. ",
"_____no_output_____"
]
],
[
[
"#hide-input\nsns.regplot(x = df3['Metrics.Sales'], y =df3['Length.Completionists.Polled'])",
"_____no_output_____"
]
],
[
[
"A similar negative relationship was observed between sales and number of completionist players. For similar reasons as the to critic scores grouping, the top game, Wii Play, is not a game that is well-known for having a definitive plot that players follow, but rather is a game that is often played socially with family and friends. ",
"_____no_output_____"
]
],
[
[
"#hide-input\ndf3[['Title', 'Metrics.Review Score', 'Metrics.Sales', 'Length.Completionists.Polled', 'Metadata.Genres']].sort_values('Metrics.Sales', ascending = False)",
"_____no_output_____"
]
],
[
[
"The distribution of genres in this group were slightly more diverse than that of the critic scores group. While Action games still held a slight majority at 8 out 14 games being part of the Action genre, Role-Playing, sports, and Driving games made up the remainder of this group. ",
"_____no_output_____"
],
[
"### 3. Completionists (or not?) ",
"_____no_output_____"
],
[
"Following my analysis of the top-performing games under critic scores and commercial sales, I have decided not to continue with using number of completionists as a measure of success for a variety of reasons. Firstly, this number would already be skewed because of how the number of players would affect this figure, and completionist data as such would require standardization. While the additional work of standardizing this data is not very much work, I also chose not to use number of completionists in the remainder of my analysis because of how easily this number could be affected by the type of game. There are many games that are made simply to be enjoyed, and do not have the aspect of following a story or plot that other games have. In the former case, players would not be as motivated to \"complete\" the game, which would skew how the number of com",
"_____no_output_____"
],
[
"### Action Games and Reviews? ",
"_____no_output_____"
],
[
"Because of the overrepresentation of Action games in the games with high critic reviews, I wanted to explore the idea that critics tend to favor games that are of the Action genre. ",
"_____no_output_____"
]
],
[
[
"#hide\ndf_action = df[df['Metadata.Genres'] == 'Action'] ",
"_____no_output_____"
],
[
"#collapse-output\ndf_action['Metrics.Review Score'].mean",
"_____no_output_____"
],
[
"#hide\ndf_sports = df[df['Metadata.Genres'] == 'Sports'] ",
"_____no_output_____"
],
[
"#collapse-output\ndf_sports['Metrics.Review Score'].mean",
"_____no_output_____"
],
[
"#hide\ndf_strategy = df[df['Metadata.Genres'] == 'Strategy'] ",
"_____no_output_____"
],
[
"#collapse-output\ndf_strategy['Metrics.Review Score'].mean",
"_____no_output_____"
]
],
[
[
"Looking at the 3 most common genres and examining the mean critic review scores, it seems that there does not seem to be an inherent bias for Action games amonst critics, since strategy games had a higher mean score, though I think this is one area of analysis that could benefit from more investigation. ",
"_____no_output_____"
],
[
"## **Who's at the Top?**",
"_____no_output_____"
],
[
"From both my own personal perspective, as well as how I assume businesses and consumers would define success, I think commerical sales is the best way to mesure the success of a game. However, because I think critic reviews may encapsulate some measure of the quality of a game, I think it would be beneficial to include critics reviews as a measure of success in some way. Therefore, I decided that when choosing the \"top games,\" I would choose those games that were present in both categories or top-performers in critic scores and sales. That is, games that received both above a 90 on critic scores and had sales above 4.69. \n\nTo account for any phenomenon that goes beyond any conventional measure of success I would like to include those titles that had extremely high sales, but perhaps were not deemed a \"good game\" by critics. These three games would be: Wii Play, Mario Kart Wii, and New Super Mario Bros, all titles that had commericial sales greater that 10 million dollars. ",
"_____no_output_____"
]
],
[
[
"#hide\ntop_reviews = df2['Title'].tolist()\ntop_sales = df3['Title'].tolist()",
"_____no_output_____"
],
[
"#collapse-output\ntop_sales",
"_____no_output_____"
],
[
"#collapse-output\ntop_reviews",
"_____no_output_____"
],
[
"#collapse-output\nprint(set(top_sales).intersection(set(top_reviews)))",
"{'Mario Kart DS', 'Call of Duty 4: Modern Warfare', 'Super Mario Galaxy', 'Super Smash Bros.: Brawl', 'Halo 3', 'Grand Theft Auto IV'}\n"
],
[
"#hide\ntop_games = set(top_sales).intersection(set(top_reviews))",
"_____no_output_____"
],
[
"#hide\ntop_games_dict = {'Grand Theft Auto IV' : 837, \n 'Mario Kart DS' : 22, \n 'Halo 3' : 420, \n 'Call of Duty 4: Modern Warfare' : 421, \n 'Super Mario Galaxy' : 422, \n 'Super Smash Bros.: Brawl' : 835\n}",
"_____no_output_____"
],
[
"#hide\ntarget_indices = [837, 22, 420, 421, 422, 835, 156, 833, 157]\ntop_games = df.iloc[target_indices]",
"_____no_output_____"
],
[
"#hide\ntop_games = top_games[['Title', 'Metrics.Review Score', 'Metrics.Sales', 'Metadata.Genres', 'Metadata.Sequel?', 'Metadata.Publishers', 'Features.Max Players', 'Release.Console', 'Release.Year']]",
"_____no_output_____"
],
[
"#hide-input\ntop_games.sort_values('Metrics.Sales', ascending = False)",
"_____no_output_____"
],
[
"#hide-input\nsns.countplot(x = top_games['Metadata.Genres'], palette = 'ch:.25')",
"_____no_output_____"
],
[
"#hide-input\nsns.countplot(x = top_games['Metadata.Publishers'], palette = 'ch:.25')",
"_____no_output_____"
],
[
"#hide-input\nsns.countplot(x = top_games['Features.Max Players'], palette = 'ch:.25')",
"_____no_output_____"
],
[
"#hide-input\nsns.countplot(x = top_games['Release.Console'], palette = 'ch:.25')",
"_____no_output_____"
]
],
[
[
"## **Discussion**",
"_____no_output_____"
],
[
"Examining the commonalities among the top performing games, it is clear that Nintendo games have the highest sales. They make up 6 of the 9 games that I identified as top-performing games, and represent the 6 highest-earning games in the entire dataset. This seems to operate independently of critic reviews, as the three highest selling games did not receive scores above 90 from critics. \n\nI think that there are factors, especially metadata about each game beyond the scope of information that was included in this dataset, that contributes to why games from Nintendo, and especially those that came out at the top of this dataset were considered top-performers by sales. \n\nThree of the top four games- Wii Play, Mario Kart Wii, and Mario Kart DS- are titles that do not have a strong storyline for the player to follow. Rather, they are multiplayer games that are centered around gaming as a social aspect. With family or friends, players can compete on teams with or against each other. Because you are constantly playing with real people in a competitive environment, the gaming experience is kept dynamic and engaging, rather then relying on a progressing in a story line. \n\nWhen considering what kinds of games are successful in the market, it may be helpful to consider whether a game is player-versus-player (PVP) or player-vs-everyone (PVE). Wii Play, Mario Kart Wii, and Mario Kart DS, are examples of PVP games, that is, players do not play by the themselves against computers, but rather against other real players, and these kinds of games inherently carry with them a competitive aspect. In terms of motivation, players are motivated to constantly return to the game in order to hone their skills in the game. In many PVE games, players are instead motivated by the desire to progress in the game itself. \n\nThe other game that was represented in the top-performing game, despite not having the same PVP quality as the others, was New Super Mario Bros. I think the reason that this title in particular was so successful is because of its recognisability. Just the name Mario in the gaming sphere is already enough for people, gamer or not, to have a mental image of what the game will entail. As a game that has had many remakes and interations, I think that this game's successful largely comes from its capacity to combine the nostalgia of players with the refreshing nature of a game remake or sequel. A game beloved by many, the Super Mario series of games is one that people are invested in because of their emotional attatchment to the games and characters. \n\nWhen it comes to learning, motivation is a crucial part of pedagogy. In both the conventional sense and in the realm of possibly gamifying learning, I think that it would be helpful to incoroporate a healthy amount of competition, whether it be against the self or against others. I think it is also important for students to have the ability to engage with other students as well, as this social aspect to learning and gaming is something that motivates students additionally. ",
"_____no_output_____"
],
[
"## **Nintendo: A Closer Look** ",
"_____no_output_____"
],
[
"Looking at the top-performing games, it is clear to see that Nintendo has a clear group on the gaming market when it comes to sales. As such, I would like to examine just what about these games makes them so desirable to players, and as such I would like to look to Nintendo themselves to see how they would market and describe these games. ",
"_____no_output_____"
]
],
[
[
"#hide\nfrom wordcloud import WordCloud, ImageColorGenerator\nfrom PIL import Image\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"#hide\nmyStopWords = list(punctuation) + stopwords.words('english')",
"_____no_output_____"
],
[
"#hide\nsuper_mario_describe = '''\nBowser has taken over the Mushroom Kingdom, and it's up to Mario to put an end to his sinister reign! Battle Bowser's vile henchmen through 32 levels in the Original 1985 game mode. Move on to collecting special Red Coins and Yoshi Eggs in Challenge mode. Then, try to unlock a secret mode that's waiting to be found by super players like you! Every mode will give you the chance to beat your own score, and there's a lot more to do than just saving a princess. So get ready for a brick-smashin', pipe-warpin', turtle-stompin' good time!\nMario™ and Luigi™ star in their first ever Mushroom Kingdom adventure! Find out why Super Mario Bros. is instantly recognizable to millions of people across the globe, and what made it the best-selling game in the world for three decades straight. Jump over obstacles, grab coins, kick shells, and throw fireballs through eight action-packed worlds in this iconic NES classic. Only you and the Mario Bros. can rescue Princess Toadstool from the clutches of the evil Bowser.\nPick up items and throw them at your adversaries to clear levels in seven fantastical worlds. Even enemies can be picked up and tossed across the screen. Each character has a unique set of abilities: Luigi can jump higher and farther than any of the other characters, Toad can dig extremely fast and pull items out of the ground quicker than anyone, and the princess is the only one who can jump and hover temporarily. This unique installment in the Mario series will keep you coming back for more!\nRelive the classic that brought renowned power-ups such as the Tanooki Suit to the world of Super Mario Bros.!\nBowser™ and the Koopalings are causing chaos yet again, but this time they’re going beyond the Mushroom Kingdom into the seven worlds that neighbor it. Now Mario™ and Luigi™ must battle a variety of enemies, including a Koopaling in each unique and distinctive world, on their way to ultimately taking on Bowser himself. Lucky for the brothers, they have more power-ups available than ever before. Fly above the action using the Super Leaf, swim faster by donning the Frog Suit, or defeat enemies using the Hammer Bros. Suit. Use the brand-new overworld map to take the chance to play a minigame in hopes of gaining extra lives or to find a Toad’s House where you can pick up additional items. All this (and more) combines into one of gaming’s most well-known and beloved titles—are you ready to experience gaming bliss?\n'''",
"_____no_output_____"
],
[
"#hide-input\nwc = WordCloud().generate_from_text(super_mario_describe)\n\n#Use matplotlib.pyplot to display the fitted wordcloud\n#Turn axis off to get rid of axis numbers\nplt.imshow(wc)\nplt.axis('off')\nplt.show()",
"_____no_output_____"
],
[
"#hide\nmario_kart_describe = '''\nSelect one of eight characters from the Mario™ series—offering a variety of driving styles—and take on three championship cups in three different kart classes. Win enough, and you'll unlock a fourth circuit: the ultra-tough Special Cup. Crossing the finish line in first place isn't an easy task, though, as each track has unique obstacles to conquer and racers can obtain special power-ups that boost them to victory. With more than 15 tracks to master and nearly endless replay value, Super Mario Kart is classic gaming…with some banana peels thrown in for good measure!\nThe newest installment of the fan-favorite Mario Kart™ franchise brings Mushroom Kingdom racing fun into glorious 3D. For the first time, drivers explore new competitive kart possibilities, such as soaring through the skies or plunging into the depths of the sea. New courses, strategic new abilities and customizable karts bring the racing excitement to new heights.\n\nFEATURES:\n\nThe Mario Kart franchise continues to evolve. New kart abilities add to the wild fun that the games are known for. On big jumps, a kart deploys a wing to let it glide over the track shortcut. When underwater, a propeller pops out to help the kart cruise across the sea floor.\nPlayers can show their own style by customizing their vehicles with accessories that give them a competitive advantage. For instance, giant tires help a kart drive off-road, while smaller tires accelerate quickly on paved courses.\nPeople can choose to race as one of their favorite Mushroom Kingdom characters or even as their Mii™ character.\nNew courses take players on wild rides over mountains, on city streets and through a dusty desert. Nintendo fans will recognize new courses on Wuhu Island and in the jungles from Donkey Kong Country™ Returns.\nThe game supports both SpotPass™ and StreetPass™ features.\nPlayers can compete in local wireless matches or online over a broadband Internet connection.\n\nThe newest installment of the fan-favorite Mario Kart™ franchise brings Mushroom Kingdom racing fun into glorious 3D. For the first time, drivers explore new competitive kart possibilities, such as soaring through the skies or plunging into the depths of the sea. New courses, strategic new abilities and customizable karts bring the racing excitement to new heights.\n\nFEATURES:\n\nThe Mario Kart franchise continues to evolve. New kart abilities add to the wild fun that the games are known for. On big jumps, a kart deploys a wing to let it glide over the track shortcut. When underwater, a propeller pops out to help the kart cruise across the sea floor.\nPlayers can show their own style by customizing their vehicles with accessories that give them a competitive advantage. For instance, giant tires help a kart drive off-road, while smaller tires accelerate quickly on paved courses.\nPeople can choose to race as one of their favorite Mushroom Kingdom characters or even as their Mii™ character.\nNew courses take players on wild rides over mountains, on city streets and through a dusty desert. Nintendo fans will recognize new courses on Wuhu Island and in the jungles from Donkey Kong Country™ Returns.\nThe game supports both SpotPass™ and StreetPass™ features.\nPlayers can compete in local wireless matches or online over a broadband Internet connection.\n'''",
"_____no_output_____"
],
[
"#hide-input\nwc2 = WordCloud().generate_from_text(mario_kart_describe)\n\n#Use matplotlib.pyplot to display the fitted wordcloud\n#Turn axis off to get rid of axis numbers\nplt.imshow(wc2)\nplt.axis('off')\nplt.show()",
"_____no_output_____"
],
[
"#hide\nsmash_bros_describe = '''\nSuper Smash Bros. for Nintendo 3DS is the first portable entry in the renowned series, in which game worlds collide. Up to four players battle each other locally or online using some of Nintendo’s most well-known and iconic characters across beautifully designed stages inspired by classic portable Nintendo games. It’s a genuine, massive Super Smash Bros. experience that’s available to play on the go, anytime, anywhere.\n\nFEATURES:\n\nSmash and crash through “Smash Run” mode, a new mode exclusive to the Nintendo 3DS version that gives up to four players five minutes to fight solo through a huge battlefield while taking down recognizable enemies from almost every major Nintendo franchise and multiple third-party partners. Defeated enemies leave behind power-ups to collect. Players who collect more power-ups have an advantage once time runs out and the battle with opponents begins.\nCompete with classic characters from the Super Smash Bros. series like Mario, Link, Samus and Pikachu, along with new challengers like Mega Man, Little Mac and newly announced Palutena, the Goddess of Light from the Kid Icarus games. For the first time players can even compete as their own Mii characters.\nCustomize different aspects of your character when playing locally or online with friends in a variety of multiplayer modes.\nView most elements of the high-energy action at silky-smooth 60 frames per second and in eye-popping stereoscopic 3D.\nFight against friends and family locally or online, or battle random challengers all over the world online in “For Fun” or “For Glory” modes.\n\nGaming icons clash in the ultimate brawl you can play anytime, anywhere! Smash rivals off the stage as new characters Simon Belmont and King K. Rool join Inkling, Ridley, and every fighter in Super Smash Bros. history. Enjoy enhanced speed and combat at new stages based on the Castlevania series, Super Mario Odyssey, and more!\n\nHaving trouble choosing a stage? Then select the Stage Morph option to transform one stage into another while battling—a series first! Plus, new echo fighters Dark Samus, Richter Belmont, and Chrom join the battle. Whether you play locally or online, savor the faster combat, new attacks, and new defensive options, like a perfect shield. Jam out to 900 different music compositions and go 1-on-1 with a friend, hold a 4-player free-for-all, kick it up to 8-player battles and more! Feel free to bust out your GameCube controllers—legendary couch competitions await—or play together anytime, anywhere!\n'''",
"_____no_output_____"
],
[
"#hide-input\nwc3 = WordCloud().generate_from_text(smash_bros_describe)\n\n#Use matplotlib.pyplot to display the fitted wordcloud\n#Turn axis off to get rid of axis numbers\nplt.imshow(wc3)\nplt.axis('off')\nplt.show()",
"_____no_output_____"
]
],
[
[
"### It's Mario's World and We're Just Playing in It ",
"_____no_output_____"
],
[
"After creating word clouds from Nintendo's descriptions of its highest selling titles from 2004-2010, there are some recurring themes that we see when Nintendo describes its games to players and potential customers. Words unique to the game, such as \"stage,\" \"kart\", and \"world\" are combined with descriptors such as \"new,\" \"fun,\" and \"unique,\" as well as familiar terms such as \"Nintendo,\" \"Mario,\" and \"Bowser,\" to create a sense that the player will be buying into a refreshing, updated, and modernized version of a product that they know and love. I think that much of Nintendo's success in the gaming market comes from the so-called empire that it has created both with its consistency of creating modern versions of its classic titles and capitalizing off of the nostalgia for these titles as well. \n\nFor developers that are not Nintendo, I think that it is important to create characters that people will love, and create a universe around these characters, incorporating them into different games and genres. While Mario is one character that definitely become a poster-child for Nintendo, I think that other characters such as Link and Zelda, or the Pokemon franchise in general have also achieved a similar status of recognizability for the company, and would likely be top-performing games in a more modern dataset. ",
"_____no_output_____"
],
[
"## **Conclusion** ",
"_____no_output_____"
],
[
"Through conducting this analysis of the video games dataset from CORGIS, I was able to learn a lot about the market in general, and what makes a \"successful\" game. My findings constrasted my expectations, but I was able to come to conclusions that I believe would be helpful for both game developers, and my own interests in gamifying learning. \n\nIn my exploration of both this project, and the course Digital Humanities 140, I learned many Python tools and became more comfortable working with new libraries as well as datasets. Although I used pandas for the majority of my analysis, the two libraries that I found helpful as well were seaborn and wordcloud for data visualization. Seaborn allowed me to combine aesthetic graphical information with statistical information, and wordcloud allowed me to create easy-to-understand visualizations, both of which reminded me of the importance of being able to tell a story with your data. \n\nIn the future, it would be fascinating to conduct a similar study with the modern video game market. Nowadays, gaming has been expanded to PC and mobile platforms, which were not represented in the CORGIS dataset. Additionally, many games are now free-to-play, so I think the metrics that are used for success may be a bit different that they were in my investigation. With the rise of e-sports and streaming, gaming is consumed in ways outside of simply playing the game, and has become a form of entertainment that is similar to movies, sporting, and YouTube. \n\nI would like to acknowledge Professor Winjum for his dedication to instruction this quarter, and his continual understanding. Thank you! ",
"_____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"
]
| [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
]
]
|
cb5ddcc8f5d9a5d4905449283f6aa742ef8fb71c | 272,526 | ipynb | Jupyter Notebook | notebook/Results_EDM2020.ipynb | qqhann/KnowledgeTracing | cecdb9af0c44efffd1ce3359f331d7d7782f551b | [
"MIT"
]
| 3 | 2021-11-24T09:49:03.000Z | 2022-01-12T06:53:05.000Z | notebook/Results_EDM2020.ipynb | qqhann/KnowledgeTracing | cecdb9af0c44efffd1ce3359f331d7d7782f551b | [
"MIT"
]
| 25 | 2021-08-15T10:57:48.000Z | 2021-08-23T21:14:24.000Z | notebook/Results_EDM2020.ipynb | qqhann/KnowledgeTracing | cecdb9af0c44efffd1ce3359f331d7d7782f551b | [
"MIT"
]
| 1 | 2022-01-23T13:05:21.000Z | 2022-01-23T13:05:21.000Z | 180.600398 | 132,284 | 0.88556 | [
[
[
"import os\nimport pandas as pd\nimport numpy as np\nimport json\nimport pickle\nfrom collections import defaultdict\nfrom pathlib import Path\nfrom statistics import mean, stdev\nfrom sklearn.metrics import ndcg_score, dcg_score\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport torch\n\nimport os, sys\nparentPath = os.path.abspath(\"..\")\nif parentPath not in sys.path:\n sys.path.insert(0, parentPath)\n \nfrom src.data import load_source\nfrom src.config import Config, get_option_fallback\nfrom src.path import get_best_model_paths, get_exp_paths, get_report_path, load_json, load_rep_cfg, get_exp_names\nfrom src.trainer import Trainer",
"_____no_output_____"
],
[
"# projectdir = Path('/code')\nprojectdir = Path('..')\nassert projectdir.exists()",
"_____no_output_____"
]
],
[
[
"# Common Functions",
"_____no_output_____"
]
],
[
[
"def summarize_test_res(rep, folds=5):\n print(rep['config']['exp_name'], end=':\\t')\n s = pd.Series([rep['best']['auc_epoch'][str(i)] for i in range(folds)])\n print(f'Best epoch at {s.mean():>6.1f}±{s.std():<5.1f}', end='\\t')\n s = pd.Series([rep['best']['auc'][str(i)] for i in range(folds)])\n print(f'Valid AUC: {s.mean()*100:.4f}±{s.std()*100:.4f}', end='\\t')\n s = pd.Series([rep['indicator']['test_auc'][str(i)][0] for i in range(folds)])\n print(f'Test AUC: {s.mean()*100:.4f}±{s.std()*100:.4f}', end='\\t')\n s = rep['indicator']['RPsoft']['all']\n print(f'Good:Bad = {s[\"good\"]}:{s[\"bad\"]}', end='\\t')\n s = rep['indicator']['test_auc']['all'][0]\n print(f'All Test AUC: {s*100:.4f}')",
"_____no_output_____"
],
[
"def show_valid_lc(name, idclist_dic, idc='eval_auc'):\n min_len = min([len(_x) for _x in idclist_dic['epoch'].values()])\n x = idclist_dic['epoch']['0'][:min_len] * (len(idclist_dic['epoch']) -1) # exclude 'all'\n y = []\n for _y in idclist_dic[idc].values():\n y += _y[:min_len]\n sns.lineplot(x=x, y=y, label=name)\n plt.title(idc)",
"_____no_output_____"
],
[
"def summarize_results(config_name, folds=5):\n report_paths = [get_report_path(projectdir, config_name, e) for e in get_exp_names(projectdir, config_name)]\n reports = [load_json(r) for r in report_paths]\n df = pd.DataFrame(columns=['dataset', 'model', 'auc', 'auc_std', 'r1_good', 'r1_goodbad', 'r2', 'r2_std'])\n for r in reports:\n row = {\n 'dataset': r['config']['config_name'],\n 'model': r['config']['exp_name'],\n 'auc': mean([r['indicator']['test_auc'][str(i)][0] for i in range(folds)]),\n 'auc_std': stdev([r['indicator']['test_auc'][str(i)][0] for i in range(folds)]) if folds > 1 else np.nan,\n 'r1_good': r['indicator']['RPsoft']['all']['good'],\n 'r1_goodbad': r['indicator']['RPsoft']['all']['good'] + r['indicator']['RPsoft']['all']['bad'],\n 'r2': mean(r['indicator']['RPhard']['all']),\n 'r2_std': stdev(r['indicator']['RPhard']['all'])\n }\n df = df.append(row, ignore_index=True)\n return df\n ",
"_____no_output_____"
]
],
[
[
"# Summary",
"_____no_output_____"
],
[
"## AUC table",
"_____no_output_____"
]
],
[
[
"summarize_results('20_0310_edm2020_assist09')",
"_____no_output_____"
],
[
"summarize_results('20_0310_edm2020_assist15')",
"_____no_output_____"
],
[
"summarize_results('20_0310_edm2020_synthetic', folds=1)",
"_____no_output_____"
],
[
"summarize_results('20_0310_edm2020_statics')",
"_____no_output_____"
],
[
"print(summarize_results('20_0310_edm2020_assist09').to_latex())\nprint(summarize_results('20_0310_edm2020_assist15').to_latex())\nprint(summarize_results('20_0310_edm2020_synthetic', folds=1).to_latex())\nprint(summarize_results('20_0310_edm2020_statics').to_latex())",
"\\begin{tabular}{lllrrllrr}\n\\toprule\n{} & dataset & model & auc & auc\\_std & r1\\_good & r1\\_goodbad & r2 & r2\\_std \\\\\n\\midrule\n0 & 20\\_0310\\_edm2020\\_assist09 & pre\\_dummy\\_epoch\\_size150.auto & 0.805398 & 0.000801 & 106 & 110 & 0.897429 & 0.112539 \\\\\n1 & 20\\_0310\\_edm2020\\_assist09 & pre\\_dummy\\_epoch\\_size10.auto & 0.802763 & 0.001107 & 105 & 110 & 0.916217 & 0.103119 \\\\\n2 & 20\\_0310\\_edm2020\\_assist09 & pre\\_dummy\\_epoch\\_size0.auto & 0.802399 & 0.002135 & 91 & 110 & 0.885842 & 0.121002 \\\\\n\\bottomrule\n\\end{tabular}\n\n\\begin{tabular}{lllrrllrr}\n\\toprule\n{} & dataset & model & auc & auc\\_std & r1\\_good & r1\\_goodbad & r2 & r2\\_std \\\\\n\\midrule\n0 & 20\\_0310\\_edm2020\\_assist15 & pre\\_dummy\\_epoch\\_size150.auto & 0.705414 & 0.001263 & 95 & 100 & 0.927833 & 0.092699 \\\\\n1 & 20\\_0310\\_edm2020\\_assist15 & pre\\_dummy\\_epoch\\_size10.auto & 0.703355 & 0.000890 & 99 & 100 & 0.921136 & 0.096746 \\\\\n2 & 20\\_0310\\_edm2020\\_assist15 & pre\\_dummy\\_epoch\\_size0.auto & 0.703117 & 0.001366 & 99 & 100 & 0.924388 & 0.091456 \\\\\n\\bottomrule\n\\end{tabular}\n\n\\begin{tabular}{lllrrllrr}\n\\toprule\n{} & dataset & model & auc & auc\\_std & r1\\_good & r1\\_goodbad & r2 & r2\\_std \\\\\n\\midrule\n0 & 20\\_0310\\_edm2020\\_synthetic & pre\\_dummy\\_epoch\\_size150.auto & 0.773313 & NaN & 46 & 50 & 0.890824 & 0.113911 \\\\\n1 & 20\\_0310\\_edm2020\\_synthetic & pre\\_dummy\\_epoch\\_size10.auto & 0.776778 & NaN & 44 & 50 & 0.894807 & 0.115647 \\\\\n2 & 20\\_0310\\_edm2020\\_synthetic & pre\\_dummy\\_epoch\\_size0.auto & 0.777116 & NaN & 26 & 50 & 0.792350 & 0.130606 \\\\\n\\bottomrule\n\\end{tabular}\n\n\\begin{tabular}{lllrrllrr}\n\\toprule\n{} & dataset & model & auc & auc\\_std & r1\\_good & r1\\_goodbad & r2 & r2\\_std \\\\\n\\midrule\n0 & 20\\_0310\\_edm2020\\_statics & pre\\_dummy\\_epoch\\_size150.auto & 0.792491 & 0.000426 & 716 & 1223 & 0.809500 & 0.158295 \\\\\n1 & 20\\_0310\\_edm2020\\_statics & pre\\_dummy\\_epoch\\_size10.auto & 0.794149 & 0.003777 & 934 & 1223 & 0.885513 & 0.126757 \\\\\n2 & 20\\_0310\\_edm2020\\_statics & pre\\_dummy\\_epoch\\_size0.auto & 0.787167 & 0.000661 & 639 & 1223 & 0.778891 & 0.149663 \\\\\n\\bottomrule\n\\end{tabular}\n\n"
]
],
[
[
"## NDCG distplot",
"_____no_output_____"
]
],
[
[
"def ndcg_distplot(config_name, ax, idx, label_names, bins=20):\n report_paths = [get_report_path(projectdir, config_name, e) for e in get_exp_names(projectdir, config_name)]\n reports = [load_json(r) for r in report_paths]\n for rep in reports:\n if rep['config']['pre_dummy_epoch_size'] not in {0, 10}:\n continue\n r = rep['indicator']['RPhard']['all']\n name = rep['config']['exp_name']\n sns.distplot(r, ax=ax,bins=bins, label=label_names[name], kde_kws={'clip': (0.0, 1.0)})\n ax.set_xlabel('NDCG score')\n if idx == 0:\n ax.set_ylabel('frequency')\n if idx == 3:\n ax.legend()\n ax.set_title(label_names[config_name])\n ax.set_xlim([0.59, 1.01])\n ax.title.set_fontsize(18)\n ax.xaxis.label.set_fontsize(14)\n ax.yaxis.label.set_fontsize(14)",
"_____no_output_____"
],
[
"fig, axs = plt.subplots(1, 4, sharey=True, figsize=(4*4,3))\n# plt.subplots_adjust(hspace=0.3)\nfig.subplots_adjust(hspace=.1, wspace=.16)\nlabel_names = {\n '20_0310_edm2020_assist09' : 'ASSISTment 2009',\n '20_0310_edm2020_assist15' : 'ASSISTment 2015',\n '20_0310_edm2020_synthetic': 'Simulated-5',\n '20_0310_edm2020_statics' : 'Statics 2011',\n 'pre_dummy_epoch_size10.auto': 'pre-train 10 epochs',\n 'pre_dummy_epoch_size0.auto': 'pre-train 0 epoch',\n}\nndcg_distplot('20_0310_edm2020_assist09' , ax=axs[0], idx=0, label_names=label_names)\nndcg_distplot('20_0310_edm2020_assist15' , ax=axs[1], idx=1, label_names=label_names)\nndcg_distplot('20_0310_edm2020_synthetic', ax=axs[2], idx=2, label_names=label_names)\nndcg_distplot('20_0310_edm2020_statics' , ax=axs[3], idx=3, label_names=label_names)",
"_____no_output_____"
]
],
[
[
"## Learning curve",
"_____no_output_____"
]
],
[
[
"def lc_plot(config_name, ax, idx, label_names):\n report_paths = [get_report_path(projectdir, config_name, e) for e in get_exp_names(projectdir, config_name)]\n reports = [load_json(r) for r in report_paths]\n for r in reports:\n if r['config']['pre_dummy_epoch_size'] not in {0, 10}:\n continue\n idclist_dic = r['indicator']\n idc = 'eval_auc'\n min_len = min([len(_x) for _x in idclist_dic['epoch'].values()])\n x = idclist_dic['epoch']['0'][:min_len] * (len(idclist_dic['epoch']) -1) # exclude 'all'\n y = []\n for _y in idclist_dic[idc].values():\n y += _y[:min_len]\n sns.lineplot(x=x, y=y, ax=ax, label=label_names[r['config']['exp_name']], ci='sd')\n ax.set_xlabel('epoch')\n if idx == 0:\n ax.set_ylabel('AUC')\n if idx == 3:\n ax.legend()\n else:\n ax.get_legend().remove()\n ax.set_title(label_names[config_name])\n ax.title.set_fontsize(18)\n ax.xaxis.label.set_fontsize(14)\n ax.yaxis.label.set_fontsize(14)",
"_____no_output_____"
],
[
"fig, axs = plt.subplots(1, 4, sharey=False, figsize=(4*4,3))\n# plt.subplots_adjust(hspace=0.3)\nfig.subplots_adjust(hspace=.1, wspace=.16)\nlabel_names = {\n '20_0310_edm2020_assist09' : 'ASSISTment 2009',\n '20_0310_edm2020_assist15' : 'ASSISTment 2015',\n '20_0310_edm2020_synthetic': 'Simulated-5',\n '20_0310_edm2020_statics' : 'Statics 2011',\n 'pre_dummy_epoch_size10.auto': 'pre-train 10 epochs',\n 'pre_dummy_epoch_size0.auto': 'pre-train 0 epoch',\n}\nlc_plot('20_0310_edm2020_assist09' , ax=axs[0], idx=0, label_names=label_names)\nlc_plot('20_0310_edm2020_assist15' , ax=axs[1], idx=1, label_names=label_names)\nlc_plot('20_0310_edm2020_synthetic', ax=axs[2], idx=2, label_names=label_names)\nlc_plot('20_0310_edm2020_statics' , ax=axs[3], idx=3, label_names=label_names)\nplt.show()",
"_____no_output_____"
]
],
[
[
"# `20_0310_edm2020_assist09`",
"_____no_output_____"
],
[
"## Simulated curve",
"_____no_output_____"
]
],
[
[
"config_name = '20_0310_edm2020_assist09'\nreport_list = []\nfor r in sorted([load_json(get_report_path(projectdir, e)) for e in get_exp_paths(projectdir, config_name)], key=lambda x: x['config']['pre_dummy_epoch_size']):\n if r['config']['pre_dummy_epoch_size'] not in {0, 10}:\n continue\n r['config']['exp_name'] = f\"DKT pre {r['config']['pre_dummy_epoch_size']}\"\n report_list.append(r)\n\n[r['config']['exp_name'] for r in report_list]",
"_____no_output_____"
],
[
"def get_simu_res(report_dic):\n return report_dic['indicator']['simu_pred']['all']\n\nsimures_list = []\nfor r in report_list:\n simu_res = get_simu_res(r)\n simures_list.append(simu_res)\n \nbase_idx = 0\nbase_res = {k:v for k, v in sorted(simures_list[base_idx].items(), key=lambda it: it[1][1][-1] - it[1][1][0])}\ndescres_list = []\nfor i, simu_res in enumerate(simures_list):\n if i == base_idx:\n continue\n desc_res = {k:simu_res[k] for k in base_res.keys()}\n descres_list.append(desc_res)",
"_____no_output_____"
],
[
"n_skills = report_list[base_idx]['config']['n_skills']\nh, w = (n_skills+7)//8, 8\nfigscale = 2.5\nhspace = 0.35\nfig, axs = plt.subplots(h, w, figsize=(w*figscale, h*figscale))\nplt.subplots_adjust(hspace=hspace)\nfor i, (v, (xidx, sanity)) in enumerate(list(base_res.items())[:h*w]):\n ax = axs[i//(w), i%(w)]\n ax.set_ylim([0, 1])\n ax.set_title('KC{}'.format(v))\n sns.lineplot(xidx, sanity, ax=ax, label='base', palette=\"ch:2.5,.25\")\n for i, desc_res in enumerate(descres_list):\n sns.lineplot(xidx, desc_res[v][1], ax=ax, label=str(i+1), palette=\"ch:2.5,.25\")\n ax.get_legend().remove()\nhandles, labels = ax.get_legend_handles_labels()\nfig.legend(handles, labels, loc='upper center')\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Single ones",
"_____no_output_____"
]
],
[
[
"def plot_single(kc):\n x, y = base_res[str(kc)]\n sns.lineplot(x=x, y=y)\nplot_single(78)",
"_____no_output_____"
],
[
"f, axs = plt.subplots(1, 3, sharey=True, figsize=(12,3))\nf.tight_layout()\nfor i, (kc, ax) in enumerate(zip([30, 83, 98], axs)):\n ax.set_ylim([0, 1])\n x, y = base_res[str(kc)]\n sns.lineplot(x=x, y=y, ax=ax)\n ax.set_title(f'KC{kc}')\n ax.set_ylabel('predicted accuracy')\n ax.set_xlabel('$k$\\n({})'.format(['a','b','c'][i]))\nplt.show()",
"_____no_output_____"
]
],
[
[
"## NDCG",
"_____no_output_____"
]
],
[
[
"for rep in report_list:\n r = rep['indicator']['RPhard']['all']\n name = rep['config']['exp_name']\n sns.distplot(r, bins=10, label=name, kde_kws={'clip': (0.0, 1.0)})\n print(f'{name:<20s}\\t{mean(r):.4f}±{stdev(r):.4f}')\nplt.legend()\nplt.show()",
"_____no_output_____"
],
[
"for rep in report_list:\n r = rep['indicator']['RPsoft']['all']\n name = rep['config']['exp_name']\n print(f'{name:<20s}\\tGood:Bad = {r[\"good\"]}:{r[\"bad\"]}')",
"_____no_output_____"
]
],
[
[
"## Learning curve",
"_____no_output_____"
]
],
[
[
"for r in report_list:\n show_valid_lc(r['config']['exp_name'], r['indicator'])\nplt.show()",
"_____no_output_____"
],
[
"for r in report_list:\n show_valid_lc(r['config']['exp_name'], r['indicator'], idc='eval_loss')\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Test AUC",
"_____no_output_____"
]
],
[
[
"for r in report_list:\n summarize_test_res(r)",
"_____no_output_____"
]
],
[
[
"# `Debug`",
"_____no_output_____"
],
[
"## Simulated curve",
"_____no_output_____"
]
],
[
[
"def get_simu_res(report_dic):\n return report_dic['indicator']['simu_pred']['all']\n\nsimures_list = []\nfor r in report_list:\n simu_res = get_simu_res(r)\n simures_list.append(simu_res)\n \nbase_idx = 0\nbase_res = {k:v for k, v in sorted(simures_list[base_idx].items(), key=lambda it: it[1][1][-1] - it[1][1][0])}\ndescres_list = []\nfor i, simu_res in enumerate(simures_list):\n if i == base_idx:\n continue\n desc_res = {k:simu_res[k] for k in base_res.keys()}\n descres_list.append(desc_res)",
"_____no_output_____"
]
],
[
[
"## NDCG",
"_____no_output_____"
]
],
[
[
"for rep in report_list:\n r = rep['indicator']['RPsoft']['all']\n name = rep['config']['exp_name']\n print(f'{name:<20s}\\tGood:Bad = {r[\"good\"]}:{r[\"bad\"]}')",
"_____no_output_____"
],
[
"for r in report_list:\n show_valid_lc(r['config']['exp_name'], r['indicator'])\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Test AUC",
"_____no_output_____"
],
[
"## Simulated curve",
"_____no_output_____"
]
],
[
[
"def get_simu_res(report_dic):\n return report_dic['indicator']['simu_pred']['all']\n\n\nsimures_list = []\nfor r in report_list:\n simu_res = get_simu_res(r)\n simures_list.append(simu_res)\n \n\nbase_idx = 1\nbase_res = {k:v for k, v in sorted(simures_list[base_idx].items(), key=lambda it: it[1][1][-1] - it[1][1][0])}\ndescres_list = []\nfor i, simu_res in enumerate(simures_list):\n if i == base_idx:\n continue\n desc_res = {k:simu_res[k] for k in base_res.keys()}\n descres_list.append(desc_res)",
"_____no_output_____"
]
],
[
[
"## NDCG",
"_____no_output_____"
]
],
[
[
"for rep in report_list:\n r = rep['indicator']['RPsoft']['all']\n name = rep['config']['exp_name']\n print(f'{name:<20s}\\tGood:Bad = {r[\"good\"]}:{r[\"bad\"]}')",
"_____no_output_____"
]
],
[
[
"## Learning curve",
"_____no_output_____"
]
],
[
[
"for r in report_list:\n show_valid_lc(r['config']['exp_name'], r['indicator'])\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Test AUC",
"_____no_output_____"
]
],
[
[
"def summarize_test_res(rep):\n print(rep['config']['exp_name'], end=':\\t')\n s = pd.Series([rep['best']['auc_epoch'][str(i)] for i in range(5)])\n print(f'Best epoch at {s.mean():>6.1f}±{s.std():<5.1f}', end='\\t')\n s = pd.Series([rep['best']['auc'][str(i)] for i in range(5)])\n print(f'Valid AUC: {s.mean()*100:.4f}±{s.std()*100:.4f}', end='\\t')\n s = rep['indicator']['test_auc']['all'][0]\n print(f'Test AUC: {s*100:.4f}')",
"_____no_output_____"
],
[
"for r in report_list:\n summarize_test_res(r)",
"_____no_output_____"
]
],
[
[
"# `20_0310_edm2020_synthetic`",
"_____no_output_____"
],
[
"## Simulated curve",
"_____no_output_____"
]
],
[
[
"config_name = '20_0310_edm2020_synthetic'\nreport_list = []\nfor r in sorted([load_json(get_report_path(projectdir, e)) for e in get_exp_paths(projectdir, config_name)], key=lambda x: x['config']['pre_dummy_epoch_size']):\n report_list.append(r)\n\n[r['config']['exp_name'] for r in report_list]",
"_____no_output_____"
],
[
"def get_simu_res(report_dic):\n return report_dic['indicator']['simu_pred']['all']\n\nsimures_list = []\nfor r in report_list:\n simu_res = get_simu_res(r)\n simures_list.append(simu_res)\n \nbase_idx = 0\nbase_res = {k:v for k, v in sorted(simures_list[base_idx].items(), key=lambda it: it[1][1][-1] - it[1][1][0])}\ndescres_list = []\nfor i, simu_res in enumerate(simures_list):\n if i == base_idx:\n continue\n desc_res = {k:simu_res[k] for k in base_res.keys()}\n descres_list.append(desc_res)",
"_____no_output_____"
],
[
"n_skills = report_list[base_idx]['config']['n_skills']\nh, w = (n_skills+7)//8, 8\nfigscale = 2.5\nhspace = 0.35\nfig, axs = plt.subplots(h, w, figsize=(w*figscale, h*figscale))\nplt.subplots_adjust(hspace=hspace)\nfor i, (v, (xidx, sanity)) in enumerate(list(base_res.items())[:h*w]):\n ax = axs[i//(w), i%(w)]\n ax.set_ylim([0, 1])\n ax.set_title('KC{} s{}0'.format(v, '>' if sanity[-1]>sanity[0] else '<'))\n sns.lineplot(xidx, sanity, ax=ax, label='base', palette=\"ch:2.5,.25\")\n for i, desc_res in enumerate(descres_list):\n sns.lineplot(xidx, desc_res[v][1], ax=ax, label=str(i+1), palette=\"ch:2.5,.25\")\n ax.get_legend().remove()\nhandles, labels = ax.get_legend_handles_labels()\nfig.legend(handles, labels, loc='upper center')\nplt.show()",
"_____no_output_____"
]
],
[
[
"## NDCG",
"_____no_output_____"
]
],
[
[
"for rep in report_list:\n r = rep['indicator']['RPhard']['all']\n name = rep['config']['exp_name']\n sns.distplot(r, bins=10, label=name, kde_kws={'clip': (0.0, 1.0)})\n print(f'{name:<20s}\\t{mean(r):.4f}±{stdev(r):.4f}')\nplt.legend()\nplt.show()",
"_____no_output_____"
],
[
"for rep in report_list:\n r = rep['indicator']['RPsoft']['all']\n name = rep['config']['exp_name']\n print(f'{name:<20s}\\tGood:Bad = {r[\"good\"]}:{r[\"bad\"]}')",
"_____no_output_____"
]
],
[
[
"## Learning curve",
"_____no_output_____"
]
],
[
[
"for r in report_list:\n show_valid_lc(r['config']['exp_name'], r['indicator'])\nplt.show()",
"_____no_output_____"
],
[
"for r in report_list:\n show_valid_lc(r['config']['exp_name'], r['indicator'])\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Test AUC",
"_____no_output_____"
]
],
[
[
"for r in report_list:\n show_valid_lc(r['config']['exp_name'], r['indicator'], idc='eval_loss')\n summarize_test_res(r, folds=1)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Test AUC",
"_____no_output_____"
]
],
[
[
"for r in report_list:\n show_valid_lc(r['config']['exp_name'], r['indicator'])\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Learning curve",
"_____no_output_____"
]
],
[
[
"for rep in report_list:\n r = rep['indicator']['RPsoft']['all']\n name = rep['config']['exp_name']\n print(f'{name:<20s}\\tGood:Bad = {r[\"good\"]}:{r[\"bad\"]}')",
"_____no_output_____"
]
],
[
[
"# `20_0310_edm2020_assist15`",
"_____no_output_____"
],
[
"## Simulated curve",
"_____no_output_____"
]
],
[
[
"# config_name = '20_0310_edm2020_assist15'\nconfig_name = '20_0310_edm2020_assist09'\n\nreport_paths = [get_report_path(projectdir, config_name, e) for e in get_exp_names(projectdir, config_name)]\nreports = [load_json(r) for r in report_paths]\n \n\n# print([r['config']['exp_name'] for r in reports])\n# =>['pre_dummy_epoch_size150.auto', 'pre_dummy_epoch_size10.auto', 'pre_dummy_epoch_size0.auto']\n\ndef get_simu_res(report_dic):\n return report_dic['indicator']['simu_pred']['all']\n\nsimures_list = []\nfor r in reports:\n if r['config']['pre_dummy_epoch_size'] not in {0, 10}:\n continue\n simu_res = get_simu_res(r)\n simures_list.append(simu_res)\n \nbase_idx = 1\nbase_res = {k:v for k, v in sorted(simures_list[base_idx].items(), key=lambda it: it[1][1][-1] - it[1][1][0])}\ndescres_list = []\nfor i, simu_res in enumerate(simures_list):\n if i == base_idx:\n continue\n desc_res = {k:simu_res[k] for k in base_res.keys()}\n descres_list.append(desc_res)\n\nn_skills = reports[base_idx]['config']['n_skills']\n# h, w = (n_skills+7)//8, 8\nh, w = 4, 8\nfigscale = 2.5\nhspace = 0.35\nfig, axs = plt.subplots(h, w, sharex=True, sharey=True, figsize=(w*figscale, h*figscale))\nplt.subplots_adjust(hspace=0.20, wspace=0.05)\nfor i, (v, (xidx, sanity)) in enumerate(list(base_res.items())[:h*w]):\n ax = axs[i//(w), i%(w)]\n ax.set_ylim([0, 1])\n ax.set_title(f'KC{v}')\n sns.lineplot(xidx, sanity, ax=ax, label='pre-train 0', palette=\"ch:2.5,.25\")\n for j, desc_res in enumerate(descres_list):\n sns.lineplot(xidx, desc_res[v][1], ax=ax, label=f'pre-train {[10,150][j]}', palette=\"ch:2.5,.25\")\n if i < 31:\n ax.get_legend().remove()\n else:\n ax.legend()\n break\n# handles, labels = ax.get_legend_handles_labels()\n# fig.legend(handles, labels, loc='upper center')\nplt.show()",
"_____no_output_____"
]
],
[
[
"## NDCG",
"_____no_output_____"
]
],
[
[
"for rep in report_list:\n r = rep['indicator']['RPhard']['all']\n name = rep['config']['exp_name']\n sns.distplot(r, bins=20, label=name, kde_kws={'clip': (0.0, 1.0)})\n print(f'{name:<20s}\\t{mean(r):.4f}±{stdev(r):.4f}')\nplt.legend()\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Learning curve AUC",
"_____no_output_____"
]
],
[
[
"for r in report_list:\n show_valid_lc(r['config']['exp_name'], r['indicator'])\n summarize_test_res(r)\nplt.show()",
"_____no_output_____"
],
[
"for r in report_list:\n show_valid_lc(r['config']['exp_name'], r['indicator'], idc='eval_loss')\nplt.show()",
"_____no_output_____"
]
]
]
| [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"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",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
]
|
cb5de545b15d2a98f4886c8337dc736c20fda79e | 604,163 | ipynb | Jupyter Notebook | experiments/convergence-an-experiment-quadrature.ipynb | matinmoezzi/neurodiffeq | eeb1fa848c14a4e3d9a833fb142371f7dec0a0bb | [
"MIT"
]
| 202 | 2021-04-11T00:24:13.000Z | 2022-03-30T17:06:40.000Z | experiments/convergence-an-experiment-quadrature.ipynb | DiffEqML/neurodiffeq | c5e7404c47a4729578ee2149f289be0a8909d775 | [
"MIT"
]
| 71 | 2019-09-04T01:21:57.000Z | 2021-03-31T10:12:32.000Z | experiments/convergence-an-experiment-quadrature.ipynb | DiffEqML/neurodiffeq | c5e7404c47a4729578ee2149f289be0a8909d775 | [
"MIT"
]
| 24 | 2021-04-24T08:04:57.000Z | 2022-03-23T08:26:43.000Z | 565.166511 | 557,968 | 0.936947 | [
[
[
"import numpy as np\nimport torch\nfrom torch import nn, optim\nimport matplotlib.pyplot as plt\nfrom neurodiffeq import diff \nfrom neurodiffeq.ode import IVP, solve_system, Monitor, ExampleGenerator, Solution, _trial_solution\nfrom neurodiffeq.networks import FCNN, SinActv \nfrom scipy.special import roots_legendre",
"_____no_output_____"
],
[
"torch.set_default_tensor_type('torch.DoubleTensor')",
"_____no_output_____"
],
[
"FROM, TO = 0., 5.\nN_NODE = 8\nQUADRATURE_DEGREE = 32\nTRAIN_SIZE = 10 # the training set is not actually used\nVALID_SIZE = 10\nMAX_EPOCHS = 10000\n\nq_points, q_weights = roots_legendre(QUADRATURE_DEGREE)\nglobal_q_points = FROM + torch.tensor(q_points).reshape(-1, 1) * (TO-FROM)\nglobal_q_points.requires_grad = True\nglobal_q_weights = torch.tensor(q_weights).reshape(-1, 1)",
"_____no_output_____"
],
[
"def solve_system_quadrature(\n ode_system, conditions, t_min, t_max,\n single_net=None, nets=None, train_generator=None, shuffle=True, valid_generator=None,\n optimizer=None, criterion=None, additional_loss_term=None, metrics=None, batch_size=16,\n max_epochs=1000,\n monitor=None, return_internal=False,\n return_best=False,\n):\n ########################################### subroutines ###########################################\n def train(train_generator, net, nets, ode_system, conditions, criterion, additional_loss_term, shuffle, optimizer):\n train_examples_t = train_generator.get_examples()\n train_examples_t = train_examples_t.reshape((-1, 1))\n n_examples_train = train_generator.size\n idx = np.random.permutation(n_examples_train) if shuffle else np.arange(n_examples_train)\n\n batch_start, batch_end = 0, batch_size\n while batch_start < n_examples_train:\n if batch_end > n_examples_train:\n batch_end = n_examples_train\n batch_idx = idx[batch_start:batch_end]\n ts = train_examples_t[batch_idx]\n\n train_loss_batch = calculate_loss(ts, net, nets, ode_system, conditions, criterion, additional_loss_term)\n\n optimizer.zero_grad()\n train_loss_batch.backward()\n optimizer.step()\n\n batch_start += batch_size\n batch_end += batch_size\n\n train_loss_epoch = calculate_loss(train_examples_t, net, nets, ode_system, conditions, criterion, additional_loss_term)\n \n train_metrics_epoch = calculate_metrics(train_examples_t, net, nets, conditions, metrics)\n return train_loss_epoch, train_metrics_epoch\n\n def valid(valid_generator, net, nets, ode_system, conditions, criterion, additional_loss_term):\n valid_examples_t = valid_generator.get_examples()\n valid_examples_t = valid_examples_t.reshape((-1, 1))\n valid_loss_epoch = calculate_loss(valid_examples_t, net, nets, ode_system, conditions, criterion, additional_loss_term)\n valid_loss_epoch = valid_loss_epoch.item()\n\n valid_metrics_epoch = calculate_metrics(valid_examples_t, net, nets, conditions, metrics)\n return valid_loss_epoch, valid_metrics_epoch\n\n # calculate the loss with Gaussian quadrature\n # uses global variables, just for convenience\n def calculate_loss(ts, net, nets, ode_system, conditions, criterion, additional_loss_term):\n ts = global_q_points\n ws = global_q_weights\n us = _trial_solution(net, nets, ts, conditions)\n Futs = ode_system(*us, ts)\n loss = sum(\n torch.sum(ws * Fut**2) for Fut in Futs\n )\n return loss\n \n def calculate_metrics(ts, net, nets, conditions, metrics):\n us = _trial_solution(net, nets, ts, conditions)\n metrics_ = {\n metric_name: metric_function(*us, ts).item()\n for metric_name, metric_function in metrics.items()\n }\n return metrics_\n ###################################################################################################\n\n if single_net and nets:\n raise RuntimeError('Only one of net and nets should be specified')\n # defaults to use a single neural network\n if (not single_net) and (not nets):\n single_net = FCNN(n_input_units=1, n_output_units=len(conditions), n_hidden_units=32, n_hidden_layers=1,\n actv=nn.Tanh)\n if single_net:\n # mark the Conditions so that we know which condition correspond to which output unit\n for ith, con in enumerate(conditions):\n con.set_impose_on(ith)\n if not train_generator:\n if (t_min is None) or (t_max is None):\n raise RuntimeError('Please specify t_min and t_max when train_generator is not specified')\n train_generator = ExampleGenerator(32, t_min, t_max, method='equally-spaced-noisy')\n if not valid_generator:\n if (t_min is None) or (t_max is None):\n raise RuntimeError('Please specify t_min and t_max when train_generator is not specified')\n valid_generator = ExampleGenerator(32, t_min, t_max, method='equally-spaced')\n if (not optimizer) and single_net: # using a single net\n optimizer = optim.Adam(single_net.parameters(), lr=0.001)\n if (not optimizer) and nets: # using multiple nets\n all_parameters = []\n for net in nets:\n all_parameters += list(net.parameters())\n optimizer = optim.Adam(all_parameters, lr=0.001)\n if not criterion:\n criterion = nn.MSELoss()\n if metrics is None:\n metrics = {}\n\n history = {}\n history['train_loss'] = []\n history['valid_loss'] = []\n for metric_name, _ in metrics.items():\n history['train__' + metric_name] = []\n history['valid__' + metric_name] = []\n\n if return_best:\n valid_loss_epoch_min = np.inf\n solution_min = None\n\n for epoch in range(max_epochs):\n train_loss_epoch, train_metrics_epoch = train(train_generator, single_net, nets, ode_system, conditions, criterion, additional_loss_term, shuffle,\n optimizer)\n history['train_loss'].append(train_loss_epoch)\n for metric_name, metric_value in train_metrics_epoch.items():\n history['train__'+metric_name].append(metric_value)\n\n valid_loss_epoch, valid_metrics_epoch = valid(valid_generator, single_net, nets, ode_system, conditions, criterion, additional_loss_term,)\n history['valid_loss'].append(valid_loss_epoch)\n for metric_name, metric_value in valid_metrics_epoch.items():\n history['valid__'+metric_name].append(metric_value)\n\n if monitor and epoch % monitor.check_every == 0:\n monitor.check(single_net, nets, conditions, history)\n\n if return_best and valid_loss_epoch < valid_loss_epoch_min:\n valid_loss_epoch_min = valid_loss_epoch\n solution_min = Solution(single_net, nets, conditions)\n\n if return_best:\n solution = solution_min\n else:\n solution = Solution(single_net, nets, conditions)\n\n if return_internal:\n internal = {\n 'single_net': single_net,\n 'nets': nets,\n 'conditions': conditions,\n 'train_generator': train_generator,\n 'valid_generator': valid_generator,\n 'optimizer': optimizer,\n 'criterion': criterion\n }\n return solution, history, internal\n else:\n return solution, history",
"_____no_output_____"
],
[
"%matplotlib notebook\n\nodes = lambda x, y, t : [diff(x, t) + t*y,\n diff(y, t) - t*x]\n\nivps = [\n IVP(t_0=0., x_0=1.),\n IVP(t_0=0., x_0=0.)\n]\n\nnets = [\n FCNN(n_hidden_units=N_NODE, n_hidden_layers=1, actv=SinActv),\n FCNN(n_hidden_units=N_NODE, n_hidden_layers=1, actv=SinActv)\n]\n\ntrain_gen = ExampleGenerator(TRAIN_SIZE, t_min=FROM, t_max=TO, method='equally-spaced')\nvalid_gen = ExampleGenerator(VALID_SIZE, t_min=FROM, t_max=TO, method='equally-spaced')\n\ndef rmse(x, y, t):\n true_x = torch.cos(t**2/2)\n true_y = torch.sin(t**2/2)\n x_sse = torch.sum((x - true_x) ** 2)\n y_sse = torch.sum((y - true_y) ** 2)\n return torch.sqrt( (x_sse+y_sse)/(len(x)+len(y)) )\n\nsolution, _ = solve_system_quadrature(\n ode_system=odes, \n conditions=ivps, \n t_min=FROM, t_max=TO,\n nets=nets,\n train_generator=train_gen,\n valid_generator=valid_gen,\n batch_size=TRAIN_SIZE,\n max_epochs=MAX_EPOCHS,\n monitor=Monitor(t_min=FROM, t_max=TO, check_every=100),\n metrics={'rmse': rmse}\n)",
"_____no_output_____"
]
]
]
| [
"code"
]
| [
[
"code",
"code",
"code",
"code",
"code"
]
]
|
cb5de723b79fe3e360adaa7f6fca8b8aa431dada | 29,094 | ipynb | Jupyter Notebook | knowknow/creating variables/trend summaries/cysum _ summarizing citation's cited career.ipynb | adnanjmi21/knowknow | cd858c1746c815361dc075a3e445c3d0cb8e2d29 | [
"MIT"
]
| 1 | 2020-07-07T15:15:50.000Z | 2020-07-07T15:15:50.000Z | knowknow/creating variables/trend summaries/cysum _ summarizing citation's cited career.ipynb | adnanjmi21/knowknow | cd858c1746c815361dc075a3e445c3d0cb8e2d29 | [
"MIT"
]
| null | null | null | knowknow/creating variables/trend summaries/cysum _ summarizing citation's cited career.ipynb | adnanjmi21/knowknow | cd858c1746c815361dc075a3e445c3d0cb8e2d29 | [
"MIT"
]
| null | null | null | 44.14871 | 187 | 0.559359 | [
[
[
"# imports",
"_____no_output_____"
]
],
[
[
"import sys; sys.path.append(_dh[0].split(\"knowknow\")[0])\nfrom knowknow import *",
"_____no_output_____"
]
],
[
[
"# User settings",
"_____no_output_____"
]
],
[
[
"database_name = \"sociology-wos\"",
"_____no_output_____"
],
[
"pubyears = None\nif 'wos' in database_name:\n pubyears = load_variable(\"%s.pubyears\" % database_name)\n print(\"Pubyears loaded for %s entries\" % len(pubyears.keys()))\n RELIABLE_DATA_ENDS_HERE = 2019\nif 'jstor' in database_name:\n RELIABLE_DATA_ENDS_HERE = 2010",
"Pubyears loaded for 397702 entries\n"
],
[
"import re\n\ndef create_cysum(cits, typ):\n \n meta_counters = defaultdict(int)\n\n cy = defaultdict(lambda:defaultdict(int))\n\n for (c,y),count in cits['c.fy'].items():\n cy[c][y] = count\n \n if 'fy' in cits:\n fyc = cits['fy']\n else:\n fyc = cits['y']\n\n cysum = {}\n for ci,c in enumerate(cy):\n meta_counters['at least one citation'] += 1\n\n count = cy[c]\n prop = {\n y: county / fyc[y]\n for y,county in count.items()\n }\n\n res = {\n 'first': min(count),\n 'last': max(count),\n 'maxcounty': max(count, key=lambda y:(count[y],y)),\n 'maxpropy': max(count, key=lambda y:(prop[y],y))\n }\n\n res['maxprop'] = prop[ res['maxpropy'] ]\n res['maxcount'] = count[ res['maxcounty'] ]\n res['total'] = sum(count.values())\n res['totalprop'] = sum(prop.values())\n res['name'] = c\n \n # gotta do something here...\n res['type'] = 'article'\n \n if typ == 'wos':\n sp = c.split(\"|\")\n if len(sp) < 2:\n continue\n try:\n res['pub'] = int(sp[1])\n res['type'] = 'article'\n except ValueError:\n res['type'] = 'book'\n res['pub'] = pubyears[c]\n \n elif typ == 'jstor':\n inparens = re.findall(r'\\(([^)]+)\\)', c)[0]\n res['pub'] = int(inparens)\n \n\n \n \n \n \n \n \n \n \n \n\n\n\n\n \n \n \n \n # DEFINING DEATH1\n # death1 is max, as long as it's before RELIABLE_DATA_ENDS_HERE\n res['death1'] = None\n if res['maxpropy'] <= RELIABLE_DATA_ENDS_HERE:\n res['death1'] = res['maxcounty']\n \n \n \n \n # DEFINING DEATH2 \n \n # this list has an entry for each year after and including the maximum citations ever received (the last time)\n # look ahead to the next ten years and take the average\n next_year_sums = [\n (ycheck, sum( c for y,c in count.items() if ycheck + 10 >= y > ycheck ))\n for ycheck in range(res['maxcounty'], RELIABLE_DATA_ENDS_HERE - 10) \n ]\n\n # need to make sure ALL subsequent decade intervals are also less...\n my_death_year = None\n\n l = len(next_year_sums)\n for i in range(l):\n not_this_one = False\n for j in range(i,l):\n if next_year_sums[j][1] >= res['maxcount']:\n not_this_one = True\n if not_this_one:\n break\n\n if not_this_one:\n continue\n\n my_death_year = next_year_sums[i][0]\n break\n\n if not len(next_year_sums):\n res['death2'] = None\n else:\n res['death2'] = my_death_year\n \n \n\n # DEATH3 is last, as long as it's before RELIABLE_DATA_ENDS_HERE\n res['death3'] = None\n if res['last'] <= RELIABLE_DATA_ENDS_HERE:\n res['death3'] = res['last']\n \n \n \n \n \n # DEATH5\n # 90% of their citations were received before death4, and it's been at least 30% of their lifespan\n myspan = np.array( [cits['c.fy'][(c,ycheck)] for ycheck in range(1900, 2020)] )\n \n res['death5'] = None\n\n Ea = np.sum(myspan)\n csum = np.sum(myspan)\n\n nonzeroyears = list(np.where(myspan>0))\n if not len(nonzeroyears):\n continue\n \n try:\n firsti = np.min(nonzeroyears)\n except:\n print(\"some strange error, that shouldn't happen, right??\")\n \n first_year = firsti + 1900\n\n for cci, cc in enumerate(myspan[firsti:]):\n\n this_year = first_year+cci\n \n # running residual... \n Ea -= cc\n\n # don't let them die too soon\n if cc == 0:\n continue\n\n if Ea/csum < 0.1 and (RELIABLE_DATA_ENDS_HERE - this_year)/(RELIABLE_DATA_ENDS_HERE - first_year) > 0.3:\n res['death5'] = this_year\n break\n \n \n \n \n \n \n if res['death2'] is not None and res['death2'] < res['pub']:\n meta_counters['death2 < pub!? dropped.'] += 1\n # small error catch\n continue\n\n #small error catch\n if res['maxpropy'] < res['pub']:\n meta_counters['maxpropy < pub!? dropped.'] += 1\n continue\n\n # don't care about those with only a single citation\n if res['total'] <= 1:\n meta_counters['literally 1 citation. dropped.'] += 1\n continue\n\n # we really don't care about those that never rise in use\n #if res['first'] == res['maxpropy']:\n # continue\n meta_counters['passed tests pre-blacklist'] += 1\n\n cysum[c] = res\n \n \n \n \n \n \n blacklist = []\n for b in blacklist:\n if b in cysum:\n del cysum[b]\n \n todelete = []\n\n for c in todelete:\n if c in cysum:\n meta_counters['passed all other tests but was blacklisted'] += 1\n del cysum[c]\n \n print(dict(meta_counters))\n \n return cysum",
"_____no_output_____"
],
[
"OVERWRITE_EXISTING = True\n\nprint(\"Processing database '%s'\"%database_name)\n\nvarname = \"%s.cysum\"%database_name\n\nrun = True # run \nif not OVERWRITE_EXISTING:\n try: \n load_variable(varname)\n run = False\n except FileNotFoundError:\n pass\n\nif run:\n cits = get_cnt(\"%s.doc\"%database_name, ['c.fy','fy'])\n\n if 'wos' in database_name and 'jstor' in database_name:\n raise Exception(\"Please put 'wos' or 'jstor' but not both in any database_name.\")\n elif 'wos' in database_name:\n cysum = create_cysum(cits, 'wos')\n elif 'jstor' in database_name:\n cysum = create_cysum(cits, 'jstor')\n else:\n raise Exception(\"Please include either 'wos' or 'jstor' in the name of the variable. This keys which data processing algorithm you used.\")\n\n save_variable(varname, cysum)\n\n print(\"%s cysum entries for database '%s'\" % (len(cysum), database_name))",
"Processing database 'sociology-wos'\nLoaded keys: dict_keys(['c.fy', 'fy'])\nAvailable keys: ['c', 'c.fj', 'c.fy', 'c.fy.j', 'fa', 'fa.c', 'fa.fj', 'fa.fj.fy', 'fa.fy', 'fj', 'fj.fy', 'fj.ta', 'fj.ty', 'fy', 'fy.ta', 'fy.ty', 'ta', 'ty']\n"
]
],
[
[
"# only necessary if you plan on filtering based on this set",
"_____no_output_____"
]
],
[
[
"save_variable(\"%s.included_citations\"%database_name, set(cysum.keys()))",
"_____no_output_____"
]
]
]
| [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
]
| [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
]
|
cb5dfe8a222fffadc1e3342348779a09322718e3 | 30,284 | ipynb | Jupyter Notebook | clases/ML/numeros.ipynb | soren-hub/Neural_networks_material | ad8d0422b3d3bb66ff061e7e3902ca48d981f93c | [
"Apache-2.0"
]
| null | null | null | clases/ML/numeros.ipynb | soren-hub/Neural_networks_material | ad8d0422b3d3bb66ff061e7e3902ca48d981f93c | [
"Apache-2.0"
]
| null | null | null | clases/ML/numeros.ipynb | soren-hub/Neural_networks_material | ad8d0422b3d3bb66ff061e7e3902ca48d981f93c | [
"Apache-2.0"
]
| null | null | null | 42.533708 | 5,148 | 0.598402 | [
[
[
"## Importando librerías",
"_____no_output_____"
]
],
[
[
"from keras.datasets import mnist\nfrom keras import layers, models\nfrom keras.utils import to_categorical\nimport numpy as np\nimport matplotlib.pyplot as plt",
"_____no_output_____"
]
],
[
[
"## Nuestro set de datos",
"_____no_output_____"
]
],
[
[
"(train_data, train_labels), (test_data, test_labels) = mnist.load_data()",
"Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz\n11493376/11490434 [==============================] - 1s 0us/step\n"
],
[
"train_data.shape",
"_____no_output_____"
],
[
"train_data[0]",
"_____no_output_____"
],
[
"plt.imshow(train_data[3])\nplt.show",
"_____no_output_____"
],
[
"train_labels[45]",
"_____no_output_____"
]
],
[
[
"## Creando un modelo de datos",
"_____no_output_____"
]
],
[
[
"model = models.Sequential()\nmodel.add(layers.Dense(512,activation='relu', input_shape=(28*28,)))\n#model.add(layers.Dense(50,kernel_initializer= \"uniform\",activation='relu'))\n#model.add(layers.Dense(100,kernel_initializer= \"uniform\",activation='softmax'))\n#model.add(layers.Dense(50,kernel_initializer= \"uniform\",activation='relu'))\nmodel.add(layers.Dense(10,activation='softmax'))",
"_____no_output_____"
],
[
"model.compile(optimizer='rmsprop',\n loss='categorical_crossentropy',\n metrics=['accuracy'])",
"_____no_output_____"
],
[
"model.summary()",
"Model: \"sequential_5\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense_15 (Dense) (None, 512) 401920 \n_________________________________________________________________\ndense_16 (Dense) (None, 50) 25650 \n_________________________________________________________________\ndense_17 (Dense) (None, 100) 5100 \n_________________________________________________________________\ndense_18 (Dense) (None, 50) 5050 \n_________________________________________________________________\ndense_19 (Dense) (None, 10) 510 \n=================================================================\nTotal params: 438,230\nTrainable params: 438,230\nNon-trainable params: 0\n_________________________________________________________________\n"
]
],
[
[
"## Limpieza de datos",
"_____no_output_____"
]
],
[
[
"x_train = train_data.reshape((60000,28,28))\n",
"_____no_output_____"
],
[
"plt.imshow(x_train[0])",
"_____no_output_____"
]
],
[
[
"```\nreshape((60000,28,28))==reshape((60000,28*28))\n```",
"_____no_output_____"
]
],
[
[
"x_train = train_data.reshape((60000,28*28))\nx_train = x_train.astype('float32')/255\n\nx_test = test_data.reshape((10000,28*28))\nx_test = x_test.astype('float32')/255",
"_____no_output_____"
],
[
"y_train = to_categorical(train_labels)\ny_test = to_categorical(test_labels)",
"_____no_output_____"
],
[
"train_labels[0]",
"_____no_output_____"
],
[
"y_train[0]",
"_____no_output_____"
]
],
[
[
"## Entrenando el modelo",
"_____no_output_____"
]
],
[
[
"model.fit(x_train, y_train, epochs=10, batch_size=128)",
"Epoch 1/10\n469/469 [==============================] - 2s 5ms/step - loss: 0.2620 - accuracy: 0.9245\nEpoch 2/10\n469/469 [==============================] - 2s 4ms/step - loss: 0.1039 - accuracy: 0.9693\nEpoch 3/10\n469/469 [==============================] - 2s 5ms/step - loss: 0.0684 - accuracy: 0.9796\nEpoch 4/10\n469/469 [==============================] - 2s 5ms/step - loss: 0.0499 - accuracy: 0.9851\nEpoch 5/10\n469/469 [==============================] - 2s 4ms/step - loss: 0.0380 - accuracy: 0.9886\nEpoch 6/10\n469/469 [==============================] - 2s 4ms/step - loss: 0.0281 - accuracy: 0.9918\nEpoch 7/10\n469/469 [==============================] - 2s 4ms/step - loss: 0.0218 - accuracy: 0.9936\nEpoch 8/10\n469/469 [==============================] - 2s 4ms/step - loss: 0.0172 - accuracy: 0.9948\nEpoch 9/10\n469/469 [==============================] - 2s 4ms/step - loss: 0.0130 - accuracy: 0.9962\nEpoch 10/10\n469/469 [==============================] - 2s 4ms/step - loss: 0.0103 - accuracy: 0.9971\n"
]
],
[
[
"## Evaluando sobre data de test",
"_____no_output_____"
]
],
[
[
"model.evaluate(x_test,y_test)[1]*100",
"313/313 [==============================] - 0s 802us/step - loss: 0.0671 - accuracy: 0.9818\n"
]
]
]
| [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
]
| [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
]
|
cb5e02596bffc2b19b5f64686fe690aaa93e86e8 | 2,917 | ipynb | Jupyter Notebook | Notebook/Ex_Jupyter/Untitled4.ipynb | habimis95/hello-world | 0c8b876e3cc291b282388e23b4904453d9123b70 | [
"BSD-3-Clause"
]
| null | null | null | Notebook/Ex_Jupyter/Untitled4.ipynb | habimis95/hello-world | 0c8b876e3cc291b282388e23b4904453d9123b70 | [
"BSD-3-Clause"
]
| 1 | 2020-07-21T03:03:10.000Z | 2020-07-21T03:05:22.000Z | Notebook/Ex_Jupyter/Untitled4.ipynb | habimis95/hello-world | 0c8b876e3cc291b282388e23b4904453d9123b70 | [
"BSD-3-Clause"
]
| null | null | null | 35.573171 | 1,283 | 0.588618 | [
[
[
"import numpy as np",
"_____no_output_____"
],
[
"f1 = open('heights_1.txt')\nf2 = open('weights_1.txt')\ndata = data.read(f1)\ndata = data.read(f2)\nf1.close()\nf1.close()\n",
"_____no_output_____"
]
]
]
| [
"code"
]
| [
[
"code",
"code"
]
]
|
cb5e248cd2c314042f281e7213c001b28753eed8 | 6,462 | ipynb | Jupyter Notebook | Part 4 - Fashion-MNIST Exercise.ipynb | spatialreasoning/DL_PyTorch | 37bb8fdd8f31926dc20efff9e57da292e27f0bad | [
"MIT"
]
| null | null | null | Part 4 - Fashion-MNIST Exercise.ipynb | spatialreasoning/DL_PyTorch | 37bb8fdd8f31926dc20efff9e57da292e27f0bad | [
"MIT"
]
| null | null | null | Part 4 - Fashion-MNIST Exercise.ipynb | spatialreasoning/DL_PyTorch | 37bb8fdd8f31926dc20efff9e57da292e27f0bad | [
"MIT"
]
| null | null | null | 33.832461 | 548 | 0.625658 | [
[
[
"# Classifying Fashion-MNIST\n\nNow it's your turn to build and train a neural network. You'll be using the [Fashion-MNIST dataset](https://github.com/zalandoresearch/fashion-mnist), a drop-in replacement for the MNIST dataset. MNIST is actually quite trivial with neural networks where you can easily achieve better than 97% accuracy. Fashion-MNIST is a set of 28x28 greyscale images of clothes. It's more complex than MNIST, so it's a better representation of the actual performance of your network, and a better representation of datasets you'll use in the real world.\n\n<img src='assets/fashion-mnist-sprite.png' width=500px>\n\nIn this notebook, you'll build your own neural network. For the most part, you could just copy and paste the code from Part 3, but you wouldn't be learning. It's important for you to write the code yourself and get it to work. Feel free to consult the previous notebook though as you work through this.\n\nFirst off, let's load the dataset through torchvision.",
"_____no_output_____"
]
],
[
[
"import torch\nfrom torchvision import datasets, transforms\nimport helper\n\n# Define a transform to normalize the data\ntransform = transforms.Compose([transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n# Download and load the training data\ntrainset = datasets.FashionMNIST('F_MNIST_data/', download=True, train=True, transform=transform)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)\n\n# Download and load the test data\ntestset = datasets.FashionMNIST('F_MNIST_data/', download=True, train=False, transform=transform)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=True)",
"_____no_output_____"
]
],
[
[
"Here we can see one of the images.",
"_____no_output_____"
]
],
[
[
"image, label = next(iter(trainloader))\nhelper.imshow(image[0,:]);",
"_____no_output_____"
]
],
[
[
"With the data loaded, it's time to import the necessary packages.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport time\n\nimport torch\nfrom torch import nn\nfrom torch import optim\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms\n\nimport helper",
"_____no_output_____"
]
],
[
[
"## Building the network\n\nHere you should define your network. As with MNIST, each image is 28x28 which is a total of 784 pixels, and there are 10 classes. You should include at least one hidden layer. We suggest you use ReLU activations for the layers and to return the logits from the forward pass. It's up to you how many layers you add and the size of those layers.",
"_____no_output_____"
]
],
[
[
"# TODO: Define your network architecture here",
"_____no_output_____"
]
],
[
[
"# Train the network\n\nNow you should create your network and train it. First you'll want to define [the criterion](http://pytorch.org/docs/master/nn.html#loss-functions) ( something like `nn.CrossEntropyLoss`) and [the optimizer](http://pytorch.org/docs/master/optim.html) (typically `optim.SGD` or `optim.Adam`).\n\nThen write the training code. Remember the training pass is a fairly straightforward process:\n\n* Make a forward pass through the network to get the logits \n* Use the logits to calculate the loss\n* Perform a backward pass through the network with `loss.backward()` to calculate the gradients\n* Take a step with the optimizer to update the weights\n\nBy adjusting the hyperparameters (hidden units, learning rate, etc), you should be able to get the training loss below 0.4.",
"_____no_output_____"
]
],
[
[
"# TODO: Create the network, define the criterion and optimizer\n",
"_____no_output_____"
],
[
"# TODO: Train the network here\n",
"_____no_output_____"
],
[
"# Test out your network!\n\ndataiter = iter(testloader)\nimages, labels = dataiter.next()\nimg = images[0]\n# Convert 2D image to 1D vector\nimg = img.resize_(1, 784)\n\n# TODO: Calculate the class probabilities (softmax) for img\nps = \n\n# Plot the image and probabilities\nhelper.view_classify(img.resize_(1, 28, 28), ps, version='Fashion')",
"_____no_output_____"
]
],
[
[
"Now that your network is trained, you'll want to save it to disk so you can load it later instead of training it again. Obviously, it's impractical to train a network every time you need one. In practice, you'll train it once, save the model, then reload it for further training or making predictions. In the next part, I'll show you how to save and load trained models.",
"_____no_output_____"
]
]
]
| [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
]
| [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
]
]
|
cb5e270bf1a80774dc98eb6d96a3d55880d2e8c0 | 111,239 | ipynb | Jupyter Notebook | Machine Learning & Data Science Masterclass - JP/12-K-Nearest-Neighbors/01-KNN-Exercise-MySolutions.ipynb | ptyadana/probability-and-statistics-for-business-and-data-science | 6c4d09c70e4c8546461eb7ebc401bb95a0827ef2 | [
"MIT"
]
| 10 | 2021-01-14T15:14:03.000Z | 2022-02-19T14:06:25.000Z | Machine Learning & Data Science Masterclass - JP/12-K-Nearest-Neighbors/01-KNN-Exercise-MySolutions.ipynb | ptyadana/probability-and-statistics-for-business-and-data-science | 6c4d09c70e4c8546461eb7ebc401bb95a0827ef2 | [
"MIT"
]
| null | null | null | Machine Learning & Data Science Masterclass - JP/12-K-Nearest-Neighbors/01-KNN-Exercise-MySolutions.ipynb | ptyadana/probability-and-statistics-for-business-and-data-science | 6c4d09c70e4c8546461eb7ebc401bb95a0827ef2 | [
"MIT"
]
| 8 | 2021-03-24T13:00:02.000Z | 2022-03-27T16:32:20.000Z | 71.90627 | 36,684 | 0.732063 | [
[
[
"<center><em>Copyright by Pierian Data Inc.</em></center>\n<center><em>For more information, visit us at <a href='http://www.pieriandata.com'>www.pieriandata.com</a></em></center>",
"_____no_output_____"
],
[
"# KNN Project Exercise \n\nDue to the simplicity of KNN for Classification, let's focus on using a PipeLine and a GridSearchCV tool, since these skills can be generalized for any model.",
"_____no_output_____"
],
[
"\n## The Sonar Data \n\n### Detecting a Rock or a Mine\n\nSonar (sound navigation ranging) is a technique that uses sound propagation (usually underwater, as in submarine navigation) to navigate, communicate with or detect objects on or under the surface of the water, such as other vessels.\n\n<img src=\"sonar.jpg\" style=\"max-height: 500px; max-width: 500px;\">\n\nThe data set contains the response metrics for 60 separate sonar frequencies sent out against a known mine field (and known rocks). These frequencies are then labeled with the known object they were beaming the sound at (either a rock or a mine). \n\n<img src=\"mine.jpg\" style=\"max-height: 500px; max-width: 500px;\">\n\nOur main goal is to create a machine learning model capable of detecting the difference between a rock or a mine based on the response of the 60 separate sonar frequencies.\n\n\nData Source: https://archive.ics.uci.edu/ml/datasets/Connectionist+Bench+(Sonar,+Mines+vs.+Rocks)\n\n### Complete the Tasks in bold\n\n**TASK: Run the cells below to load the data.**",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns",
"_____no_output_____"
],
[
"df = pd.read_csv('../Data/sonar.all-data.csv')",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
]
],
[
[
"## Data Exploration",
"_____no_output_____"
]
],
[
[
"df.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 208 entries, 0 to 207\nData columns (total 61 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Freq_1 208 non-null float64\n 1 Freq_2 208 non-null float64\n 2 Freq_3 208 non-null float64\n 3 Freq_4 208 non-null float64\n 4 Freq_5 208 non-null float64\n 5 Freq_6 208 non-null float64\n 6 Freq_7 208 non-null float64\n 7 Freq_8 208 non-null float64\n 8 Freq_9 208 non-null float64\n 9 Freq_10 208 non-null float64\n 10 Freq_11 208 non-null float64\n 11 Freq_12 208 non-null float64\n 12 Freq_13 208 non-null float64\n 13 Freq_14 208 non-null float64\n 14 Freq_15 208 non-null float64\n 15 Freq_16 208 non-null float64\n 16 Freq_17 208 non-null float64\n 17 Freq_18 208 non-null float64\n 18 Freq_19 208 non-null float64\n 19 Freq_20 208 non-null float64\n 20 Freq_21 208 non-null float64\n 21 Freq_22 208 non-null float64\n 22 Freq_23 208 non-null float64\n 23 Freq_24 208 non-null float64\n 24 Freq_25 208 non-null float64\n 25 Freq_26 208 non-null float64\n 26 Freq_27 208 non-null float64\n 27 Freq_28 208 non-null float64\n 28 Freq_29 208 non-null float64\n 29 Freq_30 208 non-null float64\n 30 Freq_31 208 non-null float64\n 31 Freq_32 208 non-null float64\n 32 Freq_33 208 non-null float64\n 33 Freq_34 208 non-null float64\n 34 Freq_35 208 non-null float64\n 35 Freq_36 208 non-null float64\n 36 Freq_37 208 non-null float64\n 37 Freq_38 208 non-null float64\n 38 Freq_39 208 non-null float64\n 39 Freq_40 208 non-null float64\n 40 Freq_41 208 non-null float64\n 41 Freq_42 208 non-null float64\n 42 Freq_43 208 non-null float64\n 43 Freq_44 208 non-null float64\n 44 Freq_45 208 non-null float64\n 45 Freq_46 208 non-null float64\n 46 Freq_47 208 non-null float64\n 47 Freq_48 208 non-null float64\n 48 Freq_49 208 non-null float64\n 49 Freq_50 208 non-null float64\n 50 Freq_51 208 non-null float64\n 51 Freq_52 208 non-null float64\n 52 Freq_53 208 non-null float64\n 53 Freq_54 208 non-null float64\n 54 Freq_55 208 non-null float64\n 55 Freq_56 208 non-null float64\n 56 Freq_57 208 non-null float64\n 57 Freq_58 208 non-null float64\n 58 Freq_59 208 non-null float64\n 59 Freq_60 208 non-null float64\n 60 Label 208 non-null object \ndtypes: float64(60), object(1)\nmemory usage: 99.2+ KB\n"
],
[
"df.describe()",
"_____no_output_____"
]
],
[
[
"\n**TASK: Create a heatmap of the correlation between the difference frequency responses.**",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(8,6))\nsns.heatmap(df.corr(), cmap='coolwarm');",
"_____no_output_____"
]
],
[
[
"-----",
"_____no_output_____"
],
[
"**TASK: What are the top 5 correlated frequencies with the target\\label?**\n\n*Note: You many need to map the label to 0s and 1s.*\n\n*Additional Note: We're looking for **absolute** correlation values.*",
"_____no_output_____"
]
],
[
[
"df['Label'].value_counts()",
"_____no_output_____"
],
[
"# As we can't find the correlation between numbers and label string, we need to map the label (Rock / Mine) to 0s and 1s\ndf['Target'] = df['Label'].map({'M': 1, 'R': 0}) ",
"_____no_output_____"
],
[
"df.head(1)",
"_____no_output_____"
],
[
"df.corr()['Target']",
"_____no_output_____"
],
[
"# get the highest 5 ones\nnp.absolute(df.corr()['Target'].sort_values(ascending=False))[:6]",
"_____no_output_____"
],
[
"#option 2\nnp.absolute(df.corr()['Target'].sort_values()).tail(6)",
"_____no_output_____"
]
],
[
[
"-------",
"_____no_output_____"
],
[
"## Train | Test Split\n\nOur approach here will be one of using Cross Validation on 90% of the dataset, and then judging our results on a final test set of 10% to evaluate our model.\n\n**TASK: Split the data into features and labels, and then split into a training set and test set, with 90% for Cross-Validation training, and 10% for a final test set.**\n\n*Note: The solution uses a random_state=42*",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import train_test_split",
"_____no_output_____"
],
[
"X = df.drop(['Label', 'Target'], axis=1) \ny = df['Label']",
"_____no_output_____"
],
[
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.1, random_state=42)",
"_____no_output_____"
]
],
[
[
"----",
"_____no_output_____"
],
[
"**TASK: Create a PipeLine that contains both a StandardScaler and a KNN model**",
"_____no_output_____"
]
],
[
[
"from sklearn.preprocessing import StandardScaler\nfrom sklearn.neighbors import KNeighborsClassifier",
"_____no_output_____"
],
[
"scaler = StandardScaler()\nknn = KNeighborsClassifier()",
"_____no_output_____"
],
[
"operations = [('scaler', scaler), ('knn', knn)]",
"_____no_output_____"
],
[
"from sklearn.pipeline import Pipeline",
"_____no_output_____"
],
[
"pipe = Pipeline(operations)",
"_____no_output_____"
]
],
[
[
"-----",
"_____no_output_____"
],
[
"**TASK: Perform a grid-search with the pipeline to test various values of k and report back the best performing parameters.**",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import GridSearchCV",
"_____no_output_____"
],
[
"k_values = list(range(1, 30))",
"_____no_output_____"
],
[
"parameters = {'knn__n_neighbors': k_values}",
"_____no_output_____"
],
[
"full_cv_classifier = GridSearchCV(pipe, parameters, cv=5, scoring='accuracy')",
"_____no_output_____"
],
[
"full_cv_classifier.fit(X_train, y_train)",
"_____no_output_____"
],
[
"# check best estimator\nfull_cv_classifier.best_estimator_.get_params()",
"_____no_output_____"
]
],
[
[
"----",
"_____no_output_____"
],
[
"**(HARD) TASK: Using the .cv_results_ dictionary, see if you can create a plot of the mean test scores per K value.**",
"_____no_output_____"
]
],
[
[
"pd.DataFrame(full_cv_classifier.cv_results_).head()",
"_____no_output_____"
],
[
"mean_test_scores = full_cv_classifier.cv_results_['mean_test_score']",
"_____no_output_____"
],
[
"mean_test_scores",
"_____no_output_____"
],
[
"# plt.plot(k_values, mean_test_scores, marker='.', markersize=10)\nplt.plot(k_values, mean_test_scores, 'o-')\nplt.xlabel('K')\nplt.ylabel('Mean Test Score / Accuracy');",
"_____no_output_____"
]
],
[
[
"----",
"_____no_output_____"
],
[
"### Final Model Evaluation\n\n**TASK: Using the grid classifier object from the previous step, get a final performance classification report and confusion matrix.**",
"_____no_output_____"
]
],
[
[
"full_pred = full_cv_classifier.predict(X_test)",
"_____no_output_____"
],
[
"from sklearn.metrics import confusion_matrix, plot_confusion_matrix, classification_report",
"_____no_output_____"
],
[
"confusion_matrix(y_test, full_pred)",
"_____no_output_____"
],
[
"plot_confusion_matrix(full_cv_classifier, X_test, y_test);",
"_____no_output_____"
]
],
[
[
"**IMPORTANT:**\n\n- As we can see from the confusion matrix, there are 1 False Positive and 1 False Negative.\n- Although False Positive case (thinking Rock as a Mine) may not be dangerous, False Negative case (thinking Mine as a Rock) is extremelly dangerous.\n- So we may need to revisit the modelling to make sure there is no False Negative.",
"_____no_output_____"
]
],
[
[
"print(classification_report(y_test, full_pred))",
" precision recall f1-score support\n\n M 0.92 0.92 0.92 13\n R 0.88 0.88 0.88 8\n\n accuracy 0.90 21\n macro avg 0.90 0.90 0.90 21\nweighted avg 0.90 0.90 0.90 21\n\n"
]
],
[
[
"### Great Job!",
"_____no_output_____"
]
]
]
| [
"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",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
]
|
cb5e2a308ab72cff98b3c334161e9e28b783d43b | 6,074 | ipynb | Jupyter Notebook | ch03tests/01testingbasics.ipynb | HChughtai/rsd-engineeringcourse | e196af2fc54658d5edb7b0f4c931a8f488d1ff9d | [
"CC-BY-3.0"
]
| null | null | null | ch03tests/01testingbasics.ipynb | HChughtai/rsd-engineeringcourse | e196af2fc54658d5edb7b0f4c931a8f488d1ff9d | [
"CC-BY-3.0"
]
| null | null | null | ch03tests/01testingbasics.ipynb | HChughtai/rsd-engineeringcourse | e196af2fc54658d5edb7b0f4c931a8f488d1ff9d | [
"CC-BY-3.0"
]
| null | null | null | 29.77451 | 480 | 0.547251 | [
[
[
"# Testing",
"_____no_output_____"
],
[
"## Introduction",
"_____no_output_____"
],
[
"When programming, it is very important to know that the code we have written does what it was intended. Unfortunately, this step is often skipped in scientific programming, especially when developing code for our own personal work.\n\nResearchers sometimes check that their code behaves correctly by manually running it on some sample data and inspecting the results. However, it is much better and safer to automate this process, so the tests can be run often -- perhaps even after each new commit! This not only reassures us that the code behaves as it should at any given moment, it also gives us more flexibility to change it, because we have a way of knowing when we have broken something by accident.\n\nIn this chapter, we will mostly look at how to write **unit tests**, which check the behaviour of small parts of our code. We will work with a particular framework for Python code, but the principles we discuss are general. We will also look at how to use a debugger to locate problems in our code, and services that simplify the automated running of tests.",
"_____no_output_____"
],
[
"### A few reasons not to do testing",
"_____no_output_____"
],
[
"Sensibility | Sense\n ------------------------------------ | -------------------------------------\n **It's boring** | *Maybe*\n **Code is just a one off throwaway** | *As with most research codes*\n **No time for it** | *A bit more code, a lot less debugging*\n **Tests can be buggy too** | *See above*\n **Not a professional programmer** | *See above*\n **Will do it later** | *See above*",
"_____no_output_____"
],
[
"### A few reasons to do testing\n\n* **laziness**: testing saves time\n* **peace of mind**: tests (should) ensure code is correct\n* **runnable specification**: best way to let others know what a function should do and\n not do\n* **reproducible debugging**: debugging that happened and is saved for later reuse\n* **code structure / modularity**: since we may have to call parts of the code independently during the tests\n* **ease of modification**: since results can be tested",
"_____no_output_____"
],
[
"### Not a panacea\n\n> Trying to improve the quality of software by doing more testing is like trying to lose weight by\n> weighing yourself more often.\n - Steve McConnell",
"_____no_output_____"
],
[
" * Testing won't corrrect a buggy code\n * Testing will tell you were the bugs are...\n * ... if the test cases *cover* the bugs",
"_____no_output_____"
],
[
"### Tests at different scales\n\nLevel of test |Area covered by test\n-------------------------- |----------------------\n**Unit testing** |smallest logical block of work (often < 10 lines of code)\n**Component testing** |several logical blocks of work together\n**Integration testing** |all components together / whole program\n\n\n<br>\n<div class=\"fragment fade-in\">\nAlways start at the smallest scale! \n\n<div class=\"fragment grow\">\nIf a unit test is too complicated, go smaller.\n</div>\n</div>",
"_____no_output_____"
],
[
"### Legacy code hardening\n\n* Very difficult to create unit-tests for existing code\n* Instead we make a **regression test**\n* Run program as a black box:\n\n```\nsetup input\nrun program\nread output\ncheck output against expected result\n```\n\n* Does not test correctness of code\n* Checks code is a similarly wrong on day N as day 0",
"_____no_output_____"
],
[
"### Testing vocabulary\n\n* **fixture**: input data\n* **action**: function that is being tested\n* **expected result**: the output that should be obtained\n* **actual result**: the output that is obtained\n* **coverage**: proportion of all possible paths in the code that the tests take",
"_____no_output_____"
],
[
"### Branch coverage:",
"_____no_output_____"
],
[
"```python\nif energy > 0:\n ! Do this \nelse:\n ! Do that\n```",
"_____no_output_____"
],
[
"Is there a test for both `energy > 0` and `energy <= 0`?",
"_____no_output_____"
]
]
]
| [
"markdown"
]
| [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
]
|
cb5e2e407e977cb80ab8dc1ab38be7f60d390d01 | 223,233 | ipynb | Jupyter Notebook | rl-tensortrade-multi0.ipynb | leandronogSS/ReinforcementLearningTrading | c9c91c73d5f088c15901b9463f191345206e0dcf | [
"MIT"
]
| 2 | 2021-08-13T11:19:44.000Z | 2021-10-11T06:44:57.000Z | rl-tensortrade-multi0.ipynb | leandronogSS/ReinforcementLearningTrading | c9c91c73d5f088c15901b9463f191345206e0dcf | [
"MIT"
]
| null | null | null | rl-tensortrade-multi0.ipynb | leandronogSS/ReinforcementLearningTrading | c9c91c73d5f088c15901b9463f191345206e0dcf | [
"MIT"
]
| null | null | null | 339.776256 | 172,388 | 0.91749 | [
[
[
"!python --version\n# In case issues with installation of tensortrade, Install the version below using that way\n# https://github.com/tensortrade-org/tensortrade/issues/229#issuecomment-633164703\n# version: https://github.com/tensortrade-org/tensortrade/releases/tag/v1.0.3",
"Python 3.7.5\r\n"
],
[
"!pip install -U tensortrade==1.0.3 ta matplotlib tensorboardX scikit-learn",
"Collecting tensortrade==1.0.3\n Using cached tensortrade-1.0.3-py3-none-any.whl\nRequirement already satisfied: ta in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (0.7.0)\nRequirement already satisfied: matplotlib in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (3.4.2)\nRequirement already satisfied: tensorboardX in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (2.2)\nRequirement already satisfied: scikit-learn in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (0.24.2)\nRequirement already satisfied: tensorflow>=2.1.0 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from tensortrade==1.0.3) (2.5.0)\nRequirement already satisfied: stochastic>=0.6.0 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from tensortrade==1.0.3) (0.6.0)\nRequirement already satisfied: pandas>=0.25.0 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from tensortrade==1.0.3) (1.2.4)\nRequirement already satisfied: pyyaml>=5.1.2 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from tensortrade==1.0.3) (5.4.1)\nRequirement already satisfied: ipython>=7.12.0 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from tensortrade==1.0.3) (7.24.1)\nRequirement already satisfied: numpy>=1.17.0 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from tensortrade==1.0.3) (1.19.5)\nRequirement already satisfied: plotly>=4.5.0 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from tensortrade==1.0.3) (4.14.3)\nRequirement already satisfied: gym>=0.14.0 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from tensortrade==1.0.3) (0.18.3)\nRequirement already satisfied: cycler>=0.10 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from matplotlib) (0.10.0)\nRequirement already satisfied: kiwisolver>=1.0.1 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from matplotlib) (1.3.1)\nRequirement already satisfied: python-dateutil>=2.7 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from matplotlib) (2.8.1)\nRequirement already satisfied: pillow>=6.2.0 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from matplotlib) (8.2.0)\nRequirement already satisfied: pyparsing>=2.2.1 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from matplotlib) (2.4.7)\nRequirement already satisfied: six in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from cycler>=0.10->matplotlib) (1.15.0)\nRequirement already satisfied: scipy in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from gym>=0.14.0->tensortrade==1.0.3) (1.6.3)\nRequirement already satisfied: pyglet<=1.5.15,>=1.4.0 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from gym>=0.14.0->tensortrade==1.0.3) (1.5.15)\nRequirement already satisfied: cloudpickle<1.7.0,>=1.2.0 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from gym>=0.14.0->tensortrade==1.0.3) (1.6.0)\nRequirement already satisfied: pygments in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from ipython>=7.12.0->tensortrade==1.0.3) (2.9.0)\nRequirement already satisfied: backcall in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from ipython>=7.12.0->tensortrade==1.0.3) (0.2.0)\nRequirement already satisfied: appnope in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from ipython>=7.12.0->tensortrade==1.0.3) (0.1.2)\nRequirement already satisfied: pexpect>4.3 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from ipython>=7.12.0->tensortrade==1.0.3) (4.8.0)\nRequirement already satisfied: traitlets>=4.2 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from ipython>=7.12.0->tensortrade==1.0.3) (5.0.5)\nRequirement already satisfied: jedi>=0.16 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from ipython>=7.12.0->tensortrade==1.0.3) (0.18.0)\nRequirement already satisfied: pickleshare in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from ipython>=7.12.0->tensortrade==1.0.3) (0.7.5)\nRequirement already satisfied: matplotlib-inline in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from ipython>=7.12.0->tensortrade==1.0.3) (0.1.2)\nRequirement already satisfied: setuptools>=18.5 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from ipython>=7.12.0->tensortrade==1.0.3) (57.0.0)\nRequirement already satisfied: decorator in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from ipython>=7.12.0->tensortrade==1.0.3) (5.0.9)\nRequirement already satisfied: prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from ipython>=7.12.0->tensortrade==1.0.3) (3.0.18)\nRequirement already satisfied: parso<0.9.0,>=0.8.0 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from jedi>=0.16->ipython>=7.12.0->tensortrade==1.0.3) (0.8.2)\nRequirement already satisfied: pytz>=2017.3 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from pandas>=0.25.0->tensortrade==1.0.3) (2021.1)\nRequirement already satisfied: ptyprocess>=0.5 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from pexpect>4.3->ipython>=7.12.0->tensortrade==1.0.3) (0.7.0)\nRequirement already satisfied: retrying>=1.3.3 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from plotly>=4.5.0->tensortrade==1.0.3) (1.3.3)\nRequirement already satisfied: wcwidth in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0->ipython>=7.12.0->tensortrade==1.0.3) (0.2.5)\nRequirement already satisfied: wheel~=0.35 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from tensorflow>=2.1.0->tensortrade==1.0.3) (0.36.2)\nRequirement already satisfied: grpcio~=1.34.0 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from tensorflow>=2.1.0->tensortrade==1.0.3) (1.34.1)\nRequirement already satisfied: wrapt~=1.12.1 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from tensorflow>=2.1.0->tensortrade==1.0.3) (1.12.1)\nRequirement already satisfied: typing-extensions~=3.7.4 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from tensorflow>=2.1.0->tensortrade==1.0.3) (3.7.4.3)\nRequirement already satisfied: tensorboard~=2.5 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from tensorflow>=2.1.0->tensortrade==1.0.3) (2.5.0)\nRequirement already satisfied: keras-nightly~=2.5.0.dev in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from tensorflow>=2.1.0->tensortrade==1.0.3) (2.5.0.dev2021032900)\nRequirement already satisfied: keras-preprocessing~=1.1.2 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from tensorflow>=2.1.0->tensortrade==1.0.3) (1.1.2)\nRequirement already satisfied: google-pasta~=0.2 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from tensorflow>=2.1.0->tensortrade==1.0.3) (0.2.0)\nRequirement already satisfied: tensorflow-estimator<2.6.0,>=2.5.0rc0 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from tensorflow>=2.1.0->tensortrade==1.0.3) (2.5.0)\nRequirement already satisfied: gast==0.4.0 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from tensorflow>=2.1.0->tensortrade==1.0.3) (0.4.0)\nRequirement already satisfied: opt-einsum~=3.3.0 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from tensorflow>=2.1.0->tensortrade==1.0.3) (3.3.0)\nRequirement already satisfied: h5py~=3.1.0 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from tensorflow>=2.1.0->tensortrade==1.0.3) (3.1.0)\nRequirement already satisfied: termcolor~=1.1.0 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from tensorflow>=2.1.0->tensortrade==1.0.3) (1.1.0)\nRequirement already satisfied: flatbuffers~=1.12.0 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from tensorflow>=2.1.0->tensortrade==1.0.3) (1.12)\nRequirement already satisfied: astunparse~=1.6.3 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from tensorflow>=2.1.0->tensortrade==1.0.3) (1.6.3)\nRequirement already satisfied: protobuf>=3.9.2 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from tensorflow>=2.1.0->tensortrade==1.0.3) (3.17.3)\nRequirement already satisfied: absl-py~=0.10 in /Users/leandronogueira/Desktop/venv3/lib/python3.7/site-packages (from tensorflow>=2.1.0->tensortrade==1.0.3) (0.12.0)\n"
],
[
"from tensortrade.data.cdd import CryptoDataDownload\nimport pandas as pd",
"_____no_output_____"
],
[
"import tensortrade.version\nprint(tensortrade.__version__)",
"1.0.3\n"
],
[
"import random\n\nimport ta\nimport pandas as pd\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import MinMaxScaler\n\nimport tensortrade.env.default as default\nfrom tensortrade.feed.core import Stream, DataFeed, NameSpace\nfrom tensortrade.oms.exchanges import Exchange\nfrom tensortrade.oms.services.execution.simulated import execute_order\nfrom tensortrade.oms.instruments import USD, BTC, ETH\nfrom tensortrade.oms.wallets import Wallet, Portfolio\nfrom tensortrade.agents import A2CAgent\nimport tensortrade.stochastic as sp \nfrom tensortrade.oms.instruments import Instrument\nfrom tensortrade.env.default.actions import SimpleOrders, BSH, ManagedRiskOrders\nfrom collections import OrderedDict\nfrom tensortrade.oms.orders.criteria import Stop, StopDirection\nfrom tensortrade.env.default.actions import ManagedRiskOrders\nfrom tensortrade.env.default.rewards import RiskAdjustedReturns\nfrom scipy.signal import savgol_filter",
"_____no_output_____"
],
[
"def fetchTaFeatures(data):\n data = ta.add_all_ta_features(data, 'open', 'high', 'low', 'close', 'volume', fillna=True)\n data.columns = [name.lower() for name in data.columns]\n return data\n\ndef createEnv(config):\n\n coins = [\"coin{}\".format(x) for x in range(5)]\n bitfinex_streams = []\n\n with NameSpace(\"bitfinex\"):\n for coin in coins:\n coinColumns = filter(lambda name: name.startswith(coin), config[\"data\"].columns)\n bitfinex_streams += [\n Stream.source(list(config[\"data\"][c]), dtype=\"float\").rename(c) for c in coinColumns\n ]\n\n\n feed = DataFeed(bitfinex_streams)\n \n streams = []\n for coin in coins:\n streams.append(Stream.source(list(data[coin+\":\"+\"close\"]), dtype=\"float\").rename(\"USD-\"+coin))\n streams = tuple(streams)\n\n\n bitstamp = Exchange(\"bitfinex\", service=execute_order)(\n Stream.source(list(data[\"coin0:close\"]), dtype=\"float\").rename(\"USD-BTC\"),\n Stream.source(list(data[\"coin1:close\"]), dtype=\"float\").rename(\"USD-ETH\"),\n Stream.source(list(data[\"coin1:close\"]), dtype=\"float\").rename(\"USD-TTC1\"),\n Stream.source(list(data[\"coin3:close\"]), dtype=\"float\").rename(\"USD-TTC2\"),\n Stream.source(list(data[\"coin4:close\"]), dtype=\"float\").rename(\"USD-TTC3\"),\n Stream.source(list(data[\"coin5:close\"]), dtype=\"float\").rename(\"USD-TTC4\"),\n Stream.source(list(data[\"coin6:close\"]), dtype=\"float\").rename(\"USD-TTC5\"),\n Stream.source(list(data[\"coin7:close\"]), dtype=\"float\").rename(\"USD-TTC6\"),\n Stream.source(list(data[\"coin8:close\"]), dtype=\"float\").rename(\"USD-TTC7\"),\n Stream.source(list(data[\"coin9:close\"]), dtype=\"float\").rename(\"USD-TTC8\"),\n\n )\n \n TTC1 = Instrument(\"TTC1\", 8, \"TensorTrade Coin1\")\n TTC2 = Instrument(\"TTC2\", 8, \"TensorTrade Coin2\")\n TTC3 = Instrument(\"TTC3\", 8, \"TensorTrade Coin3\")\n \n TTC4 = Instrument(\"TTC4\", 8, \"TensorTrade Coin4\")\n TTC5 = Instrument(\"TTC5\", 8, \"TensorTrade Coin5\")\n TTC6 = Instrument(\"TTC6\", 8, \"TensorTrade Coin6\")\n \n TTC7 = Instrument(\"TTC7\", 8, \"TensorTrade Coin7\")\n TTC8 = Instrument(\"TTC8\", 8, \"TensorTrade Coin8\")\n \n cash = Wallet(bitstamp, 10000 * USD)\n asset = Wallet(bitstamp, 0 * BTC)\n asset1 = Wallet(bitstamp, 0 * ETH)\n \n asset2 = Wallet(bitstamp, 0 * TTC1)\n asset3 = Wallet(bitstamp, 0 * TTC2)\n asset4 = Wallet(bitstamp, 0 * TTC3)\n \n asset5 = Wallet(bitstamp, 0 * TTC4)\n asset6 = Wallet(bitstamp, 0 * TTC5)\n asset7 = Wallet(bitstamp, 0 * TTC6)\n \n asset8 = Wallet(bitstamp, 0 * TTC7)\n asset9 = Wallet(bitstamp, 0 * TTC8)\n\n portfolio = Portfolio(USD, [cash, asset, asset1, asset2, asset3, asset4, asset5, asset6, asset7, asset8, asset9\n \n ])\n\n portfolio = Portfolio(USD, [cash, asset, asset1 \n ])\n reward = RiskAdjustedReturns(return_algorithm = \"sortino\", window_size=300)\n action_scheme = ManagedRiskOrders(stop=[0.1], take=[0.05, 0.1, 0.04], trade_sizes=[5])\n env = default.create(\n feed=feed,\n portfolio=portfolio,\n action_scheme=action_scheme,\n reward_scheme=reward,\n window_size=config[\"window_size\"]\n )\n \n return env\n",
"_____no_output_____"
],
[
"coins = [\"coin{}\".format(x) for x in range(10)]\ndfs = []\nfuncs = [sp.gbm, sp.heston]\nfor coin in coins:\n df = funcs[random.randint(0, 1)](\n base_price=random.randint(1, 2000),\n base_volume=random.randint(10, 5000),\n start_date=\"2010-01-01\",\n times_to_generate=5000,\n time_frame='1H').add_prefix(coin+\":\")\n for column in [\"close\", \"open\", \"high\", \"low\"]:\n df[coin+f\":diff_{column}\"] = df[coin+f\":{column}\"].apply(np.log).diff().dropna()\n df[coin+f\":soft_{column}\"] = savgol_filter(df[coin+\":\"+column], 35, 2)\n\n ta.add_all_ta_features(\n df,\n colprefix=coin+\":\",\n **{k: coin+\":\" + k for k in ['open', 'high', 'low', 'close', 'volume']})\n \n dfs.append(df)\n\ndata = pd.concat(dfs, axis=1)\n",
"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ta/trend.py:768: RuntimeWarning:\n\ninvalid value encountered in double_scalars\n\n/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ta/trend.py:772: RuntimeWarning:\n\ninvalid value encountered in double_scalars\n\n/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ta/trend.py:768: RuntimeWarning:\n\ninvalid value encountered in double_scalars\n\n/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ta/trend.py:772: RuntimeWarning:\n\ninvalid value encountered in double_scalars\n\n/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ta/trend.py:768: RuntimeWarning:\n\ninvalid value encountered in double_scalars\n\n/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ta/trend.py:772: RuntimeWarning:\n\ninvalid value encountered in double_scalars\n\n/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ta/trend.py:768: RuntimeWarning:\n\ninvalid value encountered in double_scalars\n\n/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ta/trend.py:772: RuntimeWarning:\n\ninvalid value encountered in double_scalars\n\n/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ta/trend.py:768: RuntimeWarning:\n\ninvalid value encountered in double_scalars\n\n/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ta/trend.py:772: RuntimeWarning:\n\ninvalid value encountered in double_scalars\n\n/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ta/trend.py:768: RuntimeWarning:\n\ninvalid value encountered in double_scalars\n\n/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ta/trend.py:772: RuntimeWarning:\n\ninvalid value encountered in double_scalars\n\n/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ta/trend.py:768: RuntimeWarning:\n\ninvalid value encountered in double_scalars\n\n/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ta/trend.py:772: RuntimeWarning:\n\ninvalid value encountered in double_scalars\n\n/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ta/trend.py:768: RuntimeWarning:\n\ninvalid value encountered in double_scalars\n\n/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ta/trend.py:772: RuntimeWarning:\n\ninvalid value encountered in double_scalars\n\n/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ta/trend.py:768: RuntimeWarning:\n\ninvalid value encountered in double_scalars\n\n/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ta/trend.py:772: RuntimeWarning:\n\ninvalid value encountered in double_scalars\n\n/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ta/trend.py:768: RuntimeWarning:\n\ninvalid value encountered in double_scalars\n\n/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ta/trend.py:772: RuntimeWarning:\n\ninvalid value encountered in double_scalars\n\n"
],
[
"scaler = MinMaxScaler()\nnorm_data = pd.DataFrame(scaler.fit_transform(data), columns=data.columns)\nnorm_data.to_csv(\"fake_data_1h_norm.csv\", index=False)",
"_____no_output_____"
],
[
"config = {\n \"window_size\": 10,\n \"data\": norm_data\n }\n\nenv = createEnv(config)",
"_____no_output_____"
],
[
"!mkdir -p agents/\n\nagent = A2CAgent(env)\nreward = agent.train(n_steps=5000, save_path=\"agents/\", n_episodes = 10)",
"==== AGENT ID: f2aef115-934c-4e97-be59-06b58bfc0f54 ====\n==== EPISODE ID (1/10): e8bf2a2d-5b78-4dd6-b0b1-5b0722c531ed ====\n==== EPISODE ID (2/10): a7e0642c-f9fc-430f-9101-f948fb8cbfa0 ====\n"
],
[
"env = createEnv({\n \"window_size\": 10, \n \"data\": norm_data\n})",
"_____no_output_____"
],
[
"episode_reward = 0\ndone = False\nobs = env.reset()\n\nwhile not done:\n action = agent.get_action(obs)\n obs, reward, done, info = env.step(action)\n episode_reward += reward",
"_____no_output_____"
],
[
"fig, axs = plt.subplots(1, 2, figsize=(15, 10))\n\nfig.suptitle(\"Performance\")\n\naxs[0].plot(np.arange(len(data[\"coin0:close\"])), data[\"coin0:close\"], label=\"price\")\naxs[0].set_title(\"Trading Chart\")\n\nperformance_df = pd.DataFrame().from_dict(env.action_scheme.portfolio.performance, orient='index')\nperformance_df.plot(ax=axs[1])\naxs[1].set_xlim(0, 5000)\naxs[1].set_title(\"Net Worth\")\n\nplt.show()",
"_____no_output_____"
],
[
"orDict = OrderedDict()\nfor k in env.action_scheme.portfolio.performance.keys():\n orDict[k] = env.action_scheme.portfolio.performance[k][\"net_worth\"]",
"_____no_output_____"
],
[
"pd.DataFrame().from_dict(orDict, orient='index').plot()",
"_____no_output_____"
]
]
]
| [
"code"
]
| [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
]
|
cb5e3f7742c93b8c846df37494c3554d3f4e5056 | 70,344 | ipynb | Jupyter Notebook | notebooks/analyzing_income_distribution.ipynb | mvashishtha/api-python | 324478efbbc7a1a0e08ae880a2a9daa5767d72d7 | [
"Apache-2.0"
]
| 1 | 2019-05-03T17:20:49.000Z | 2019-05-03T17:20:49.000Z | notebooks/analyzing_income_distribution.ipynb | mvashishtha/api-python | 324478efbbc7a1a0e08ae880a2a9daa5767d72d7 | [
"Apache-2.0"
]
| 1 | 2019-07-25T19:01:36.000Z | 2019-07-25T19:01:36.000Z | notebooks/analyzing_income_distribution.ipynb | mvashishtha/api-python | 324478efbbc7a1a0e08ae880a2a9daa5767d72d7 | [
"Apache-2.0"
]
| 5 | 2019-06-14T03:56:18.000Z | 2019-08-01T01:30:35.000Z | 68.561404 | 29,714 | 0.63343 | [
[
[
"Copyright 2019 Google LLC.\nSPDX-License-Identifier: Apache-2.0\n\n**Notebook Version** - 1.0.0",
"_____no_output_____"
]
],
[
[
"# Install datacommons\n!pip install --upgrade --quiet git+https://github.com/datacommonsorg/[email protected]",
" Building wheel for datacommons (setup.py) ... \u001b[?25l\u001b[?25hdone\n"
]
],
[
[
"# Analyzing Income Distribution\n\nThe American Community Survey (published by the US Census) annually reports the number of individuals in a given income bracket at the State level. We can use this information, stored in Data Commons, to visualize disparity in income for each State in the US. Our goal for this tutorial will be to generate a plot that visualizes the total number of individuals across a given set of income brackets for a given state. \n\nBefore we begin, we'll setup our notebook",
"_____no_output_____"
]
],
[
[
"# Import the Data Commons library\nimport datacommons as dc\n\n# Import other libraries\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport json\n\nfrom google.colab import drive",
"_____no_output_____"
]
],
[
[
"We will also need to provide the API with an API key. See the [Analyzing Statistics in Data Commons Using the Python Client API](https://colab.research.google.com/drive/1ZNXTHu3J0W3vo9Mg3kNUpk0hnD6Ce1u6#scrollTo=ijxoBhFHjo3Z) to see how to set this up for a Colab Notebook.",
"_____no_output_____"
]
],
[
[
"# Mount the Drive\ndrive.mount('/content/drive', force_remount=True)\n\n# REPLACE THIS with the path to your key.\nkey_path = '/content/drive/My Drive/DataCommons/secret.json'\n\n# Read the key in and provide it to the Data Commons API\nwith open(key_path, 'r') as f:\n secrets = json.load(f)\n dc.set_api_key(secrets['dc_api_key'])",
"Mounted at /content/drive\n"
]
],
[
[
"## Preparing the Data\n\nWe'll begin by creating a dataframe with states and their total population. We can use **`get_places_in`** to get all States within the United States. We can then call **`get_populations`** and **`get_observations`** to get the population of all persons in each State.",
"_____no_output_____"
]
],
[
[
"# Initialize a DataFrame holding the USA.\ndata = pd.DataFrame({'country': ['country/USA']})\n\n# Add a column for states and get their names\ndata['state'] = dc.get_places_in(data['country'], 'State')\ndata = dc.flatten_frame(data)\n\n# Get all state names and store it in a column \"name\"\ndata['name'] = dc.get_property_values(data['state'], 'name')\ndata = dc.flatten_frame(data)\n\n# Get StatisticalPopulations representing all persons in each state. \ndata['all_pop'] = dc.get_populations(data['state'], 'Person')\n\n# Get the total count of all persons in each population\ndata['all'] = dc.get_observations(data['all_pop'], \n 'count',\n 'measuredValue',\n '2017', \n measurement_method='CenusACS5yrSurvey')\n\n# Display the first five rows of the table.\ndata.head(5)",
"_____no_output_____"
]
],
[
[
"### Querying for Income Brackets\n\nNext, let's get the population level for each income bracket. The datacommons graph identifies 16 different income brackets. For each bracket and state, we can get the population level. Remember that we first get the StatisticalPopulation, and then a corresponding observation. We'll filter observations to between published in 2017 by the American Community Survey. ",
"_____no_output_____"
]
],
[
[
"# A list of income brackets\nincome_brackets = [\n \"USDollarUpto10000\",\n \"USDollar10000To14999\",\n \"USDollar15000To19999\",\n \"USDollar20000To24999\",\n \"USDollar25000To29999\",\n \"USDollar30000To34999\",\n \"USDollar35000To39999\",\n \"USDollar40000To44999\",\n \"USDollar45000To49999\",\n \"USDollar50000To59999\",\n \"USDollar60000To74999\",\n \"USDollar75000To99999\",\n \"USDollar100000To124999\",\n \"USDollar125000To149999\",\n \"USDollar150000To199999\",\n \"USDollar200000Onwards\",\n]\n\n# Add a column containin the population count for each income bracket\nfor bracket in income_brackets:\n # Get the new column names\n pop_col = '{}_pop'.format(bracket)\n obs_col = bracket\n \n # Create the constraining properties map\n pvs = {'income': bracket}\n\n # Get the StatisticalPopulation and Observation\n data[pop_col] = dc.get_populations(data['state'], 'Household', \n constraining_properties=pvs)\n data[obs_col] = dc.get_observations(data[pop_col], \n 'count', \n 'measuredValue', \n '2017', \n measurement_method='CenusACS5yrSurvey')\n\n# Display the table\ndata.head(5)",
"_____no_output_____"
]
],
[
[
"Let's limit the size of this DataFrame by selecting columns with only the State name and Observations.",
"_____no_output_____"
]
],
[
[
"# Select columns that will be used for plotting\ndata = data[['name', 'all'] + income_brackets]\n\n# Display the table\ndata.head(5)",
"_____no_output_____"
]
],
[
[
"## Analyzing the Data\n\nLet's plot our data as a histogram. Notice that the income ranges as tabulated by the US Census are not equal. At the low end, the range is 0-9999, whereas, towards the top, the range 150,000-199,999 is five times as broad! We will make the width of each of the columns correspond to their range, and will give us an idea of the total earnings, not just the number of people in that group.\n\nFirst we provide code for generating the plot.",
"_____no_output_____"
]
],
[
[
"# Histogram bins\nlabel_to_range = {\n \"USDollarUpto10000\": [0, 9999],\n \"USDollar10000To14999\": [10000, 14999],\n \"USDollar15000To19999\": [15000, 19999],\n \"USDollar20000To24999\": [20000, 24999],\n \"USDollar25000To29999\": [25000, 29999],\n \"USDollar30000To34999\": [30000, 34999],\n \"USDollar35000To39999\": [35000, 39999],\n \"USDollar40000To44999\": [40000, 44999],\n \"USDollar45000To49999\": [45000, 49999],\n \"USDollar50000To59999\": [50000, 59999],\n \"USDollar60000To74999\": [60000, 74999],\n \"USDollar75000To99999\": [75000, 99999],\n \"USDollar100000To124999\": [100000, 124999],\n \"USDollar125000To149999\": [125000, 149999],\n \"USDollar150000To199999\": [150000, 199999],\n \"USDollar200000Onwards\": [250000, 300000],\n}\nbins = [\n 0, 10000, 15000, 20000, 25000, 30000, 35000, 40000, 45000, 50000, 60000, \n 75000, 100000, 125000, 150000, 250000\n]\n\ndef plot_income(data, state_name):\n # Assert that \"state_name\" is a valid state name\n frame_search = data.loc[data['name'] == state_name].squeeze()\n if frame_search.shape[0] == 0:\n print('{} does not have sufficient income data to generate the plot!'.format(state_name))\n return\n \n # Print the resulting series\n data = frame_search[2:]\n \n # Calculate the bar lengths\n lengths = []\n for bracket in income_brackets:\n r = label_to_range[bracket] \n lengths.append(int((r[1] - r[0]) / 18))\n \n # Calculate the x-axis positions\n pos, total = [], 0\n for l in lengths:\n pos.append(total + (l // 2))\n total += l\n \n # Plot the histogram\n plt.figure(figsize=(12, 10))\n plt.xticks(pos, income_brackets, rotation=90)\n plt.grid(True)\n plt.bar(pos, data.values, lengths, color='b', alpha=0.3)\n \n # Return the resulting frame.\n return frame_search",
"_____no_output_____"
]
],
[
[
"We can then call this code with a state to plot the income bracket sizes.",
"_____no_output_____"
]
],
[
[
"#@title Enter State to plot { run: \"auto\" }\nstate_name = \"Tennessee\" #@param [\"Missouri\", \"Arkansas\", \"Arizona\", \"Ohio\", \"Connecticut\", \"Vermont\", \"Illinois\", \"South Dakota\", \"Iowa\", \"Oklahoma\", \"Kansas\", \"Washington\", \"Oregon\", \"Hawaii\", \"Minnesota\", \"Idaho\", \"Alaska\", \"Colorado\", \"Delaware\", \"Alabama\", \"North Dakota\", \"Michigan\", \"California\", \"Indiana\", \"Kentucky\", \"Nebraska\", \"Louisiana\", \"New Jersey\", \"Rhode Island\", \"Utah\", \"Nevada\", \"South Carolina\", \"Wisconsin\", \"New York\", \"North Carolina\", \"New Hampshire\", \"Georgia\", \"Pennsylvania\", \"West Virginia\", \"Maine\", \"Mississippi\", \"Montana\", \"Tennessee\", \"New Mexico\", \"Massachusetts\", \"Wyoming\", \"Maryland\", \"Florida\", \"Texas\", \"Virginia\"]\nresult = plot_income(data, state_name)\n\n# Show the plot\nplt.show()",
"_____no_output_____"
]
],
[
[
"and we can display the raw table of values.",
"_____no_output_____"
]
],
[
[
"# Additionally print the table of income bracket sizes \nresult",
"_____no_output_____"
]
],
[
[
"This is only the beginning! What else can you analyze? For example, you could try computing a measure of income disparity in each state (see [Gini Coefficient](https://en.wikipedia.org/wiki/Gini_coefficient)).\n\nYou could then expand the dataframe to include more information and analyze how attributes like education level, crime, or even weather effect income disparity.\n\n",
"_____no_output_____"
]
]
]
| [
"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"
],
[
"markdown"
]
]
|
cb5e425a9b51ac54281ae5f5832082a879f8c33d | 92,196 | ipynb | Jupyter Notebook | icwe/Processing Service - CSPARQL Engine.ipynb | riccardotommasini/sparql-kernel | 7be147d18fc2ca681e3403be56c4a1d780e6a7d4 | [
"BSD-3-Clause"
]
| 1 | 2021-08-21T05:00:55.000Z | 2021-08-21T05:00:55.000Z | icwe/Processing Service - CSPARQL Engine.ipynb | riccardotommasini/rsp-kernel | 7be147d18fc2ca681e3403be56c4a1d780e6a7d4 | [
"BSD-3-Clause"
]
| null | null | null | icwe/Processing Service - CSPARQL Engine.ipynb | riccardotommasini/rsp-kernel | 7be147d18fc2ca681e3403be56c4a1d780e6a7d4 | [
"BSD-3-Clause"
]
| null | null | null | 68.394659 | 332 | 0.572454 | [
[
[
"# Processing Service",
"_____no_output_____"
],
[
"## use the magic to add the engine backend",
"_____no_output_____"
]
],
[
[
"%log debug\n%engine http://docker.for.mac.localhost:8181/csparql",
"_____no_output_____"
]
],
[
[
"## Let's take a look at what this engine can do",
"_____no_output_____"
]
],
[
[
"%display diagram\nDESCRIBE ENGINE",
"_____no_output_____"
]
],
[
[
"### We now want to add a stream. \n#### If we wouldn't know which streams to register we can consult a catalog\n#### In this case we have a convenient stream just prepared (sorry for the funny url, docker issues)",
"_____no_output_____"
]
],
[
[
"%display table\nDESCRIBE STREAM <http://docker.for.mac.localhost:8181/csparql/streams/s2>",
"_____no_output_____"
]
],
[
[
"## We are using c-sparql as both publisher and engine, but we could have used an external publisher",
"_____no_output_____"
]
],
[
[
"%display table\nDESCRIBE STREAM <http://docker.for.mac.localhost:4000/stream1>",
"_____no_output_____"
]
],
[
[
"## Let's start with a simple task, spo C-SPARQL Query",
"_____no_output_____"
],
[
"### sorry againt for the uri...docker",
"_____no_output_____"
]
],
[
[
"%display table\nREGISTER TASK q1 AS \nCONSTRUCT {?s ?p ?o} \nFROM STREAM <http://localhost:4000/stream1> [RANGE 1m STEP 10s] \nWHERE {?s ?p ?o}",
"_____no_output_____"
]
],
[
[
"### It seems that the engine created a stream out of this query",
"_____no_output_____"
],
[
"### Let's describe the stream not",
"_____no_output_____"
]
],
[
[
"%display table\nDESCRIBE STREAM <http://docker.for.mac.localhost:8181/csparql/streams/q1>",
"_____no_output_____"
],
[
"%display diagram\nDESCRIBE STREAM <http://docker.for.mac.localhost:8181/csparql/streams/q1>",
"_____no_output_____"
]
],
[
[
"## the stream exists, but has no endpoint, we need to expose it",
"_____no_output_____"
]
],
[
[
"REGISTER STREAM s2 FROM TASK q1",
"_____no_output_____"
],
[
"%display table\nDESCRIBE STREAM <http://docker.for.mac.localhost:8181/csparql/streams/q1>",
"_____no_output_____"
],
[
"%display table\nREGISTER TASK q2 AS \nCONSTRUCT {?s ?p ?o} \nFROM STREAM <http://localhost:8181/csparql/streams/q1> [RANGE 1m STEP 10s] \nWHERE {?s ?p ?o}",
"_____no_output_____"
],
[
"%display diagram\nDESCRIBE STREAM <http://docker.for.mac.localhost:8181/csparql/streams/q2>",
"_____no_output_____"
]
]
]
| [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
]
| [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
]
|
cb5e45f524dbaa6be14eaa6a0b9ea995e3a4a459 | 34,549 | ipynb | Jupyter Notebook | notebooks/Natural disaster pattern predictor/WO_Natural disaster pattern predictor.ipynb | kene111/CFC2020 | df9dc46728a290995900d2f3607388019976e2f2 | [
"Apache-2.0"
]
| null | null | null | notebooks/Natural disaster pattern predictor/WO_Natural disaster pattern predictor.ipynb | kene111/CFC2020 | df9dc46728a290995900d2f3607388019976e2f2 | [
"Apache-2.0"
]
| 6 | 2021-04-08T21:38:44.000Z | 2022-02-27T09:16:42.000Z | notebooks/Natural disaster pattern predictor/WO_Natural disaster pattern predictor.ipynb | kene111/CFC2020 | df9dc46728a290995900d2f3607388019976e2f2 | [
"Apache-2.0"
]
| 1 | 2020-09-11T11:26:00.000Z | 2020-09-11T11:26:00.000Z | 24.31316 | 155 | 0.462387 | [
[
[
"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns",
"_____no_output_____"
],
[
"# Import the dataset\nus = pd.read_csv('US ND prediction/us_disaster_declarations.csv')",
"_____no_output_____"
],
[
"us.head()",
"_____no_output_____"
],
[
"# checking for null values\nus.isnull().sum()",
"_____no_output_____"
],
[
"# shape of dataset\nus.shape",
"_____no_output_____"
],
[
"# Getting the dates coloumn\nli = us['declaration_date'].tolist()",
"_____no_output_____"
],
[
"li[:5]",
"_____no_output_____"
],
[
"# Seperate the day, month, and year into seperate lists.\ndef date_ordering(dates):\n year = []\n month = []\n day = []\n for l in li:\n l = str(l)\n str_date = l.split('-')\n str_date = list(str_date)\n day.append(int(\"\".join(str_date[2][:2]))) \n year.append(int(\"\".join(str_date[0])))\n month.append(int(\"\".join(str_date[1])))\n return(year, month, day)\n\nyear, month, day = date_ordering(li) ",
"_____no_output_____"
],
[
"#Create new coloumns\nus['year'] = year\nus['month'] = month\nus['day'] = day",
"_____no_output_____"
],
[
"us.head()",
"_____no_output_____"
],
[
"# collecting the needed coloumns.\nus = us[['year','month','day','state','designated_area','declaration_title']]",
"_____no_output_____"
],
[
"us.head()",
"_____no_output_____"
],
[
"# visual display of the most affected states\nstate_count = us['state'].value_counts()\nsns.set(style=\"darkgrid\")\nsns.barplot(state_count.index, state_count.values, alpha=0.9)\nplt.title('Frequency Distribution of State')\nplt.ylabel('Number of Occurrences', fontsize=12)\nplt.xlabel('States', fontsize=12)\nplt.xticks(rotation = 90)\nplt.show() # So from what we can see there is alot of disasters in the state of texas\n",
"_____no_output_____"
],
[
"state = dict(enumerate(us.state.astype('category').cat.categories))\ndesignated_area = dict(enumerate(us.designated_area.astype('category').cat.categories))\nstate = dict(enumerate(us.declaration_title.astype('category').cat.categories))",
"_____no_output_____"
],
[
"us['state_code'] = us.state.astype('category').cat.codes\nus['designated_area_code'] = us.designated_area.astype('category').cat.codes\nus['declaration_title_code'] = us.declaration_title.astype('category').cat.codes",
"_____no_output_____"
],
[
"us.head()",
"_____no_output_____"
],
[
"us.drop(['state','designated_area','declaration_title'],inplace = True, axis=1)",
"_____no_output_____"
],
[
"us.head()",
"_____no_output_____"
],
[
"year = us['year'].tolist()\nmonth = us['month'].tolist()\nday =us['day'].tolist()",
"_____no_output_____"
],
[
"combo =[]\nzipped = zip(day, month, year)\nfor i,j, k in zipped:\n combo.append(str(i)+'/'+str(j)+'/'+ str(k))",
"_____no_output_____"
],
[
"us['fulldate'] = combo",
"_____no_output_____"
],
[
"us.set_index(\"fulldate\", inplace = True) ",
"_____no_output_____"
],
[
"us.head()",
"_____no_output_____"
],
[
"# Trying to see if I can use the countries to visualize a trend.\nus['state_code'].plot()",
"_____no_output_____"
],
[
"# Trying to see if I can visualize a trend in natural disasters.\nus['declaration_title_code'].plot()",
"_____no_output_____"
],
[
"us_ = us.tolist()",
"_____no_output_____"
],
[
"us_test = us[9000:,:]",
"_____no_output_____"
],
[
"from sklearn.preprocessing import MinMaxScaler\nsc =MinMaxScaler(feature_range = (0,1))\nus_scaled_set = sc.fit_transform(us)",
"_____no_output_____"
],
[
"time_steps = 365\nlength = len(us_scaled_set)\ncol = us.shape[1]",
"_____no_output_____"
],
[
"# creating the time steps\nx_train = []\ny_train = []\n\nfor i in range(time_steps, length):\n x_train.append(us_scaled_set[i-time_steps:i, :]) \n y_train.append(us_scaled_set[i,:])",
"_____no_output_____"
],
[
"x_train, y_train = np.array(x_train), np.array(y_train)",
"_____no_output_____"
],
[
"x_train = np.reshape(x_train,(x_train.shape[0], x_train.shape[1], col))",
"_____no_output_____"
],
[
"#language['level_back'] = language['code'].map(d)",
"_____no_output_____"
],
[
"#https://www.kaggle.com/headsortails/us-natural-disaster-declarations",
"_____no_output_____"
]
],
[
[
"### Vocalnic eruption data",
"_____no_output_____"
]
],
[
[
"volc = pd.read_csv('data/txt/volerup.txt',delimiter = '\\t', quoting = 3, encoding='utf-8')",
"_____no_output_____"
],
[
"volc.head()",
"_____no_output_____"
],
[
"volc.tail()",
"_____no_output_____"
],
[
"volc.isnull().sum()",
"_____no_output_____"
],
[
"len(volc)",
"_____no_output_____"
],
[
"Country_count = volc['Country'].value_counts()\nsns.set(style=\"darkgrid\")\nsns.barplot(Country_count.index, Country_count.values, alpha=0.9)\nplt.title('Frequency Distribution of Countries')\nplt.ylabel('Number of Occurrences', fontsize=12)\nplt.xlabel('Countries', fontsize=12)\nplt.xticks(rotation = 90)\nplt.show() # So from what we can see there is alot of volcanic eruption in indonesia\n",
"_____no_output_____"
],
[
"labels = volc['Country'].astype('category').cat.categories.tolist()\ncounts = volc['Country'].value_counts()\nsizes = [counts[var_cat] for var_cat in labels]\nfig1, ax1 = plt.subplots()\nax1.pie(sizes, labels=labels, autopct='%1.1f%%', shadow=True) #autopct is show the % on plot\nax1.axis('equal')\nplt.show()",
"_____no_output_____"
],
[
"volc = volc[['Year','Month','Day','Latitude','Longitude']]",
"_____no_output_____"
],
[
"len(volc)",
"_____no_output_____"
],
[
"volc.head()",
"_____no_output_____"
],
[
"volc = volc.fillna(volc['Month'].value_counts().index[0])\nvolc = volc.fillna(volc['Day'].value_counts().index[0])",
"_____no_output_____"
],
[
"volc.head()",
"_____no_output_____"
],
[
"# Repition shows that there were places that the eruption happend more than once.\nprint(volc.Latitude.duplicated().sum())\nprint(volc.Longitude.duplicated().sum())",
"_____no_output_____"
],
[
"volc.set_index(\"Year\", inplace = True) ",
"_____no_output_____"
]
],
[
[
"### Trying to see if there are trends in the coordinates.",
"_____no_output_____"
]
],
[
[
"volc['Latitude'].plot()",
"_____no_output_____"
],
[
"volc['Longitude'].plot()",
"_____no_output_____"
],
[
"#volc['country_num'] = volc['Country'].astype('category').cat.codes\n#volc['Location_num'] = volc['Location'].astype('category').cat.codes\n#volc['Name_num'] = volc['Name'].astype('category').cat.codes",
"_____no_output_____"
],
[
"#volc.drop(['Country','Location','Name'],inplace = True, axis=1)",
"_____no_output_____"
],
[
"#volc.head()",
"_____no_output_____"
],
[
"#from sklearn.preprocessing import OneHotEncoder\n#from sklearn.compose import ColumnTransformer",
"_____no_output_____"
],
[
"#ct = ColumnTransformer(\n# [('one_hot_encoder', OneHotEncoder(categories='auto'), [2,3,4])], # The column numbers to be transformed (here is [0] but can be [0, 1, 3])\n# remainder='passthrough' # Leave the rest of the columns untouched\n#)",
"_____no_output_____"
],
[
"#X = ct.fit_transform(volc)",
"_____no_output_____"
],
[
"#x = X.toarray()",
"_____no_output_____"
],
[
"#x",
"_____no_output_____"
],
[
"# ------------------------------------------------------------------------------------------------------------------------------------",
"_____no_output_____"
],
[
"volc = volc.reset_index()",
"_____no_output_____"
],
[
"volc.head()",
"_____no_output_____"
],
[
"#hold = volc['Latitude'].astype(str) + \",\" + volc['Longitude'].astype(str)\n#volc['coor'] = hold",
"_____no_output_____"
],
[
"#volc.head()",
"_____no_output_____"
],
[
"from sklearn.preprocessing import MinMaxScaler\nsc =MinMaxScaler(feature_range = (0,1))\nvolc_scaled_set = sc.fit_transform(volc)",
"_____no_output_____"
],
[
"volc_scaled_set",
"_____no_output_____"
],
[
"time_steps = 30 \ncheck = len(volc_scaled_set)\ncheck",
"_____no_output_____"
],
[
"# creating the time steps\nx_train = []\ny_train = []\n\nfor i in range(time_steps, check):\n x_train.append(volc_scaled_set[i-time_steps:i, :]) \n y_train.append(volc_scaled_set[i,:])\n ",
"_____no_output_____"
],
[
"x_train, y_train = np.array(x_train), np.array(y_train)",
"_____no_output_____"
],
[
"len(x_train)",
"_____no_output_____"
],
[
"x_train = np.reshape(x_train,(x_train.shape[0], x_train.shape[1], 5))",
"_____no_output_____"
],
[
"from keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nfrom keras.layers import Dropout\nfrom keras import backend",
"_____no_output_____"
],
[
"# f beta metric, incase of imbalanced dataset ...... \ndef f_beta(y_true, y_pred, beta =2):\n # clip prediction\n y_pred = backend.clip(y_pred, 0, 1)\n \n # calculate elements\n tp = backend.sum(backend.round(backend.clip(y_true * y_pred, 0,1)), axis = 1)\n fp = backend.sum(backend.round(backend.clip(y_pred - y_true, 0,1)), axis = 1)\n fn = backend.sum(backend.round(backend.clip(y_true - y_pred, 0,1)), axis = 1)\n \n # precision\n p = tp / (tp + fp + backend.epsilon())\n \n # recall\n r = tp / (tp +fn + backend.epsilon())\n \n # calculate fbeta\n \n bb = beta ** 2\n fbeta_score = backend.mean((1 + bb) * (p * r) / (bb * p + r + backend.epsilon()))\n return fbeta_score\n ",
"_____no_output_____"
],
[
"detector.fit(x_train, y_train, epochs = 90, batch_size = 10)",
"_____no_output_____"
],
[
"# ---------------------------------------------------------------------------------------------------------",
"_____no_output_____"
]
],
[
[
"### Tsunmi data",
"_____no_output_____"
]
],
[
[
"tsu = pd.read_csv('data/txt/tsrunup.txt',delimiter = '\\t', quoting = 3, encoding='latin-1')",
"_____no_output_____"
],
[
"tsu.head()",
"_____no_output_____"
],
[
"tsu.isnull().sum()",
"_____no_output_____"
],
[
"tsu = tsu[['YEAR', 'LOCATION_NAME','COUNTRY','LATITUDE','LONGITUDE']]",
"_____no_output_____"
],
[
"tsu.head()",
"_____no_output_____"
],
[
"# Repition shows that there were places that the eruption happend more than once.\nprint(tsu.LATITUDE.duplicated().sum())\nprint(tsu.LONGITUDE.duplicated().sum())",
"_____no_output_____"
],
[
"print(tsu.LOCATION_NAME.duplicated().sum())",
"_____no_output_____"
],
[
"### ------------------------------------------------------------------------------------------------------",
"_____no_output_____"
]
],
[
[
"# Earthquake data",
"_____no_output_____"
]
],
[
[
"earth = pd.read_csv('data/txt/signif.txt',delimiter = '\\t', quoting = 3, encoding='latin-1')",
"_____no_output_____"
],
[
"earth.head()",
"_____no_output_____"
],
[
"earth.isnull().sum()",
"_____no_output_____"
],
[
"earth =earth[['YEAR', 'LOCATION_NAME','COUNTRY','LATITUDE','LONGITUDE']]",
"_____no_output_____"
],
[
"print(earth.LATITUDE.duplicated().sum())\nprint(earth.LONGITUDE.duplicated().sum())",
"_____no_output_____"
],
[
"print(earth.LOCATION_NAME.duplicated().sum())",
"_____no_output_____"
],
[
"# https://medium.com/@kasiarachuta/choosing-columns-in-pandas-dataframe-d0677b34a6ca",
"_____no_output_____"
],
[
"# https://towardsdatascience.com/time-series-forecasting-with-recurrent-neural-networks-74674e289816",
"_____no_output_____"
],
[
"# https://www.datacamp.com/community/tutorials/categorical-data",
"_____no_output_____"
],
[
"# https://cmdlinetips.com/2018/11/how-to-join-two-text-columns-into-a-single-column-in-pandas/",
"_____no_output_____"
]
]
]
| [
"code",
"markdown",
"code",
"markdown",
"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"
],
[
"markdown"
],
[
"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",
"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"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
]
|
cb5e4afddf5afd6f01169bceaf032a8dcec45b01 | 202,569 | ipynb | Jupyter Notebook | Traffic_Sign_Classifier.ipynb | rrsaikarthik3/Project_3_Classifying_Traffic_signs | 3c90746488d488e26792037fe383297a967bed09 | [
"MIT"
]
| null | null | null | Traffic_Sign_Classifier.ipynb | rrsaikarthik3/Project_3_Classifying_Traffic_signs | 3c90746488d488e26792037fe383297a967bed09 | [
"MIT"
]
| null | null | null | Traffic_Sign_Classifier.ipynb | rrsaikarthik3/Project_3_Classifying_Traffic_signs | 3c90746488d488e26792037fe383297a967bed09 | [
"MIT"
]
| null | null | null | 169.940436 | 86,096 | 0.880006 | [
[
[
"# Self-Driving Car Engineer Nanodegree\n\n## Deep Learning\n\n## Project: Build a Traffic Sign Recognition Classifier\n\nIn this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary. \n\n> **Note**: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \\n\",\n \"**File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission. \n\nIn addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a [write up template](https://github.com/udacity/CarND-Traffic-Sign-Classifier-Project/blob/master/writeup_template.md) that can be used to guide the writing process. Completing the code template and writeup template will cover all of the [rubric points](https://review.udacity.com/#!/rubrics/481/view) for this project.\n\nThe [rubric](https://review.udacity.com/#!/rubrics/481/view) contains \"Stand Out Suggestions\" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the \"stand out suggestions\", you can include the code in this Ipython notebook and also discuss the results in the writeup file.\n\n\n>**Note:** Code and Markdown cells can be executed using the **Shift + Enter** keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.",
"_____no_output_____"
],
[
"---\n## Step 0: Load The Data",
"_____no_output_____"
]
],
[
[
"# Load pickled data\nimport pickle\nimport numpy as np\nimport tensorflow as tf\nimport cv2 as cv\n# TODO: Fill this in based on where you saved the training and testing data\n\ntraining_file = 'traffic-signs-data/train.p'\nvalidation_file='traffic-signs-data/valid.p'\ntesting_file = 'traffic-signs-data/test.p'\n\nwith open(training_file, mode='rb') as f:\n train = pickle.load(f)\nwith open(validation_file, mode='rb') as f:\n valid = pickle.load(f)\nwith open(testing_file, mode='rb') as f:\n test = pickle.load(f)\n \n \nX_train, y_train = train['features'], train['labels']\nX_validation, y_validation = valid['features'], valid['labels']\nX_test, y_test = test['features'], test['labels']\n",
"_____no_output_____"
]
],
[
[
"---\n\n## Step 1: Dataset Summary & Exploration\n\nThe pickled data is a dictionary with 4 key/value pairs:\n\n- `'features'` is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).\n- `'labels'` is a 1D array containing the label/class id of the traffic sign. The file `signnames.csv` contains id -> name mappings for each id.\n- `'sizes'` is a list containing tuples, (width, height) representing the original width and height the image.\n- `'coords'` is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. **THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES**\n\nComplete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the [pandas shape method](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shape.html) might be useful for calculating some of the summary results. ",
"_____no_output_____"
],
[
"### Provide a Basic Summary of the Data Set Using Python, Numpy and/or Pandas",
"_____no_output_____"
]
],
[
[
"### Replace each question mark with the appropriate value. \n### Use python, pandas or numpy methods rather than hard coding the results\n### Feel free to use as many code cells as needed.\nimport matplotlib.pyplot as plt\n# TODO: Number of training examples\nn_train = len(X_train)\n\n# TODO: Number of validation examples\nn_validation = len(X_validation)\n\n# TODO: Number of testing examples.\nn_test = len(X_test)\n\n# TODO: What's the shape of an traffic sign image?\nimage_shape = X_train[0].shape\n\n# TODO: How many unique classes/labels there are in the dataset.\nn_classes = len(np.unique(y_train))\n\nprint(\"Number of training examples =\", n_train)\nprint(\"Number of validation examples =\", n_validation)\nprint(\"Number of testing examples =\", n_test)\nprint(\"Image data shape =\", image_shape)\nprint(\"Number of classes =\", n_classes)\n",
"Number of training examples = 34799\nNumber of validation examples = 4410\nNumber of testing examples = 12630\nImage data shape = (32, 32, 3)\nNumber of classes = 43\n"
],
[
"fig, ax = plt.subplots(figsize =(5, 4)) \nax.hist(y_train,bins = n_classes) \n # Plot showing number of training examples corresponding to each class\n# Show plot \n\n \n# Labeling the X-axis \nplt.xlabel('Y-Value - Traffic Sign Indicator') \n# Labeling the Y-axis \nplt.ylabel('Number of training data samples') \n# Give a title to the graph\nplt.title('Hysteresis plot of #training samples for each given Y') \nplt.xticks(range(n_classes)) \n# Show a legend on the plot \n\n#Saving the plot as an image\nfig.savefig('examples/Hysteresis_plot.jpg', bbox_inches='tight', dpi=75)\n\nplt.show() ",
"_____no_output_____"
],
[
"import random\nfrom sklearn.utils import shuffle\nX_train, y_train = shuffle(X_train, y_train)\nplt.imshow(X_train[1500])\n \ncv.imwrite('examples/Pre-process_ex.jpg', cv.cvtColor(X_train[1500], cv.COLOR_RGB2BGR))",
"_____no_output_____"
],
[
"import cv2 as cv\nM = []\nangles = [-10,10,-25,25]\nfor angle in angles:\n M.append(cv.getRotationMatrix2D((16,16), angle, 1))\n",
"_____no_output_____"
],
[
"def augment_data(X,y):\n X_n = []\n y_n = []\n for i in range(0,len(X)):\n X_n.append(X[i])\n y_n.append(y[i])\n for j in range(0,len(M)):\n rotated = cv.warpAffine(X[i], M[j], (X[i].shape[1], X[i].shape[0]))\n X_n.append(rotated)\n y_n.append(y[i])\n \n return X_n,y_n\n\nX_train,y_train = augment_data(X_train,y_train)\n",
"_____no_output_____"
],
[
"plt.imshow(X_train[5*1500+4])\ncv.imwrite('examples/Rotated_Image.jpg', cv.cvtColor(X_train[5*1500+4], cv.COLOR_RGB2BGR))",
"_____no_output_____"
],
[
"# TODO: Number of training examples\nX_train = np.array(X_train)\ny_train = np.array(y_train)\nn_train = len(y_train)\n\n# TODO: Number of validation examples\nn_validation = len(X_validation)\n\n# TODO: Number of testing examples.\nn_test = len(X_test)\n\n# TODO: What's the shape of an traffic sign image?\nimage_shape = X_train[0].shape\n\n# TODO: How many unique classes/labels there are in the dataset.\nn_classes = len(np.unique(y_train))\n\nprint(\"Number of training examples =\", n_train)\nprint(\"Number of validation examples =\", n_validation)\nprint(\"Number of testing examples =\", n_test)\nprint(\"Image data shape =\", image_shape)\nprint(\"Number of classes =\", n_classes)",
"Number of training examples = 173995\nNumber of validation examples = 4410\nNumber of testing examples = 12630\nImage data shape = (32, 32, 3)\nNumber of classes = 43\n"
],
[
"fig, ax = plt.subplots(figsize =(5, 4)) \nax.hist(y_train,bins = n_classes) \n # Plot showing number of training examples corresponding to each class\n# Show plot \n\n \n# Labeling the X-axis \nplt.xlabel('Y-Value - Traffic Sign Indicator') \n# Labeling the Y-axis \nplt.ylabel('Number of training data samples') \n# Give a title to the graph\nplt.title('Hysteresis plot of #training samples for each given Y') \nplt.xticks(range(n_classes)) \n# Show a legend on the plot \n\n#Saving the plot as an image\nfig.savefig('examples/Post_Augmentation_Hysteresis_plot.jpg', bbox_inches='tight', dpi=75)\n\nplt.show() ",
"_____no_output_____"
]
],
[
[
"### Include an exploratory visualization of the dataset",
"_____no_output_____"
],
[
"Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc. \n\nThe [Matplotlib](http://matplotlib.org/) [examples](http://matplotlib.org/examples/index.html) and [gallery](http://matplotlib.org/gallery.html) pages are a great resource for doing visualizations in Python.\n\n**NOTE:** It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections. It can be interesting to look at the distribution of classes in the training, validation and test set. Is the distribution the same? Are there more examples of some classes than others?",
"_____no_output_____"
],
[
"----\n\n## Step 2: Design and Test a Model Architecture\n\nDesign and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the [German Traffic Sign Dataset](http://benchmark.ini.rub.de/?section=gtsrb&subsection=dataset).\n\nThe LeNet-5 implementation shown in the [classroom](https://classroom.udacity.com/nanodegrees/nd013/parts/fbf77062-5703-404e-b60c-95b78b2f3f9e/modules/6df7ae49-c61c-4bb2-a23e-6527e69209ec/lessons/601ae704-1035-4287-8b11-e2c2716217ad/concepts/d4aca031-508f-4e0b-b493-e7b706120f81) at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play! \n\nWith the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission. \n\nThere are various aspects to consider when thinking about this problem:\n\n- Neural network architecture (is the network over or underfitting?)\n- Play around preprocessing techniques (normalization, rgb to grayscale, etc)\n- Number of examples per label (some have more than others).\n- Generate fake data.\n\nHere is an example of a [published baseline model on this problem](http://yann.lecun.com/exdb/publis/pdf/sermanet-ijcnn-11.pdf). It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.",
"_____no_output_____"
],
[
"### Pre-process the Data Set (normalization, grayscale, etc.)",
"_____no_output_____"
],
[
"Minimally, the image data should be normalized so that the data has mean zero and equal variance. For image data, `(pixel - 128)/ 128` is a quick way to approximately normalize the data and can be used in this project. \n\nOther pre-processing steps are optional. You can try different techniques to see if it improves performance. \n\nUse the code cell (or multiple code cells, if necessary) to implement the first step of your project.",
"_____no_output_____"
]
],
[
[
"### Preprocess the data here. It is required to normalize the data. Other preprocessing steps could include \n### converting to grayscale, etc.\n\n# Visualizations will be shown in the notebook.\n%matplotlib inline\n\ndef normalize(images):\n image_out = []\n for img in images:\n img = (img)/255\n image_out.append(img)\n norm_img = np.zeros((800,800))\n #image_out.append(cv.normalize(img, norm_img, 0, 255, cv.NORM_MINMAX))\n \n return image_out\n\n\n\ndef grayscale(images):\n image_out = []\n for img in images:\n\n # Convert the RGB image to HSV\n graysc = cv.cvtColor(img,cv.COLOR_BGR2GRAY)\n #img = cv.cvtColor(img, cv.COLOR_BGR2RGB)\n #img = cv.cvtColor(img, cv.COLOR_RGB2HSV)\n \n #temp = np.dstack((grayscale,grayscale,grayscale))\n temp = np.dstack((graysc,graysc,graysc))\n image_out.append(temp) \n return image_out\n\n#X_train = grayscale(X_train)\n#X_validation = grayscale(X_validation)\n#X_test = grayscale(X_test)\n\nX_train = normalize(X_train)\nX_validation = normalize(X_validation)\nX_test = normalize(X_test)\n\n\n\n\n\n\n",
"_____no_output_____"
],
[
"print(X_train[5*1500])\ncv.imwrite('examples/Normalized_Image.jpg',X_train[5*1500])",
"[[[0.50196078 0.59215686 0.74901961]\n [0.49803922 0.59607843 0.75686275]\n [0.49411765 0.59607843 0.75686275]\n ...\n [0.49411765 0.6 0.74901961]\n [0.50588235 0.60392157 0.76078431]\n [0.50980392 0.59607843 0.75294118]]\n\n [[0.49803922 0.58823529 0.74509804]\n [0.49019608 0.58823529 0.75294118]\n [0.49019608 0.59215686 0.76078431]\n ...\n [0.50980392 0.60392157 0.76078431]\n [0.50588235 0.6 0.75686275]\n [0.50196078 0.59215686 0.74509804]]\n\n [[0.49019608 0.58431373 0.74117647]\n [0.48235294 0.58039216 0.74509804]\n [0.48627451 0.58823529 0.74901961]\n ...\n [0.50980392 0.59607843 0.76078431]\n [0.50588235 0.59607843 0.75686275]\n [0.50196078 0.59607843 0.75686275]]\n\n ...\n\n [[0.43529412 0.52156863 0.6745098 ]\n [0.44313725 0.52941176 0.67843137]\n [0.44313725 0.52941176 0.6745098 ]\n ...\n [0.44313725 0.53333333 0.67843137]\n [0.43921569 0.53333333 0.67843137]\n [0.43137255 0.53333333 0.67058824]]\n\n [[0.43529412 0.52156863 0.6627451 ]\n [0.43529412 0.52156863 0.6627451 ]\n [0.43529412 0.52156863 0.66666667]\n ...\n [0.43529412 0.52941176 0.67058824]\n [0.43921569 0.53333333 0.6745098 ]\n [0.42745098 0.52941176 0.67058824]]\n\n [[0.43529412 0.5254902 0.65098039]\n [0.42745098 0.51764706 0.65098039]\n [0.42352941 0.51372549 0.65098039]\n ...\n [0.43137255 0.5254902 0.6627451 ]\n [0.43529412 0.52941176 0.66666667]\n [0.43137255 0.52941176 0.67058824]]]\n"
],
[
"X_train, y_train = shuffle(X_train, y_train)\nfor i in range(0,len(X_train)):\n if(y_train[i] == 28):\n img = X_train[i]\n break\nplt.imshow(img)",
"_____no_output_____"
],
[
"from tensorflow.contrib.layers import flatten\nEPOCHS = 20\nBATCH_SIZE = 128\ndef LeNet(x): \n # Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer\n mu = 0\n sigma = 0.1\n dropout = 0.5\n w1 = tf.Variable(tf.random_normal([5, 5, 3, 25],mean=mu,stddev = sigma))\n b1 = tf.Variable(tf.random_normal([25],mean=mu, stddev = sigma))\n # TODO: Layer 1: Convolutional. Input = 32x32x3. Output = 28x28x25.\n l1 = tf.nn.conv2d(x, w1, strides=[1, 1, 1, 1], padding='VALID')\n l1 = tf.nn.bias_add(l1, b1)\n\n # TODO: Activation.\n l1 = tf.nn.relu(l1)\n \n # TODO: Pooling. Input = 28x28x25. Output = 14x14x25.\n l1 = tf.nn.max_pool(l1,ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1],padding='SAME')\n \n # TODO: Layer 2: Convolutional. Output = 10x10x50.\n w2 = tf.Variable(tf.random_normal([5, 5, 25, 50],mean=mu, stddev = sigma))\n b2 = tf.Variable(tf.random_normal([50],mean=mu, stddev = sigma))\n\n l2 = tf.nn.conv2d(l1, w2, strides=[1, 1, 1, 1], padding='VALID')\n l2 = tf.nn.bias_add(l2, b2)\n \n # TODO: Activation.\n l2 = tf.nn.relu(l2)\n \n # TODO: Pooling. Input = 10x10x16. Output = 5x5x50.\n l2 = tf.nn.max_pool(l2,ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1],padding='SAME') \n # TODO: Flatten. Input = 5x5x50. Output = 1250.\n l2 = tf.contrib.layers.flatten(l2)\n # TODO: Layer 3: Fully Connected. Input = 1250. Output = 400. \n w3 = tf.Variable(tf.random_normal([1250, 400],mean=mu, stddev = sigma))\n b3 = tf.Variable(tf.random_normal([400],mean=mu, stddev = sigma))\n fc1 = tf.add(tf.matmul(l2, w3), b3)\n \n # TODO: Activation.\n fc1 = tf.nn.relu(fc1)\n fc1 = tf.nn.dropout(fc1, dropout)\n \n \n # TODO: Layer 4: Fully Connected. Input = 400. Output = 100.\n w4 = tf.Variable(tf.random_normal([400, 100],mean=mu, stddev = sigma))\n b4 = tf.Variable(tf.random_normal([100],mean=mu, stddev = sigma))\n fc2 = tf.add(tf.matmul(fc1, w4), b4)\n \n # TODO: Activation.\n fc2 = tf.nn.relu(fc2)\n #fc2 = tf.nn.dropout(fc2, dropout)\n \n \n \n\n # TODO: Layer 5: Fully Connected. Input = 100. Output = 43.\n w5 = tf.Variable(tf.random_normal([100, 43],mean=mu, stddev = sigma))\n b5 = tf.Variable(tf.random_normal([43],mean=mu, stddev = sigma))\n logits = tf.add(tf.matmul(fc2, w5), b5)\n #logits = tf.nn.softmax(logits)\n \n return logits",
"_____no_output_____"
]
],
[
[
"### Train, Validate and Test the Model",
"_____no_output_____"
],
[
"A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation\nsets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.",
"_____no_output_____"
]
],
[
[
"### Train your model here.\n### Calculate and report the accuracy on the training and validation set.\n### Once a final model architecture is selected, \n### the accuracy on the test set should be calculated and reported as well.\n### Feel free to use as many code cells as needed.\n### Define your architecture here.\n### Feel free to use as many code cells as needed.\nrate = 0.0015\nx = tf.placeholder(tf.float32, (None, 32, 32, 3))\ny = tf.placeholder(tf.int32, (None))\none_hot_y = tf.one_hot(y, 43)\n\nlogits = LeNet(x)\ncross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits)\nloss_operation = tf.reduce_mean(cross_entropy)\noptimizer = tf.train.AdamOptimizer(learning_rate = rate)\ntraining_operation = optimizer.minimize(loss_operation)\n\nsoftmax = tf.nn.softmax(logits) \n#pred = tf.argmax(logits,1)\ncorrect_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))\naccuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\nsaver = tf.train.Saver()\n\ndef evaluate(X_data, y_data):\n num_examples = len(X_data)\n total_accuracy = 0\n sess = tf.get_default_session()\n for offset in range(0, num_examples, BATCH_SIZE):\n batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]\n accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y})\n total_accuracy += (accuracy * len(batch_x))\n return total_accuracy / num_examples",
"WARNING:tensorflow:\nThe TensorFlow contrib module will not be included in TensorFlow 2.0.\nFor more information, please see:\n * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n * https://github.com/tensorflow/addons\n * https://github.com/tensorflow/io (for I/O related ops)\nIf you depend on functionality not listed there, please file an issue.\n\nWARNING:tensorflow:From C:\\Users\\rrsai\\Anaconda3\\envs\\IntroToTensorFlow\\lib\\site-packages\\tensorflow_core\\contrib\\layers\\python\\layers\\layers.py:1634: flatten (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse keras.layers.flatten instead.\nWARNING:tensorflow:From C:\\Users\\rrsai\\Anaconda3\\envs\\IntroToTensorFlow\\lib\\site-packages\\tensorflow_core\\python\\layers\\core.py:332: 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.\nWARNING:tensorflow:From <ipython-input-12-affe62223206>:42: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease use `rate` instead of `keep_prob`. Rate should be set to `rate = 1 - keep_prob`.\nWARNING:tensorflow:From <ipython-input-13-d6f9b563dfc2>:14: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\n\nFuture major versions of TensorFlow will allow gradients to flow\ninto the labels input on backprop by default.\n\nSee `tf.nn.softmax_cross_entropy_with_logits_v2`.\n\n"
],
[
"with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n num_examples = len(X_train)\n \n print(\"Training...\")\n print()\n for i in range(EPOCHS):\n X_train, y_train = shuffle(X_train, y_train)\n for offset in range(0, num_examples, BATCH_SIZE):\n end = offset + BATCH_SIZE\n batch_x, batch_y = X_train[offset:end], y_train[offset:end]\n sess.run(training_operation, feed_dict={x: batch_x, y: batch_y})\n #print(sess.run(logits, feed_dict = {x:batch_x}))\n \n validation_accuracy = evaluate(X_validation, y_validation)\n print(\"EPOCH {} ...\".format(i+1))\n print(\"Validation Accuracy = {:.3f}\".format(validation_accuracy))\n print()\n \n saver.save(sess, './lenet')\n print(\"Model saved\")",
"Training...\n\nEPOCH 1 ...\nValidation Accuracy = 0.901\n\nEPOCH 2 ...\nValidation Accuracy = 0.942\n\nEPOCH 3 ...\nValidation Accuracy = 0.947\n\nEPOCH 4 ...\nValidation Accuracy = 0.950\n\nEPOCH 5 ...\nValidation Accuracy = 0.953\n\nEPOCH 6 ...\nValidation Accuracy = 0.968\n\nEPOCH 7 ...\nValidation Accuracy = 0.944\n\nEPOCH 8 ...\nValidation Accuracy = 0.954\n\nEPOCH 9 ...\nValidation Accuracy = 0.958\n\nEPOCH 10 ...\nValidation Accuracy = 0.954\n\nEPOCH 11 ...\nValidation Accuracy = 0.961\n\nEPOCH 12 ...\nValidation Accuracy = 0.958\n\nEPOCH 13 ...\nValidation Accuracy = 0.956\n\nEPOCH 14 ...\nValidation Accuracy = 0.948\n\nEPOCH 15 ...\nValidation Accuracy = 0.958\n\nEPOCH 16 ...\nValidation Accuracy = 0.953\n\nEPOCH 17 ...\nValidation Accuracy = 0.961\n\nEPOCH 18 ...\nValidation Accuracy = 0.954\n\nEPOCH 19 ...\nValidation Accuracy = 0.951\n\nEPOCH 20 ...\nValidation Accuracy = 0.955\n\nModel saved\n"
]
],
[
[
"---\n\n## Step 3: Test a Model on New Images\n\nTo give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.\n\nYou may find `signnames.csv` useful as it contains mappings from the class id (integer) to the actual sign name.",
"_____no_output_____"
],
[
"### Load and Output the Images",
"_____no_output_____"
],
[
"### Predict the Sign Type for Each Image",
"_____no_output_____"
]
],
[
[
"### Run the predictions here and use the model to output the prediction for each image.\n### Make sure to pre-process the images with the same pre-processing pipeline used earlier.\n### Feel free to use as many code cells as needed.\n### Load the images and plot them here.\n### Feel free to use as many code cells as needed.\nwith tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('.'))\n\n test_accuracy = evaluate(X_test, y_test)\n train_Accuracy = evaluate(X_train,y_train)\n #print(sess.run(pred,feed_dict={x: X_test}))\n # http://localhost:8889/notebooks/Documents/Self_Driving_Car/Project_3_Classifying_Traffic_signs/CarND-Traffic-Sign-Classifier-Project-master/Trial_1.ipynb#Analyze-Performance print(sess.run(tf.nn.top_k(softmax, k=3),feed_dict={x: X_test}))\n \n \n print(\"Test Accuracy = {:.3f}\".format(test_accuracy))\n print(\"Training Accuracy = = {:.3f}\".format(train_Accuracy))",
"INFO:tensorflow:Restoring parameters from .\\lenet\nTest Accuracy = 0.942\nTraining Accuracy = = 0.992\n"
],
[
"import os\nimport glob\nimport matplotlib.image as mpimg\nimport math\n### Loading 5 New Images\nnew_test_im = []\ntest = []\nfor img in os.listdir(\"new_test_images/\"):\n image = mpimg.imread(str(os.path.join(\"new_test_images/\",img)))\n width = int(32)\n height = int(32)\n dim = (width, height)\n # resize image\n resized = cv.resize(image, dim,interpolation = cv.INTER_AREA)\n resized = np.uint8(resized)\n test.append(image)\n new_test_im.append(resized)\n### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.\nplt.imshow(test[0])\n",
"_____no_output_____"
],
[
"#X_test_new = grayscale(new_test_im)\nX_test_new = normalize(new_test_im)\nplt.imshow(X_test_new[0])",
"_____no_output_____"
],
[
"y_true_test = [28,19,20,18,36,39,25,25,23,23]\n### Feel free to use as many code cells as needed.\nwith tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('.'))\n\n #print(sess.run(tf.nn.top_k(softmax, k=3),feed_dict={x: X_test_new}))\n #print(sess.run(pred,feed_dict ={x:X_test_new}))\n print(sess.run(tf.nn.top_k(softmax, k=3),feed_dict ={x:X_test_new}))\n \n \n",
"INFO:tensorflow:Restoring parameters from .\\lenet\nTopKV2(values=array([[1.0000000e+00, 0.0000000e+00, 0.0000000e+00],\n [1.0000000e+00, 1.0455428e-12, 2.4460186e-13],\n [1.0000000e+00, 0.0000000e+00, 0.0000000e+00],\n [1.0000000e+00, 0.0000000e+00, 0.0000000e+00],\n [9.9805415e-01, 1.9459319e-03, 0.0000000e+00],\n [1.0000000e+00, 0.0000000e+00, 0.0000000e+00],\n [1.0000000e+00, 1.3245671e-38, 0.0000000e+00],\n [1.0000000e+00, 0.0000000e+00, 0.0000000e+00],\n [1.0000000e+00, 0.0000000e+00, 0.0000000e+00],\n [1.0000000e+00, 2.7554958e-19, 1.5261866e-21]], dtype=float32), indices=array([[28, 0, 1],\n [ 8, 1, 4],\n [20, 0, 1],\n [18, 0, 1],\n [36, 38, 0],\n [39, 0, 1],\n [25, 22, 0],\n [25, 0, 1],\n [23, 0, 1],\n [31, 21, 25]]))\n"
]
],
[
[
"For each of the new images, print out the model's softmax probabilities to show the **certainty** of the model's predictions (limit the output to the top 5 probabilities for each image). [`tf.nn.top_k`](https://www.tensorflow.org/versions/r0.12/api_docs/python/nn.html#top_k) could prove helpful here. \n\nThe example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.\n\n`tf.nn.top_k` will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.\n\nTake this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. `tf.nn.top_k` is used to choose the three classes with the highest probability:\n\n```\n# (5, 6) array\na = np.array([[ 0.24879643, 0.07032244, 0.12641572, 0.34763842, 0.07893497,\n 0.12789202],\n [ 0.28086119, 0.27569815, 0.08594638, 0.0178669 , 0.18063401,\n 0.15899337],\n [ 0.26076848, 0.23664738, 0.08020603, 0.07001922, 0.1134371 ,\n 0.23892179],\n [ 0.11943333, 0.29198961, 0.02605103, 0.26234032, 0.1351348 ,\n 0.16505091],\n [ 0.09561176, 0.34396535, 0.0643941 , 0.16240774, 0.24206137,\n 0.09155967]])\n```\n\nRunning it through `sess.run(tf.nn.top_k(tf.constant(a), k=3))` produces:\n\n```\nTopKV2(values=array([[ 0.34763842, 0.24879643, 0.12789202],\n [ 0.28086119, 0.27569815, 0.18063401],\n [ 0.26076848, 0.23892179, 0.23664738],\n [ 0.29198961, 0.26234032, 0.16505091],\n [ 0.34396535, 0.24206137, 0.16240774]]), indices=array([[3, 0, 5],\n [0, 1, 4],\n [0, 5, 1],\n [1, 3, 5],\n [1, 4, 3]], dtype=int32))\n```\n\nLooking just at the first row we get `[ 0.34763842, 0.24879643, 0.12789202]`, you can confirm these are the 3 largest probabilities in `a`. You'll also notice `[3, 0, 5]` are the corresponding indices.",
"_____no_output_____"
]
],
[
[
"### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web. \n### Feel free to use as many code cells as needed.",
"_____no_output_____"
]
],
[
[
"### Project Writeup\n\nOnce you have completed the code implementation, document your results in a project writeup using this [template](https://github.com/udacity/CarND-Traffic-Sign-Classifier-Project/blob/master/writeup_template.md) as a guide. The writeup can be in a markdown or pdf file. ",
"_____no_output_____"
],
[
"> **Note**: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \\n\",\n \"**File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission.",
"_____no_output_____"
],
[
"---\n\n## Step 4 (Optional): Visualize the Neural Network's State with Test Images\n\n This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol.\n\n Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the [LeNet lab's](https://classroom.udacity.com/nanodegrees/nd013/parts/fbf77062-5703-404e-b60c-95b78b2f3f9e/modules/6df7ae49-c61c-4bb2-a23e-6527e69209ec/lessons/601ae704-1035-4287-8b11-e2c2716217ad/concepts/d4aca031-508f-4e0b-b493-e7b706120f81) feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable.\n\nFor an example of what feature map outputs look like, check out NVIDIA's results in their paper [End-to-End Deep Learning for Self-Driving Cars](https://devblogs.nvidia.com/parallelforall/deep-learning-self-driving-cars/) in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image.\n\n<figure>\n <img src=\"visualize_cnn.png\" width=\"380\" alt=\"Combined Image\" />\n <figcaption>\n <p></p> \n <p style=\"text-align: center;\"> Your output should look something like this (above)</p> \n </figcaption>\n</figure>\n <p></p> \n",
"_____no_output_____"
]
],
[
[
"### Visualize your network's feature maps here.\n### Feel free to use as many code cells as needed.\n\n# image_input: the test image being fed into the network to produce the feature maps\n# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific weight layer\n# activation_min/max: can be used to view the activation contrast in more detail, by default matplot sets min and max to the actual min and max values of the output\n# plt_num: used to plot out multiple different weight feature map sets on the same block, just extend the plt number for each new feature map entry\n\ndef outputFeatureMap(image_input, tf_activation, activation_min=-1, activation_max=-1 ,plt_num=1):\n # Here make sure to preprocess your image_input in a way your network expects\n # with size, normalization, ect if needed\n # image_input =\n # Note: x should be the same name as your network's tensorflow data placeholder variable\n # If you get an error tf_activation is not defined it may be having trouble accessing the variable from inside a function\n activation = tf_activation.eval(session=sess,feed_dict={x : image_input})\n featuremaps = activation.shape[3]\n plt.figure(plt_num, figsize=(15,15))\n for featuremap in range(featuremaps):\n plt.subplot(6,8, featuremap+1) # sets the number of feature maps to show on each row and column\n plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number\n if activation_min != -1 & activation_max != -1:\n plt.imshow(activation[0,:,:, featuremap], interpolation=\"nearest\", vmin =activation_min, vmax=activation_max, cmap=\"gray\")\n elif activation_max != -1:\n plt.imshow(activation[0,:,:, featuremap], interpolation=\"nearest\", vmax=activation_max, cmap=\"gray\")\n elif activation_min !=-1:\n plt.imshow(activation[0,:,:, featuremap], interpolation=\"nearest\", vmin=activation_min, cmap=\"gray\")\n else:\n plt.imshow(activation[0,:,:, featuremap], interpolation=\"nearest\", cmap=\"gray\")",
"_____no_output_____"
]
]
]
| [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
]
| [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
]
]
|
cb5e4c0d1042a8fdf2947c2219585c7b2d90b19c | 6,635 | ipynb | Jupyter Notebook | recommender games/item-to-item.ipynb | DanielaLaura/-Recommendation-Sys | e64960f886f1902b6c371aab1d03ad549c4387c8 | [
"MIT"
]
| null | null | null | recommender games/item-to-item.ipynb | DanielaLaura/-Recommendation-Sys | e64960f886f1902b6c371aab1d03ad549c4387c8 | [
"MIT"
]
| null | null | null | recommender games/item-to-item.ipynb | DanielaLaura/-Recommendation-Sys | e64960f886f1902b6c371aab1d03ad549c4387c8 | [
"MIT"
]
| null | null | null | 27.995781 | 319 | 0.574981 | [
[
[
"# coding: utf-8\nimport pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.font_manager as fm\nimport seaborn as sn\nfrom pymongo import MongoClient\nfrom pandas.plotting import scatter_matrix\n\n%matplotlib inline",
"_____no_output_____"
],
[
"from pymongo import MongoClient\nclient = MongoClient(\"mongodb://analytics:[email protected]:27017,gamerec-shard-00-01-nbybv.mongodb.net:27017,gamerec-shard-00-02-nbybv.mongodb.net:27017/test?ssl=true&replicaSet=gamerec-shard-0&authSource=admin&retryWrites=true\")",
"_____no_output_____"
],
[
"print(client.gamerec)",
"Database(MongoClient(host=['gamerec-shard-00-01-nbybv.mongodb.net:27017', 'gamerec-shard-00-00-nbybv.mongodb.net:27017', 'gamerec-shard-00-02-nbybv.mongodb.net:27017'], document_class=dict, tz_aware=False, connect=True, ssl=True, replicaset='gamerec-shard-0', authsource='admin', retrywrites=True), 'gamerec')\n"
],
[
"client.database_names()",
"C:\\Users\\Daniela\\Anaconda3\\envs\\tensorflow\\lib\\site-packages\\ipykernel_launcher.py:1: DeprecationWarning: database_names is deprecated. Use list_database_names instead.\n \"\"\"Entry point for launching an IPython kernel.\n"
],
[
"db = client.cleaned_full_comments",
"_____no_output_____"
],
[
"collection = db.cleaned_full_comments",
"_____no_output_____"
],
[
"import pandas as pd\ncomm_df= pd.DataFrame(list(collection.find({}, {'_id': 0})))",
"_____no_output_____"
],
[
"# Setting up pivot table for actual userscores\nimport numpy as np\ndf_actual_pivot = pd.pivot_table(comm_df, values = ['Userscore'],\n index = ['Title', 'Platform', 'Username'],\n aggfunc = np.mean).unstack()\n\nactual_user_means = df_actual_pivot.mean(axis=0)\n\ndf_actual_pivot_mean = df_actual_pivot - actual_user_means\ndf_actual_pivot_mean.fillna(0, inplace=True)\n\n# Setting up pivot table for vader rated sentiment scores\n\ndf_vader_pivot = pd.pivot_table(comm_df, values = ['actual_sentiment_score'],\n index = ['Title', 'Platform', 'Username'], \n aggfunc = np.mean).unstack()\n\nvader_user_means = df_vader_pivot.mean(axis=0)\n\ndf_vader_pivot_mean = df_vader_pivot - vader_u",
"_____no_output_____"
],
[
"from sklearn.metrics.pairwise import cosine_similarity, euclidean_distances",
"_____no_output_____"
],
[
"actual_cosine_dists = cosine_similarity(df_actual_pivot_mean)\n\nvader_cosine_dists = cosine_similarity(df_vader_pivot_mean)",
"_____no_output_____"
],
[
"actual_cosine_dists = pd.DataFrame(actual_cosine_dists, columns=df_actual_pivot_mean.index)\nactual_cosine_dists.index = actual_cosine_dists.columns\n\nvader_cosine_dists = pd.DataFrame(vader_cosine_dists, columns=df_vader_pivot_mean.index)\nvader_cosine_dists.index = vader_cosine_dists.columns\nvader_cosine_dists.iloc[0:5,0:5]",
"_____no_output_____"
],
[
"def get_similar_games_actual(games_list, n=100):\n \n games = [game for game in games_list if game in actual_cosine_dists.columns]\n games_summed = actual_cosine_dists[games_list].apply(lambda row: np.sum(row), axis=1)\n games_summed = games_summed.sort_values(ascending=False)\n \n ranked_games = games_summed.index[games_summed.isin(games_list)==False]\n ranked_games = ranked_games.tolist()\n \n for g in games_list:\n ranked_games.remove(g)\n \n if n is None:\n return ranked_games\n else:\n return ranked_games[:n]",
"_____no_output_____"
],
[
"#games_i_like = [(\"Baldur's Gate II: Shadows of Amn\", 'PC'), (\"BioShock\",'PlayStation3')]\ngames_i_like = [(\"The Legend of Zelda: Breath of the Wild\", 'Switch')]\n\nfor i, game in enumerate(get_similar_games_actual(games_i_like, 50)):\n print(\"%d. %s on %s\" % (i+1, game[0], game[1]))",
"_____no_output_____"
]
]
]
| [
"code"
]
| [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
]
|
cb5e563dee91d267bf95062d84759df3b7c74dbe | 6,168 | ipynb | Jupyter Notebook | example-zipgutz-U1.ipynb | amiragha/mps | 1ccde15036d96a5ace95ed563822077d6ed0a402 | [
"MIT"
]
| null | null | null | example-zipgutz-U1.ipynb | amiragha/mps | 1ccde15036d96a5ace95ed563822077d6ed0a402 | [
"MIT"
]
| null | null | null | example-zipgutz-U1.ipynb | amiragha/mps | 1ccde15036d96a5ace95ed563822077d6ed0a402 | [
"MIT"
]
| null | null | null | 29.511962 | 118 | 0.517672 | [
[
[
"empty"
]
]
]
| [
"empty"
]
| [
[
"empty"
]
]
|
cb5e56e59af005c110e61d897359e9441a517522 | 6,517 | ipynb | Jupyter Notebook | exercises/Jupyter/keyboard-shortcuts.ipynb | rogalskim/udacity-ai-with-python | 7e50c4ff496b3cfa34df505d9d2dc87a8481dccb | [
"MIT"
]
| null | null | null | exercises/Jupyter/keyboard-shortcuts.ipynb | rogalskim/udacity-ai-with-python | 7e50c4ff496b3cfa34df505d9d2dc87a8481dccb | [
"MIT"
]
| null | null | null | exercises/Jupyter/keyboard-shortcuts.ipynb | rogalskim/udacity-ai-with-python | 7e50c4ff496b3cfa34df505d9d2dc87a8481dccb | [
"MIT"
]
| null | null | null | 31.483092 | 508 | 0.610864 | [
[
[
"# Keyboard shortcuts\n\nIn this notebook, you'll get some practice using keyboard shortcuts. These are key to becoming proficient at using notebooks and will greatly increase your work speed.\n\nFirst up, switching between edit mode and command mode. Edit mode allows you to type into cells while command mode will use key presses to execute commands such as creating new cells and openning the command palette. When you select a cell, you can tell which mode you're currently working in by the color of the box around the cell. In edit mode, the box and thick left border are colored green. In command mode, they are colored blue. Also in edit mode, you should see a cursor in the cell itself.\n\nBy default, when you create a new cell or move to the next one, you'll be in command mode. To enter edit mode, press Enter/Return. To go back from edit mode to command mode, press Escape.\n\n> **Exercise:** Click on this cell, then press Enter + Shift to get to the next cell. Switch between edit and command mode a few times.",
"_____no_output_____"
]
],
[
[
"# mode practice",
"_____no_output_____"
]
],
[
[
"## Help with commands\n\nIf you ever need to look up a command, you can bring up the list of shortcuts by pressing `H` in command mode. The keyboard shortcuts are also available above in the Help menu. Go ahead and try it now.",
"_____no_output_____"
],
[
"## Creating new cells\n\nOne of the most common commands is creating new cells. You can create a cell above the current cell by pressing `A` in command mode. Pressing `B` will create a cell below the currently selected cell.",
"_____no_output_____"
],
[
"Above!",
"_____no_output_____"
],
[
"> **Exercise:** Create a cell above this cell using the keyboard command.",
"_____no_output_____"
],
[
"> **Exercise:** Create a cell below this cell using the keyboard command.",
"_____no_output_____"
],
[
"And below!",
"_____no_output_____"
],
[
"## Switching between Markdown and code\n\nWith keyboard shortcuts, it is quick and simple to switch between Markdown and code cells. To change from Markdown to a code cell, press `Y`. To switch from code to Markdown, press `M`.\n\n> **Exercise:** Switch the cell below between Markdown and code cells.",
"_____no_output_____"
]
],
[
[
"## Practice here\n\ndef fibo(n): # Recursive Fibonacci sequence!\n if n == 0:\n return 0\n elif n == 1:\n return 1\n return fibo(n-1) + fibo(n-2)",
"_____no_output_____"
]
],
[
[
"## Line numbers\n\nA lot of times it is helpful to number the lines in your code for debugging purposes. You can turn on numbers by pressing `L` (in command mode of course) on a code cell.\n\n> **Exercise:** Turn line numbers on and off in the above code cell.",
"_____no_output_____"
],
[
"## Deleting cells\n\nDeleting cells is done by pressing `D` twice in a row so `D`, `D`. This is to prevent accidently deletions, you have to press the button twice!\n\n> **Exercise:** Delete the cell below.",
"_____no_output_____"
],
[
"## Saving the notebook\n\nNotebooks are autosaved every once in a while, but you'll often want to save your work between those times. To save the book, press `S`. So easy!",
"_____no_output_____"
],
[
"## The Command Palette\n\nYou can easily access the command palette by pressing Shift + Control/Command + `P`. \n\n> **Note:** This won't work in Firefox and Internet Explorer unfortunately. There is already a keyboard shortcut assigned to those keys in those browsers. However, it does work in Chrome and Safari.\n\nThis will bring up the command palette where you can search for commands that aren't available through the keyboard shortcuts. For instance, there are buttons on the toolbar that move cells up and down (the up and down arrows), but there aren't corresponding keyboard shortcuts. To move a cell down, you can open up the command palette and type in \"move\" which will bring up the move commands.\n\n> **Exercise:** Use the command palette to move the cell below down one position.",
"_____no_output_____"
]
],
[
[
"# below this cell",
"_____no_output_____"
],
[
"# Move this cell down",
"_____no_output_____"
]
],
[
[
"## Finishing up\n\nThere is plenty more you can do such as copying, cutting, and pasting cells. I suggest getting used to using the keyboard shortcuts, you’ll be much quicker at working in notebooks. When you become proficient with them, you'll rarely need to move your hands away from the keyboard, greatly speeding up your work.\n\nRemember, if you ever need to see the shortcuts, just press `H` in command mode.\n",
"_____no_output_____"
]
]
]
| [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
]
| [
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
]
|
cb5e828ef8117376565cfb76d2ccc880cc3d3cc0 | 137,627 | ipynb | Jupyter Notebook | ImageClassificationUsingCNN.ipynb | SR2090/Image-Classification-MNIST | 6c06b81ee9d6416b27e60e66afbfaa3ebda8b95b | [
"MIT"
]
| null | null | null | ImageClassificationUsingCNN.ipynb | SR2090/Image-Classification-MNIST | 6c06b81ee9d6416b27e60e66afbfaa3ebda8b95b | [
"MIT"
]
| null | null | null | ImageClassificationUsingCNN.ipynb | SR2090/Image-Classification-MNIST | 6c06b81ee9d6416b27e60e66afbfaa3ebda8b95b | [
"MIT"
]
| null | null | null | 140.579162 | 32,678 | 0.827156 | [
[
[
"<a href=\"https://colab.research.google.com/github/SR2090/Image-Classification-MNIST/blob/main/ImageClassificationUsingCNN.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 matplotlib.pyplot as plt\n%matplotlib inline\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Dropout, Flatten",
"_____no_output_____"
]
],
[
[
"## 2. Importing and Loading the data",
"_____no_output_____"
]
],
[
[
"from tensorflow.keras.datasets import fashion_mnist",
"_____no_output_____"
],
[
"(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()",
"Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-labels-idx1-ubyte.gz\n32768/29515 [=================================] - 0s 0us/step\nDownloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-images-idx3-ubyte.gz\n26427392/26421880 [==============================] - 0s 0us/step\nDownloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/t10k-labels-idx1-ubyte.gz\n8192/5148 [===============================================] - 0s 0us/step\nDownloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/t10k-images-idx3-ubyte.gz\n4423680/4422102 [==============================] - 0s 0us/step\n"
],
[
"labelMap = [\"T-shirt/top\",\"Trouser\",\"Pullover\",\"Dress\",\"Coat\",\"Sandal\",\"Shirt\",\"Sneaker\",\"Bag\",\"Ankle boot\"]",
"_____no_output_____"
]
],
[
[
"## 3. Explore the data",
"_____no_output_____"
]
],
[
[
"from tensorflow.keras.utils import to_categorical",
"_____no_output_____"
],
[
"print('Training data shape : ', train_images.shape, train_labels.shape)\nprint('Testing data shape : ', test_images.shape, test_labels.shape)",
"Training data shape : (60000, 28, 28) (60000,)\nTesting data shape : (10000, 28, 28) (10000,)\n"
],
[
"classes = np.unique(train_labels)\nnClasses = len(classes)\nprint('Total number of outputs : ', nClasses)\nprint('Output Classes : ', classes)",
"Total number of outputs : 10\nOutput Classes : [0 1 2 3 4 5 6 7 8 9]\n"
],
[
"plt.figure(figsize=[10,5])\n# Display the first image in the training data\n# plt.subplot(121);plt.imshow(train_images[0,:,:]);plt.title(\"Ground Truth : {}\".format(train_labels[0]))\n# plt.subplot(121);plt.imshow(test_images[0,:,:]);plt.title(\"Ground Truth : {}\".format(test_labels[0]))\nplt.subplot(121)\nplt.imshow(train_images[0,:,:])\nplt.title(\"Ground Truth : {}\".format(train_labels[0]))\n\n# Display the first image in testing data\nplt.subplot(122)\nplt.imshow(test_images[0,:,:])\nplt.title(\"Ground Truth : {}\".format(test_labels[0]))",
"_____no_output_____"
]
],
[
[
"## 4. Preprocess the data",
"_____no_output_____"
],
[
"Perform normalization of data (i.e. convert the images to float and normalize the intensity values to lie between 0-1 and convert the labels to categorical variables to be used in Keras.",
"_____no_output_____"
]
],
[
[
"nDims = 1\nnRows, nCols = train_images.shape[1:]\ntrain_data = train_images.reshape(train_images.shape[0], nRows, nCols, nDims)\n# Input shape to feed it to the neural network\ntest_data = test_images.reshape(test_images.shape[0], nRows, nCols, nDims)\ninput_shape = (nRows,nCols,nDims)",
"_____no_output_____"
],
[
"# Normalize the value between 0 and 1 \n# 1. Convert to float32\ntrain_data = train_data.astype('float32')\ntest_data = test_data.astype('float32')\n# 2. Scale the data to lie between 0 to 1\ntrain_data /= 255\ntest_data /= 255",
"_____no_output_____"
]
],
[
[
"- Category is changed from integer to boolean representation using the to_categorical in keras. ",
"_____no_output_____"
]
],
[
[
"train_labels_one_hot = to_categorical(train_labels)\ntest_lables_one_hot = to_categorical(test_labels)",
"_____no_output_____"
],
[
"print('Original Label 0 :', train_labels[0])\nprint('After conversion to categorical (one-hot): ', train_labels_one_hot[0])\ntrain_labels",
"Original Label 0 : 9\nAfter conversion to categorical (one-hot): [0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n"
]
],
[
[
"## 5. Model Architecture\n- This is obtained through hit and trial\n- Find an existing problem model and try to reconfigure it for the problem you are trying to solve\n- Both the aformentioned should be similar",
"_____no_output_____"
],
[
"\"\" For implementing a CNN, we will stack up Convolutional Layers, followed by Max Pooling layers. We will also include Dropout to avoid overfitting.\n\nFinally, we will add a fully connected ( Dense ) layer followed by a softmax layer. Given below is the model structure.\n\nWe use 6 convolutional layers and 1 fully-connected layer.\n\nThe first 2 convolutional layers have 32 filters / kernels with a window size of 3×3.\nThe remaining conv layers have 64 filters.\nWe also add a max pooling layer with window size 2×2 after each pair of conv layer.\nWe add a dropout layer with a dropout ratio of 0.25 after every pooling layer.\nIn the final line, we add the dense layer which performs the classification among 10 classes using a softmax layer.\"\"",
"_____no_output_____"
]
],
[
[
"# def createModel():\n# model = Sequential()\n# # THe first 2 layers have 32 filters of window size 3x3 bigger kernels are not efficient and hardly produce better result\n# # Sometimes they even may produce worse result\n# model.add(Conv2D(32, (3,3), padding='same', activation='relu', input_shape=input_shape))\n# # second conv layer to obtain hierarcial features\n# model.add(Conv2D(32, (3, 3), activation='relu'))\n# # Redue the length and width to improve efficiency\n# model.add(MaxPooling2D(pool_size(2,2)))\n# # Dropout to prevent overfitting\n# model.add(Dropout(0.25))\n\n# model.add(Conv2D(64,(3,3), padding='same', activation='relu'))\n# model.add(Conv2D(64,(3,3),activation='relu')\n# model.add(MaxPooling2D(pool_size=(2, 2)))\n# model.add(Dropout(0.25))\n\n# model.add(Conv2D(64, (3, 3), padding='same', activation='relu'))\n# model.add(Conv2D(64, (3, 3), activation='relu'))\n# model.add(MaxPooling2D(pool_size=(2, 2)))\n# model.add(Dropout(0.25))\n\n# model.add(Flatten())\n# model.add(Dense(512, activation='relu'))\n# model.add(Dropout(0.5))\n# model.add(Dense(nClasses, activation='softmax'))\n \n# return model",
"_____no_output_____"
],
[
"def createModel():\n model = Sequential()\n # The first two layers with 32 filters of window size 3x3\n model.add(Conv2D(32, (3, 3), padding='same', activation='relu', input_shape=input_shape))\n model.add(Conv2D(32, (3, 3), activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.25))\n\n model.add(Conv2D(64, (3, 3), padding='same', activation='relu'))\n model.add(Conv2D(64, (3, 3), activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.25))\n\n model.add(Conv2D(64, (3, 3), padding='same', activation='relu'))\n model.add(Conv2D(64, (3, 3), activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.25))\n\n model.add(Flatten())\n model.add(Dense(512, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(nClasses, activation='softmax'))\n \n return model",
"_____no_output_____"
],
[
"model1 = createModel()\nbatch_size = 256\nepochs = 20\nmodel1.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])\n\nmodel1.summary()",
"Model: \"sequential_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d_6 (Conv2D) (None, 28, 28, 32) 320 \n_________________________________________________________________\nconv2d_7 (Conv2D) (None, 26, 26, 32) 9248 \n_________________________________________________________________\nmax_pooling2d_3 (MaxPooling2 (None, 13, 13, 32) 0 \n_________________________________________________________________\ndropout_4 (Dropout) (None, 13, 13, 32) 0 \n_________________________________________________________________\nconv2d_8 (Conv2D) (None, 13, 13, 64) 18496 \n_________________________________________________________________\nconv2d_9 (Conv2D) (None, 11, 11, 64) 36928 \n_________________________________________________________________\nmax_pooling2d_4 (MaxPooling2 (None, 5, 5, 64) 0 \n_________________________________________________________________\ndropout_5 (Dropout) (None, 5, 5, 64) 0 \n_________________________________________________________________\nconv2d_10 (Conv2D) (None, 5, 5, 64) 36928 \n_________________________________________________________________\nconv2d_11 (Conv2D) (None, 3, 3, 64) 36928 \n_________________________________________________________________\nmax_pooling2d_5 (MaxPooling2 (None, 1, 1, 64) 0 \n_________________________________________________________________\ndropout_6 (Dropout) (None, 1, 1, 64) 0 \n_________________________________________________________________\nflatten_1 (Flatten) (None, 64) 0 \n_________________________________________________________________\ndense_2 (Dense) (None, 512) 33280 \n_________________________________________________________________\ndropout_7 (Dropout) (None, 512) 0 \n_________________________________________________________________\ndense_3 (Dense) (None, 10) 5130 \n=================================================================\nTotal params: 177,258\nTrainable params: 177,258\nNon-trainable params: 0\n_________________________________________________________________\n"
]
],
[
[
"## 6. Training the model",
"_____no_output_____"
]
],
[
[
"history = model1.fit(train_data, train_labels_one_hot, batch_size=batch_size, epochs=epochs, verbose=1, \n validation_data=(test_data, test_lables_one_hot))\n# test_loss,test_accuracy = model1.evaluate(test_data, test_labels_one_hot)",
"Epoch 1/20\n235/235 [==============================] - 4s 17ms/step - loss: 0.8870 - accuracy: 0.6678 - val_loss: 0.5814 - val_accuracy: 0.7727\nEpoch 2/20\n235/235 [==============================] - 4s 16ms/step - loss: 0.5045 - accuracy: 0.8134 - val_loss: 0.4625 - val_accuracy: 0.8247\nEpoch 3/20\n235/235 [==============================] - 4s 15ms/step - loss: 0.4041 - accuracy: 0.8523 - val_loss: 0.3519 - val_accuracy: 0.8706\nEpoch 4/20\n235/235 [==============================] - 4s 16ms/step - loss: 0.3532 - accuracy: 0.8717 - val_loss: 0.2989 - val_accuracy: 0.8924\nEpoch 5/20\n235/235 [==============================] - 4s 15ms/step - loss: 0.3161 - accuracy: 0.8852 - val_loss: 0.2973 - val_accuracy: 0.8871\nEpoch 6/20\n235/235 [==============================] - 4s 15ms/step - loss: 0.2953 - accuracy: 0.8944 - val_loss: 0.2698 - val_accuracy: 0.9011\nEpoch 7/20\n235/235 [==============================] - 4s 15ms/step - loss: 0.2751 - accuracy: 0.9005 - val_loss: 0.2741 - val_accuracy: 0.9017\nEpoch 8/20\n235/235 [==============================] - 4s 16ms/step - loss: 0.2598 - accuracy: 0.9053 - val_loss: 0.3014 - val_accuracy: 0.8859\nEpoch 9/20\n235/235 [==============================] - 4s 16ms/step - loss: 0.2475 - accuracy: 0.9099 - val_loss: 0.2683 - val_accuracy: 0.9015\nEpoch 10/20\n235/235 [==============================] - 4s 16ms/step - loss: 0.2380 - accuracy: 0.9148 - val_loss: 0.2507 - val_accuracy: 0.9070\nEpoch 11/20\n235/235 [==============================] - 4s 16ms/step - loss: 0.2303 - accuracy: 0.9167 - val_loss: 0.2317 - val_accuracy: 0.9154\nEpoch 12/20\n235/235 [==============================] - 4s 16ms/step - loss: 0.2243 - accuracy: 0.9194 - val_loss: 0.2410 - val_accuracy: 0.9156\nEpoch 13/20\n235/235 [==============================] - 4s 15ms/step - loss: 0.2165 - accuracy: 0.9215 - val_loss: 0.2296 - val_accuracy: 0.9194\nEpoch 14/20\n235/235 [==============================] - 4s 15ms/step - loss: 0.2121 - accuracy: 0.9234 - val_loss: 0.2724 - val_accuracy: 0.9023\nEpoch 15/20\n235/235 [==============================] - 4s 15ms/step - loss: 0.2049 - accuracy: 0.9263 - val_loss: 0.2167 - val_accuracy: 0.9236\nEpoch 16/20\n235/235 [==============================] - 4s 15ms/step - loss: 0.1993 - accuracy: 0.9272 - val_loss: 0.2323 - val_accuracy: 0.9164\nEpoch 17/20\n235/235 [==============================] - 4s 15ms/step - loss: 0.1953 - accuracy: 0.9302 - val_loss: 0.2294 - val_accuracy: 0.9237\nEpoch 18/20\n235/235 [==============================] - 4s 15ms/step - loss: 0.1924 - accuracy: 0.9303 - val_loss: 0.2112 - val_accuracy: 0.9224\nEpoch 19/20\n235/235 [==============================] - 4s 15ms/step - loss: 0.1889 - accuracy: 0.9321 - val_loss: 0.2143 - val_accuracy: 0.9254\nEpoch 20/20\n235/235 [==============================] - 4s 15ms/step - loss: 0.1837 - accuracy: 0.9329 - val_loss: 0.2224 - val_accuracy: 0.9211\n"
]
],
[
[
"## 7. Checking loss and accuracy curves ",
"_____no_output_____"
],
[
"### 7.1 Training Loss vs Validation Loss\n\n- Training and validation loss both going down",
"_____no_output_____"
]
],
[
[
"# Trai\nplt.figure(figsize=[8,6])\nplt.plot(history.history['loss'],'r',linewidth=3.0)\nplt.plot(history.history['val_loss'],'b',linewidth=3.0)\nplt.legend(['Training loss', 'Validation Loss'],fontsize=18)\nplt.xlabel('Epochs ',fontsize=16)\nplt.ylabel('Loss',fontsize=16)\nplt.title('Loss Curves',fontsize=16)",
"_____no_output_____"
]
],
[
[
"### 7.2 Traing Accuracy vs Validation Accuracy",
"_____no_output_____"
],
[
" - Training and Validation loss both are increasing",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=[8,6])\nplt.plot(history.history['accuracy'],'r',linewidth=3.0)\nplt.plot(history.history['val_accuracy'],'b',linewidth=3.0)\nplt.legend(['Training Accuracy', 'Validation Accuracy'],fontsize=18)\nplt.xlabel('Epochs ',fontsize=16)\nplt.ylabel('Accuracy',fontsize=16)\nplt.title('Accuracy Curves',fontsize=16)",
"_____no_output_____"
]
],
[
[
"## 8. Draw Inference ",
"_____no_output_____"
],
[
"### 8.1 On a centered Image",
"_____no_output_____"
]
],
[
[
"testSample = test_data[0,:]\nplt.imshow(testSample.reshape(28,28));plt.show()\n\nlabel = model1.predict_classes(testSample.reshape(1,28,28,nDims))[0]\nprint(\"Label = {}, Item = {}\".format(label,labelMap[label]))",
"_____no_output_____"
]
],
[
[
"### 8.2 On a Shifted Up image",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"shiftUp = np.zeros(testSample.shape)\nshiftUp[1:20,:] = testSample[6:25,:]\nplt.imshow(shiftUp.reshape(28,28));plt.show()\n\nlabel = model1.predict_classes(shiftUp.reshape(1,28,28,nDims))[0]\nprint(\"Label = {}, Item = {}\".format(label,labelMap[label]))",
"_____no_output_____"
]
],
[
[
"### 8.3 On a shifted down image",
"_____no_output_____"
]
],
[
[
"shiftDown = np.zeros(testSample.shape)\nshiftDown[10:27,:] = testSample[6:23,:]\nplt.imshow(shiftDown.reshape(28,28));plt.show()\n\nlabel = model1.predict_classes(shiftDown.reshape(1,28,28,nDims))[0]\nprint(\"Label = {}, Item = {}\".format(label,labelMap[label]))",
"_____no_output_____"
]
],
[
[
"### 8.4 On left shit",
"_____no_output_____"
]
],
[
[
"# testSample.shape\n# shiftDown = np.zeros((56,56,1))\n# shiftDown[5:22,0:28] = testSample[6:23,0:28]\n# plt.imshow(shiftDown);plt.show()\n\n# label = model1.predict_classes(shiftDown.reshape(1,28,28,nDims))[0]\n# print(\"Label = {}, Item = {}\".format(label,labelMap[label]))",
"_____no_output_____"
],
[
"",
"_____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",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
]
|
cb5e94e5cca862c17688107505a583da3f21048d | 60,082 | ipynb | Jupyter Notebook | tutorials/Tutorial5_Evaluation.ipynb | abarbosa94/haystack | 74b0868d28bd773bd47f35c6b698991355ae0883 | [
"Apache-2.0"
]
| null | null | null | tutorials/Tutorial5_Evaluation.ipynb | abarbosa94/haystack | 74b0868d28bd773bd47f35c6b698991355ae0883 | [
"Apache-2.0"
]
| null | null | null | tutorials/Tutorial5_Evaluation.ipynb | abarbosa94/haystack | 74b0868d28bd773bd47f35c6b698991355ae0883 | [
"Apache-2.0"
]
| null | null | null | 30.131394 | 230 | 0.587231 | [
[
[
"# Evaluation of a QA System\n\nEXECUTABLE VERSION: [colab](https://colab.research.google.com/github/deepset-ai/haystack/blob/master/tutorials/Tutorial5_Evaluation.ipynb)\n\nTo be able to make a statement about the performance of a question-answering system, it is important to evalute it. Furthermore, evaluation allows to determine which parts of the system can be improved.",
"_____no_output_____"
],
[
"### Prepare environment\n\n#### Colab: Enable the GPU runtime\nMake sure you enable the GPU runtime to experience decent speed in this tutorial.\n**Runtime -> Change Runtime type -> Hardware accelerator -> GPU**\n\n<img src=\"https://raw.githubusercontent.com/deepset-ai/haystack/master/docs/_src/img/colab_gpu_runtime.jpg\">",
"_____no_output_____"
]
],
[
[
"# Make sure you have a GPU running\n!nvidia-smi",
"_____no_output_____"
]
],
[
[
"## Start an Elasticsearch server\nYou can start Elasticsearch on your local machine instance using Docker. If Docker is not readily available in your environment (eg., in Colab notebooks), then you can manually download and execute Elasticsearch from source.",
"_____no_output_____"
]
],
[
[
"# Install the latest release of Haystack in your own environment \n#! pip install farm-haystack\n\n# Install the latest master of Haystack\n!pip install git+https://github.com/deepset-ai/haystack.git\n!pip install urllib3==1.25.4\n!pip install torch==1.6.0+cu101 torchvision==0.6.1+cu101 -f https://download.pytorch.org/whl/torch_stable.html\n",
"_____no_output_____"
],
[
"# In Colab / No Docker environments: Start Elasticsearch from source\n! wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.9.2-linux-x86_64.tar.gz -q\n! tar -xzf elasticsearch-7.9.2-linux-x86_64.tar.gz\n! chown -R daemon:daemon elasticsearch-7.9.2\n\nimport os\nfrom subprocess import Popen, PIPE, STDOUT\nes_server = Popen(['elasticsearch-7.9.2/bin/elasticsearch'],\n stdout=PIPE, stderr=STDOUT,\n preexec_fn=lambda: os.setuid(1) # as daemon\n )\n# wait until ES has started\n! sleep 30",
"_____no_output_____"
],
[
"from farm.utils import initialize_device_settings\n\ndevice, n_gpu = initialize_device_settings(use_cuda=True)",
"_____no_output_____"
],
[
"from haystack.preprocessor.utils import fetch_archive_from_http\n\n# Download evaluation data, which is a subset of Natural Questions development set containing 50 documents\ndoc_dir = \"../data/nq\"\ns3_url = \"https://s3.eu-central-1.amazonaws.com/deepset.ai-farm-qa/datasets/nq_dev_subset_v2.json.zip\"\nfetch_archive_from_http(url=s3_url, output_dir=doc_dir)",
"_____no_output_____"
],
[
"# make sure these indices do not collide with existing ones, the indices will be wiped clean before data is inserted\ndoc_index = \"tutorial5_docs\"\nlabel_index = \"tutorial5_labels\"",
"_____no_output_____"
],
[
"# Connect to Elasticsearch\nfrom haystack.document_store.elasticsearch import ElasticsearchDocumentStore\n\n# Connect to Elasticsearch\ndocument_store = ElasticsearchDocumentStore(host=\"localhost\", username=\"\", password=\"\", index=\"document\",\n create_index=False, embedding_field=\"emb\",\n embedding_dim=768, excluded_meta_data=[\"emb\"])",
"_____no_output_____"
],
[
"# Add evaluation data to Elasticsearch Document Store\n# We first delete the custom tutorial indices to not have duplicate elements\ndocument_store.delete_all_documents(index=doc_index)\ndocument_store.delete_all_documents(index=label_index)\ndocument_store.add_eval_data(filename=\"../data/nq/nq_dev_subset_v2.json\", doc_index=doc_index, label_index=label_index)",
"_____no_output_____"
]
],
[
[
"## Initialize components of QA-System",
"_____no_output_____"
]
],
[
[
"# Initialize Retriever\nfrom haystack.retriever.sparse import ElasticsearchRetriever\nretriever = ElasticsearchRetriever(document_store=document_store)\n# Alternative: Evaluate DensePassageRetriever\n# Note, that DPR works best when you index short passages < 512 tokens as only those tokens will be used for the embedding.\n# Here, for nq_dev_subset_v2.json we have avg. num of tokens = 5220(!).\n# DPR still outperforms Elastic's BM25 by a small margin here.\n# from haystack.retriever.dense import DensePassageRetriever\n# retriever = DensePassageRetriever(document_store=document_store,\n# query_embedding_model=\"facebook/dpr-question_encoder-single-nq-base\",\n# passage_embedding_model=\"facebook/dpr-ctx_encoder-single-nq-base\",\n# use_gpu=True,\n# embed_title=True,\n# max_seq_len=256,\n# batch_size=16,\n# remove_sep_tok_from_untitled_passages=True)\n#document_store.update_embeddings(retriever, index=doc_index)",
"_____no_output_____"
],
[
"# Initialize Reader\nfrom haystack.reader.farm import FARMReader\n\nreader = FARMReader(\"deepset/roberta-base-squad2\", top_k_per_candidate=4)",
"_____no_output_____"
],
[
"# Initialize Finder which sticks together Reader and Retriever\nfrom haystack.finder import Finder\n\nfinder = Finder(reader, retriever)",
"_____no_output_____"
]
],
[
[
"## Evaluation of Retriever",
"_____no_output_____"
]
],
[
[
"## Evaluate Retriever on its own\nretriever_eval_results = retriever.eval(top_k=20, label_index=label_index, doc_index=doc_index)\n## Retriever Recall is the proportion of questions for which the correct document containing the answer is\n## among the correct documents\nprint(\"Retriever Recall:\", retriever_eval_results[\"recall\"])\n## Retriever Mean Avg Precision rewards retrievers that give relevant documents a higher rank\nprint(\"Retriever Mean Avg Precision:\", retriever_eval_results[\"map\"])",
"_____no_output_____"
]
],
[
[
"## Evaluation of Reader",
"_____no_output_____"
]
],
[
[
"# Evaluate Reader on its own\nreader_eval_results = reader.eval(document_store=document_store, device=device, label_index=label_index, doc_index=doc_index)\n# Evaluation of Reader can also be done directly on a SQuAD-formatted file without passing the data to Elasticsearch\n#reader_eval_results = reader.eval_on_file(\"../data/nq\", \"nq_dev_subset_v2.json\", device=device)\n\n## Reader Top-N-Accuracy is the proportion of predicted answers that match with their corresponding correct answer\nprint(\"Reader Top-N-Accuracy:\", reader_eval_results[\"top_n_accuracy\"])\n## Reader Exact Match is the proportion of questions where the predicted answer is exactly the same as the correct answer\nprint(\"Reader Exact Match:\", reader_eval_results[\"EM\"])\n## Reader F1-Score is the average overlap between the predicted answers and the correct answers\nprint(\"Reader F1-Score:\", reader_eval_results[\"f1\"])",
"_____no_output_____"
]
],
[
[
"## Evaluation of Finder",
"_____no_output_____"
]
],
[
[
"# Evaluate combination of Reader and Retriever through Finder\n# Evaluate combination of Reader and Retriever through Finder\nfinder_eval_results = finder.eval(top_k_retriever=1, top_k_reader=10, label_index=label_index, doc_index=doc_index)\nfinder.print_eval_results(finder_eval_results)",
"_____no_output_____"
]
]
]
| [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
]
| [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
]
|
cb5e979be38bede81b5335f138be33eebabc1d2e | 887,348 | ipynb | Jupyter Notebook | Day 1/Day1(Linear Regression or Least Square Fit).ipynb | golesuman/66-days-of-data-challenge- | 39d623f91979952b1987c023ef96c2210d631fc6 | [
"Apache-2.0"
]
| 2 | 2021-07-05T12:20:09.000Z | 2021-09-28T12:26:19.000Z | Day 1/Day1(Linear Regression or Least Square Fit).ipynb | golesuman/66daysofdata | 030ad00e0dcd8521bf3b5ae54baf46495c1e559d | [
"Apache-2.0"
]
| null | null | null | Day 1/Day1(Linear Regression or Least Square Fit).ipynb | golesuman/66daysofdata | 030ad00e0dcd8521bf3b5ae54baf46495c1e559d | [
"Apache-2.0"
]
| null | null | null | 441.906375 | 122,620 | 0.926265 | [
[
[
"## Importing dependencies and loading the data",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.datasets import load_boston\ndataset=load_boston()",
"_____no_output_____"
],
[
"dataset",
"_____no_output_____"
]
],
[
[
"### So in the given data there are certain features and target prices of houses in boston. So let's first transform the given data into dataframe",
"_____no_output_____"
]
],
[
[
"df=pd.DataFrame(dataset.data,columns=dataset.feature_names)\ndf.head()",
"_____no_output_____"
]
],
[
[
"Let's put the target variable to the dataframe\n",
"_____no_output_____"
]
],
[
[
"df['Target']=dataset.target\ndf.head()",
"_____no_output_____"
]
],
[
[
"## Since we have transformed the data into the dataframe now let's do the Exploratory Data Analysis i.e. EDA",
"_____no_output_____"
]
],
[
[
"df.describe()",
"_____no_output_____"
]
],
[
[
"Let's see if there is any missing data or not",
"_____no_output_____"
]
],
[
[
"df.isnull().sum()",
"_____no_output_____"
]
],
[
[
"### Since there is not any missing data let's see the correlation between the features",
"_____no_output_____"
]
],
[
[
"df.corr()",
"_____no_output_____"
]
],
[
[
"### Let's visualize the data on the heatmap",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(10,10)) #this increase the dimension of the figure\nsns.heatmap(df.corr(),annot=True) #this plots the data into the heatmap",
"_____no_output_____"
]
],
[
[
"### let's see the distribution of the data since all the features are continuous",
"_____no_output_____"
]
],
[
[
"cont=[feature for feature in df.columns]\ncont",
"_____no_output_____"
],
[
"for feature in cont:\n sns.distplot(df[feature])\n plt.show()",
"/home/suman/anaconda3/lib/python3.8/site-packages/seaborn/distributions.py:2551: FutureWarning: `distplot` is a deprecated function and will be removed in a future version. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or `histplot` (an axes-level function for histograms).\n warnings.warn(msg, FutureWarning)\n"
]
],
[
[
"#### Let's draw the regplot between the features and target",
"_____no_output_____"
]
],
[
[
"for feature in cont:\n if feature!='Target':\n sns.regplot(x=feature,y='Target',data=df)\n plt.show()",
"_____no_output_____"
],
[
"cont",
"_____no_output_____"
],
[
"plt.figure(figsize=(10,10)) #this increase the dimension of the figure\nsns.heatmap(df.corr(),annot=True)",
"_____no_output_____"
]
],
[
[
"### Let's do some feature engineering and drop some features which have low correlation with the target",
"_____no_output_____"
]
],
[
[
"'''Now let's take some of the features and test a model and after \nseeing the result we can again take some more features to see if the model is working fine or not.'''\nx=df.loc[:,[\n 'ZN',\n 'INDUS',\n 'NOX',\n 'RM',\n 'AGE',\n 'DIS',\n 'TAX',\n 'PTRATIO',\n 'B',\n 'LSTAT']]\ny=df.Target\nx.head()",
"_____no_output_____"
],
[
"# Now let's split the data into train and test data using train_test_split\nfrom 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=5)",
"_____no_output_____"
],
[
"# fitting the model\nfrom sklearn.linear_model import LinearRegression\nmodel=LinearRegression()\nmodel.fit(x_train,y_train)",
"_____no_output_____"
],
[
"# Predicting the values\ny_pre=model.predict(x_test)\ny_pre",
"_____no_output_____"
],
[
"# Let's see how our model is performing\nfrom sklearn.metrics import r2_score\nscore=r2_score(y_test,y_pre)\nscore",
"_____no_output_____"
],
[
"sns.scatterplot(y_test,y_pre)",
"/home/suman/anaconda3/lib/python3.8/site-packages/seaborn/_decorators.py:36: FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.\n warnings.warn(\n"
],
[
"sns.distplot(y_test-y_pre)",
"/home/suman/anaconda3/lib/python3.8/site-packages/seaborn/distributions.py:2551: FutureWarning: `distplot` is a deprecated function and will be removed in a future version. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or `histplot` (an axes-level function for histograms).\n warnings.warn(msg, FutureWarning)\n"
]
]
]
| [
"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"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
]
|
cb5e98edb07c95996ffc5445a5af7ac380b3cd99 | 52,116 | ipynb | Jupyter Notebook | label-crops/2020-04-03-ROICrops.ipynb | w210-accessibility/classify-streetview | d60328484ea992b4cb2ffecb04bb548efaf06f1b | [
"MIT"
]
| 2 | 2020-06-23T04:02:50.000Z | 2022-02-08T00:59:24.000Z | label-crops/2020-04-03-ROICrops.ipynb | w210-accessibility/classify-streetview | d60328484ea992b4cb2ffecb04bb548efaf06f1b | [
"MIT"
]
| null | null | null | label-crops/2020-04-03-ROICrops.ipynb | w210-accessibility/classify-streetview | d60328484ea992b4cb2ffecb04bb548efaf06f1b | [
"MIT"
]
| null | null | null | 31.855746 | 165 | 0.40335 | [
[
[
"# Move Files ",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport os\nfrom datetime import datetime\n\nimport shutil\nimport random",
"_____no_output_____"
],
[
"pd.set_option('max_colwidth', -1)",
"_____no_output_____"
]
],
[
[
"# Create list of current files",
"_____no_output_____"
]
],
[
[
"SAGEMAKER_REPO_PATH = r'/home/ec2-user/SageMaker/classify-streetview'\nORIGINAL_IMAGE_PATH = os.path.join(SAGEMAKER_REPO_PATH, 'images')\nORIGINAL_TRAIN_PATH = os.path.join(ORIGINAL_IMAGE_PATH, 'train')\nos.listdir(ORIGINAL_TRAIN_PATH)",
"_____no_output_____"
],
[
"subset_list = ['train', 'valid', 'test']\n# Include obstacle and surface prob in case we need to move those images\nclass_list = ['3_present', '0_missing', '1_null', '2_obstacle', '4_surface_prob']",
"_____no_output_____"
],
[
"original_df_list = []",
"_____no_output_____"
],
[
"# Get all existing jpgs with their detailed info\nfor split in subset_list:\n for class_name in class_list:\n full_folder_path = os.path.join(ORIGINAL_IMAGE_PATH, split, class_name)\n jpg_names = os.listdir(full_folder_path)\n df_part = pd.DataFrame({'jpg_name' : jpg_names, 'original_folder_path' : full_folder_path, 'original_group' : split, 'original_label' : class_name})\n original_df_list.append(df_part)",
"_____no_output_____"
],
[
"# Create a full list all files\ndf_original = pd.concat(original_df_list)\nprint(df_original.shape)\ndf_original.head()",
"(7455, 4)\n"
],
[
"df_original.to_csv('March-SmartCrop-ImageList.csv', index = False)",
"_____no_output_____"
],
[
"df_original['original_label'].value_counts()",
"_____no_output_____"
]
],
[
[
"## Get the New ROI Image Details",
"_____no_output_____"
]
],
[
[
"df_train = pd.read_csv('train_labels.csv')\ndf_train['new_group'] = 'train'\ndf_val = pd.read_csv('validation_labels.csv')\ndf_val['new_group'] = 'valid'\ndf_test = pd.read_csv('test_labels.csv')\ndf_test['new_group'] = 'test'",
"_____no_output_____"
],
[
"df_new_roi = pd.concat([df_train, df_val, df_test])\nprint(df_new_roi.shape)\ndf_new_roi.head()",
"(13440, 9)\n"
],
[
"df_new_roi['jpg_name'] = df_new_roi['img_id'].astype(str) + '_' + df_new_roi['heading'].astype(str) + '_' +df_new_roi['crop_number'].astype(str) + '.jpg'\ndf_new_roi.head()",
"_____no_output_____"
]
],
[
[
"# Combine ROI Images with Original Image details",
"_____no_output_____"
]
],
[
[
"df_combine = df_new_roi.merge(df_original, how = 'outer', left_on = 'jpg_name', right_on = 'jpg_name')\nprint(df_combine.shape)\ndf_combine.head()",
"(13441, 13)\n"
],
[
"df_combine['crop_number'].value_counts(dropna = False)",
"_____no_output_____"
],
[
"df_combine.loc[df_combine['crop_number'].isna()]",
"_____no_output_____"
],
[
"df_combine['original_folder_path'].value_counts(dropna = False).head()",
"_____no_output_____"
],
[
"df_group_label = df_combine.groupby(['ground_truth', 'original_label'])['jpg_name'].count()\ndf_group_label",
"_____no_output_____"
],
[
"df_combine['jpg_name'].value_counts().describe()",
"_____no_output_____"
]
],
[
[
"# Observations\n* There's exactly 1 row per jpg_name\n* There's a row with ipynb_checkpoints, which is fine\n* There are some lost images (mainly null) \n* The grouping by label showing how images move around into the new \"ground_truth\" ",
"_____no_output_____"
],
[
"# Create the list of files before and after locations",
"_____no_output_____"
]
],
[
[
"df_move = df_combine.dropna().copy()\ndf_move.shape",
"_____no_output_____"
],
[
"df_move['ground_truth'].value_counts()",
"_____no_output_____"
],
[
"df_move['new_group'].value_counts()",
"_____no_output_____"
],
[
"df_move.head()",
"_____no_output_____"
],
[
"df_move['new_folder_path'] = SAGEMAKER_REPO_PATH + '/roi-images/' + df_move['new_group'] + '/' + df_move['ground_truth'] \ndf_move.head()",
"_____no_output_____"
],
[
"df_move.to_csv('roi-images-sagemaker-paths.csv', index = False)",
"_____no_output_____"
]
],
[
[
"# Actually Copy the Images",
"_____no_output_____"
]
],
[
[
"# Make sure folders exst for all new folders\nunique_new_folders = list(df_move['new_folder_path'].unique())\nprint(len(unique_new_folders))\nfor new_folder in unique_new_folders:\n if not os.path.exists(new_folder):\n os.makedirs(new_folder)\n print(new_folder)",
"9\n/home/ec2-user/SageMaker/classify-streetview/roi-images/train/1_null\n/home/ec2-user/SageMaker/classify-streetview/roi-images/train/2_present\n/home/ec2-user/SageMaker/classify-streetview/roi-images/train/0_missing\n/home/ec2-user/SageMaker/classify-streetview/roi-images/valid/1_null\n/home/ec2-user/SageMaker/classify-streetview/roi-images/valid/0_missing\n/home/ec2-user/SageMaker/classify-streetview/roi-images/valid/2_present\n/home/ec2-user/SageMaker/classify-streetview/roi-images/test/1_null\n/home/ec2-user/SageMaker/classify-streetview/roi-images/test/2_present\n/home/ec2-user/SageMaker/classify-streetview/roi-images/test/0_missing\n"
],
[
"for index, row in df_move.iterrows():\n original = os.path.join(row['original_folder_path'], row['jpg_name'])\n target = os.path.join(row['new_folder_path'], row['jpg_name'])\n try:\n shutil.copyfile(original, target)\n except:\n print(f\"could not copy: {row['jpg_name']}\")",
"_____no_output_____"
]
],
[
[
"# Make an alphabetical list of the test images",
"_____no_output_____"
]
],
[
[
"df_test = df_move.loc[df_move['new_group'] == 'test']\nprint(df_test.shape)\ndf_test.columns",
"(958, 14)\n"
],
[
"keep_cols = ['img_id', 'heading', 'crop_number', '0_missing', '1_null', '2_present', 'count_all', 'ground_truth', 'jpg_name', 'new_folder_path']\ndf_test_keep = df_test[keep_cols].copy()\ndf_test_keep = df_test_keep.sort_values(['new_folder_path', 'jpg_name'])\ndf_test_keep.head()",
"_____no_output_____"
],
[
"df_test_keep.to_csv('test_roi_image_locations_sorted.csv', index = False)",
"_____no_output_____"
]
]
]
| [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
]
| [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
]
|
cb5eaa949a3929ad0a96e5286a9b693a1cc07014 | 56,030 | ipynb | Jupyter Notebook | main_TSP_edge_classification.ipynb | nnzhan/AutoGCN | 22c1062152a67581b310c371dfc5a5e27f79dddb | [
"MIT"
]
| 5 | 2021-07-13T14:16:22.000Z | 2022-03-07T10:41:21.000Z | main_TSP_edge_classification.ipynb | nfkjsfoeif/AutoGCN | 4496bc066936d93b2e852c8010d95fb372910a80 | [
"MIT"
]
| null | null | null | main_TSP_edge_classification.ipynb | nfkjsfoeif/AutoGCN | 4496bc066936d93b2e852c8010d95fb372910a80 | [
"MIT"
]
| 1 | 2020-09-16T14:58:24.000Z | 2020-09-16T14:58:24.000Z | 66.151122 | 1,924 | 0.599804 | [
[
[
"## Main Driver Notebook for Training Graph NNs on TSP for Edge Classification",
"_____no_output_____"
],
[
"### MODELS\n- GatedGCN \n- GCN \n- GAT \n- GraphSage \n- GIN \n- MoNet \n- MLP\n\n### DATASET\n- TSP\n\n### TASK\n- Edge Classification, i.e. Classifying each edge as belonging/not belonging to the optimal TSP solution set.",
"_____no_output_____"
]
],
[
[
"\"\"\"\n IMPORTING LIBS\n\"\"\"\nimport dgl\n\nimport numpy as np\nimport os\nimport socket\nimport time\nimport random\nimport glob\nimport argparse, json\nimport pickle\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\n\nfrom tensorboardX import SummaryWriter\nfrom tqdm import tqdm\n\nclass DotDict(dict):\n def __init__(self, **kwds):\n self.update(kwds)\n self.__dict__ = self\n ",
"_____no_output_____"
],
[
"# \"\"\"\n# AUTORELOAD IPYTHON EXTENSION FOR RELOADING IMPORTED MODULES\n# \"\"\"\n\ndef in_ipynb():\n try:\n cfg = get_ipython().config \n return True\n except NameError:\n return False\n \nnotebook_mode = in_ipynb()\nprint(notebook_mode)\n\nif notebook_mode == True:\n %load_ext autoreload\n %autoreload 2\n ",
"True\n"
],
[
"\"\"\"\n IMPORTING CUSTOM MODULES/METHODS\n\"\"\"\nfrom nets.TSP_edge_classification.load_net import gnn_model # import all GNNS\nfrom data.data import LoadData # import dataset\nfrom train.train_TSP_edge_classification import train_epoch, evaluate_network # import train functions\n",
"_____no_output_____"
],
[
"\"\"\"\n GPU Setup\n\"\"\"\ndef gpu_setup(use_gpu, gpu_id):\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(gpu_id) \n\n if torch.cuda.is_available() and use_gpu:\n print('cuda available with GPU:',torch.cuda.get_device_name(0))\n device = torch.device(\"cuda\")\n else:\n print('cuda not available')\n device = torch.device(\"cpu\")\n return device\n\n\nuse_gpu = True\ngpu_id = -1\ndevice = None\n",
"_____no_output_____"
],
[
"# \"\"\"\n# USER CONTROLS\n# \"\"\"\nif notebook_mode == True:\n \n MODEL_NAME = 'MLP'\n # MODEL_NAME = 'GCN'\n MODEL_NAME = 'GatedGCN'\n # MODEL_NAME = 'GAT'\n # MODEL_NAME = 'GraphSage'\n # MODEL_NAME = 'DiffPool'\n # MODEL_NAME = 'GIN'\n\n DATASET_NAME = 'TSP'\n\n out_dir = 'out/TSP_edge_classification/'\n root_log_dir = out_dir + 'logs/' + MODEL_NAME + \"_\" + DATASET_NAME + \"_\" + time.strftime('%Hh%Mm%Ss_on_%b_%d_%Y')\n root_ckpt_dir = out_dir + 'checkpoints/' + MODEL_NAME + \"_\" + DATASET_NAME + \"_\" + time.strftime('%Hh%Mm%Ss_on_%b_%d_%Y')\n\n print(\"[I] Loading data (notebook) ...\")\n dataset = LoadData(DATASET_NAME)\n trainset, valset, testset = dataset.train, dataset.val, dataset.test\n print(\"[I] Finished loading.\")\n ",
"[I] Loading data (notebook) ...\n[I] Loading dataset TSP...\ntrain, test, val sizes : 10000 1000 1000\n[I] Finished loading.\n[I] Data load time: 20.0447s\n[I] Finished loading.\n"
],
[
"MODEL_NAME = 'GatedGCN'\nMODEL_NAME = 'GCN'\nMODEL_NAME = 'GAT'\n#MODEL_NAME = 'GraphSage'\n#MODEL_NAME = 'MLP'\n#MODEL_NAME = 'GIN'\n#MODEL_NAME = 'MoNet'\n",
"_____no_output_____"
],
[
"# \"\"\"\n# PARAMETERS\n# \"\"\"\nif notebook_mode == True:\n \n #MODEL_NAME = 'GCN'\n \n n_heads = -1\n edge_feat = False\n pseudo_dim_MoNet = -1\n kernel = -1\n gnn_per_block = -1\n embedding_dim = -1\n pool_ratio = -1\n n_mlp_GIN = -1\n gated = False\n self_loop = False\n max_time = 48\n\n \n if MODEL_NAME == 'MLP':\n seed=41; epochs=500; batch_size=64; init_lr=0.001; lr_reduce_factor=0.5; lr_schedule_patience=10; min_lr = 1e-5; weight_decay=0\n L=3; hidden_dim=144; out_dim=hidden_dim; dropout=0.0; readout='mean'; gated = False # Change gated = True for Gated MLP model\n \n if MODEL_NAME == 'GCN':\n seed=41; epochs=500; batch_size=64; init_lr=0.001; lr_reduce_factor=0.5; lr_schedule_patience=10; min_lr = 1e-5; weight_decay=0\n L=4; hidden_dim=128; out_dim=hidden_dim; dropout=0.0; readout='mean';\n \n if MODEL_NAME == 'GraphSage':\n seed=41; epochs=500; batch_size=64; init_lr=0.001; lr_reduce_factor=0.5; lr_schedule_patience=10; min_lr = 1e-5; weight_decay=0\n L=4; hidden_dim=96; out_dim=hidden_dim; dropout=0.0; readout='mean';\n\n if MODEL_NAME == 'GAT':\n seed=41; epochs=500; batch_size=64; init_lr=0.001; lr_reduce_factor=0.5; lr_schedule_patience=10; min_lr = 1e-5; weight_decay=0\n L=4; n_heads=8; hidden_dim=16; out_dim=128; dropout=0.0; readout='mean';\n \n if MODEL_NAME == 'GIN':\n seed=41; epochs=500; batch_size=64; init_lr=0.001; lr_reduce_factor=0.5; lr_schedule_patience=10; min_lr = 1e-5; weight_decay=0\n L=4; hidden_dim=112; out_dim=hidden_dim; dropout=0.0; readout='mean';\n \n if MODEL_NAME == 'MoNet':\n seed=41; epochs=500; batch_size=64; init_lr=0.001; lr_reduce_factor=0.5; lr_schedule_patience=10; min_lr = 1e-5; weight_decay=0\n L=4; hidden_dim=80; out_dim=hidden_dim; dropout=0.0; readout='mean';\n \n if MODEL_NAME == 'GatedGCN':\n seed=41; epochs=500; batch_size=64; init_lr=0.001; lr_reduce_factor=0.5; lr_schedule_patience=10; min_lr = 1e-5; weight_decay=0\n L=4; hidden_dim=64; out_dim=hidden_dim; dropout=0.0; readout='mean'; edge_feat = True\n\n # generic new_params\n net_params = {}\n net_params['device'] = device\n net_params['in_dim'] = trainset[0][0].ndata['feat'][0].size(0)\n net_params['in_dim_edge'] = trainset[0][0].edata['feat'][0].size(0)\n net_params['residual'] = True\n net_params['hidden_dim'] = hidden_dim\n net_params['out_dim'] = out_dim\n num_classes = len(np.unique(np.concatenate(trainset[:][1])))\n net_params['n_classes'] = num_classes\n net_params['n_heads'] = n_heads\n net_params['L'] = L # min L should be 2\n net_params['readout'] = \"mean\"\n net_params['graph_norm'] = True\n net_params['batch_norm'] = True\n net_params['in_feat_dropout'] = 0.0\n net_params['dropout'] = 0.0\n net_params['edge_feat'] = edge_feat\n net_params['self_loop'] = self_loop\n \n # for MLPNet \n net_params['gated'] = gated\n \n # specific for MoNet\n net_params['pseudo_dim_MoNet'] = 2\n net_params['kernel'] = 3\n \n # specific for GIN\n net_params['n_mlp_GIN'] = 2\n net_params['learn_eps_GIN'] = True\n net_params['neighbor_aggr_GIN'] = 'sum'\n \n # specific for graphsage\n net_params['sage_aggregator'] = 'meanpool' \n\n # setting seeds\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n if device == 'cuda':\n torch.cuda.manual_seed(seed)\n ",
"_____no_output_____"
],
[
"\"\"\"\n VIEWING MODEL CONFIG AND PARAMS\n\"\"\"\ndef view_model_param(MODEL_NAME, net_params):\n model = gnn_model(MODEL_NAME, net_params)\n total_param = 0\n print(\"MODEL DETAILS:\\n\")\n #print(model)\n for param in model.parameters():\n # print(param.data.size())\n total_param += np.prod(list(param.data.size()))\n print('MODEL/Total parameters:', MODEL_NAME, total_param)\n return total_param\n\n\nif notebook_mode == True:\n view_model_param(MODEL_NAME, net_params)\n ",
"MODEL DETAILS:\n\nMODEL/Total parameters: GAT 109250\n"
],
[
"\"\"\"\n TRAINING CODE\n\"\"\"\n\ndef train_val_pipeline(MODEL_NAME, dataset, params, net_params, dirs):\n t0 = time.time()\n per_epoch_time = []\n \n DATASET_NAME = dataset.name\n \n #assert net_params['self_loop'] == False, \"No self-loop support for %s dataset\" % DATASET_NAME\n \n trainset, valset, testset = dataset.train, dataset.val, dataset.test\n \n root_log_dir, root_ckpt_dir, write_file_name, write_config_file = dirs\n device = net_params['device']\n \n # Write the network and optimization hyper-parameters in folder config/\n with open(write_config_file + '.txt', 'w') as f:\n f.write(\"\"\"Dataset: {},\\nModel: {}\\n\\nparams={}\\n\\nnet_params={}\\n\\n\\nTotal Parameters: {}\\n\\n\"\"\"\\\n .format(DATASET_NAME, MODEL_NAME, params, net_params, net_params['total_param']))\n \n log_dir = os.path.join(root_log_dir, \"RUN_\" + str(0))\n writer = SummaryWriter(log_dir=log_dir)\n\n # setting seeds\n random.seed(params['seed'])\n np.random.seed(params['seed'])\n torch.manual_seed(params['seed'])\n if device == 'cuda':\n torch.cuda.manual_seed(params['seed'])\n \n print(\"Training Graphs: \", len(trainset))\n print(\"Validation Graphs: \", len(valset))\n print(\"Test Graphs: \", len(testset))\n print(\"Number of Classes: \", net_params['n_classes'])\n\n model = gnn_model(MODEL_NAME, net_params)\n model = model.to(device)\n\n optimizer = optim.Adam(model.parameters(), lr=params['init_lr'], weight_decay=params['weight_decay'])\n scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min',\n factor=params['lr_reduce_factor'],\n patience=params['lr_schedule_patience'],\n verbose=True)\n \n epoch_train_losses, epoch_val_losses = [], []\n epoch_train_f1s, epoch_val_f1s = [], [] \n \n train_loader = DataLoader(trainset, batch_size=params['batch_size'], shuffle=True, collate_fn=dataset.collate)\n val_loader = DataLoader(valset, batch_size=params['batch_size'], shuffle=False, collate_fn=dataset.collate)\n test_loader = DataLoader(testset, batch_size=params['batch_size'], shuffle=False, collate_fn=dataset.collate)\n\n # At any point you can hit Ctrl + C to break out of training early.\n try:\n with tqdm(range(params['epochs'])) as t:\n for epoch in t:\n\n t.set_description('Epoch %d' % epoch) \n\n start = time.time()\n\n epoch_train_loss, epoch_train_f1, optimizer = train_epoch(model, optimizer, device, train_loader, epoch)\n epoch_val_loss, epoch_val_f1 = evaluate_network(model, device, val_loader, epoch)\n\n epoch_train_losses.append(epoch_train_loss)\n epoch_val_losses.append(epoch_val_loss)\n epoch_train_f1s.append(epoch_train_f1)\n epoch_val_f1s.append(epoch_val_f1)\n\n writer.add_scalar('train/_loss', epoch_train_loss, epoch)\n writer.add_scalar('val/_loss', epoch_val_loss, epoch)\n writer.add_scalar('train/_f1', epoch_train_f1, epoch)\n writer.add_scalar('val/_f1', epoch_val_f1, epoch)\n writer.add_scalar('learning_rate', optimizer.param_groups[0]['lr'], epoch) \n\n _, epoch_test_f1 = evaluate_network(model, device, test_loader, epoch) \n t.set_postfix(time=time.time()-start, lr=optimizer.param_groups[0]['lr'],\n train_loss=epoch_train_loss, val_loss=epoch_val_loss,\n train_f1=epoch_train_f1, val_f1=epoch_val_f1,\n test_f1=epoch_test_f1) \n\n per_epoch_time.append(time.time()-start)\n\n # Saving checkpoint\n ckpt_dir = os.path.join(root_ckpt_dir, \"RUN_\")\n if not os.path.exists(ckpt_dir):\n os.makedirs(ckpt_dir)\n torch.save(model.state_dict(), '{}.pkl'.format(ckpt_dir + \"/epoch_\" + str(epoch)))\n\n files = glob.glob(ckpt_dir + '/*.pkl')\n for file in files:\n epoch_nb = file.split('_')[-1]\n epoch_nb = int(epoch_nb.split('.')[0])\n if epoch_nb < epoch-1:\n os.remove(file)\n\n scheduler.step(epoch_val_loss)\n\n if optimizer.param_groups[0]['lr'] < params['min_lr']:\n print(\"\\n!! LR EQUAL TO MIN LR SET.\")\n break\n \n # Stop training after params['max_time'] hours\n if time.time()-t0 > params['max_time']*3600:\n print('-' * 89)\n print(\"Max_time for training elapsed {:.2f} hours, so stopping\".format(params['max_time']))\n break\n \n except KeyboardInterrupt:\n print('-' * 89)\n print('Exiting from training early because of KeyboardInterrupt')\n \n _, test_f1 = evaluate_network(model, device, test_loader, epoch)\n _, train_f1 = evaluate_network(model, device, train_loader, epoch)\n print(\"Test F1: {:.4f}\".format(test_f1))\n print(\"Train F1: {:.4f}\".format(train_f1))\n print(\"TOTAL TIME TAKEN: {:.4f}s\".format(time.time()-t0))\n print(\"AVG TIME PER EPOCH: {:.4f}s\".format(np.mean(per_epoch_time)))\n\n writer.close()\n\n \"\"\"\n Write the results in out_dir/results folder\n \"\"\"\n with open(write_file_name + '.txt', 'w') as f:\n f.write(\"\"\"Dataset: {},\\nModel: {}\\n\\nparams={}\\n\\nnet_params={}\\n\\n{}\\n\\nTotal Parameters: {}\\n\\n\n FINAL RESULTS\\nTEST F1: {:.4f}\\nTRAIN F1: {:.4f}\\n\\n\n Total Time Taken: {:.4f}hrs\\nAverage Time Per Epoch: {:.4f}s\\n\\n\\n\"\"\"\\\n .format(DATASET_NAME, MODEL_NAME, params, net_params, model, net_params['total_param'],\n np.mean(np.array(test_f1)), np.mean(np.array(train_f1)), (time.time()-t0)/3600, np.mean(per_epoch_time)))\n \n\n # send results to gmail\n try:\n from gmail import send\n subject = 'Result for Dataset: {}, Model: {}'.format(DATASET_NAME, MODEL_NAME)\n body = \"\"\"Dataset: {},\\nModel: {}\\n\\nparams={}\\n\\nnet_params={}\\n\\n{}\\n\\nTotal Parameters: {}\\n\\n\n FINAL RESULTS\\nTEST F1: {:.4f}\\nTRAIN F1: {:.4f}\\n\\n\n Total Time Taken: {:.4f}hrs\\nAverage Time Per Epoch: {:.4f}s\\n\\n\\n\"\"\"\\\n .format(DATASET_NAME, MODEL_NAME, params, net_params, model, net_params['total_param'],\n np.mean(np.array(test_f1)), np.mean(np.array(train_f1)), (time.time()-t0)/3600, np.mean(per_epoch_time))\n send(subject, body)\n except:\n pass\n ",
"_____no_output_____"
],
[
"def main(notebook_mode=False,config=None):\n \n \"\"\"\n USER CONTROLS\n \"\"\"\n \n # terminal mode\n if notebook_mode==False:\n \n parser = argparse.ArgumentParser()\n parser.add_argument('--config', help=\"Please give a config.json file with training/model/data/param details\")\n parser.add_argument('--gpu_id', help=\"Please give a value for gpu id\")\n parser.add_argument('--model', help=\"Please give a value for model name\")\n parser.add_argument('--dataset', help=\"Please give a value for dataset name\")\n parser.add_argument('--out_dir', help=\"Please give a value for out_dir\")\n parser.add_argument('--seed', help=\"Please give a value for seed\")\n parser.add_argument('--epochs', help=\"Please give a value for epochs\")\n parser.add_argument('--batch_size', help=\"Please give a value for batch_size\")\n parser.add_argument('--init_lr', help=\"Please give a value for init_lr\")\n parser.add_argument('--lr_reduce_factor', help=\"Please give a value for lr_reduce_factor\")\n parser.add_argument('--lr_schedule_patience', help=\"Please give a value for lr_schedule_patience\")\n parser.add_argument('--min_lr', help=\"Please give a value for min_lr\")\n parser.add_argument('--weight_decay', help=\"Please give a value for weight_decay\")\n parser.add_argument('--print_epoch_interval', help=\"Please give a value for print_epoch_interval\") \n parser.add_argument('--L', help=\"Please give a value for L\")\n parser.add_argument('--hidden_dim', help=\"Please give a value for hidden_dim\")\n parser.add_argument('--out_dim', help=\"Please give a value for out_dim\")\n parser.add_argument('--residual', help=\"Please give a value for residual\")\n parser.add_argument('--edge_feat', help=\"Please give a value for edge_feat\")\n parser.add_argument('--readout', help=\"Please give a value for readout\")\n parser.add_argument('--kernel', help=\"Please give a value for kernel\")\n parser.add_argument('--n_heads', help=\"Please give a value for n_heads\")\n parser.add_argument('--gated', help=\"Please give a value for gated\")\n parser.add_argument('--in_feat_dropout', help=\"Please give a value for in_feat_dropout\")\n parser.add_argument('--dropout', help=\"Please give a value for dropout\")\n parser.add_argument('--graph_norm', help=\"Please give a value for graph_norm\")\n parser.add_argument('--batch_norm', help=\"Please give a value for batch_norm\")\n parser.add_argument('--sage_aggregator', help=\"Please give a value for sage_aggregator\")\n parser.add_argument('--data_mode', help=\"Please give a value for data_mode\")\n parser.add_argument('--num_pool', help=\"Please give a value for num_pool\")\n parser.add_argument('--gnn_per_block', help=\"Please give a value for gnn_per_block\")\n parser.add_argument('--embedding_dim', help=\"Please give a value for embedding_dim\")\n parser.add_argument('--pool_ratio', help=\"Please give a value for pool_ratio\")\n parser.add_argument('--linkpred', help=\"Please give a value for linkpred\")\n parser.add_argument('--cat', help=\"Please give a value for cat\")\n parser.add_argument('--self_loop', help=\"Please give a value for self_loop\")\n parser.add_argument('--max_time', help=\"Please give a value for max_time\")\n args = parser.parse_args()\n with open(args.config) as f:\n config = json.load(f)\n \n\n # device\n if args.gpu_id is not None:\n config['gpu']['id'] = int(args.gpu_id)\n config['gpu']['use'] = True\n device = gpu_setup(config['gpu']['use'], config['gpu']['id'])\n\n # model, dataset, out_dir\n if args.model is not None:\n MODEL_NAME = args.model\n else:\n MODEL_NAME = config['model']\n if args.dataset is not None:\n DATASET_NAME = args.dataset\n else:\n DATASET_NAME = config['dataset']\n dataset = LoadData(DATASET_NAME)\n if args.out_dir is not None:\n out_dir = args.out_dir\n else:\n out_dir = config['out_dir']\n\n # parameters\n params = config['params']\n if args.seed is not None:\n params['seed'] = int(args.seed)\n if args.epochs is not None:\n params['epochs'] = int(args.epochs)\n if args.batch_size is not None:\n params['batch_size'] = int(args.batch_size)\n if args.init_lr is not None:\n params['init_lr'] = float(args.init_lr)\n if args.lr_reduce_factor is not None:\n params['lr_reduce_factor'] = float(args.lr_reduce_factor)\n if args.lr_schedule_patience is not None:\n params['lr_schedule_patience'] = int(args.lr_schedule_patience)\n if args.min_lr is not None:\n params['min_lr'] = float(args.min_lr)\n if args.weight_decay is not None:\n params['weight_decay'] = float(args.weight_decay)\n if args.print_epoch_interval is not None:\n params['print_epoch_interval'] = int(args.print_epoch_interval)\n if args.max_time is not None:\n params['max_time'] = float(args.max_time)\n\n # network parameters\n net_params = config['net_params']\n net_params['device'] = device\n net_params['gpu_id'] = config['gpu']['id']\n net_params['batch_size'] = params['batch_size']\n if args.L is not None:\n net_params['L'] = int(args.L)\n if args.hidden_dim is not None:\n net_params['hidden_dim'] = int(args.hidden_dim)\n if args.out_dim is not None:\n net_params['out_dim'] = int(args.out_dim) \n if args.residual is not None:\n net_params['residual'] = True if args.residual=='True' else False\n if args.edge_feat is not None:\n net_params['edge_feat'] = True if args.edge_feat=='True' else False\n if args.readout is not None:\n net_params['readout'] = args.readout\n if args.kernel is not None:\n net_params['kernel'] = int(args.kernel)\n if args.n_heads is not None:\n net_params['n_heads'] = int(args.n_heads)\n if args.gated is not None:\n net_params['gated'] = True if args.gated=='True' else False\n if args.in_feat_dropout is not None:\n net_params['in_feat_dropout'] = float(args.in_feat_dropout)\n if args.dropout is not None:\n net_params['dropout'] = float(args.dropout)\n if args.graph_norm is not None:\n net_params['graph_norm'] = True if args.graph_norm=='True' else False\n if args.batch_norm is not None:\n net_params['batch_norm'] = True if args.batch_norm=='True' else False\n if args.sage_aggregator is not None:\n net_params['sage_aggregator'] = args.sage_aggregator\n if args.data_mode is not None:\n net_params['data_mode'] = args.data_mode\n if args.num_pool is not None:\n net_params['num_pool'] = int(args.num_pool)\n if args.gnn_per_block is not None:\n net_params['gnn_per_block'] = int(args.gnn_per_block)\n if args.embedding_dim is not None:\n net_params['embedding_dim'] = int(args.embedding_dim)\n if args.pool_ratio is not None:\n net_params['pool_ratio'] = float(args.pool_ratio)\n if args.linkpred is not None:\n net_params['linkpred'] = True if args.linkpred=='True' else False\n if args.cat is not None:\n net_params['cat'] = True if args.cat=='True' else False\n if args.self_loop is not None:\n net_params['self_loop'] = True if args.self_loop=='True' else False\n \n\n # notebook mode\n if notebook_mode:\n \n # parameters\n params = config['params']\n \n # dataset\n DATASET_NAME = config['dataset']\n dataset = LoadData(DATASET_NAME)\n \n # device\n device = gpu_setup(config['gpu']['use'], config['gpu']['id'])\n out_dir = config['out_dir']\n \n # GNN model\n MODEL_NAME = config['model']\n \n # network parameters\n net_params = config['net_params']\n net_params['device'] = device\n net_params['gpu_id'] = config['gpu']['id']\n net_params['batch_size'] = params['batch_size']\n \n \n # TSP\n net_params['in_dim'] = dataset.train[0][0].ndata['feat'][0].shape[0]\n net_params['in_dim_edge'] = dataset.train[0][0].edata['feat'][0].size(0)\n num_classes = len(np.unique(np.concatenate(dataset.train[:][1])))\n net_params['n_classes'] = num_classes\n \n root_log_dir = out_dir + 'logs/' + MODEL_NAME + \"_\" + DATASET_NAME + \"_GPU\" + str(config['gpu']['id']) + \"_\" + time.strftime('%Hh%Mm%Ss_on_%b_%d_%Y')\n root_ckpt_dir = out_dir + 'checkpoints/' + MODEL_NAME + \"_\" + DATASET_NAME + \"_GPU\" + str(config['gpu']['id']) + \"_\" + time.strftime('%Hh%Mm%Ss_on_%b_%d_%Y')\n write_file_name = out_dir + 'results/result_' + MODEL_NAME + \"_\" + DATASET_NAME + \"_GPU\" + str(config['gpu']['id']) + \"_\" + time.strftime('%Hh%Mm%Ss_on_%b_%d_%Y')\n write_config_file = out_dir + 'configs/config_' + MODEL_NAME + \"_\" + DATASET_NAME + \"_GPU\" + str(config['gpu']['id']) + \"_\" + time.strftime('%Hh%Mm%Ss_on_%b_%d_%Y')\n dirs = root_log_dir, root_ckpt_dir, write_file_name, write_config_file\n\n if not os.path.exists(out_dir + 'results'):\n os.makedirs(out_dir + 'results')\n \n if not os.path.exists(out_dir + 'configs'):\n os.makedirs(out_dir + 'configs')\n\n net_params['total_param'] = view_model_param(MODEL_NAME, net_params)\n train_val_pipeline(MODEL_NAME, dataset, params, net_params, dirs)\n\n \n \n \n \n \n \nif notebook_mode==True:\n \n config = {}\n # gpu config\n gpu = {}\n gpu['use'] = use_gpu\n gpu['id'] = gpu_id\n config['gpu'] = gpu\n # GNN model, dataset, out_dir\n config['model'] = MODEL_NAME\n config['dataset'] = DATASET_NAME\n config['out_dir'] = out_dir\n # parameters\n params = {}\n params['seed'] = seed\n params['epochs'] = epochs\n params['batch_size'] = batch_size\n params['init_lr'] = init_lr\n params['lr_reduce_factor'] = lr_reduce_factor \n params['lr_schedule_patience'] = lr_schedule_patience\n params['min_lr'] = min_lr\n params['weight_decay'] = weight_decay\n params['print_epoch_interval'] = 5\n params['max_time'] = max_time\n config['params'] = params\n # network parameters\n config['net_params'] = net_params\n \n # convert to .py format\n from utils.cleaner_main import *\n cleaner_main('main_TSP_edge_classification')\n \n main(True,config)\n \nelse:\n \n main()\n ",
"Convert main_TSP_edge_classification.ipynb to main_TSP_edge_classification.py\nClean main_TSP_edge_classification.py\nDone. \n[I] Loading dataset TSP...\ntrain, test, val sizes : 10000 1000 1000\n[I] Finished loading.\n[I] Data load time: 24.1761s\ncuda not available\n"
]
]
]
| [
"markdown",
"code"
]
| [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
]
|
cb5eb0c764792066e4647feb02b72bcf1b6d0d9d | 14,626 | ipynb | Jupyter Notebook | flux/test_flux.ipynb | matsunagalab/notebooks | b5cfd038999e2f01874145d26de32fdc933f2fd8 | [
"BSD-3-Clause"
]
| null | null | null | flux/test_flux.ipynb | matsunagalab/notebooks | b5cfd038999e2f01874145d26de32fdc933f2fd8 | [
"BSD-3-Clause"
]
| null | null | null | flux/test_flux.ipynb | matsunagalab/notebooks | b5cfd038999e2f01874145d26de32fdc933f2fd8 | [
"BSD-3-Clause"
]
| null | null | null | 31.053079 | 1,461 | 0.541638 | [
[
[
"empty"
]
]
]
| [
"empty"
]
| [
[
"empty"
]
]
|
cb5eb29bb99ad32e7de001102266b69cbf6d57af | 5,364 | ipynb | Jupyter Notebook | s1/codes/stopwords.ipynb | gebakx/ihlt | 10c22f6e6c38a84772457d8c4093878ef917d9cf | [
"MIT"
]
| null | null | null | s1/codes/stopwords.ipynb | gebakx/ihlt | 10c22f6e6c38a84772457d8c4093878ef917d9cf | [
"MIT"
]
| null | null | null | s1/codes/stopwords.ipynb | gebakx/ihlt | 10c22f6e6c38a84772457d8c4093878ef917d9cf | [
"MIT"
]
| 1 | 2019-11-20T22:58:32.000Z | 2019-11-20T22:58:32.000Z | 19.576642 | 43 | 0.299963 | [
[
[
"## Stopwords reader",
"_____no_output_____"
]
],
[
[
"from nltk.corpus import stopwords\n\nsw=set(stopwords.words('english'))\nlen(sw)",
"_____no_output_____"
],
[
"'the' in sw",
"_____no_output_____"
],
[
"sw",
"_____no_output_____"
]
]
]
| [
"markdown",
"code"
]
| [
[
"markdown"
],
[
"code",
"code",
"code"
]
]
|
cb5ebc7ad519cdd63a4cb64d47f8e998ae7c5ef3 | 127,596 | ipynb | Jupyter Notebook | dayoung_trial1/16_retry.ipynb | dayoungMM/Regression_project | f136bd0093a4129083fe5d6d1824fd2af7209d15 | [
"MIT"
]
| null | null | null | dayoung_trial1/16_retry.ipynb | dayoungMM/Regression_project | f136bd0093a4129083fe5d6d1824fd2af7209d15 | [
"MIT"
]
| null | null | null | dayoung_trial1/16_retry.ipynb | dayoungMM/Regression_project | f136bd0093a4129083fe5d6d1824fd2af7209d15 | [
"MIT"
]
| 2 | 2019-11-27T10:44:33.000Z | 2019-12-19T06:42:45.000Z | 65.033639 | 139 | 0.398422 | [
[
[
"df = pd.read_csv('../raw_data/df_grouped_rate.csv') #폴더 위치는 상이할 수 있음",
"_____no_output_____"
],
[
"y=df.iloc[:,3:4]\ny",
"_____no_output_____"
],
[
"X= df.iloc[:,1:].drop(['sales_total'],axis=1)\nX",
"_____no_output_____"
],
[
"# 더미변수화\nX_dum1 = pd.get_dummies(X.iloc[:,0]) #district는 범주형으로 인식 안해서 따로 실시\nX_dum1.tail()",
"_____no_output_____"
],
[
"X_dum2 = pd.get_dummies(X.iloc[:,1:])\nX = pd.concat([X_dum1, X_dum2],axis=1)\nX.columns[1010:1050]",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import RobustScaler\n# Train-test split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) # y 값이 정의되지 않아 df.sales_total 으로 대체하겠습니다.\n# 로버스트 스케일링\nrb = RobustScaler()\nXs_train = rb.fit_transform(X_train)\nXs_test = rb.transform(X_test)",
"_____no_output_____"
],
[
"# 회귀분석\nfrom sklearn.linear_model import LinearRegression\nregressor = LinearRegression()\nmodel = regressor.fit(Xs_train, y_train)",
"_____no_output_____"
],
[
"# 정확도 결과값\nprint(model.score(Xs_train, y_train))\nprint(model.score(Xs_test, y_test))",
"0.44122126381363413\n0.4295974441417073\n"
],
[
"# 오차 결과값\nfrom sklearn import metrics\ny_pred = model.predict(Xs_test)\nprint('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_pred)) \nprint('Mean Squared Error:', metrics.mean_squared_error(y_test, y_pred)) \nprint('Root Mean Squared Error:', np.sqrt(metrics.mean_squared_error(y_test, y_pred)))",
"Mean Absolute Error: 637271522.9511323\nMean Squared Error: 1.5393853539031647e+18\nRoot Mean Squared Error: 1240719691.9139974\n"
],
[
"import statsmodels.api as sm\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import RobustScaler\n# Train-test split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) # y 값이 정의되지 않아 df.sales_total 으로 대체하겠습니다.\n# 로버스트 스케일링\nrb = RobustScaler()\nXs_train = rb.fit_transform(X_train)\nXs_test = rb.transform(X_test)\n\nmodel = sm.OLS(y_train, Xs_train)\nresult = model.fit()\nprint(result.summary())",
" OLS Regression Results \n==============================================================================\nDep. Variable: sales_total R-squared: 0.443\nModel: OLS Adj. R-squared: 0.436\nMethod: Least Squares F-statistic: 66.62\nDate: Sat, 15 Feb 2020 Prob (F-statistic): 0.00\nTime: 16:13:53 Log-Likelihood: -2.0276e+06\nNo. Observations: 90612 AIC: 4.057e+06\nDf Residuals: 89544 BIC: 4.067e+06\nDf Model: 1067 \nCovariance Type: nonrobust \n==============================================================================\n coef std err t P>|t| [0.025 0.975]\n------------------------------------------------------------------------------\nx1 -6.125e+06 1.38e+08 -0.045 0.964 -2.76e+08 2.63e+08\nx2 1.059e+08 3.53e+08 0.300 0.764 -5.86e+08 7.98e+08\nx3 6.749e+08 1.31e+08 5.132 0.000 4.17e+08 9.33e+08\nx4 2.027e+08 1.44e+08 1.410 0.159 -7.92e+07 4.85e+08\nx5 -4.528e+08 1.69e+08 -2.674 0.007 -7.85e+08 -1.21e+08\nx6 2.669e+08 1.67e+08 1.595 0.111 -6.1e+07 5.95e+08\nx7 7.003e+08 1.84e+08 3.814 0.000 3.4e+08 1.06e+09\nx8 5.509e+08 2.21e+08 2.490 0.013 1.17e+08 9.84e+08\nx9 3.344e+08 1.95e+08 1.718 0.086 -4.71e+07 7.16e+08\nx10 -3.597e+08 1.28e+08 -2.815 0.005 -6.1e+08 -1.09e+08\nx11 4.501e+08 1.28e+08 3.513 0.000 1.99e+08 7.01e+08\nx12 -8.244e+07 1.61e+08 -0.513 0.608 -3.97e+08 2.33e+08\nx13 2.498e+08 1.59e+08 1.571 0.116 -6.19e+07 5.61e+08\nx14 1.38e+08 2.01e+08 0.687 0.492 -2.56e+08 5.32e+08\nx15 5.719e+08 1.29e+08 4.450 0.000 3.2e+08 8.24e+08\nx16 2.927e+08 1.2e+08 2.439 0.015 5.75e+07 5.28e+08\nx17 -1.886e+08 3.85e+08 -0.490 0.624 -9.43e+08 5.66e+08\nx18 3.714e+08 3.53e+08 1.051 0.293 -3.21e+08 1.06e+09\nx19 7.009e+07 1.28e+08 0.550 0.583 -1.8e+08 3.2e+08\nx20 2.357e+08 1.44e+08 1.637 0.102 -4.65e+07 5.18e+08\nx21 -3.943e+08 1.54e+08 -2.557 0.011 -6.97e+08 -9.21e+07\nx22 2.415e+08 1.32e+08 1.831 0.067 -1.7e+07 5e+08\nx23 -1.549e+08 1.98e+08 -0.784 0.433 -5.42e+08 2.33e+08\nx24 -4.854e+07 2.03e+08 -0.239 0.811 -4.46e+08 3.49e+08\nx25 -6.507e+08 2.45e+08 -2.661 0.008 -1.13e+09 -1.71e+08\nx26 -3.8e+08 1.98e+08 -1.917 0.055 -7.69e+08 8.53e+06\nx27 -4.427e+08 1.91e+08 -2.322 0.020 -8.16e+08 -6.9e+07\nx28 -2.102e+08 1.19e+08 -1.770 0.077 -4.43e+08 2.26e+07\nx29 5.522e+08 3.02e+08 1.826 0.068 -4.04e+07 1.14e+09\nx30 -4.263e+07 1.41e+08 -0.302 0.763 -3.19e+08 2.34e+08\nx31 -4.862e+08 1.36e+08 -3.575 0.000 -7.53e+08 -2.2e+08\nx32 -3.344e+08 1.15e+08 -2.919 0.004 -5.59e+08 -1.1e+08\nx33 -2.357e+08 1.37e+08 -1.719 0.086 -5.05e+08 3.3e+07\nx34 -1.602e+08 1.16e+08 -1.383 0.167 -3.87e+08 6.69e+07\nx35 -4.187e+07 1.46e+08 -0.286 0.775 -3.29e+08 2.45e+08\nx36 4.987e+07 1.6e+08 0.311 0.756 -2.64e+08 3.64e+08\nx37 -5.307e+08 2.41e+08 -2.205 0.027 -1e+09 -5.9e+07\nx38 3.749e+08 3e+08 1.248 0.212 -2.14e+08 9.64e+08\nx39 1.207e+09 1.31e+08 9.228 0.000 9.51e+08 1.46e+09\nx40 3.879e+07 1.7e+08 0.228 0.820 -2.95e+08 3.72e+08\nx41 -7.827e+07 1.21e+08 -0.644 0.519 -3.16e+08 1.6e+08\nx42 -6.707e+08 1.64e+08 -4.087 0.000 -9.92e+08 -3.49e+08\nx43 -1.24e+09 1.77e+08 -6.993 0.000 -1.59e+09 -8.93e+08\nx44 -6.273e+08 1.81e+08 -3.466 0.001 -9.82e+08 -2.73e+08\nx45 -2.378e+08 1.36e+08 -1.746 0.081 -5.05e+08 2.91e+07\nx46 2.405e+08 1.25e+08 1.926 0.054 -4.18e+06 4.85e+08\nx47 -6.356e+08 1.54e+08 -4.122 0.000 -9.38e+08 -3.33e+08\nx48 -6.158e+08 1.34e+08 -4.609 0.000 -8.78e+08 -3.54e+08\nx49 -9.393e+08 2.54e+08 -3.700 0.000 -1.44e+09 -4.42e+08\nx50 -7.806e+08 1.5e+08 -5.198 0.000 -1.07e+09 -4.86e+08\nx51 2.992e+08 1.68e+08 1.785 0.074 -2.93e+07 6.28e+08\nx52 4.663e+08 1.52e+08 3.072 0.002 1.69e+08 7.64e+08\nx53 -1.225e+08 1.43e+08 -0.855 0.392 -4.03e+08 1.58e+08\nx54 3.66e+08 1.39e+08 2.635 0.008 9.37e+07 6.38e+08\nx55 4.04e+08 1.39e+08 2.906 0.004 1.32e+08 6.76e+08\nx56 -2.672e+08 1.25e+08 -2.142 0.032 -5.12e+08 -2.27e+07\nx57 -7.668e+08 1.7e+08 -4.518 0.000 -1.1e+09 -4.34e+08\nx58 -1.033e+09 2.22e+08 -4.661 0.000 -1.47e+09 -5.98e+08\nx59 -3.038e+08 1.54e+08 -1.977 0.048 -6.05e+08 -2.61e+06\nx60 4.635e+08 1.29e+08 3.605 0.000 2.12e+08 7.15e+08\nx61 -6.527e+08 1.49e+08 -4.389 0.000 -9.44e+08 -3.61e+08\nx62 6.224e+08 1.83e+08 3.409 0.001 2.65e+08 9.8e+08\nx63 -6.287e+08 1.51e+08 -4.157 0.000 -9.25e+08 -3.32e+08\nx64 -5.241e+08 1.38e+08 -3.806 0.000 -7.94e+08 -2.54e+08\nx65 -7.146e+08 2.05e+08 -3.481 0.001 -1.12e+09 -3.12e+08\nx66 -4.146e+08 1.31e+08 -3.162 0.002 -6.72e+08 -1.58e+08\nx67 -4.28e+08 1.32e+08 -3.242 0.001 -6.87e+08 -1.69e+08\nx68 -5.804e+08 1.5e+08 -3.857 0.000 -8.75e+08 -2.85e+08\nx69 1.887e+09 1.44e+08 13.142 0.000 1.61e+09 2.17e+09\nx70 -3.45e+07 1.47e+08 -0.235 0.815 -3.23e+08 2.54e+08\nx71 -3.886e+08 1.23e+08 -3.149 0.002 -6.3e+08 -1.47e+08\nx72 5.594e+08 1.29e+08 4.333 0.000 3.06e+08 8.13e+08\nx73 2.003e+08 1.61e+08 1.244 0.213 -1.15e+08 5.16e+08\nx74 9.712e+07 1.4e+08 0.693 0.488 -1.77e+08 3.72e+08\nx75 6.837e+08 2.02e+08 3.385 0.001 2.88e+08 1.08e+09\nx76 -3.98e+08 1.27e+08 -3.124 0.002 -6.48e+08 -1.48e+08\nx77 -9.833e+08 1.63e+08 -6.048 0.000 -1.3e+09 -6.65e+08\nx78 -3.539e+08 1.18e+08 -2.996 0.003 -5.85e+08 -1.22e+08\nx79 -1.444e+09 1.62e+08 -8.930 0.000 -1.76e+09 -1.13e+09\nx80 -8.999e+08 1.51e+08 -5.976 0.000 -1.2e+09 -6.05e+08\nx81 -5.298e+08 1.55e+08 -3.408 0.001 -8.34e+08 -2.25e+08\nx82 4.81e+08 3.54e+08 1.358 0.174 -2.13e+08 1.17e+09\nx83 -3.625e+08 3.03e+08 -1.197 0.231 -9.56e+08 2.31e+08\nx84 -3.888e+07 1.2e+08 -0.323 0.747 -2.75e+08 1.97e+08\nx85 -3.972e+07 1.24e+08 -0.321 0.748 -2.82e+08 2.03e+08\nx86 1.848e+08 1.33e+08 1.394 0.163 -7.5e+07 4.45e+08\nx87 -1.331e+09 1.65e+08 -8.064 0.000 -1.65e+09 -1.01e+09\nx88 -7.583e+08 2.11e+08 -3.589 0.000 -1.17e+09 -3.44e+08\nx89 -1.564e+08 1.4e+08 -1.113 0.266 -4.32e+08 1.19e+08\nx90 -2.893e+08 1.13e+08 -2.571 0.010 -5.1e+08 -6.88e+07\nx91 2.033e+08 3.4e+08 0.597 0.550 -4.64e+08 8.71e+08\nx92 8.197e+07 1.45e+08 0.564 0.572 -2.03e+08 3.67e+08\nx93 7.069e+08 1.35e+08 5.236 0.000 4.42e+08 9.72e+08\nx94 -2.879e+08 1.82e+08 -1.582 0.114 -6.44e+08 6.87e+07\nx95 -7.717e+07 2.93e+08 -0.264 0.792 -6.51e+08 4.96e+08\nx96 -6.546e+08 1.99e+08 -3.296 0.001 -1.04e+09 -2.65e+08\nx97 -4.595e+08 1.2e+08 -3.833 0.000 -6.94e+08 -2.25e+08\nx98 4.71e+08 1.27e+08 3.719 0.000 2.23e+08 7.19e+08\nx99 2.245e+08 1.47e+08 1.527 0.127 -6.36e+07 5.13e+08\nx100 -2.167e+08 1.52e+08 -1.428 0.153 -5.14e+08 8.06e+07\nx101 1.165e+08 1.43e+08 0.814 0.416 -1.64e+08 3.97e+08\nx102 -3.223e+07 2.06e+08 -0.156 0.876 -4.36e+08 3.72e+08\nx103 4.413e+08 1.06e+08 4.162 0.000 2.33e+08 6.49e+08\nx104 -2.581e+08 1.47e+08 -1.761 0.078 -5.45e+08 2.92e+07\nx105 -2.893e+08 1.15e+08 -2.516 0.012 -5.15e+08 -6.4e+07\nx106 -5.136e+08 1.32e+08 -3.886 0.000 -7.73e+08 -2.55e+08\nx107 2.754e+08 1.66e+08 1.658 0.097 -5.01e+07 6.01e+08\nx108 -1.122e+07 1.39e+08 -0.081 0.936 -2.84e+08 2.62e+08\nx109 1.083e+07 1.24e+08 0.088 0.930 -2.31e+08 2.53e+08\nx110 2.186e+08 1.44e+08 1.513 0.130 -6.46e+07 5.02e+08\nx111 -1.877e+08 1.19e+08 -1.577 0.115 -4.21e+08 4.56e+07\nx112 -2.899e+08 1.63e+08 -1.777 0.076 -6.1e+08 2.98e+07\nx113 6.625e+08 1.46e+08 4.545 0.000 3.77e+08 9.48e+08\nx114 -2.008e+08 1.47e+08 -1.362 0.173 -4.9e+08 8.81e+07\nx115 -2.823e+07 1.37e+08 -0.206 0.837 -2.97e+08 2.41e+08\nx116 -3.551e+08 1.33e+08 -2.663 0.008 -6.16e+08 -9.37e+07\nx117 -2e+08 1.15e+08 -1.741 0.082 -4.25e+08 2.51e+07\nx118 -1.815e+08 1.29e+08 -1.412 0.158 -4.33e+08 7.05e+07\nx119 2.83e+07 1.2e+08 0.237 0.813 -2.06e+08 2.63e+08\nx120 7.195e+08 1.14e+08 6.302 0.000 4.96e+08 9.43e+08\nx121 1.385e+08 1.57e+08 0.880 0.379 -1.7e+08 4.47e+08\nx122 -3.234e+08 1.1e+08 -2.950 0.003 -5.38e+08 -1.09e+08\nx123 -4.738e+07 1.4e+08 -0.338 0.735 -3.22e+08 2.27e+08\nx124 -1.035e+09 2.65e+08 -3.905 0.000 -1.55e+09 -5.16e+08\nx125 -1.206e+09 2.08e+08 -5.803 0.000 -1.61e+09 -7.99e+08\nx126 4.965e+08 1.28e+08 3.887 0.000 2.46e+08 7.47e+08\nx127 6.311e+08 1.47e+08 4.299 0.000 3.43e+08 9.19e+08\nx128 1.007e+09 1.21e+08 8.324 0.000 7.7e+08 1.24e+09\nx129 2.405e+08 1.53e+08 1.567 0.117 -6.03e+07 5.41e+08\nx130 -3.281e+07 1.31e+08 -0.250 0.803 -2.9e+08 2.24e+08\nx131 -6.129e+08 1.45e+08 -4.239 0.000 -8.96e+08 -3.3e+08\nx132 5.285e+08 1.2e+08 4.386 0.000 2.92e+08 7.65e+08\nx133 6.717e+08 1.13e+08 5.929 0.000 4.5e+08 8.94e+08\nx134 2.958e+07 1.78e+08 0.166 0.868 -3.2e+08 3.79e+08\nx135 1.633e+08 1.22e+08 1.336 0.181 -7.62e+07 4.03e+08\nx136 3.236e+08 1.16e+08 2.782 0.005 9.57e+07 5.52e+08\nx137 5.514e+08 1.36e+08 4.067 0.000 2.86e+08 8.17e+08\nx138 7.28e+08 1.23e+08 5.928 0.000 4.87e+08 9.69e+08\nx139 -8.243e+08 1.24e+08 -6.654 0.000 -1.07e+09 -5.81e+08\nx140 -7.316e+08 1.42e+08 -5.169 0.000 -1.01e+09 -4.54e+08\nx141 2.55e+08 1.23e+08 2.066 0.039 1.31e+07 4.97e+08\nx142 1.997e+08 1.78e+08 1.121 0.262 -1.5e+08 5.49e+08\nx143 -3.349e+08 1.34e+08 -2.500 0.012 -5.98e+08 -7.23e+07\nx144 -1.527e+08 1.35e+08 -1.127 0.260 -4.18e+08 1.13e+08\nx145 -8.759e+07 1.29e+08 -0.681 0.496 -3.4e+08 1.65e+08\nx146 -2.925e+08 1.44e+08 -2.035 0.042 -5.74e+08 -1.08e+07\nx147 -1.904e+08 1.08e+08 -1.767 0.077 -4.02e+08 2.08e+07\nx148 -4.219e+08 1.34e+08 -3.157 0.002 -6.84e+08 -1.6e+08\nx149 -9.777e+07 1.47e+08 -0.665 0.506 -3.86e+08 1.9e+08\nx150 -3.135e+07 1.43e+08 -0.219 0.827 -3.12e+08 2.5e+08\nx151 5.463e+08 1.74e+08 3.147 0.002 2.06e+08 8.87e+08\nx152 1.584e+08 1.2e+08 1.316 0.188 -7.75e+07 3.94e+08\nx153 -6.978e+07 1.14e+08 -0.613 0.540 -2.93e+08 1.53e+08\nx154 -9.705e+08 1.65e+08 -5.888 0.000 -1.29e+09 -6.47e+08\nx155 4.202e+08 1.21e+08 3.465 0.001 1.82e+08 6.58e+08\nx156 2.06e+08 1.79e+08 1.149 0.251 -1.45e+08 5.57e+08\nx157 -8.039e+06 1.26e+08 -0.064 0.949 -2.56e+08 2.4e+08\nx158 6.488e+08 1.36e+08 4.774 0.000 3.82e+08 9.15e+08\nx159 3.865e+08 1.28e+08 3.015 0.003 1.35e+08 6.38e+08\nx160 9.994e+08 1.09e+08 9.158 0.000 7.85e+08 1.21e+09\nx161 1.755e+08 1.18e+08 1.482 0.138 -5.66e+07 4.08e+08\nx162 2.082e+08 1.51e+08 1.382 0.167 -8.7e+07 5.03e+08\nx163 -7.817e+08 1.4e+08 -5.577 0.000 -1.06e+09 -5.07e+08\nx164 5.324e+07 1.14e+08 0.467 0.641 -1.7e+08 2.77e+08\nx165 7.472e+08 1.21e+08 6.153 0.000 5.09e+08 9.85e+08\nx166 6.209e+08 1.13e+08 5.481 0.000 3.99e+08 8.43e+08\nx167 5.717e+08 1.55e+08 3.677 0.000 2.67e+08 8.76e+08\nx168 -1.231e+08 3.41e+08 -0.361 0.718 -7.91e+08 5.45e+08\nx169 4.975e+08 1.8e+08 2.766 0.006 1.45e+08 8.5e+08\nx170 -1.451e+08 1.65e+08 -0.879 0.379 -4.69e+08 1.78e+08\nx171 2.066e+08 1.39e+08 1.486 0.137 -6.6e+07 4.79e+08\nx172 9.849e+07 1.29e+08 0.761 0.446 -1.55e+08 3.52e+08\nx173 -7.777e+07 2.78e+08 -0.280 0.779 -6.22e+08 4.66e+08\nx174 -7.261e+07 1.38e+08 -0.527 0.598 -3.43e+08 1.97e+08\nx175 3.398e+08 1.34e+08 2.533 0.011 7.69e+07 6.03e+08\nx176 4.274e+08 1.13e+08 3.774 0.000 2.05e+08 6.49e+08\nx177 1.525e+08 1.33e+08 1.147 0.251 -1.08e+08 4.13e+08\nx178 2.556e+08 1.73e+08 1.476 0.140 -8.38e+07 5.95e+08\nx179 8.779e+08 1.22e+08 7.210 0.000 6.39e+08 1.12e+09\nx180 8.946e+07 1.35e+08 0.665 0.506 -1.74e+08 3.53e+08\nx181 -1.576e+08 2.05e+08 -0.770 0.441 -5.59e+08 2.44e+08\nx182 -3.051e+08 1.67e+08 -1.828 0.068 -6.32e+08 2.2e+07\nx183 1.071e+08 1.14e+08 0.944 0.345 -1.15e+08 3.3e+08\nx184 6.368e+07 1.16e+08 0.547 0.584 -1.64e+08 2.92e+08\nx185 3.719e+08 2.92e+08 1.273 0.203 -2.01e+08 9.45e+08\nx186 -1.921e+08 2.85e+08 -0.675 0.500 -7.5e+08 3.66e+08\nx187 -2.093e+06 1.4e+08 -0.015 0.988 -2.77e+08 2.73e+08\nx188 1.138e+08 1.27e+08 0.894 0.371 -1.36e+08 3.63e+08\nx189 -4.038e+08 1.2e+08 -3.378 0.001 -6.38e+08 -1.69e+08\nx190 1.255e+08 2.17e+08 0.578 0.563 -3e+08 5.51e+08\nx191 -9.305e+08 2.02e+08 -4.614 0.000 -1.33e+09 -5.35e+08\nx192 -2.207e+07 1.13e+08 -0.195 0.845 -2.44e+08 2e+08\nx193 -1.075e+08 2.02e+08 -0.533 0.594 -5.03e+08 2.88e+08\nx194 1.152e+08 1.38e+08 0.832 0.405 -1.56e+08 3.86e+08\nx195 2.321e+08 1.22e+08 1.905 0.057 -6.73e+06 4.71e+08\nx196 7.429e+08 1.63e+08 4.553 0.000 4.23e+08 1.06e+09\nx197 2.773e+08 1.14e+08 2.422 0.015 5.29e+07 5.02e+08\nx198 1.512e+08 1.55e+08 0.979 0.328 -1.52e+08 4.54e+08\nx199 1.554e+07 1.37e+08 0.114 0.910 -2.52e+08 2.84e+08\nx200 6.202e+07 1.13e+08 0.550 0.583 -1.59e+08 2.83e+08\nx201 2.421e+08 1.61e+08 1.504 0.133 -7.35e+07 5.58e+08\nx202 -2.778e+08 1.49e+08 -1.865 0.062 -5.7e+08 1.41e+07\nx203 9.06e+07 1.24e+08 0.732 0.464 -1.52e+08 3.33e+08\nx204 -9.359e+06 1.37e+08 -0.068 0.945 -2.78e+08 2.59e+08\nx205 -3.449e+08 2.22e+08 -1.553 0.120 -7.8e+08 9.02e+07\nx206 -1.865e+08 1.39e+08 -1.340 0.180 -4.59e+08 8.63e+07\nx207 1.65e+08 1.54e+08 1.073 0.283 -1.36e+08 4.66e+08\nx208 4.576e+07 3.53e+08 0.130 0.897 -6.46e+08 7.37e+08\nx209 -5.267e+07 1.52e+08 -0.347 0.729 -3.5e+08 2.45e+08\nx210 6.284e+08 4.5e+08 1.395 0.163 -2.54e+08 1.51e+09\nx211 -6.58e+08 3e+08 -2.190 0.029 -1.25e+09 -6.91e+07\nx212 8.935e+07 1.85e+08 0.483 0.629 -2.73e+08 4.52e+08\nx213 3.297e+08 1.29e+08 2.556 0.011 7.69e+07 5.83e+08\nx214 2.138e+06 1.31e+08 0.016 0.987 -2.54e+08 2.58e+08\nx215 2.957e+08 1.4e+08 2.104 0.035 2.03e+07 5.71e+08\nx216 5.223e+08 1.25e+08 4.170 0.000 2.77e+08 7.68e+08\nx217 -2.987e+08 1.55e+08 -1.930 0.054 -6.02e+08 4.68e+06\nx218 -5.739e+08 2.02e+08 -2.836 0.005 -9.7e+08 -1.77e+08\nx219 1.736e+08 1.09e+08 1.596 0.111 -3.96e+07 3.87e+08\nx220 4.215e+07 1.21e+08 0.348 0.728 -1.95e+08 2.79e+08\nx221 4.446e+08 1.19e+08 3.731 0.000 2.11e+08 6.78e+08\nx222 1.183e+08 1.57e+08 0.753 0.451 -1.9e+08 4.26e+08\nx223 5.826e+08 1.51e+08 3.852 0.000 2.86e+08 8.79e+08\nx224 -1.273e+08 1.55e+08 -0.822 0.411 -4.31e+08 1.76e+08\nx225 3.962e+08 1.07e+08 3.715 0.000 1.87e+08 6.05e+08\nx226 1.056e+08 1.36e+08 0.774 0.439 -1.62e+08 3.73e+08\nx227 3.33e+08 1.66e+08 2.002 0.045 7.05e+06 6.59e+08\nx228 2.442e+08 1.13e+08 2.157 0.031 2.23e+07 4.66e+08\nx229 1.204e+08 1.13e+08 1.062 0.288 -1.02e+08 3.43e+08\nx230 3.799e+08 1.16e+08 3.263 0.001 1.52e+08 6.08e+08\nx231 -7.14e+07 1.27e+08 -0.563 0.573 -3.2e+08 1.77e+08\nx232 2.549e+08 1.1e+08 2.316 0.021 3.92e+07 4.71e+08\nx233 3.011e+08 1.68e+08 1.793 0.073 -2.8e+07 6.3e+08\nx234 3.722e+08 1.19e+08 3.115 0.002 1.38e+08 6.06e+08\nx235 -2.15e+08 1.59e+08 -1.352 0.176 -5.27e+08 9.67e+07\nx236 7.928e+08 1.09e+08 7.272 0.000 5.79e+08 1.01e+09\nx237 -3e+08 1.35e+08 -2.226 0.026 -5.64e+08 -3.58e+07\nx238 5.259e+08 1.16e+08 4.542 0.000 2.99e+08 7.53e+08\nx239 2.544e+07 1.49e+08 0.171 0.864 -2.66e+08 3.17e+08\nx240 4.038e+07 1.54e+08 0.262 0.794 -2.62e+08 3.43e+08\nx241 -2.23e+08 1.4e+08 -1.596 0.111 -4.97e+08 5.09e+07\nx242 6.781e+08 1.31e+08 5.159 0.000 4.2e+08 9.36e+08\nx243 3.394e+08 1.21e+08 2.807 0.005 1.02e+08 5.76e+08\nx244 3.521e+08 1.2e+08 2.925 0.003 1.16e+08 5.88e+08\nx245 3.114e+07 1.53e+08 0.203 0.839 -2.69e+08 3.32e+08\nx246 1.553e+08 1.18e+08 1.318 0.187 -7.56e+07 3.86e+08\nx247 -2.907e+08 1.48e+08 -1.968 0.049 -5.8e+08 -1.13e+06\nx248 2.832e+08 1.3e+08 2.184 0.029 2.9e+07 5.37e+08\nx249 3.299e+07 2.1e+08 0.157 0.875 -3.8e+08 4.45e+08\nx250 2.496e+08 1.51e+08 1.652 0.099 -4.65e+07 5.46e+08\nx251 3.431e+08 1.06e+08 3.247 0.001 1.36e+08 5.5e+08\nx252 3.254e+08 1.53e+08 2.126 0.034 2.54e+07 6.25e+08\nx253 3.926e+08 1.14e+08 3.449 0.001 1.69e+08 6.16e+08\nx254 -2.753e+07 1.41e+08 -0.195 0.845 -3.04e+08 2.49e+08\nx255 6.496e+08 1.38e+08 4.711 0.000 3.79e+08 9.2e+08\nx256 2.575e+08 1.44e+08 1.784 0.074 -2.54e+07 5.4e+08\nx257 1.48e+08 1.17e+08 1.267 0.205 -8.1e+07 3.77e+08\nx258 3.287e+08 1.4e+08 2.342 0.019 5.37e+07 6.04e+08\nx259 3.191e+08 1.21e+08 2.628 0.009 8.11e+07 5.57e+08\nx260 -5.29e+08 1.58e+08 -3.343 0.001 -8.39e+08 -2.19e+08\nx261 9.332e+07 2.87e+08 0.325 0.745 -4.69e+08 6.56e+08\nx262 3.513e+08 1.21e+08 2.909 0.004 1.15e+08 5.88e+08\nx263 -6.026e+07 1.22e+08 -0.495 0.621 -2.99e+08 1.78e+08\nx264 2.719e+08 1.51e+08 1.802 0.072 -2.38e+07 5.68e+08\nx265 -1.902e+08 1.49e+08 -1.278 0.201 -4.82e+08 1.01e+08\nx266 -9.227e+07 1.9e+08 -0.487 0.626 -4.64e+08 2.79e+08\nx267 -4.609e+07 1.47e+08 -0.315 0.753 -3.33e+08 2.41e+08\nx268 -1.93e+08 1.39e+08 -1.388 0.165 -4.66e+08 7.96e+07\nx269 2.552e+08 1.22e+08 2.097 0.036 1.67e+07 4.94e+08\nx270 1.362e+08 2.72e+08 0.501 0.616 -3.96e+08 6.69e+08\nx271 4.846e+08 3.3e+08 1.471 0.141 -1.61e+08 1.13e+09\nx272 7.683e+07 1.22e+08 0.632 0.527 -1.61e+08 3.15e+08\nx273 -2.903e+07 1.31e+08 -0.221 0.825 -2.86e+08 2.28e+08\nx274 2.827e+08 5.69e+08 0.497 0.619 -8.33e+08 1.4e+09\nx275 -2.651e+08 1.21e+08 -2.196 0.028 -5.02e+08 -2.84e+07\nx276 1.956e+07 1.45e+08 0.135 0.893 -2.65e+08 3.04e+08\nx277 -2.208e+08 1.09e+08 -2.028 0.043 -4.34e+08 -7.43e+06\nx278 -3.264e+08 2.46e+08 -1.328 0.184 -8.08e+08 1.55e+08\nx279 -6.278e+08 1.79e+08 -3.509 0.000 -9.78e+08 -2.77e+08\nx280 -4.101e+08 1.33e+08 -3.078 0.002 -6.71e+08 -1.49e+08\nx281 4.025e+08 1.33e+08 3.022 0.003 1.41e+08 6.64e+08\nx282 1.634e+08 2.06e+08 0.794 0.427 -2.4e+08 5.67e+08\nx283 -3.713e+08 1.22e+08 -3.050 0.002 -6.1e+08 -1.33e+08\nx284 3.417e+08 1.87e+08 1.829 0.067 -2.45e+07 7.08e+08\nx285 -9.261e+07 1.26e+08 -0.733 0.464 -3.4e+08 1.55e+08\nx286 -4.146e+07 1.76e+08 -0.236 0.813 -3.85e+08 3.03e+08\nx287 1.661e+08 1.01e+08 1.641 0.101 -3.22e+07 3.64e+08\nx288 -5.548e+08 1.55e+08 -3.584 0.000 -8.58e+08 -2.51e+08\nx289 -3.87e+08 1.26e+08 -3.071 0.002 -6.34e+08 -1.4e+08\nx290 8.214e+08 1.45e+08 5.653 0.000 5.37e+08 1.11e+09\nx291 8.588e+08 1.33e+08 6.446 0.000 5.98e+08 1.12e+09\nx292 2.136e+08 1.4e+08 1.524 0.127 -6.1e+07 4.88e+08\nx293 -1.111e+08 1.4e+08 -0.794 0.427 -3.85e+08 1.63e+08\nx294 -9.839e+07 1.17e+08 -0.839 0.401 -3.28e+08 1.31e+08\nx295 2.262e+07 1.63e+08 0.139 0.890 -2.97e+08 3.42e+08\nx296 -2.01e+08 2.84e+08 -0.707 0.480 -7.58e+08 3.56e+08\nx297 -1.367e+08 1.47e+08 -0.932 0.351 -4.24e+08 1.51e+08\nx298 6.428e+08 1.44e+08 4.458 0.000 3.6e+08 9.25e+08\nx299 -1.019e+08 1.46e+08 -0.696 0.486 -3.89e+08 1.85e+08\nx300 -1.985e+08 1.18e+08 -1.684 0.092 -4.29e+08 3.25e+07\nx301 -5.289e+07 1.2e+08 -0.442 0.658 -2.87e+08 1.82e+08\nx302 -3.505e+08 1.46e+08 -2.406 0.016 -6.36e+08 -6.5e+07\nx303 3.356e+08 1.48e+08 2.263 0.024 4.49e+07 6.26e+08\nx304 8.858e+06 1.23e+08 0.072 0.943 -2.33e+08 2.51e+08\nx305 6.647e+08 1.44e+08 4.628 0.000 3.83e+08 9.46e+08\nx306 -5.979e+08 2.22e+08 -2.699 0.007 -1.03e+09 -1.64e+08\nx307 4.469e+08 1.27e+08 3.517 0.000 1.98e+08 6.96e+08\nx308 1.772e+08 1.14e+08 1.552 0.121 -4.65e+07 4.01e+08\nx309 -1.647e+08 1.34e+08 -1.227 0.220 -4.28e+08 9.83e+07\nx310 -1.885e+08 1.49e+08 -1.263 0.207 -4.81e+08 1.04e+08\nx311 -2.521e+08 1.54e+08 -1.640 0.101 -5.53e+08 4.92e+07\nx312 -8.933e+07 1.59e+08 -0.561 0.575 -4.01e+08 2.23e+08\nx313 1.162e+08 1.41e+08 0.822 0.411 -1.61e+08 3.94e+08\nx314 1.91e+08 1.25e+08 1.529 0.126 -5.38e+07 4.36e+08\nx315 4.931e+08 3.3e+08 1.493 0.135 -1.54e+08 1.14e+09\nx316 -2.191e+08 3.41e+08 -0.643 0.520 -8.87e+08 4.49e+08\nx317 3.937e+08 1.56e+08 2.516 0.012 8.7e+07 7e+08\nx318 6.066e+08 1.45e+08 4.174 0.000 3.22e+08 8.91e+08\nx319 -2.313e+08 2.19e+08 -1.059 0.290 -6.6e+08 1.97e+08\nx320 2.97e+08 1.84e+08 1.613 0.107 -6.4e+07 6.58e+08\nx321 6.198e+08 1.2e+08 5.164 0.000 3.85e+08 8.55e+08\nx322 4.791e+08 1.21e+08 3.944 0.000 2.41e+08 7.17e+08\nx323 3.014e+08 1.4e+08 2.146 0.032 2.61e+07 5.77e+08\nx324 7.128e+08 1.72e+08 4.145 0.000 3.76e+08 1.05e+09\nx325 1.623e+08 2.05e+08 0.791 0.429 -2.4e+08 5.65e+08\nx326 4.959e+08 1.33e+08 3.720 0.000 2.35e+08 7.57e+08\nx327 -7.636e+08 1.82e+08 -4.202 0.000 -1.12e+09 -4.07e+08\nx328 -3.448e+08 1.59e+08 -2.171 0.030 -6.56e+08 -3.35e+07\nx329 -8.246e+07 3.4e+08 -0.243 0.808 -7.49e+08 5.84e+08\nx330 5.856e+07 1.27e+08 0.460 0.645 -1.91e+08 3.08e+08\nx331 -7.684e+07 2.66e+08 -0.288 0.773 -5.99e+08 4.45e+08\nx332 6.958e+07 1.55e+08 0.449 0.654 -2.34e+08 3.74e+08\nx333 3.695e+08 1.63e+08 2.263 0.024 4.95e+07 6.89e+08\nx334 -2.998e+07 1.49e+08 -0.202 0.840 -3.21e+08 2.61e+08\nx335 1.584e+08 1.25e+08 1.265 0.206 -8.71e+07 4.04e+08\nx336 5.059e+08 1.15e+08 4.390 0.000 2.8e+08 7.32e+08\nx337 4.9e+07 1.42e+08 0.346 0.729 -2.29e+08 3.27e+08\nx338 4.816e+08 1.5e+08 3.216 0.001 1.88e+08 7.75e+08\nx339 -1.213e+08 2.12e+08 -0.572 0.568 -5.37e+08 2.95e+08\nx340 1.635e+08 1.43e+08 1.142 0.254 -1.17e+08 4.44e+08\nx341 6.542e+08 1.36e+08 4.800 0.000 3.87e+08 9.21e+08\nx342 1.872e+08 1.69e+08 1.110 0.267 -1.43e+08 5.18e+08\nx343 3.481e+07 1.69e+08 0.206 0.837 -2.97e+08 3.66e+08\nx344 2.336e+08 1.52e+08 1.537 0.124 -6.43e+07 5.32e+08\nx345 1.007e+09 1.11e+08 9.047 0.000 7.89e+08 1.22e+09\nx346 3.2e+08 1.41e+08 2.267 0.023 4.34e+07 5.97e+08\nx347 -2.161e+08 2.78e+08 -0.777 0.437 -7.61e+08 3.29e+08\nx348 1.544e+08 1.12e+08 1.381 0.167 -6.48e+07 3.74e+08\nx349 6.325e+08 1.46e+08 4.337 0.000 3.47e+08 9.18e+08\nx350 -2.998e+08 1.34e+08 -2.230 0.026 -5.63e+08 -3.63e+07\nx351 7.087e+08 1.19e+08 5.945 0.000 4.75e+08 9.42e+08\nx352 -3.306e+08 1.34e+08 -2.474 0.013 -5.93e+08 -6.87e+07\nx353 1.468e+08 1.54e+08 0.951 0.342 -1.56e+08 4.5e+08\nx354 3.435e+08 1.56e+08 2.197 0.028 3.71e+07 6.5e+08\nx355 1.813e+08 1.36e+08 1.333 0.182 -8.52e+07 4.48e+08\nx356 1.696e+08 1.4e+08 1.210 0.226 -1.05e+08 4.44e+08\nx357 6.594e+08 1.14e+08 5.781 0.000 4.36e+08 8.83e+08\nx358 2.198e+08 1.3e+08 1.689 0.091 -3.52e+07 4.75e+08\nx359 7.383e+08 1.16e+08 6.341 0.000 5.1e+08 9.67e+08\nx360 4.34e+08 2.95e+08 1.471 0.141 -1.44e+08 1.01e+09\nx361 -5.018e+07 1.27e+08 -0.397 0.692 -2.98e+08 1.98e+08\nx362 5.618e+08 2.16e+08 2.604 0.009 1.39e+08 9.85e+08\nx363 1.575e+08 1.4e+08 1.129 0.259 -1.16e+08 4.31e+08\nx364 4.706e+08 1.25e+08 3.769 0.000 2.26e+08 7.15e+08\nx365 1.703e+08 1.15e+08 1.484 0.138 -5.47e+07 3.95e+08\nx366 -5.087e+08 4.51e+08 -1.128 0.259 -1.39e+09 3.75e+08\nx367 3.651e+08 1.27e+08 2.872 0.004 1.16e+08 6.14e+08\nx368 2.801e+08 1.59e+08 1.757 0.079 -3.24e+07 5.93e+08\nx369 7.485e+07 1.56e+08 0.481 0.631 -2.3e+08 3.8e+08\nx370 1.357e+08 1.18e+08 1.149 0.251 -9.58e+07 3.67e+08\nx371 3.114e+08 1.28e+08 2.439 0.015 6.12e+07 5.62e+08\nx372 2.913e+08 1.41e+08 2.069 0.039 1.53e+07 5.67e+08\nx373 2.762e+08 1.24e+08 2.226 0.026 3.3e+07 5.19e+08\nx374 5.308e+08 1.36e+08 3.894 0.000 2.64e+08 7.98e+08\nx375 -1.473e+08 1.23e+08 -1.201 0.230 -3.88e+08 9.31e+07\nx376 -1.783e+08 1.33e+08 -1.345 0.179 -4.38e+08 8.15e+07\nx377 -4.968e+07 1.25e+08 -0.399 0.690 -2.94e+08 1.94e+08\nx378 1.113e+09 1.12e+08 9.918 0.000 8.93e+08 1.33e+09\nx379 1.95e+08 1.58e+08 1.231 0.218 -1.15e+08 5.06e+08\nx380 -2.76e+08 1.29e+08 -2.139 0.032 -5.29e+08 -2.31e+07\nx381 -7.233e+07 3e+08 -0.241 0.809 -6.6e+08 5.15e+08\nx382 -2.46e+08 1.25e+08 -1.971 0.049 -4.91e+08 -1.33e+06\nx383 5.67e+08 1.11e+08 5.107 0.000 3.49e+08 7.85e+08\nx384 5.71e+08 1.1e+08 5.211 0.000 3.56e+08 7.86e+08\nx385 -5.187e+07 1.29e+08 -0.404 0.687 -3.04e+08 2e+08\nx386 1.978e+08 1.54e+08 1.286 0.199 -1.04e+08 4.99e+08\nx387 1.988e+08 1.32e+08 1.511 0.131 -5.9e+07 4.57e+08\nx388 -4.349e+07 1.27e+08 -0.343 0.732 -2.92e+08 2.05e+08\nx389 -2.079e+08 1.27e+08 -1.636 0.102 -4.57e+08 4.13e+07\nx390 1.307e+08 1.38e+08 0.950 0.342 -1.39e+08 4e+08\nx391 6.468e+07 1.33e+08 0.487 0.626 -1.96e+08 3.25e+08\nx392 4.076e+08 1.25e+08 3.262 0.001 1.63e+08 6.53e+08\nx393 -4.098e+08 1.38e+08 -2.960 0.003 -6.81e+08 -1.38e+08\nx394 3.72e+08 1.28e+08 2.912 0.004 1.22e+08 6.22e+08\nx395 -6.049e+08 1.43e+08 -4.239 0.000 -8.85e+08 -3.25e+08\nx396 -3.068e+07 1.6e+08 -0.191 0.848 -3.45e+08 2.84e+08\nx397 6.616e+07 1.42e+08 0.464 0.642 -2.13e+08 3.45e+08\nx398 9.388e+07 2.38e+08 0.395 0.693 -3.72e+08 5.6e+08\nx399 1.846e+08 1.25e+08 1.480 0.139 -5.99e+07 4.29e+08\nx400 7.794e+08 1.25e+08 6.237 0.000 5.35e+08 1.02e+09\nx401 4.394e+08 1.45e+08 3.029 0.002 1.55e+08 7.24e+08\nx402 7.031e+08 1.2e+08 5.868 0.000 4.68e+08 9.38e+08\nx403 -7.945e+07 1.2e+08 -0.660 0.509 -3.15e+08 1.57e+08\nx404 2.568e+08 1.39e+08 1.847 0.065 -1.57e+07 5.29e+08\nx405 4.648e+08 1.67e+08 2.782 0.005 1.37e+08 7.92e+08\nx406 1.911e+07 1.37e+08 0.139 0.889 -2.5e+08 2.88e+08\nx407 1.38e+08 1.45e+08 0.954 0.340 -1.46e+08 4.22e+08\nx408 2.021e+08 1.45e+08 1.398 0.162 -8.13e+07 4.86e+08\nx409 1.629e+09 1.38e+08 11.844 0.000 1.36e+09 1.9e+09\nx410 3.847e+08 1.18e+08 3.262 0.001 1.54e+08 6.16e+08\nx411 4.348e+08 1.14e+08 3.801 0.000 2.11e+08 6.59e+08\nx412 2.203e+08 1.5e+08 1.471 0.141 -7.32e+07 5.14e+08\nx413 1.024e+08 1.19e+08 0.864 0.388 -1.3e+08 3.35e+08\nx414 2.463e+08 1.41e+08 1.748 0.081 -2.99e+07 5.22e+08\nx415 3.781e+08 1.2e+08 3.159 0.002 1.44e+08 6.13e+08\nx416 9.819e+08 1.28e+08 7.686 0.000 7.31e+08 1.23e+09\nx417 3.625e+07 1.48e+08 0.245 0.806 -2.53e+08 3.26e+08\nx418 7.593e+08 1.15e+08 6.585 0.000 5.33e+08 9.85e+08\nx419 2.421e+08 1.32e+08 1.832 0.067 -1.69e+07 5.01e+08\nx420 3.941e+07 1.25e+08 0.316 0.752 -2.05e+08 2.84e+08\nx421 8.55e+07 1.49e+08 0.572 0.567 -2.07e+08 3.78e+08\nx422 3.643e+07 1.43e+08 0.255 0.799 -2.44e+08 3.17e+08\nx423 1.172e+08 1.33e+08 0.882 0.378 -1.43e+08 3.78e+08\nx424 -1.7e+08 1.38e+08 -1.229 0.219 -4.41e+08 1.01e+08\nx425 4.97e+07 1.34e+08 0.370 0.711 -2.14e+08 3.13e+08\nx426 -2.4e+08 1.3e+08 -1.847 0.065 -4.95e+08 1.47e+07\nx427 3.125e+08 1.28e+08 2.442 0.015 6.17e+07 5.63e+08\nx428 4.825e+08 1.13e+08 4.264 0.000 2.61e+08 7.04e+08\nx429 5.949e+08 3.42e+08 1.741 0.082 -7.5e+07 1.26e+09\nx430 -4.64e+07 1.28e+08 -0.362 0.717 -2.98e+08 2.05e+08\nx431 3.454e+08 1.14e+08 3.017 0.003 1.21e+08 5.7e+08\nx432 4.65e+08 1.9e+08 2.445 0.014 9.22e+07 8.38e+08\nx433 1.308e+08 1.11e+08 1.182 0.237 -8.6e+07 3.48e+08\nx434 -6.724e+08 1.55e+08 -4.325 0.000 -9.77e+08 -3.68e+08\nx435 7.222e+07 1.18e+08 0.612 0.541 -1.59e+08 3.04e+08\nx436 2.745e+08 1.19e+08 2.310 0.021 4.16e+07 5.07e+08\nx437 -3.485e+08 1.46e+08 -2.382 0.017 -6.35e+08 -6.18e+07\nx438 -2.596e+08 1.16e+08 -2.230 0.026 -4.88e+08 -3.15e+07\nx439 -1.751e+08 2.37e+08 -0.738 0.461 -6.41e+08 2.9e+08\nx440 3.154e+07 1.16e+08 0.272 0.785 -1.95e+08 2.58e+08\nx441 -7.733e+08 1.82e+08 -4.255 0.000 -1.13e+09 -4.17e+08\nx442 2.573e+08 1.31e+08 1.968 0.049 1.1e+06 5.14e+08\nx443 5.183e+08 1.72e+08 3.006 0.003 1.8e+08 8.56e+08\nx444 3.059e+08 1.32e+08 2.315 0.021 4.7e+07 5.65e+08\nx445 1.548e+07 1.11e+08 0.140 0.889 -2.01e+08 2.32e+08\nx446 -2.383e+08 1.45e+08 -1.641 0.101 -5.23e+08 4.62e+07\nx447 1.635e+08 1.06e+08 1.537 0.124 -4.5e+07 3.72e+08\nx448 3.416e+07 1.97e+08 0.173 0.862 -3.52e+08 4.21e+08\nx449 3.976e+08 1.37e+08 2.908 0.004 1.3e+08 6.66e+08\nx450 -8.339e+08 1.69e+08 -4.931 0.000 -1.17e+09 -5.02e+08\nx451 -2.051e+08 1.74e+08 -1.181 0.238 -5.46e+08 1.35e+08\nx452 1.007e+09 1.18e+08 8.529 0.000 7.75e+08 1.24e+09\nx453 -1.643e+08 1.41e+08 -1.169 0.243 -4.4e+08 1.11e+08\nx454 3.869e+08 1.48e+08 2.623 0.009 9.78e+07 6.76e+08\nx455 -4.063e+07 1.81e+08 -0.225 0.822 -3.95e+08 3.14e+08\nx456 -5.948e+08 1.34e+08 -4.447 0.000 -8.57e+08 -3.33e+08\nx457 1.88e+08 1.38e+08 1.358 0.175 -8.34e+07 4.59e+08\nx458 -1.19e+08 1.26e+08 -0.941 0.347 -3.67e+08 1.29e+08\nx459 -5.674e+08 2.38e+08 -2.388 0.017 -1.03e+09 -1.02e+08\nx460 -4.746e+07 1.31e+08 -0.363 0.716 -3.04e+08 2.09e+08\nx461 -1.157e+09 1.54e+08 -7.502 0.000 -1.46e+09 -8.55e+08\nx462 -5.601e+08 1.41e+08 -3.980 0.000 -8.36e+08 -2.84e+08\nx463 8.497e+08 1.31e+08 6.493 0.000 5.93e+08 1.11e+09\nx464 5.666e+07 1.29e+08 0.440 0.660 -1.95e+08 3.09e+08\nx465 2.098e+08 1.18e+08 1.773 0.076 -2.22e+07 4.42e+08\nx466 3.13e+08 1.48e+08 2.118 0.034 2.34e+07 6.03e+08\nx467 -1.17e+08 1.17e+08 -1.003 0.316 -3.46e+08 1.12e+08\nx468 8.795e+07 1.54e+08 0.573 0.567 -2.13e+08 3.89e+08\nx469 -5.492e+08 1.42e+08 -3.856 0.000 -8.28e+08 -2.7e+08\nx470 -8.667e+08 1.26e+08 -6.904 0.000 -1.11e+09 -6.21e+08\nx471 -3.641e+08 1.31e+08 -2.789 0.005 -6.2e+08 -1.08e+08\nx472 -7.94e+08 1.38e+08 -5.770 0.000 -1.06e+09 -5.24e+08\nx473 2.941e+08 1.21e+08 2.422 0.015 5.61e+07 5.32e+08\nx474 -2.416e+08 1.32e+08 -1.835 0.066 -5e+08 1.64e+07\nx475 1.225e+08 1.26e+08 0.970 0.332 -1.25e+08 3.7e+08\nx476 -3.868e+08 1.28e+08 -3.018 0.003 -6.38e+08 -1.36e+08\nx477 -4.852e+08 1.49e+08 -3.258 0.001 -7.77e+08 -1.93e+08\nx478 -4.887e+08 1.19e+08 -4.123 0.000 -7.21e+08 -2.56e+08\nx479 2.05e+08 1.29e+08 1.588 0.112 -4.8e+07 4.58e+08\nx480 4.824e+08 1.21e+08 3.994 0.000 2.46e+08 7.19e+08\nx481 4.398e+07 1.81e+08 0.243 0.808 -3.1e+08 3.98e+08\nx482 -4.115e+08 1.5e+08 -2.738 0.006 -7.06e+08 -1.17e+08\nx483 3.997e+07 1.7e+08 0.235 0.814 -2.94e+08 3.73e+08\nx484 -1.611e+08 3.09e+08 -0.521 0.603 -7.68e+08 4.45e+08\nx485 -5.797e+08 1.28e+08 -4.521 0.000 -8.31e+08 -3.28e+08\nx486 -2.108e+08 1.27e+08 -1.656 0.098 -4.6e+08 3.87e+07\nx487 -7.981e+08 3.41e+08 -2.339 0.019 -1.47e+09 -1.29e+08\nx488 -2.09e+08 1.53e+08 -1.363 0.173 -5.09e+08 9.15e+07\nx489 -2.001e+07 1.45e+08 -0.138 0.890 -3.03e+08 2.63e+08\nx490 -1.463e+08 1.23e+08 -1.189 0.234 -3.88e+08 9.49e+07\nx491 6.437e+06 1.26e+08 0.051 0.959 -2.4e+08 2.53e+08\nx492 9.35e+08 1.42e+08 6.590 0.000 6.57e+08 1.21e+09\nx493 3.054e+08 1.34e+08 2.278 0.023 4.27e+07 5.68e+08\nx494 -1.166e+08 1.62e+08 -0.722 0.470 -4.33e+08 2e+08\nx495 1.048e+08 1.31e+08 0.802 0.423 -1.51e+08 3.61e+08\nx496 5.248e+08 1.22e+08 4.316 0.000 2.86e+08 7.63e+08\nx497 6.527e+07 1.17e+08 0.559 0.576 -1.64e+08 2.94e+08\nx498 5.746e+08 1.13e+08 5.082 0.000 3.53e+08 7.96e+08\nx499 -8.982e+07 1.23e+08 -0.733 0.463 -3.3e+08 1.5e+08\nx500 2.043e+08 1.2e+08 1.705 0.088 -3.06e+07 4.39e+08\nx501 -7.57e+07 1.32e+08 -0.575 0.566 -3.34e+08 1.83e+08\nx502 5.481e+08 1.4e+08 3.921 0.000 2.74e+08 8.22e+08\nx503 -1.091e+08 1.41e+08 -0.771 0.441 -3.86e+08 1.68e+08\nx504 -4.103e+08 1.53e+08 -2.679 0.007 -7.1e+08 -1.1e+08\nx505 1.867e+08 1.92e+08 0.975 0.330 -1.89e+08 5.62e+08\nx506 1.928e+08 1.29e+08 1.492 0.136 -6.04e+07 4.46e+08\nx507 2.359e+08 1.51e+08 1.561 0.118 -6.02e+07 5.32e+08\nx508 1.229e+08 1.25e+08 0.985 0.325 -1.22e+08 3.67e+08\nx509 6.544e+08 1.36e+08 4.797 0.000 3.87e+08 9.22e+08\nx510 6.081e+08 1.54e+08 3.959 0.000 3.07e+08 9.09e+08\nx511 4.771e+08 1.32e+08 3.616 0.000 2.19e+08 7.36e+08\nx512 3.35e+08 1.81e+08 1.847 0.065 -2.05e+07 6.9e+08\nx513 4.065e+08 1.33e+08 3.053 0.002 1.46e+08 6.67e+08\nx514 1.123e+07 1.45e+08 0.077 0.938 -2.73e+08 2.95e+08\nx515 2.993e+08 1.21e+08 2.481 0.013 6.28e+07 5.36e+08\nx516 1.948e+08 1.1e+08 1.779 0.075 -1.98e+07 4.09e+08\nx517 -2.723e+08 1.26e+08 -2.154 0.031 -5.2e+08 -2.45e+07\nx518 -1.399e+09 3e+08 -4.668 0.000 -1.99e+09 -8.12e+08\nx519 -2.683e+08 1.14e+08 -2.349 0.019 -4.92e+08 -4.44e+07\nx520 1.448e+08 1.16e+08 1.248 0.212 -8.25e+07 3.72e+08\nx521 -1.26e+08 1.06e+08 -1.193 0.233 -3.33e+08 8.11e+07\nx522 -1.389e+09 2.63e+08 -5.275 0.000 -1.9e+09 -8.73e+08\nx523 -3.42e+08 1.57e+08 -2.185 0.029 -6.49e+08 -3.52e+07\nx524 -3.26e+07 1.19e+08 -0.275 0.783 -2.65e+08 2e+08\nx525 -9.484e+08 1.95e+08 -4.863 0.000 -1.33e+09 -5.66e+08\nx526 -5.519e+08 1.46e+08 -3.785 0.000 -8.38e+08 -2.66e+08\nx527 -8.576e+08 1.17e+08 -7.348 0.000 -1.09e+09 -6.29e+08\nx528 -7.324e+08 1.26e+08 -5.833 0.000 -9.78e+08 -4.86e+08\nx529 -7.226e+08 1.34e+08 -5.405 0.000 -9.85e+08 -4.61e+08\nx530 -8.116e+08 1.33e+08 -6.105 0.000 -1.07e+09 -5.51e+08\nx531 -3.945e+08 1.2e+08 -3.290 0.001 -6.3e+08 -1.59e+08\nx532 2.376e+08 1.15e+08 2.065 0.039 1.21e+07 4.63e+08\nx533 -1.319e+08 1.5e+08 -0.882 0.378 -4.25e+08 1.61e+08\nx534 -1.286e+07 1.65e+08 -0.078 0.938 -3.36e+08 3.1e+08\nx535 2.216e+08 1.48e+08 1.493 0.136 -6.94e+07 5.13e+08\nx536 -2.933e+07 1.68e+08 -0.174 0.862 -3.59e+08 3e+08\nx537 2.411e+08 1.14e+08 2.112 0.035 1.73e+07 4.65e+08\nx538 -2.809e+08 2.84e+08 -0.988 0.323 -8.38e+08 2.76e+08\nx539 -8.965e+07 1.27e+08 -0.704 0.482 -3.39e+08 1.6e+08\nx540 -3e+07 1.35e+08 -0.222 0.825 -2.95e+08 2.35e+08\nx541 8.222e+07 1.18e+08 0.698 0.485 -1.49e+08 3.13e+08\nx542 -2.464e+08 1.35e+08 -1.823 0.068 -5.11e+08 1.85e+07\nx543 4.377e+08 1.28e+08 3.415 0.001 1.86e+08 6.89e+08\nx544 -9.047e+07 2.29e+08 -0.396 0.692 -5.39e+08 3.58e+08\nx545 2.163e+08 1.2e+08 1.795 0.073 -1.99e+07 4.52e+08\nx546 3.875e+08 2.11e+08 1.838 0.066 -2.56e+07 8.01e+08\nx547 1.966e+08 1.31e+08 1.497 0.134 -6.08e+07 4.54e+08\nx548 1.534e+08 1.22e+08 1.254 0.210 -8.63e+07 3.93e+08\nx549 8.361e+08 1.3e+08 6.446 0.000 5.82e+08 1.09e+09\nx550 2.959e+08 1.22e+08 2.420 0.016 5.62e+07 5.35e+08\nx551 2.838e+08 1.64e+08 1.730 0.084 -3.76e+07 6.05e+08\nx552 4.998e+08 1.24e+08 4.022 0.000 2.56e+08 7.43e+08\nx553 4.71e+08 1.54e+08 3.056 0.002 1.69e+08 7.73e+08\nx554 2.963e+08 1.2e+08 2.470 0.014 6.12e+07 5.31e+08\nx555 5.421e+08 1.31e+08 4.151 0.000 2.86e+08 7.98e+08\nx556 2.979e+08 1.97e+08 1.513 0.130 -8.8e+07 6.84e+08\nx557 -5.673e+07 1.14e+08 -0.497 0.619 -2.8e+08 1.67e+08\nx558 -4.365e+08 1.23e+08 -3.561 0.000 -6.77e+08 -1.96e+08\nx559 2.709e+08 1.15e+08 2.365 0.018 4.64e+07 4.95e+08\nx560 -1.777e+08 1.65e+08 -1.076 0.282 -5.01e+08 1.46e+08\nx561 1.21e+09 1.27e+08 9.502 0.000 9.61e+08 1.46e+09\nx562 6.97e+08 1.47e+08 4.730 0.000 4.08e+08 9.86e+08\nx563 3.096e+07 1.45e+08 0.213 0.831 -2.54e+08 3.16e+08\nx564 1.521e+08 1.17e+08 1.296 0.195 -7.8e+07 3.82e+08\nx565 5.082e+08 1.19e+08 4.265 0.000 2.75e+08 7.42e+08\nx566 1.307e+08 1.45e+08 0.904 0.366 -1.53e+08 4.14e+08\nx567 5.508e+08 1.26e+08 4.381 0.000 3.04e+08 7.97e+08\nx568 2.812e+08 1.54e+08 1.826 0.068 -2.07e+07 5.83e+08\nx569 3.155e+08 1.6e+08 1.976 0.048 2.56e+06 6.29e+08\nx570 7.397e+07 1.83e+08 0.405 0.685 -2.84e+08 4.32e+08\nx571 1.478e+08 1.22e+08 1.214 0.225 -9.08e+07 3.86e+08\nx572 -1.74e+08 1.7e+08 -1.024 0.306 -5.07e+08 1.59e+08\nx573 -1.271e+07 1.3e+08 -0.097 0.922 -2.68e+08 2.43e+08\nx574 1.781e+08 1.4e+08 1.270 0.204 -9.67e+07 4.53e+08\nx575 2.341e+08 1.24e+08 1.894 0.058 -8.1e+06 4.76e+08\nx576 -2.318e+08 1.26e+08 -1.842 0.065 -4.78e+08 1.48e+07\nx577 -5.619e+06 1.27e+08 -0.044 0.965 -2.54e+08 2.43e+08\nx578 5.546e+08 1.14e+08 4.867 0.000 3.31e+08 7.78e+08\nx579 2.05e+08 2.27e+08 0.904 0.366 -2.4e+08 6.49e+08\nx580 5.495e+08 1.18e+08 4.664 0.000 3.19e+08 7.8e+08\nx581 4.764e+07 1.41e+08 0.339 0.735 -2.28e+08 3.23e+08\nx582 4.338e+08 1.52e+08 2.854 0.004 1.36e+08 7.32e+08\nx583 -5.542e+08 1.23e+08 -4.498 0.000 -7.96e+08 -3.13e+08\nx584 2.902e+08 1.33e+08 2.183 0.029 2.96e+07 5.51e+08\nx585 3.565e+08 1.59e+08 2.245 0.025 4.53e+07 6.68e+08\nx586 6.046e+08 1.11e+08 5.433 0.000 3.86e+08 8.23e+08\nx587 1.748e+08 1.31e+08 1.332 0.183 -8.23e+07 4.32e+08\nx588 2.81e+08 1.65e+08 1.704 0.088 -4.22e+07 6.04e+08\nx589 2.599e+08 1.16e+08 2.239 0.025 3.24e+07 4.87e+08\nx590 7.79e+08 1.09e+08 7.146 0.000 5.65e+08 9.93e+08\nx591 -3.877e+07 1.26e+08 -0.307 0.759 -2.87e+08 2.09e+08\nx592 1.983e+08 1.26e+08 1.573 0.116 -4.87e+07 4.45e+08\nx593 -1.887e+08 1.51e+08 -1.247 0.213 -4.85e+08 1.08e+08\nx594 -4.754e+08 1.15e+08 -4.125 0.000 -7.01e+08 -2.5e+08\nx595 -9.322e+07 1.12e+08 -0.834 0.404 -3.12e+08 1.26e+08\nx596 -2.078e+08 1.26e+08 -1.646 0.100 -4.55e+08 3.97e+07\nx597 4.433e+08 1.65e+08 2.682 0.007 1.19e+08 7.67e+08\nx598 5.189e+08 1.27e+08 4.096 0.000 2.71e+08 7.67e+08\nx599 3.677e+08 1.82e+08 2.017 0.044 1.04e+07 7.25e+08\nx600 1.074e+08 1.65e+08 0.653 0.514 -2.15e+08 4.3e+08\nx601 2.374e+08 1.14e+08 2.074 0.038 1.3e+07 4.62e+08\nx602 4.1e+08 1.25e+08 3.275 0.001 1.65e+08 6.55e+08\nx603 3.133e+07 1.17e+08 0.269 0.788 -1.97e+08 2.6e+08\nx604 3.213e+08 1.16e+08 2.781 0.005 9.49e+07 5.48e+08\nx605 1.028e+08 1.25e+08 0.825 0.410 -1.42e+08 3.47e+08\nx606 -5.336e+07 1.12e+08 -0.477 0.634 -2.73e+08 1.66e+08\nx607 1.246e+08 2.67e+08 0.467 0.640 -3.98e+08 6.47e+08\nx608 3.178e+08 1.52e+08 2.087 0.037 1.93e+07 6.16e+08\nx609 8.305e+08 1.39e+08 5.976 0.000 5.58e+08 1.1e+09\nx610 5.233e+07 1.75e+08 0.300 0.765 -2.9e+08 3.95e+08\nx611 7.77e+07 1.44e+08 0.541 0.589 -2.04e+08 3.59e+08\nx612 8.598e+08 1.12e+08 7.687 0.000 6.41e+08 1.08e+09\nx613 -9.735e+07 1.2e+08 -0.809 0.419 -3.33e+08 1.39e+08\nx614 1.612e+08 1.11e+08 1.455 0.146 -5.6e+07 3.78e+08\nx615 1.205e+08 1.35e+08 0.895 0.371 -1.43e+08 3.85e+08\nx616 3.195e+07 1.42e+08 0.225 0.822 -2.47e+08 3.11e+08\nx617 -1.313e+08 1.2e+08 -1.093 0.275 -3.67e+08 1.04e+08\nx618 3.764e+08 1.08e+08 3.492 0.000 1.65e+08 5.88e+08\nx619 -4.614e+07 1.21e+08 -0.382 0.703 -2.83e+08 1.91e+08\nx620 2.6e+08 1.33e+08 1.951 0.051 -1.13e+06 5.21e+08\nx621 -5.232e+07 1.39e+08 -0.377 0.706 -3.25e+08 2.2e+08\nx622 -5.897e+07 1.49e+08 -0.397 0.692 -3.5e+08 2.32e+08\nx623 4.893e+08 1.51e+08 3.242 0.001 1.93e+08 7.85e+08\nx624 6.633e+08 1.47e+08 4.522 0.000 3.76e+08 9.51e+08\nx625 2.124e+08 1.41e+08 1.502 0.133 -6.48e+07 4.9e+08\nx626 1.607e+08 1.58e+08 1.016 0.310 -1.49e+08 4.71e+08\nx627 -1.104e+07 1.48e+08 -0.075 0.941 -3.01e+08 2.79e+08\nx628 -2.5e+08 1.33e+08 -1.881 0.060 -5.11e+08 1.05e+07\nx629 1.345e+08 1.52e+08 0.885 0.376 -1.63e+08 4.32e+08\nx630 -2.514e+08 1.28e+08 -1.960 0.050 -5.03e+08 2.33e+04\nx631 4.913e+08 1.28e+08 3.837 0.000 2.4e+08 7.42e+08\nx632 -4.975e+08 1.2e+08 -4.152 0.000 -7.32e+08 -2.63e+08\nx633 1.22e+08 1.47e+08 0.828 0.407 -1.67e+08 4.11e+08\nx634 -4.44e+08 1.64e+08 -2.700 0.007 -7.66e+08 -1.22e+08\nx635 1.172e+09 1.2e+08 9.738 0.000 9.36e+08 1.41e+09\nx636 -6.507e+07 1.28e+08 -0.508 0.612 -3.16e+08 1.86e+08\nx637 8.935e+08 1.38e+08 6.467 0.000 6.23e+08 1.16e+09\nx638 -1.806e+08 1.35e+08 -1.340 0.180 -4.45e+08 8.36e+07\nx639 4.394e+08 1.33e+08 3.296 0.001 1.78e+08 7.01e+08\nx640 1.894e+08 1.68e+08 1.130 0.259 -1.39e+08 5.18e+08\nx641 5.004e+08 1.29e+08 3.885 0.000 2.48e+08 7.53e+08\nx642 2.508e+09 1.13e+08 22.188 0.000 2.29e+09 2.73e+09\nx643 7.23e+08 1.5e+08 4.807 0.000 4.28e+08 1.02e+09\nx644 4.153e+08 1.24e+08 3.351 0.001 1.72e+08 6.58e+08\nx645 2.514e+07 1.25e+08 0.200 0.841 -2.21e+08 2.71e+08\nx646 2.269e+08 1.42e+08 1.598 0.110 -5.14e+07 5.05e+08\nx647 -8.666e+08 2.53e+08 -3.424 0.001 -1.36e+09 -3.71e+08\nx648 2.335e+08 1.14e+08 2.052 0.040 1.05e+07 4.56e+08\nx649 1.088e+08 1.8e+08 0.605 0.545 -2.44e+08 4.62e+08\nx650 -3.708e+08 1.48e+08 -2.512 0.012 -6.6e+08 -8.15e+07\nx651 -1.422e+08 1.11e+08 -1.276 0.202 -3.6e+08 7.62e+07\nx652 3.479e+08 1.58e+08 2.198 0.028 3.77e+07 6.58e+08\nx653 3.139e+08 1.4e+08 2.246 0.025 4e+07 5.88e+08\nx654 1.779e+08 1.54e+08 1.152 0.249 -1.25e+08 4.81e+08\nx655 -1.061e+08 2.26e+08 -0.470 0.639 -5.49e+08 3.37e+08\nx656 1.582e+08 1.55e+08 1.019 0.308 -1.46e+08 4.63e+08\nx657 4.034e+07 1.33e+08 0.303 0.762 -2.21e+08 3.01e+08\nx658 3.377e+08 1.22e+08 2.763 0.006 9.81e+07 5.77e+08\nx659 6.732e+08 1.23e+08 5.471 0.000 4.32e+08 9.14e+08\nx660 2.041e+08 1.37e+08 1.493 0.135 -6.38e+07 4.72e+08\nx661 6.467e+08 1.27e+08 5.107 0.000 3.98e+08 8.95e+08\nx662 5.827e+08 1.43e+08 4.071 0.000 3.02e+08 8.63e+08\nx663 3.42e+08 1.43e+08 2.391 0.017 6.17e+07 6.22e+08\nx664 8.369e+08 1.23e+08 6.797 0.000 5.96e+08 1.08e+09\nx665 -4.503e+07 1.44e+08 -0.313 0.754 -3.27e+08 2.37e+08\nx666 9.898e+08 1.85e+08 5.351 0.000 6.27e+08 1.35e+09\nx667 3.657e+08 1.5e+08 2.439 0.015 7.18e+07 6.6e+08\nx668 9.916e+08 1.61e+08 6.145 0.000 6.75e+08 1.31e+09\nx669 5.672e+08 1.18e+08 4.787 0.000 3.35e+08 7.99e+08\nx670 4.223e+08 1.34e+08 3.159 0.002 1.6e+08 6.84e+08\nx671 5.65e+08 1.24e+08 4.540 0.000 3.21e+08 8.09e+08\nx672 -9.692e+07 1.19e+08 -0.816 0.414 -3.3e+08 1.36e+08\nx673 2.457e+08 1.53e+08 1.602 0.109 -5.49e+07 5.46e+08\nx674 3.812e+08 1.25e+08 3.049 0.002 1.36e+08 6.26e+08\nx675 2.51e+08 1.35e+08 1.856 0.063 -1.4e+07 5.16e+08\nx676 3.884e+08 1.4e+08 2.773 0.006 1.14e+08 6.63e+08\nx677 2.859e+08 1.31e+08 2.176 0.030 2.84e+07 5.43e+08\nx678 3.542e+08 1.41e+08 2.521 0.012 7.89e+07 6.3e+08\nx679 1.955e+08 1.89e+08 1.032 0.302 -1.76e+08 5.67e+08\nx680 4.444e+08 1.3e+08 3.427 0.001 1.9e+08 6.98e+08\nx681 -1.493e+08 1.27e+08 -1.179 0.239 -3.97e+08 9.9e+07\nx682 -7.409e+08 1.56e+08 -4.762 0.000 -1.05e+09 -4.36e+08\nx683 -1.882e+08 1.84e+08 -1.021 0.307 -5.5e+08 1.73e+08\nx684 -4.101e+08 2.53e+08 -1.623 0.105 -9.05e+08 8.51e+07\nx685 -3.313e+08 1.39e+08 -2.391 0.017 -6.03e+08 -5.97e+07\nx686 -2.813e+08 1.17e+08 -2.403 0.016 -5.11e+08 -5.18e+07\nx687 -5.074e+08 1.27e+08 -3.987 0.000 -7.57e+08 -2.58e+08\nx688 -3.709e+08 1.2e+08 -3.085 0.002 -6.07e+08 -1.35e+08\nx689 -4.629e+08 1.33e+08 -3.483 0.000 -7.23e+08 -2.02e+08\nx690 -1.81e+08 1.2e+08 -1.508 0.131 -4.16e+08 5.42e+07\nx691 2.138e+08 1.2e+08 1.785 0.074 -2.1e+07 4.49e+08\nx692 3.151e+07 1.34e+08 0.235 0.814 -2.31e+08 2.94e+08\nx693 7.663e+07 1.3e+08 0.591 0.555 -1.78e+08 3.31e+08\nx694 6.205e+07 1.38e+08 0.449 0.653 -2.09e+08 3.33e+08\nx695 -1.301e+08 1.44e+08 -0.905 0.366 -4.12e+08 1.52e+08\nx696 -5.455e+07 1.29e+08 -0.424 0.672 -3.07e+08 1.98e+08\nx697 -3.303e+08 1.66e+08 -1.989 0.047 -6.56e+08 -4.75e+06\nx698 -4.591e+08 1.72e+08 -2.668 0.008 -7.96e+08 -1.22e+08\nx699 -2.749e+07 1.98e+08 -0.139 0.889 -4.15e+08 3.6e+08\nx700 1.467e+08 1.41e+08 1.040 0.298 -1.3e+08 4.23e+08\nx701 -2.021e+07 1.29e+08 -0.157 0.875 -2.73e+08 2.32e+08\nx702 1.986e+08 1.4e+08 1.418 0.156 -7.59e+07 4.73e+08\nx703 3.989e+07 1.21e+08 0.330 0.742 -1.97e+08 2.77e+08\nx704 1.199e+08 1.44e+08 0.834 0.404 -1.62e+08 4.01e+08\nx705 1.015e+09 1.29e+08 7.841 0.000 7.61e+08 1.27e+09\nx706 6.021e+08 1.25e+08 4.811 0.000 3.57e+08 8.47e+08\nx707 1.426e+08 1.49e+08 0.957 0.339 -1.5e+08 4.35e+08\nx708 -3.842e+08 1.06e+08 -3.623 0.000 -5.92e+08 -1.76e+08\nx709 -8.413e+07 1.2e+08 -0.704 0.482 -3.18e+08 1.5e+08\nx710 2.597e+08 1.22e+08 2.128 0.033 2.04e+07 4.99e+08\nx711 -1.849e+08 1.65e+08 -1.122 0.262 -5.08e+08 1.38e+08\nx712 2.504e+07 1.44e+08 0.174 0.862 -2.58e+08 3.08e+08\nx713 -2.195e+08 1.86e+08 -1.179 0.238 -5.84e+08 1.45e+08\nx714 -3.749e+08 2.04e+08 -1.840 0.066 -7.74e+08 2.45e+07\nx715 -4.852e+08 1.49e+08 -3.253 0.001 -7.78e+08 -1.93e+08\nx716 -1.736e+07 1.48e+08 -0.117 0.907 -3.08e+08 2.73e+08\nx717 2.867e+08 1.17e+08 2.452 0.014 5.76e+07 5.16e+08\nx718 1.336e+08 1.32e+08 1.012 0.312 -1.25e+08 3.92e+08\nx719 -4.846e+08 1.89e+08 -2.571 0.010 -8.54e+08 -1.15e+08\nx720 7.582e+07 1.43e+08 0.528 0.597 -2.05e+08 3.57e+08\nx721 -6.653e+06 1.43e+08 -0.047 0.963 -2.86e+08 2.73e+08\nx722 -1.784e+07 1.31e+08 -0.136 0.892 -2.75e+08 2.39e+08\nx723 1.301e+08 4.24e+08 0.307 0.759 -7.01e+08 9.61e+08\nx724 -5.612e+08 3.18e+08 -1.763 0.078 -1.19e+09 6.28e+07\nx725 -3.479e+08 1.43e+08 -2.426 0.015 -6.29e+08 -6.69e+07\nx726 1.957e+08 1.16e+08 1.688 0.091 -3.15e+07 4.23e+08\nx727 -2.8e+07 1.97e+08 -0.142 0.887 -4.14e+08 3.58e+08\nx728 -1.243e+08 1.38e+08 -0.903 0.366 -3.94e+08 1.45e+08\nx729 3.543e+08 1.21e+08 2.929 0.003 1.17e+08 5.91e+08\nx730 6.451e+08 1.23e+08 5.229 0.000 4.03e+08 8.87e+08\nx731 1.895e+08 1.18e+08 1.604 0.109 -4.21e+07 4.21e+08\nx732 2.714e+08 1.65e+08 1.642 0.101 -5.25e+07 5.95e+08\nx733 -3.896e+08 1.74e+08 -2.241 0.025 -7.3e+08 -4.89e+07\nx734 -2.428e+08 2.22e+08 -1.096 0.273 -6.77e+08 1.91e+08\nx735 -2.154e+08 1.35e+08 -1.599 0.110 -4.79e+08 4.86e+07\nx736 1.487e+08 1.22e+08 1.222 0.222 -8.99e+07 3.87e+08\nx737 3.242e+08 1.25e+08 2.584 0.010 7.82e+07 5.7e+08\nx738 2.647e+07 1.27e+08 0.208 0.835 -2.23e+08 2.76e+08\nx739 -3.065e+08 1.3e+08 -2.353 0.019 -5.62e+08 -5.12e+07\nx740 -9.193e+08 2.63e+08 -3.490 0.000 -1.44e+09 -4.03e+08\nx741 1.885e+07 1.06e+08 0.177 0.859 -1.9e+08 2.27e+08\nx742 -4.093e+08 1.22e+08 -3.365 0.001 -6.48e+08 -1.71e+08\nx743 9.936e+07 1.72e+08 0.576 0.565 -2.39e+08 4.37e+08\nx744 -3.325e+08 1.3e+08 -2.561 0.010 -5.87e+08 -7.8e+07\nx745 -1.511e+08 1.57e+08 -0.963 0.336 -4.59e+08 1.57e+08\nx746 -7.755e+06 1.2e+08 -0.064 0.949 -2.44e+08 2.28e+08\nx747 6.655e+06 1.82e+08 0.036 0.971 -3.51e+08 3.64e+08\nx748 -6.983e+08 1.93e+08 -3.624 0.000 -1.08e+09 -3.21e+08\nx749 -7.119e+08 2.01e+08 -3.548 0.000 -1.11e+09 -3.19e+08\nx750 -4.85e+07 1.46e+08 -0.331 0.740 -3.35e+08 2.38e+08\nx751 -1.69e+08 1.37e+08 -1.237 0.216 -4.37e+08 9.88e+07\nx752 -6.221e+08 1.36e+08 -4.584 0.000 -8.88e+08 -3.56e+08\nx753 -6.551e+08 1.34e+08 -4.875 0.000 -9.19e+08 -3.92e+08\nx754 -2.679e+07 1.27e+08 -0.211 0.833 -2.75e+08 2.22e+08\nx755 5.753e+08 1.19e+08 4.819 0.000 3.41e+08 8.09e+08\nx756 -7.901e+08 1.19e+08 -6.631 0.000 -1.02e+09 -5.57e+08\nx757 -1.744e+08 1.85e+08 -0.942 0.346 -5.37e+08 1.88e+08\nx758 4.299e+08 1.37e+08 3.141 0.002 1.62e+08 6.98e+08\nx759 -1.882e+08 1.18e+08 -1.596 0.110 -4.19e+08 4.28e+07\nx760 -9.923e+08 4.05e+08 -2.452 0.014 -1.79e+09 -1.99e+08\nx761 -8.772e+08 1.83e+08 -4.792 0.000 -1.24e+09 -5.18e+08\nx762 5.644e+07 2.93e+08 0.193 0.847 -5.18e+08 6.31e+08\nx763 2.191e+08 1.43e+08 1.529 0.126 -6.18e+07 5e+08\nx764 5.34e+08 1.27e+08 4.216 0.000 2.86e+08 7.82e+08\nx765 -4.268e+08 2.03e+08 -2.098 0.036 -8.26e+08 -2.81e+07\nx766 -2.128e+08 1.12e+08 -1.898 0.058 -4.33e+08 6.92e+06\nx767 5.181e+06 1.22e+08 0.042 0.966 -2.34e+08 2.44e+08\nx768 1.254e+08 1.88e+08 0.667 0.505 -2.43e+08 4.94e+08\nx769 1.301e+08 1.99e+08 0.653 0.514 -2.6e+08 5.2e+08\nx770 1.198e+08 1.29e+08 0.932 0.351 -1.32e+08 3.72e+08\nx771 -1.047e+09 1.7e+08 -6.171 0.000 -1.38e+09 -7.15e+08\nx772 5.527e+08 1.39e+08 3.973 0.000 2.8e+08 8.25e+08\nx773 -1.676e+08 2.85e+08 -0.588 0.557 -7.26e+08 3.91e+08\nx774 -5.506e+07 1.48e+08 -0.372 0.710 -3.45e+08 2.35e+08\nx775 3.105e+08 1.33e+08 2.326 0.020 4.89e+07 5.72e+08\nx776 -2.133e+08 1.67e+08 -1.276 0.202 -5.41e+08 1.14e+08\nx777 2.179e+08 1.31e+08 1.668 0.095 -3.82e+07 4.74e+08\nx778 3.232e+08 1.46e+08 2.221 0.026 3.8e+07 6.08e+08\nx779 8.413e+08 1.24e+08 6.800 0.000 5.99e+08 1.08e+09\nx780 5.398e+06 1.36e+08 0.040 0.968 -2.61e+08 2.72e+08\nx781 -1.67e+08 1.17e+08 -1.429 0.153 -3.96e+08 6.2e+07\nx782 3.352e+08 1.82e+08 1.837 0.066 -2.24e+07 6.93e+08\nx783 4.066e+08 1.23e+08 3.302 0.001 1.65e+08 6.48e+08\nx784 1.291e+08 1.47e+08 0.881 0.378 -1.58e+08 4.16e+08\nx785 -3.542e+08 1.93e+08 -1.839 0.066 -7.32e+08 2.32e+07\nx786 -1.658e+07 1.42e+08 -0.117 0.907 -2.95e+08 2.62e+08\nx787 -4.555e+07 1.65e+08 -0.276 0.783 -3.69e+08 2.78e+08\nx788 1.74e+08 1.4e+08 1.242 0.214 -1e+08 4.48e+08\nx789 3.775e+08 1.26e+08 2.999 0.003 1.31e+08 6.24e+08\nx790 1.755e+08 1.3e+08 1.351 0.177 -7.91e+07 4.3e+08\nx791 3.488e+08 1.16e+08 3.020 0.003 1.22e+08 5.75e+08\nx792 2.932e+08 1.54e+08 1.901 0.057 -9.17e+06 5.96e+08\nx793 3.167e+08 1.21e+08 2.618 0.009 7.96e+07 5.54e+08\nx794 3.281e+08 1.11e+08 2.959 0.003 1.11e+08 5.45e+08\nx795 4.323e+08 1.19e+08 3.619 0.000 1.98e+08 6.66e+08\nx796 1.978e+08 1.32e+08 1.496 0.135 -6.14e+07 4.57e+08\nx797 2.759e+08 1.37e+08 2.007 0.045 6.45e+06 5.45e+08\nx798 3.049e+08 1.21e+08 2.526 0.012 6.83e+07 5.41e+08\nx799 -2.597e+08 1.94e+08 -1.337 0.181 -6.4e+08 1.21e+08\nx800 1.771e+08 1.27e+08 1.399 0.162 -7.11e+07 4.25e+08\nx801 -9.351e+07 1.47e+08 -0.638 0.523 -3.81e+08 1.94e+08\nx802 1.855e+08 1.16e+08 1.593 0.111 -4.27e+07 4.14e+08\nx803 -1.161e+08 5.19e+08 -0.224 0.823 -1.13e+09 9.02e+08\nx804 -5.084e+07 1.33e+08 -0.383 0.702 -3.11e+08 2.1e+08\nx805 3.705e+08 1.58e+08 2.339 0.019 6.01e+07 6.81e+08\nx806 1.294e+08 2.08e+08 0.622 0.534 -2.78e+08 5.37e+08\nx807 5.368e+08 1.29e+08 4.157 0.000 2.84e+08 7.9e+08\nx808 8.863e+07 1.56e+08 0.567 0.571 -2.18e+08 3.95e+08\nx809 3.767e+08 1.89e+08 1.997 0.046 6.9e+06 7.47e+08\nx810 1.073e+08 1.35e+08 0.797 0.426 -1.57e+08 3.71e+08\nx811 6.33e+08 1.94e+08 3.268 0.001 2.53e+08 1.01e+09\nx812 -4.695e+07 1.92e+08 -0.245 0.807 -4.23e+08 3.29e+08\nx813 6.304e+08 1.45e+08 4.336 0.000 3.45e+08 9.15e+08\nx814 8.635e+07 1.44e+08 0.599 0.549 -1.96e+08 3.69e+08\nx815 2.898e+08 1.2e+08 2.413 0.016 5.44e+07 5.25e+08\nx816 5.29e+08 1.34e+08 3.936 0.000 2.66e+08 7.92e+08\nx817 5.341e+08 1.42e+08 3.772 0.000 2.57e+08 8.12e+08\nx818 1.214e+09 1.43e+08 8.489 0.000 9.33e+08 1.49e+09\nx819 5.256e+08 3.86e+08 1.362 0.173 -2.31e+08 1.28e+09\nx820 2.416e+08 2.03e+08 1.191 0.234 -1.56e+08 6.39e+08\nx821 2.095e+08 1.14e+08 1.841 0.066 -1.36e+07 4.33e+08\nx822 6.289e+08 1.89e+08 3.330 0.001 2.59e+08 9.99e+08\nx823 -1.094e+08 1.42e+08 -0.768 0.442 -3.89e+08 1.7e+08\nx824 -1.65e+08 1.31e+08 -1.255 0.209 -4.23e+08 9.26e+07\nx825 2.244e+08 1.15e+08 1.956 0.050 -4.57e+05 4.49e+08\nx826 -8.547e+05 1.35e+08 -0.006 0.995 -2.65e+08 2.63e+08\nx827 4.672e+08 1.13e+08 4.151 0.000 2.47e+08 6.88e+08\nx828 -5.635e+08 1.26e+08 -4.463 0.000 -8.11e+08 -3.16e+08\nx829 -2.989e+08 1.19e+08 -2.522 0.012 -5.31e+08 -6.66e+07\nx830 1.214e+08 1.5e+08 0.811 0.417 -1.72e+08 4.15e+08\nx831 -5.655e+07 1.23e+08 -0.459 0.647 -2.98e+08 1.85e+08\nx832 1.977e+08 1.07e+08 1.846 0.065 -1.22e+07 4.08e+08\nx833 -3.353e+08 1.33e+08 -2.521 0.012 -5.96e+08 -7.46e+07\nx834 6.556e+06 1.34e+08 0.049 0.961 -2.56e+08 2.69e+08\nx835 2.91e+08 1.13e+08 2.565 0.010 6.86e+07 5.13e+08\nx836 2.565e+08 1.56e+08 1.644 0.100 -4.93e+07 5.62e+08\nx837 7.963e+08 1.22e+08 6.526 0.000 5.57e+08 1.04e+09\nx838 1.864e+08 1.58e+08 1.180 0.238 -1.23e+08 4.96e+08\nx839 -1.414e+08 6.37e+08 -0.222 0.824 -1.39e+09 1.11e+09\nx840 2.418e+08 1.5e+08 1.612 0.107 -5.22e+07 5.36e+08\nx841 2.292e+08 1.84e+08 1.248 0.212 -1.31e+08 5.89e+08\nx842 -5.32e+08 1.81e+08 -2.942 0.003 -8.86e+08 -1.78e+08\nx843 -5.773e+08 1.32e+08 -4.377 0.000 -8.36e+08 -3.19e+08\nx844 5.783e+07 1.15e+08 0.503 0.615 -1.68e+08 2.83e+08\nx845 -6.16e+08 1.96e+08 -3.149 0.002 -9.99e+08 -2.33e+08\nx846 -5.704e+08 1.5e+08 -3.808 0.000 -8.64e+08 -2.77e+08\nx847 -8.599e+08 1.61e+08 -5.356 0.000 -1.17e+09 -5.45e+08\nx848 -2.127e+09 1.8e+08 -11.825 0.000 -2.48e+09 -1.77e+09\nx849 4.854e+08 1.44e+08 3.361 0.001 2.02e+08 7.69e+08\nx850 -1.097e+08 1.27e+08 -0.864 0.388 -3.58e+08 1.39e+08\nx851 -6.014e+08 1.32e+08 -4.543 0.000 -8.61e+08 -3.42e+08\nx852 -9.705e+08 1.28e+08 -7.581 0.000 -1.22e+09 -7.2e+08\nx853 -1.986e+08 1.59e+08 -1.252 0.211 -5.1e+08 1.12e+08\nx854 -1.002e+08 1.24e+08 -0.807 0.420 -3.44e+08 1.43e+08\nx855 3.264e+08 2.33e+08 1.402 0.161 -1.3e+08 7.83e+08\nx856 -6.984e+08 1.26e+08 -5.555 0.000 -9.45e+08 -4.52e+08\nx857 1.496e+08 1.32e+08 1.134 0.257 -1.09e+08 4.08e+08\nx858 -6.458e+07 1.27e+08 -0.510 0.610 -3.13e+08 1.84e+08\nx859 -1.082e+09 1.43e+08 -7.583 0.000 -1.36e+09 -8.02e+08\nx860 -8.349e+08 1.51e+08 -5.533 0.000 -1.13e+09 -5.39e+08\nx861 -8.153e+08 1.27e+08 -6.396 0.000 -1.07e+09 -5.65e+08\nx862 -1.168e+09 1.8e+08 -6.475 0.000 -1.52e+09 -8.14e+08\nx863 -1.131e+09 1.55e+08 -7.276 0.000 -1.44e+09 -8.27e+08\nx864 6.199e+07 1.57e+08 0.394 0.694 -2.46e+08 3.7e+08\nx865 -1.927e+08 1.61e+08 -1.198 0.231 -5.08e+08 1.23e+08\nx866 -3.339e+08 1.3e+08 -2.577 0.010 -5.88e+08 -8e+07\nx867 -4.45e+08 1.13e+08 -3.930 0.000 -6.67e+08 -2.23e+08\nx868 -2.703e+08 1.3e+08 -2.083 0.037 -5.25e+08 -1.6e+07\nx869 -4.276e+08 1.23e+08 -3.477 0.001 -6.69e+08 -1.87e+08\nx870 -1.29e+09 1.92e+08 -6.703 0.000 -1.67e+09 -9.13e+08\nx871 -5.953e+08 2.52e+08 -2.362 0.018 -1.09e+09 -1.01e+08\nx872 -6.503e+08 2.38e+08 -2.727 0.006 -1.12e+09 -1.83e+08\nx873 -5.454e+07 1.25e+08 -0.435 0.664 -3e+08 1.91e+08\nx874 -2.766e+08 1.48e+08 -1.864 0.062 -5.67e+08 1.42e+07\nx875 -1.605e+08 2.51e+08 -0.640 0.522 -6.52e+08 3.31e+08\nx876 -7.257e+08 1.37e+08 -5.298 0.000 -9.94e+08 -4.57e+08\nx877 -5.688e+08 2.67e+08 -2.127 0.033 -1.09e+09 -4.47e+07\nx878 -6.583e+08 1.41e+08 -4.677 0.000 -9.34e+08 -3.82e+08\nx879 -9.529e+08 1.54e+08 -6.194 0.000 -1.25e+09 -6.51e+08\nx880 -8.808e+08 1.46e+08 -6.052 0.000 -1.17e+09 -5.96e+08\nx881 -4.362e+08 1.41e+08 -3.085 0.002 -7.13e+08 -1.59e+08\nx882 -7.19e+08 1.53e+08 -4.697 0.000 -1.02e+09 -4.19e+08\nx883 2.558e+08 1.34e+08 1.903 0.057 -7.65e+06 5.19e+08\nx884 3.446e+08 1.59e+08 2.171 0.030 3.35e+07 6.56e+08\nx885 -3.271e+08 2.39e+08 -1.370 0.171 -7.95e+08 1.41e+08\nx886 -1.481e+08 1.36e+08 -1.086 0.277 -4.15e+08 1.19e+08\nx887 -3.016e+08 1.29e+08 -2.338 0.019 -5.54e+08 -4.88e+07\nx888 1.723e+08 1.44e+08 1.193 0.233 -1.11e+08 4.55e+08\nx889 -1.468e+09 3.19e+08 -4.607 0.000 -2.09e+09 -8.43e+08\nx890 -1.083e+09 1.39e+08 -7.799 0.000 -1.36e+09 -8.11e+08\nx891 -3.829e+07 1.2e+08 -0.319 0.749 -2.73e+08 1.97e+08\nx892 4.257e+08 1.26e+08 3.376 0.001 1.79e+08 6.73e+08\nx893 7.336e+08 1.19e+08 6.180 0.000 5.01e+08 9.66e+08\nx894 3.416e+08 1.78e+08 1.919 0.055 -7.31e+06 6.91e+08\nx895 -1.546e+08 1.42e+08 -1.091 0.275 -4.32e+08 1.23e+08\nx896 1.091e+08 4.03e+08 0.270 0.787 -6.81e+08 9e+08\nx897 -4.525e+08 1.37e+08 -3.292 0.001 -7.22e+08 -1.83e+08\nx898 -1.069e+09 1.51e+08 -7.059 0.000 -1.37e+09 -7.72e+08\nx899 -1.498e+09 1.49e+08 -10.051 0.000 -1.79e+09 -1.21e+09\nx900 -1.147e+08 1.32e+08 -0.867 0.386 -3.74e+08 1.45e+08\nx901 -1.264e+09 1.34e+08 -9.467 0.000 -1.53e+09 -1e+09\nx902 5.127e+08 1.59e+08 3.226 0.001 2.01e+08 8.24e+08\nx903 4.909e+07 1.55e+08 0.317 0.751 -2.54e+08 3.53e+08\nx904 -4.646e+07 1.43e+08 -0.324 0.746 -3.28e+08 2.35e+08\nx905 8.272e+06 1.56e+08 0.053 0.958 -2.98e+08 3.15e+08\nx906 -3.026e+08 1.59e+08 -1.904 0.057 -6.14e+08 8.9e+06\nx907 -7.922e+07 2.84e+08 -0.279 0.780 -6.36e+08 4.77e+08\nx908 -1.382e+09 2.59e+08 -5.339 0.000 -1.89e+09 -8.75e+08\nx909 -1.34e+09 2.5e+08 -5.365 0.000 -1.83e+09 -8.51e+08\nx910 3.445e+08 1.37e+08 2.522 0.012 7.68e+07 6.12e+08\nx911 -3.685e+08 1.19e+08 -3.098 0.002 -6.02e+08 -1.35e+08\nx912 -1.013e+09 1.7e+08 -5.971 0.000 -1.35e+09 -6.8e+08\nx913 -1.81e+08 1.64e+08 -1.107 0.268 -5.02e+08 1.4e+08\nx914 -1.385e+09 1.39e+08 -9.934 0.000 -1.66e+09 -1.11e+09\nx915 -7.141e+08 1.75e+08 -4.091 0.000 -1.06e+09 -3.72e+08\nx916 -1.118e+09 1.8e+08 -6.219 0.000 -1.47e+09 -7.66e+08\nx917 -1.554e+09 1.45e+08 -10.704 0.000 -1.84e+09 -1.27e+09\nx918 -6.445e+08 1.78e+08 -3.622 0.000 -9.93e+08 -2.96e+08\nx919 -3.114e+08 1.21e+08 -2.564 0.010 -5.49e+08 -7.34e+07\nx920 -2.941e+08 1.28e+08 -2.295 0.022 -5.45e+08 -4.29e+07\nx921 -3.185e+08 1.69e+08 -1.881 0.060 -6.5e+08 1.33e+07\nx922 -9.888e+08 1.5e+08 -6.584 0.000 -1.28e+09 -6.94e+08\nx923 -3.773e+08 1.4e+08 -2.695 0.007 -6.52e+08 -1.03e+08\nx924 -2.53e+08 1.58e+08 -1.601 0.109 -5.63e+08 5.66e+07\nx925 3.556e+08 1.33e+08 2.674 0.007 9.5e+07 6.16e+08\nx926 -8.5e+08 2.09e+08 -4.062 0.000 -1.26e+09 -4.4e+08\nx927 -1.173e+09 1.41e+08 -8.292 0.000 -1.45e+09 -8.96e+08\nx928 -4.775e+08 1.7e+08 -2.809 0.005 -8.11e+08 -1.44e+08\nx929 -1.042e+09 1.57e+08 -6.631 0.000 -1.35e+09 -7.34e+08\nx930 -2.024e+07 1.15e+08 -0.176 0.860 -2.46e+08 2.05e+08\nx931 2.831e+08 1.37e+08 2.067 0.039 1.46e+07 5.52e+08\nx932 2.289e+09 1.39e+08 16.476 0.000 2.02e+09 2.56e+09\nx933 -1.125e+09 1.54e+08 -7.302 0.000 -1.43e+09 -8.23e+08\nx934 -5.736e+08 1.38e+08 -4.167 0.000 -8.43e+08 -3.04e+08\nx935 1.741e+08 1.36e+08 1.283 0.199 -9.19e+07 4.4e+08\nx936 -3.256e+08 1.62e+08 -2.011 0.044 -6.43e+08 -8.25e+06\nx937 3.673e+08 1.2e+08 3.069 0.002 1.33e+08 6.02e+08\nx938 3.513e+08 1.14e+08 3.074 0.002 1.27e+08 5.75e+08\nx939 -5.296e+07 1.17e+08 -0.451 0.652 -2.83e+08 1.77e+08\nx940 -1.102e+09 1.28e+08 -8.597 0.000 -1.35e+09 -8.51e+08\nx941 1.013e+08 1.05e+08 0.968 0.333 -1.04e+08 3.06e+08\nx942 2.434e+08 1.1e+08 2.210 0.027 2.75e+07 4.59e+08\nx943 8.156e+08 1.14e+08 7.130 0.000 5.91e+08 1.04e+09\nx944 3.166e+08 1.22e+08 2.585 0.010 7.66e+07 5.57e+08\nx945 3.166e+08 1.19e+08 2.659 0.008 8.32e+07 5.5e+08\nx946 -2.487e+08 1.18e+08 -2.104 0.035 -4.8e+08 -1.7e+07\nx947 -2.191e+08 1.61e+08 -1.361 0.174 -5.35e+08 9.66e+07\nx948 -5.701e+06 1.09e+08 -0.053 0.958 -2.18e+08 2.07e+08\nx949 -5.979e+08 1.04e+08 -5.759 0.000 -8.01e+08 -3.94e+08\nx950 -3.891e+08 1.12e+08 -3.482 0.000 -6.08e+08 -1.7e+08\nx951 3.304e+08 1.24e+08 2.661 0.008 8.71e+07 5.74e+08\nx952 -1.36e+08 1.23e+08 -1.102 0.271 -3.78e+08 1.06e+08\nx953 -4.514e+08 1.13e+08 -4.009 0.000 -6.72e+08 -2.31e+08\nx954 -7.303e+07 1.18e+08 -0.618 0.537 -3.05e+08 1.59e+08\nx955 1.073e+09 1.13e+08 9.491 0.000 8.52e+08 1.29e+09\nx956 -6.219e+08 1.22e+08 -5.118 0.000 -8.6e+08 -3.84e+08\nx957 -4.771e+08 1.09e+08 -4.365 0.000 -6.91e+08 -2.63e+08\nx958 2.704e+06 1.32e+08 0.021 0.984 -2.55e+08 2.61e+08\nx959 -5.252e+08 1.32e+08 -3.987 0.000 -7.83e+08 -2.67e+08\nx960 4.012e+08 1.08e+08 3.718 0.000 1.9e+08 6.13e+08\nx961 -5.694e+08 1.21e+08 -4.720 0.000 -8.06e+08 -3.33e+08\nx962 -4.558e+08 1.24e+08 -3.684 0.000 -6.98e+08 -2.13e+08\nx963 -2.236e+07 1.18e+08 -0.189 0.850 -2.54e+08 2.09e+08\nx964 9.945e+07 1.21e+08 0.820 0.412 -1.38e+08 3.37e+08\nx965 1.621e+08 1.12e+08 1.449 0.147 -5.72e+07 3.81e+08\nx966 -4.079e+07 1.48e+08 -0.275 0.783 -3.32e+08 2.5e+08\nx967 -9.519e+08 3.33e+08 -2.862 0.004 -1.6e+09 -3e+08\nx968 1.753e+08 1.31e+08 1.340 0.180 -8.12e+07 4.32e+08\nx969 -7.499e+07 1.23e+08 -0.610 0.542 -3.16e+08 1.66e+08\nx970 1.093e+08 1.36e+08 0.806 0.421 -1.57e+08 3.75e+08\nx971 -9.928e+08 1.34e+08 -7.391 0.000 -1.26e+09 -7.3e+08\nx972 2.867e+08 1.5e+08 1.916 0.055 -6.6e+06 5.8e+08\nx973 -9.151e+08 1.32e+08 -6.915 0.000 -1.17e+09 -6.56e+08\nx974 -2.14e+08 1.16e+08 -1.844 0.065 -4.41e+08 1.34e+07\nx975 5.182e+08 1.11e+08 4.670 0.000 3.01e+08 7.36e+08\nx976 1.767e+08 1.13e+08 1.568 0.117 -4.42e+07 3.98e+08\nx977 3.113e+07 1.08e+08 0.287 0.774 -1.81e+08 2.43e+08\nx978 4.859e+08 1.04e+08 4.661 0.000 2.82e+08 6.9e+08\nx979 2.051e+08 1.27e+08 1.621 0.105 -4.3e+07 4.53e+08\nx980 -2.86e+08 1.03e+08 -2.782 0.005 -4.88e+08 -8.45e+07\nx981 -4.267e+08 1.25e+08 -3.415 0.001 -6.72e+08 -1.82e+08\nx982 -6.123e+08 1.25e+08 -4.904 0.000 -8.57e+08 -3.68e+08\nx983 1.547e+08 1.06e+08 1.455 0.146 -5.37e+07 3.63e+08\nx984 5.094e+08 1.34e+08 3.806 0.000 2.47e+08 7.72e+08\nx985 -1.709e+08 1.14e+08 -1.503 0.133 -3.94e+08 5.2e+07\nx986 -2.332e+07 1.45e+08 -0.161 0.872 -3.08e+08 2.61e+08\nx987 9.397e+07 1.14e+08 0.826 0.409 -1.29e+08 3.17e+08\nx988 -2.036e+08 1.18e+08 -1.722 0.085 -4.35e+08 2.82e+07\nx989 -4.533e+08 1.2e+08 -3.783 0.000 -6.88e+08 -2.18e+08\nx990 -4.448e+08 1.23e+08 -3.604 0.000 -6.87e+08 -2.03e+08\nx991 5.95e+07 2.71e+08 0.219 0.826 -4.72e+08 5.91e+08\nx992 -2.051e+08 1.52e+08 -1.347 0.178 -5.03e+08 9.33e+07\nx993 9.67e+07 3.53e+08 0.274 0.784 -5.96e+08 7.89e+08\nx994 2.802e+08 1.45e+08 1.936 0.053 -3.41e+06 5.64e+08\nx995 1.675e+08 1.25e+08 1.342 0.180 -7.71e+07 4.12e+08\nx996 6.343e+07 1.16e+08 0.547 0.584 -1.64e+08 2.91e+08\nx997 3.347e+08 1.15e+08 2.904 0.004 1.09e+08 5.61e+08\nx998 -1.022e+08 1.3e+08 -0.784 0.433 -3.57e+08 1.53e+08\nx999 -4.247e+07 1.06e+08 -0.401 0.688 -2.5e+08 1.65e+08\nx1000 -2.419e+07 1.35e+08 -0.179 0.858 -2.9e+08 2.41e+08\nx1001 -2.759e+08 1.25e+08 -2.211 0.027 -5.21e+08 -3.14e+07\nx1002 1.103e+07 1.24e+08 0.089 0.929 -2.33e+08 2.55e+08\nx1003 -5.547e+07 1.16e+08 -0.476 0.634 -2.84e+08 1.73e+08\nx1004 7.45e+07 1.17e+08 0.637 0.524 -1.55e+08 3.04e+08\nx1005 5.772e+08 1.33e+08 4.340 0.000 3.17e+08 8.38e+08\nx1006 -4.188e+08 1.26e+08 -3.324 0.001 -6.66e+08 -1.72e+08\nx1007 1.16e+08 1.35e+08 0.857 0.392 -1.49e+08 3.81e+08\nx1008 5.392e+08 5.07e+06 106.360 0.000 5.29e+08 5.49e+08\nx1009 2.019e+07 4.76e+06 4.238 0.000 1.09e+07 2.95e+07\nx1010 5.373e+07 5.01e+06 10.714 0.000 4.39e+07 6.36e+07\nx1011 5.079e+07 4.66e+06 10.905 0.000 4.17e+07 5.99e+07\nx1012 1.683e+08 2.61e+07 6.441 0.000 1.17e+08 2.2e+08\nx1013 -2.963e+07 2.73e+07 -1.084 0.279 -8.32e+07 2.4e+07\nx1014 -8.384e+07 1.33e+07 -6.284 0.000 -1.1e+08 -5.77e+07\nx1015 3.274e+07 2.22e+07 1.473 0.141 -1.08e+07 7.63e+07\nx1016 5.119e+08 2.93e+07 17.463 0.000 4.54e+08 5.69e+08\nx1017 -1.126e+08 7.3e+06 -15.427 0.000 -1.27e+08 -9.83e+07\nx1018 1.94e+07 8.72e+06 2.226 0.026 2.32e+06 3.65e+07\nx1019 -2.358e+07 8.86e+06 -2.661 0.008 -4.1e+07 -6.21e+06\nx1020 4.145e+07 1.02e+07 4.067 0.000 2.15e+07 6.14e+07\nx1021 2.575e+07 1.44e+07 1.789 0.074 -2.46e+06 5.4e+07\nx1022 4.294e+07 1.54e+07 2.786 0.005 1.27e+07 7.31e+07\nx1023 5.88e+07 1.43e+07 4.111 0.000 3.08e+07 8.68e+07\nx1024 5.657e+07 1.94e+07 2.921 0.003 1.86e+07 9.45e+07\nx1025 1.004e+09 3e+07 33.442 0.000 9.45e+08 1.06e+09\nx1026 3.192e+08 3.05e+07 10.466 0.000 2.59e+08 3.79e+08\nx1027 3.091e+08 3.78e+07 8.175 0.000 2.35e+08 3.83e+08\nx1028 4.082e+08 3.77e+07 10.827 0.000 3.34e+08 4.82e+08\nx1029 4.628e+07 2.73e+07 1.693 0.090 -7.28e+06 9.98e+07\nx1030 3.935e+08 3.36e+07 11.714 0.000 3.28e+08 4.59e+08\nx1031 4.107e+08 3.25e+07 12.644 0.000 3.47e+08 4.74e+08\nx1032 4.835e+08 3.34e+07 14.483 0.000 4.18e+08 5.49e+08\nx1033 8.911e+07 2.81e+07 3.174 0.002 3.41e+07 1.44e+08\nx1034 1.273e+08 3.27e+07 3.898 0.000 6.33e+07 1.91e+08\nx1035 4.684e+08 3.09e+07 15.162 0.000 4.08e+08 5.29e+08\nx1036 4.496e+08 4e+07 11.249 0.000 3.71e+08 5.28e+08\nx1037 -4.268e+07 2.92e+07 -1.463 0.144 -9.99e+07 1.45e+07\nx1038 9.127e+08 3.51e+07 26.033 0.000 8.44e+08 9.81e+08\nx1039 4.184e+08 3.36e+07 12.437 0.000 3.52e+08 4.84e+08\nx1040 1.194e+09 3.51e+07 34.038 0.000 1.13e+09 1.26e+09\nx1041 2.706e+08 5.89e+07 4.594 0.000 1.55e+08 3.86e+08\nx1042 -1.24e+09 9.09e+07 -13.640 0.000 -1.42e+09 -1.06e+09\nx1043 5.744e+07 3.78e+07 1.518 0.129 -1.67e+07 1.32e+08\nx1044 -6.11e+07 3.9e+07 -1.569 0.117 -1.37e+08 1.52e+07\nx1045 3.345e+08 4.69e+07 7.134 0.000 2.43e+08 4.26e+08\nx1046 9.792e+06 3.92e+07 0.250 0.803 -6.7e+07 8.66e+07\nx1047 -4.255e+07 3.22e+07 -1.321 0.187 -1.06e+08 2.06e+07\nx1048 2.031e+08 3.75e+07 5.422 0.000 1.3e+08 2.77e+08\nx1049 3.857e+08 3.23e+07 11.937 0.000 3.22e+08 4.49e+08\nx1050 -6.657e+08 2.65e+07 -25.133 0.000 -7.18e+08 -6.14e+08\nx1051 -3.047e+07 4.05e+07 -0.753 0.452 -1.1e+08 4.89e+07\nx1052 -1.282e+08 3.39e+07 -3.778 0.000 -1.95e+08 -6.17e+07\nx1053 1.428e+09 2.7e+07 52.790 0.000 1.37e+09 1.48e+09\nx1054 2.236e+09 2.8e+07 79.807 0.000 2.18e+09 2.29e+09\nx1055 1.97e+08 5.67e+07 3.475 0.001 8.59e+07 3.08e+08\nx1056 4.443e+07 3.85e+07 1.155 0.248 -3.1e+07 1.2e+08\nx1057 3.695e+08 2.85e+07 12.986 0.000 3.14e+08 4.25e+08\nx1058 2.807e+08 4.47e+07 6.275 0.000 1.93e+08 3.68e+08\nx1059 -1.811e+08 2.86e+07 -6.332 0.000 -2.37e+08 -1.25e+08\nx1060 1.116e+08 3.13e+07 3.565 0.000 5.02e+07 1.73e+08\nx1061 1.179e+09 2.98e+07 39.561 0.000 1.12e+09 1.24e+09\nx1062 3.221e+08 3.48e+07 9.246 0.000 2.54e+08 3.9e+08\nx1063 -2.644e+08 3.07e+07 -8.624 0.000 -3.24e+08 -2.04e+08\nx1064 6.351e+08 4.31e+07 14.749 0.000 5.51e+08 7.19e+08\nx1065 4.577e+07 3.74e+07 1.222 0.222 -2.76e+07 1.19e+08\nx1066 -6.426e+07 3.34e+07 -1.923 0.055 -1.3e+08 1.25e+06\nx1067 1.207e+09 4.3e+07 28.045 0.000 1.12e+09 1.29e+09\nx1068 -1.993e+08 2.99e+07 -6.670 0.000 -2.58e+08 -1.41e+08\nx1069 -7.151e+07 4.52e+07 -1.584 0.113 -1.6e+08 1.7e+07\n==============================================================================\nOmnibus: 116172.839 Durbin-Watson: 2.007\nProb(Omnibus): 0.000 Jarque-Bera (JB): 85264506.370\nSkew: 6.589 Prob(JB): 0.00\nKurtosis: 152.700 Cond. No. 1.25e+17\n==============================================================================\n\nWarnings:\n[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n[2] The smallest eigenvalue is 4.28e-29. This might indicate that there are\nstrong multicollinearity problems or that the design matrix is singular.\n"
]
]
]
| [
"code"
]
| [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
]
|
cb5ebf7412c4eb5e82a5e5eaf0775c8b0847f211 | 70,294 | ipynb | Jupyter Notebook | tackling_missing_data_dropping.ipynb | PacktPublishing/Python-for-Data-Analysis-step-by-step-with-projects- | d4303844d927f7bd61e48b71a9d272f426dfba0e | [
"MIT"
]
| 6 | 2021-12-19T00:45:37.000Z | 2022-03-26T05:11:59.000Z | tackling_missing_data_dropping.ipynb | PacktPublishing/Python-for-Data-Analysis-step-by-step-with-projects- | d4303844d927f7bd61e48b71a9d272f426dfba0e | [
"MIT"
]
| null | null | null | tackling_missing_data_dropping.ipynb | PacktPublishing/Python-for-Data-Analysis-step-by-step-with-projects- | d4303844d927f7bd61e48b71a9d272f426dfba0e | [
"MIT"
]
| 10 | 2021-12-13T16:54:04.000Z | 2022-03-30T18:12:27.000Z | 40.283095 | 92 | 0.343415 | [
[
[
"# Dropping by rows",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nwdi = pd.read_pickle('wdi.pkl')",
"_____no_output_____"
],
[
"wdi.dropna()",
"_____no_output_____"
],
[
"wdi.dropna(thresh=18)",
"_____no_output_____"
],
[
"wdi_no_missing_rows = wdi.dropna()\nwdi_no_missing_rows",
"_____no_output_____"
],
[
"wdi_no_missing_rows.info()",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 115 entries, 217 to 433\nData columns (total 19 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 country_name 115 non-null object \n 1 access_to_electricity_pct 115 non-null float64\n 2 atms_per_100000 115 non-null float64\n 3 compulsory_education_years 115 non-null float64\n 4 health_expenditure_pct_of_gdp 115 non-null float64\n 5 gdp_per_capita_usd 115 non-null float64\n 6 gdp_per_capita_ppp 115 non-null float64\n 7 life_expectancy_female 115 non-null float64\n 8 life_expectancy_male 115 non-null float64\n 9 life_expectancy 115 non-null float64\n 10 population_density 115 non-null float64\n 11 population 115 non-null float64\n 12 alcohol_consumption_per_capita 115 non-null float64\n 13 unemployment_rate_female 115 non-null float64\n 14 unemployment_rate_male 115 non-null float64\n 15 unemployment_rate 115 non-null float64\n 16 year 115 non-null int64 \n 17 country_category 115 non-null object \n 18 is_region 115 non-null int64 \ndtypes: float64(15), int64(2), object(2)\nmemory usage: 18.0+ KB\n"
],
[
"wdi.nunique()",
"_____no_output_____"
],
[
"wdi_no_missing_rows.nunique()",
"_____no_output_____"
]
],
[
[
"# Dropping by columns",
"_____no_output_____"
]
],
[
[
"wdi.dropna(axis=1)",
"_____no_output_____"
],
[
"wdi.dropna(axis=1, thresh=300).info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 434 entries, 0 to 433\nData columns (total 17 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 country_name 434 non-null object \n 1 access_to_electricity_pct 434 non-null float64\n 2 atms_per_100000 406 non-null float64\n 3 compulsory_education_years 412 non-null float64\n 4 health_expenditure_pct_of_gdp 427 non-null float64\n 5 gdp_per_capita_usd 434 non-null float64\n 6 gdp_per_capita_ppp 434 non-null float64\n 7 life_expectancy_female 434 non-null float64\n 8 life_expectancy_male 434 non-null float64\n 9 life_expectancy 434 non-null float64\n 10 population_density 432 non-null float64\n 11 population 434 non-null float64\n 12 unemployment_rate_female 434 non-null float64\n 13 unemployment_rate_male 434 non-null float64\n 14 unemployment_rate 434 non-null float64\n 15 year 434 non-null int64 \n 16 is_region 434 non-null int64 \ndtypes: float64(14), int64(2), object(1)\nmemory usage: 57.8+ KB\n"
],
[
"wdi.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 434 entries, 0 to 433\nData columns (total 19 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 country_name 434 non-null object \n 1 access_to_electricity_pct 434 non-null float64\n 2 atms_per_100000 406 non-null float64\n 3 compulsory_education_years 412 non-null float64\n 4 health_expenditure_pct_of_gdp 427 non-null float64\n 5 gdp_per_capita_usd 434 non-null float64\n 6 gdp_per_capita_ppp 434 non-null float64\n 7 life_expectancy_female 434 non-null float64\n 8 life_expectancy_male 434 non-null float64\n 9 life_expectancy 434 non-null float64\n 10 population_density 432 non-null float64\n 11 population 434 non-null float64\n 12 alcohol_consumption_per_capita 215 non-null float64\n 13 unemployment_rate_female 434 non-null float64\n 14 unemployment_rate_male 434 non-null float64\n 15 unemployment_rate 434 non-null float64\n 16 year 434 non-null int64 \n 17 country_category 282 non-null object \n 18 is_region 434 non-null int64 \ndtypes: float64(15), int64(2), object(2)\nmemory usage: 64.5+ KB\n"
]
]
]
| [
"markdown",
"code",
"markdown",
"code"
]
| [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
]
|
cb5ec47a537f0f0b0812ade12d5c5c02be67a509 | 16,771 | ipynb | Jupyter Notebook | exercise1-knn/psyc272-cava-knn-username.ipynb | psyc230/cava_exercises | fe7d0107db214e04aa1ed30996373a894e47531f | [
"BSD-2-Clause"
]
| 1 | 2019-10-29T01:31:27.000Z | 2019-10-29T01:31:27.000Z | exercise1-knn/psyc272-cava-knn-username.ipynb | psyc230/cava_exercises | fe7d0107db214e04aa1ed30996373a894e47531f | [
"BSD-2-Clause"
]
| 3 | 2021-02-02T22:11:28.000Z | 2022-01-13T03:03:36.000Z | exercise1-knn/psyc272-cava-knn-username.ipynb | psyc230/cava_exercises | fe7d0107db214e04aa1ed30996373a894e47531f | [
"BSD-2-Clause"
]
| 2 | 2019-10-01T00:48:23.000Z | 2019-10-22T01:32:46.000Z | 35.381857 | 311 | 0.583865 | [
[
[
"# k-Nearest Neighbor (kNN) exercise\n\n#### This assignment was adapted from Stanford's CS231n course: http://cs231n.stanford.edu/\n\nThe kNN classifier consists of two stages:\n\n- During training, the classifier takes the training data and simply remembers it\n- During testing, kNN classifies every test image by comparing to all training images and transfering the labels of the k most similar training examples\n- The value of k is cross-validated\n\nIn this exercise you will implement these steps and understand the basic Image Classification pipeline, cross-validation, and gain proficiency in writing efficient, vectorized code.\n\n### YOUR NAME: YOUR_NAME\n\n### List of collaborators (optional): N/A",
"_____no_output_____"
]
],
[
[
"# Run some setup code for this notebook.\n\nimport random\nimport numpy as np\nfrom psyc272cava.data_utils import load_CIFAR10\nimport matplotlib.pyplot as plt\n\n# This is a bit of magic to make matplotlib figures appear inline in the notebook\n# rather than in a new window.\n%matplotlib inline\nplt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots\nplt.rcParams['image.interpolation'] = 'nearest'\nplt.rcParams['image.cmap'] = 'gray'\n\n# Some more magic so that the notebook will reload external python modules;\n# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython\n%load_ext autoreload\n%autoreload 2",
"_____no_output_____"
],
[
"# Information about the CIFAR-10 dataset: https://www.cs.toronto.edu/~kriz/cifar.html\n\n# Load the raw CIFAR-10 data.\ncifar10_dir = 'psyc272cava/datasets/cifar-10-batches-py'\n\n# Cleaning up variables to prevent loading data multiple times (which may cause memory issue)\ntry:\n del X_train, y_train\n del X_test, y_test\n print('Clear previously loaded data.')\nexcept:\n pass\n\nX_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir)\n\n# As a sanity check, we print out the size of the training and test data.\nprint('Training data shape: ', X_train.shape)\nprint('Training labels shape: ', y_train.shape)\nprint('Test data shape: ', X_test.shape)\nprint('Test labels shape: ', y_test.shape)",
"_____no_output_____"
],
[
"# Visualize some examples from the dataset.\n# We show a few examples of training images from each class.\nclasses = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\nnum_classes = len(classes)\nsamples_per_class = 10\nfor y, cls in enumerate(classes):\n idxs = np.flatnonzero(y_train == y)\n idxs = np.random.choice(idxs, samples_per_class, replace=False)\n for i, idx in enumerate(idxs):\n plt_idx = i * num_classes + y + 1\n plt.subplot(samples_per_class, num_classes, plt_idx)\n plt.imshow(X_train[idx].astype('uint8'))\n plt.axis('off')\n if i == 0:\n plt.title(cls)\nplt.show()",
"_____no_output_____"
],
[
"# Subsample the data for more efficient code execution in this exercise\nnum_training = 5000\nmask = list(range(num_training))\nX_train = X_train[mask]\ny_train = y_train[mask]\n\nnum_test = 500\nmask = list(range(num_test))\nX_test = X_test[mask]\ny_test = y_test[mask]\n\n# Reshape the image data into rows\nX_train = np.reshape(X_train, (X_train.shape[0], -1))\nX_test = np.reshape(X_test, (X_test.shape[0], -1))\nprint(X_train.shape, X_test.shape)",
"_____no_output_____"
],
[
"from psyc272cava.classifiers import KNearestNeighbor\n\n# Create a kNN classifier instance. \n# Remember that training a kNN classifier is a noop: \n# the Classifier simply remembers the data and does no further processing \nclassifier = KNearestNeighbor()\nclassifier.train(X_train, y_train)",
"_____no_output_____"
]
],
[
[
"We would now like to classify the test data with the kNN classifier. Recall that we can break down this process into two steps: \n\n1. First we must compute the distances between all test examples and all train examples. \n2. Given these distances, for each test example we find the k nearest examples and have them vote for the label\n\nLets begin with computing the distance matrix between all training and test examples. For example, if there are **Ntr** training examples and **Nte** test examples, this stage should result in a **Nte x Ntr** matrix where each element (i,j) is the distance between the i-th test and j-th train example.\n\n**Note: For the three distance computations that we require you to implement in this notebook, you may not use the np.linalg.norm() function that numpy provides.**\n\nFirst, open `psyc272cava/classifiers/k_nearest_neighbor.py` and implement the function `compute_distances_two_loops` that uses a (very inefficient) double loop over all pairs of (test, train) examples and computes the distance matrix one element at a time.",
"_____no_output_____"
]
],
[
[
"# Open psyc272cava/classifiers/k_nearest_neighbor.py and implement\n# compute_distances_two_loops.\n\n# Test your implementation:\ndists = classifier.compute_distances_two_loops(X_test)\nprint(dists.shape)",
"_____no_output_____"
],
[
"# We can visualize the distance matrix: each row is a single test example and\n# its distances to training examples\nplt.imshow(dists, interpolation='none')\nplt.show()",
"_____no_output_____"
],
[
"# Now implement the function predict_labels and run the code below:\n# We use k = 1 (which is Nearest Neighbor).\ny_test_pred = classifier.predict_labels(dists, k=1)\n\n# Compute and print the fraction of correctly predicted examples\nnum_correct = np.sum(y_test_pred == y_test)\naccuracy = float(num_correct) / num_test\nprint('Got %d / %d correct => accuracy: %f' % (num_correct, num_test, accuracy))",
"_____no_output_____"
]
],
[
[
"You should expect to see approximately `27%` accuracy. Now lets try out a larger `k`, say `k = 5`:",
"_____no_output_____"
]
],
[
[
"y_test_pred = classifier.predict_labels(dists, k=5)\nnum_correct = np.sum(y_test_pred == y_test)\naccuracy = float(num_correct) / num_test\nprint('Got %d / %d correct => accuracy: %f' % (num_correct, num_test, accuracy))",
"_____no_output_____"
]
],
[
[
"You should expect to see a slightly better performance than with `k = 1`.",
"_____no_output_____"
]
],
[
[
"# Now lets speed up distance matrix computation by using partial vectorization\n# with one loop. Implement the function compute_distances_one_loop and run the\n# code below:\ndists_one = classifier.compute_distances_one_loop(X_test)\n\n# To ensure that our vectorized implementation is correct, we make sure that it\n# agrees with the naive implementation. There are many ways to decide whether\n# two matrices are similar; one of the simplest is the Frobenius norm. In case\n# you haven't seen it before, the Frobenius norm of two matrices is the square\n# root of the squared sum of differences of all elements; in other words, reshape\n# the matrices into vectors and compute the Euclidean distance between them.\ndifference = np.linalg.norm(dists - dists_one, ord='fro')\nprint('One loop difference was: %f' % (difference, ))\nif difference < 0.001:\n print('Good! The distance matrices are the same')\nelse:\n print('Uh-oh! The distance matrices are different')",
"_____no_output_____"
],
[
"# Now implement the fully vectorized version inside compute_distances_no_loops\n# and run the code\ndists_two = classifier.compute_distances_no_loops(X_test)\n\n# check that the distance matrix agrees with the one we computed before:\ndifference = np.linalg.norm(dists - dists_two, ord='fro')\nprint('No loop difference was: %f' % (difference, ))\nif difference < 0.001:\n print('Good! The distance matrices are the same')\nelse:\n print('Uh-oh! The distance matrices are different')",
"_____no_output_____"
],
[
"# Let's compare how fast the implementations are\ndef time_function(f, *args):\n \"\"\"\n Call a function f with args and return the time (in seconds) that it took to execute.\n \"\"\"\n import time\n tic = time.time()\n f(*args)\n toc = time.time()\n return toc - tic\n\ntwo_loop_time = time_function(classifier.compute_distances_two_loops, X_test)\nprint('Two loop version took %f seconds' % two_loop_time)\n\none_loop_time = time_function(classifier.compute_distances_one_loop, X_test)\nprint('One loop version took %f seconds' % one_loop_time)\n\nno_loop_time = time_function(classifier.compute_distances_no_loops, X_test)\nprint('No loop version took %f seconds' % no_loop_time)\n\n# You should see significantly faster performance with the fully vectorized implementation!\n\n# NOTE: depending on what machine you're using, \n# you might not see a speedup when you go from two loops to one loop, \n# and might even see a slow-down.",
"_____no_output_____"
]
],
[
[
"### Cross-validation\n\nWe have implemented the k-Nearest Neighbor classifier but we set the value k = 5 arbitrarily. We will now determine the best value of this hyperparameter with cross-validation.",
"_____no_output_____"
]
],
[
[
"num_folds = 5\nk_choices = [1, 3, 5, 8, 10, 12, 15, 20, 50, 100]\n\nX_train_folds = []\ny_train_folds = []\n################################################################################\n# TODO: #\n# Split up the training data into folds. After splitting, X_train_folds and #\n# y_train_folds should each be lists of length num_folds, where #\n# y_train_folds[i] is the label vector for the points in X_train_folds[i]. #\n# Hint: Look up the numpy array_split function. #\n################################################################################\n# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n\npass\n\n# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n\n# A dictionary holding the accuracies for different values of k that we find\n# when running cross-validation. After running cross-validation,\n# k_to_accuracies[k] should be a list of length num_folds giving the different\n# accuracy values that we found when using that value of k.\n\nk_to_accuracies = {}\nnum_split = X_train.shape[0] / num_folds\nacc_k = np.zeros((len(k_choices), num_folds), dtype=np.float)\n\n\n################################################################################\n# TODO: #\n# Perform k-fold cross validation to find the best value of k. For each #\n# possible value of k, run the k-nearest-neighbor algorithm num_folds times, #\n# where in each case you use all but one of the folds as training data and the #\n# last fold as a validation set. Store the accuracies for all fold and all #\n# values of k in the k_to_accuracies dictionary. #\n################################################################################\n# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n\npass\n\n# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n\n# Print out the computed accuracies\nfor k in sorted(k_to_accuracies):\n for accuracy in k_to_accuracies[k]:\n print('k = %d, accuracy = %f' % (k, accuracy))",
"_____no_output_____"
],
[
"# plot the raw observations\nfor k in k_choices:\n accuracies = k_to_accuracies[k]\n plt.scatter([k] * len(accuracies), accuracies)\n\n# plot the trend line with error bars that correspond to standard deviation\naccuracies_mean = np.array([np.mean(v) for k,v in sorted(k_to_accuracies.items())])\naccuracies_std = np.array([np.std(v) for k,v in sorted(k_to_accuracies.items())])\nplt.errorbar(k_choices, accuracies_mean, yerr=accuracies_std)\nplt.title('Cross-validation on k')\nplt.xlabel('k')\nplt.ylabel('Cross-validation accuracy')\nplt.show()",
"_____no_output_____"
],
[
"# Based on the cross-validation results above, choose the best value for k, \n# retrain the classifier using all the training data, and test it on the test\n# data. You should be able to get above 28% accuracy on the test data.\nbest_k = 9\n\nclassifier = KNearestNeighbor()\nclassifier.train(X_train, y_train)\ny_test_pred = classifier.predict(X_test, k=best_k)\n\n# Compute and display the accuracy\nnum_correct = np.sum(y_test_pred == y_test)\naccuracy = float(num_correct) / num_test\nprint('Got %d / %d correct => accuracy: %f' % (num_correct, num_test, accuracy))",
"_____no_output_____"
]
]
]
| [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
]
| [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
]
|
cb5ecffd33a1f9364d6b7e936eeef93bf8cb52a2 | 103,936 | ipynb | Jupyter Notebook | Laboratorios/C2_machine_learning/04_analisis_no_supervisado/laboratorio_09.ipynb | martinsaieh/mat281_portfolio | 01950ad119cd7d56d9a72d105b1267738159798f | [
"MIT"
]
| null | null | null | Laboratorios/C2_machine_learning/04_analisis_no_supervisado/laboratorio_09.ipynb | martinsaieh/mat281_portfolio | 01950ad119cd7d56d9a72d105b1267738159798f | [
"MIT"
]
| null | null | null | Laboratorios/C2_machine_learning/04_analisis_no_supervisado/laboratorio_09.ipynb | martinsaieh/mat281_portfolio | 01950ad119cd7d56d9a72d105b1267738159798f | [
"MIT"
]
| null | null | null | 51.709453 | 31,176 | 0.502376 | [
[
[
"<img src=\"images/usm.jpg\" width=\"480\" height=\"240\" align=\"left\"/>",
"_____no_output_____"
],
[
"# MAT281 - Laboratorio N°03\n\n## Objetivos del laboratorio\n\n* Reforzar conceptos básicos de análisis no supervisado.",
"_____no_output_____"
],
[
"## Contenidos\n\n* [Problema 01](#p1)\n",
"_____no_output_____"
],
[
"<a id='p1'></a>\n## I.- Problema 01\n\n\n<img src=\"https://freedesignfile.com/upload/2013/06/Car-logos-1.jpg\" width=\"360\" height=\"360\" align=\"center\"/>\n\n\nEl conjunto de datos se denomina `vehiculos_procesado_con_grupos.csv`, el cual contine algunas de las características más importante de un vehículo.\n\nEn este ejercicio se tiene como objetivo, es poder clasificar los distintos vehículos basados en las cracterísticas que se presentan a continuación. La dificultad de este ejercicio radíca en que ahora tenemos variables numéricas y variables categóricas.\n\nLo primero será cargar el conjunto de datos:",
"_____no_output_____"
]
],
[
[
"import os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.dummy import DummyClassifier\nfrom sklearn.cluster import KMeans\n\n\n%matplotlib inline\nsns.set_palette(\"deep\", desat=.6)\nsns.set(rc={'figure.figsize':(11.7,8.27)})",
"_____no_output_____"
],
[
"# cargar datos\ndf = pd.read_csv(os.path.join(\"data\",\"vehiculos_procesado_con_grupos.csv\"), sep=\",\")\\\n .drop(\n [\"fabricante\", \n \"modelo\",\n \"transmision\", \n \"traccion\", \n \"clase\", \n \"combustible\",\n \"consumo\"], \n \n axis=1)\n\ndf.head()",
"_____no_output_____"
]
],
[
[
"En este caso, no solo se tienen datos numéricos, sino que también categóricos. Además, tenemos problemas de datos **vacíos (Nan)**. Así que para resolver este problema, seguiremos varios pasos:",
"_____no_output_____"
],
[
"## 1.- Normalizar datos\n\n1. Cree un conjunto de datos con las variables numéricas, además, para cada dato vacía, rellene con el promedio asociado a esa columna. Finalmente, normalize los datos mediante el procesamiento **MinMaxScaler** de **sklearn**.\n\n2.- Cree un conjunto de datos con las variables categóricas , además, transforme de variables numéricas a categóricas ocupando el comando **get_dummies** de pandas ([refrenecia](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.get_dummies.html)). Explique a grande rasgo como se realiza la codificación de variables numéricas a categóricas.\n\n3.- Junte ambos dataset en uno, llamado **df_procesado**. \n",
"_____no_output_____"
],
[
"1.-",
"_____no_output_____"
]
],
[
[
"df.dtypes",
"_____no_output_____"
],
[
"df_numerica = df[['year','desplazamiento', 'cilindros', 'co2','consumo_litros_milla']] ",
"_____no_output_____"
],
[
"df_numerica.isnull().sum()",
"_____no_output_____"
],
[
"df_numerica = df_numerica.fillna(df.mean())",
"_____no_output_____"
],
[
"df_numerica.isnull().sum()",
"_____no_output_____"
],
[
"scaler = MinMaxScaler()\ncolumns = ['year','desplazamiento', 'cilindros', 'co2','consumo_litros_milla']\ndf_numerica[columns] = scaler.fit_transform(df_numerica[columns])\n\ndf_numerica.head()",
"_____no_output_____"
]
],
[
[
"2.-",
"_____no_output_____"
]
],
[
[
"df_categoricas = pd.get_dummies(df[['clase_tipo', 'traccion_tipo', 'transmision_tipo', 'combustible_tipo', \n 'tamano_motor_tipo', 'consumo_tipo', 'co2_tipo']],dummy_na=True)\ndf_categoricas.head()",
"_____no_output_____"
]
],
[
[
"3.-",
"_____no_output_____"
]
],
[
[
"df_procesado = pd.concat([df_numerica, df_categoricas ], axis=1)\ndf_procesado",
"_____no_output_____"
]
],
[
[
"## 2.- Realizar ajuste mediante kmeans\n\nUna vez depurado el conjunto de datos, es momento de aplicar el algoritmo de **kmeans**.\n\n1. Ajuste el modelo de **kmeans** sobre el conjunto de datos, con un total de 8 clusters.\n2. Calcular los cluster y el valor de los centroides.\n3. Realizar que resumas las principales cualidades de cada cluster. Para cada cluster calcule:\n\n a. Valor promedio de las variables numérica.\\\n b. Moda para las variables numericas\n \n ",
"_____no_output_____"
],
[
"1.-",
"_____no_output_____"
]
],
[
[
"kmeans = KMeans(n_clusters=8, random_state=2)\nkmeans = kmeans.fit(df_procesado)",
"_____no_output_____"
]
],
[
[
"2.-",
"_____no_output_____"
]
],
[
[
"centroids = kmeans.cluster_centers_ \n\nclusters = kmeans.labels_ \ndf_procesado[\"cluster\"] = clusters\ndf_procesado[\"cluster\"] = df_procesado[\"cluster\"].astype('category')",
"_____no_output_____"
]
],
[
[
"3.-",
"_____no_output_____"
]
],
[
[
"df_procesado.groupby(['cluster']).mean()",
"_____no_output_____"
],
[
"df_procesado.groupby(['cluster']).agg(pd.Series.mode)",
"_____no_output_____"
]
],
[
[
"## 3.- Elegir Número de cluster\n\nEstime mediante la **regla del codo**, el número de cluster apropiados para el caso.\nPara efectos prácticos, eliga la siguiente secuencia como número de clusters a comparar:\n\n$$[5, 10, 20, 30, 50, 75, 100, 200, 300]$$\n\nUna ve realizado el gráfico, saque sus propias conclusiones del caso.\n",
"_____no_output_____"
]
],
[
[
"clasifiers=[5,10,20,30,50,75,100,200,300]\ninertia=[]\nfor i in clasifiers:\n km = KMeans(n_clusters = i).fit(df_procesado)\n u = km.inertia_\n inertia.append(u)\n \nfig, (ax1) = plt.subplots(1, figsize=(16,6))\nxx = np.arange(len(clasifiers))\nax1.plot(xx, inertia)\nax1.set_xticks(xx)\nax1.set_xticklabels(clasifiers, rotation = 'vertical')\nplt.xlabel('Número de Clusters')\nplt.ylabel('Valor Inertia')\nplt.title('Elbow Curve')\nplt.grid() \nplt.show()",
"_____no_output_____"
]
],
[
[
"De la regla del codo se puede notar que los primeros valores críticos a ser candidatos para el numero de clusters son $10$ o $20$, ya que aquí la gráfica tiene un quiebre considerable.",
"_____no_output_____"
]
]
]
| [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
]
| [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
]
|
cb5ed6e93f4f6c4d33211f1a1a8c66f3083f87bb | 4,068 | ipynb | Jupyter Notebook | Métodos Computacionais em Astronomia/lista2-2/.ipynb_checkpoints/questao1-checkpoint.ipynb | xiaoyongkong/UFRJ | 824e97f4be56e0fc4336b6d5507233b079c9b31b | [
"MIT"
]
| 1 | 2021-03-04T17:46:09.000Z | 2021-03-04T17:46:09.000Z | Métodos Computacionais em Astronomia/lista2-2/.ipynb_checkpoints/questao1-checkpoint.ipynb | xiaoyongkong/UFRJ | 824e97f4be56e0fc4336b6d5507233b079c9b31b | [
"MIT"
]
| null | null | null | Métodos Computacionais em Astronomia/lista2-2/.ipynb_checkpoints/questao1-checkpoint.ipynb | xiaoyongkong/UFRJ | 824e97f4be56e0fc4336b6d5507233b079c9b31b | [
"MIT"
]
| null | null | null | 27.673469 | 137 | 0.393559 | [
[
[
"import numpy as np",
"_____no_output_____"
],
[
"# Leia o arquivo array.dat usando o comando np.loadtxt() e armazene o mesmo como “array_original”\narray_original = np.loadtxt(\"array.dat\")\nprint(array_original)",
"[[ 11. 6. -3. 5. 9. -10. 0. 1. -7. -6. 6. 4. 11. -8.\n -9. 6. -4. 2. 1. 10.]\n [ 5. 3. -1. 0. -9. -6. -4. -6. 1. 10. 5. 5. 1. 1.\n 11. 6. 8. -1. 3. 10.]\n [ 9. 3. 5. 11. 11. 11. 3. 6. 2. 7. 11. 8. -3. 2.\n -9. 7. -10. 10. 2. -1.]\n [ 0. -1. -7. -8. -5. -3. 9. 2. 7. 4. 11. -7. 10. 0.\n 1. 2. 10. 8. 1. -8.]\n [ -3. 3. -8. -4. 6. 9. -4. -2. -7. -1. -9. -5. -9. -3.\n -7. -5. -6. 11. -10. 2.]\n [ 5. -6. -2. 0. 2. -8. -3. -7. 7. -2. -2. -4. -3. -1.\n 8. 10. 4. -2. -3. 2.]]\n"
],
[
"# Defina um novo array como sendo igual a 3a coluna do array_original, e um outro array como sendo a 5a linha do array_original.\nnovo_array = array_original[:,2]\noutro_array = array_original[4]\nprint(novo_array)\nprint()\nprint(outro_array)",
"[-3. -1. 5. -7. -8. -2.]\n\n[ -3. 3. -8. -4. 6. 9. -4. -2. -7. -1. -9. -5. -9. -3.\n -7. -5. -6. 11. -10. 2.]\n"
],
[
"# Defina um novo array com com as colunas pares do array_ogirinal\ncolunas_pares = array_original[:,1::2]\nprint(colunas_pares)",
"[[ 6. 5. -10. 1. -6. 4. -8. 6. 2. 10.]\n [ 3. 0. -6. -6. 10. 5. 1. 6. -1. 10.]\n [ 3. 11. 11. 6. 7. 8. 2. 7. 10. -1.]\n [ -1. -8. -3. 2. 4. -7. 0. 2. 8. -8.]\n [ 3. -4. 9. -2. -1. -5. -3. -5. 11. 2.]\n [ -6. 0. -8. -7. -2. -4. -1. 10. -2. 2.]]\n"
],
[
"# Defina um novo array com as linhas impares do array_original\nlinhas_impares = array_original[0::2]\nprint(linhas_impares)",
"[[ 11. 6. -3. 5. 9. -10. 0. 1. -7. -6. 6. 4. 11. -8.\n -9. 6. -4. 2. 1. 10.]\n [ 9. 3. 5. 11. 11. 11. 3. 6. 2. 7. 11. 8. -3. 2.\n -9. 7. -10. 10. 2. -1.]\n [ -3. 3. -8. -4. 6. 9. -4. -2. -7. -1. -9. -5. -9. -3.\n -7. -5. -6. 11. -10. 2.]]\n"
]
]
]
| [
"code"
]
| [
[
"code",
"code",
"code",
"code",
"code"
]
]
|
cb5ef64dc16d2e14bc54531f8cdee047504e94f4 | 10,050 | ipynb | Jupyter Notebook | 0 Before you start.ipynb | werkaaa/deep-learning-intro-pytorch | 9e7e3bd678084c37ef5933c1d2cfc1da2db200cc | [
"MIT"
]
| null | null | null | 0 Before you start.ipynb | werkaaa/deep-learning-intro-pytorch | 9e7e3bd678084c37ef5933c1d2cfc1da2db200cc | [
"MIT"
]
| 1 | 2018-12-29T12:54:27.000Z | 2018-12-29T12:54:27.000Z | 0 Before you start.ipynb | werkaaa/deep-learning-intro-pytorch | 9e7e3bd678084c37ef5933c1d2cfc1da2db200cc | [
"MIT"
]
| null | null | null | 60.909091 | 216 | 0.691841 | [
[
[
"# Thinking in tensors, writing in PyTorch\n\nA hands-on course by [Piotr Migdał](https://p.migdal.pl) et al. (2019).\n\n[](https://colab.research.google.com/github/stared/thinking-in-tensors-writing-in-pytorch/blob/master/0%20Before%20you%20start.ipynb)\n\n## Notebook 0: Before you start\n\n\nIt is an introduction to deep learning using PyTorch.\n\nMore about it in the description: https://github.com/stared/thinking-in-tensors-writing-in-pytorch\n\nAlso, if you have any problems, please use [GitHub issues](https://github.com/stared/thinking-in-tensors-writing-in-pytorch/issues). \n\n\n### Installation instructions\n\nThe whole course in Jupyter Notebook, an interactive interface for Python 3.\n\nThere are a few ways to run it.\n\n* online, using [Google Colaboratory](https://colab.research.google.com/)\n* locally, using [Anaconda Distribution](https://www.anaconda.com/distribution/#download-section)\n\nOn top of standard scientific libraries to Python (3.5 or higher), we need:\n\n* [PyTorch](https://pytorch.org/)\n* [livelossplot](https://github.com/stared/livelossplot)",
"_____no_output_____"
]
],
[
[
"import torch",
"_____no_output_____"
],
[
"torch.__version__ # should be 1.0.0 or higher",
"_____no_output_____"
],
[
"import livelossplot",
"_____no_output_____"
],
[
"livelossplot.__version__ #should be 0.3.4 or higher",
"_____no_output_____"
],
[
"# if it doesn't work, type\n!pip install livelossplot",
"Requirement already satisfied: livelossplot in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (0.3.4)\nRequirement already satisfied: matplotlib in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from livelossplot) (2.2.2)\nRequirement already satisfied: notebook in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from livelossplot) (5.7.0)\nRequirement already satisfied: numpy>=1.7.1 in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from matplotlib->livelossplot) (1.14.5)\nRequirement already satisfied: cycler>=0.10 in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from matplotlib->livelossplot) (0.10.0)\nRequirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from matplotlib->livelossplot) (2.2.0)\nRequirement already satisfied: python-dateutil>=2.1 in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from matplotlib->livelossplot) (2.7.2)\nRequirement already satisfied: pytz in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from matplotlib->livelossplot) (2018.3)\nRequirement already satisfied: six>=1.10 in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from matplotlib->livelossplot) (1.12.0)\nRequirement already satisfied: kiwisolver>=1.0.1 in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from matplotlib->livelossplot) (1.0.1)\nRequirement already satisfied: jinja2 in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from notebook->livelossplot) (2.10)\nRequirement already satisfied: tornado>=4 in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from notebook->livelossplot) (5.1.1)\nRequirement already satisfied: pyzmq>=17 in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from notebook->livelossplot) (17.1.2)\nRequirement already satisfied: ipython_genutils in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from notebook->livelossplot) (0.2.0)\nRequirement already satisfied: traitlets>=4.2.1 in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from notebook->livelossplot) (4.3.2)\nRequirement already satisfied: jupyter_core>=4.4.0 in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from notebook->livelossplot) (4.4.0)\nRequirement already satisfied: jupyter_client>=5.2.0 in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from notebook->livelossplot) (5.2.3)\nRequirement already satisfied: nbformat in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from notebook->livelossplot) (4.3.0)\nRequirement already satisfied: nbconvert in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from notebook->livelossplot) (5.1.1)\nRequirement already satisfied: ipykernel in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from notebook->livelossplot) (4.10.0)\nRequirement already satisfied: Send2Trash in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from notebook->livelossplot) (1.5.0)\nRequirement already satisfied: terminado>=0.8.1 in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from notebook->livelossplot) (0.8.1)\nRequirement already satisfied: prometheus_client in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from notebook->livelossplot) (0.4.2)\nRequirement already satisfied: setuptools in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from kiwisolver>=1.0.1->matplotlib->livelossplot) (40.6.3)\nRequirement already satisfied: MarkupSafe>=0.23 in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from jinja2->notebook->livelossplot) (1.0)\nRequirement already satisfied: mistune!=0.6 in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from nbconvert->notebook->livelossplot) (0.7.4)\nRequirement already satisfied: pygments in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from nbconvert->notebook->livelossplot) (2.2.0)\nRequirement already satisfied: entrypoints>=0.2.2 in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from nbconvert->notebook->livelossplot) (0.2.2)\nRequirement already satisfied: bleach in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from nbconvert->notebook->livelossplot) (3.0.2)\nRequirement already satisfied: pandocfilters>=1.4.1 in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from nbconvert->notebook->livelossplot) (1.4.1)\nRequirement already satisfied: testpath in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from nbconvert->notebook->livelossplot) (0.3)\nRequirement already satisfied: ipython>=4.0.0 in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from ipykernel->notebook->livelossplot) (6.3.1)\nRequirement already satisfied: webencodings in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from bleach->nbconvert->notebook->livelossplot) (0.5.1)\nRequirement already satisfied: appnope; sys_platform == \"darwin\" in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from ipython>=4.0.0->ipykernel->notebook->livelossplot) (0.1.0)\nRequirement already satisfied: pexpect; sys_platform != \"win32\" in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from ipython>=4.0.0->ipykernel->notebook->livelossplot) (4.5.0)\nRequirement already satisfied: prompt-toolkit<2.0.0,>=1.0.15 in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from ipython>=4.0.0->ipykernel->notebook->livelossplot) (1.0.15)\nRequirement already satisfied: jedi>=0.10 in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from ipython>=4.0.0->ipykernel->notebook->livelossplot) (0.13.3)\nRequirement already satisfied: backcall in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from ipython>=4.0.0->ipykernel->notebook->livelossplot) (0.1.0)\nRequirement already satisfied: decorator in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from ipython>=4.0.0->ipykernel->notebook->livelossplot) (4.3.0)\nRequirement already satisfied: pickleshare in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from ipython>=4.0.0->ipykernel->notebook->livelossplot) (0.7.4)\nRequirement already satisfied: simplegeneric>0.8 in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from ipython>=4.0.0->ipykernel->notebook->livelossplot) (0.8.1)\nRequirement already satisfied: ptyprocess>=0.5 in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from pexpect; sys_platform != \"win32\"->ipython>=4.0.0->ipykernel->notebook->livelossplot) (0.5.2)\nRequirement already satisfied: wcwidth in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from prompt-toolkit<2.0.0,>=1.0.15->ipython>=4.0.0->ipykernel->notebook->livelossplot) (0.1.7)\nRequirement already satisfied: parso>=0.3.0 in /Users/pmigdal/anaconda3/lib/python3.5/site-packages (from jedi>=0.10->ipython>=4.0.0->ipykernel->notebook->livelossplot) (0.4.0)\n"
]
]
]
| [
"markdown",
"code"
]
| [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
]
|
cb5f04792d034407ece548286f2f503e012a941e | 195,924 | ipynb | Jupyter Notebook | ibm/basics_of_qiskit/Challenge1_BasicQuantumCircuits_Solutions.ipynb | sdabhi23/q-cloud-programming | 308c7032176897a967d1ae1cd1b64bbc28f3f3fd | [
"MIT"
]
| 4 | 2020-07-08T08:14:40.000Z | 2020-08-24T06:29:51.000Z | ibm/basics_of_qiskit/Challenge1_BasicQuantumCircuits_Solutions.ipynb | sdabhi23/q-cloud-programming | 308c7032176897a967d1ae1cd1b64bbc28f3f3fd | [
"MIT"
]
| 2 | 2020-07-10T02:43:49.000Z | 2020-07-10T02:55:31.000Z | ibm/basics_of_qiskit/Challenge1_BasicQuantumCircuits_Solutions.ipynb | sdabhi23/q-cloud-programming | 308c7032176897a967d1ae1cd1b64bbc28f3f3fd | [
"MIT"
]
| null | null | null | 230.770318 | 28,768 | 0.905402 | [
[
[
"# Introduction to Qiskit\nWelcome to the Quantum Challenge! Here you will be using Qiskit, the open source quantum software development kit developed by IBM Quantum and community members around the globe. The following exercises will familiarize you with the basic elements of Qiskit and quantum circuits. \n\nTo begin, let us define what a quantum circuit is:\n\n> **\"A quantum circuit is a computational routine consisting of coherent quantum operations on quantum data, such as qubits. It is an ordered sequence of quantum gates, measurements, and resets, which may be conditioned on real-time classical computation.\"** (https://qiskit.org/textbook/ch-algorithms/defining-quantum-circuits.html)\n\nWhile this might be clear to a quantum physicist, don't worry if it is not self-explanatory to you. During this exercise you will learn what a qubit is, how to apply quantum gates to it, and how to measure its final state. You will then be able to create your own quantum circuits! By the end, you should be able to explain the fundamentals of quantum circuits to your colleagues.\n\nBefore starting with the exercises, please run cell *Cell 1* below by clicking on it and pressing 'shift' + 'enter'. This is the general way to execute a code cell in the Jupyter notebook environment that you are using now. While it is running, you will see `In [*]:` in the top left of that cell. Once it finishes running, you will see a number instead of the star, which indicates how many cells you've run. You can find more information about Jupyter notebooks here: https://qiskit.org/textbook/ch-prerequisites/python-and-jupyter-notebooks.html.\n\n---\nFor useful tips to complete this exercise as well as pointers for communicating with other participants and asking questions, please take a look at the following [repository](https://github.com/qiskit-community/may4_challenge_exercises). You will also find a copy of these exercises, so feel free to edit and experiment with these notebooks.\n\n---",
"_____no_output_____"
]
],
[
[
"# Cell 1\nimport numpy as np\n\nfrom qiskit import Aer, QuantumCircuit, execute\nfrom qiskit.visualization import plot_histogram\nfrom IPython.display import display, Math, Latex\n\nfrom may4_challenge import plot_state_qsphere\nfrom may4_challenge.ex1 import minicomposer\nfrom may4_challenge.ex1 import check1, check2, check3, check4, check5, check6, check7, check8\nfrom may4_challenge.ex1 import return_state, vec_in_braket, statevec",
"_____no_output_____"
]
],
[
[
"## Exercise I: Basic Operations on Qubits and Measurements\n\n### Writing down single-qubit states\nLet us start by looking at a single qubit. The main difference between a classical bit, which can take the values 0 and 1 only, is that a quantum bit, or **qubit**, can be in the states $\\vert0\\rangle$, $\\vert1\\rangle$, as well as a linear combination of these two states. This feature is known as superposition, and allows us to write the most general state of a qubit as: \n\n$$\\vert\\psi\\rangle = \\sqrt{1-p}\\vert0\\rangle + e^{i \\phi} \\sqrt{p} \\vert1\\rangle$$\n\nIf we were to measure the state of this qubit, we would find the result $1$ with probability $p$, and the result $0$ with probability $1-p$. As you can see, the total probability is $1$, meaning that we will indeed measure either $0$ or $1$, and no other outcomes exists.\n\nIn addition to $p$, you might have noticed another parameter above. The variable $\\phi$ indicates the relative quantum phase between the two states $\\vert0\\rangle$ and $\\vert1\\rangle$. As we will discover later, this relative phase is quite important. For now, it suffices to note that the quantum phase is what enables interference between quantum states, resulting in our ability to write quantum algorithms for solving specific tasks.\n\nIf you are interested in learning more, we refer you to [the section in the Qiskit textbook on representations of single-qubit states](https://qiskit.org/textbook/ch-states/representing-qubit-states.html).\n\n### Visualizing quantum states\nWe visualize quantum states throughout this exercise using what is known as a `qsphere`. Here is how the `qsphere` looks for the states $\\vert0\\rangle$ and $\\vert1\\rangle$, respectively. Note that the top-most part of the sphere represents the state $\\vert0\\rangle$, while the bottom represents $\\vert1\\rangle$.\n\n<img src=\"qsphere01.png\" alt=\"qsphere with states 0 and 1\" style=\"width: 400px;\"/>\n\nIt should be no surprise that the superposition state with quantum phase $\\phi = 0$ and probability $p = 1/2$ (meaning an equal likelihood of measuring both 0 and 1) is shown on the `qsphere` with two points. However, note also that the size of the circles at the two points is smaller than when we had simply $\\vert0\\rangle$ and $\\vert1\\rangle$ above. This is because the size of the circles is proportional to the probability of measuring each one, which is now reduced by half.\n\n<img src=\"qsphereplus.png\" alt=\"qsphere with superposition 1\" style=\"width: 200px;\"/>\n\nIn the case of superposition states, where the quantum phase is non-zero, the qsphere allows us to visualize that phase by changing the color of the respective blob. For example, the state with $\\phi = 90^\\circ$ (degrees) and probability $p = 1/2$ is shown in the `qsphere` below. \n\n<img src=\"qspherey.png\" alt=\"qsphere with superposition 2\" style=\"width: 200px;\"/>\n\n### Manipulating qubits\nQubits are manipulated by applying quantum gates. Let's go through an overview of the different gates that we will consider in the following exercises.\n\nFirst, let's describe how we can change the value of $p$ for our general quantum state. To do this, we will use two gates:\n\n1. **$X$-gate**: This gate flips between the two states $\\vert0\\rangle$ and $\\vert1\\rangle$. This operation is the same as the classical NOT gate. As a result, the $X$-gate is sometimes referred to as a bit flip or NOT gate. Mathematically, the $X$ gate changes $p$ to $1-p$, so in particular from 0 to 1, and vice versa.\n\n2. **$H$-gate**: This gate allows us to go from the state $\\vert0\\rangle$ to the state $\\frac{1}{\\sqrt{2}}\\left(\\vert0\\rangle + \\vert1\\rangle\\right)$. This state is also known as the $\\vert+\\rangle$. Mathematically, this means going from $p=0, \\phi=0$ to $p=1/2, \\phi=0$. As the final state of the qubit is a superposition of $\\vert0\\rangle$ and $\\vert1\\rangle$, the Hadamard gate represents a true quantum operation.\n\nNotice that both gates changed the value of $p$, but not $\\phi$. Fortunately for us, it's quite easy to visualize the action of these gates by looking at the figure below.\n\n<img src=\"quantumgates.png\" alt=\"quantum gates\" style=\"width: 400px;\"/>\n\nOnce we have the state $\\vert+\\rangle$, we can then change the quantum phase by applying several other gates. For example, an $S$ gate adds a phase of $90$ degrees to $\\phi$, while the $Z$ gate adds a phase of $180$ degrees to $\\phi$. To subtract a phase of $90$ degrees, we can apply the $S^\\dagger$ gate, which is read as S-dagger, and commonly written as `sdg`. Finally, there is a $Y$ gate which applies a sequence of $Z$ and $X$ gates.\n\nYou can experiment with the gates $X$, $Y$, $Z$, $H$, $S$ and $S^\\dagger$ to become accustomed to the different operations and how they affect the state of a qubit. To do so, you can run *Cell 2* which starts our circuit widget. After running the cell, choose a gate to apply to a qubit, and then choose the qubit (in the first examples, the only qubit to choose is qubit 0). Watch how the corresponding state changes with each gate, as well as the description of that state. It will also provide you with the code that creates the corresponding quantum circuit in Qiskit below the qsphere.\n\nIf you want to learn more about describing quantum states, Pauli operators, and other single-qubit gates, see chapter 1 of our textbook: https://qiskit.org/textbook/ch-states/introduction.html.",
"_____no_output_____"
]
],
[
[
"# Cell 2\n# press shift + return to run this code cell\n# then, click on the gate that you want to apply to your qubit\n# next, you have to choose the qubit that you want to apply it to (choose '0' here)\n# click on clear to restart\nminicomposer(1, dirac=True, qsphere=True)",
"_____no_output_____"
]
],
[
[
"Here are four small exercises to attain different states on the qsphere. You can either solve them with the widget above and copy paste the code it provides into the respective cells to create the quantum circuits, or you can directly insert a combination of the following code lines into the program to apply the different gates: \n\n qc.x(0) # bit flip\n qc.y(0) # bit and phase flip\n qc.z(0) # phase flip\n qc.h(0) # superpostion\n qc.s(0) # quantum phase rotation by pi/2 (90 degrees)\n qc.sdg(0) # quantum phase rotation by -pi/2 (90 degrees)\n \nThe '(0)' indicates that we apply this gate to qubit 'q0', which is the first (and in this case only) qubit.\n\nTry to attain the given state on the qsphere in each of the following exercises.\n### I.i) Let us start by performing a bit flip. The goal is to reach the state $\\vert1\\rangle$ starting from state $\\vert0\\rangle$. <img src=\"state1.png\" width=\"300\"> \n\n\nIf you have reached the desired state with the widget, copy and paste the code from *Cell 2* into *Cell 3* (where it says \"FILL YOUR CODE IN HERE\") and run it to check your solution.",
"_____no_output_____"
]
],
[
[
"# Cell 3\ndef create_circuit():\n qc = QuantumCircuit(1)\n #\n #\n qc.x(0)\n #\n #\n return qc\n\n# check solution\nqc = create_circuit()\nstate = statevec(qc)\ncheck1(state)\nplot_state_qsphere(state.data, show_state_labels=True, show_state_angles=True) ",
"Missing environment variable MAY4_CHALLENGE_VALIDATION_ENDPOINT. Set it with the URL to the root of the validation server.\n\nUsing staging server at https://eu-gb.functions.cloud.ibm.com/api/v1/web/salvador.de.la.puente.gonzalez%40ibm.com_dev/default/may4_challenge\n"
]
],
[
[
"### I.ii) Next, let's create a superposition. The goal is to reach the state $|+\\rangle = \\frac{1}{\\sqrt{2}}\\left(|0\\rangle + |1\\rangle\\right)$. <img src=\"stateplus.png\" width=\"300\"> \nFill in the code in the lines indicated in *Cell 4*. If you prefer the widget, you can still copy the code that the widget gives in *Cell 2* and paste it into *Cell 4*.",
"_____no_output_____"
]
],
[
[
"# Cell 4\ndef create_circuit2():\n qc = QuantumCircuit(1)\n #\n #\n qc.h(0)\n #\n #\n return qc\n\nqc = create_circuit2()\nstate = statevec(qc)\ncheck2(state)\nplot_state_qsphere(state.data, show_state_labels=True, show_state_angles=True) ",
"Correct 🎉! Well done!\nYour progress: 2/8\n"
]
],
[
[
"### I.iii) Let's combine those two. The goal is to reach the state $|-\\rangle = \\frac{1}{\\sqrt{2}}\\left(|0\\rangle - |1\\rangle\\right)$. <img src=\"stateminus.png\" width=\"300\"> \nCan you combine the above two tasks to come up with the solution?",
"_____no_output_____"
]
],
[
[
"# Cell 5\ndef create_circuit3():\n qc = QuantumCircuit(1)\n #\n #\n qc.x(0)\n qc.h(0)\n #\n #\n return qc\n\nqc = create_circuit3()\nstate = statevec(qc)\ncheck3(state)\nplot_state_qsphere(state.data, show_state_labels=True, show_state_angles=True) ",
"Correct 🎉! Well done!\nYour progress: 3/8\n"
]
],
[
[
"### I.iv) Finally, we move on to the complex numbers. The goal is to reach the state $|\\circlearrowleft\\rangle = \\frac{1}{\\sqrt{2}}\\left(|0\\rangle - i|1\\rangle\\right)$. <img src=\"stateleft.png\" width=\"300\"> ",
"_____no_output_____"
]
],
[
[
"# Cell 6\ndef create_circuit4():\n qc = QuantumCircuit(1)\n #\n #\n qc.h(0)\n qc.sdg(0)\n #\n #\n return qc\n\nqc = create_circuit4()\nstate = statevec(qc)\ncheck4(state)\nplot_state_qsphere(state.data, show_state_labels=True, show_state_angles=True) ",
"Correct 🎉! Well done!\nYour progress: 4/8\n"
]
],
[
[
"\n## Exercise II: Quantum Circuits Using Multi-Qubit Gates\n\nGreat job! Now that you've understood the single-qubit gates, let us look at gates operating on multiple qubits. The basic gates on two qubits are given by\n\n qc.cx(c,t) # controlled-X (= CNOT) gate with control qubit c and target qubit t\n qc.cz(c,t) # controlled-Z gate with control qubit c and target qubit t\n qc.swap(a,b) # SWAP gate that swaps the states of qubit a and qubit b\n\nIf you'd like to read more about the different multi-qubit gates and their relations, visit chapter 2 of our textbook: https://qiskit.org/textbook/ch-gates/introduction.html.\n\nAs before, you can use the two-qubit circuit widget below to see how the combined two qubit state evolves when applying different gates (run *Cell 7*) and get the corresponding code that you can copy and paste into the program. Note that for two qubits a general state is of the form $a|00\\rangle + b |01\\rangle + c |10\\rangle + d|11\\rangle$, where $a$, $b$, $c$, and $d$ are complex numbers whose absolute values squared give the probability to measure the respective state; e.g., $|a|^2$ would be the probability to end in state '0' on both qubits. This means we can now have up to four points on the qsphere.",
"_____no_output_____"
]
],
[
[
"# Cell 7\n# press shift + return to run this code cell\n# then, click on the gate that you want to apply followed by the qubit(s) that you want it to apply to\n# for controlled gates, the first qubit you choose is the control qubit and the second one the target qubit\n# click on clear to restart\n\nminicomposer(2, dirac = True, qsphere = True)",
"_____no_output_____"
]
],
[
[
"We start with the canonical two qubit gate, the controlled-NOT (also CNOT or CX) gate. Here, as with all controlled two qubit gates, one qubit is labelled as the \"control\", while the other is called the \"target\". If the control qubit is in state $|0\\rangle$, it applies the identity $I$ gate to the target, i.e., no operation is performed. Instead, if the control qubit is in state $|1\\rangle$, an X-gate is performed on the target qubit. Therefore, with both qubits in one of the two classical states, $|0\\rangle$ or $|1\\rangle$, the CNOT gate is limited to classical operations.\n\nThis situation changes dramatically when we first apply a Hadamard gate to the control qubit, bringing it into the superposition state $|+\\rangle$. The action of a CNOT gate on this non-classical input can produce highly entangled states between control and target qubits. If the target qubit is initially in the $|0\\rangle$ state, the resulting state is denoted by $|\\Phi^+\\rangle$, and is one of the so-called Bell states. \n\n### II.i) Construct the Bell state $|\\Phi^+\\rangle = \\frac{1}{\\sqrt{2}}\\left(|00\\rangle + |11\\rangle\\right)$. <img src=\"phi+.png\" width=\"300\"> \nFor this state we would have probability $\\frac{1}{2}$ to measure \"00\" and probability $\\frac{1}{2}$ to measure \"11\". Thus, the outcomes of both qubits are perfectly correlated.",
"_____no_output_____"
]
],
[
[
"# Cell 8\ndef create_circuit():\n qc = QuantumCircuit(2)\n #\n #\n qc.h(0)\n qc.cx(0, 1)\n #\n #\n return qc\n\nqc = create_circuit()\nstate = statevec(qc) # determine final state after running the circuit\ndisplay(Math(vec_in_braket(state.data)))\ncheck5(state)\nqc.draw(output='mpl') # we draw the circuit",
"_____no_output_____"
]
],
[
[
"Next, try to create the state of perfectly anti-correlated qubits. Note the minus sign here, which indicates the relative phase between the two states. \n### II.ii) Construct the Bell state $\\vert\\Psi^-\\rangle = \\frac{1}{\\sqrt{2}}\\left(\\vert01\\rangle - \\vert10\\rangle\\right)$. <img src=\"psi-.png\" width=\"300\"> ",
"_____no_output_____"
]
],
[
[
"# Cell 9\ndef create_circuit6():\n qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also \n # two classical bits for the measurement later\n #\n #\n qc.h(0)\n qc.x(1)\n qc.cx(0, 1)\n qc.z(1)\n #\n #\n return qc\n\nqc = create_circuit6()\nstate = statevec(qc) # determine final state after running the circuit\ndisplay(Math(vec_in_braket(state.data)))\ncheck6(state)\nqc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0\nqc.measure(1, 1) # we perform a measurement on qubit q_1 and store the information on the classical bit c_1\nqc.draw(output='mpl') # we draw the circuit",
"_____no_output_____"
]
],
[
[
"As you can tell from the circuit (and the code) we have added measurement operators to the circuit. Note that in order to store the measurement results, we also need two classical bits, which we have added when creating the quantum circuit: `qc = QuantumCircuit(num_qubits, num_classicalbits)`.\n\nIn *Cell 10* we have defined a function `run_circuit()` that will run a circuit on the simulator. If the right state is prepared, we have probability $\\frac{1}{2}$ to measure each of the two outcomes, \"01\" and \"10\". However, performing the measurement with 1000 shots does not imply that we will measure exactly 500 times \"01\" and 500 times \"10\". Just like flipping a coin multiple times, it is unlikely that one will get exactly a 50/50 split between the two possible output values. Instead, there are fluctuations about this ideal distribution. You can call `run_circuit` multiple times to see the variance in the ouput.\n",
"_____no_output_____"
]
],
[
[
"# Cell 10\ndef run_circuit(qc):\n backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend\n result = execute(qc, backend, shots = 1000).result() # we run the simulation\n counts = result.get_counts() # we get the counts\n return counts\n\ncounts = run_circuit(qc)\nprint(counts)\nplot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities",
"{'10': 485, '01': 515}\n"
]
],
[
[
"### II.iii) You are given the quantum circuit described in the function below. Swap the states of the first and the second qubit. \nThis should be your final state: <img src=\"stateIIiii.png\" width=\"300\"> ",
"_____no_output_____"
]
],
[
[
"# Cell 11\ndef create_circuit7():\n qc = QuantumCircuit(2)\n qc.rx(np.pi/3,0)\n qc.x(1)\n return qc\n\nqc = create_circuit7()\n#\n#\nqc.swap(0, 1)\n#\n#\nstate = statevec(qc) # determine final state after running the circuit\ndisplay(Math(vec_in_braket(state.data)))\ncheck7(state)\nplot_state_qsphere(state.data, show_state_labels=True, show_state_angles=True) ",
"_____no_output_____"
]
],
[
[
"### II.iv) Write a program from scratch that creates the GHZ state (on three qubits), $\\vert \\text{GHZ}\\rangle = \\frac{1}{\\sqrt{2}} \\left(|000\\rangle + |111 \\rangle \\right)$, performs a measurement with 2000 shots, and returns the counts. <img src=\"ghz.png\" width=\"300\"> \nIf you want to track the state as it is evolving, you could use the circuit widget from above for three qubits, i.e., `minicomposer(3, dirac=True, qsphere=True)`. For how to get the counts of a measurement, look at the code in *Cell 9* and *Cell 10*.",
"_____no_output_____"
]
],
[
[
"# Cell 12\n#\ndef run_circuit(qc, shots):\n backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend\n result = execute(qc, backend, shots = shots).result() # we run the simulation\n counts = result.get_counts() # we get the counts\n return counts\n\nqc = QuantumCircuit(3)\nqc.h(0)\nqc.cx(0, 1)\nqc.cx(1, 2)\nqc.measure_all()\ncounts = run_circuit(qc, 2000)\n#\n#\n#\nprint(counts)\ncheck8(counts)\nplot_histogram(counts)",
"{'000': 993, '111': 1007}\nCorrect 🎉! Well done!\nYour progress: 8/8\n"
]
],
[
[
"Congratulations for finishing this introduction to Qiskit! Once you've reached all 8 points, the solution string will be displayed. You need to copy and paste that string on the IBM Quantum Challenge page to complete the exercise and track your progress.\n\nNow that you have created and run your first quantum circuits, you are ready for the next exercise, where we will make use of the actual hardware and learn how to reduce the noise in the outputs.",
"_____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"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
]
|
cb5f123f760d8bb71244d94b64b8d2bd59c53a85 | 15,520 | ipynb | Jupyter Notebook | notebooks/pServer.ipynb | malfarasplux/biofeatures | 90cba009a34dbaf35ec112edc8f2e93a72563c5b | [
"ISC"
]
| null | null | null | notebooks/pServer.ipynb | malfarasplux/biofeatures | 90cba009a34dbaf35ec112edc8f2e93a72563c5b | [
"ISC"
]
| null | null | null | notebooks/pServer.ipynb | malfarasplux/biofeatures | 90cba009a34dbaf35ec112edc8f2e93a72563c5b | [
"ISC"
]
| 1 | 2020-02-10T09:55:58.000Z | 2020-02-10T09:55:58.000Z | 34.035088 | 1,206 | 0.560245 | [
[
[
"from pythonosc import dispatcher, osc_server\nfrom pythonosc.udp_client import SimpleUDPClient\nimport time\n\ndeflating = False\n\ndef print_volume_handler(unused_addr, args, volume):\n global deflating, deflateStartTime\n \n print(\"[{0}] ~ {1}\".format(args, volume))\n \n if (volume > 1090 or deflating):\n client.send_message(\"/actuator/1/inflate\", -80.0) # Send float message between -100 and 100\n \n if deflating == False:\n deflating = True\n deflateStartTime = time.time()\n \n elif time.time() - deflateStartTime > 5:\n deflating = False\n \n elif deflating == False:\n client.send_message(\"/actuator/1/inflate\", 80.0) # Send float message between -100 and 100\n\n\ndeflateStartTime = time.time()\n \nip = \"192.168.0.106\"\nport = 32000\n\nclient = SimpleUDPClient(ip, port) # Create client\n \ndispatcher = dispatcher.Dispatcher()\ndispatcher.map(\"/sensor/pressure\", print_volume_handler, \"Pressure\")\n\nserver = osc_server.ThreadingOSCUDPServer((\"192.168.0.106\", 31000), dispatcher)\nprint(\"Serving on {}\".format(server.server_address))\nserver.serve_forever()",
"_____no_output_____"
],
[
"from pythonosc.udp_client import SimpleUDPClient\n\nip = \"192.168.0.106\"\nport = 32000\n\nclient = SimpleUDPClient(ip, port) # Create client\n\nclient.send_message(\"/actuator/1/inflate\", -0.0)\n",
"_____no_output_____"
],
[
"from pythonosc import dispatcher, osc_server\nfrom pythonosc.udp_client import SimpleUDPClient\n\n\ndef print_volume_handler(unused_addr, args, volume):\n print(\"[{0}] ~ {1}\".format(args, volume))\n \n client.send_message(\"/actuator/1/inflate\", -100.0) # Send float message between -100 and 100\n\n\n \nip = \"192.168.0.106\"\nport = 32000\n\nclient = SimpleUDPClient(ip, port) # Create client\n \ndispatcher = dispatcher.Dispatcher()\ndispatcher.map(\"/sensor/pressure\", print_volume_handler, \"Pressure\")\n\nserver = osc_server.ThreadingOSCUDPServer((\"192.168.0.106\", 31000), dispatcher)\nprint(\"Serving on {}\".format(server.server_address))\nserver.serve_forever()",
"_____no_output_____"
],
[
"import time\ntime.time()",
"_____no_output_____"
]
],
[
[
"# Respiration Real-Time Analysis",
"_____no_output_____"
]
],
[
[
"import biosppy.signals.resp as resp\nimport numpy as np\nimport csv as csv\nimport json \nimport matplotlib.pyplot as plt\n\ndef calc_resp_intervals(data, last_breath = False):\n processed_data = resp.resp(signal=data, sampling_rate=200, show=False)\n filtered_signal = processed_data[1]\n inst_resp_rate = processed_data[4]\n \n signal_diff = np.diff(filtered_signal)\n signal_signum = signal_diff > 0\n \n resp_changes = np.append(np.where(signal_signum[:-1] != signal_signum[1:])[0], [len(signal_signum) - 1])\n \n if not last_breath:\n \n resp_intervals = np.append([0], resp_changes)\n interval_lengths = np.diff(resp_intervals)\n interval_breathe_in = [signal_signum[i] for i in resp_changes]\n return interval_lengths, interval_breathe_in\n \n else:\n if len(resp_changes) > 1:\n last_interval = resp_changes[-1] - resp_changes[-2]\n else:\n last_interval = resp_changes[-1] \n \n return last_interval, signal_signum[resp_changes[-1]]",
"_____no_output_____"
],
[
"import time\nfrom pythonosc.udp_client import SimpleUDPClient\n\nresp_data = []\nlast_update = time.time()\n\nupdate_freq = 0.5\n\nriot_ip = '192.168.1.2'\nriot_port = 8888\nactuator_port = 12000\nactuator_ip = '192.168.0.103'\n\n\nclient = SimpleUDPClient(actuator_ip, actuator_port) \n\ndef process_riot_data(unused_addr, *values):\n global resp_data, last_update, client\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 = calc_resp_intervals(resp_data, last_breath = True)\n \n if breathe_in:\n print(\"Breathing in\")\n client.send_message(\"/actuator/inflate\", 100.0)\n else:\n print(\"Breathing out\")\n client.send_message(\"/actuator/inflate\", -100.0)\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:]\n ",
"_____no_output_____"
],
[
"from pythonosc import dispatcher\nfrom pythonosc import osc_server\n\nriot_dispatcher = dispatcher.Dispatcher()\nriot_dispatcher.map(\"/*/raw\", process_riot_data)\n\nserver = osc_server.ThreadingOSCUDPServer((riot_ip, riot_port), riot_dispatcher)\nprint(\"Serving on {}\".format(server.server_address))\nserver.serve_forever()",
"Serving on ('192.168.1.2', 8888)\nBreathing out\nBreathing out\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing outBreathing out\n\nBreathing out\nBreathing out\nBreathing out\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing out\nBreathing out\nBreathing outBreathing out\n\nBreathing out\nBreathing out\nBreathing out\nBreathing out\nBreathing out\nBreathing out\nBreathing out\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing out\nBreathing out\nBreathing out\nBreathing out\nBreathing out\nBreathing out\nBreathing out\nBreathing out\nBreathing out\nBreathing out\nBreathing out\nBreathing out\nBreathing out\nBreathing in\nBreathing in\nBreathing inBreathing in\n\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing out\nBreathing out\nBreathing out\nBreathing out\nBreathing out\nBreathing out\nBreathing out\nBreathing in\nBreathing out\nBreathing out\nBreathing out\nBreathing out\nBreathing out\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing inBreathing in\n\nBreathing inBreathing in\n\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing out\nBreathing out\nBreathing out\nBreathing out\nBreathing out\nBreathing out\nBreathing out\nBreathing out\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing out\nBreathing out\nBreathing out\nBreathing out\nBreathing out\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\nBreathing in\n"
],
[
"from pythonosc.udp_client import SimpleUDPClient\n\nriot_ip = '192.168.0.103'\nriot_port = 8888\nactuator_port = 12000\n\nclient = SimpleUDPClient(riot_ip, actuator_port) \n\nclient.send_message(\"/actuator/inflate\", -0.0)",
"_____no_output_____"
],
[
"def test(lst):\n lst[0] = \"test\"\n\n \nlst = [1,2,3,4]\n\nlst2 = lst.copy()\n\ntest(lst2)\n\nprint(lst2)\nprint(lst)",
"['test', 2, 3, 4]\n[1, 2, 3, 4]\n"
]
]
]
| [
"code",
"markdown",
"code"
]
| [
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
]
|
cb5f3631eee1657fce7a3c2bc2c582b1bb324f47 | 89,315 | ipynb | Jupyter Notebook | notebooks/cosmic_string_project.ipynb | vafaei-ar/ccgpack | 73cf1d644f747fd2251ed9256cae740e6b052da7 | [
"BSD-3-Clause"
]
| 3 | 2019-04-15T08:40:32.000Z | 2019-04-18T22:06:29.000Z | notebooks/cosmic_string_project.ipynb | vafaei-ar/ccgpack | 73cf1d644f747fd2251ed9256cae740e6b052da7 | [
"BSD-3-Clause"
]
| null | null | null | notebooks/cosmic_string_project.ipynb | vafaei-ar/ccgpack | 73cf1d644f747fd2251ed9256cae740e6b052da7 | [
"BSD-3-Clause"
]
| 2 | 2019-04-15T08:41:35.000Z | 2021-10-02T08:24:22.000Z | 750.546218 | 86,842 | 0.943559 | [
[
[
"%matplotlib inline\n\nimport numpy as np\nimport pylab as plt\nfrom scipy.ndimage import imread\nimport ccgpack as ccg\nfrom seekstring import data_provider\nimport pywt \n\ndef wavelet(data, wlf, threshold):\n wavelet = pywt.Wavelet(wlf)\n levels = pywt.dwt_max_level(data.shape[0], wavelet)\n WaveletCoeffs = pywt.wavedec2(data, wavelet, level=levels)\n NewWaveletCoeffs = map (lambda x: pywt.threshold(x,threshold,'less'),WaveletCoeffs)\n data = pywt.waverec2( NewWaveletCoeffs, wavelet)\n return data",
"_____no_output_____"
],
[
"img = imread('../images/einstein.jpg')\nplt.imshow(img,'gray')\nplt.axis('off')\nimg = img.astype(float)\nimg /= img.max()",
"_____no_output_____"
],
[
"def extractor(m,c,filt='sch'): \n mp = ccg.curvelet(m,c)\n mp = ccg.filters(mp,edd_method=filt)\n return ccg.stat_describe(mp)[1]\n\nextractor(img,3)",
"_____no_output_____"
]
]
]
| [
"code"
]
| [
[
"code",
"code",
"code"
]
]
|
cb5f389a622a0d6011540c12702a2ccbdbde6d6c | 16,395 | ipynb | Jupyter Notebook | site/ru/guide/estimator.ipynb | NarimaneHennouni/docs-l10n | 39a48e0d5aa34950e29efd5c1f111c120185e9d9 | [
"Apache-2.0"
]
| null | null | null | site/ru/guide/estimator.ipynb | NarimaneHennouni/docs-l10n | 39a48e0d5aa34950e29efd5c1f111c120185e9d9 | [
"Apache-2.0"
]
| null | null | null | site/ru/guide/estimator.ipynb | NarimaneHennouni/docs-l10n | 39a48e0d5aa34950e29efd5c1f111c120185e9d9 | [
"Apache-2.0"
]
| null | null | null | 39.697337 | 725 | 0.595059 | [
[
[
"##### Copyright 2019 The TensorFlow Authors.",
"_____no_output_____"
]
],
[
[
"#@title 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_____"
]
],
[
[
"# Оценщики",
"_____no_output_____"
],
[
"<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://www.tensorflow.org/guide/estimator\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />Смотрите на TensorFlow.org</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ru/guide/estimator.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Запустите в Google Colab</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/tensorflow/docs-l10n/blob/master/site/ru/guide/estimator.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />Изучайте код на GitHub</a>\n </td>\n <td>\n <a href=\"https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/ru/guide/estimator.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Скачайте ноутбук</a>\n </td>\n</table>",
"_____no_output_____"
],
[
"Note: Данный раздел переведён с помощью русскоязычного сообщества Tensorflow на общественных началах. Поскольку перевод не является официальным, мы не гарантируем, что он на 100% точен и соответствует [официальной документации на английском языке](https://www.tensorflow.org/?hl=en). Если у вас есть предложения по исправлению перевода, мы будем очень рады увидеть pull request в репозиторий [tensorflow/docs-l10n](https://github.com/tensorflow/docs-l10n) на GitHub. Если вы хотите помочь сделать документацию по Tensorflow лучше (выполнить перевод или проверить перевод, подготовленный кем-то другим), напишите нам на [[email protected] list](https://groups.google.com/a/tensorflow.org/forum/#!forum/docs-ru).",
"_____no_output_____"
],
[
"Этот документ знакомит с `tf.estimator` — высокоуровневым TensorFlow\nAPI. Оценщики включают следующие действия:\n\n* обучение\n* оценка\n* предсказание\n* экспорт для serving\n\nВы можете использовать созданные нами оценщики или\nсобственные кастомные оценщики. Все оценщики - как созданные нами, так и пользовательские - являются\nклассами, основанными на классе `tf.estimator.Estimator`.\n\nБыстрый пример можно посмотреть в [Учебниках по оценщикам](../../tutorials/estimator/linear.ipynb). Обзор структуры API приведен в [статье](https://arxiv.org/abs/1708.02637).",
"_____no_output_____"
],
[
"## Преимущества\n\nАналогично `tf.keras.Model`, `estimator` это абстракция на уровне модели. `tf.estimator` предоставляет некоторые возможности, которые все еще находятся в стадии разработки для `tf.keras`. Это:\n\n * Обучение на сервере параметров\n * Полная [TFX](http://tensorflow.org/tfx) интеграция.",
"_____no_output_____"
],
[
"## Возможности оценщиков\nОценщики предоставляют следующие преимущества:\n\n* Вы можете запускать модели на основе оценщиков на локальном компьютере или в распределенной многосерверной среде без изменения вашей модели. Кроме того, вы можете запускать модели на основе оценщиков на CPU, GPU, или TPU без изменения исходного кода вашей модели.\n* Оценщики обеспечивают безопасный распределенный цикл обучения, который контролирует каким образом и когда:\n * загружаются данные\n * обрабатываются исключения\n * создаются файлы чекпоинтов и восстанавливаются после сбоев\n * сохраняются сводные данные для TensorBoard\n\nПри написании приложения с оценщиками, вы должны отделить конвейер входных данных\nот модели. Это разделение упрощает эксперименты с различными наборами данных.",
"_____no_output_____"
],
[
"## Готовые оценщики\n\nПредварительно созданные оценщики позволяют вам работать на гораздо более высоком концептуальном уровне, чем базовые API TensorFlow. Вам больше не нужно беспокоиться о создании вычислительного графа или сессий, поскольку оценщики делают всю \"грязную работу\" за вас. Кроме того, оценщики, позволяют вам экспериментировать с различными архитектурами моделей, внося только минимальные изменения в код. `tf.estimator.DNNClassifier`, например, представляет собой заранее подготовленный класс Estimator, который обучает модели классификации на основе полносвязных нейронных сетей прямого распространения.\n\n### Структура программы на готовом оценщике\n\nСоздание программы TensorFlow на готовом оценщике обычно состоит из четырех этапов:\n\n#### 1. Напишите одну или несколько функций импорта данных.\n\nНапример, вы можете создать одну функцию для импорта тренировочных данных и другую функцию для импорта тестовых данных. Каждая функция импорта данных должна возвращать два объекта:\n\n* словарь, в котором ключами являются имена признаков, а значениями - тензоры (Tensor или SparseTensor), содержащие соответствующие признаку данные\n* Tensor, содержащий одну или более меток\n\nНапример, следующий код иллюстрирует базовый каркас для входной функции:\n\n```\ndef input_fn(dataset):\n ... # манипулирет датасетом, извлекает словарь со свойствами и метку\n return feature_dict, label\n```\n\nSee [data guide](../../guide/data.md) for details.\n\n#### 2. Определяет столбцы свойств.\n\nКаждый `tf.feature_column` определяет имя признака, его тип и любую предобработку. Например, следующий фрагмент кода создает три столбца признаков содержащих целые числа или значения с плавающей точкой. Первые два столбца признаков просто идентифицируют имя признака и тип. Третий столбец признаков определяет лямбду - программу которая будет вызвана для масштабирования сырых данных:\n\n```\n# Определим три столбца с числовыми признаками.\npopulation = tf.feature_column.numeric_column('population')\ncrime_rate = tf.feature_column.numeric_column('crime_rate')\nmedian_education = tf.feature_column.numeric_column(\n 'median_education',\n normalizer_fn=lambda x: x - global_education_mean)\n```\nДля дополнительной информации см. [учебник по столбцам признаков](https://www.tensorflow.org/tutorials/keras/feature_columns).\n\n#### 3. Создание экземпляра готового оценщика.\n\nНапример, вот так можно просто создать экземпляр оценщика `LinearClassifier`:\n\n```\n# Создадим экземпляр оценщика, передав столбцы признаков.\nestimator = tf.estimator.LinearClassifier(\n feature_columns=[population, crime_rate, median_education])\n```\nДля дополнительной информации см. [учебник линейной классификации](https://www.tensorflow.org/tutorials/estimator/linear).\n\n#### 4. Вызов метода обучения, оценки или вывода.\n\nНапример, все оценщики предоставляют метод `train` который обучает модель.\n\n```\n# `input_fn` это функция созданная на шаге 1\nestimator.train(input_fn=my_training_set, steps=2000)\n```\nВы можете видеть пример этого ниже.\n\n### Преимущества готовых оценщиков\n\nГотовые оценщики включают в себя лучшие практики, предоставляя следующие преимущества:\n\n* Лучшие практики для определения того, где должны выполняться различные части вычислительного графа, реализуя стратегии на одной машине или на кластере.\n* Лучшие практики для написания событий (сводок) и универсально полезные сводки.\n\nЕсли вы не используете готовые оценщики, вам нужно реализовать предыдущие функции самостоятельно.",
"_____no_output_____"
],
[
"## Кастомные оценщики\n\nСердцем каждого оценщика, будь он готовый или кастомный, является его *функция модели*, которая представляет собой метод построения графов для обучения, оценки и прогнозирования. Когда вы используете готовый оценщик, кто-то за вас уже реализовал функцию модели. Если вы пологаетесь на кастомнного оценщика, вам нужно написать функцию модели самостоятельно\n\n## Рекомендуемый процесс работы\n\n1. Предполагая, что существует готовый оценщик, используйте его для посторения своей первой модели и используйте его результаты для определения бейзлайна.\n2. Создайте и протестируйте весь конвейер, включая целостность и надежность ваших данных с этим готовым оценщиком.\n3. Если имеются другие подходящие готовые оценщики, проведите эксперименты какой из готовых оценщиков дает лучшие результаты.\n4. Возможно еще улучшить вашу модель созданием кастомного оценщика.",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf",
"_____no_output_____"
],
[
"import tensorflow_datasets as tfds\ntfds.disable_progress_bar()",
"_____no_output_____"
]
],
[
[
"## Создание оценщика из модели Keras\n\nВы можете конвертировать существующие модели Keras models в оценщики с помощью `tf.keras.estimator.model_to_estimator`. Это позволяет вашей модели Keras\nполучить сильные стороны оценщиков, такие как, например, распределенное обучение.\n\nСоздайте экземпляр модели Keras MobileNet V2 и скомпилируйте модель с оптимизатором, потерями и метриками необходимыми для обучения:",
"_____no_output_____"
]
],
[
[
"keras_mobilenet_v2 = tf.keras.applications.MobileNetV2(\n input_shape=(160, 160, 3), include_top=False)\nkeras_mobilenet_v2.trainable = False\n\nestimator_model = tf.keras.Sequential([\n keras_mobilenet_v2,\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(1, activation='softmax')\n])\n\n# Компилируем модель\nestimator_model.compile(\n optimizer='adam',\n loss='binary_crossentropy',\n metrics=['accuracy'])",
"_____no_output_____"
]
],
[
[
"Создайте `Estimator` из скомпилированной модели Keras. Начальное состояние модели Keras сохранено в созданном `Estimator`:",
"_____no_output_____"
]
],
[
[
"est_mobilenet_v2 = tf.keras.estimator.model_to_estimator(keras_model=estimator_model)",
"_____no_output_____"
]
],
[
[
"Относитесь к полученному `Estimator` так же как к любому другому `Estimator`.",
"_____no_output_____"
]
],
[
[
"IMG_SIZE = 160 # Размер всех изображений будет приведен к 160x160\n\ndef preprocess(image, label):\n image = tf.cast(image, tf.float32)\n image = (image/127.5) - 1\n image = tf.image.resize(image, (IMG_SIZE, IMG_SIZE))\n return image, label",
"_____no_output_____"
],
[
"def train_input_fn(batch_size):\n data = tfds.load('cats_vs_dogs', as_supervised=True)\n train_data = data['train']\n train_data = train_data.map(preprocess).shuffle(500).batch(batch_size)\n return train_data",
"_____no_output_____"
]
],
[
[
"Для обучения вызовите функцию обучения оценщика:",
"_____no_output_____"
]
],
[
[
"est_mobilenet_v2.train(input_fn=lambda: train_input_fn(32), steps=500)",
"_____no_output_____"
]
],
[
[
"Аналогично, для оценки вызовите функцию оценки оценщика:",
"_____no_output_____"
]
],
[
[
"est_mobilenet_v2.evaluate(input_fn=lambda: train_input_fn(32), steps=10)",
"_____no_output_____"
]
],
[
[
"Дополнительную информацию можно получить в документации по `tf.keras.estimator.model_to_estimator`.",
"_____no_output_____"
]
]
]
| [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
]
| [
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
]
|
cb5f485a2af25ff8f60aa9a1def2b3f5c7cb6fbd | 209,269 | ipynb | Jupyter Notebook | apps/variational-autoencoder/using_variational_autoencoder_to_generate_faces.ipynb | Gavin-Sun555/analytics-zoo | accd9b1d270e7a071c67af0bff3a95c988d33e86 | [
"Apache-2.0"
]
| 2,970 | 2017-06-08T00:24:43.000Z | 2022-03-30T12:14:55.000Z | apps/variational-autoencoder/using_variational_autoencoder_to_generate_faces.ipynb | Gavin-Sun555/analytics-zoo | accd9b1d270e7a071c67af0bff3a95c988d33e86 | [
"Apache-2.0"
]
| 3,530 | 2017-05-09T08:29:10.000Z | 2022-03-21T02:11:45.000Z | apps/variational-autoencoder/using_variational_autoencoder_to_generate_faces.ipynb | Gavin-Sun555/analytics-zoo | accd9b1d270e7a071c67af0bff3a95c988d33e86 | [
"Apache-2.0"
]
| 972 | 2017-05-09T07:03:50.000Z | 2022-03-23T07:48:48.000Z | 385.394107 | 145,284 | 0.937267 | [
[
[
"# Using Variational Autoencoder to Generate Faces",
"_____no_output_____"
],
[
"In this example, we are going to use VAE to generate faces. The dataset we are going to use is [CelebA](http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html). The dataset consists of more than 200K celebrity face images. You have to download the Align&Cropped Images from the above website to run this example.",
"_____no_output_____"
]
],
[
[
"from bigdl.nn.layer import *\nfrom bigdl.nn.criterion import *\nfrom bigdl.optim.optimizer import *\nfrom bigdl.dataset import mnist\nimport datetime as dt\nfrom glob import glob\nimport os\nimport numpy as np\n\nfrom utils import *\nimport imageio\n\nimage_size = 148\nZ_DIM = 128\nENCODER_FILTER_NUM = 32\n\n#download the data CelebA, and may repalce with your own data path\nDATA_PATH = os.getenv(\"ANALYTICS_ZOO_HOME\") + \"/apps/variational-autoencoder/img_align_celeba\"\n\nfrom zoo.common.nncontext import *\nsc = init_nncontext(\"Variational Autoencoder Example\")\nsc.addFile(os.getenv(\"ANALYTICS_ZOO_HOME\")+\"/apps/variational-autoencoder/utils.py\")",
"_____no_output_____"
]
],
[
[
"## Define the Model",
"_____no_output_____"
],
[
"Here, we define a slightly more complicate CNN networks using convolution, batchnorm, and leakyRelu.",
"_____no_output_____"
]
],
[
[
"def conv_bn_lrelu(in_channels, out_channles, kw=4, kh=4, sw=2, sh=2, pw=-1, ph=-1):\n model = Sequential()\n model.add(SpatialConvolution(in_channels, out_channles, kw, kh, sw, sh, pw, ph))\n model.add(SpatialBatchNormalization(out_channles))\n model.add(LeakyReLU(0.2))\n return model\n\ndef upsample_conv_bn_lrelu(in_channels, out_channles, out_width, out_height, kw=3, kh=3, sw=1, sh=1, pw=-1, ph=-1):\n model = Sequential()\n model.add(ResizeBilinear(out_width, out_height))\n model.add(SpatialConvolution(in_channels, out_channles, kw, kh, sw, sh, pw, ph))\n model.add(SpatialBatchNormalization(out_channles))\n model.add(LeakyReLU(0.2))\n return model",
"_____no_output_____"
],
[
"def get_encoder_cnn():\n input0 = Input()\n \n #CONV\n conv1 = conv_bn_lrelu(3, ENCODER_FILTER_NUM)(input0) # 32 * 32 * 32\n conv2 = conv_bn_lrelu(ENCODER_FILTER_NUM, ENCODER_FILTER_NUM * 2)(conv1) # 16 * 16 * 64\n conv3 = conv_bn_lrelu(ENCODER_FILTER_NUM * 2, ENCODER_FILTER_NUM * 4)(conv2) # 8 * 8 * 128\n conv4 = conv_bn_lrelu(ENCODER_FILTER_NUM * 4, ENCODER_FILTER_NUM * 8)(conv3) # 4 * 4 * 256\n view = View([4*4*ENCODER_FILTER_NUM*8])(conv4)\n \n inter = Linear(4*4*ENCODER_FILTER_NUM*8, 2048)(view)\n inter = BatchNormalization(2048)(inter)\n inter = ReLU()(inter)\n \n # fully connected to generate mean and log-variance\n mean = Linear(2048, Z_DIM)(inter)\n \n log_variance = Linear(2048, Z_DIM)(inter)\n \n model = Model([input0], [mean, log_variance])\n return model",
"_____no_output_____"
],
[
"def get_decoder_cnn():\n input0 = Input()\n linear = Linear(Z_DIM, 2048)(input0)\n linear = Linear(2048, 4*4*ENCODER_FILTER_NUM * 8)(linear)\n reshape = Reshape([ENCODER_FILTER_NUM * 8, 4, 4])(linear)\n bn = SpatialBatchNormalization(ENCODER_FILTER_NUM * 8)(reshape)\n \n # upsampling\n up1 = upsample_conv_bn_lrelu(ENCODER_FILTER_NUM*8, ENCODER_FILTER_NUM*4, 8, 8)(bn) # 8 * 8 * 128\n up2 = upsample_conv_bn_lrelu(ENCODER_FILTER_NUM*4, ENCODER_FILTER_NUM*2, 16, 16)(up1) # 16 * 16 * 64\n up3 = upsample_conv_bn_lrelu(ENCODER_FILTER_NUM*2, ENCODER_FILTER_NUM, 32, 32)(up2) # 32 * 32 * 32\n up4 = upsample_conv_bn_lrelu(ENCODER_FILTER_NUM, 3, 64, 64)(up3) # 64 * 64 * 3\n output = Sigmoid()(up4)\n \n model = Model([input0], [output])\n return model",
"_____no_output_____"
],
[
"def get_autoencoder_cnn():\n input0 = Input()\n encoder = get_encoder_cnn()(input0)\n sampler = GaussianSampler()(encoder)\n \n decoder_model = get_decoder_cnn()\n decoder = decoder_model(sampler)\n \n model = Model([input0], [encoder, decoder])\n return model, decoder_model",
"_____no_output_____"
],
[
"model, decoder = get_autoencoder_cnn()",
"creating: createInput\ncreating: createInput\ncreating: createSequential\ncreating: createSpatialConvolution\ncreating: createSpatialBatchNormalization\ncreating: createLeakyReLU\ncreating: createSequential\ncreating: createSpatialConvolution\ncreating: createSpatialBatchNormalization\ncreating: createLeakyReLU\ncreating: createSequential\ncreating: createSpatialConvolution\ncreating: createSpatialBatchNormalization\ncreating: createLeakyReLU\ncreating: createSequential\ncreating: createSpatialConvolution\ncreating: createSpatialBatchNormalization\ncreating: createLeakyReLU\ncreating: createView\ncreating: createLinear\ncreating: createBatchNormalization\ncreating: createReLU\ncreating: createLinear\ncreating: createLinear\ncreating: createModel\ncreating: createGaussianSampler\ncreating: createInput\ncreating: createLinear\ncreating: createLinear\ncreating: createReshape\ncreating: createSpatialBatchNormalization\ncreating: createSequential\ncreating: createResizeBilinear\ncreating: createSpatialConvolution\ncreating: createSpatialBatchNormalization\ncreating: createLeakyReLU\ncreating: createSequential\ncreating: createResizeBilinear\ncreating: createSpatialConvolution\ncreating: createSpatialBatchNormalization\ncreating: createLeakyReLU\ncreating: createSequential\ncreating: createResizeBilinear\ncreating: createSpatialConvolution\ncreating: createSpatialBatchNormalization\ncreating: createLeakyReLU\ncreating: createSequential\ncreating: createResizeBilinear\ncreating: createSpatialConvolution\ncreating: createSpatialBatchNormalization\ncreating: createLeakyReLU\ncreating: createSigmoid\ncreating: createModel\ncreating: createModel\n"
]
],
[
[
"## Load the Dataset",
"_____no_output_____"
]
],
[
[
"def get_data():\n data_files = glob(os.path.join(DATA_PATH, \"*.jpg\"))\n \n rdd_train_images = sc.parallelize(data_files[:100000]) \\\n .map(lambda path: inverse_transform(get_image(path, image_size)).transpose(2, 0, 1))\n rdd_train_sample = rdd_train_images.map(lambda img: Sample.from_ndarray(img, [np.array(0.0), img]))\n return rdd_train_sample",
"_____no_output_____"
],
[
"train_data = get_data()\n\n",
"_____no_output_____"
]
],
[
[
"## Define the Training Objective",
"_____no_output_____"
]
],
[
[
"criterion = ParallelCriterion()\ncriterion.add(KLDCriterion(), 1.0) # You may want to twick this parameter\ncriterion.add(BCECriterion(size_average=False), 1.0 / 64)",
"creating: createParallelCriterion\ncreating: createKLDCriterion\ncreating: createBCECriterion\n"
]
],
[
[
"## Define the Optimizer",
"_____no_output_____"
]
],
[
[
"batch_size = 100\n\n\n# Create an Optimizer\noptimizer = Optimizer(\n model=model,\n training_rdd=train_data,\n criterion=criterion,\n optim_method=Adam(0.001, beta1=0.5),\n end_trigger=MaxEpoch(1),\n batch_size=batch_size)\n\n\napp_name='vea-'+dt.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\ntrain_summary = TrainSummary(log_dir='/tmp/vae',\n app_name=app_name)\n\ntrain_summary.set_summary_trigger(\"LearningRate\", SeveralIteration(10))\ntrain_summary.set_summary_trigger(\"Parameters\", EveryEpoch())\n\n\noptimizer.set_train_summary(train_summary)\n\nprint (\"saving logs to \",app_name)",
"creating: createAdam\ncreating: createMaxEpoch\ncreating: createDistriOptimizer\ncreating: createTrainSummary\ncreating: createSeveralIteration\ncreating: createEveryEpoch\n('saving logs to ', 'vea-20180514-113346')\n"
]
],
[
[
"## Spin Up the Training",
"_____no_output_____"
],
[
"This could take a while. It took about 2 hours on a desktop with a intel i7-6700 cpu and 40GB java heap memory. You can reduce the training time by using less data (some changes in the \"Load the Dataset\" section), but the performce may not as good.",
"_____no_output_____"
]
],
[
[
"redire_spark_logs()\nshow_bigdl_info_logs()",
"_____no_output_____"
],
[
"def gen_image_row():\n decoder.evaluate()\n return np.column_stack([decoder.forward(np.random.randn(1, Z_DIM)).reshape(3, 64,64).transpose(1, 2, 0) for s in range(8)])\n\ndef gen_image():\n return np.row_stack([gen_image_row() for i in range(8)])",
"_____no_output_____"
],
[
"for i in range(1, 6):\n optimizer.set_end_when(MaxEpoch(i))\n trained_model = optimizer.optimize()\n image = gen_image()\n if not os.path.exists(\"./images\"):\n os.makedirs(\"./images\")\n if not os.path.exists(\"./models\"):\n os.makedirs(\"./models\")\n # you may change the following directory accordingly and make sure the directory\n # you are writing to exists\n imageio.imwrite(\"./images/image_%s.png\" % i , image)\n decoder.saveModel(\"./models/decoder_%s.model\" % i, over_write = True)",
"creating: createMaxEpoch\n"
],
[
"import matplotlib\nmatplotlib.use('Agg')\n%pylab inline\n\nimport numpy as np\nimport datetime as dt\nimport matplotlib.pyplot as plt",
"Populating the interactive namespace from numpy and matplotlib\n"
],
[
"loss = np.array(train_summary.read_scalar(\"Loss\"))\n\nplt.figure(figsize = (12,12))\nplt.plot(loss[:,0],loss[:,1],label='loss')\nplt.xlim(0,loss.shape[0]+10)\nplt.grid(True)\nplt.title(\"loss\")",
"_____no_output_____"
]
],
[
[
"## Random Sample Some Images",
"_____no_output_____"
]
],
[
[
"from matplotlib.pyplot import imshow\nimg = gen_image()\nimshow(img)",
"_____no_output_____"
]
]
]
| [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
]
| [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
]
|
cb5f4b5bb6a94876551006dae6c0180860a67851 | 11,681 | ipynb | Jupyter Notebook | week3/exercises/.ipynb_checkpoints/Regularization_exc-checkpoint.ipynb | boraatlay/bootcamp | 2c8bb94401ad528e8c589d63184debf5bac4184b | [
"MIT"
]
| null | null | null | week3/exercises/.ipynb_checkpoints/Regularization_exc-checkpoint.ipynb | boraatlay/bootcamp | 2c8bb94401ad528e8c589d63184debf5bac4184b | [
"MIT"
]
| null | null | null | week3/exercises/.ipynb_checkpoints/Regularization_exc-checkpoint.ipynb | boraatlay/bootcamp | 2c8bb94401ad528e8c589d63184debf5bac4184b | [
"MIT"
]
| null | null | null | 42.169675 | 5,976 | 0.702851 | [
[
[
"### Importing essentials\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n### Importing sciKit-learn stuff\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.linear_model import LinearRegression",
"_____no_output_____"
],
[
"#df = pd.DataFrame(np.array([[1.0, 1.6, 2.0],[1.0, 2.5, 3.0]]),columns=['x', 'y'])\n#df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),columns=['a', 'b', 'c'])\ndf1= {'x': [1.0,2.5,3],\n 'y': [1.0,1.6,2.0]}",
"_____no_output_____"
],
[
"df=pd.DataFrame(df1)",
"_____no_output_____"
],
[
"df",
"_____no_output_____"
],
[
"sns.scatterplot(data=df,x='x', y='y')",
"_____no_output_____"
],
[
"w_list = [0.5, 2.0]\nregstr = 1",
"_____no_output_____"
],
[
"y = df['y']\nx = df['x']",
"_____no_output_____"
],
[
"def CalcLinReg(w, x, y):\n \n y_preds = [1.] * len(y) ### Predicted y values\n res_quad = [1.] * len(y) ### List of quadratic residuals\n \n for i in range(len(x)):\n y_preds[i] = w[1] * x[i] + w[0]\n res_quad[i] = (y_preds[i] - y[i])**2\n \n return res_quad",
"_____no_output_____"
],
[
"sumw2 = w_list[0]**2 + w_list[1]**2",
"_____no_output_____"
],
[
"print(sumw2)",
"4.25\n"
],
[
"linreg = sum(CalcLinReg(w_list, x, y)) / len(y)\n\nlinrid = sum(CalcLinReg(w_list, x, y)) / len(y) + regstr * sumw2",
"_____no_output_____"
],
[
"print(linreg)\nprint(linrid)",
"12.57\n16.82\n"
]
]
]
| [
"code"
]
| [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
]
|
cb5f56a008e2892c5a60abd4e1d27b8476adaf81 | 15,391 | ipynb | Jupyter Notebook | DEEP_NLP_resources/3-Deep-Learning for NLP/LSTM and GRU on Sentiment Analysis.ipynb | YaqianQi/Coursera | b42696bdf88ac27652436311efae650ada699e63 | [
"MIT"
]
| 3 | 2020-04-08T13:33:21.000Z | 2021-06-24T06:25:40.000Z | DEEP_NLP_resources/3-Deep-Learning for NLP/LSTM and GRU on Sentiment Analysis.ipynb | YaqianQi/Coursera | b42696bdf88ac27652436311efae650ada699e63 | [
"MIT"
]
| null | null | null | DEEP_NLP_resources/3-Deep-Learning for NLP/LSTM and GRU on Sentiment Analysis.ipynb | YaqianQi/Coursera | b42696bdf88ac27652436311efae650ada699e63 | [
"MIT"
]
| null | null | null | 20.066493 | 104 | 0.513937 | [
[
[
"<img src=\"../Pics/MLSb-T.png\" width=\"160\">\n<br><br>\n<center><u><H1>LSTM and GRU on Sentiment Analysis</H1></u></center>",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\nfrom keras.backend.tensorflow_backend import set_session\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nconfig.log_device_placement = True\nsess = tf.Session(config=config)\nset_session(sess)",
"_____no_output_____"
],
[
"import numpy as np\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Embedding, GRU, LSTM, CuDNNLSTM, CuDNNGRU, Dropout\nfrom keras.datasets import imdb\nfrom keras.callbacks import EarlyStopping\nfrom keras.optimizers import Adam",
"_____no_output_____"
],
[
"num_words = 20000",
"_____no_output_____"
],
[
"(X_train, y_train), (X_test, y_test) = imdb.load_data(num_words=num_words)",
"_____no_output_____"
],
[
"print(len(X_train), 'train_data')\nprint(len(X_test), 'test_data')",
"_____no_output_____"
],
[
"print(X_train[0])",
"_____no_output_____"
],
[
"len(X_train[0])",
"_____no_output_____"
]
],
[
[
"## Hyperparameters:",
"_____no_output_____"
]
],
[
[
"max_len = 256\nembedding_size = 10\nbatch_size = 128\nn_epochs = 10",
"_____no_output_____"
]
],
[
[
"## Creating Sequences",
"_____no_output_____"
]
],
[
[
"pad = 'pre' #'post'",
"_____no_output_____"
],
[
"X_train_pad = pad_sequences(X_train, maxlen=max_len, padding=pad, truncating=pad)\nX_test_pad = pad_sequences(X_test, maxlen=max_len, padding=pad, truncating=pad)",
"_____no_output_____"
],
[
"X_train_pad[0]",
"_____no_output_____"
]
],
[
[
"## Creating the model:",
"_____no_output_____"
]
],
[
[
"model = Sequential()",
"_____no_output_____"
],
[
"#The input is a 2D tensor: (samples, sequence_length)\n# this layer will return 3D tensor: (samples, sequence_length, embedding_dim)\nmodel.add(Embedding(input_dim=num_words,\n output_dim=embedding_size,\n input_length=max_len,\n name='layer_embedding'))",
"_____no_output_____"
],
[
"model.add(Dropout(0.2))",
"_____no_output_____"
],
[
"#model.add(LSTM(128,dropout=0.2, recurrent_dropout=0.2))",
"_____no_output_____"
],
[
"model.add(CuDNNLSTM(128, return_sequences=False))",
"_____no_output_____"
],
[
"model.add(Dropout(0.2))",
"_____no_output_____"
],
[
"model.add(Dense(1, activation='sigmoid', name='classification'))",
"_____no_output_____"
],
[
"model.summary()",
"_____no_output_____"
]
],
[
[
"## Compiling the model:",
"_____no_output_____"
]
],
[
[
"#optimizer = Adam(lr=0.001, decay=1e-6)",
"_____no_output_____"
],
[
"model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])",
"_____no_output_____"
]
],
[
[
"## Callbacks:",
"_____no_output_____"
]
],
[
[
"callback_early_stopping = EarlyStopping(monitor='val_loss', patience=5, verbose=1)",
"_____no_output_____"
]
],
[
[
"## Training the model:",
"_____no_output_____"
]
],
[
[
"%%time\nmodel.fit(X_train_pad, y_train,\n epochs=n_epochs,\n batch_size=batch_size, \n validation_split=0.05,\n callbacks=[callback_early_stopping]\n )",
"_____no_output_____"
]
],
[
[
"## Testing the model:",
"_____no_output_____"
]
],
[
[
"%%time\neval_ = model.evaluate(X_test_pad, y_test)",
"_____no_output_____"
],
[
"print(\"Loss: {0:.5}\".format(eval_[0]))\nprint(\"Accuracy: {0:.2%}\".format(eval_[1]))",
"_____no_output_____"
]
],
[
[
"## Saving the model:",
"_____no_output_____"
]
],
[
[
"model.save(\"..\\data\\models\\{}\".format('Sentiment-LSTM-GRU'))",
"_____no_output_____"
]
],
[
[
"## GRU model:",
"_____no_output_____"
]
],
[
[
"model_GRU = Sequential()",
"_____no_output_____"
],
[
"model_GRU.add(Embedding(input_dim=num_words,\n output_dim=embedding_size,\n input_length=max_len,\n name='layer_embedding'))",
"_____no_output_____"
],
[
"model_GRU.add(CuDNNGRU(units=16, return_sequences=True))",
"_____no_output_____"
],
[
"model_GRU.add(CuDNNGRU(units=8, return_sequences=True))",
"_____no_output_____"
],
[
"model_GRU.add(CuDNNGRU(units=4, return_sequences=False))",
"_____no_output_____"
],
[
"model_GRU.add(Dense(1, activation='sigmoid'))",
"_____no_output_____"
],
[
"model_GRU.summary()",
"_____no_output_____"
],
[
"model_GRU.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])",
"_____no_output_____"
],
[
"%%time\nmodel_GRU.fit(X_train_pad, y_train, validation_split=0.05, epochs=n_epochs, batch_size=batch_size)",
"_____no_output_____"
],
[
"%%time\neval_GRU = model_GRU.evaluate(X_test_pad, y_test)",
"_____no_output_____"
],
[
"print(\"Loss: {0:.5}\".format(eval_GRU[0]))\nprint(\"Accuracy: {0:.2%}\".format(eval_GRU[1]))",
"_____no_output_____"
]
],
[
[
"## Examples of Mis-Classified Text",
"_____no_output_____"
]
],
[
[
"#making predictions for the first 1000 test samples\ny_pred = model.predict(X_test_pad[:1000])",
"_____no_output_____"
],
[
"y_pred = y_pred.T[0]",
"_____no_output_____"
],
[
"labels_pred = np.array([1.0 if p > 0.5 else 0.0 for p in y_pred])",
"_____no_output_____"
],
[
"true_labels = np.array(y_test[:1000])",
"_____no_output_____"
],
[
"incorrect = np.where(labels_pred != true_labels)\nincorrect = incorrect[0]",
"_____no_output_____"
],
[
"print(incorrect)",
"_____no_output_____"
],
[
"len(incorrect)",
"_____no_output_____"
],
[
"idx = incorrect[1]\nidx",
"_____no_output_____"
],
[
"text = X_test[idx]\nprint(text)",
"_____no_output_____"
],
[
"y_pred[idx]",
"_____no_output_____"
],
[
"true_labels[idx]",
"_____no_output_____"
]
],
[
[
"## Converting integers in Text",
"_____no_output_____"
]
],
[
[
"# A dictionary mapping words to an integer index\nword_index = imdb.get_word_index()",
"_____no_output_____"
],
[
"word_index.items()",
"_____no_output_____"
],
[
"reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])\nprint(reverse_word_index)",
"_____no_output_____"
],
[
"def decode_index(text):\n return ' '.join([reverse_word_index.get(i) for i in text])",
"_____no_output_____"
],
[
"decode_index(X_train[0])",
"_____no_output_____"
],
[
"text_data = []\nfor i in range(len(X_train)):\n text_data.append(decode_index(X_train[i]))",
"_____no_output_____"
],
[
"text_data[0]",
"_____no_output_____"
]
],
[
[
"## Embeddings",
"_____no_output_____"
]
],
[
[
"layer_embedding = model.get_layer('layer_embedding')",
"_____no_output_____"
],
[
"weights_embedding = layer_embedding.get_weights()[0]",
"_____no_output_____"
],
[
"weights_embedding.shape",
"_____no_output_____"
],
[
"weights_embedding[word_index.get('good')]",
"_____no_output_____"
]
],
[
[
"## Similar Words",
"_____no_output_____"
]
],
[
[
"from scipy.spatial.distance import cdist",
"_____no_output_____"
],
[
"def print_similar_words(word, metric='cosine'):\n \n token = word_index.get(word)\n\n embedding = weights_embedding[token]\n\n distances = cdist(weights_embedding, [embedding],\n metric=metric).T[0]\n \n sorted_index = np.argsort(distances)\n \n sorted_distances = distances[sorted_index]\n \n sorted_words = [reverse_word_index[token] for token in sorted_index\n if token != 0]\n\n def print_words(words, distances):\n for word, distance in zip(words, distances):\n print(\"{0:.3f} - {1}\".format(distance, word))\n\n N = 10\n\n print(\"Distance from '{0}':\".format(word))\n\n print_words(sorted_words[0:N], sorted_distances[0:N])\n\n print(\"-------\")\n\n print_words(sorted_words[-N:], sorted_distances[-N:])",
"_____no_output_____"
],
[
"print_similar_words('good', metric='cosine')",
"_____no_output_____"
]
],
[
[
"## Reference:\n\nhttps://keras.io/layers/recurrent/",
"_____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",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
]
]
|
cb5f57ec71b184604941e23d82b3c2b0f7de1bbf | 5,680 | ipynb | Jupyter Notebook | examples/user_guide/Introduction.ipynb | jonmmease/hvplot | d3330223a940efdf8faad0fef1f5c7ad1f5a8033 | [
"BSD-3-Clause"
]
| null | null | null | examples/user_guide/Introduction.ipynb | jonmmease/hvplot | d3330223a940efdf8faad0fef1f5c7ad1f5a8033 | [
"BSD-3-Clause"
]
| null | null | null | examples/user_guide/Introduction.ipynb | jonmmease/hvplot | d3330223a940efdf8faad0fef1f5c7ad1f5a8033 | [
"BSD-3-Clause"
]
| 1 | 2020-06-09T16:30:21.000Z | 2020-06-09T16:30:21.000Z | 38.120805 | 439 | 0.641021 | [
[
[
"The PyData ecosystem has a number of core Python data containers that allow users to work with a wide array of datatypes, including:\n\n* [Pandas](http://pandas.pydata.org): DataFrame, Series (columnar/tabular data)\n* [XArray](http://xarray.pydata.org): Dataset, DataArray (multidimensional arrays)\n* [Dask](http://dask.pydata.org): DataFrame, Series, Array (distributed/out of core arrays and columnar data)\n* [Streamz](http://streamz.readthedocs.io): DataFrame(s), Series(s) (streaming columnar data)\n* [Intake](http://github.com/ContinuumIO/intake): DataSource (remote data)\n\nMany of these libraries have the concept of a high-level plotting API that lets a user generate common plot types very easily. The native plotting APIs are generally built on [Matplotlib](http://matplotlib.org), which provides a solid foundation, but means that users miss out the benefits of modern, interactive plotting libraries for the web like [Bokeh](http://bokeh.pydata.org) and [HoloViews](http://holoviews.org).\n\nhvPlot provides a high-level plotting API built on HoloViews and Bokeh that provides a general and consistent API for plotting data in all the abovementioned formats.\n\nAs a first simple illustration of using hvPlot, let's create a small set of random data in Pandas to explore:",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\n\nindex = pd.date_range('1/1/2000', periods=1000)\ndf = pd.DataFrame(np.random.randn(1000, 4), index=index, columns=list('ABCD')).cumsum()\n\ndf.head()",
"_____no_output_____"
]
],
[
[
"## Pandas default .plot()\n\nPandas provides Matplotlib-based plotting by default, using the `.plot()` method:",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n\ndf.plot();",
"_____no_output_____"
]
],
[
[
"The result is a PNG image that displays easily, but is otherwise static.\n\n## .hvplot()\n\nIf we instead change `%matplotlib inline` to `import hvplot.pandas` and use the ``df.hvplot`` method, it will now display an interactively explorable [Bokeh](http://bokeh.pydata.org) plot with panning, zooming, hovering, and clickable/selectable legends:",
"_____no_output_____"
]
],
[
[
"import hvplot.pandas\n\ndf.hvplot()",
"_____no_output_____"
]
],
[
[
"This interactive plot makes it much easier to explore the properties of the data, without having to write code to select ranges, columns, or data values manually. Note that while pandas, dask and xarray all use the ``.hvplot`` method, ``intake`` uses hvPlot as its main plotting API, which means that is available using ``.plot()``. \n\n## hvPlot native API\n\nFor the plot above, hvPlot dynamically added the Pandas `.hvplot()` method, so that you can use the same syntax as with the Pandas default plotting. If you prefer to be more explicit, you can instead work directly with hvPlot objects:",
"_____no_output_____"
]
],
[
[
"from hvplot import hvPlot\nimport holoviews as hv\nhv.extension('bokeh')\n\nplot = hvPlot(df)\nplot(y='A')",
"_____no_output_____"
]
],
[
[
"Here we've imported the HoloViews and hvPlot libraries, loaded the HoloViews extension that initializes it to create Bokeh plots inside Jupyter notebooks, created a hvPlot object `plot` for our dataframe, generated a viewable HoloViews object from it by calling `plot()` (here with some additional options to select one column for plotting), and then had Juypter display the resulting HoloViews object using Bokeh in the notebook.\n\nIn most cases we'll assume you are using the simpler `import hvplot.pandas` approach that takes care of all these steps for you, but if you prefer you are welcome to break them down explicitly in this way.\n\n## Getting help\n\nWhen working inside IPython or the Jupyter notebook hvplot methods will automatically complete valid keywords, e.g. pressing tab after declaring the plot type will provide all valid keywords and the docstring:\n\n```python\ndf.hvplot.line(<TAB>\n```\n\nOutside an interactive environment ``hvplot.help`` will bring up information providing the ``kind`` of plot, e.g.:\n\n```python\nhvplot.help('line')\n```\n\nFor more detail on the available options see the [Customization](Customization.ipynb) user guide.",
"_____no_output_____"
],
[
"\n## Next steps\n\nNow that you can see how hvPlot is used, let's jump straight in and discover some of the more powerful things we can do with it in the [Plotting](Plotting.ipynb) section.",
"_____no_output_____"
]
]
]
| [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
]
| [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
]
|
cb5f7abc3034e694a92857fd580aafc3d43cd65d | 20,024 | ipynb | Jupyter Notebook | cnn.ipynb | tlkh/simple-news-classifier | bf308026a7fb36d35a78a8d79c8b01e23efef1a3 | [
"MIT"
]
| null | null | null | cnn.ipynb | tlkh/simple-news-classifier | bf308026a7fb36d35a78a8d79c8b01e23efef1a3 | [
"MIT"
]
| null | null | null | cnn.ipynb | tlkh/simple-news-classifier | bf308026a7fb36d35a78a8d79c8b01e23efef1a3 | [
"MIT"
]
| null | null | null | 49.935162 | 1,449 | 0.597733 | [
[
[
"import pickle\nwith open('cleaned_texts.pickle', 'rb') as handle:\n texts = pickle.load(handle)\n \nwith open('labels.pickle', 'rb') as handle:\n labels = pickle.load(handle)",
"_____no_output_____"
],
[
"MAX_NB_WORDS = 100000 # max no. of words for tokenizer\nMAX_SEQUENCE_LENGTH = 400 # max length of each entry (sentence), including padding\nVALIDATION_SPLIT = 0.2\nEMBEDDING_DIM = 50 # embedding dimensions for word vectors (word2vec/GloVe)\nGLOVE_DIR = \"glove/glove.6B/glove.6B.\"+str(EMBEDDING_DIM)+\"d.txt\"",
"_____no_output_____"
],
[
"shortened_texts = []\nfor text in texts:\n shortened_texts.append(text[:MAX_SEQUENCE_LENGTH])",
"_____no_output_____"
],
[
"classes = [\"fake\", \"satire\", \"bias\", \"conspiracy\", \"state\", \"junksci\", \"hate\", \"clickbait\", \"unreliable\", \"political\", \"reliable\"]\ncat_labels = []\nfor label in labels:\n cat_labels.append(classes.index(label))",
"_____no_output_____"
],
[
"import numpy as np\nimport pandas as pd\nimport re, sys, os, csv, keras, pickle\nfrom keras import regularizers, initializers, optimizers, callbacks\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.utils.np_utils import to_categorical\nfrom keras.layers import *\nfrom keras.models import Model\nfrom keras import backend as K\nfrom keras.engine.topology import Layer, InputSpec\nprint(\"[i] Using Keras version\",keras.__version__)",
"Using TensorFlow backend.\n"
],
[
"\"\"\" #uncomment this chunk to create a new Tokenizer\ntokenizer = Tokenizer(num_words=MAX_NB_WORDS/2)\ntokenizer.fit_on_texts(shortened_texts)\nwith open('tokenizer.pickle', 'wb') as handle:\n pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL)\nprint(\"[i] Saved word tokenizer to file: tokenizer.pickle\")\n\"\"\"\n\nwith open('tokenizer.pickle', 'rb') as handle:\n tokenizer = pickle.load(handle) # load a previously generated Tokenizer",
"_____no_output_____"
],
[
"word_index = tokenizer.word_index\nprint('[i] Found %s unique tokens.' % len(word_index))",
"[i] Found 1404620 unique tokens.\n"
],
[
"sequences = tokenizer.texts_to_sequences(shortened_texts)\ndata = pad_sequences(sequences, padding='post', maxlen=(MAX_SEQUENCE_LENGTH))",
"_____no_output_____"
],
[
"labels = to_categorical(np.asarray(cat_labels)) # convert the category label to one-hot encoding\nprint('[i] Shape of data tensor:', data.shape)\nprint('[i] Shape of label tensor:', labels.shape)\n\nindices = np.arange(data.shape[0])\nnp.random.shuffle(indices)\ndata = data[indices]\nlabels = labels[indices]\nnb_validation_samples = int(VALIDATION_SPLIT * data.shape[0])\nx_train = data[:-nb_validation_samples]\ny_train = labels[:-nb_validation_samples]\nx_val = data[-nb_validation_samples:]\ny_val = labels[-nb_validation_samples:]\n\nprint('[i] Number of entries in each category:')\nprint(\"[+] Training:\",y_train.sum(axis=0))\nprint(\"[+] Validation:\",y_val.sum(axis=0))",
"[i] Shape of data tensor: (6319863, 400)\n[i] Shape of label tensor: (6319863, 11)\n[i] Number of entries in each category:\n[+] Training: [ 634544. 89082. 801549. 586993. 0. 81484. 48620. 171051.\n 221723. 1098747. 1322098.]\n[+] Validation: [158380. 22354. 200538. 146668. 0. 20437. 12209. 42702. 55470.\n 274801. 330413.]\n"
],
[
"embeddings_index = {}\nf = open(GLOVE_DIR)\nprint(\"[i] (long) Loading GloVe from:\",GLOVE_DIR,\"...\",end=\"\")\nfor line in f:\n values = line.split()\n word = values[0]\n embeddings_index[word] = np.asarray(values[1:], dtype='float32')\nf.close()\nprint(\"Done.\\n[+] Proceeding with Embedding Matrix...\", end=\"\")\nembedding_matrix = np.random.random((len(word_index) + 1, EMBEDDING_DIM))\nfor word, i in word_index.items():\n embedding_vector = embeddings_index.get(word)\n if embedding_vector is not None:\n # words not found in embedding index will be all-zeros.\n embedding_matrix[i] = embedding_vector\nprint(\" Completed!\")",
"[i] (long) Loading GloVe from: glove/glove.6B/glove.6B.50d.txt ...Done.\n[+] Proceeding with Embedding Matrix... Completed!\n"
],
[
"sequence_input = Input(shape=(MAX_SEQUENCE_LENGTH,), dtype='int32') # input to the model\n\nembedding_layer = Embedding(len(word_index) + 1,\n EMBEDDING_DIM,\n weights=[embedding_matrix],\n input_length=MAX_SEQUENCE_LENGTH,\n trainable=True)\n\nembedded_sequences = embedding_layer(sequence_input)",
"_____no_output_____"
],
[
"l_conv_3 = Conv1D(filters=256,kernel_size=3,activation='relu')(embedded_sequences)\nl_conv_4 = Conv1D(filters=256,kernel_size=5,activation='relu')(embedded_sequences)\nl_conv_5 = Conv1D(filters=256,kernel_size=7,activation='relu',)(embedded_sequences)\n\nl_conv = Concatenate(axis=1)([l_conv_3, l_conv_4, l_conv_5])",
"_____no_output_____"
],
[
"l_pool = MaxPooling1D(4)(l_conv)\nl_drop = Dropout(0.3)(l_pool)\nl_flat = GlobalAveragePooling1D()(l_drop)\nl_dense = Dense(128, activation='relu')(l_flat)\npreds = Dense(11, activation='softmax')(l_dense) #follows the number of classes",
"_____no_output_____"
],
[
"from keras.utils import multi_gpu_model\nimport tensorflow as tf\n\nwith tf.device('/cpu:0'):\n model = Model(sequence_input, preds)\n \nadadelta = optimizers.Adadelta(lr=2.0, rho=0.95, epsilon=None, decay=0.1)\n\nparallel_model = multi_gpu_model(model, gpus=2)\nparallel_model.compile(loss='categorical_crossentropy',\n optimizer=adadelta,\n metrics=['acc'])\n\nmodel.summary()",
"__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_1 (InputLayer) (None, 400) 0 \n__________________________________________________________________________________________________\nembedding_1 (Embedding) (None, 400, 50) 70231050 input_1[0][0] \n__________________________________________________________________________________________________\nconv1d_1 (Conv1D) (None, 398, 256) 38656 embedding_1[0][0] \n__________________________________________________________________________________________________\nconv1d_2 (Conv1D) (None, 396, 256) 64256 embedding_1[0][0] \n__________________________________________________________________________________________________\nconv1d_3 (Conv1D) (None, 394, 256) 89856 embedding_1[0][0] \n__________________________________________________________________________________________________\nconcatenate_1 (Concatenate) (None, 1188, 256) 0 conv1d_1[0][0] \n conv1d_2[0][0] \n conv1d_3[0][0] \n__________________________________________________________________________________________________\nmax_pooling1d_1 (MaxPooling1D) (None, 297, 256) 0 concatenate_1[0][0] \n__________________________________________________________________________________________________\ndropout_1 (Dropout) (None, 297, 256) 0 max_pooling1d_1[0][0] \n__________________________________________________________________________________________________\nglobal_average_pooling1d_1 (Glo (None, 256) 0 dropout_1[0][0] \n__________________________________________________________________________________________________\ndense_1 (Dense) (None, 128) 32896 global_average_pooling1d_1[0][0] \n__________________________________________________________________________________________________\ndense_2 (Dense) (None, 11) 1419 dense_1[0][0] \n==================================================================================================\nTotal params: 70,458,133\nTrainable params: 70,458,133\nNon-trainable params: 0\n__________________________________________________________________________________________________\n"
],
[
"#adadelta = optimizers.Adadelta(lr=2.0, rho=0.95, epsilon=None, decay=0.1) # let's use a hipster optimizer because we can\n#model.compile(loss='categorical_crossentropy',\n# optimizer=adadelta,\n# metrics=['acc'])\n#model.summary()",
"_____no_output_____"
],
[
"print(\"Training Progress:\")\nmodel_log = parallel_model.fit(x_train, y_train, validation_data=(x_val, y_val),\n epochs=30, batch_size=512)",
"Training Progress:\nTrain on 5055891 samples, validate on 1263972 samples\nEpoch 1/30\n5055891/5055891 [==============================] - 927s 183us/step - loss: 1.8031 - acc: 0.3552 - val_loss: 1.7741 - val_acc: 0.3675\nEpoch 2/30\n5055891/5055891 [==============================] - 933s 185us/step - loss: 1.7606 - acc: 0.3698 - val_loss: 1.7490 - val_acc: 0.3723\nEpoch 3/30\n4547072/5055891 [=========================>....] - ETA: 1:27 - loss: 1.7420 - acc: 0.3729"
]
]
]
| [
"code"
]
| [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
]
|
cb5f81bbb333329d6591abfb86a470aa33f41aa1 | 38,855 | ipynb | Jupyter Notebook | scripts/example_pipeline.ipynb | VIDA-NYU/alphad3m | db40193a448300d87442c451f9da17fa5cb845fd | [
"Apache-2.0"
]
| null | null | null | scripts/example_pipeline.ipynb | VIDA-NYU/alphad3m | db40193a448300d87442c451f9da17fa5cb845fd | [
"Apache-2.0"
]
| null | null | null | scripts/example_pipeline.ipynb | VIDA-NYU/alphad3m | db40193a448300d87442c451f9da17fa5cb845fd | [
"Apache-2.0"
]
| 1 | 2021-11-22T16:33:47.000Z | 2021-11-22T16:33:47.000Z | 29.91147 | 232 | 0.320345 | [
[
[
"# Load dataset & problem",
"_____no_output_____"
]
],
[
[
"import pickle\n\nfrom d3m_ta2_nyu.d3mds import D3MDS",
"_____no_output_____"
],
[
"ds = D3MDS('data/LL0_21_car/LL0_21_car_dataset',\n 'data/LL0_21_car/LL0_21_car_problem')",
"_____no_output_____"
],
[
"train_data = ds.get_train_data()\ntrain_data.head()",
"_____no_output_____"
],
[
"train_targets = ds.get_train_targets()",
"_____no_output_____"
],
[
"test_data = ds.get_test_data()\ntest_data.head()",
"_____no_output_____"
],
[
"test_targets = ds.get_test_targets()",
"_____no_output_____"
],
[
"len(train_data), len(train_targets), len(test_data), len(test_targets)",
"_____no_output_____"
]
],
[
[
"# Imputation using dsbox",
"_____no_output_____"
]
],
[
[
"from dsbox.datapreprocessing.cleaner import KNNImputation, KnnHyperparameter",
"Using TensorFlow backend.\n/Users/remram/Documents/programming/_venvs/d3m/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: compiletime version 3.5 of module 'tensorflow.python.framework.fast_tensor_util' does not match runtime version 3.6\n return f(*args, **kwds)\n"
],
[
"imputer = KNNImputation(hyperparams=KnnHyperparameter.defaults())",
"_____no_output_____"
],
[
"results = imputer.produce(inputs=train_data)\nassert results.has_finished\ntrain_data = results.value\ntrain_data.head()",
"Exception in thread Thread-4:\nTraceback (most recent call last):\n File \"/opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py\", line 916, in _bootstrap_inner\n self.run()\n File \"/opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py\", line 1180, in run\n self.finished.wait(self.interval)\n File \"/opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py\", line 551, in wait\n signaled = self._cond.wait(timeout)\n File \"/opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py\", line 299, in wait\n gotit = waiter.acquire(True, timeout)\nOverflowError: timestamp too large to convert to C _PyTime_t\n\n"
],
[
"results = imputer.produce(inputs=test_data)\nassert results.has_finished\ntest_data = results.value\ntest_data.head()",
"Exception in thread Thread-5:\nTraceback (most recent call last):\n File \"/opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py\", line 916, in _bootstrap_inner\n self.run()\n File \"/opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py\", line 1180, in run\n self.finished.wait(self.interval)\n File \"/opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py\", line 551, in wait\n signaled = self._cond.wait(timeout)\n File \"/opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py\", line 299, in wait\n gotit = waiter.acquire(True, timeout)\nOverflowError: timestamp too large to convert to C _PyTime_t\n\n"
]
],
[
[
"# Encoding using dsbox",
"_____no_output_____"
]
],
[
[
"from dsbox.datapreprocessing.cleaner import Encoder, EncHyperparameter",
"_____no_output_____"
],
[
"encoder = Encoder(hyperparams=EncHyperparameter.defaults())",
"_____no_output_____"
],
[
"encoder.set_training_data(inputs=train_data)\nencoder.fit()",
"_____no_output_____"
],
[
"params = pickle.loads(pickle.dumps(encoder.get_params()))",
"_____no_output_____"
],
[
"hparams = EncHyperparameter(pickle.loads(pickle.dumps(dict(encoder.hyperparams))))",
"_____no_output_____"
],
[
"encoder = Encoder(hyperparams=hparams)\nencoder.set_params(params=params)",
"_____no_output_____"
],
[
"results = encoder.produce(inputs=train_data)\nassert results.has_finished\ntrain_data = results.value\ntrain_data.head()",
"_____no_output_____"
],
[
"results = encoder.produce(inputs=test_data)\nassert results.has_finished\ntest_data = results.value\ntest_data.head()",
"_____no_output_____"
]
],
[
[
"# Classification",
"_____no_output_____"
]
],
[
[
"ds.problem.prDoc['about']['taskType'], ds.problem.prDoc['about']['taskSubType']",
"_____no_output_____"
],
[
"from sklearn.neighbors.classification import KNeighborsClassifier",
"_____no_output_____"
],
[
"classifier = KNeighborsClassifier()",
"_____no_output_____"
],
[
"classifier.fit(train_data, train_targets)",
"_____no_output_____"
],
[
"prediction = classifier.predict(test_data)",
"_____no_output_____"
],
[
"print(\"{} / {}\".format(sum(1 for i, j in zip(prediction, test_targets) if i == j), len(test_targets)))",
"295 / 345\n"
]
]
]
| [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
]
| [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
]
|
cb5f81fa2bd50482f087985aa36b19dfc3b8388f | 972,930 | ipynb | Jupyter Notebook | temp.ipynb | anandsaha/handson-ml-book-exercises | f2fa82167e83489e1e7afc86c0da38a331bb93e8 | [
"MIT"
]
| null | null | null | temp.ipynb | anandsaha/handson-ml-book-exercises | f2fa82167e83489e1e7afc86c0da38a331bb93e8 | [
"MIT"
]
| null | null | null | temp.ipynb | anandsaha/handson-ml-book-exercises | f2fa82167e83489e1e7afc86c0da38a331bb93e8 | [
"MIT"
]
| null | null | null | 978.802817 | 265,084 | 0.947915 | [
[
[
"import os\nimport tarfile\nfrom six.moves import urllib\n\nDOWNLOAD_ROOT = \"https://raw.githubusercontent.com/ageron/handson-ml/master/\"\nHOUSING_PATH = \"datasets/housing\"\nHOUSING_URL = DOWNLOAD_ROOT + HOUSING_PATH + \"/housing.tgz\"\n",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
],
[
"import pandas as pd\n\ndef load_housing_data(housing_path=HOUSING_PATH):\n csv_path = os.path.join(housing_path, \"housing.csv\")\n return pd.read_csv(csv_path)",
"_____no_output_____"
],
[
"housing = load_housing_data()",
"_____no_output_____"
],
[
"housing.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 20640 entries, 0 to 20639\nData columns (total 10 columns):\nlongitude 20640 non-null float64\nlatitude 20640 non-null float64\nhousing_median_age 20640 non-null float64\ntotal_rooms 20640 non-null float64\ntotal_bedrooms 20433 non-null float64\npopulation 20640 non-null float64\nhouseholds 20640 non-null float64\nmedian_income 20640 non-null float64\nmedian_house_value 20640 non-null float64\nocean_proximity 20640 non-null object\ndtypes: float64(9), object(1)\nmemory usage: 1.6+ MB\n"
],
[
"housing_num = housing.drop(['ocean_proximity'], axis=1)\nhousing_cat = housing['ocean_proximity'].values.reshape(-1, 1)",
"_____no_output_____"
],
[
"housing_num.shape",
"_____no_output_____"
],
[
"housing_cat.shape",
"_____no_output_____"
],
[
"type(housing_num)",
"_____no_output_____"
],
[
"type(housing_cat)",
"_____no_output_____"
]
],
[
[
"Histogram",
"_____no_output_____"
]
],
[
[
"housing_num.hist(bins=50, figsize=(10, 10))",
"_____no_output_____"
]
],
[
[
"Splitting data",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import train_test_split",
"_____no_output_____"
],
[
"train_set, test_set = train_test_split(housing, test_size=0.2, random_state=42)",
"_____no_output_____"
],
[
"train_set.hist(bins=50, figsize=(10, 10))",
"_____no_output_____"
]
],
[
[
"Stratified Shuffle",
"_____no_output_____"
]
],
[
[
"import numpy as np",
"_____no_output_____"
],
[
"housing['income_cat'] = np.ceil(housing['median_income'] / 1.5)\nhousing[\"income_cat\"].where(housing[\"income_cat\"] < 5, 5.0, inplace=True)",
"_____no_output_____"
],
[
"housing['income_cat'].value_counts()/len(housing)",
"_____no_output_____"
],
[
"from sklearn.model_selection import StratifiedShuffleSplit\nsplit = StratifiedShuffleSplit(n_splits=1,test_size=0.2, random_state=42)\nfor train_idx, test_idx in split.split(housing, housing['income_cat']):\n strat_train = housing.loc[train_idx]\n strat_test = housing.loc[test_idx]\n \nstrat_train.drop(['income_cat'], axis=1, inplace=True)\nstrat_test.drop(['income_cat'], axis=1, inplace=True)\nstrat_train.hist(bins=50, figsize=(10, 10))\nstrat_test.hist(bins=50, figsize=(10, 10))",
"_____no_output_____"
],
[
"strat_test.plot(kind=\"scatter\", x=\"longitude\", y=\"latitude\", alpha=0.05)",
"_____no_output_____"
],
[
"strat_train.plot(kind=\"scatter\", x=\"longitude\", y=\"latitude\", alpha=0.05)",
"_____no_output_____"
],
[
"import matplotlib.cm as cm",
"_____no_output_____"
],
[
"housing.plot(kind='scatter', x=\"longitude\", y=\"latitude\", alpha=0.4, figsize=(15, 10),\n c='median_house_value', s=housing[\"population\"]/100, cmap=plt.get_cmap(\"jet\"), colorbar=True)",
"_____no_output_____"
],
[
"corr = housing.corr()\ncorr[\"median_house_value\"].sort_values(ascending=False)",
"_____no_output_____"
],
[
"from pandas.tools.plotting import scatter_matrix",
"_____no_output_____"
],
[
"attr = [\"median_house_value\", \"median_income\", \"total_rooms\", \"housing_median_age\"]\nscatter_matrix(housing[attr], figsize=(10, 10))",
"_____no_output_____"
],
[
"housing.plot(kind='scatter', x='median_income', y='median_house_value', alpha=0.05, figsize=(10, 10))",
"_____no_output_____"
],
[
"from sklearn.preprocessing import Imputer",
"_____no_output_____"
],
[
"imp = Imputer(strategy='median')",
"_____no_output_____"
],
[
"housing = train_set.copy()",
"_____no_output_____"
],
[
"housing.info()",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 16512 entries, 14196 to 15795\nData columns (total 10 columns):\nlongitude 16512 non-null float64\nlatitude 16512 non-null float64\nhousing_median_age 16512 non-null float64\ntotal_rooms 16512 non-null float64\ntotal_bedrooms 16512 non-null float64\npopulation 16512 non-null float64\nhouseholds 16512 non-null float64\nmedian_income 16512 non-null float64\nmedian_house_value 16512 non-null float64\nocean_proximity 16512 non-null object\ndtypes: float64(9), object(1)\nmemory usage: 1.4+ MB\n"
],
[
"housing_num = housing.drop(['ocean_proximity'], axis=1)\nhousing_cat = pd.DataFrame(housing['ocean_proximity'].values.reshape(-1, 1))",
"_____no_output_____"
],
[
"imp.fit(housing_num)",
"_____no_output_____"
],
[
"X = imp.transform(housing_num)",
"_____no_output_____"
],
[
"from sklearn.preprocessing import LabelEncoder",
"_____no_output_____"
],
[
"le = LabelEncoder()",
"_____no_output_____"
],
[
"housing_cat_encoded = le.fit_transform(housing_cat.values.reshape(-1, ))",
"_____no_output_____"
],
[
"housing_cat_encoded",
"_____no_output_____"
],
[
"from sklearn.preprocessing import OneHotEncoder",
"_____no_output_____"
],
[
"ohe = OneHotEncoder()",
"_____no_output_____"
],
[
"housing_cat_encoded = ohe.fit_transform(housing_cat_encoded.reshape(-1, 1))",
"_____no_output_____"
],
[
"housing_cat_encoded[0].toarray()",
"_____no_output_____"
],
[
"from sklearn.preprocessing import LabelBinarizer",
"_____no_output_____"
],
[
"lb = LabelBinarizer()",
"_____no_output_____"
],
[
"housing_cat_encoded = lb.fit_transform(housing_cat).astype(np.float32)",
"_____no_output_____"
],
[
"housing_cat_encoded[0]",
"_____no_output_____"
],
[
"from sklearn.preprocessing import StandardScaler",
"_____no_output_____"
],
[
"n = np.random.randint(0, 10, size=(10,1)).astype(np.float64)",
"_____no_output_____"
],
[
"ss = StandardScaler()",
"_____no_output_____"
],
[
"ss.fit_transform(n)",
"_____no_output_____"
],
[
"n",
"_____no_output_____"
]
]
]
| [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
]
| [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"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"
]
]
|
cb5f855ba771cab0225b950da644966679851c1f | 11,997 | ipynb | Jupyter Notebook | run_reverse.ipynb | booydar/x-transformers | 97f0a854fdf4df8a3fbf6a580e2375463af3538c | [
"MIT"
]
| null | null | null | run_reverse.ipynb | booydar/x-transformers | 97f0a854fdf4df8a3fbf6a580e2375463af3538c | [
"MIT"
]
| null | null | null | run_reverse.ipynb | booydar/x-transformers | 97f0a854fdf4df8a3fbf6a580e2375463af3538c | [
"MIT"
]
| null | null | null | 33.232687 | 213 | 0.527632 | [
[
[
"import numpy as np\nimport random\nimport time\nimport torch\nfrom x_transformers.x_transformers import XTransformer\nimport torch\n\nfrom run_experiment import *\nfrom generate_data import *",
"_____no_output_____"
]
],
[
[
"## Variables",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import ParameterGrid\n\nTAG = 'improve_score_2paper_55len'\n\nTASK_NAME = 'reverse'\nTRAIN_SIZE = 100_000\nVAL_SIZE = 2_000\nTEST_SIZE = 10_000\nNUM_INITS = 3\n\n\nNUM_BATCHES = int(2.3e5)\nBATCH_SIZE = 128\nLEARNING_RATE = 3e-4\nGENERATE_EVERY = 3000\nNUM_TOKENS = 16 + 2\nENC_SEQ_LEN = 55\nDEC_SEQ_LEN = 55\n\nINPUT_LEN = 55",
"_____no_output_____"
]
],
[
[
"#### Generate data",
"_____no_output_____"
]
],
[
[
"# class reverse_generator:\n# def __init__(self):\n# self.src_mask = torch.ones(BATCH_SIZE, ENC_SEQ_LEN).bool().cuda()\n# self.tgt_mask = torch.ones(BATCH_SIZE, DEC_SEQ_LEN+1).bool().cuda()\n \n# def __next__(self):\n# X = np.zeros([BATCH_SIZE, ENC_SEQ_LEN]).astype(int)\n# y = np.zeros([BATCH_SIZE, DEC_SEQ_LEN+1]).astype(int)\n# y[:, 0] = 1\n# for i in range(BATCH_SIZE):\n# sequence_length = np.random.randint(1, ENC_SEQ_LEN)\n# random_sequence = np.random.randint(2, NUM_TOKENS, sequence_length)\n \n# X[i, :sequence_length] = random_sequence\n# y[i, 1:sequence_length + 1] = random_sequence[::-1]\n\n\n# return torch.tensor(X), torch.tensor(y), self.src_mask, self.tgt_mask \n \n# generator = reverse_generator()\n# generate_data(generator, task_name=TASK_NAME, train_size=TRAIN_SIZE, test_size=TEST_SIZE, val_size=VAL_SIZE) ",
"_____no_output_____"
]
],
[
[
"#### Gridsearch params",
"_____no_output_____"
]
],
[
[
"optimizer = torch.optim.Adam\n\noptim_params = list(ParameterGrid({\n 'lr': [0.001, 0.0008, 0.0012, 0.0003]\n}))\n\nprint(len(optim_params))\noptim_params",
"4\n"
],
[
"gen_train = data_loader(task_name=f'{TASK_NAME}_train', batch_size=BATCH_SIZE, enc_seq_len=INPUT_LEN, dec_seq_len=DEC_SEQ_LEN)\ngen_val = data_loader(task_name=f'{TASK_NAME}_val', batch_size=VAL_SIZE, enc_seq_len=INPUT_LEN, dec_seq_len=DEC_SEQ_LEN)\ngen_test = data_loader(task_name=f'{TASK_NAME}_test', batch_size=TEST_SIZE, enc_seq_len=INPUT_LEN, dec_seq_len=DEC_SEQ_LEN)\n\n\nprint_file = f'logs/{TASK_NAME}_{TAG}_cout_logs.txt'\nt = time.time()\n\nparam = list(model_parameters)[0]\nparam['enc_depth'], param['enc_heads'] = param['depth,heads']\nparam['dec_depth'], param['dec_heads'] = param['depth,heads']\nparam.pop('depth,heads')\n\nwith torch.cuda.device(1):\n for i, optim_param in enumerate(list(optim_params)):\n with open(print_file, 'a') as f:\n f.write('\\n\\n' + str(optim_param)+'\\n')\n \n for init_num in range(1):\n model = XTransformer(**param).cuda()\n\n model_name = f\"{TASK_NAME}{INPUT_LEN}_dim{param['dim']}d{param['enc_depth']}h{param['enc_heads']}M{param['enc_num_memory_tokens']}l{param['enc_max_seq_len']}_v{init_num}_{optim_param}\"\n\n optim = optimizer(model.parameters(), **optim_param)\n train_validate_model(model, \n train_generator=gen_train, \n val_generator=gen_val, \n optim=optim, \n model_name=model_name, \n dec_seq_len=DEC_SEQ_LEN,\n num_batches=NUM_BATCHES,\n generate_every=GENERATE_EVERY,\n print_file=print_file)\n test_model(model, gen_test, model_name, param, TASK_NAME, tag=str(optim_param), dec_seq_len=param['dec_max_seq_len'])\n with open(print_file, 'a') as f:\n f.write(f'\\nTotal time: {time.time() - t}\\n')\n t = time.time()",
"_____no_output_____"
]
],
[
[
"### Run",
"_____no_output_____"
]
],
[
[
"LEARNING_RATE = 0.001\n\nmodel_parameters = ParameterGrid({'dim': [128],\n 'tie_token_embeds': [True],\n 'return_tgt_loss': [True],\n 'enc_num_tokens': [NUM_TOKENS],\n 'depth,heads': [(2,4)],\n 'enc_max_seq_len': [55, 28],\n 'dec_num_tokens': [NUM_TOKENS],\n 'dec_max_seq_len': [DEC_SEQ_LEN],\n 'enc_num_memory_tokens': [0, 4, 16]})\n\nprint('Total runs: ', NUM_INITS * len(model_parameters))",
"Total runs: 18\n"
],
[
"gen_train = data_loader(task_name=f'{TASK_NAME}_train', batch_size=BATCH_SIZE, enc_seq_len=INPUT_LEN, dec_seq_len=DEC_SEQ_LEN)\ngen_val = data_loader(task_name=f'{TASK_NAME}_val', batch_size=VAL_SIZE, enc_seq_len=INPUT_LEN, dec_seq_len=DEC_SEQ_LEN)\ngen_test = data_loader(task_name=f'{TASK_NAME}_test', batch_size=TEST_SIZE, enc_seq_len=INPUT_LEN, dec_seq_len=DEC_SEQ_LEN)\n\n\nprint_file = f'logs/{TASK_NAME}_{TAG}_memory_logs.txt'\nt = time.time()\nwith torch.cuda.device(1):\n for init_num in range(NUM_INITS):\n with open(print_file, 'a') as f:\n f.write('\\n\\nInit number ' + str(init_num)+'\\n')\n for i, param in enumerate(list(model_parameters)):\n with open(print_file, 'a') as f:\n f.write('\\n\\n' + str(param)+'\\n')\n param['enc_depth'], param['enc_heads'] = param['depth,heads']\n param['dec_depth'], param['dec_heads'] = param['depth,heads']\n param.pop('depth,heads')\n\n with open(print_file, 'a') as f:\n f.write(f'{i / len(model_parameters) * 100}%')\n model = XTransformer(**param).cuda()\n\n model_name = f\"{TASK_NAME}{INPUT_LEN}_dim{param['dim']}d{param['enc_depth']}h{param['enc_heads']}M{param['enc_num_memory_tokens']}l{param['enc_max_seq_len']}_v{init_num}\"\n\n optim = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE)\n train_validate_model(model, \n train_generator=gen_train, \n val_generator=gen_val, \n optim=optim, \n model_name=model_name, \n dec_seq_len=DEC_SEQ_LEN,\n num_batches=NUM_BATCHES,\n generate_every=GENERATE_EVERY,\n print_file=print_file)\n test_model(model, gen_test, model_name, param, TASK_NAME, tag=TAG, dec_seq_len=param['dec_max_seq_len'])\n with open(print_file, 'a') as f:\n f.write(f'\\nTotal time: {time.time() - t}\\n')\n t = time.time()",
"_____no_output_____"
]
],
[
[
"stopped on: \n{'dec_max_seq_len': 16, 'dec_num_tokens': 18, 'depth,heads': (2, 4), 'dim': 64, 'enc_max_seq_len': 8, 'enc_num_memory_tokens': 16, 'enc_num_tokens': 18, 'return_tgt_loss': True, 'tie_token_embeds': True}",
"_____no_output_____"
],
[
"### Test!",
"_____no_output_____"
]
],
[
[
"init_num = 0\n\ngen_train = data_loader(task_name=f'{TASK_NAME}_train', batch_size=BATCH_SIZE, enc_seq_len=ENC_SEQ_LEN, dec_seq_len=DEC_SEQ_LEN)\ngen_val = data_loader(task_name=f'{TASK_NAME}_val', batch_size=VAL_SIZE, enc_seq_len=ENC_SEQ_LEN, dec_seq_len=DEC_SEQ_LEN)\ngen_test = data_loader(task_name=f'{TASK_NAME}_test', batch_size=TEST_SIZE, enc_seq_len=ENC_SEQ_LEN, dec_seq_len=DEC_SEQ_LEN)\n\n\nparam = list(model_parameters)[5]\nprint(param)\nparam['enc_depth'], param['enc_heads'] = param['depth,heads']\nparam['dec_depth'], param['dec_heads'] = param['depth,heads']\nparam.pop('depth,heads')\n\nmodel = XTransformer(**param).cuda()\n\nmodel_name = f\"{TASK_NAME}_dim{param['dim']}d{param['enc_depth']}h{param['enc_heads']}M{param['enc_num_memory_tokens']}l{param['enc_max_seq_len']}_v{init_num}\"\n\noptim = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE)\n\nsrc, tgt, _, _ = next(gen_train)\n\nprint(model.encoder.max_seq_len, model.encoder.num_memory_tokens)\nmodel.encoder(torch.cat((src, src)), return_embeddings=True).shape",
"{'dec_max_seq_len': 16, 'dec_num_tokens': 18, 'depth,heads': (1, 1), 'dim': 64, 'enc_max_seq_len': 8, 'enc_num_memory_tokens': 4, 'enc_num_tokens': 18, 'return_tgt_loss': True, 'tie_token_embeds': True}\n8 4\n"
]
]
]
| [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
]
| [
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
]
]
|
cb5f879e6e6ebf402f4499e4bd68d6896eb94c2d | 328,057 | ipynb | Jupyter Notebook | code/notebooks/webcam-test.ipynb | tschinz/ffhs-masterthesis-epu | 6b1b4e8f3fdfd6ca97b9e468b12007f28e27b4ee | [
"MIT"
]
| null | null | null | code/notebooks/webcam-test.ipynb | tschinz/ffhs-masterthesis-epu | 6b1b4e8f3fdfd6ca97b9e468b12007f28e27b4ee | [
"MIT"
]
| null | null | null | code/notebooks/webcam-test.ipynb | tschinz/ffhs-masterthesis-epu | 6b1b4e8f3fdfd6ca97b9e468b12007f28e27b4ee | [
"MIT"
]
| null | null | null | 4,152.620253 | 326,692 | 0.964582 | [
[
[
"# Simple Webcam test",
"_____no_output_____"
]
],
[
[
"from functions import *",
"_____no_output_____"
],
[
"fpath = saveWebcamImage(path=WEBCAM_PATH)\ndisplayFile(fpath)",
"_____no_output_____"
],
[
"frame = getWebcamImage(show=True)",
"_____no_output_____"
]
]
]
| [
"markdown",
"code"
]
| [
[
"markdown"
],
[
"code",
"code",
"code"
]
]
|
cb5f8b062ed38e6dd824ef4593bfee21eb555633 | 19,273 | ipynb | Jupyter Notebook | python-sdk/tutorials/automl-with-azureml/continuous-retraining/auto-ml-continuous-retraining.ipynb | jplummer01/azureml-examples | 6a073d157f21060312941f71cfbcf25d0c541183 | [
"MIT"
]
| null | null | null | python-sdk/tutorials/automl-with-azureml/continuous-retraining/auto-ml-continuous-retraining.ipynb | jplummer01/azureml-examples | 6a073d157f21060312941f71cfbcf25d0c541183 | [
"MIT"
]
| null | null | null | python-sdk/tutorials/automl-with-azureml/continuous-retraining/auto-ml-continuous-retraining.ipynb | jplummer01/azureml-examples | 6a073d157f21060312941f71cfbcf25d0c541183 | [
"MIT"
]
| null | null | null | 32.833049 | 486 | 0.613293 | [
[
[
"# Automated Machine Learning \n**Continuous retraining using Pipelines and Time-Series TabularDataset**\n## Contents\n1. [Introduction](#Introduction)\n2. [Setup](#Setup)\n3. [Compute](#Compute)\n4. [Run Configuration](#Run-Configuration)\n5. [Data Ingestion Pipeline](#Data-Ingestion-Pipeline)\n6. [Training Pipeline](#Training-Pipeline)\n7. [Publish Retraining Pipeline and Schedule](#Publish-Retraining-Pipeline-and-Schedule)\n8. [Test Retraining](#Test-Retraining)",
"_____no_output_____"
],
[
"## Introduction\nIn this example we use AutoML and Pipelines to enable contious retraining of a model based on updates to the training dataset. We will create two pipelines, the first one to demonstrate a training dataset that gets updated over time. We leverage time-series capabilities of `TabularDataset` to achieve this. The second pipeline utilizes pipeline `Schedule` to trigger continuous retraining. \nMake sure you have executed the [configuration notebook](../../../configuration.ipynb) before running this notebook.\nIn this notebook you will learn how to:\n* Create an Experiment in an existing Workspace.\n* Configure AutoML using AutoMLConfig.\n* Create data ingestion pipeline to update a time-series based TabularDataset\n* Create training pipeline to prepare data, run AutoML, register the model and setup pipeline triggers.\n\n## Setup\nAs part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments.",
"_____no_output_____"
]
],
[
[
"import logging\n\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom sklearn import datasets\n\nimport azureml.core\nfrom azureml.core.experiment import Experiment\nfrom azureml.core.workspace import Workspace\nfrom azureml.train.automl import AutoMLConfig",
"_____no_output_____"
]
],
[
[
"This sample notebook may use features that are not available in previous versions of the Azure ML SDK.",
"_____no_output_____"
],
[
"Accessing the Azure ML workspace requires authentication with Azure.\n\nThe default authentication is interactive authentication using the default tenant. Executing the ws = Workspace.from_config() line in the cell below will prompt for authentication the first time that it is run.\n\nIf you have multiple Azure tenants, you can specify the tenant by replacing the ws = Workspace.from_config() line in the cell below with the following:\n```\nfrom azureml.core.authentication import InteractiveLoginAuthentication\nauth = InteractiveLoginAuthentication(tenant_id = 'mytenantid')\nws = Workspace.from_config(auth = auth)\n```\nIf you need to run in an environment where interactive login is not possible, you can use Service Principal authentication by replacing the ws = Workspace.from_config() line in the cell below with the following:\n```\nfrom azureml.core.authentication import ServicePrincipalAuthentication\nauth = auth = ServicePrincipalAuthentication('mytenantid', 'myappid', 'mypassword')\nws = Workspace.from_config(auth = auth)\n```\nFor more details, see aka.ms/aml-notebook-auth",
"_____no_output_____"
]
],
[
[
"ws = Workspace.from_config()\ndstor = ws.get_default_datastore()\n\n# Choose a name for the run history container in the workspace.\nexperiment_name = \"retrain-noaaweather\"\nexperiment = Experiment(ws, experiment_name)\n\noutput = {}\noutput[\"Subscription ID\"] = ws.subscription_id\noutput[\"Workspace\"] = ws.name\noutput[\"Resource Group\"] = ws.resource_group\noutput[\"Location\"] = ws.location\noutput[\"Run History Name\"] = experiment_name\noutput[\"SDK Version\"] = azureml.core.VERSION\npd.set_option(\"display.max_colwidth\", None)\noutputDf = pd.DataFrame(data=output, index=[\"\"])\noutputDf.T",
"_____no_output_____"
]
],
[
[
"## Compute \n\n#### Create or Attach existing AmlCompute\n\nYou will need to create a compute target for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n\n> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n\n#### Creation of AmlCompute takes approximately 5 minutes. \nIf the AmlCompute with that name is already in your workspace this code will skip the creation process.\nAs with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota.",
"_____no_output_____"
]
],
[
[
"from azureml.core.compute import ComputeTarget, AmlCompute\nfrom azureml.core.compute_target import ComputeTargetException\n\n# Choose a name for your CPU cluster\namlcompute_cluster_name = \"cont-cluster\"\n\n# Verify that cluster does not exist already\ntry:\n compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n print(\"Found existing cluster, use it.\")\nexcept ComputeTargetException:\n compute_config = AmlCompute.provisioning_configuration(\n vm_size=\"STANDARD_DS12_V2\", max_nodes=4\n )\n compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\ncompute_target.wait_for_completion(show_output=True)",
"_____no_output_____"
]
],
[
[
"## Run Configuration",
"_____no_output_____"
]
],
[
[
"from azureml.core.runconfig import CondaDependencies, RunConfiguration\n\n# create a new RunConfig object\nconda_run_config = RunConfiguration(framework=\"python\")\n\n# Set compute target to AmlCompute\nconda_run_config.target = compute_target\n\nconda_run_config.environment.docker.enabled = True\n\ncd = CondaDependencies.create(\n pip_packages=[\n \"azureml-sdk[automl]\",\n \"applicationinsights\",\n \"azureml-opendatasets\",\n \"azureml-defaults\",\n ],\n conda_packages=[\"numpy==1.19.5\"],\n pin_sdk_version=False,\n)\nconda_run_config.environment.python.conda_dependencies = cd\n\nprint(\"run config is ready\")",
"_____no_output_____"
]
],
[
[
"## Data Ingestion Pipeline \nFor this demo, we will use NOAA weather data from [Azure Open Datasets](https://azure.microsoft.com/services/open-datasets/). You can replace this with your own dataset, or you can skip this pipeline if you already have a time-series based `TabularDataset`.\n",
"_____no_output_____"
]
],
[
[
"# The name and target column of the Dataset to create\ndataset = \"NOAA-Weather-DS4\"\ntarget_column_name = \"temperature\"",
"_____no_output_____"
]
],
[
[
"\n### Upload Data Step\nThe data ingestion pipeline has a single step with a script to query the latest weather data and upload it to the blob store. During the first run, the script will create and register a time-series based `TabularDataset` with the past one week of weather data. For each subsequent run, the script will create a partition in the blob store by querying NOAA for new weather data since the last modified time of the dataset (`dataset.data_changed_time`) and creating a data.csv file.",
"_____no_output_____"
]
],
[
[
"from azureml.pipeline.core import Pipeline, PipelineParameter\nfrom azureml.pipeline.steps import PythonScriptStep\n\nds_name = PipelineParameter(name=\"ds_name\", default_value=dataset)\nupload_data_step = PythonScriptStep(\n script_name=\"upload_weather_data.py\",\n allow_reuse=False,\n name=\"upload_weather_data\",\n arguments=[\"--ds_name\", ds_name],\n compute_target=compute_target,\n runconfig=conda_run_config,\n)",
"_____no_output_____"
]
],
[
[
"### Submit Pipeline Run",
"_____no_output_____"
]
],
[
[
"data_pipeline = Pipeline(\n description=\"pipeline_with_uploaddata\", workspace=ws, steps=[upload_data_step]\n)\ndata_pipeline_run = experiment.submit(\n data_pipeline, pipeline_parameters={\"ds_name\": dataset}\n)",
"_____no_output_____"
],
[
"data_pipeline_run.wait_for_completion(show_output=False)",
"_____no_output_____"
]
],
[
[
"## Training Pipeline\n### Prepare Training Data Step\n\nScript to check if new data is available since the model was last trained. If no new data is available, we cancel the remaining pipeline steps. We need to set allow_reuse flag to False to allow the pipeline to run even when inputs don't change. We also need the name of the model to check the time the model was last trained.",
"_____no_output_____"
]
],
[
[
"from azureml.pipeline.core import PipelineData\n\n# The model name with which to register the trained model in the workspace.\nmodel_name = PipelineParameter(\"model_name\", default_value=\"noaaweatherds\")",
"_____no_output_____"
],
[
"data_prep_step = PythonScriptStep(\n script_name=\"check_data.py\",\n allow_reuse=False,\n name=\"check_data\",\n arguments=[\"--ds_name\", ds_name, \"--model_name\", model_name],\n compute_target=compute_target,\n runconfig=conda_run_config,\n)",
"_____no_output_____"
],
[
"from azureml.core import Dataset\n\ntrain_ds = Dataset.get_by_name(ws, dataset)\ntrain_ds = train_ds.drop_columns([\"partition_date\"])",
"_____no_output_____"
]
],
[
[
"### AutoMLStep\nCreate an AutoMLConfig and a training step.",
"_____no_output_____"
]
],
[
[
"from azureml.train.automl import AutoMLConfig\nfrom azureml.pipeline.steps import AutoMLStep\n\nautoml_settings = {\n \"iteration_timeout_minutes\": 10,\n \"experiment_timeout_hours\": 0.25,\n \"n_cross_validations\": 3,\n \"primary_metric\": \"r2_score\",\n \"max_concurrent_iterations\": 3,\n \"max_cores_per_iteration\": -1,\n \"verbosity\": logging.INFO,\n \"enable_early_stopping\": True,\n}\n\nautoml_config = AutoMLConfig(\n task=\"regression\",\n debug_log=\"automl_errors.log\",\n path=\".\",\n compute_target=compute_target,\n training_data=train_ds,\n label_column_name=target_column_name,\n **automl_settings,\n)",
"_____no_output_____"
],
[
"from azureml.pipeline.core import PipelineData, TrainingOutput\n\nmetrics_output_name = \"metrics_output\"\nbest_model_output_name = \"best_model_output\"\n\nmetrics_data = PipelineData(\n name=\"metrics_data\",\n datastore=dstor,\n pipeline_output_name=metrics_output_name,\n training_output=TrainingOutput(type=\"Metrics\"),\n)\nmodel_data = PipelineData(\n name=\"model_data\",\n datastore=dstor,\n pipeline_output_name=best_model_output_name,\n training_output=TrainingOutput(type=\"Model\"),\n)",
"_____no_output_____"
],
[
"automl_step = AutoMLStep(\n name=\"automl_module\",\n automl_config=automl_config,\n outputs=[metrics_data, model_data],\n allow_reuse=False,\n)",
"_____no_output_____"
]
],
[
[
"### Register Model Step\nScript to register the model to the workspace. ",
"_____no_output_____"
]
],
[
[
"register_model_step = PythonScriptStep(\n script_name=\"register_model.py\",\n name=\"register_model\",\n allow_reuse=False,\n arguments=[\n \"--model_name\",\n model_name,\n \"--model_path\",\n model_data,\n \"--ds_name\",\n ds_name,\n ],\n inputs=[model_data],\n compute_target=compute_target,\n runconfig=conda_run_config,\n)",
"_____no_output_____"
]
],
[
[
"### Submit Pipeline Run",
"_____no_output_____"
]
],
[
[
"training_pipeline = Pipeline(\n description=\"training_pipeline\",\n workspace=ws,\n steps=[data_prep_step, automl_step, register_model_step],\n)",
"_____no_output_____"
],
[
"training_pipeline_run = experiment.submit(\n training_pipeline,\n pipeline_parameters={\"ds_name\": dataset, \"model_name\": \"noaaweatherds\"},\n)",
"_____no_output_____"
],
[
"training_pipeline_run.wait_for_completion(show_output=False)",
"_____no_output_____"
]
],
[
[
"### Publish Retraining Pipeline and Schedule\nOnce we are happy with the pipeline, we can publish the training pipeline to the workspace and create a schedule to trigger on blob change. The schedule polls the blob store where the data is being uploaded and runs the retraining pipeline if there is a data change. A new version of the model will be registered to the workspace once the run is complete.",
"_____no_output_____"
]
],
[
[
"pipeline_name = \"Retraining-Pipeline-NOAAWeather\"\n\npublished_pipeline = training_pipeline.publish(\n name=pipeline_name, description=\"Pipeline that retrains AutoML model\"\n)\n\npublished_pipeline",
"_____no_output_____"
],
[
"from azureml.pipeline.core import Schedule\n\nschedule = Schedule.create(\n workspace=ws,\n name=\"RetrainingSchedule\",\n pipeline_parameters={\"ds_name\": dataset, \"model_name\": \"noaaweatherds\"},\n pipeline_id=published_pipeline.id,\n experiment_name=experiment_name,\n datastore=dstor,\n wait_for_provisioning=True,\n polling_interval=1440,\n)",
"_____no_output_____"
]
],
[
[
"## Test Retraining\nHere we setup the data ingestion pipeline to run on a schedule, to verify that the retraining pipeline runs as expected. \n\nNote: \n* Azure NOAA Weather data is updated daily and retraining will not trigger if there is no new data available. \n* Depending on the polling interval set in the schedule, the retraining may take some time trigger after data ingestion pipeline completes.",
"_____no_output_____"
]
],
[
[
"pipeline_name = \"DataIngestion-Pipeline-NOAAWeather\"\n\npublished_pipeline = training_pipeline.publish(\n name=pipeline_name, description=\"Pipeline that updates NOAAWeather Dataset\"\n)\n\npublished_pipeline",
"_____no_output_____"
],
[
"from azureml.pipeline.core import Schedule\n\nschedule = Schedule.create(\n workspace=ws,\n name=\"RetrainingSchedule-DataIngestion\",\n pipeline_parameters={\"ds_name\": dataset},\n pipeline_id=published_pipeline.id,\n experiment_name=experiment_name,\n datastore=dstor,\n wait_for_provisioning=True,\n polling_interval=1440,\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",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
]
|
cb5f91afdf8250f063833d4a50dc9e36de39b823 | 52,647 | ipynb | Jupyter Notebook | attacks/.ipynb_checkpoints/non-targeted_attacks_collection-checkpoint.ipynb | sundyCoder/STPD | 67207aac7f23c7ee0b6c674995a86c76cd1f6a4d | [
"MIT"
]
| null | null | null | attacks/.ipynb_checkpoints/non-targeted_attacks_collection-checkpoint.ipynb | sundyCoder/STPD | 67207aac7f23c7ee0b6c674995a86c76cd1f6a4d | [
"MIT"
]
| null | null | null | attacks/.ipynb_checkpoints/non-targeted_attacks_collection-checkpoint.ipynb | sundyCoder/STPD | 67207aac7f23c7ee0b6c674995a86c76cd1f6a4d | [
"MIT"
]
| null | null | null | 94.518851 | 10,980 | 0.808308 | [
[
[
"\n# Python Libraries\n%matplotlib inline\nimport pickle\nimport numpy as np\nimport pandas as pd\nimport matplotlib\nfrom keras.datasets import cifar10\nfrom keras import backend as K\n\n# Custom Networks\nfrom networks.lenet import LeNet\nfrom networks.pure_cnn import PureCnn\nfrom networks.network_in_network import NetworkInNetwork\nfrom networks.resnet import ResNet\nfrom networks.densenet import DenseNet\nfrom networks.wide_resnet import WideResNet\nfrom networks.capsnet import CapsNet\nimport cv2 as cv\n\n# Helper functions\nfrom differential_evolution import differential_evolution\nimport helper\n#from scipy.misc import imsave\nimport scipy.misc\n\nmatplotlib.style.use('ggplot')\nnp.random.seed(100)",
"_____no_output_____"
],
[
"(x_train, y_train), (x_test, y_test) = cifar10.load_data()\nclass_names = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\n",
"_____no_output_____"
],
[
"def perturb_image(xs, img):\n # If this function is passed just one perturbation vector,\n # pack it in a list to keep the computation the same\n if xs.ndim < 2:\n xs = np.array([xs])\n \n # Copy the image n == len(xs) times so that we can \n # create n new perturbed images\n tile = [len(xs)] + [1]*(xs.ndim+1)\n imgs = np.tile(img, tile)\n \n # Make sure to floor the members of xs as int types\n xs = xs.astype(int)\n \n for x,img in zip(xs, imgs):\n # Split x into an array of 5-tuples (perturbation pixels)\n # i.e., [[x,y,r,g,b], ...]\n pixels = np.split(x, len(x) // 5)\n for pixel in pixels:\n # At each pixel's x,y position, assign its rgb value\n x_pos, y_pos, *rgb = pixel\n img[x_pos, y_pos] = rgb\n \n return imgs",
"_____no_output_____"
],
[
"K.tensorflow_backend._get_available_gpus()\n#nin = NetworkInNetwork()\n#resnet = ResNet()\ndensenet = DenseNet()\n\nmodels = [densenet]\n",
"Successfully loaded densenet\n"
],
[
"x_test.shape",
"_____no_output_____"
],
[
"def predict_classes(xs, img, target_class, model, minimize=True):\n # Perturb the image with the given pixel(s) x and get the prediction of the model\n imgs_perturbed = perturb_image(xs, img)\n predictions = model.predict(imgs_perturbed)[:,target_class]\n # This function should always be minimized, so return its complement if needed\n return predictions if minimize else 1 - predictions",
"_____no_output_____"
],
[
"def attack_success(x, img, target_class, model, targeted_attack=False, verbose=False):\n # Perturb the image with the given pixel(s) and get the prediction of the model\n attack_image = perturb_image(x, x_test[img])\n\n confidence = model.predict(attack_image)[0]\n predicted_class = np.argmax(confidence)\n \n # If the prediction is what we want (misclassification or \n # targeted classification), return True\n if (verbose):\n print('Confidence:', confidence[target_class])\n if ((targeted_attack and predicted_class == target_class) or\n (not targeted_attack and predicted_class != target_class)):\n return True\n # NOTE: return None otherwise (not False), due to how Scipy handles its callback function",
"_____no_output_____"
],
[
"# def save_success(img, name):\n# scipy.misc.imsave('data/'+name + tail, img)",
"_____no_output_____"
],
[
"count = 0\nimport os\ndef attack(img, model,cls_id, case_path, target=None, pixel_count=1, \n maxiter=75, popsize=400,verbose=False):\n # Change the target class based on whether this is a targeted attack or not\n targeted_attack = target is not None\n target_class = target if targeted_attack else y_test[img,0]\n \n # Define bounds for a flat vector of x,y,r,g,b values\n # For more pixels, repeat this layout\n bounds = [(0,32), (0,32), (0,256), (0,256), (0,256)] * pixel_count\n \n # Population multiplier, in terms of the size of the perturbation vector x\n popmul = max(1, popsize // len(bounds))\n \n # Format the predict/callback functions for the differential evolution algorithm\n predict_fn = lambda xs: predict_classes(\n xs, x_test[img], target_class, model, target is None)\n callback_fn = lambda x, convergence: attack_success(\n x, img, target_class, model, targeted_attack, verbose)\n \n # Call Scipy's Implementation of Differential Evolution\n attack_result = differential_evolution(\n predict_fn, bounds, maxiter=maxiter, popsize=popmul,\n recombination=1, atol=-1, callback=callback_fn, polish=False)\n\n # Calculate some useful statistics to return from this function\n attack_image = perturb_image(attack_result.x, x_test[img])[0]\n prior_probs = model.predict_one(x_test[img])\n predicted_probs = model.predict_one(attack_image)\n predicted_class = np.argmax(predicted_probs)\n actual_class = y_test[img,0]\n success = predicted_class != actual_class\n \n# if(success):\n# #count += 1\n# name = 'horrse_attacked_'+str(img)+'_'+str(actual_class) +'_'+str(predicted_class)+'.png'\n# save_success(attack_image,name)\n \n cdiff = prior_probs[actual_class] - predicted_probs[actual_class]\n import scipy.misc\n if(predicted_probs[actual_class] < 0.5):\n # Show the best attempt at a solution (successful or not)\n helper.plot_image(attack_image, actual_class, class_names, predicted_class)\n #saved\n \n cls_name = case_path + str(cls_id)+'_'+class_names[cls_id] \n ori_name = cls_name + '/original/'+str(img) + '_' + str(actual_class) + '.png'\n ori_path = cls_name + '/original/'\n if not os.path.exists(ori_path):\n #os.makedirs(Annotations_path)\n os.system('mkdir -p %s' % (ori_path))\n scipy.misc.imsave(ori_name, x_test[img])\n at_name = cls_name + '/attacked/'+str(img) +'_'+str(actual_class) +'_'+str(predicted_class)+'.png'\n at_path = cls_name + '/attacked/'\n if not os.path.exists(at_path):\n #os.makedirs(Annotations_path)\n os.system('mkdir -p %s' %(at_path))\n #scipy.misc.imsave(at_name, attack_image)\n cv.imwrite(at_name, attack_image)\n #np.savetxt('horse_cor_'+str(img)+'.txt', attack_result.x,delimiter=',')\n #np.savetxt('test.out', x, delimiter=',')\n print(\"success:\", prior_probs[actual_class], predicted_probs[actual_class])\n else:\n ok_cls_name = case_path+str(cls_id)+'_'+class_names[cls_id]\n ok_name = ok_cls_name + '/OK/'+str(img) +'_' + str(actual_class)+ '.png'\n ok_path = ok_cls_name + '/OK/'\n if not os.path.exists(ok_path):\n #os.makedirs(Annotations_path)\n os.system('mkdir -p %s' %(ok_path))\n cv.imwrite(ok_name, x_test[img])\n #scipy.misc.imsave(ok_name, x_test[img])\n # Show the best attempt at a solution (successful or not)\n helper.plot_image(attack_image, actual_class, class_names, predicted_class)\n\n return [model.name, pixel_count, img, actual_class, predicted_class, success, cdiff, prior_probs, predicted_probs, attack_result.x]",
"_____no_output_____"
],
[
"# pixels = 1 # Number of pixels to attack\n# model = resnet\n\n# for i in range(10000):\n# if(y_test[i] == 0):\n# image = i\n# cls = 0\n# _ = attack(image, model, cls, pixel_count=pixels,verbose=True)\n\n\npixels = 1 # Number of pixels to attack\nmodel = densenet\ncase_path = 'densenet_data_p1/'\nfor i in range(10000): \n print(i)\n cls = y_test[i][0]\n image = i \n _ = attack(image, model, cls, case_path,pixel_count=pixels,verbose=True)",
"605\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\nConfidence: 1.0\n"
],
[
"15+52+6+40+28+30+29+27+22+29+33+30+13+57+16+41+10+54+8+63",
"_____no_output_____"
],
[
"print(y_test.shap)",
"_____no_output_____"
]
]
]
| [
"code"
]
| [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
]
|
cb5faee3b6b87923efe760c84faf0a532524186b | 77,891 | ipynb | Jupyter Notebook | notes/Basic Plotting.ipynb | pywaker/datascience | e3e9b55b06489ad1dc10189414311d3d38b840e6 | [
"CC-BY-4.0"
]
| 3 | 2019-03-22T04:15:45.000Z | 2019-06-29T09:27:06.000Z | notes/Basic Plotting.ipynb | learningwithdg/datascience | e3e9b55b06489ad1dc10189414311d3d38b840e6 | [
"CC-BY-4.0"
]
| null | null | null | notes/Basic Plotting.ipynb | learningwithdg/datascience | e3e9b55b06489ad1dc10189414311d3d38b840e6 | [
"CC-BY-4.0"
]
| 2 | 2019-05-21T04:26:25.000Z | 2019-05-21T04:27:15.000Z | 355.666667 | 21,620 | 0.857031 | [
[
[
"import matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"%matplotlib inline",
"_____no_output_____"
],
[
"plt.scatter([1700, 2100, 1900, 1300, 1600, 2200], [53000, 65000, 59000, 41000, 50000, 68000])\nplt.show()",
"_____no_output_____"
],
[
"x = [1300, 1400, 1600, 1900, 2100, 2300]\ny = [88000, 72000, 94000, 86000, 112000, 98000]",
"_____no_output_____"
],
[
"plt.scatter(x, y, s=32, c='cyan', alpha=0.5)\nplt.show()",
"_____no_output_____"
],
[
"plt.bar(x, y, width=20, alpha=0.5)\nplt.show()",
"_____no_output_____"
],
[
"plt.hist([100, 400, 200, 100, 400, 100, 300, 200, 100], alpha=0.5)\nplt.show()",
"_____no_output_____"
],
[
"colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']\nplt.pie([11, 13, 56, 67, 23], colors=colors, shadow=True, startangle=90)\nplt.show()",
"_____no_output_____"
],
[
"height = [65.0, 59.8, 63.3, 63.2, 65.0, 63.3, 65.8, 62.8, 61.1, 64.3, 63.0, 64.2, 65.4, 64.1, 64.7, 64.0, 66.1, 64.6, 67.0, 64.0, 59.0, 65.2, 62.9, 65.4, 63.7, 65.7, 64.1, 65.4, 64.7, 65.3, 65.2, 64.8, 66.4, 65.0, 65.6, 65.5, 67.4, 65.1, 66.8, 65.5, 67.8, 65.1, 69.5, 65.5, 62.5, 66.6, 63.8, 66.4, 64.5, 66.1, 65.0, 66.0, 64.7, 66.0, 65.7, 66.5, 65.5, 65.7, 65.6, 66.0, 66.9, 65.9, 66.6, 65.9, 66.5, 66.5, 67.9, 65.8, 68.3, 66.3, 67.7, 66.1, 68.5, 66.3, 69.4, 66.3, 71.8, 66.4, 62.4, 67.2, 64.5, 67.5, 64.5, 67.0, 63.9, 66.8, 65.4, 67.0, 65.0, 66.8, 65.7, 69.3, 68.7, 69.1, 66.5, 61.7, 64.9, 65.7, 69.6, 69.0, 64.8, 67.4, 65.3, 67.2, 65.8, 67.1, 65.8, 67.3, 65.6, 67.6, 65.9, 67.5, 65.8, 66.9, 67.1, 67.6, 66.6, 67.2, 67.4, 66.8, 67.3, 67.2, 66.6, 67.5, 68.2, 67.6, 67.8, 67.2, 68.3, 67.5, 68.1, 67.4, 69.0, 67.6, 68.9, 67.3, 69.6, 66.8, 70.4, 66.7, 70.0, 66.9, 72.8, 67.6, 62.8, 68.0, 62.9, 68.5, 63.9, 68.0, 64.5, 68.3, 64.5, 68.3, 66.0, 68.3, 65.8, 68.2, 66.0, 68.5, 65.5, 68.1, 65.7, 68.3, 66.8, 68.0, 66.7, 68.6, 67.0, 67.9, 66.9, 68.1, 66.8, 68.4, 67.1, 67.9, 67.7, 68.2, 68.3, 68.0, 67.6, 68.2, 68.4, 67.9, 67.7, 68.6, 68.7, 68.0, 69.3, 68.3, 68.7, 67.9, 69.1, 68.6, 69.3, 68.2, 68.6, 68.6, 69.6, 68.1, 70.4, 68.4, 71.2, 67.8, 70.8, 68.6, 71.7, 67.9, 73.3, 67.8, 63.0, 68.8, 63.7, 69.6, 65.4, 69.7, 64.6, 69.4, 66.4, 69.7, 65.8, 69.2, 65.7, 69.5, 66.1, 69.6, 66.5, 69.3, 66.6, 69.5, 66.6, 68.7, 67.7, 69.3, 68.5, 69.2, 67.8, 69.2, 67.6, 69.5, 68.1, 69.1, 69.2, 68.9, 68.7, 69.5, 68.6, 69.3, 68.6, 69.2, 68.6, 68.7, 70.4, 69.3, 70.0, 68.9, 70.1, 69.3, 70.2, 69.2, 71.3, 69.6, 70.9, 69.1, 72.2, 69.1, 75.0, 69.0, 64.9, 69.9, 65.6, 70.1, 65.7, 69.9, 65.9, 70.3, 65.9, 70.5, 67.4, 70.5, 67.5, 69.8, 67.6, 70.4, 68.5, 70.0, 68.5, 69.8, 68.1, 70.7, 69.5, 70.2, 69.1, 70.1, 69.4, 70.0, 69.4, 70.3, 69.5, 69.8, 70.2, 70.0, 69.9, 69.9, 70.4, 69.7, 70.9, 70.1, 71.3, 70.0, 72.1, 70.7, 72.2, 70.0, 75.4, 70.1, 64.5, 71.3, 66.4, 70.8, 65.6, 71.4, 66.8, 71.2, 66.9, 71.7, 68.2, 71.4, 67.5, 70.7, 67.8, 71.3, 69.0, 71.0, 69.3, 71.3, 68.7, 70.9, 69.7, 71.3, 70.3, 71.6, 70.0, 71.2, 70.2, 71.0, 70.9, 71.4, 71.2, 71.6, 72.4, 71.1, 73.0, 70.9, 74.8, 71.7, 67.4, 72.4, 67.3, 71.9, 67.8, 72.3, 69.3, 72.2, 68.7, 72.5, 70.0, 72.0, 69.8, 72.3, 70.7, 72.5, 71.1, 72.3, 72.5, 72.0, 72.5, 72.2, 67.5, 72.8, 68.2, 73.0, 68.8, 72.9, 69.9, 73.2, 71.5, 73.6, 70.8, 72.9, 71.9, 73.2, 63.1, 74.3, 68.2, 74.4, 70.1, 73.8, 70.8, 73.9, 72.6, 73.8, 67.9, 75.6, 67.5, 75.7, 72.8, 77.2, 62.7, 61.3, 68.2, 74.3, 65.1, 70.9, 73.4, 75.3, 62.9, 61.8, 62.5, 64.0, 69.9, 62.5, 71.1, 73.7, 71.1, 66.3, 69.5, 62.2, 70.2, 65.4, 65.5, 64.0, 62.0, 62.8, 63.6, 63.5, 65.6, 63.5, 68.0, 62.9, 61.8, 63.7, 63.8, 63.7, 64.9, 64.4, 65.8, 63.7, 66.4, 64.4, 68.8, 64.3, 61.8, 65.2, 64.3, 65.1, 63.7, 65.6, 65.0, 64.9, 65.3, 65.1, 64.8, 65.2, 65.7, 65.6, 66.0, 65.6, 67.0, 64.9, 67.8, 65.4, 69.0, 64.7, 62.2, 65.8, 62.8, 65.8, 63.9, 66.7, 65.4, 66.5, 64.6, 66.4, 65.6, 66.3, 66.2, 66.2, 66.0, 66.4, 65.8, 66.7, 67.4, 66.2, 67.1, 66.4, 67.3, 66.7, 67.9, 65.8, 68.3, 66.2, 68.0, 66.3, 68.7, 65.8, 71.2, 66.3, 62.4, 66.9, 62.9, 66.8, 64.1, 67.4, 63.9, 67.7, 64.8, 67.2, 65.4, 67.3, 64.8, 67.5, 68.7, 69.0, 65.2, 62.0, 64.3, 64.1, 66.1, 66.0, 69.0, 65.8, 64.5, 66.9, 66.1, 66.8, 65.7, 67.0, 66.5, 67.4, 65.6, 66.8, 66.4, 67.3, 67.3, 67.5, 66.8, 67.2, 66.7, 67.6, 67.3, 66.9, 67.4, 66.7, 67.9, 67.2, 67.8, 67.2, 68.1, 66.8, 68.3, 66.8, 68.8, 67.5, 69.4, 67.1, 69.3, 67.1, 70.5, 66.9, 70.1, 67.5, 70.6, 66.9, 62.4, 67.7, 63.2, 67.9, 63.5, 68.7, 63.9, 68.6, 64.6, 68.4, 64.9, 68.4, 65.9, 68.4, 66.2, 68.4, 66.5, 67.9, 65.5, 68.3, 66.9, 68.0, 67.1, 68.2, 66.8, 68.6, 67.2, 68.6, 66.5, 67.8, 67.0, 67.9, 66.6, 68.2, 68.2, 68.0, 67.6, 67.9, 68.3, 67.8, 68.0, 68.6, 69.0, 68.1, 69.3, 67.9, 68.9, 68.5, 68.9, 68.6, 69.4, 68.1, 69.5, 68.1, 70.3, 67.7, 69.9, 68.4, 70.7, 68.6, 70.6, 68.3, 72.4, 68.1, 72.5, 68.4, 62.7, 69.4, 63.9, 69.0, 64.5, 69.4, 64.8, 68.9, 65.4, 69.4, 65.8, 69.3, 66.3, 69.0, 65.8, 69.6, 66.8, 69.2, 67.2, 69.7, 67.3, 68.9, 67.5, 69.1, 67.9, 69.0, 68.4, 69.2, 67.6, 69.6, 68.5, 68.8, 68.6, 69.2, 69.1, 69.1, 68.6, 69.0, 69.2, 69.3, 68.6, 69.2, 68.5, 68.9, 69.7, 69.4, 70.4, 68.7, 70.0, 68.8, 70.3, 69.4, 71.3, 69.4, 71.3, 69.5, 72.6, 69.2, 64.4, 70.0, 64.9, 69.9, 66.3, 70.0, 66.0, 69.7, 65.7, 69.8, 66.7, 69.9, 66.6, 70.3, 68.3, 69.8, 67.9, 69.9, 68.0, 70.3, 68.3, 70.7, 68.8, 70.4, 69.1, 70.4, 69.0, 70.6, 69.4, 70.2, 69.8, 69.9, 69.6, 70.2, 70.5, 70.3, 69.9, 70.3, 71.0, 69.8, 71.2, 70.5, 71.5, 70.0, 71.6, 69.7, 73.2, 69.9, 63.9, 70.9, 66.0, 71.4, 66.0, 71.2, 67.5, 70.8, 66.7, 70.7, 68.3, 71.3, 67.7, 70.9, 68.3, 70.9, 68.4, 70.9, 69.1, 71.2, 69.1, 71.3, 69.7, 71.2, 70.0, 71.4, 69.6, 71.6, 70.0, 71.0, 70.9, 71.2, 70.6, 71.4, 72.3, 71.4, 71.5, 70.9, 73.0, 71.3, 66.2, 72.1, 67.3, 72.0, 67.8, 72.0, 69.1, 71.7, 69.4, 71.9, 69.6, 72.2, 70.1, 72.3, 70.2, 72.6, 71.3, 72.0, 72.1, 71.8, 72.3, 71.8, 67.1, 73.1, 67.9, 73.4, 69.1, 73.2, 69.6, 73.4, 69.7, 73.2, 70.5, 72.9, 72.4, 72.8, 72.8, 73.3, 68.1, 74.0, 68.6, 74.6, 71.3, 73.9, 72.1, 74.6, 74.7, 74.3, 71.2, 75.1, 68.3, 77.2, 60.4, 60.8, 63.9, 62.4, 63.1, 66.4, 64.0, 58.5, 73.9, 70.0, 72.0, 71.0, 61.0, 65.0, 65.4, 70.5, 72.0, 69.2, 71.3, 64.9, 65.2, 68.8, 68.9, 69.9, 64.5, 62.5, 64.0, 63.3, 66.5, 63.5, 67.1, 62.9, 62.3, 63.9, 63.8, 64.3, 65.4, 64.2, 65.6, 64.6, 66.2, 64.3, 67.6, 63.8, 60.2, 65.7, 63.0, 64.8, 63.6, 65.6, 65.2, 64.7, 65.1, 64.8, 64.8, 65.1, 66.2, 65.6, 66.2, 65.3, 66.6, 65.1, 68.0, 65.1, 69.0, 64.8, 62.1, 66.0, 63.2, 66.4, 64.5, 66.4, 63.8, 66.3, 64.6, 65.8, 64.6, 66.1, 66.1, 66.5, 66.0, 66.3, 65.7, 66.6, 67.1, 66.0, 67.3, 66.5, 67.2, 66.0, 68.4, 66.5, 67.6, 66.4, 67.6, 66.3, 68.5, 66.3, 70.0, 66.6, 61.1, 66.8, 62.7, 67.5, 64.3, 67.2, 64.1, 66.8, 63.7, 67.3, 64.7, 66.8, 64.7, 66.9, 68.0, 68.1, 64.6, 63.6, 66.1, 63.2, 65.3, 65.7, 69.7, 67.2, 65.3, 67.4, 65.5, 67.6, 66.1, 67.2, 66.2, 67.1, 66.0, 66.8, 66.0, 67.1, 65.9, 66.9, 67.1, 66.8, 67.0, 67.0, 67.4, 67.7, 67.4, 67.6, 67.3, 67.7, 68.3, 67.3, 68.3, 67.0, 67.6, 67.0, 68.2, 67.1, 69.1, 67.2, 68.8, 67.5, 70.5, 67.7, 70.0, 66.9, 69.5, 67.0, 61.5, 67.7, 62.9, 68.5, 64.1, 67.9, 63.9, 67.8, 65.1, 68.3, 64.6, 68.2, 65.9, 68.6, 66.2, 67.8, 65.7, 67.9, 66.1, 67.7, 66.3, 68.0, 67.2, 68.1, 66.9, 67.8, 66.9, 68.1, 66.6, 68.2, 67.2, 68.6, 67.1, 68.3, 67.9, 68.4, 67.9, 68.6, 67.8, 68.3, 67.9, 67.9, 68.6, 67.7, 68.6, 68.4, 69.0, 68.1, 69.0, 68.0, 69.1, 68.2, 68.5, 68.1, 70.2, 68.5, 69.8, 68.6, 69.9, 67.7, 71.5, 68.7, 72.4, 68.6, 71.9, 68.4, 61.0, 69.1, 63.0, 69.4, 64.6, 69.5, 65.4, 69.1, 64.8, 69.6, 65.5, 69.4, 65.6, 69.2, 66.1, 68.8, 67.4, 69.1, 66.6, 69.0, 67.4, 69.1, 67.2, 69.1, 68.2, 68.7, 67.9, 69.0, 68.0, 69.0, 67.7, 69.2, 68.9, 68.8, 68.7, 68.7, 69.1, 69.0, 68.8, 69.3, 68.8, 69.4, 69.3, 68.9, 69.6, 69.3, 69.8, 69.6, 70.2, 69.4, 70.1, 69.0, 71.1, 69.5, 71.4, 68.7, 71.8, 69.2, 64.4, 70.4, 65.2, 70.1, 66.1, 70.4, 65.8, 70.0, 65.5, 69.8, 66.7, 70.4, 67.2, 70.0, 67.2, 70.3, 68.1, 69.9, 67.9, 70.7, 68.2, 70.3, 69.3, 69.7, 68.8, 70.3, 69.2, 70.0, 68.7, 69.7, 69.5, 70.2, 70.0, 70.0, 69.7, 70.3, 70.2, 70.4, 70.8, 69.8, 70.9, 69.8, 71.3, 70.5, 72.3, 70.0, 72.8, 70.6, 64.4, 71.1, 64.9, 71.2, 65.8, 71.0, 67.4, 70.9, 67.4, 70.8, 67.9, 71.5, 67.9, 71.6, 68.5, 70.8, 67.6, 71.0, 69.4, 71.6, 69.3, 71.1, 69.5, 71.5, 70.2, 71.4, 70.0, 71.5, 69.8, 71.0, 69.6, 71.6, 71.5, 71.4, 72.2, 71.2, 72.4, 70.9, 72.5, 71.5, 64.7, 72.4, 66.8, 72.6, 67.8, 71.8, 68.2, 72.0, 69.2, 72.0, 68.9, 72.4, 70.1, 71.9, 70.1, 72.1, 71.0, 72.6, 71.4, 72.5, 72.0, 71.8, 72.7, 72.6, 68.0, 73.1, 69.0, 73.2, 68.9, 73.4, 69.6, 73.4, 71.2, 73.7, 72.0, 72.8, 72.9, 73.0, 65.9, 74.7, 68.5, 73.9, 70.7, 74.4, 72.3, 74.0, 72.6, 73.9, 68.8, 75.7, 73.5, 76.1, 70.1, 78.2, 67.9, 61.9, 64.7, 69.9, 60.8, 62.3, 74.9, 71.4, 70.6, 71.6, 60.9, 65.5, 65.3, 71.9, 71.4, 71.2, 71.7, 64.5, 62.7, 65.3, 71.4, 69.6, 66.6, 65.1, 67.2, 61.0, 62.5, 63.1, 64.9, 63.6, 66.9, 63.5, 62.4, 63.8, 63.6, 64.2, 65.4, 64.7, 65.0, 64.1, 66.4, 64.4, 66.7, 64.6, 59.5, 64.8, 63.0, 65.2, 64.1, 65.6, 64.1, 65.6, 64.5, 64.9, 65.2, 65.6, 66.3, 65.7, 66.0, 65.6, 66.8, 65.1, 68.2, 64.9, 68.7, 65.7, 61.3, 66.5, 63.3, 66.2, 63.9, 65.9, 64.1, 66.3, 64.8, 66.3, 64.6, 66.2, 66.2, 66.1, 66.5, 66.2, 66.4, 65.8, 67.3, 66.6, 67.4, 66.5, 67.3, 66.3, 67.7, 66.5, 68.4, 66.3, 67.8, 65.9, 69.3, 66.6, 69.7, 66.6, 60.0, 67.3, 62.1, 67.4, 63.6, 67.5, 63.8, 66.9, 64.5, 67.1, 64.7, 67.0, 65.4, 66.9, 65.1, 68.1, 69.3, 67.5, 67.7, 63.0, 64.9, 67.4, 69.5, 68.8, 65.1, 66.9, 65.0, 67.3, 65.6, 67.2, 65.9, 67.1, 65.7, 67.1, 65.9, 67.2, 65.9, 66.7, 67.4, 66.8, 66.5, 67.4, 67.4, 67.4, 67.2, 67.0, 67.3, 67.4, 68.1, 66.9, 68.0, 66.9, 68.0, 66.8, 68.4, 66.8, 68.8, 67.2, 69.5, 67.5, 70.2, 67.7, 69.7, 67.1, 70.2, 67.6, 61.1, 68.0, 62.7, 68.7, 64.3, 68.4, 64.3, 68.0, 65.0, 68.6, 64.8, 68.5, 66.2, 67.8, 66.1, 68.1, 66.4, 68.2, 66.2, 68.5, 65.9, 68.6, 67.0, 68.7, 67.5, 68.4, 66.7, 68.5, 66.7, 68.6, 67.3, 67.9, 67.1, 68.0, 67.8, 68.0, 68.4, 68.6, 67.7, 68.1, 68.1, 67.9, 67.7, 68.6, 69.0, 67.9, 69.2, 68.6, 69.3, 68.7, 69.3, 68.4, 68.8, 68.2, 69.6, 68.3, 69.6, 68.1, 69.9, 67.8, 70.6, 68.2, 72.3, 68.0, 71.6, 68.0, 72.9, 68.1, 63.3, 69.2, 64.3, 69.2, 65.1, 68.9, 65.2, 69.3, 65.9, 69.5, 66.0, 69.0, 65.6, 69.3, 65.8, 69.6, 66.9, 69.4, 67.0, 69.0, 67.4, 69.3, 67.9, 69.1, 67.8, 69.3, 68.4, 69.3, 68.3, 68.7, 68.4, 69.5, 68.7, 69.5, 69.0, 68.9, 69.3, 68.8, 68.8, 69.4, 68.9, 68.8, 69.8, 69.1, 69.7, 69.2, 70.4, 69.3, 70.3, 68.8, 71.0, 69.1, 71.3, 69.4, 72.0, 68.7, 63.3, 70.4, 64.9, 70.5, 65.7, 70.1, 66.1, 69.8, 66.5, 70.3, 66.1, 70.3, 66.7, 69.7, 67.1, 70.1, 67.6, 70.4, 68.2, 69.9, 68.3, 69.8, 68.1, 69.9, 69.2, 70.3, 69.2, 70.2, 68.5, 70.4, 68.8, 70.4, 69.7, 70.7, 69.9, 69.7, 70.5, 70.5, 71.2, 70.5, 70.6, 70.5, 70.5, 70.5, 72.4, 70.3, 73.2, 70.3, 64.1, 71.4, 64.6, 71.0, 65.7, 71.6, 67.1, 70.9, 66.8, 71.4, 68.4, 71.5, 68.3, 71.2, 68.3, 71.6, 68.4, 71.6, 68.7, 71.3, 68.7, 71.1, 69.0, 71.5, 70.2, 71.0, 69.9, 71.5, 70.2, 70.9, 70.2, 71.4, 71.4, 71.3, 70.7, 71.2, 72.4, 71.5, 73.0, 70.8, 64.7, 72.7, 67.1, 72.0, 67.8, 72.3, 68.4, 72.2, 69.2, 72.4, 68.6, 72.0, 69.9, 71.8, 70.2, 72.5, 70.5, 72.6, 71.0, 71.9, 71.8, 72.6, 72.8, 72.4, 68.0, 73.1, 67.8, 73.6, 69.3, 73.3, 70.5, 73.1, 71.4, 73.7, 72.3, 73.6, 71.9, 72.9, 64.6, 73.9, 67.8, 74.3, 69.9, 73.9, 70.9, 74.2, 72.7, 74.5, 69.0, 75.1, 72.4, 76.4, 69.1, 78.4, 70.2, 61.2, 72.4, 72.6, 59.6, 64.9, 73.3, 73.0, 68.1, 71.8, 63.2, 65.3, 66.0, 60.9, 71.5, 72.1, 68.1, 71.0, 65.3, 61.7, 70.4, 67.5, 68.4, 64.4, 61.9, 63.3, 65.0, 63.5, 66.2, 63.7, 59.5, 63.9, 62.8, 63.9, 63.9, 63.9, 64.6, 64.1, 65.6, 64.7, 66.3, 64.4, 70.6, 63.9, 62.1, 64.8, 64.4, 65.3, 64.4, 65.2, 64.9, 65.5, 65.3, 65.2, 65.2, 65.4, 66.1, 65.6, 66.1, 64.7, 67.4, 64.8, 67.8, 65.6, 70.3, 65.4, 63.2, 66.5, 63.7, 65.7, 64.1, 66.1, 64.7, 66.3, 65.1, 66.6, 65.9, 66.4, 65.7, 66.5, 66.0, 66.3, 67.3, 66.4, 66.7, 66.3, 66.6, 66.1, 66.8, 66.5, 68.2, 66.3, 67.5, 66.1, 68.4, 65.9, 69.1, 65.7, 70.8, 66.1, 61.7, 67.6, 63.0, 67.4, 64.3, 67.0, 63.9, 67.2, 65.5, 67.2, 64.7, 67.4, 64.7, 67.4, 67.5, 68.2, 66.8, 62.7, 65.0, 66.3, 69.4, 65.7, 63.7, 68.4, 64.6, 67.5, 66.0, 67.2, 66.0, 67.2, 66.5, 67.5, 66.3, 66.9, 65.7, 67.7, 66.9, 67.0, 66.7, 66.7, 66.5, 66.8, 67.1, 67.4, 67.0, 66.9, 67.6, 67.5, 67.6, 66.9, 67.5, 67.0, 68.1, 66.9, 68.6, 67.0, 68.5, 67.1, 69.2, 67.5, 69.8, 67.5, 69.9, 67.3, 70.5, 67.6, 62.8, 67.8, 63.2, 68.1, 64.4, 68.5, 64.3, 68.6, 64.7, 67.9, 64.7, 68.6, 66.0, 68.2, 65.6, 68.3, 65.8, 68.2, 65.9, 68.2, 66.6, 68.2, 66.8, 68.6, 66.8, 68.3, 67.2, 68.7, 67.1, 68.5, 66.9, 67.7, 68.0, 68.0, 68.0, 67.8, 68.3, 68.1, 68.3, 68.6, 68.2, 68.2, 68.5, 68.2, 68.5, 68.2, 69.1, 68.1, 69.2, 68.1, 69.3, 68.5, 69.4, 68.4, 70.3, 68.2, 69.7, 67.7, 70.5, 67.9, 71.3, 68.3, 72.2, 68.3, 72.3, 68.3, 62.9, 69.6, 63.9, 68.7, 64.6, 68.9, 65.5, 68.8, 65.9, 69.1, 66.3, 69.0, 65.8, 69.0, 66.5, 68.7, 67.3, 69.5, 67.4, 69.1, 67.1, 69.1, 68.5, 69.6, 67.7, 69.4, 68.1, 69.2, 67.6, 68.8, 67.8, 69.0, 69.3, 69.5, 69.1, 69.6, 68.7, 69.4, 69.0, 69.6, 68.9, 69.4, 68.8, 68.9, 69.9, 68.7, 70.5, 69.3, 70.0, 68.7, 69.8, 68.8, 71.4, 69.5, 71.1, 69.7, 72.7, 69.7, 65.3, 70.5, 66.0, 70.0, 65.5, 70.6, 65.6, 70.5, 65.9, 70.0, 67.1, 69.9, 66.9, 70.5, 67.9, 69.9, 67.7, 69.7, 67.5, 70.6, 68.0, 70.2, 68.8, 70.3, 69.4, 70.2, 68.6, 70.5, 69.1, 70.5, 70.5, 70.2, 69.9, 70.0, 70.0, 70.2, 69.6, 70.2, 71.0, 70.0, 70.6, 70.4, 71.5, 70.4, 71.6, 70.2, 73.9, 70.2, 65.0, 70.7, 66.3, 71.5, 65.9, 71.4, 66.9, 71.2, 67.2, 70.9, 68.1, 71.3, 67.6, 71.4, 67.6, 71.2, 69.4, 71.2, 68.9, 71.2, 69.1, 71.0, 69.8, 71.4, 70.0, 71.2, 69.6, 71.6, 70.3, 71.3, 70.7, 71.5, 70.9, 70.9, 72.5, 71.5, 73.0, 71.1, 74.4, 70.9, 67.4, 72.7, 66.5, 71.8, 68.0, 72.6, 68.8, 72.5, 69.3, 71.9, 70.3, 72.2, 70.2, 72.6, 70.8, 72.3, 70.7, 72.1, 72.4, 72.3, 72.4, 72.1, 67.2, 72.8, 67.8, 72.8, 68.9, 73.5, 70.4, 73.7, 71.2, 72.8, 71.4, 73.4, 71.7, 73.0, 72.6, 73.2, 67.6, 74.5, 68.6, 73.8, 71.0, 73.8, 72.0, 73.8, 75.2, 73.8, 73.1, 75.6, 69.9, 77.2, 65.5, 60.1, 72.6, 76.8, 72.2, 66.7, 63.2, 58.8, 73.3, 67.9, 65.8, 61.0, 67.7, 59.8, 67.0, 70.8, 71.3, 68.3, 71.8, 69.3, 70.7, 69.3, 70.3, 67.0, ]",
"_____no_output_____"
],
[
"plt.hist(height, alpha=0.5)\nplt.show()",
"_____no_output_____"
]
]
]
| [
"code"
]
| [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
]
|
cb5fbfc59e43ae1f3aadddda420d5f9221489267 | 77,092 | ipynb | Jupyter Notebook | generate_designs/generate_experiment_designs.ipynb | StevenM1/flashtask | 22e88b386f934972fc9a208b3bbb231d53c21628 | [
"MIT"
]
| null | null | null | generate_designs/generate_experiment_designs.ipynb | StevenM1/flashtask | 22e88b386f934972fc9a208b3bbb231d53c21628 | [
"MIT"
]
| null | null | null | generate_designs/generate_experiment_designs.ipynb | StevenM1/flashtask | 22e88b386f934972fc9a208b3bbb231d53c21628 | [
"MIT"
]
| null | null | null | 48.978399 | 327 | 0.485628 | [
[
[
"from __future__ import division\nimport pandas as pd\nimport numpy as np\nimport os\nimport re\nimport copy\nfrom pprint import pprint\nfrom glob import glob\nimport cPickle as pkl",
"_____no_output_____"
]
],
[
[
"### Functions to generate blocks of trials\nLocalizer, cognitive, and limbic",
"_____no_output_____"
]
],
[
[
"def create_localizer_block_single_effector(n_trials, response_modality='eye', \n block_number=None, pseudorandomize=True, \n add_timing=True, null_trials=0, TR=2):\n \n # Only two trial types here: 'left' is correct, or 'right' is correct\n trial_types = np.repeat([0, 1], repeats=n_trials/2) # left/right\n \n # Initialize arrays\n cue_by_trial = np.zeros(n_trials, dtype='<U5')\n correct_answers = np.zeros(n_trials, dtype=np.int8)\n\n # Define the cues for every trial\n cue_by_trial[(trial_types == 0)] = 'LEFT'\n cue_by_trial[(trial_types == 1)] = 'RIGHT'\n# cue_by_trial[(trial_types == 2) | (trial_types == 3)] = 'anti'\n\n # Define the responses ('correct answers')/directions for every trial\n correct_answers[trial_types == 0] = 0\n correct_answers[trial_types == 1] = 1\n# correct_answers[(trial_types == 0) | (trial_types == 2)] = 0 # 0 = respond LEFT\n# correct_answers[(trial_types == 1) | (trial_types == 3)] = 1 # 1 = respond RIGHT\n \n # Create dataframe for easier handling\n trial_data = pd.DataFrame({'correct_answer': correct_answers,\n 'cue': cue_by_trial,\n 'trial_type': trial_types})\n \n # Should we pseudorandomize?\n if pseudorandomize:\n trial_data = Pseudorandomizer(trial_data, max_identical_iters={'correct_answer': 3,\n 'cue': 3}).run()\n \n trial_data['null_trial'] = False\n if null_trials > 0:\n trial_data = add_pseudorandom_null_trials(trial_data, n_null_trials=null_trials)\n \n # Add block number for completeness\n if block_number is not None:\n trial_data['block'] = block_number\n trial_data['block_type'] = 'localizer'\n\n # Usually, we also want to add the duration of all the 'trial phases'\n if add_timing:\n # Set phase_3 and phase_0 to 0 (no post-cue fixcross, no feedback)\n trial_data = get_localizer_timing(trial_data, TR=TR)\n \n trial_data['response_modality'] = response_modality.lower()\n \n return trial_data",
"_____no_output_____"
],
[
"def create_cognitive_block(n_trials, block_number=None, response_modality=None, \n add_timing=True, pseudorandomize=True, n_null_trials=0, TR=2):\n \"\"\"\n Creates a block of SAT-trials; mixing speed and accuracy trials\n \"\"\"\n \n trial_types = np.hstack((np.repeat([0, 1], repeats=n_trials / 4), # SPEED cue, left/right corr\n np.repeat([2, 3], repeats=n_trials / 4))) # ACCURACY cue, left/right corr\n\n if trial_types.shape[0] != n_trials:\n raise(ValueError('The provided n_trials (%d) could not be split into the correct number of trial types. '\n 'Closest option is %d trials' % (n_trials, trial_types.shape[0])))\n\n cue_by_trial = np.zeros(n_trials, dtype='<U5')\n correct_answers = np.zeros(n_trials, dtype=np.int8)\n\n cue_by_trial[(trial_types == 0) | (trial_types == 1)] = 'SPD'\n cue_by_trial[(trial_types == 2) | (trial_types == 3)] = 'ACC'\n\n correct_answers[(trial_types == 0) | (trial_types == 2)] = 0 # 0 = left is correct\n correct_answers[(trial_types == 1) | (trial_types == 3)] = 1 # 1 = right is correct\n\n # Create dataframe for easier handling\n trial_data = pd.DataFrame({'correct_answer': correct_answers,\n 'cue': cue_by_trial,\n 'trial_type': trial_types})\n \n if pseudorandomize:\n trial_data = Pseudorandomizer(trial_data, \n max_identical_iters={'cue': 5, 'correct_answer': 5}).run()\n \n if n_null_trials > 0:\n trial_data['null_trial'] = False\n trial_data = add_pseudorandom_null_trials(trial_data, \n n_null_trials=n_null_trials, \n null_column_name='null_trial')\n\n if block_number is not None:\n trial_data['block'] = block_number\n \n if response_modality is not None:\n trial_data['response_modality'] = response_modality\n trial_data['block_type'] = 'cognitive_%s' % response_modality \n\n if add_timing:\n while True:\n trial_data = get_block_timing(trial_data, TR=TR) # Add default timing\n \n if check_good_ITI_phase0(trial_data):\n break\n \n return trial_data",
"_____no_output_____"
],
[
"def create_limbic_block(n_trials, subject_number=1, block_number=None, \n response_modality=None, add_timing=True, pseudorandomize=True,\n n_null_trials=0, TR=2):\n \n trial_types = np.hstack((np.repeat([0, 1], repeats=n_trials/4), # Neutral cue, left/right corr\n np.repeat([2, 3], repeats=n_trials/8), # Left cue, left/right corr\n np.repeat([4, 5], repeats=n_trials/8))) # Right cue, left/right corr\n\n if trial_types.shape[0] != n_trials:\n raise(ValueError('The provided n_trials (%d) could not be split into the correct number of trial types. '\n 'Closest option is %d trials' % (n_trials, trial_types.shape[0])))\n\n cue_by_trial = np.zeros(n_trials, dtype='<U5')\n correct_answers = np.zeros(n_trials, dtype=np.int8)\n\n cue_by_trial[(trial_types == 0) | (trial_types == 1)] = 'NEU'\n cue_by_trial[(trial_types == 2) | (trial_types == 3)] = 'LEFT'\n cue_by_trial[(trial_types == 4) | (trial_types == 5)] = 'RIGHT'\n\n correct_answers[(trial_types == 0) |\n (trial_types == 2) |\n (trial_types == 4)] = 0 # 0 = left is correct\n correct_answers[(trial_types == 1) |\n (trial_types == 3) |\n (trial_types == 5)] = 1 # 1 = right is correct\n\n # Create dataframe for easier handling\n trial_data = pd.DataFrame({'correct_answer': correct_answers,\n 'cue': cue_by_trial,\n 'trial_type': trial_types})\n\n if pseudorandomize:\n trial_data = Pseudorandomizer(trial_data, \n max_identical_iters={'cue': 4, 'correct_answer': 4}).run()\n \n if n_null_trials > 0:\n trial_data['null_trial'] = False\n trial_data = add_pseudorandom_null_trials(trial_data, \n n_null_trials=n_null_trials, \n null_column_name='null_trial')\n \n if block_number is not None:\n trial_data['block'] = block_number\n \n if response_modality is not None:\n trial_data['response_modality'] = response_modality\n trial_data['block_type'] = 'limbic_%s' % response_modality \n\n if add_timing:\n while True:\n trial_data = get_block_timing(trial_data, TR=TR) # Add default timing\n \n if check_good_ITI_phase0(trial_data):\n break\n\n return trial_data",
"_____no_output_____"
]
],
[
[
"### Function that creates timing columns for a block of trials",
"_____no_output_____"
]
],
[
[
"def get_localizer_timing(trial_data, phase_0=None, phase_1=None, phase_2=None, phase_3=None, phase_4=None, phase_5=None, phase_6=None, TR=2):\n \"\"\"\n Each localizer trial consists of 7 phases.\n \n In phase_0, we wait for the scanner pulse. Note that phase_0 of trial n is the ITI after trial n-1. Set this timing always to 0: it is the `minimum` time to wait for the pulse\n In phase_1, we show the pre-cue fixation cross. By default, timing is jittered (0s, 0.5s, 1s, 1.5s if TR=2 -- 0, .75, 1.5, 2.25 if TR=3).\n In phase_2, we show the cue. Follows an exponential distrbibu.\n In phase_3, we show the post-cue fixation cross. Defaults to 0s.\n In phase_4, we assume the participant responds, and wait a bit until we show the fix cross. Defaults to 0.6s\n In phase_5 and phase_6, we do nothing (exist for compatibility with the experimental blocks)\n Phase_7 is ITI\n \"\"\"\n \n if TR == 2:\n trial_data['phase_0'] = 0 if phase_0 is None else phase_0\n trial_data['phase_1'] = np.random.choice([0.2, .7, 1.2, 1.7], size=trial_data.shape[0]) if phase_1 is None else phase_1\n trial_data['phase_2'] = 0.8 if phase_2 is None else phase_2\n trial_data['phase_3'] = 0 if phase_3 is None else phase_3\n trial_data['phase_4'] = 0.6 if phase_4 is None else phase_4\n trial_data['phase_5'] = 0 if phase_5 is None else phase_5\n trial_data['phase_6'] = 0 if phase_6 is None else phase_6\n elif TR == 3:\n trial_data['phase_0'] = 0 if phase_0 is None else phase_0\n trial_data['phase_1'] = np.random.choice([0, .750, 1.500, 2.250], size=trial_data.shape[0]) if phase_1 is None else phase_1\n trial_data['phase_2'] = np.round(np.random.exponential(scale=1/6, size=trial_data.shape[0])+.8, 3) if phase_2 is None else phase_2\n# trial_data['phase_2'] = np.round(np.random.uniform() ) if phase_2 is None else phase_2\n trial_data['phase_3'] = 0 if phase_3 is None else phase_3\n trial_data['phase_4'] = 0.8 if phase_4 is None else phase_4\n trial_data['phase_5'] = 0 if phase_5 is None else phase_5\n trial_data['phase_6'] = 0 if phase_6 is None else phase_6\n\n # Calculate duration of trial (depends on random, jittered durations of the fix cross)\n trial_data['trial_duration'] = trial_data[['phase_' + str(x) for x in range(7)]].sum(axis=1)\n\n # Because of TR = 2s, some trials can last 8 seconds, but most will last 10. Find trials with total time < 8 seconds\n # We calculate the ITI as the difference between the minimum number of pulses necessary for all phases to show.\n # [same applies to TR = 3]\n# min_TRs = np.ceil(trial_data['trial_duration'].values / TR)\n# trial_data['phase_7'] = min_TRs*TR - trial_data['trial_duration'].values\n trial_data['phase_7'] = 6 - trial_data['trial_duration'].values\n\n # Recalculate trial duration so it includes the ITI\n trial_data['trial_duration'] = trial_data[['phase_' + str(x) for x in range(8)]].sum(axis=1)\n\n # Add trial start times relative to start of block\n trial_data['trial_start_time_block'] = trial_data['trial_duration'].shift(1).cumsum()\n trial_data.loc[0, 'trial_start_time_block'] = 0\n\n # Add cue onset times relative to start of block\n trial_data['cue_onset_time_block'] = trial_data['trial_start_time_block'] + \\\n trial_data['phase_1']\n\n # Add stimulus onset times relative to start of block\n trial_data['stimulus_onset_time_block'] = trial_data['trial_start_time_block'] + \\\n trial_data['phase_1'] + \\\n trial_data['phase_2'] + \\\n trial_data['phase_3']\n return trial_data\n ",
"_____no_output_____"
],
[
"def get_block_timing(trial_data, phase_0=None, phase_1=None, phase_2=None, phase_3=None, phase_4=None, phase_5=None, phase_6=None, TR=2):\n \"\"\"\n Each trial consists of 7 phases.\n \n In phase_0, we wait for the scanner pulse. Note that phase_0 of trial n is the ITI after trial n-1. Set this timing always to 0: it is the `minimum` time to wait for the pulse\n In phase_1, we show the pre-cue fixation cross. By default, timing is jittered (0s, 0.5s, 1s, 1.5s)\n In phase_2, we show the cue. In decision-making trials, this is 4.8 seconds.\n In phase_3, we show the post-cue fixation cross. Timing is jittered (0s, 0.5s, 1s, 1.5s)\n In phase_4, we show the stimulus. Default is 1.5s.\n Phase 5 is defined as the period of stimulus presentation, after the participant made a response. The duration is determined by the participant RT, so not set here.\n In phase_6, we show feedback. Default is 0.35s. \n \"\"\"\n \n if TR == 2:\n trial_data['phase_0'] = 0 if phase_0 is None else phase_0\n trial_data['phase_1'] = np.random.choice([0, .5, 1, 1.5], size=trial_data.shape[0]) if phase_1 is None else phase_1\n trial_data['phase_2'] = 4.8 if phase_2 is None else phase_2\n trial_data['phase_3'] = np.random.choice([0, .5, 1, 1.5], size=trial_data.shape[0]) if phase_3 is None else phase_3\n trial_data['phase_4'] = 2 if phase_4 is None else phase_4\n trial_data['phase_5'] = 0 if phase_5 is None else phase_5\n trial_data['phase_6'] = 0.35 if phase_6 is None else phase_6\n elif TR == 3:\n trial_data['phase_0'] = 0 if phase_0 is None else phase_0\n trial_data['phase_1'] = np.random.choice([0, .750, 1.500, 2.250], size=trial_data.shape[0]) if phase_1 is None else phase_1\n trial_data['phase_2'] = 1 if phase_2 is None else phase_2\n trial_data['phase_3'] = np.random.choice([0.750, 1.500, 2.250, 3.000], size=trial_data.shape[0]) if phase_3 is None else phase_3\n trial_data['phase_4'] = 2 if phase_4 is None else phase_4\n trial_data['phase_5'] = 0 if phase_5 is None else phase_5\n trial_data['phase_6'] = 0.5 if phase_6 is None else phase_6\n\n\n # Calculate duration of trial (depends on random, jittered durations of the fix cross)\n trial_data['trial_duration'] = trial_data[['phase_' + str(x) for x in range(7)]].sum(axis=1)\n\n if TR == 2:\n # Because of TR = 2s, some trials can last 8 seconds, but most will last 10. Find trials with total time < 8 seconds\n # We calculate the ITI as the difference between the minimum number of pulses necessary for all phases to show.\n min_TRs = np.ceil(trial_data['trial_duration'].values / TR)\n trial_data['phase_7'] = min_TRs*TR - trial_data['trial_duration'].values\n elif TR == 3:\n # In this case, fill all trials until 9s have passed.\n trial_data['phase_7'] = 9 - trial_data['trial_duration'].values\n\n # Recalculate trial duration so it includes the ITI\n trial_data['trial_duration'] = trial_data[['phase_' + str(x) for x in range(8)]].sum(axis=1)\n\n # Add trial start times relative to start of block\n trial_data['trial_start_time_block'] = trial_data['trial_duration'].shift(1).cumsum()\n trial_data.loc[0, 'trial_start_time_block'] = 0\n\n # Add cue onset times relative to start of block\n trial_data['cue_onset_time_block'] = trial_data['trial_start_time_block'] + \\\n trial_data['phase_1']\n\n # Add stimulus onset times relative to start of block\n trial_data['stimulus_onset_time_block'] = trial_data['trial_start_time_block'] + \\\n trial_data['phase_1'] + \\\n trial_data['phase_2'] + \\\n trial_data['phase_3']\n return trial_data",
"_____no_output_____"
]
],
[
[
"### Function to check timing\nIf ITI after trial n is 0, it is not allowed to have trial n+1 phase1 = 0 (otherwise, a new cue can be shown immediately after feedback)",
"_____no_output_____"
]
],
[
[
"def check_good_ITI_phase0(data):\n # Get rid of Null Trials, and the trials before the Null Trials\n nulls = data[data['null_trial'] == True].index.values\n nulls = np.hstack((nulls, data.shape[0]-1))\n \n start_id = 0\n for end_id in nulls:\n data_subset = data.iloc[np.arange(start_id, end_id)].copy()\n # Shift rows in column phase_1\n data_subset['phase_1'] = data_subset['phase_1'].shift(-1)\n\n # Check whether (shifted) phase_1 values == phase_7 values, AND phase_1 values is 0.\n idx = (data_subset['phase_1'].values == data_subset['phase_7'].values) & (data_subset['phase_1'].values == 0.00)\n\n if np.sum(idx) > 0:\n# print(data_subset[['phase_1', 'phase_7']])\n return False\n \n start_id = end_id + 1\n \n return True \n \n# dat = create_cognitive_block(n_trials=100,\n# block_number=1, \n# response_modality='hand',\n# n_null_trials=7, \n# TR=3)\n# print(dat[['phase_1', 'phase_7']].head(6))\n# check_good_ITI_phase0(dat)",
"_____no_output_____"
]
],
[
[
"### Class for pseudorandomization",
"_____no_output_____"
]
],
[
[
"class Pseudorandomizer(object):\n \n def __init__(self, data, max_identical_iters={'cue': 4, 'correct_answer': 4}): \n self.data = data\n self.max_identical_iters = {x: y+1 for x, y in max_identical_iters.items()}\n # add 1: if 4 rows is allowed, only give an error after 5 identical rows\n \n def check_trial_rows(self, data, row_n): \n \"\"\"\n Returns True if any of the conditions for pseudorandomization are violated for the given rows, \n False if they are fine.\n \"\"\"\n \n # First, check for the maximum iterations\n for column, max_iter in self.max_identical_iters.items():\n if row_n - max_iter < 0:\n continue\n\n # Select rows [max_iter-1 - row_n] we're going to check. Never select any row with index < 0\n row_selection = [x for x in np.arange(row_n, row_n-max_iter, -1)]\n\n # Next, we check if the selected rows only contain *1* trial type. \n # If so, this means we have max_iter rows of the same trials, and we need to change something.\n if data.iloc[row_selection][column].nunique() == 1:\n return True\n\n return False\n\n def run(self, debug=False):\n \"\"\"\n Pseudorandomizes: makes sure that it is not possible to have more than x iterations for every type of column, specified in columns.\n \"\"\"\n # Start by copying from original data, and shuffle\n self.data = self.data.sample(frac=1, \n random_state=np.random.randint(0, 1e7, dtype='int')).reset_index(drop=True) \n \n if debug:\n outer_while_i = 0\n debug_print_after_i = 100\n\n good_set = False\n while not good_set:\n if debug:\n outer_while_i += 1\n\n reshuffle = False # Assume the dataset does not need reshuffling.\n for row_n in range(0, self.data.shape[0]):\n\n # Select rows [max_iter-1 - row_n] we're going to check\n\n # Check if the current row, and the (max_iters-1) rows before, are the same value (number of unique values = 1).\n # If so, then move the current row number to the bottom of the dataframe. However, we need to re-check the same four rows again\n # after moving a row to the bottom: therefore, a while loop is necessary.\n checked_row = False\n n_attempts_at_moving = 0\n \n if debug:\n inner_while_i = 0\n \n while not checked_row:\n if debug:\n inner_while_i += 1\n if inner_while_i > debug_print_after_i:\n print('New inner loop started for current row')\n\n if self.check_trial_rows(self.data, row_n):\n if debug and inner_while_i > debug_print_after_i:\n print('Found too many consecutively identical rows.')\n\n # If there are too many consecutively identical rows at the bottom of the dataframe, \n # break and start over/shuffle\n if row_n >= (self.data.shape[0] - self.max_identical_iters[self.max_identical_iters.keys()[0]]):\n if debug and inner_while_i > debug_print_after_i:\n print('These occurred at row_n %d, which is at the bottom of the DF.' % row_n)\n\n checked_row = True\n reshuffle = True\n\n # Too many consecutive identical rows? Move row_n to the bottom, and check again with the new row_n.\n else:\n if debug and inner_while_i > debug_print_after_i:\n print('These occurred at row_n %d. Checking the remainder of the DF.' % row_n)\n\n # Check if moving to the bottom even makes sense: if all remaining values are identical, it doesn't.\n if (self.data.iloc[row_n:][self.max_identical_iters.keys()].nunique().values < 2).any():\n if debug and inner_while_i > debug_print_after_i:\n print('All remaining values are identical. I should stop the for-loop, and start over.')\n\n checked_row = True\n reshuffle = True\n else:\n if n_attempts_at_moving < 50:\n n_attempts_at_moving += 1\n\n if debug and inner_while_i > debug_print_after_i:\n print('Not all remaining values are identical. I should move the final part to the bottom.')\n\n # If not, move the current row to the bottom\n row_to_move = self.data.iloc[row_n,:]\n\n # Delete row from df\n self.data.drop(row_n, axis=0, inplace=True)\n\n # Append original row to end. Make sure to reset index\n self.data = self.data.append(row_to_move).reset_index(drop=True)\n\n # If we already tried moving the current row to the bottom for 50 times, let's forget about it and restart\n else:\n checked_row = True\n reshuffle = True\n else:\n if debug and inner_while_i > debug_print_after_i:\n print('Checked row, but the row is fine. Next row.')\n checked_row = True\n\n if reshuffle:\n good_set = False\n break # out of the for loop\n\n # Reached the bottom of the dataframe, but no reshuffle call? Then we're set.\n if row_n == self.data.shape[0]-1:\n good_set = True\n\n if reshuffle:\n # Shuffle, reset index to ensure trial_data.drop(row_n) rows\n self.data = self.data.sample(frac=1, random_state=np.random.randint(0, 1e7, dtype='int')).reset_index(drop=True)\n \n return self.data\n \ndef add_pseudorandom_null_trials(data, min_row=4, max_row=4, min_n_rows_separate=7, \n n_null_trials=10, null_column_name=''):\n \"\"\" \n Adds null trials interspersed at pseudorandom locations. You can determine the minimum\n number of trials at the start before a null trial, the minimum number of trials at the end in which no\n nulls are shown, and the minimum number of trials that the null trials have to be separated \n \"\"\"\n \n good_idx = False\n while not good_idx:\n indx = np.random.choice(np.arange(min_row, data.shape[0]-max_row), \n replace=False, size=n_null_trials)\n diffs = np.diff(np.sort(indx))\n if (diffs >= min_n_rows_separate).all():\n good_idx = True\n \n data.index = np.setdiff1d(np.arange(data.shape[0] + n_null_trials), indx)\n new_rows = pd.DataFrame({null_column_name: [True]*n_null_trials}, columns=data.columns, index=indx) \n data = data.append(new_rows).sort_index()\n \n # Always end with a null trial\n last_row = pd.DataFrame({null_column_name: [True]*1}, columns=data.columns, index=[data.shape[0]])\n data = data.append(last_row).sort_index() \n \n return data",
"_____no_output_____"
]
],
[
[
"### Functions for brute-force optimizing",
"_____no_output_____"
]
],
[
[
"def create_localizer(n_localizer_blocks, n_trials_per_localizer_block, localizer_order, block_number=0, pseudorandomize=True, TR=3):\n\n # Initiate empty dataframe, generate block\n block_data = pd.DataFrame()\n for localizer_block in range(int(n_localizer_blocks/2)):\n loc_block = create_localizer_block_single_effector(n_trials=n_trials_per_localizer_block, \n response_modality=localizer_order[0],\n block_number=block_number,\n pseudorandomize=pseudorandomize, TR=TR)\n block_data = block_data.append(loc_block)\n loc_block = create_localizer_block_single_effector(n_trials=n_trials_per_localizer_block, \n response_modality=localizer_order[1],\n block_number=block_number,\n pseudorandomize=pseudorandomize, TR=TR)\n block_data = block_data.append(loc_block)\n\n return block_data",
"_____no_output_____"
],
[
"# Function to convolve design\nfrom nipy.modalities.fmri import hrf, utils\n\ndef stim_to_design(pp_design, block=None, silent=False):\n \n # Check if we only need to do a subset of the design\n if block is not None:\n pp_design = pp_design.loc[pp_design['block'] == block]\n \n # Get rid of null trials\n pp_design = pp_design.loc[pp_design['null_trial'] == False,:]\n\n # hrf.glover is a symbolic function; get a function of time to work on arrays\n hrf_func = utils.lambdify_t(hrf.glover(utils.T))\n \n max_time = np.ceil((pp_design['stimulus_onset_time'].max()+25)*10)\n\n if 0 in pp_design['block'].unique():\n block0_trials = pp_design.loc[pp_design['block'] == 0]\n # Get cue-types and response types for the first block\n loc_cue_vec = np.zeros(shape=(int(max_time), 4))\n response_vec = np.zeros(shape=(int(max_time), 4))\n loc_cue_names = []\n response_names = []\n\n i = -1\n for effector_type in block0_trials['response_modality'].unique():\n for cue_type in block0_trials['cue'].unique():\n \n subset = pp_design.loc[(pp_design['block'] == 0 ) &\n (pp_design['response_modality'] == effector_type) &\n (pp_design['cue'] == cue_type)]\n i += 1\n response_names.append('resp_%s_%s' % (effector_type, cue_type))\n loc_cue_names.append('cue_%s_%s' % (effector_type, cue_type))\n\n # Get cue onsets & durations\n onsets = np.round(subset['cue_onset_time'].values*10)\n durations = np.round(subset['phase_2'].values*10)\n for onset, duration in zip(onsets, durations):\n loc_cue_vec[np.arange(onset, onset+duration, dtype='int'), i] = 1\n\n # Get response onsets & durations\n onsets = np.round(subset['stimulus_onset_time'].values*10)\n durations = np.round(subset['phase_4'].values*10)\n for onset, duration in zip(onsets, durations):\n response_vec[np.arange(onset, onset+duration, dtype='int'), i] = 1\n \n # For all further EVs, make sure not to include the localizer trials.\n pp_design = pp_design.loc[pp_design['block'] > 0]\n\n # 10 types of stimuli: (n_cue_types) * (n_stim_types)\n stim_vec = np.zeros(shape=(int(max_time), pp_design['correct_answer'].nunique()*pp_design['cue'].nunique()))\n stim_names = []\n\n # Get stimulus onsets and durations\n i = -1\n for stim_type in pp_design['correct_answer'].unique():\n\n for cue_type in pp_design['cue'].unique():\n i += 1\n stim_names.append('stimulus_' + str(int(stim_type)) + '_' + cue_type)\n subset = pp_design.loc[(pp_design['correct_answer'] == stim_type) &\n (pp_design['cue'] == cue_type)]\n stim_onsets = np.round(subset['stimulus_onset_time'].values*10)\n stim_durations = np.round(subset['phase_4'].values*10)\n\n for onset, duration in zip(stim_onsets, stim_durations):\n# stim_vec = np.hstack((stim_vec, np.zeros(shape=(int(max_time), 1))))\n stim_vec[np.arange(onset, onset+duration, dtype='int'), i] = 1\n\n # Get cue onsets by cue type\n cue_names = []\n n_conditions = len(np.unique(pp_design['cue']))\n cue_vec = np.zeros(shape=(int(max_time), n_conditions)) # A column per cue type condition\n i = -1\n for condition in pp_design['cue'].unique():\n i += 1\n cue_names.append('cue_' + condition)\n\n # Find cue onsets\n onsets = np.round(pp_design.loc[pp_design['cue'] == condition, 'cue_onset_time'].values*10)\n durations = np.round(pp_design.loc[pp_design['cue'] == condition, 'phase_2'].values*10)\n for onset, duration in zip(onsets, durations):\n cue_vec[np.arange(onset, onset+duration, dtype='int'), i] = 1\n\n # Combine everything in a single array\n if 'loc_cue_vec' in locals():\n ev_vec = np.hstack((loc_cue_vec, response_vec, cue_vec, stim_vec))\n ev_names = loc_cue_names + response_names + cue_names + stim_names\n else:\n ev_vec = np.hstack((cue_vec, stim_vec))\n ev_names = cue_names + stim_names\n\n # Create hrf to convolve with\n hrf_full = hrf_func(np.linspace(0, stop=int(max_time/10), num=int(max_time)))\n\n # Pre-allocate output. This will be an n_timepoints x n_conditions+1 matrix.\n X = np.empty(shape=(int(max_time), ev_vec.shape[1]))\n\n # Convolve everything: the stimulus first, the cues afterwards.\n for i, ev_name in enumerate(ev_names):\n if not silent:\n print('Convolving %s...' % ev_name)\n X[:, i] = np.convolve(hrf_full, ev_vec[:, i])[:int(max_time)]\n \n return X, ev_names",
"_____no_output_____"
],
[
"def optimize_brute_force(n_trials, \n c, # contrasts to be optimized\n run_type='localizer',\n block_number=0,\n pseudorandomize=True, \n TR=3,\n n_attempts=1e4,\n \n # For non-localizer:\n n_null_trials=0,\n response_modality='hand',\n \n # for localizer:\n n_localizer_blocks=None, localizer_order=None):\n \n \"\"\" Performs a brute force search of the best possible trial order & jitter times for a single run \"\"\"\n n_attempts = int(n_attempts)\n \n # Generate n_attempt seeds to check\n seeds = np.round(np.random.uniform(low=int(0), high=int(2**32 - 1), size=n_attempts)).astype(int)\n effs = np.zeros(shape=seeds.shape)\n best_eff = 0\n \n best_block = None\n \n for i in range(n_attempts):\n # Set seed\n np.random.seed(seed=seeds[i])\n \n # Generate run\n if run_type == 'localizer':\n block_data = create_localizer(n_localizer_blocks=n_localizer_blocks, \n n_trials_per_localizer_block=n_trials, \n localizer_order=localizer_order, \n block_number=block_number, \n pseudorandomize=pseudorandomize, TR=TR)\n elif run_type == 'cognitive':\n block_data = create_cognitive_block(n_trials=n_trials, \n block_number=block_number, \n response_modality=response_modality,\n n_null_trials=n_null_trials, \n TR=TR)\n elif run_type == 'limbic':\n block_data = create_limbic_block(n_trials=n_trials, \n block_number=block_number, \n response_modality=response_modality,\n n_null_trials=n_null_trials,\n TR=TR)\n\n # Add trial start times (relative to start of experiment)\n block_data['trial_start_time'] = block_data['trial_duration'].shift(1).cumsum()\n block_data.loc[0, 'trial_start_time'] = 0\n\n # Add cue onset times (relative to start of experiment)\n block_data['cue_onset_time'] = block_data['trial_start_time'] + \\\n block_data['phase_1']\n\n # Add stimulus onset times (relative to start of experiment)\n block_data['stimulus_onset_time'] = block_data['trial_start_time'] + \\\n block_data['phase_1'] + \\\n block_data['phase_2'] + \\\n block_data['phase_3']\n \n # Calculate efficiency\n X, ev_names = stim_to_design(block_data, block=block_number, silent=True)\n \n # Loop over the contrasts\n dvars = [(c[ii, :].dot(np.linalg.pinv(X.T.dot(X))).dot(c[ii, :].T))\n for ii in range(c.shape[0])]\n eff = c.shape[0] / np.sum(dvars)\n effs[i] = eff\n \n # Found a better block than anything earlier? Save this\n if eff > best_eff:\n best_eff = eff\n best_seed = seeds[i]\n best_block = block_data\n \n # Save everything\n out_dict = {'seeds': seeds, \n 'efficiencies': effs, \n 'best_eff': best_eff, \n 'best_seed': best_seed, \n 'best_block': best_block,\n 'contrasts': c,\n 'contrast_ev_names': ev_names}\n \n print('Done optimizing, tried %d seeds. Best efficiency: %.4f (mean eff: %.3f (SD %.3f))' % \n (n_attempts, best_eff, np.mean(effs), np.std(effs)))\n\n # return block\n return best_block, out_dict",
"_____no_output_____"
]
],
[
[
"## Order of blocks by participant\n\n- X = localizer hand\n- Y = localizer eye\n- A = cognitive, hand\n- B = cognitive, eye\n- C = limbic, hand\n- D = limbic, eye\n\n4 blocks, 4\\*3\\*2\\*1 = 4! = 24 block orders\n\n2 localizer 'blocks', 2\\*1 = 2 possible orders.\nIn total, 48 possible block orders",
"_____no_output_____"
]
],
[
[
"import itertools\nfrom pprint import pprint\n\n# Use itertools permutations to get all possible orders of both blocks and localizers\nblock_order = list(itertools.permutations(\"ABCD\"))\nloc_order = list(itertools.permutations(\"XY\"))\n\n# Repeat all elements in loc_orders to match sizes\nloc_order = [item for item in loc_order for i in range(len(block_order))]\n\n# Merge localizer and blocks\nblock_order = [(x[0], x[1], y[0], y[1], y[2], y[3]) for x, y in zip(loc_order, block_order*2)]\npprint(block_order)\nlen(block_order) # 48 possible conditions!",
"[('X', 'Y', 'A', 'B', 'C', 'D'),\n ('X', 'Y', 'A', 'B', 'D', 'C'),\n ('X', 'Y', 'A', 'C', 'B', 'D'),\n ('X', 'Y', 'A', 'C', 'D', 'B'),\n ('X', 'Y', 'A', 'D', 'B', 'C'),\n ('X', 'Y', 'A', 'D', 'C', 'B'),\n ('X', 'Y', 'B', 'A', 'C', 'D'),\n ('X', 'Y', 'B', 'A', 'D', 'C'),\n ('X', 'Y', 'B', 'C', 'A', 'D'),\n ('X', 'Y', 'B', 'C', 'D', 'A'),\n ('X', 'Y', 'B', 'D', 'A', 'C'),\n ('X', 'Y', 'B', 'D', 'C', 'A'),\n ('X', 'Y', 'C', 'A', 'B', 'D'),\n ('X', 'Y', 'C', 'A', 'D', 'B'),\n ('X', 'Y', 'C', 'B', 'A', 'D'),\n ('X', 'Y', 'C', 'B', 'D', 'A'),\n ('X', 'Y', 'C', 'D', 'A', 'B'),\n ('X', 'Y', 'C', 'D', 'B', 'A'),\n ('X', 'Y', 'D', 'A', 'B', 'C'),\n ('X', 'Y', 'D', 'A', 'C', 'B'),\n ('X', 'Y', 'D', 'B', 'A', 'C'),\n ('X', 'Y', 'D', 'B', 'C', 'A'),\n ('X', 'Y', 'D', 'C', 'A', 'B'),\n ('X', 'Y', 'D', 'C', 'B', 'A'),\n ('Y', 'X', 'A', 'B', 'C', 'D'),\n ('Y', 'X', 'A', 'B', 'D', 'C'),\n ('Y', 'X', 'A', 'C', 'B', 'D'),\n ('Y', 'X', 'A', 'C', 'D', 'B'),\n ('Y', 'X', 'A', 'D', 'B', 'C'),\n ('Y', 'X', 'A', 'D', 'C', 'B'),\n ('Y', 'X', 'B', 'A', 'C', 'D'),\n ('Y', 'X', 'B', 'A', 'D', 'C'),\n ('Y', 'X', 'B', 'C', 'A', 'D'),\n ('Y', 'X', 'B', 'C', 'D', 'A'),\n ('Y', 'X', 'B', 'D', 'A', 'C'),\n ('Y', 'X', 'B', 'D', 'C', 'A'),\n ('Y', 'X', 'C', 'A', 'B', 'D'),\n ('Y', 'X', 'C', 'A', 'D', 'B'),\n ('Y', 'X', 'C', 'B', 'A', 'D'),\n ('Y', 'X', 'C', 'B', 'D', 'A'),\n ('Y', 'X', 'C', 'D', 'A', 'B'),\n ('Y', 'X', 'C', 'D', 'B', 'A'),\n ('Y', 'X', 'D', 'A', 'B', 'C'),\n ('Y', 'X', 'D', 'A', 'C', 'B'),\n ('Y', 'X', 'D', 'B', 'A', 'C'),\n ('Y', 'X', 'D', 'B', 'C', 'A'),\n ('Y', 'X', 'D', 'C', 'A', 'B'),\n ('Y', 'X', 'D', 'C', 'B', 'A')]\n"
]
],
[
[
"## Loop over participant numbers to generate the correct blocks in order, and save",
"_____no_output_____"
]
],
[
[
"a = [x for x in range(120) if x % 4 == 0 and x % 8 == 0]\nprint(a)",
"[0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96, 104, 112]\n"
]
],
[
[
"## For which participants do you want to create designs?",
"_____no_output_____"
]
],
[
[
"participant_range = [25, 26]",
"_____no_output_____"
],
[
"n_trials_per_localizer_block = 8\nn_localizer_blocks = 6\nTR = 3\n\nos.chdir('/Users/steven/Sync/PhDprojects/subcortex/flashtask/designs')\n\nn_optim_attempts = 1e3\nn_trials_limbic = 80\nn_trials_cognitive = 72\nn_null_trials_limbic = 8\nn_null_trials_cognitive = 7\n\n## Contrasts to optim for\nc_localizer = np.array([\n [0, 0, 0, 0, 1, 1, 0, 0], # hand vs baseline\n [0, 0, 0, 0, 0, 0, 1, 1], # eye vs baseline\n [0, 0, 0, 0, 1, 1, -1, -1] # hand - eye\n ])\n\n# Cognitive: [u'cue_ACC', u'cue_SPD', u'stimulus_0_ACC', u'stimulus_0_SPD', u'stimulus_1_ACC', u'stimulus_1_SPD']\n# Of interest: ACC vs SPD cue\n# ACC vs SPD stimulus\n# ACC vs SPD trial (cue + stim)\nc_cognitive = np.array([\n [1, -1, 0, 0, 0, 0], # ACC vs SPD cue\n [0, 0, 1, -1, 1, -1], # ACC vs SPD stimulus\n [1, -1, 1, -1, 1, -1] # ACC vs SPD cue and stimulus\n])\n\n# Limbic:\n# [u'cue_RIGHT', u'cue_NEU', u'cue_LEFT', \n# u'stimulus_1_RIGHT', u'stimulus_1_NEU', u'stimulus_1_LEFT', \n# u'stimulus_0_RIGHT', u'stimulus_0_NEU', u'stimulus_0_LEFT']\n# Of interest: direction vs neutral cue; direction vs neutral stim; direction vs neutral cue+stim\nc_limbic = np.array([\n [1, -2, 1, 0, 0, 0, 0, 0, 0], # direction vs neutral cue\n [0, 0, 0, 1, -2, 1, 1, -2, 1], # direction vs neutral stim\n [1, -2, 1, 1, -2, 1, 1, -2, 1] # direction vs neutral cue+stim\n])\n\n# Loop & Run\nfor pp in range(participant_range[0], participant_range[1]):\n pp_str = str(pp).zfill(3)\n print('Processing pp %s...' % pp_str)\n block_order_this_pp = block_order[pp % len(block_order)]\n \n # Empty DataFrame\n design_this_pp = pd.DataFrame()\n \n # Get localizer block\n if block_order_this_pp[0] == 'X':\n localizer_order = ['hand', 'eye']\n else:\n localizer_order = ['eye', 'hand']\n\n design_this_pp, optim_res = optimize_brute_force(n_trials=n_trials_per_localizer_block,\n c=c_localizer, \n run_type='localizer',\n block_number=0,\n pseudorandomize=True, \n TR=3,\n n_attempts=n_optim_attempts,\n n_localizer_blocks=6, \n localizer_order=localizer_order)\n with open('pp_' + pp_str + '_block_0_optim.pkl', 'wb') as f:\n pkl.dump(optim_res, f)\n \n # Get blocks\n for block_number, block_char in enumerate(block_order_this_pp):\n if block_char in ['X', 'Y']:\n continue\n \n if block_char == 'A':\n block_data, optim_res = optimize_brute_force(n_trials=n_trials_cognitive, \n c=c_cognitive,\n run_type='cognitive',\n block_number=block_number-1, \n response_modality='hand',\n n_null_trials=n_null_trials_cognitive, \n TR=TR,\n pseudorandomize=True,\n n_attempts=n_optim_attempts)\n elif block_char == 'B':\n block_data, optim_res = optimize_brute_force(n_trials=n_trials_cognitive, \n c=c_cognitive,\n run_type='cognitive',\n block_number=block_number-1, \n response_modality='eye',\n n_null_trials=n_null_trials_cognitive, \n TR=TR,\n pseudorandomize=True,\n n_attempts=n_optim_attempts)\n elif block_char == 'C':\n block_data, optim_res = optimize_brute_force(n_trials=n_trials_limbic, \n c=c_limbic,\n run_type='limbic',\n block_number=block_number-1, \n response_modality='hand',\n n_null_trials=n_null_trials_limbic, \n TR=TR,\n pseudorandomize=True,\n n_attempts=n_optim_attempts)\n elif block_char == 'D':\n block_data, optim_res = optimize_brute_force(n_trials=n_trials_limbic, \n c=c_limbic,\n run_type='limbic',\n block_number=block_number-1, \n response_modality='eye',\n n_null_trials=n_null_trials_limbic, \n TR=TR,\n pseudorandomize=True,\n n_attempts=n_optim_attempts)\n\n with open('pp_' + pp_str + '_block_' + str(block_number-1) + '_optim.pkl', 'wb') as f:\n pkl.dump(optim_res, f)\n design_this_pp = design_this_pp.append(block_data)\n\n # Set indices\n design_this_pp.index.name = 'block_trial_ID'\n design_this_pp.reset_index(inplace=True)\n design_this_pp.index.name = 'trial_ID'\n \n # Add trial start times (relative to start of experiment)\n design_this_pp['trial_start_time'] = design_this_pp['trial_duration'].shift(1).cumsum()\n design_this_pp.loc[0, 'trial_start_time'] = 0\n\n # Add cue onset times (relative to start of experiment)\n design_this_pp['cue_onset_time'] = design_this_pp['trial_start_time'] + \\\n design_this_pp['phase_1']\n\n # Add stimulus onset times (relative to start of experiment)\n design_this_pp['stimulus_onset_time'] = design_this_pp['trial_start_time'] + \\\n design_this_pp['phase_1'] + \\\n design_this_pp['phase_2'] + \\\n design_this_pp['phase_3']\n \n # Re-order column order for nicety\n design_this_pp = design_this_pp[['block_trial_ID', 'block', 'block_type', 'null_trial', 'correct_answer', 'cue', 'response_modality', 'trial_type', \n 'phase_0', 'phase_1', 'phase_2', 'phase_3', 'phase_4', 'phase_5', 'phase_6', 'phase_7', 'trial_duration', \n 'trial_start_time', 'cue_onset_time', 'stimulus_onset_time',\n 'trial_start_time_block', 'cue_onset_time_block', 'stimulus_onset_time_block']]\n \n # Save full data\n if not os.path.exists(os.path.join('pp_%s' % pp_str, 'all_blocks')):\n os.makedirs(os.path.join('pp_%s' % pp_str, 'all_blocks'))\n design_this_pp.to_csv(os.path.join('pp_%s' % pp_str, 'all_blocks', 'trials.csv'), index=True)\n \n # Save individual blocks\n for block_num, block_type in zip(design_this_pp['block'].unique(), design_this_pp['block_type'].unique()):\n block = design_this_pp.loc[design_this_pp['block'] == block_num]\n \n if not os.path.exists(os.path.join('pp_%s' % pp_str, 'block_%d_type_%s' % (block_num, block_type))):\n os.makedirs(os.path.join('pp_%s' % pp_str, 'block_%d_type_%s' % (block_num, block_type)))\n \n block.to_csv(os.path.join('pp_%s' % pp_str, 'block_%d_type_%s' % (block_num, block_type), 'trials.csv'), index=True)",
"Processing pp 025...\n"
]
],
[
[
"# Creating EVs, .fsf-files, and running FSL\nAll following code is used to transform the created designs into FSL-accepted formats. First, we create 3-column .txt-files for every regressor. Then, we *manually* and painfully make the .fsf file for a single subject (for all designs) in the FSL gui (if someone can point me to a CLI for this, I'd be very grateful).\nFinally, we copy the created .fsf-file and substitute all references to the first pp for each other pp.\n\nThe current set-up is to model the following EVs:\n- Localizer (8 EVs):\n 1. cue: direction x response modality (left/right x eye/hand) = 4 EVs\n 2. response: direction x response modality (left/right x eye/hand) = 4 EVs.\n- Limbic blocks (9 EVs):\n 1. cue: direction (left/right/neutral) = 3 EVs\n 2. stimulus: cued direction (left/right/neutral) x stimulus direction (left/right) = 6 EVs\n- Cognitive blocks (6 EVs):\n 1. cue: instruction (spd/acc) = 2 EVs\n 2. stimulus: cued instruction (spd/acc) x stimulus direction (left/right) = 4 EVs\n\nIn total, the first-level design has 23 EVs (currently not including responses). In the following code, we extract the EV timing from the design files.\n\n### Create EV .txts files that can be read by FSL",
"_____no_output_____"
]
],
[
[
"for pp_num in range(participant_range[0], participant_range[1]):\n print('Processing pp %d...' % (pp_num))\n \n pp_str = str(pp_num).zfill(3)\n \n # Get all blocks directories of this subject, making sure to ignore any existing .feat-dirs\n pp_block_dirs = glob('pp_%s/*' % pp_str)\n pp_block_dirs = [x for x in pp_block_dirs if not x.endswith('.feat')]\n \n # Loop over blocks\n for pp_block_dir in pp_block_dirs:\n \n # For all blocks, or the localizer block, we can use the \"global\" timing (not within-block) to create EVs.\n if 'all_blocks' in pp_block_dir or 'localizer' in pp_block_dir:\n stim_onset_col = 'stimulus_onset_time'\n cue_onset_col = 'cue_onset_time'\n else: # Otherwise, use only the block timing\n stim_onset_col = 'stimulus_onset_time_block'\n cue_onset_col = 'cue_onset_time_block'\n \n # Define output directory, create if it doesnt exist\n output_dir = os.path.join(pp_block_dir, 'evs')\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n \n # Read design from csv\n design = pd.read_csv(os.path.join(pp_block_dir, 'trials.csv'))\n design = design[['correct_answer','trial_type', 'block', 'phase_2', 'phase_4', 'cue', cue_onset_col, \n stim_onset_col, 'response_modality', 'null_trial']]\n \n # Get rid of all null trials\n design = design.loc[design['null_trial'] != True]\n \n # Weights of all EVs are 1\n design['weight'] = 1\n \n # For the localizer block\n if 0 in design['block'].unique():\n subs = design.loc[design['block'] == 0]\n \n # EVs for cues and responses, separated for the response modality (eye/hand) and direction (left/right): \n # 4 EVs for cue (left/right x eye/hand), and 4 EVs for the responses (left/right x eye/hand)\n for effector in subs['response_modality'].unique():\n for cue in subs['cue'].unique():\n # response\n ev = subs.loc[(subs['response_modality'] == effector) & \n (subs['cue'] == cue), [stim_onset_col, 'phase_4', 'weight']].values.tolist()\n \n with open(os.path.join(output_dir, 'ev_resp_%s_%s.txt' % (effector, cue)), 'wb') as f:\n for _list in ev:\n for _string in _list:\n f.write(str(_string) + '\\n')\n f.write('\\n')\n \n # responses\n ev = subs.loc[(subs['response_modality'] == effector) & \n (subs['cue'] == cue), [cue_onset_col, 'phase_2', 'weight']].values.tolist()\n \n with open(os.path.join(output_dir, 'ev_cue_%s_%s.txt' % (effector, cue)), 'wb') as f:\n for _list in ev:\n for _string in _list:\n f.write(str(_string) + '\\n')\n f.write('\\n')\n \n # Get rid of localizer block here\n design = design.loc[design['block'] > 0]\n \n # For all decision-making blocks, we model the cue types (spd/acc or left/neu/right), so create EVs for these\n for cue_type in design['cue'].unique():\n \n # Get cue onset time, cue duration, and cue weight\n ev = design.loc[(design['cue'] == cue_type), [cue_onset_col, 'phase_2', 'weight']].values.tolist()\n\n with open(os.path.join(output_dir, 'ev_cue_%s.txt' % cue_type), 'wb') as f:\n for _list in ev:\n for _string in _list:\n f.write(str(_string) + '\\n')\n f.write('\\n')\n\n # We also model the stimuli, separate for type (left/right), but separate for every cue type (spd/acc OR left/neu/right)\n for stim_type in design['correct_answer'].unique():\n if np.isnan(stim_type): # a nan stimtype corresponds to a null trial, so skip these\n continue\n\n for cue_type in design['cue'].unique():\n \n # Get stimulus onset time, stimulus duration, and weight\n ev = design.loc[(design['correct_answer'] == stim_type) &\n (design['cue'] == cue_type), \n [stim_onset_col, 'phase_4', 'weight']].values.tolist()\n\n with open(os.path.join(output_dir, 'ev_stimulus_%d_%s.txt' % (stim_type, cue_type)), 'wb') as f:\n for _list in ev:\n for _string in _list:\n f.write(str(_string) + '\\n')\n f.write('\\n')",
"_____no_output_____"
]
],
[
[
"### Load FSL design text file for pp 1, and create for all other pps\nBefore running this, the .fsf-design files for pp1 (each block) should be created manually!",
"_____no_output_____"
]
],
[
[
"for block_name in ['all_blocks', '_type_localizer', '_type_cognitive_hand', '_type_cognitive_eye', '_type_limbic_eye', '*_type_limbic_hand']:\n # Get .fsf-file from pp001\n pp_001_fn = glob(os.path.join('pp_001', '*' + block_name, 'design.fsf'))[0]\n pp_001_block_name = pp_001_fn.split('/')[1]\n \n with open(pp_001_fn, 'rb') as f:\n fsf_templ = f.readlines()\n\n for pp in range(participant_range[0], participant_range[1]):\n fsf_thispp = copy.copy(fsf_templ)\n \n # Get path to save the design.fsf file for this pp\n this_pp_fn = os.path.join(glob(os.path.join('pp_' + str(pp).zfill(3), '*' + block_name))[0], 'design.fsf')\n this_pp_block_name = this_pp_fn.split('/')[1]\n \n for i, line in enumerate(fsf_thispp):\n if not block_name == 'all_blocks':\n fsf_thispp[i] = re.sub(pp_001_block_name,\n this_pp_block_name, line)\n fsf_thispp[i] = re.sub('pp_001', 'pp_' + str(pp).zfill(3), fsf_thispp[i])\n\n # Find fn for current pp\n with open(this_pp_fn, 'wb') as f:\n f.writelines(fsf_thispp)",
"_____no_output_____"
]
],
[
[
"## Loop over subject and block directories, calling command line feat every time\n",
"_____no_output_____"
]
],
[
[
"\nwd = os.getcwd()\nfor sub in range(participant_range[0], participant_range[1]):\n os.chdir(wd)\n sub_dir = 'pp_' + str(sub).zfill(3)\n block_dirs = [f for f in os.listdir(sub_dir) if os.path.isdir(os.path.join(sub_dir, f))]\n block_dirs = [f for f in block_dirs if not '.feat' in f]\n \n for block_dir in block_dirs:\n design_dir = os.path.join(wd, sub_dir, block_dir)\n os.chdir(design_dir)\n \n os.system('feat design.fsf')\n\nos.chdir(wd)",
"_____no_output_____"
]
],
[
[
"## The following is old, do not run",
"_____no_output_____"
],
[
"design creation without optimizing:",
"_____no_output_____"
]
],
[
[
"n_trials_per_localizer_block = 8\nn_localizer_blocks = 6\nTR = 3\n\nos.chdir('/Users/steven/Sync/PhDprojects/subcortex/flashtask/designs')\n\nn_trials_limbic = 84\nn_trials_cognitive = 72\nn_null_trials_limbic = 8\nn_null_trials_cognitive = 7\nn_participants = 100\n\nfor pp in range(0, n_participants):\n pp_str = str(pp+1).zfill(3)\n block_order_this_pp = block_order[pp % len(block_order)]\n \n # Empty DataFrame\n design_this_pp = pd.DataFrame()\n \n # Get localizer block\n if block_order_this_pp[0] == 'X':\n localizer_order = ['hand', 'eye']\n else:\n localizer_order = ['eye', 'hand']\n\n for localizer_block in range(int(n_localizer_blocks/2)):\n block_data = pd.DataFrame()\n for localizer_block in range(int(n_localizer_blocks/2)):\n loc_block = create_localizer_block_single_effector(n_trials=n_trials_per_localizer_block, \n response_modality=localizer_order[0],\n block_number=0,\n pseudorandomize=True, TR=TR)\n block_data = block_data.append(loc_block)\n loc_block = create_localizer_block_single_effector(n_trials=n_trials_per_localizer_block, \n response_modality=localizer_order[1],\n block_number=0,\n pseudorandomize=True, TR=TR)\n block_data = block_data.append(loc_block)\n design_this_pp = design_this_pp.append(block_data)\n\n # Get blocks\n for block_number, block_char in enumerate(block_order_this_pp):\n if block_char in ['X', 'Y']:\n continue\n \n if block_char == 'A':\n block_data = create_cognitive_block(n_trials=n_trials_cognitive, \n block_number=block_number-1, \n response_modality='hand',\n n_null_trials=n_null_trials_cognitive, \n TR=TR)\n elif block_char == 'B':\n block_data = create_cognitive_block(n_trials=n_trials_cognitive, \n block_number=block_number-1, \n response_modality='eye',\n n_null_trials=n_null_trials_cognitive,\n TR=TR)\n elif block_char == 'C':\n block_data = create_limbic_block(n_trials=n_trials_limbic, \n block_number=block_number-1, \n response_modality='hand',\n n_null_trials=n_null_trials_limbic,\n TR=TR)\n elif block_char == 'D':\n block_data = create_limbic_block(n_trials=n_trials_limbic, \n block_number=block_number-1, \n response_modality='eye',\n n_null_trials=n_null_trials_limbic,\n TR=TR)\n \n design_this_pp = design_this_pp.append(block_data)\n\n # Set indices\n design_this_pp.index.name = 'block_trial_ID'\n design_this_pp.reset_index(inplace=True)\n design_this_pp.index.name = 'trial_ID'\n \n # Add trial start times (relative to start of experiment)\n design_this_pp['trial_start_time'] = design_this_pp['trial_duration'].shift(1).cumsum()\n design_this_pp.loc[0, 'trial_start_time'] = 0\n\n # Add cue onset times (relative to start of experiment)\n design_this_pp['cue_onset_time'] = design_this_pp['trial_start_time'] + \\\n design_this_pp['phase_1']\n\n # Add stimulus onset times (relative to start of experiment)\n design_this_pp['stimulus_onset_time'] = design_this_pp['trial_start_time'] + \\\n design_this_pp['phase_1'] + \\\n design_this_pp['phase_2'] + \\\n design_this_pp['phase_3']\n \n # Re-order column order for nicety\n design_this_pp = design_this_pp[['block_trial_ID', 'block', 'block_type', 'null_trial', 'correct_answer', 'cue', 'response_modality', 'trial_type', \n 'phase_0', 'phase_1', 'phase_2', 'phase_3', 'phase_4', 'phase_5', 'phase_6', 'phase_7', 'trial_duration', \n 'trial_start_time', 'cue_onset_time', 'stimulus_onset_time',\n 'trial_start_time_block', 'cue_onset_time_block', 'stimulus_onset_time_block']]\n \n # Save full data\n if not os.path.exists(os.path.join('pp_%s' % pp_str, 'all_blocks')):\n os.makedirs(os.path.join('pp_%s' % pp_str, 'all_blocks'))\n design_this_pp.to_csv(os.path.join('pp_%s' % pp_str, 'all_blocks', 'trials.csv'), index=True)\n \n # Save individual blocks\n for block_num, block_type in zip(design_this_pp['block'].unique(), design_this_pp['block_type'].unique()):\n block = design_this_pp.loc[design_this_pp['block'] == block_num]\n \n if not os.path.exists(os.path.join('pp_%s' % pp_str, 'block_%d_type_%s' % (block_num, block_type))):\n os.makedirs(os.path.join('pp_%s' % pp_str, 'block_%d_type_%s' % (block_num, block_type)))\n \n block.to_csv(os.path.join('pp_%s' % pp_str, 'block_%d_type_%s' % (block_num, block_type), 'trials.csv'), index=True)",
"_____no_output_____"
],
[
"def create_localizer_block_single_effector_type2(n_trials, response_modality='eye', \n block_number=None, pseudorandomize=True, \n add_timing=True, null_trials=0, TR=2):\n \"\"\"\n This is NOT used\n \"\"\"\n # Only two trial types here: 'left' is correct, or 'right' is correct\n trial_types = np.hstack((np.repeat([0, 1], repeats=n_trials / 4), # Pro-saccadic cue, left/right corr\n np.repeat([2, 3], repeats=n_trials / 4))) # Anti-saccadic cue, left/right corr\n \n # Initialize arrays\n cue_by_trial = np.zeros(n_trials, dtype='<U10')\n correct_answers = np.zeros(n_trials, dtype=np.int8)\n\n # Define the cues for every trial\n cue_by_trial[(trial_types == 0)] = 'pro_LEFT'\n cue_by_trial[(trial_types == 1)] = 'pro_RIGHT'\n cue_by_trial[(trial_types == 2)] = 'anti_LEFT'\n cue_by_trial[(trial_types == 3)] = 'anti_RIGHT'\n\n # Define the responses ('correct answers')/directions for every trial\n correct_answers[(trial_types == 0) | (trial_types == 2)] = 0 # 0 = respond LEFT\n correct_answers[(trial_types == 1) | (trial_types == 3)] = 1 # 1 = respond RIGHT\n \n # Create dataframe for easier handling\n trial_data = pd.DataFrame({'correct_answer': correct_answers,\n 'cue': cue_by_trial,\n 'trial_type': trial_types})\n \n # Should we pseudorandomize?\n if pseudorandomize:\n trial_data = Pseudorandomizer(trial_data, max_identical_iters={'correct_answer': 3,\n 'cue': 3}).run()\n \n trial_data['null_trial'] = False\n if null_trials > 0:\n trial_data = add_pseudorandom_null_trials(trial_data, n_null_trials=null_trials)\n \n # Add block number for completeness\n if block_number is not None:\n trial_data['block'] = block_number\n trial_data['block_type'] = 'localizer'\n\n # Usually, we also want to add the duration of all the 'trial phases'\n if add_timing:\n # Set phase_3 and phase_0 to 0 (no post-cue fixcross, no feedback)\n trial_data = get_localizer_timing(trial_data, TR=TR)\n# trial_data['response_duration'] = 1.5\n \n trial_data['response_modality'] = response_modality.lower()\n \n return trial_data",
"_____no_output_____"
]
]
]
| [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"raw"
]
| [
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"raw",
"raw"
]
]
|
cb5fc4245a7ba8609eaed4d13d43632358833274 | 1,385 | ipynb | Jupyter Notebook | util/yoyo.ipynb | awsomesawce/my-python-scripts | f9a1d1b0956135e720467bdeb6e5f0e669630112 | [
"BSD-2-Clause"
]
| null | null | null | util/yoyo.ipynb | awsomesawce/my-python-scripts | f9a1d1b0956135e720467bdeb6e5f0e669630112 | [
"BSD-2-Clause"
]
| null | null | null | util/yoyo.ipynb | awsomesawce/my-python-scripts | f9a1d1b0956135e720467bdeb6e5f0e669630112 | [
"BSD-2-Clause"
]
| null | null | null | 20.671642 | 125 | 0.532852 | [
[
[
"import json, os, pathlib, site, sys, sysconfig, platform\n# Debug-style modules\nimport inspect, reprlib",
"_____no_output_____"
],
[
"\"\"\"Data in python\"\"\"\nimport pyrsistent\n\nprint(pyrsistent)",
"<module 'pyrsistent' from 'C:\\\\Users\\\\Carl\\\\miniconda3\\\\lib\\\\site-packages\\\\pyrsistent\\\\__init__.py'>\n"
]
]
]
| [
"code"
]
| [
[
"code",
"code"
]
]
|
cb5fecdf1a427946f5c626f59a172ef69790db96 | 27,848 | ipynb | Jupyter Notebook | notebooks/netcdf_pytorch_dataset.ipynb | vnshanmukh/nowcasting_dataset | 168305ba62abb035c4dbb2cf2089722b952e7311 | [
"MIT"
]
| 15 | 2021-07-24T09:54:13.000Z | 2022-02-01T10:14:28.000Z | notebooks/netcdf_pytorch_dataset.ipynb | vnshanmukh/nowcasting_dataset | 168305ba62abb035c4dbb2cf2089722b952e7311 | [
"MIT"
]
| 455 | 2021-06-11T10:37:49.000Z | 2022-03-24T14:51:47.000Z | notebooks/netcdf_pytorch_dataset.ipynb | vnshanmukh/nowcasting_dataset | 168305ba62abb035c4dbb2cf2089722b952e7311 | [
"MIT"
]
| 10 | 2021-08-09T16:17:57.000Z | 2022-03-23T00:19:17.000Z | 41.317507 | 231 | 0.541619 | [
[
[
"from pathlib import Path\nimport pandas as pd\nimport numpy as np\nimport xarray as xr\nimport gcsfs\nfrom typing import List\nimport io\nimport hashlib\nimport os\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\n\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nimport pytorch_lightning as pl\n\n\nimport nowcasting_dataset.time as nd_time\nfrom nowcasting_dataset.dataset import worker_init_fn, NetCDFDataset\nfrom nowcasting_dataset.geospatial import osgb_to_lat_lon\n\nimport tilemapbase\n\nfrom neptune.new.integrations.pytorch_lightning import NeptuneLogger\nfrom neptune.new.types import File\n\nimport logging\nlogging.basicConfig()\nlogger = logging.getLogger('nowcasting_dataset')\nlogger.setLevel(logging.DEBUG)",
"_____no_output_____"
],
[
"%%time\ntrain_dataset = NetCDFDataset(12_500, 'gs://solar-pv-nowcasting-data/prepared_ML_training_data/v2/train/', '/home/jack/temp/train')\n#validation_dataset = NetCDFDataset(1_000, 'gs://solar-pv-nowcasting-data/prepared_ML_training_data/v2/validation/', '/home/jack/temp/validation')",
"CPU times: user 5 µs, sys: 1e+03 ns, total: 6 µs\nWall time: 8.82 µs\n"
],
[
"def get_batch():\n \"\"\"Useful for testing.\"\"\"\n train_dataset.per_worker_init(0)\n batch = train_dataset[1]\n return batch",
"_____no_output_____"
],
[
"train_dataloader = torch.utils.data.DataLoader(\n train_dataset,\n pin_memory=True,\n num_workers=24,\n prefetch_factor=8,\n worker_init_fn=worker_init_fn,\n persistent_workers=True,\n \n # Disable automatic batching because dataset\n # returns complete batches.\n batch_size=None,\n)",
"_____no_output_____"
]
],
[
[
"## Define simple ML model",
"_____no_output_____"
]
],
[
[
"params = dict(\n batch_size=32,\n history_len=6, #: Number of timesteps of history, not including t0.\n forecast_len=12, #: Number of timesteps of forecast.\n image_size_pixels=32,\n nwp_channels=('t', 'dswrf', 'prate', 'r', 'sde', 'si10', 'vis', 'lcc', 'mcc', 'hcc'),\n sat_channels=(\n 'HRV', 'IR_016', 'IR_039', 'IR_087', 'IR_097', 'IR_108', 'IR_120',\n 'IR_134', 'VIS006', 'VIS008', 'WV_062', 'WV_073')\n)",
"_____no_output_____"
],
[
"tilemapbase.init(create=True)",
"_____no_output_____"
],
[
"def plot_example(batch, model_output, example_i: int=0, border: int=0):\n fig = plt.figure(figsize=(20, 20))\n ncols=4\n nrows=2\n \n # Satellite data\n extent = (\n float(batch['sat_x_coords'][example_i, 0].cpu().numpy()), \n float(batch['sat_x_coords'][example_i, -1].cpu().numpy()), \n float(batch['sat_y_coords'][example_i, -1].cpu().numpy()), \n float(batch['sat_y_coords'][example_i, 0].cpu().numpy())) # left, right, bottom, top\n \n def _format_ax(ax):\n ax.scatter(\n batch['x_meters_center'][example_i].cpu(), \n batch['y_meters_center'][example_i].cpu(), \n s=500, color='white', marker='x')\n\n ax = fig.add_subplot(nrows, ncols, 1) #, projection=ccrs.OSGB(approx=False))\n sat_data = batch['sat_data'][example_i, :, :, :, 0].cpu().numpy()\n sat_min = np.min(sat_data)\n sat_max = np.max(sat_data)\n ax.imshow(sat_data[0], extent=extent, interpolation='none', vmin=sat_min, vmax=sat_max)\n ax.set_title('t = -{}'.format(params['history_len']))\n _format_ax(ax)\n\n ax = fig.add_subplot(nrows, ncols, 2)\n ax.imshow(sat_data[params['history_len']+1], extent=extent, interpolation='none', vmin=sat_min, vmax=sat_max)\n ax.set_title('t = 0')\n _format_ax(ax)\n \n ax = fig.add_subplot(nrows, ncols, 3)\n ax.imshow(sat_data[-1], extent=extent, interpolation='none', vmin=sat_min, vmax=sat_max)\n ax.set_title('t = {}'.format(params['forecast_len']))\n _format_ax(ax)\n \n ax = fig.add_subplot(nrows, ncols, 4)\n lat_lon_bottom_left = osgb_to_lat_lon(extent[0], extent[2])\n lat_lon_top_right = osgb_to_lat_lon(extent[1], extent[3])\n tiles = tilemapbase.tiles.build_OSM()\n lat_lon_extent = tilemapbase.Extent.from_lonlat(\n longitude_min=lat_lon_bottom_left[1],\n longitude_max=lat_lon_top_right[1],\n latitude_min=lat_lon_bottom_left[0],\n latitude_max=lat_lon_top_right[0])\n plotter = tilemapbase.Plotter(lat_lon_extent, tile_provider=tiles, zoom=6)\n plotter.plot(ax, tiles)\n\n ############## TIMESERIES ##################\n # NWP\n ax = fig.add_subplot(nrows, ncols, 5)\n nwp_dt_index = pd.to_datetime(batch['nwp_target_time'][example_i].cpu().numpy(), unit='s')\n pd.DataFrame(\n batch['nwp'][example_i, :, :, 0, 0].T.cpu().numpy(), \n index=nwp_dt_index,\n columns=params['nwp_channels']).plot(ax=ax)\n ax.set_title('NWP')\n\n # datetime features\n ax = fig.add_subplot(nrows, ncols, 6)\n ax.set_title('datetime features')\n datetime_feature_cols = ['hour_of_day_sin', 'hour_of_day_cos', 'day_of_year_sin', 'day_of_year_cos']\n datetime_features_df = pd.DataFrame(index=nwp_dt_index, columns=datetime_feature_cols)\n for key in datetime_feature_cols:\n datetime_features_df[key] = batch[key][example_i].cpu().numpy()\n datetime_features_df.plot(ax=ax)\n ax.legend()\n ax.set_xlabel(nwp_dt_index[0].date())\n\n # PV yield\n ax = fig.add_subplot(nrows, ncols, 7)\n ax.set_title('PV yield for PV ID {:,d}'.format(batch['pv_system_id'][example_i].cpu()))\n pv_actual = pd.Series(\n batch['pv_yield'][example_i].cpu().numpy(),\n index=nwp_dt_index,\n name='actual')\n pv_pred = pd.Series(\n model_output[example_i].detach().cpu().numpy(),\n index=nwp_dt_index[params['history_len']+1:],\n name='prediction')\n pd.concat([pv_actual, pv_pred], axis='columns').plot(ax=ax)\n ax.legend()\n\n # fig.tight_layout()\n \n return fig",
"_____no_output_____"
],
[
"SAT_X_MEAN = np.float32(309000)\nSAT_X_STD = np.float32(316387.42073603)\nSAT_Y_MEAN = np.float32(519000)\nSAT_Y_STD = np.float32(406454.17945938)",
"_____no_output_____"
],
[
"TOTAL_SEQ_LEN = params['history_len'] + params['forecast_len'] + 1\nCHANNELS = 32\nN_CHANNELS_LAST_CONV = 4\nKERNEL = 3\nEMBEDDING_DIM = 16\nNWP_SIZE = 10 * 2 * 2 # channels x width x height\nN_DATETIME_FEATURES = 4\nCNN_OUTPUT_SIZE = N_CHANNELS_LAST_CONV * ((params['image_size_pixels'] - 6) ** 2)\nFC_OUTPUT_SIZE = 8\nRNN_HIDDEN_SIZE = 16\n\nclass LitAutoEncoder(pl.LightningModule):\n def __init__(\n self,\n history_len = params['history_len'],\n forecast_len = params['forecast_len'],\n ):\n super().__init__()\n self.history_len = history_len\n self.forecast_len = forecast_len\n\n self.sat_conv1 = nn.Conv2d(in_channels=len(params['sat_channels'])+5, out_channels=CHANNELS, kernel_size=KERNEL)#, groups=history_len+1)\n self.sat_conv2 = nn.Conv2d(in_channels=CHANNELS, out_channels=CHANNELS, kernel_size=KERNEL) #, groups=CHANNELS//2)\n self.sat_conv3 = nn.Conv2d(in_channels=CHANNELS, out_channels=N_CHANNELS_LAST_CONV, kernel_size=KERNEL) #, groups=CHANNELS)\n\n #self.maxpool = nn.MaxPool2d(kernel_size=KERNEL)\n\n self.fc1 = nn.Linear(\n in_features=CNN_OUTPUT_SIZE, \n out_features=256)\n\n self.fc2 = nn.Linear(\n in_features=256 + EMBEDDING_DIM,\n out_features=128)\n #self.fc2 = nn.Linear(in_features=EMBEDDING_DIM + N_DATETIME_FEATURES, out_features=128)\n self.fc3 = nn.Linear(in_features=128, out_features=64)\n self.fc4 = nn.Linear(in_features=64, out_features=32)\n self.fc5 = nn.Linear(in_features=32, out_features=FC_OUTPUT_SIZE)\n\n if EMBEDDING_DIM:\n self.pv_system_id_embedding = nn.Embedding(\n num_embeddings=940,\n embedding_dim=EMBEDDING_DIM)\n \n \n self.encoder_rnn = nn.GRU(\n input_size=FC_OUTPUT_SIZE + N_DATETIME_FEATURES + 1 + NWP_SIZE, # plus 1 for history\n hidden_size=RNN_HIDDEN_SIZE,\n num_layers=2,\n batch_first=True)\n self.decoder_rnn = nn.GRU(\n input_size=FC_OUTPUT_SIZE + N_DATETIME_FEATURES + NWP_SIZE,\n hidden_size=RNN_HIDDEN_SIZE,\n num_layers=2,\n batch_first=True)\n \n self.decoder_fc1 = nn.Linear(\n in_features=RNN_HIDDEN_SIZE,\n out_features=8)\n self.decoder_fc2 = nn.Linear(\n in_features=8,\n out_features=1)\n \n ### EXTRA CHANNELS\n # Center marker\n new_batch_size = params['batch_size'] * TOTAL_SEQ_LEN\n self.center_marker = torch.zeros(\n (\n new_batch_size, \n 1, \n params['image_size_pixels'], \n params['image_size_pixels']\n ),\n dtype=torch.float32, device=self.device)\n half_width = params['image_size_pixels'] // 2\n self.center_marker[..., half_width-2:half_width+2, half_width-2:half_width+2] = 1\n \n # pixel x & y\n pixel_range = (torch.arange(params['image_size_pixels'], device=self.device) - 64) / 37\n pixel_range = pixel_range.unsqueeze(0).unsqueeze(0)\n self.pixel_x = pixel_range.unsqueeze(-2).expand(new_batch_size, 1, params['image_size_pixels'], -1)\n self.pixel_y = pixel_range.unsqueeze(-1).expand(new_batch_size, 1, -1, params['image_size_pixels'])\n \n\n def forward(self, x):\n # ******************* Satellite imagery *************************\n # Shape: batch_size, seq_length, width, height, channel\n # TODO: Use optical flow, not actual sat images of the future!\n sat_data = x['sat_data']\n batch_size, seq_len, width, height, n_chans = sat_data.shape\n\n # Stack timesteps as extra examples\n new_batch_size = batch_size * seq_len\n # 0 1 2 3\n sat_data = sat_data.reshape(new_batch_size, width, height, n_chans)\n\n # Conv2d expects channels to be the 2nd dim!\n sat_data = sat_data.permute(0, 3, 1, 2)\n # Now shape: new_batch_size, n_chans, width, height\n\n ### EXTRA CHANNELS\n # geo-spatial x\n x_coords = x['sat_x_coords'] # shape: batch_size, image_size_pixels\n x_coords = x_coords - SAT_X_MEAN\n x_coords = x_coords / SAT_X_STD\n x_coords = x_coords.unsqueeze(1).expand(-1, width, -1).unsqueeze(1).repeat_interleave(repeats=TOTAL_SEQ_LEN, dim=0)\n \n # geo-spatial y\n y_coords = x['sat_y_coords'] # shape: batch_size, image_size_pixels\n y_coords = y_coords - SAT_Y_MEAN\n y_coords = y_coords / SAT_Y_STD\n y_coords = y_coords.unsqueeze(-1).expand(-1, -1, height).unsqueeze(1).repeat_interleave(repeats=TOTAL_SEQ_LEN, dim=0)\n \n # Concat\n if sat_data.device != self.center_marker.device:\n self.center_marker = self.center_marker.to(sat_data.device)\n self.pixel_x = self.pixel_x.to(sat_data.device)\n self.pixel_y = self.pixel_y.to(sat_data.device)\n \n sat_data = torch.cat((sat_data, self.center_marker, x_coords, y_coords, self.pixel_x, self.pixel_y), dim=1)\n \n del x_coords, y_coords\n\n \n # Pass data through the network :)\n out = F.relu(self.sat_conv1(sat_data))\n #out = self.maxpool(out)\n out = F.relu(self.sat_conv2(out))\n #out = self.maxpool(out)\n out = F.relu(self.sat_conv3(out))\n\n out = out.reshape(new_batch_size, CNN_OUTPUT_SIZE)\n out = F.relu(self.fc1(out))\n \n # ********************** Embedding of PV system ID *********************\n if EMBEDDING_DIM:\n pv_embedding = self.pv_system_id_embedding(x['pv_system_row_number'].repeat_interleave(TOTAL_SEQ_LEN))\n out = torch.cat(\n (\n out,\n pv_embedding\n ), \n dim=1)\n\n # Fully connected layers.\n out = F.relu(self.fc2(out))\n out = F.relu(self.fc3(out))\n out = F.relu(self.fc4(out))\n out = F.relu(self.fc5(out))\n\n # ******************* PREP DATA FOR RNN *****************************************\n out = out.reshape(batch_size, TOTAL_SEQ_LEN, FC_OUTPUT_SIZE) # TODO: Double-check this does what we expect!\n \n # The RNN encoder gets recent history: satellite, NWP, datetime features, and recent PV history.\n # The RNN decoder gets what we know about the future: satellite, NWP, and datetime features.\n\n # *********************** NWP Data **************************************\n nwp_data = x['nwp'].float() # Shape: batch_size, channel, seq_length, width, height\n nwp_data = nwp_data.permute(0, 2, 1, 3, 4) # RNN expects seq_len to be dim 1.\n batch_size, nwp_seq_len, n_nwp_chans, nwp_width, nwp_height = nwp_data.shape\n nwp_data = nwp_data.reshape(batch_size, nwp_seq_len, n_nwp_chans * nwp_width * nwp_height)\n\n # Concat\n rnn_input = torch.cat(\n (\n out,\n nwp_data,\n x['hour_of_day_sin'].unsqueeze(-1),\n x['hour_of_day_cos'].unsqueeze(-1),\n x['day_of_year_sin'].unsqueeze(-1),\n x['day_of_year_cos'].unsqueeze(-1),\n ),\n dim=2)\n \n pv_yield_history = x['pv_yield'][:, :self.history_len+1].unsqueeze(-1)\n encoder_input = torch.cat(\n (\n rnn_input[:, :self.history_len+1],\n pv_yield_history\n ),\n dim=2)\n \n encoder_output, encoder_hidden = self.encoder_rnn(encoder_input)\n decoder_output, _ = self.decoder_rnn(rnn_input[:, -self.forecast_len:], encoder_hidden)\n # decoder_output is shape batch_size, seq_len, rnn_hidden_size\n \n decoder_output = F.relu(self.decoder_fc1(decoder_output))\n decoder_output = self.decoder_fc2(decoder_output)\n \n return decoder_output.squeeze()\n \n def _training_or_validation_step(self, batch, is_train_step):\n y_hat = self(batch)\n y = batch['pv_yield'][:, -self.forecast_len:]\n #y = torch.rand((32, 1), device=self.device)\n mse_loss = F.mse_loss(y_hat, y)\n nmae_loss = (y_hat - y).abs().mean()\n # TODO: Compute correlation coef using np.corrcoef(tensor with shape (2, num_timesteps))[0, 1]\n # on each example, and taking the mean across the batch?\n tag = \"Train\" if is_train_step else \"Validation\"\n self.log_dict({f'MSE/{tag}': mse_loss}, on_step=is_train_step, on_epoch=True)\n self.log_dict({f'NMAE/{tag}': nmae_loss}, on_step=is_train_step, on_epoch=True)\n \n return nmae_loss\n\n def training_step(self, batch, batch_idx):\n return self._training_or_validation_step(batch, is_train_step=True)\n \n def validation_step(self, batch, batch_idx):\n if batch_idx == 0:\n # Plot example\n model_output = self(batch)\n fig = plot_example(batch, model_output)\n self.logger.experiment['validation/plot'].log(File.as_image(fig))\n \n return self._training_or_validation_step(batch, is_train_step=False)\n\n def configure_optimizers(self):\n optimizer = torch.optim.Adam(self.parameters(), lr=0.001)\n return optimizer",
"_____no_output_____"
],
[
"model = LitAutoEncoder()",
"_____no_output_____"
],
[
"logger = NeptuneLogger(project='OpenClimateFix/predict-pv-yield')\nlogger.log_hyperparams(params)\nprint('logger.version =', logger.version)",
"https://app.neptune.ai/OpenClimateFix/predict-pv-yield/e/PRED-73\nRemember to stop your run once you’ve finished logging your metadata (https://docs.neptune.ai/api-reference/run#stop). It will be stopped automatically only when the notebook kernel/interactive console is terminated.\nlogger.version = PRED-73\n"
],
[
"trainer = pl.Trainer(gpus=1, max_epochs=10_000, logger=logger)",
"GPU available: True, used: True\nTPU available: False, using: 0 TPU cores\n"
],
[
"trainer.fit(model, train_dataloader)",
"/home/jack/miniconda3/envs/nowcasting_dataset/lib/python3.9/site-packages/pytorch_lightning/trainer/configuration_validator.py:101: UserWarning: you defined a validation_step but have no val_dataloader. Skipping val loop\n rank_zero_warn(f'you defined a {step_name} but have no {loader_name}. Skipping {stage} loop')\nLOCAL_RANK: 0 - CUDA_VISIBLE_DEVICES: [0]\n\n | Name | Type | Params\n------------------------------------------------------\n0 | sat_conv1 | Conv2d | 4.9 K \n1 | sat_conv2 | Conv2d | 9.2 K \n2 | sat_conv3 | Conv2d | 1.2 K \n3 | fc1 | Linear | 692 K \n4 | fc2 | Linear | 34.9 K\n5 | fc3 | Linear | 8.3 K \n6 | fc4 | Linear | 2.1 K \n7 | fc5 | Linear | 264 \n8 | pv_system_id_embedding | Embedding | 15.0 K\n9 | encoder_rnn | GRU | 5.0 K \n10 | decoder_rnn | GRU | 5.0 K \n11 | decoder_fc1 | Linear | 136 \n12 | decoder_fc2 | Linear | 9 \n------------------------------------------------------\n778 K Trainable params\n0 Non-trainable params\n778 K Total params\n3.114 Total estimated model params size (MB)\n"
]
]
]
| [
"code",
"markdown",
"code"
]
| [
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
]
|
cb602e8ebeb2c2c3cf6b9ea1c8ccdc67c7ec5403 | 13,067 | ipynb | Jupyter Notebook | pyaims/doc/examples/pyaims_tutorial.ipynb | brainvisa/aims-free | 5852c1164292cadefc97cecace022d14ab362dc4 | [
"CECILL-B"
]
| 4 | 2019-07-09T05:34:10.000Z | 2020-10-16T00:03:15.000Z | pyaims/doc/examples/pyaims_tutorial.ipynb | brainvisa/aims-free | 5852c1164292cadefc97cecace022d14ab362dc4 | [
"CECILL-B"
]
| 72 | 2018-10-31T14:52:50.000Z | 2022-03-04T11:22:51.000Z | pyaims/doc/examples/pyaims_tutorial.ipynb | brainvisa/aims-free | 5852c1164292cadefc97cecace022d14ab362dc4 | [
"CECILL-B"
]
| null | null | null | 59.940367 | 911 | 0.546644 | [
[
[
"empty"
]
]
]
| [
"empty"
]
| [
[
"empty"
]
]
|
cb6038c9a8a5172b5bce35198d518845ba7a1e6f | 619,339 | ipynb | Jupyter Notebook | Final notebooks/202122_Fall_AA_Group17_Exploration_FeatSelection.ipynb | iryna-savchuk/group_work_ml | 6cfd6ae0647b3fe89a6f1dfb93c77ebd99371778 | [
"Unlicense"
]
| null | null | null | Final notebooks/202122_Fall_AA_Group17_Exploration_FeatSelection.ipynb | iryna-savchuk/group_work_ml | 6cfd6ae0647b3fe89a6f1dfb93c77ebd99371778 | [
"Unlicense"
]
| null | null | null | Final notebooks/202122_Fall_AA_Group17_Exploration_FeatSelection.ipynb | iryna-savchuk/group_work_ml | 6cfd6ae0647b3fe89a6f1dfb93c77ebd99371778 | [
"Unlicense"
]
| 3 | 2021-11-02T15:12:26.000Z | 2021-12-10T11:29:05.000Z | 319.411552 | 109,452 | 0.920049 | [
[
[
"<a class=\"anchor\" id=\"2nd-bullet\">\n\n### 1.1. Import the needed libraries\n \n</a>",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# data partition\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import shuffle\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import PowerTransformer\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom math import ceil\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import precision_score\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import precision_recall_curve\nfrom regressors import stats\n#filter methods\n# spearman \n# chi-square\nimport scipy.stats as stats\nfrom scipy.stats import chi2_contingency\n\n#wrapper methods\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.feature_selection import RFE\n\n# embedded methods\nfrom sklearn.linear_model import LassoCV\n\nimport warnings\nwarnings.filterwarnings('ignore')",
"_____no_output_____"
]
],
[
[
"<a class=\"anchor\" id=\"3rd-bullet\">\n\n### Import the dataset\n \n</a>",
"_____no_output_____"
]
],
[
[
"df = pd.read_csv('train.csv')\ndf.set_index('Access_ID', inplace = True)\ndf.head(3)",
"_____no_output_____"
]
],
[
[
"<a class=\"anchor\" id=\"4th-bullet\">\n\n\n## 3. Data Understanding\n\n</a>\n\n",
"_____no_output_____"
],
[
"<a class=\"anchor\" id=\"4th-bullet\">\n\n\n### 3.1 Logical Checks\n\n</a>\n\n",
"_____no_output_____"
]
],
[
[
"#Check the info of the dataset\ndf.info()\n#no missing values",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 9999 entries, 102863333 to 798444008\nData columns (total 16 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Date 9999 non-null object \n 1 AccountMng_Pages 9999 non-null int64 \n 2 AccountMng_Duration 9999 non-null float64\n 3 FAQ_Pages 9999 non-null int64 \n 4 FAQ_Duration 9999 non-null float64\n 5 Product_Pages 9999 non-null int64 \n 6 Product_Duration 9999 non-null float64\n 7 GoogleAnalytics_BounceRate 9999 non-null float64\n 8 GoogleAnalytics_ExitRate 9999 non-null float64\n 9 GoogleAnalytics_PageValue 9999 non-null float64\n 10 OS 9999 non-null object \n 11 Browser 9999 non-null int64 \n 12 Country 9999 non-null object \n 13 Type_of_Traffic 9999 non-null int64 \n 14 Type_of_Visitor 9999 non-null object \n 15 Buy 9999 non-null int64 \ndtypes: float64(6), int64(6), object(4)\nmemory usage: 1.3+ MB\n"
],
[
"#fix data types - will create dummy variables later\ndf.Type_of_Traffic = df.Type_of_Traffic.astype(\"str\")\ndf.Browser = df.Browser.astype(\"str\")\ndf[\"Date\"]=pd.to_datetime(df[\"Date\"])",
"_____no_output_____"
],
[
"# check distribution of target variable\nprint(df[\"Buy\"].value_counts())\nprint(\"Percent of positive labels: \" + str(round(df[\"Buy\"].value_counts()[1]/len(df),2)))",
"0 8447\n1 1552\nName: Buy, dtype: int64\nPercent of positive labels: 0.16\n"
],
[
"#MISSING: checking the page values and duration variables",
"_____no_output_____"
]
],
[
[
"<a class=\"anchor\" id=\"4th-bullet\">\n\n\n### 3.2 Data exploration\n\n</a>\n\n",
"_____no_output_____"
]
],
[
[
"df.describe().T",
"_____no_output_____"
]
],
[
[
"#### Observations:\n- the dataset don't have null values\n- it has outliers in some features - need to explore and solve them\n- it has 9.999 observations and 15 features (9 numerical and 6 categorical)\n- the dependent variable is 'Buy'",
"_____no_output_____"
]
],
[
[
"# split the dataset\nX = df.drop('Buy', axis=1)\ny = df['Buy']\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.25, random_state=5, stratify=y)",
"_____no_output_____"
],
[
"# Define metric and non-metric features\nnon_metric_features = ['Date', 'OS', 'Browser', 'Country', 'Type_of_Traffic', 'Type_of_Visitor']\nmetric_features = X_train.columns.drop(non_metric_features).to_list()",
"_____no_output_____"
],
[
"# All Numeric Variables' Box Plots in one figure\nsns.set()\n\n# Prepare figure. Create individual axes where each box plot will be placed\nfig, axes = plt.subplots(3, ceil(len(metric_features) / 3), figsize=(22, 15))\n\n# Plot data\n# Iterate across axes objects and associate each box plot (hint: use the ax argument):\nfor ax, feat in zip(axes.flatten(), metric_features): # Notice the zip() function and flatten() method\n sns.boxplot(y=X_train[feat], ax=ax)\n #ax.set_title(feat, y=-0.16)\n \n# Layout\n# Add a centered title to the figure:\ntitle = \"Numeric Variables' Box Plots\"\n\nplt.suptitle(title, y=0.91)\n\n# plt.savefig(os.path.join('..', 'figures', 'numeric_variables_boxplots.png'), dpi=200)\nplt.show()",
"_____no_output_____"
],
[
"# All Numeric Variables' Histograms in one figure\nsns.set()\n\n# Prepare figure. Create individual axes where each histogram will be placed\nfig, axes = plt.subplots(3, ceil(len(metric_features) / 3), figsize=(22, 15))\n\n# Plot data\n# Iterate across axes objects and associate each histogram (hint: use the ax.hist() instead of plt.hist()):\nfor ax, feat in zip(axes.flatten(), metric_features): # Notice the zip() function and flatten() method\n ax.hist(X_train[feat], bins=30)\n ax.set_title(feat, y=-0.15)\n \n# Layout\n# Add a centered title to the figure:\ntitle = \"Numeric Variables' Histograms\"\n\nplt.suptitle(title, y=0.91)\n\n# plt.savefig(os.path.join('..', 'figures', 'numeric_variables_histograms.png'), dpi=200)\nplt.show()",
"_____no_output_____"
],
[
"# All Numeric Variables' Box Plots in one figure - with the dependent variable\nsns.set()\n\n# Prepare figure. Create individual axes where each box plot will be placed\nfig, axes = plt.subplots(3, ceil(len(metric_features) / 3), figsize=(22, 15))\n\n# Plot data\n# Iterate across axes objects and associate each box plot (hint: use the ax argument):\nfor ax, feat in zip(axes.flatten(), metric_features): # Notice the zip() function and flatten() method\n sns.boxplot(y=X_train[feat], x=y_train, ax=ax)\n \n# Layout\n# Add a centered title to the figure:\ntitle = \"Numeric Variables' Box Plots\"\n\nplt.suptitle(title, y=0.91)\n\n# plt.savefig(os.path.join('..', 'figures', 'numeric_variables_boxplots.png'), dpi=200)\nplt.show()",
"_____no_output_____"
],
[
"# All Numeric Variables' Histograms in one figure\nsns.set()\n\n# Prepare figure. Create individual axes where each histogram will be placed\nfig, axes = plt.subplots(3, ceil(len(metric_features) / 3), figsize=(22, 15))\n\n# Plot data\n# Iterate across axes objects and associate each histogram (hint: use the ax.hist() instead of plt.hist()):\nfor ax, feat in zip(axes.flatten(), metric_features): # Notice the zip() function and flatten() method\n sns.histplot(data=X_train, x=feat, hue=y_train, ax=ax, bins=30)\n \n# Layout\n# Add a centered title to the figure:\ntitle = \"Numeric Variables' Histograms\"\n\nplt.suptitle(title, y=0.91)\n\n# plt.savefig(os.path.join('..', 'figures', 'numeric_variables_histograms.png'), dpi=200)\nplt.show()",
"_____no_output_____"
]
],
[
[
"Observations:\n- the dataset has outliers in all of the numeric features\n- the data is right skewed in all of the numeric features, there is a lot of zero values in all features except in 'GoogleAnalytics_ExitRate'\n- the distribution of the observations that didn't buy the products is very similar to those that bought the product. This means that it can be difficult to the model to learn the differences of these two groups",
"_____no_output_____"
],
[
"<a class=\"anchor\" id=\"4th-bullet\">\n\n\n### 3.3 Outliers\n\n</a>\n\n",
"_____no_output_____"
]
],
[
[
"#baseline model performance\nX_train_num = X_train[metric_features]\nX_val_num = X_val[metric_features]",
"_____no_output_____"
],
[
"#define model\nmodel1 = LogisticRegression().fit(X_train_num, y_train)\ny_pred_train = model1.predict(X_train_num)\ny_pred_val = model1.predict(X_val_num)\n\n#results\nprint('f1_train:', f1_score(y_train, y_pred_train))\nprint(confusion_matrix(y_val, y_pred_val))\nprint('precision:', precision_score(y_val, y_pred_val))\nprint('f1_val:', f1_score(y_val, y_pred_val))",
"f1_train: 0.4913693901035672\n[[2063 49]\n [ 263 125]]\nprecision: 0.7183908045977011\nf1_val: 0.44483985765124556\n"
],
[
"df_train = pd.concat([X_train, y_train], axis=1)\ndf_train_backup = df_train.copy()",
"_____no_output_____"
],
[
"#function to automatically remove outliers besed on the IQR, not currently in use\ndef outliers(df_train,metric_features):\n for variable in metric_features:\n var_mean = df_train[variable].mean()\n var_std = df_train[variable].std()\n df_train=df_train.loc[df_train[variable] < var_mean + (5 * var_std)]\n df_train=df_train.loc[df_train[variable] > var_mean - (5 * var_std)]\n return df_train\ndf_train = outliers(df_train,metric_features)",
"_____no_output_____"
],
[
"print('Percentage of data kept after removing outliers:', np.round(df_train.shape[0] / df_train_backup.shape[0], 4))",
"Percentage of data kept after removing outliers: 0.9593\n"
],
[
"#testing model performance after removing outliers\nX_train_num = df_train.drop(['Buy'], axis=1)[metric_features]\ny_train = df_train['Buy']",
"_____no_output_____"
],
[
"#define model\nmodel2 = LogisticRegression().fit(X_train_num, y_train)\ny_pred_train = model2.predict(X_train_num)\ny_pred_val = model2.predict(X_val_num)\n\n#results\nprint('f1_train:', f1_score(y_train, y_pred_train))\nprint(confusion_matrix(y_val, y_pred_val))\nprint('precision:', precision_score(y_val, y_pred_val))\nprint('f1_val:', f1_score(y_val, y_pred_val))",
"f1_train: 0.5087719298245614\n[[2038 74]\n [ 248 140]]\nprecision: 0.6542056074766355\nf1_val: 0.46511627906976744\n"
],
[
"#resetting the dataset\ndf_train = df_train_backup.copy()",
"_____no_output_____"
],
[
"# Manually defined tresholds for outliers using boxplots\n\nfilters1 = (\n (df_train['AccountMng_Duration']<=2000)\n &(df_train['AccountMng_Pages']<=20)\n &(df_train['GoogleAnalytics_BounceRate']<=.17)\n &(df_train['FAQ_Duration']<=1500)\n &(df_train['FAQ_Pages']<=13)\n &(df_train['Product_Pages']<=500)\n &(df_train['Product_Duration']<=25000)\n &(df_train['GoogleAnalytics_PageValue']<=300)\n)\n\nfilters2 = (\n (df_train['AccountMng_Duration']<=2000)\n &\n (df_train['FAQ_Duration']<=2000)\n &\n (df_train['Product_Pages']<=650)\n &\n (df_train['Product_Duration']<=50000)\n &\n (df_train['GoogleAnalytics_PageValue']<=350)\n)\n\ndf_train = df_train[filters1]\n\nprint('Percentage of data kept after removing outliers:', np.round(df_train.shape[0] / df_train_backup.shape[0], 4))",
"Percentage of data kept after removing outliers: 0.9365\n"
],
[
"#testing model performance after removing outliers using manual thresholds\nX_train_num = df_train.drop(['Buy'], axis=1)[metric_features]\ny_train = df_train['Buy']",
"_____no_output_____"
],
[
"#define model\nmodel3 = LogisticRegression().fit(X_train_num, y_train)\ny_pred_train = model3.predict(X_train_num)\ny_pred_val = model3.predict(X_val_num)\n\n#results\nprint('f1_train:', f1_score(y_train, y_pred_train))\nprint(confusion_matrix(y_val, y_pred_val))\nprint('precision:', precision_score(y_val, y_pred_val))\nprint('f1_val:', f1_score(y_val, y_pred_val))",
"f1_train: 0.49624060150375937\n[[2059 53]\n [ 262 126]]\nprecision: 0.7039106145251397\nf1_val: 0.4444444444444445\n"
]
],
[
[
"Observations:\n- at this stage, using automated outlier removal was the better option, but this was partially due to the inclusion of all numeric variables, like FAQ_Duration that has many outliers but not a lot of relevency. As we refine our variable selection, manual outlier selection produced a more accurate model. \n- filters2 is the result of finding the best outlier filters after feature selection, which we will use here to keep the results accurate to our report.",
"_____no_output_____"
]
],
[
[
"df_train = df_train_backup.copy()\ndf_train = df_train[filters2]\nprint('Percentage of data kept after removing outliers:', np.round(df_train.shape[0] / df_train_backup.shape[0], 4))",
"Percentage of data kept after removing outliers: 0.9987\n"
]
],
[
[
"<a class=\"anchor\" id=\"4th-bullet\">\n\n\n## 4. Data Preparation\n\n</a>\n\n",
"_____no_output_____"
],
[
"<a class=\"anchor\" id=\"4th-bullet\">\n\n\n### 4.1 Feature Engineering and Transformation\n\n</a>\n\n",
"_____no_output_____"
]
],
[
[
"X_train = df_train.drop(['Buy'], axis=1)\ny_train = df_train['Buy']",
"_____no_output_____"
],
[
"#create dummy variables in train data:\n\n#type of visitor\ndict_visitor = {'Returner': 0, 'New_Access': 1, 'Other': 0}\nX_train['Type_of_Visitor_new'] = X_train['Type_of_Visitor'].map(dict_visitor)\ndict_visitor = {'Returner': 1, 'New_Access': 0, 'Other': 0}\nX_train['Type_of_Visitor_return'] = X_train['Type_of_Visitor'].map(dict_visitor)\n\n#type of traffic\nX_train[\"Type_of_Traffic_high\"]=X_train[\"Type_of_Traffic\"].map(lambda x: 1 if (x in [7,8,15]) else 0)\nX_train[\"Type_of_Traffic_med\"]=X_train[\"Type_of_Traffic\"].map(lambda x: 1 if (x in [10,11,2,5]) else 0)\nX_train = pd.get_dummies(X_train, columns = [\"Type_of_Traffic\"], drop_first=True)\n\n#create month variable from the date information \nX_train[\"Month\"]=X_train[\"Date\"].map(lambda x: x.month)\nX_train[\"Months_high\"]=X_train[\"Month\"].map(lambda x: 1 if x>7 & x<12 else 0)\ntoday = pd.to_datetime(\"2021-01-01\")\nX_train[\"Time_not_visited\"]=X_train[\"Date\"].map(lambda x: (today-x).days)\n\n#OS\nX_train[\"is_apple\"]=X_train[\"OS\"].map(lambda x: 1 if (x in ['iOS', 'MacOSX']) else 0)\nX_train = pd.get_dummies(X_train, columns = ['OS'], drop_first=True)\nX_train.drop('OS_Other', inplace=True, axis=1)\n\n# same for validation data\n#type of visitor\nX_val['Type_of_Visitor_new'] = X_val['Type_of_Visitor'].map(dict_visitor)\nX_val['Type_of_Visitor_return'] = X_val['Type_of_Visitor'].map(dict_visitor)\n\n#type of traffic\nX_val[\"Type_of_Traffic_high\"]=X_val[\"Type_of_Traffic\"].map(lambda x: 1 if (x in [7,8,15]) else 0)\nX_val[\"Type_of_Traffic_med\"]=X_val[\"Type_of_Traffic\"].map(lambda x: 1 if (x in [10,11,2,5]) else 0)\nX_val = pd.get_dummies(X_val, columns = [\"Type_of_Traffic\"], drop_first=True)\n\n#create month variable from the date information \nX_val[\"Month\"]=X_val[\"Date\"].map(lambda x: x.month)\nX_val[\"Months_high\"]=X_val[\"Month\"].map(lambda x: 1 if x>7 & x<12 else 0)\nX_val[\"Time_not_visited\"]=X_val[\"Date\"].map(lambda x: (today-x).days)\n\n#OS\nX_val[\"is_apple\"]=X_val[\"OS\"].map(lambda x: 1 if (x in ['iOS', 'MacOSX']) else 0)\nX_val = pd.get_dummies(X_val, columns = ['OS'], drop_first=True)",
"_____no_output_____"
],
[
"#engineering: time spent per page variables \nX_train[\"Mng\"] = X_train.AccountMng_Duration/X_train.AccountMng_Pages\nX_train[\"FAQ\"] = X_train.FAQ_Duration/X_train.FAQ_Pages\nX_train[\"Product\"] = X_train.Product_Duration/X_train.Product_Pages\nX_train.fillna(0, inplace=True)\n\nX_val[\"Mng\"] = X_val.AccountMng_Duration/X_val.AccountMng_Pages\nX_val[\"FAQ\"] = X_val.FAQ_Duration/X_val.FAQ_Pages\nX_val[\"Product\"] = X_val.Product_Duration/X_val.Product_Pages\nX_val.fillna(0, inplace=True)",
"_____no_output_____"
],
[
"#engineering: Country data \ncountry_gdp_2019 = {\n\"Portugal\": 79, \n\"Spain\": 91, \n\"Brazil\": 100, \n\"France\": 106, \n\"Other\": 100, \n\"Italy\": 96, \n\"United Kingdom\": 104, \n\"Germany\": 120, \n\"Switzerland\": 157\n}\ncountry_digital_2019 = {\n\"Portugal\": 20.71, \n\"Spain\": 32.48, \n\"Brazil\": 62.03, \n\"France\": 52.84, \n\"Other\": 57.80, \n\"Italy\": 39.79, \n\"United Kingdom\": 72.77, \n\"Germany\": \t58.69, \n\"Switzerland\": 67.49\n}",
"_____no_output_____"
],
[
"#engineering: Country data train\nX_train[\"country_gdp_2019\"] = X_train[\"Country\"].apply(lambda x: country_gdp_2019[x])\nX_train[\"country_digital_2019\"] = X_train[\"Country\"].apply(lambda x: country_digital_2019[x])\n#engineering: Country data val\nX_val[\"country_gdp_2019\"] = X_val[\"Country\"].apply(lambda x: country_gdp_2019[x])\nX_val[\"country_digital_2019\"] = X_val[\"Country\"].apply(lambda x: country_digital_2019[x])",
"_____no_output_____"
],
[
"#creating log transormations of numeric variables \n#AccountMng_Pages\nX_train[\"logAccountMng_Pages\"]=X_train[\"AccountMng_Pages\"].map(lambda x : 1 if x<=1 else x)\nX_train[\"logAccountMng_Pages\"]=np.log(X_train[\"logAccountMng_Pages\"])\n#AccountMng_Pages\nX_train[\"logAccountMng_Duration\"]=X_train[\"AccountMng_Duration\"].map(lambda x : 1 if x<=1 else x)\nX_train[\"logAccountMng_Duration\"]=np.log(X_train[\"logAccountMng_Duration\"])\n#logFAQ_Pages\nX_train[\"logFAQ_Pages\"]=X_train[\"FAQ_Pages\"].map(lambda x : 1 if x<=1 else x)\nX_train[\"logFAQ_Pages\"]=np.log(X_train[\"logFAQ_Pages\"])\n\n#AccountMng_Pages\nX_val[\"logAccountMng_Pages\"]=X_val[\"AccountMng_Pages\"].map(lambda x : 1 if x<=1 else x)\nX_val[\"logAccountMng_Pages\"]=np.log(X_val[\"logAccountMng_Pages\"])\n#AccountMng_Pages\nX_val[\"logAccountMng_Duration\"]=X_val[\"AccountMng_Duration\"].map(lambda x : 1 if x<=1 else x)\nX_val[\"logAccountMng_Duration\"]=np.log(X_val[\"logAccountMng_Duration\"])\n#logFAQ_Pages\nX_val[\"logFAQ_Pages\"]=X_val[\"FAQ_Pages\"].map(lambda x : 1 if x<=1 else x)\nX_val[\"logFAQ_Pages\"]=np.log(X_val[\"logFAQ_Pages\"])",
"_____no_output_____"
],
[
"#confirming the same variables were created for both sets\nX_train.shape[1]==X_val.shape[1]",
"_____no_output_____"
],
[
"#MISSING: scaling numeric variables ",
"_____no_output_____"
],
[
"#scaler = MinMaxScaler().fit(X_train_num)\n#X_train_num_scaled = scaler.transform(X_train_num) # this will return an array\n\n# Convert the array to a pandas dataframe\n#X_train_num_scaled = pd.DataFrame(X_train_num_scaled, columns = X_train_num.columns).set_index(X_train.index)\n#X_val_num_scaled = scaler.transform(X_val_num)\n#X_val_num_scaled = pd.DataFrame(X_val_num_scaled, columns = X_val_num.columns).set_index(X_val.index)",
"_____no_output_____"
],
[
"#Power transforming variables \nnon_metric_features = X_train.columns.drop(metric_features).to_list()\n#separate numeric and non-numeric\nX_train_num = X_train[metric_features]\nX_train_cat = X_train[non_metric_features]\n# DO IT for validation\nX_val_num = X_val[metric_features]\nX_val_cat = X_val[non_metric_features]",
"_____no_output_____"
],
[
"#use train to power transform train\npower = PowerTransformer().fit(X_train_num)\nX_train_num_power = power.transform(X_train_num)\nX_train_num_power = pd.DataFrame(X_train_num_power, columns = X_train_num.columns).set_index(X_train_num.index)\n\n#and for validation (using train data)\nX_val_num_power = power.transform(X_val_num)\n# Convert the array to a pandas dataframe\nX_val_num_power = pd.DataFrame(X_val_num_power, columns = X_val_num.columns).set_index(X_val_num.index)\nX_val_num_power.head(3)\n\nX_train_power = pd.concat([X_train_num_power, X_train_cat], axis=1)\nX_val_power = pd.concat([X_val_num_power, X_val_cat], axis=1)",
"_____no_output_____"
]
],
[
[
"<a class=\"anchor\" id=\"4th-bullet\">\n\n\n### 4.2 Feature Selection\n\n</a>\n\n",
"_____no_output_____"
]
],
[
[
"#none of the features are univariate\nX_train_num.var()",
"_____no_output_____"
],
[
"all_train_num = X_train_num.join(y_train)\ndef cor_heatmap(cor):\n plt.figure(figsize=(12,10))\n sns.heatmap(data = cor, annot = True, cmap = plt.cm.Reds, fmt='.1')\n plt.show()\n#build correlation matrix\ncor_spearman = all_train_num.corr(method ='spearman')",
"_____no_output_____"
],
[
"cor_heatmap(cor_spearman)",
"_____no_output_____"
]
],
[
[
"Observations:\n- Features highly correlated (keep only one):\n - __'AccountMng_Pages'__ and __'AccountMng_Duration'__ (Number of pages visited and total amount of time spent by the user - account management related pages)\n - __'FAQ_Pages'__ and __'FAQ_Duration'__ (Number of pages visited and total amount of time spent by the user - FAQ related pages)\n - __'Product_Pages'__ and __'Product_Duration'__ (Number of pages visited and total amount of time spent by the user - Product related pages)\n - __'GoogleAnalytics_BounceRate'__ and __'GoogleAnalytics_ExitRate'__ (Bounce and exit rate, both explains the the exit rate of the pages visited by the user)",
"_____no_output_____"
]
],
[
[
"#lasso part 1: correlated features only\nX_train_num_sub = X_train_num[['AccountMng_Pages', 'AccountMng_Duration', 'FAQ_Pages', 'FAQ_Duration',\n 'Product_Pages', 'Product_Duration', 'GoogleAnalytics_BounceRate',\n 'GoogleAnalytics_ExitRate']]",
"_____no_output_____"
],
[
"lasso1 = LogisticRegression(penalty='l1', solver='liblinear')\nlasso1.fit(X_train_num_sub, y_train)\ncoef = pd.Series(lasso1.coef_[0], index = X_train_num_sub.columns)",
"_____no_output_____"
],
[
"print(\"Lasso picked \" + str(sum(coef != 0)) + \" variables and eliminated the other \" + str(sum(coef == 0)) + \" variables\")",
"Lasso picked 7 variables and eliminated the other 1 variables\n"
],
[
"coef.sort_values()",
"_____no_output_____"
]
],
[
[
"Observations:\n- the number of pages visited variables were more valuable for the first three pairs, and ‘GoogleAnalytics_ExitRate’ was more important than ‘GoogleAnalytics_BounceRate’, so the latter variable was dropped for each of the above pairs.",
"_____no_output_____"
]
],
[
[
"X_train_power.drop([\"GoogleAnalytics_BounceRate\",\"AccountMng_Duration\",\"Product_Duration\",\"FAQ_Duration\"], inplace=True, axis=1)\nX_val_power.drop([\"GoogleAnalytics_BounceRate\",\"AccountMng_Duration\",\"Product_Duration\",\"FAQ_Duration\"], inplace=True, axis=1)",
"_____no_output_____"
],
[
"#chi-squared test for categorical variables \ndef TestIndependence(X,y,var,alpha=0.05): \n dfObserved = pd.crosstab(y,X) \n chi2, p, dof, expected = stats.chi2_contingency(dfObserved.values)\n dfExpected = pd.DataFrame(expected, columns=dfObserved.columns, index = dfObserved.index)\n if p<alpha:\n result=\"{0} is IMPORTANT for Prediction\".format(var)\n else:\n result=\"{0} is NOT an important predictor. (Discard {0} from model)\".format(var)\n print(result)",
"_____no_output_____"
],
[
"df_sub = df_train[['Date', 'OS', 'Browser', 'Country', 'Type_of_Traffic', 'Type_of_Visitor']]",
"_____no_output_____"
],
[
"for var in df_sub:\n TestIndependence(df_train[var],df_train[\"Buy\"], var)",
"Date is IMPORTANT for Prediction\nOS is IMPORTANT for Prediction\nBrowser is IMPORTANT for Prediction\nCountry is NOT an important predictor. (Discard Country from model)\nType_of_Traffic is IMPORTANT for Prediction\nType_of_Visitor is IMPORTANT for Prediction\n"
],
[
"X_train_power.drop(\"Country\",inplace=True,axis=1)\nX_val_power.drop(\"Country\",inplace=True,axis=1)",
"_____no_output_____"
],
[
"X_train_num_power = X_train_power.select_dtypes(include=np.number).set_index(X_train_power.index)\nX_val_num_power = X_val_power.select_dtypes(include=np.number).set_index(X_val_power.index)",
"_____no_output_____"
],
[
"#lasso regression part 2\ndef plot_importance(coef,name):\n imp_coef = coef.sort_values()\n plt.figure(figsize=(8,10))\n imp_coef.plot(kind = \"barh\")\n plt.title(\"Feature importance using \" + name + \" Model\")\n plt.show()",
"_____no_output_____"
],
[
"lasso2 = LogisticRegression(penalty='l1', solver='liblinear', C=.4)\nlasso2.fit(X_train_num_power, y_train)\ncoef = pd.Series(lasso2.coef_[0], index = X_train_num_power.columns)",
"_____no_output_____"
],
[
"print(\"Lasso picked \" + str(sum(coef != 0)) + \" variables and eliminated the other \" + str(sum(coef == 0)) + \" variables\")",
"Lasso picked 26 variables and eliminated the other 15 variables\n"
],
[
"coef.sort_values()",
"_____no_output_____"
],
[
"plot_importance(coef,'Lasso')",
"_____no_output_____"
],
[
"X_train_num_power.drop(['OS_Ubuntu','Type_of_Traffic_5','OS_Fedora',\n 'OS_Chrome OS','Type_of_Traffic_9','Type_of_Traffic_7',\n 'Type_of_Traffic_6','OS_Windows','Type_of_Traffic_3',\n 'Type_of_Traffic_14','Type_of_Traffic_12','Type_of_Traffic_med',\n 'Type_of_Traffic_high','Type_of_Visitor_new','Type_of_Traffic_4'], inplace=True, axis=1)\nX_val_num_power.drop(['OS_Ubuntu','Type_of_Traffic_5','OS_Fedora',\n 'OS_Chrome OS','Type_of_Traffic_9','Type_of_Traffic_7',\n 'Type_of_Traffic_6','OS_Windows','Type_of_Traffic_3',\n 'Type_of_Traffic_14','Type_of_Traffic_12','Type_of_Traffic_med',\n 'Type_of_Traffic_high','Type_of_Visitor_new','Type_of_Traffic_4'], inplace=True, axis=1)",
"_____no_output_____"
],
[
"#RFE loop test with remaining variables\n\n#no of features\nnof_list=np.arange(1,27) \nhigh_score=0\n#Variable to store the optimum features\nnof=0 \nscore_list =[]\nfor n in range(len(nof_list)):\n model = LogisticRegression()\n rfe = RFE(model,nof_list[n])\n X_train_rfe = rfe.fit_transform(X_train_num_power,y_train)\n X_val_rfe = rfe.transform(X_val_num_power)\n model.fit(X_train_rfe,y_train)\n \n score = model.score(X_val_rfe,y_val)\n score_list.append(score)\n \n if(score>high_score):\n high_score = score\n nof = nof_list[n]\nprint(\"Optimum number of features: %d\" %nof)\nprint(\"Score with %d features: %f\" % (nof, high_score))",
"Optimum number of features: 25\nScore with 25 features: 0.894400\n"
],
[
"model = LogisticRegression()\nrfe = RFE(estimator = model, n_features_to_select = 10)\nX_rfe = rfe.fit_transform(X = X_train_num_power, y = y_train)\nselected_features = pd.Series(rfe.support_, index = X_train_num_power.columns)\nselected_features",
"_____no_output_____"
],
[
"model = LogisticRegression()\nrfe = RFE(estimator = model, n_features_to_select = 4)\nX_rfe = rfe.fit_transform(X = X_train_num_power, y = y_train)\nselected_features = pd.Series(rfe.support_, index = X_train_num_power.columns)\nselected_features",
"_____no_output_____"
]
],
[
[
"Observations:\n- Important variables include 'GoogleAnalytics_PageValue', 'Type_of_Visitor_return', 'Type_of_Traffic_11' and 'Type_of_Traffic_8'",
"_____no_output_____"
],
[
"<a class=\"anchor\" id=\"4th-bullet\">\n\n\n### 4.3 Data Balancing\n\n</a>\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"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
]
]
|
cb60472c31f2ccbd9c81e33e29147d6077bc7afc | 44,398 | ipynb | Jupyter Notebook | material/session_5/exercise_5_sol.ipynb | karlbindslev/sds_group29 | 6f5263b08b35f35374b7f01b31a0e90d1cf4d53e | [
"MIT",
"Unlicense"
]
| 24 | 2017-08-07T09:16:51.000Z | 2021-12-06T20:09:52.000Z | material/session_5/exercise_5_sol.ipynb | karlbindslev/sds_group29 | 6f5263b08b35f35374b7f01b31a0e90d1cf4d53e | [
"MIT",
"Unlicense"
]
| 31 | 2018-08-11T09:34:52.000Z | 2018-09-17T09:40:02.000Z | material/session_5/exercise_5_sol.ipynb | karlbindslev/sds_group29 | 6f5263b08b35f35374b7f01b31a0e90d1cf4d53e | [
"MIT",
"Unlicense"
]
| 39 | 2017-08-06T08:49:01.000Z | 2020-10-28T12:52:46.000Z | 170.761538 | 35,160 | 0.889612 | [
[
[
"# Exercise Set 5: Python plotting\n\n*Morning, August 15, 2018\n\nIn this Exercise set we will work with visualizations in python, using two powerful plotting libraries. We will also quickly touch upon using pandas for exploratory plotting. ",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nimport numpy as np \nimport pandas as pd\nimport seaborn as sns \n\n%matplotlib inline \n\niris = sns.load_dataset('iris')\ntitanic = sns.load_dataset('titanic')",
"_____no_output_____"
]
],
[
[
"## Exercise Section 5.1: Exploring the data with plots\n\nWe will work with the two datasets `iris` and `titanic` both of which you should already have loaded. The goal with the plots you produce in this section is to give yourself and your group members an improved understanding of the datasets. \n\n\n> **Ex. 5.1.1:**: Show the first five rows of the titanic dataset. What information is in the dataset? Use a barplot to show the probability of survival for men and women within each passenger class. Can you make a boxplot showing the same information (why/why not?). _Bonus:_ show a boxplot for the fare-prices within each passenger class. \n>\n> Spend five minutes discussing what you can learn about the survival-selection aboard titanic from the figure(s).\n>\n> > _Hint:_ https://seaborn.pydata.org/generated/seaborn.barplot.html, specifically the `hue` option.\n",
"_____no_output_____"
]
],
[
[
"# [Answer to Ex. 5.1.1]\n\n# Will be in assignment 1",
"_____no_output_____"
]
],
[
[
"> **Ex. 5.1.2:** Using the iris flower dataset, draw a scatterplot of sepal length and petal length. Include a second order polynomial fitted to the data. Add a title to the plot and rename the axis labels.\n> _Discuss:_ Is this a meaningful way to display the data? What could we do differently?\n>\n> For a better understanding of the dataset this image might be useful:\n> <img src=\"iris_pic.png\" alt=\"Drawing\" style=\"width: 200px;\"/>\n>\n>> _Hint:_ use the `.regplot` method from seaborn. ",
"_____no_output_____"
]
],
[
[
"# [Answer to Ex. 5.1.2]\n\n# Will be in assignment 1",
"_____no_output_____"
]
],
[
[
"> **Ex. 5.1.3:** Combine the two of the figures you created above into a two-panel figure similar to the one shown here:\n> <img src=\"Example.png\" alt=\"Drawing\" style=\"width: 600px;\"/>\n>\n> Save the figure as a png file on your computer. \n>> _Hint:_ See [this question](https://stackoverflow.com/questions/41384040/subplot-for-seaborn-boxplot) on stackoverflow for inspiration.",
"_____no_output_____"
]
],
[
[
"# [Answer to Ex. 5.1.3]\n\n# Will be in assignment 1",
"_____no_output_____"
]
],
[
[
"> **Ex. 5.1.4:** Use [pairplot with hue](https://seaborn.pydata.org/generated/seaborn.pairplot.html) to create a figure that clearly shows how the different species vary across measurements. Change the color palette and remove the shading from the density plots. _Bonus:_ Try to explain how the `diag_kws` argument works (_hint:_ [read here](https://stackoverflow.com/questions/1769403/understanding-kwargs-in-python))",
"_____no_output_____"
]
],
[
[
"# [Answer to Ex. 5.1.4]\n\n# Will be in assignment 1",
"_____no_output_____"
]
],
[
[
"## Exercise Section 5.2: Explanatory plotting\n\nIn this section we will only work with the titanic dataset. We will create a simple figure from the bottom using the [_grammar of graphics_](http://vita.had.co.nz/papers/layered-grammar.pdf) framework.\n\n<br>\n**_NOTE:_** Because of the way the jupyter notebooks are made, you will have to complete this exercise in a single code cell. \n\n> **Ex. 5.2.1:** Create an empty coordinate system with the *x* axis spanning from 0 to 100 and the *y* axis spanning 0 to 0.05.\n<br><br>\n\n> **Ex. 5.2.2:** Add three KDE-curves to the existing axis. The KDEs should estimate the density of passenger age within each passenger class. Add a figure title and axis labels. Make sure the legend entries makes sense. *If* you have time, change the colors.\n>\n> > _Hint:_ a `for` loop might be useful here.\n<br><br>\n\nThe following exercises highlight some of the advanced uses of matplotlib and seaborn. These techniques allow you to create customized plots with a lot of versatility. These are **_BONUS_** questions.\n> **Ex. 5.2.3:** Add a new subplot that sits within the outer one. Use `[0.55, 0.6, 0.3, 0.2]` the subplots size. At this point your figure should look something like this: \n>\n> <img src=\"exampleq3.png\" alt=\"Drawing\" style=\"width: 400px;\"/>\n>\n>> _Hint:_ This [link](https://jakevdp.github.io/PythonDataScienceHandbook/04.08-multiple-subplots.html) has some tips for plotting subplots.\n\n<br><br>\n> **Ex. 5.2.4:** Move the legend outside the graph window, and add a barplot of survival probabilities split by class to the small subplot.\n>\n>> _Hint:_ [Look here](https://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot) for examples of how to move the legend box around.\n>\n> In the end your figure should look similar to this one:\n> <img src=\"final4.png\" alt=\"Drawing\" style=\"width: 400px;\"/>\n",
"_____no_output_____"
]
],
[
[
"# [Answer to Ex. 5.1.5]\n\n# Question 1\nfig, ax1 = plt.subplots(1,1)\n\nax1.set_xlim(0, 100)\nax1.set_ylim(0, 0.05)\n\n# Question 2\nfor c in set(titanic['class']):\n sub_data = titanic.loc[titanic['class'] == c]\n sns.kdeplot(sub_data.age, ax = ax1, label = c + ' class')\n\nax1.set_xlabel(\"Age\")\nax1.set_ylabel(\"Density\")\nax1.set_title(\"Age densities\")\n\n# BONUS QUESTIONS ----------------------------------------\n# Question 3\nax2 = fig.add_axes([0.55, 0.6, 0.3, 0.2])\nplt.savefig('exampleq3.png')\n\n# Question 4\nbox = ax1.get_position()\nax1.set_position([box.x0, box.y0 + box.height * 0.1,\n box.width, box.height * 0.9])\n\nax1.legend(loc='upper center', bbox_to_anchor=(0.5, -0.2),\n fancybox=True, shadow=True, ncol=5)\n\n\n\n# Question 5\nsns.barplot(x='class', y='survived', data=titanic, ax = ax2)\n\nplt.savefig('final4.png')",
"C:\\Users\\qsd161\\AppData\\Local\\Continuum\\miniconda3\\lib\\site-packages\\statsmodels\\nonparametric\\kde.py:448: RuntimeWarning: invalid value encountered in greater\n X = X[np.logical_and(X > clip[0], X < clip[1])] # won't work for two columns.\nC:\\Users\\qsd161\\AppData\\Local\\Continuum\\miniconda3\\lib\\site-packages\\statsmodels\\nonparametric\\kde.py:448: RuntimeWarning: invalid value encountered in less\n X = X[np.logical_and(X > clip[0], X < clip[1])] # won't work for two columns.\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"
]
]
|
cb6053fc91c291ef97af6b3337938d1e56a16aaf | 10,264 | ipynb | Jupyter Notebook | tutorials/Certification_Trainings/Healthcare/6.Clinical_Context_Spell_Checker.ipynb | ewbolme/spark-nlp-workshop | 421e9b8b3941c825262e46fdf09243996e757992 | [
"Apache-2.0"
]
| 1 | 2020-12-14T06:07:12.000Z | 2020-12-14T06:07:12.000Z | tutorials/Certification_Trainings/Healthcare/6.Clinical_Context_Spell_Checker.ipynb | ewbolme/spark-nlp-workshop | 421e9b8b3941c825262e46fdf09243996e757992 | [
"Apache-2.0"
]
| null | null | null | tutorials/Certification_Trainings/Healthcare/6.Clinical_Context_Spell_Checker.ipynb | ewbolme/spark-nlp-workshop | 421e9b8b3941c825262e46fdf09243996e757992 | [
"Apache-2.0"
]
| null | null | null | 31.581538 | 464 | 0.537217 | [
[
[
"",
"_____no_output_____"
],
[
"[](https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/Certification_Trainings/Healthcare/6.Clinical_Context_Spell_Checker.ipynb)",
"_____no_output_____"
],
[
"<H1> Context Spell Checker - Medical </H1>\n",
"_____no_output_____"
]
],
[
[
"import json\n\nfrom google.colab import files\n\nlicense_keys = files.upload()\n\nwith open(list(license_keys.keys())[0]) as f:\n license_keys = json.load(f)\n\nlicense_keys.keys()",
"_____no_output_____"
],
[
"license_keys['JSL_VERSION']",
"_____no_output_____"
],
[
"import os\n\n# Install java\n! apt-get update -qq\n! apt-get install -y openjdk-8-jdk-headless -qq > /dev/null\n\nos.environ[\"JAVA_HOME\"] = \"/usr/lib/jvm/java-8-openjdk-amd64\"\nos.environ[\"PATH\"] = os.environ[\"JAVA_HOME\"] + \"/bin:\" + os.environ[\"PATH\"]\n! java -version\n\nsecret = license_keys['SECRET']\n\nos.environ['SPARK_NLP_LICENSE'] = license_keys['SPARK_NLP_LICENSE']\nos.environ['AWS_ACCESS_KEY_ID']= license_keys['AWS_ACCESS_KEY_ID']\nos.environ['AWS_SECRET_ACCESS_KEY'] = license_keys['AWS_SECRET_ACCESS_KEY']\njsl_version = license_keys['JSL_VERSION']\nversion = license_keys['PUBLIC_VERSION']\n\n! pip install --ignore-installed -q pyspark==2.4.4\n\n! python -m pip install --upgrade spark-nlp-jsl==$jsl_version --extra-index-url https://pypi.johnsnowlabs.com/$secret\n\n! pip install --ignore-installed -q spark-nlp==$version\n\nimport sparknlp\n\nprint (sparknlp.version())\n\nimport json\nimport os\nfrom pyspark.ml import Pipeline\nfrom pyspark.sql import SparkSession\n\n\nfrom sparknlp.annotator import *\nfrom sparknlp_jsl.annotator import *\nfrom sparknlp.base import *\nimport sparknlp_jsl\n\nspark = sparknlp_jsl.start(secret)",
"_____no_output_____"
],
[
"documentAssembler = DocumentAssembler()\\\n .setInputCol(\"text\")\\\n .setOutputCol(\"document\")\n\ntokenizer = RecursiveTokenizer()\\\n .setInputCols([\"document\"])\\\n .setOutputCol(\"token\")\\\n .setPrefixes([\"\\\"\", \"(\", \"[\", \"\\n\"])\\\n .setSuffixes([\".\", \",\", \"?\", \")\",\"!\", \"'s\"])\n\nspellModel = ContextSpellCheckerModel\\\n .pretrained('spellcheck_clinical', 'en', 'clinical/models')\\\n .setInputCols(\"token\")\\\n .setOutputCol(\"checked\")",
"spellcheck_clinical download started this may take some time.\nApproximate size to download 145 MB\n[OK!]\n"
],
[
"pipeline = Pipeline(\n stages = [\n documentAssembler,\n tokenizer,\n spellModel\n ])\n\nempty_ds = spark.createDataFrame([[\"\"]]).toDF(\"text\")\n\nlp = LightPipeline(pipeline.fit(empty_ds))",
"_____no_output_____"
]
],
[
[
"Ok!, at this point we have our spell checking pipeline as expected. Let's see what we can do with it, see these errors,\n\n_\n__Witth__ the __hell__ of __phisical__ __terapy__ the patient was __imbulated__ and on posoperative, the __impatient__ tolerating a post __curgical__ soft diet._\n\n_With __paint__ __wel__ controlled on __orall__ pain medications, she was discharged __too__ __reihabilitation__ __facilitay__._\n\n_She is to also call the __ofice__ if she has any __ever__ greater than 101, or __leeding__ __form__ the surgical wounds._\n\n_Abdomen is __sort__, nontender, and __nonintended__._\n\n_Patient not showing pain or any __wealth__ problems._\n \n_No __cute__ distress_\n\nCheck that some of the errors are valid English words, only by considering the context the right choice can be made.",
"_____no_output_____"
]
],
[
[
"example = [\"Witth the hell of phisical terapy the patient was imbulated and on posoperative, the impatient tolerating a post curgical soft diet.\",\n \"With paint wel controlled on orall pain medications, she was discharged too reihabilitation facilitay.\",\n \"She is to also call the ofice if she has any ever greater than 101, or leeding form the surgical wounds.\",\n \"Abdomen is sort, nontender, and nonintended.\",\n \"Patient not showing pain or any wealth problems.\",\n \"No cute distress\"\n \n]\n\nfor pairs in lp.annotate(example):\n\n print (list(zip(pairs['token'],pairs['checked'])))",
"[('Witth', 'With'), ('the', 'the'), ('hell', 'cell'), ('of', 'of'), ('phisical', 'physical'), ('terapy', 'therapy'), ('the', 'the'), ('patient', 'patient'), ('was', 'was'), ('imbulated', 'ambulated'), ('and', 'and'), ('on', 'on'), ('posoperative', 'postoperative'), (',', ','), ('the', 'the'), ('impatient', 'patient'), ('tolerating', 'tolerating'), ('a', 'a'), ('post', 'post'), ('curgical', 'surgical'), ('soft', 'soft'), ('diet', 'diet'), ('.', '.')]\n[('With', 'With'), ('paint', 'pain'), ('wel', 'well'), ('controlled', 'controlled'), ('on', 'on'), ('orall', 'oral'), ('pain', 'pain'), ('medications', 'medications'), (',', ','), ('she', 'she'), ('was', 'was'), ('discharged', 'discharged'), ('too', 'to'), ('reihabilitation', 'rehabilitation'), ('facilitay', 'facility'), ('.', '.')]\n[('She', 'She'), ('is', 'is'), ('to', 'to'), ('also', 'also'), ('call', 'call'), ('the', 'the'), ('ofice', 'once'), ('if', 'if'), ('she', 'she'), ('has', 'has'), ('any', 'any'), ('ever', 'fever'), ('greater', 'greater'), ('than', 'than'), ('101', '101'), (',', ','), ('or', 'or'), ('leeding', 'leading'), ('form', 'from'), ('the', 'the'), ('surgical', 'surgical'), ('wounds', 'wounds'), ('.', '.')]\n[('Abdomen', 'Abdomen'), ('is', 'is'), ('sort', 'sort'), (',', ','), ('nontender', 'nontender'), (',', ','), ('and', 'and'), ('nonintended', 'unintended'), ('.', '.')]\n[('Patient', 'Patient'), ('not', 'not'), ('showing', 'showing'), ('pain', 'pain'), ('or', 'or'), ('any', 'any'), ('wealth', 'health'), ('problems', 'problems'), ('.', '.')]\n[('No', 'No'), ('cute', 'acute'), ('distress', 'distress')]\n"
]
]
]
| [
"markdown",
"code",
"markdown",
"code"
]
| [
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
]
|
cb6057a6a04d588c04369611da669341532f85c3 | 101,547 | ipynb | Jupyter Notebook | Hipotese1.ipynb | matheusraz/DS-Project | d1f98f25f457fe72495c02043f7b677ad9ed09cd | [
"MIT"
]
| null | null | null | Hipotese1.ipynb | matheusraz/DS-Project | d1f98f25f457fe72495c02043f7b677ad9ed09cd | [
"MIT"
]
| null | null | null | Hipotese1.ipynb | matheusraz/DS-Project | d1f98f25f457fe72495c02043f7b677ad9ed09cd | [
"MIT"
]
| null | null | null | 48.14936 | 15,112 | 0.472166 | [
[
[
"### Hipótese 1 (MLPRegressor)\n`Matheus Raz ([email protected])`\n\n`João Paulo Lins ([email protected])`\n\n#### É possível prever o número de vendas globais de um game baseado no seu gênero, rating, publisher e plataforma?",
"_____no_output_____"
]
],
[
[
"from IPython.display import display\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.neural_network import MLPRegressor\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import explained_variance_score\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn.model_selection import cross_val_score, cross_val_predict\nfrom sklearn import metrics",
"_____no_output_____"
],
[
"df = pd.read_csv('vgsalesPP2.csv')\ndf.drop(['Unnamed: 0'],axis=1,inplace=True)\ndf",
"_____no_output_____"
],
[
"all_genres = df.loc[:,'Action':'Strategy'].copy().copy()\nall_ratings = df.loc[:,'AO':'T'].copy()\nall_platforms = df.loc[:,'2600':'XOne'].copy()\nall_publishers = df.loc[:,'10TACLE Studios':'responDESIGN'].copy()\ngenres_and_ratings = all_genres.join(all_ratings).copy()\nplatforms_and_publishers = all_platforms.join(all_publishers).copy()\n\nX = genres_and_ratings.join(platforms_and_publishers).values.copy()\ny = df[\"Global_Sales\"].values.copy()",
"_____no_output_____"
],
[
"X",
"_____no_output_____"
],
[
"y",
"_____no_output_____"
],
[
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30)",
"_____no_output_____"
],
[
"scores = []\nfor i in range(5, 100):\n mlp = MLPRegressor(\n hidden_layer_sizes=(i,), activation='relu', solver='adam', alpha=0.001, batch_size='auto',\n learning_rate='constant', learning_rate_init=0.01, power_t=0.5, max_iter=1000, shuffle=True,\n random_state=9, tol=0.0001, verbose=False, warm_start=False, momentum=0.9, nesterovs_momentum=True,\n early_stopping=False, validation_fraction=0.1, beta_1=0.9, beta_2=0.999, epsilon=1e-08)\n model = mlp.fit(X_train, y_train)\n pred_i = model.predict(X_test)\n scores.append(model.score(X_test, y_test))",
"_____no_output_____"
],
[
"best_result = 0\nfor i in scores:\n if(i > best_result):\n best_result = i\n\nbest_hidden_layer_sizes = scores.index(best_result) + 1\nprint(\"Melhor resultado:\",best_result,\"para\",best_hidden_layer_sizes,\"camadas escondidas\")",
"Melhor resultado: 0.15689742752075853 para 43 camadas escondidas\n"
]
],
[
[
"### Conclusão\n\nVariando da 5 a 100 o número de camadas da Rede Neural MLP Regressor o melhor resultado obitido foi de apenas 15% de taxa de acerto. Sendo assim, a hipótese de que seria possível prever o número de vendas globais de um game baseado no seu gênero, rating, publisher e plataforma foi refutada.",
"_____no_output_____"
]
],
[
[
"mlp = MLPRegressor(\n hidden_layer_sizes=(best_hidden_layer_sizes,), activation='relu', solver='adam', alpha=0.001, batch_size='auto',\n learning_rate='constant', learning_rate_init=0.01, power_t=0.5, max_iter=1000, shuffle=True,\n random_state=9, tol=0.0001, verbose=False, warm_start=False, momentum=0.9, nesterovs_momentum=True,\n early_stopping=False, validation_fraction=0.1, beta_1=0.9, beta_2=0.999, epsilon=1e-08)\nmlp",
"_____no_output_____"
],
[
"model = mlp.fit(X_train, y_train)\npredictions = mlp.predict(X_test)\nplt.scatter(y_test, predictions)\nplt.xlabel(\"True Values\")\nplt.ylabel(\"Predictions\")\nprint(\"Score:\", model.score(X_test, y_test))",
"Score: 0.0232801046162312\n"
],
[
"scores = cross_val_score(model, X, y, cv=6)\nprint (\"Cross-validated scores:\", scores)",
"Cross-validated scores: [-3.56271672e-01 -4.35831082e+01 -2.45221344e+02 -5.57120558e+02\n -1.37866501e+03 -2.92653606e+03]\n"
],
[
"predictions = cross_val_predict(model, X, y, cv=6)\nplt.scatter(y, predictions)",
"_____no_output_____"
],
[
"accuracy = metrics.r2_score(y, predictions)\nprint (\"Cross-Predicted Accuracy:\", accuracy)",
"Cross-Predicted Accuracy: -0.13085496771291116\n"
]
]
]
| [
"markdown",
"code",
"markdown",
"code"
]
| [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
]
|
cb605acb110587a34d89a9372c702de501439348 | 131,219 | ipynb | Jupyter Notebook | Neural Network.ipynb | evazhang612/229proj | bb9aa12c878844697c82558f974ac4a5adcbe9c0 | [
"MIT"
]
| null | null | null | Neural Network.ipynb | evazhang612/229proj | bb9aa12c878844697c82558f974ac4a5adcbe9c0 | [
"MIT"
]
| null | null | null | Neural Network.ipynb | evazhang612/229proj | bb9aa12c878844697c82558f974ac4a5adcbe9c0 | [
"MIT"
]
| null | null | null | 214.761047 | 42,940 | 0.866391 | [
[
[
"from datetime import datetime \n\nimport numpy as np\nimport pandas as pd\nimport sklearn\nfrom sklearn.linear_model import LinearRegression\n#parse data \nfrom sklearn import preprocessing\nfrom sklearn.preprocessing import LabelEncoder\n#label encoding on categorical data \n\n#FAMA 49CRSP Common Stocks \ndf = pd.read_csv('FAMA_49CRSP.csv', dtype={'public_date' : str})",
"_____no_output_____"
],
[
"import sklearn.preprocessing \nfrom sklearn.preprocessing import KBinsDiscretizer\nfrom sklearn.model_selection import train_test_split\n\n#preprocessing here\n#sort by date \ndf = df.sort_values(by = 'public_date', ascending = True)\ndf = df.dropna()\n\n#encode integer categories into numbers \nlabel_encoder = LabelEncoder()\ninteger_encoded = label_encoder.fit_transform(df.FFI49_desc)\ndf.FFI49_desc = integer_encoded\n\n#df = df.dropna()\n\newlabels = df.indret_ew\nvwlabels = df.indret_vw\n\ndf = df.drop(labels=['indret_ew', 'indret_vw'], axis=1)\n#3year on year change as a prediction feature, raw pct change \nyoythree = ewlabels.diff(periods = 3)\n#3 years rolling percent change, averaged ie. (y1-y2 + (y3-y2)change)/2 \nrollavgpct = ewlabels.rolling(3).mean()\n\n#drop first 3 years\ndf = df.iloc[3:]\newlabels = ewlabels.iloc[3:]\nyoythree = yoythree.iloc[3:]\n#yoypctthree = yoypctthree.iloc[3:]\nrollavgpct = rollavgpct.iloc[3:]\n\n#add -1 and 1 so the bins will take on bins to be equal and set to max -1 and 1\n#extrema = pd.Series([-1,1])\n#ewnlabels = ewlabels.append(extrema)\n\n#make a new output (bucket by percentage?)\n# enc = KBinsDiscretizer(n_bins=8, encode='ordinal',strategy = 'uniform')\n# ewnlabels = np.asarray(ewnlabels)\n# ewnlabels = ewnlabels.reshape((-1,1))\n# labels_binned = enc.fit_transform(ewnlabels)\n\n# labels_binned = labels_binned[:-2]\n\n#1 Split-Timer series data, 0.64 Train, 0.16 dev, 0.2 Test\n#x_train, x_test, y_train, y_test = train_test_split(df, labels_binned, test_size = 0.2, shuffle = False)\nx_train, x_test, y_train, y_test = train_test_split(df, ewlabels, test_size = 0.2, shuffle = False)\nx_train, x_dev, y_train, y_dev = train_test_split(x_train, y_train, test_size = 0.2, shuffle = False)",
"_____no_output_____"
],
[
"def get_dates(x_train, x_dev, x_test):\n train_dates = [datetime(year=int(x[0:4]), month=int(x[4:6]), day=int(x[6:8])) for x in x_train['public_date']] \n dev_dates = [datetime(year=int(x[0:4]), month=int(x[4:6]), day=int(x[6:8])) for x in x_dev['public_date']]\n test_dates = [datetime(year=int(x[0:4]), month=int(x[4:6]), day=int(x[6:8])) for x in x_test['public_date']]\n \n x_train = x_train.drop('public_date', axis=1)\n x_dev = x_dev.drop('public_date', axis=1)\n x_test = x_test.drop('public_date', axis=1)\n \n return train_dates, dev_dates, test_dates, x_train, x_dev, x_test\n\ntrain_dates, dev_dates, test_dates, x_train, x_dev, x_test = get_dates(x_train, x_dev, x_test)\n\nprint(x_train.shape)\nprint(x_test.shape)",
"(13167, 70)\n(4115, 70)\n"
],
[
"from matplotlib import pyplot\n\nfig1 = pyplot.figure(1, figsize = (6,6))\npyplot.plot(train_dates, y_train, color = 'green', label = 'industry_ew_train')\npyplot.plot(dev_dates, y_dev, color = 'yellow', label = 'industry_ew_dev')\npyplot.plot(test_dates, y_test, color = 'red', label = 'industry_ew_test')\npyplot.xlabel('Date')\npyplot.ylabel('Industry Return (Equally Weighted)')\npyplot.legend()\npyplot.show()",
"_____no_output_____"
],
[
"#tutorial keras practice\n#https://machinelearningmastery.com/tutorial-first-neural-network-python-keras/\n\n\n#####IGNORE THIS!!!!!!!!\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation,Softmax\nfrom keras.optimizers import SGD\nfrom sklearn.metrics import mean_squared_error\nimport numpy\n\nmodel = Sequential()\n#parameters = number of neurons, initialization method, activation function\nmodel.add(Dense(32, input_dim=76, init = 'uniform', activation = 'relu'))\nmodel.add(Dense(16, init = 'uniform', activation = 'relu'))\nmodel.add(Dense(1, init = 'uniform', activation = 'sigmoid'))\n\n# For a binary classification problem\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\nmodel.fit(x_tra, y_tra, epochs=25, batch_size=32)\n\n\nprint(\"----------------------------------------------------------\")\nscores = model.evaluate(x_tra,y_tra)\nprint(\"\\n%s: %.2f%%\" % (model.metrics_names[1], scores[1]*100))\n\nprint(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\")\n\ny_devpred = model.predict(x_dev)\nprint(\"--------------------------------------------\")\nprint(mean_squared_error(y_dev,y_devpred))",
"/home/klchou/.local/lib/python3.6/site-packages/ipykernel_launcher.py:14: UserWarning: Update your `Dense` call to the Keras 2 API: `Dense(32, input_dim=76, activation=\"relu\", kernel_initializer=\"uniform\")`\n \n/home/klchou/.local/lib/python3.6/site-packages/ipykernel_launcher.py:15: UserWarning: Update your `Dense` call to the Keras 2 API: `Dense(16, activation=\"relu\", kernel_initializer=\"uniform\")`\n from ipykernel import kernelapp as app\n/home/klchou/.local/lib/python3.6/site-packages/ipykernel_launcher.py:16: UserWarning: Update your `Dense` call to the Keras 2 API: `Dense(1, activation=\"sigmoid\", kernel_initializer=\"uniform\")`\n app.launch_new_instance()\n"
],
[
"#Regression Model:\n#1 Layer: 76 -> 12.78% and 15.28%\n#2 Layer: 76,1 -> 0.40% and 0.48%\n#3 Layers: 76, 32, 1 -> 0% and 65%\n#4 layers: 76,48,32,1 + adam + -> 60.52% and 56.70%\n#4 Layers: 76,32,16,1 -> 61.33% and 57.18%\n#4 Layers: 76,32,8,1 -> 0%\n#4 layers: 76,48,8,1 -> 0%\n#6 layers: 76,48,32,16,8,1 -> 20% and 0%\n\nimport pandas\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.wrappers.scikit_learn import KerasRegressor\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import KFold\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import Pipeline\nfrom matplotlib import pyplot\nimport seaborn as sns\n\n\nmodel = Sequential()\n#parameters = number of neurons, initialization method, activation function\nmodel.add(Dense(72, input_dim=x_train.shape[1], kernel_initializer='normal', activation='relu'))\n#model.add(Dense(48, kernel_initializer='normal',activation = 'relu'))\nmodel.add(Dense(32, kernel_initializer='normal',activation = 'relu'))\n#model.add(Dense(16, kernel_initializer='normal',activation = 'relu'))\nmodel.add(Dense(8, kernel_initializer='normal',activation = 'relu'))\nmodel.add(Dense(1, kernel_initializer='normal', activation = 'linear'))\n \n# Compile model\n#opt = Adam(lr=0.002, beta_1=0.9, beta_2=0.999, epsilon=1e-08)\n#model.compile(loss='mean_squared_error', optimizer=opt, metrics=['accuracy'])\n#model.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])\nmodel.compile(loss='mse', optimizer='adam', metrics=['mse', 'mae', 'mape', 'cosine'])\nhistory = model.fit(np.asarray(x_train), y_train, epochs=50)\n\nfig2 = pyplot.figure(2,figsize = (10,10))\npyplot.plot(history.history['mean_squared_error'], color = 'blue')\npyplot.plot(history.history['mean_absolute_error'], color = 'green')\npyplot.plot(history.history['mean_absolute_percentage_error'], color = 'orange')\npyplot.plot(history.history['cosine_proximity'], color = 'red')\npyplot.ylim(-10,10)\npyplot.show()\n\n#train set\nprint(\"----------------------------------------------------------\")\ntrain_predictions = model.predict(x_train) \nscores = model.evaluate(np.asarray(x_train), y_train)\nfor i in range(len(scores)):\n print(\"\\n%s: %.2f%%\" % (model.metrics_names[i], scores[i]))\n\n#dev set\nprint(\"----------------------------------------------------------\")\ndev_predictions = model.predict(x_dev) \nscores = model.evaluate(np.asarray(x_dev),y_dev)\nfor i in range(len(scores)):\n print(\"\\n%s: %.2f%%\" % (model.metrics_names[i], scores[i]))\n\nfig3 = pyplot.figure(3, figsize = (10,10))\npyplot.plot(dev_dates, y_dev, color = 'green')\npyplot.plot(dev_dates, dev_predictions, color = 'red')\npyplot.show()\n\n#test set\nprint(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\")\ntest_predictions = model.predict(x_test).reshape((-1))\nscores = model.evaluate(np.asarray(x_test),y_test)\nfor i in range(len(scores)):\n print(\"\\n%s: %.2f%%\" % (model.metrics_names[i], scores[i]))\n\nfig4 = pyplot.figure(4, figsize = (10,10))\npyplot.plot(test_dates, y_test, color = 'green')\npyplot.plot(test_dates, test_predictions, color = 'red')\npyplot.show()",
"Epoch 1/50\n13167/13167 [==============================] - 1s 80us/step - loss: 0.0978 - mean_squared_error: 0.0978 - mean_absolute_error: 0.0904 - mean_absolute_percentage_error: 11898.8460 - cosine_proximity: -0.0873\nEpoch 2/50\n13167/13167 [==============================] - 1s 53us/step - loss: 0.0049 - mean_squared_error: 0.0049 - mean_absolute_error: 0.0523 - mean_absolute_percentage_error: 9403.1272 - cosine_proximity: -0.1198\nEpoch 3/50\n13167/13167 [==============================] - 1s 53us/step - loss: 0.0049 - mean_squared_error: 0.0049 - mean_absolute_error: 0.0523 - mean_absolute_percentage_error: 14084.0951 - cosine_proximity: -0.1306\nEpoch 4/50\n13167/13167 [==============================] - 1s 53us/step - loss: 0.0050 - mean_squared_error: 0.0050 - mean_absolute_error: 0.0529 - mean_absolute_percentage_error: 10834.7172 - cosine_proximity: -0.0948\nEpoch 5/50\n13167/13167 [==============================] - 1s 54us/step - loss: 0.0050 - mean_squared_error: 0.0050 - mean_absolute_error: 0.0532 - mean_absolute_percentage_error: 14446.1271 - cosine_proximity: -0.0945\nEpoch 6/50\n13167/13167 [==============================] - 1s 55us/step - loss: 0.0050 - mean_squared_error: 0.0050 - mean_absolute_error: 0.0528 - mean_absolute_percentage_error: 10738.8438 - cosine_proximity: -0.1146\nEpoch 7/50\n13167/13167 [==============================] - 1s 54us/step - loss: 0.0051 - mean_squared_error: 0.0051 - mean_absolute_error: 0.0538 - mean_absolute_percentage_error: 14942.3014 - cosine_proximity: -0.0852\nEpoch 8/50\n13167/13167 [==============================] - 1s 54us/step - loss: 0.0050 - mean_squared_error: 0.0050 - mean_absolute_error: 0.0528 - mean_absolute_percentage_error: 11129.7420 - cosine_proximity: -0.1118\nEpoch 9/50\n13167/13167 [==============================] - 1s 53us/step - loss: 0.0051 - mean_squared_error: 0.0051 - mean_absolute_error: 0.0539 - mean_absolute_percentage_error: 13104.1686 - cosine_proximity: -0.0931\nEpoch 10/50\n13167/13167 [==============================] - 1s 51us/step - loss: 0.0050 - mean_squared_error: 0.0050 - mean_absolute_error: 0.0529 - mean_absolute_percentage_error: 10869.8542 - cosine_proximity: -0.1071\nEpoch 11/50\n13167/13167 [==============================] - 1s 52us/step - loss: 0.0048 - mean_squared_error: 0.0048 - mean_absolute_error: 0.0513 - mean_absolute_percentage_error: 11216.9720 - cosine_proximity: -0.1666\nEpoch 12/50\n13167/13167 [==============================] - 1s 51us/step - loss: 0.0048 - mean_squared_error: 0.0048 - mean_absolute_error: 0.0513 - mean_absolute_percentage_error: 11209.6673 - cosine_proximity: -0.1653\nEpoch 13/50\n13167/13167 [==============================] - 1s 51us/step - loss: 0.0048 - mean_squared_error: 0.0048 - mean_absolute_error: 0.0512 - mean_absolute_percentage_error: 11523.7672 - cosine_proximity: -0.1683\nEpoch 14/50\n13167/13167 [==============================] - 1s 50us/step - loss: 0.0048 - mean_squared_error: 0.0048 - mean_absolute_error: 0.0512 - mean_absolute_percentage_error: 10803.8641 - cosine_proximity: -0.1675\nEpoch 15/50\n13167/13167 [==============================] - 1s 46us/step - loss: 0.0048 - mean_squared_error: 0.0048 - mean_absolute_error: 0.0511 - mean_absolute_percentage_error: 11353.2605 - cosine_proximity: -0.1704\nEpoch 16/50\n13167/13167 [==============================] - 1s 49us/step - loss: 0.0048 - mean_squared_error: 0.0048 - mean_absolute_error: 0.0511 - mean_absolute_percentage_error: 11367.2764 - cosine_proximity: -0.1689\nEpoch 17/50\n13167/13167 [==============================] - 1s 55us/step - loss: 0.0048 - mean_squared_error: 0.0048 - mean_absolute_error: 0.0510 - mean_absolute_percentage_error: 11237.7022 - cosine_proximity: -0.1694\nEpoch 18/50\n13167/13167 [==============================] - 1s 54us/step - loss: 0.0048 - mean_squared_error: 0.0048 - mean_absolute_error: 0.0512 - mean_absolute_percentage_error: 11316.1448 - cosine_proximity: -0.1689\nEpoch 19/50\n13167/13167 [==============================] - 1s 54us/step - loss: 0.0047 - mean_squared_error: 0.0047 - mean_absolute_error: 0.0511 - mean_absolute_percentage_error: 11666.8128 - cosine_proximity: -0.1721\nEpoch 20/50\n13167/13167 [==============================] - 1s 51us/step - loss: 0.0047 - mean_squared_error: 0.0047 - mean_absolute_error: 0.0510 - mean_absolute_percentage_error: 11166.1622 - cosine_proximity: -0.1713\nEpoch 21/50\n13167/13167 [==============================] - 1s 61us/step - loss: 0.0047 - mean_squared_error: 0.0047 - mean_absolute_error: 0.0510 - mean_absolute_percentage_error: 10024.0921 - cosine_proximity: -0.1718\nEpoch 22/50\n13167/13167 [==============================] - 1s 64us/step - loss: 0.0047 - mean_squared_error: 0.0047 - mean_absolute_error: 0.0510 - mean_absolute_percentage_error: 11821.5069 - cosine_proximity: -0.1724\nEpoch 23/50\n13167/13167 [==============================] - 1s 59us/step - loss: 0.0047 - mean_squared_error: 0.0047 - mean_absolute_error: 0.0510 - mean_absolute_percentage_error: 11516.2538 - cosine_proximity: -0.1722\nEpoch 24/50\n13167/13167 [==============================] - 1s 53us/step - loss: 0.0047 - mean_squared_error: 0.0047 - mean_absolute_error: 0.0510 - mean_absolute_percentage_error: 11580.2912 - cosine_proximity: -0.1727\nEpoch 25/50\n13167/13167 [==============================] - 1s 55us/step - loss: 0.0047 - mean_squared_error: 0.0047 - mean_absolute_error: 0.0509 - mean_absolute_percentage_error: 11878.0242 - cosine_proximity: -0.1730\nEpoch 26/50\n13167/13167 [==============================] - 1s 62us/step - loss: 0.0047 - mean_squared_error: 0.0047 - mean_absolute_error: 0.0510 - mean_absolute_percentage_error: 10919.9075 - cosine_proximity: -0.1727\nEpoch 27/50\n13167/13167 [==============================] - 1s 57us/step - loss: 0.0047 - mean_squared_error: 0.0047 - mean_absolute_error: 0.0509 - mean_absolute_percentage_error: 10429.9875 - cosine_proximity: -0.1729\nEpoch 28/50\n13167/13167 [==============================] - 1s 56us/step - loss: 0.0047 - mean_squared_error: 0.0047 - mean_absolute_error: 0.0509 - mean_absolute_percentage_error: 11543.5173 - cosine_proximity: -0.1729\nEpoch 29/50\n13167/13167 [==============================] - 1s 56us/step - loss: 0.0047 - mean_squared_error: 0.0047 - mean_absolute_error: 0.0510 - mean_absolute_percentage_error: 12081.5344 - cosine_proximity: -0.1704\nEpoch 30/50\n13167/13167 [==============================] - 1s 54us/step - loss: 0.0047 - mean_squared_error: 0.0047 - mean_absolute_error: 0.0510 - mean_absolute_percentage_error: 11238.2028 - cosine_proximity: -0.1712\nEpoch 31/50\n13167/13167 [==============================] - 1s 60us/step - loss: 0.0047 - mean_squared_error: 0.0047 - mean_absolute_error: 0.0509 - mean_absolute_percentage_error: 11703.0555 - cosine_proximity: -0.1724\nEpoch 32/50\n13167/13167 [==============================] - 1s 59us/step - loss: 0.0047 - mean_squared_error: 0.0047 - mean_absolute_error: 0.0510 - mean_absolute_percentage_error: 11189.4146 - cosine_proximity: -0.1716\nEpoch 33/50\n13167/13167 [==============================] - 1s 58us/step - loss: 0.0047 - mean_squared_error: 0.0047 - mean_absolute_error: 0.0509 - mean_absolute_percentage_error: 11611.3966 - cosine_proximity: -0.1733\nEpoch 34/50\n13167/13167 [==============================] - 1s 53us/step - loss: 0.0047 - mean_squared_error: 0.0047 - mean_absolute_error: 0.0509 - mean_absolute_percentage_error: 10826.7089 - cosine_proximity: -0.1730\nEpoch 35/50\n13167/13167 [==============================] - 1s 59us/step - loss: 0.0047 - mean_squared_error: 0.0047 - mean_absolute_error: 0.0509 - mean_absolute_percentage_error: 11256.0200 - cosine_proximity: -0.1709\nEpoch 36/50\n13167/13167 [==============================] - 1s 57us/step - loss: 0.0047 - mean_squared_error: 0.0047 - mean_absolute_error: 0.0509 - mean_absolute_percentage_error: 10728.3646 - cosine_proximity: -0.1745\nEpoch 37/50\n13167/13167 [==============================] - 1s 57us/step - loss: 0.0047 - mean_squared_error: 0.0047 - mean_absolute_error: 0.0509 - mean_absolute_percentage_error: 11185.2698 - cosine_proximity: -0.1729\nEpoch 38/50\n"
],
[
"from keras.models import Sequential\nfrom keras.layers import Dense, Activation\nfrom keras.optimizers import SGD\nfrom sklearn.metrics import mean_squared_error\nimport numpy\n\nmodel = Sequential()\nmodel.add(Dense(32, input_dim=x_train.shape[1], init = 'uniform', activation = 'relu'))\nmodel.add(Dense(16, init = 'uniform', activation = 'relu'))\nmodel.add(Dense(8, init = 'uniform', activation = 'softmax'))\n\n# For a multi-class classification problem\nmodel.compile(optimizer='rmsprop',\n loss='categorical_crossentropy',\n metrics=['accuracy'])\nmodel.fit(x_train, y_train, epochs=25, batch_size=32)\n\n\nprint(\"----------------------------------------------------------\")\nscores = model.evaluate(x_train,y_train)\nprint(\"\\n%s: %.2f%%\" % (model.metrics_names[1], scores[1]*100))\n\nprint(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\")\ny_devpred = model.predict(x_dev)\nprint(\"--------------------------------------------\")\nprint(mean_squared_error(y_dev,y_devpred))",
"/home/klchou/.local/lib/python3.6/site-packages/ipykernel_launcher.py:8: UserWarning: Update your `Dense` call to the Keras 2 API: `Dense(32, input_dim=72, activation=\"relu\", kernel_initializer=\"uniform\")`\n \n/home/klchou/.local/lib/python3.6/site-packages/ipykernel_launcher.py:9: UserWarning: Update your `Dense` call to the Keras 2 API: `Dense(16, activation=\"relu\", kernel_initializer=\"uniform\")`\n if __name__ == '__main__':\n/home/klchou/.local/lib/python3.6/site-packages/ipykernel_launcher.py:10: UserWarning: Update your `Dense` call to the Keras 2 API: `Dense(8, activation=\"softmax\", kernel_initializer=\"uniform\")`\n # Remove the CWD from sys.path while we load stuff.\n"
],
[
"from keras.models import Sequential\nfrom keras.layers import Dense, Activation,Softmax\nfrom keras.optimizers import SGD\n\nmodel = Sequential()\nmodel.add(Dense(32, input_shape = (x_train.shape)))\nmodel.add(Dense(64, activation='relu'))\nmodel.add(Dense(10, activation='softmax'))\n\n# For a multi-class classification problem\nmodel.compile(optimizer='rmsprop',\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n# For a binary classification problem\nmodel.compile(optimizer='rmsprop',\n loss='binary_crossentropy',\n metrics=['accuracy'])\n\n# For a mean squared error regression problem\nmodel.compile(optimizer='rmsprop',\n loss='mse')\n\nmodel.fit(x_train, y_train, epochs=5, batch_size=32)\ny_devpred = model.predict(x_dev)\nprint(\"--------------------------------------------\")\nprint(mean_squared_error(y_dev,y_devpred))\n",
"_____no_output_____"
]
]
]
| [
"code"
]
| [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
]
|
cb6060ca39c4e02396b95d408ae4a4f4f616728d | 25,761 | ipynb | Jupyter Notebook | demo.ipynb | GT-AcerZhang/video_face_detection | ee6593ce289ca34d814e34d22665664136ab9db4 | [
"Apache-2.0"
]
| 1 | 2021-07-06T09:39:04.000Z | 2021-07-06T09:39:04.000Z | demo.ipynb | GT-AcerZhang/video_face_detection | ee6593ce289ca34d814e34d22665664136ab9db4 | [
"Apache-2.0"
]
| null | null | null | demo.ipynb | GT-AcerZhang/video_face_detection | ee6593ce289ca34d814e34d22665664136ab9db4 | [
"Apache-2.0"
]
| 1 | 2021-03-07T10:11:10.000Z | 2021-03-07T10:11:10.000Z | 44.958115 | 1,138 | 0.550871 | [
[
[
"<font face=楷体 size=6><b>黑人抬棺人脸检测:</b>\n\n<font face=楷体 size=5><b>背景:</b>\n \n<font face=楷体 size=3>黑人抬棺这么火,怎么能不用paddlehub试一试呢?\n<br>\n<font face=楷体 size=3>临近期末,准备考试,还要准备考研,555,明明有好点子,但是没时间做,先出一个黑人抬棺的视频8\n \n<font face=楷体 size=5><b>结果:</b>\n \n<font face=楷体 size=3>在我的B站上: <a href=https://www.bilibili.com/video/BV1Sk4y1r7Zz>https://www.bilibili.com/video/BV1Sk4y1r7Zz</a>\n \n<font face=楷体 size=5><b>思路和步骤:</b>\n \n<font face=楷体 size=3>思路嘛,再简单不过,一帧一帧拆分,一帧一帧人脸检测\n<font face=楷体 size=3>步骤嘛,人脸检测 + ffmpeg拆分合并\n \n<font face=楷体 size=5><b>总结:</b><br>\n<font face=楷体 size=3>paddlehub蛮好用的,改日有时间定要搞一番事业<br>\n<font face=楷体 size=3>时间太少了,考研党伤不起啊啊啊",
"_____no_output_____"
]
],
[
[
"from IPython.display import HTML\nHTML('<iframe style=\"width:98%;height: 450px;\" src=\"//player.bilibili.com/player.html?bvid=BV1Sk4y1r7Zz\" scrolling=\"no\" border=\"0\" frameborder=\"no\" framespacing=\"0\" allowfullscreen=\"true\"> </iframe>')",
"_____no_output_____"
],
[
"# ---------------------------------------------------------------------------\r\n# 为使用 `GPU` 设置环境变量 , (仍然报错, 已在github上提交issue——目前已解决)\r\n# ---------------------------------------------------------------------------\r\n%set_env CUDA_VISIBLE_DEVICES = 0",
"env: CUDA_VISIBLE_DEVICES=0\n"
],
[
"# ---------------------------------------------------------------------------\r\n# 安装视频处理环境\r\n# ---------------------------------------------------------------------------\r\n!pip install moviepy -i https://pypi.tuna.tsinghua.edu.cn/simple\r\n!pip install ffmpeg",
"Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple\nRequirement already satisfied: moviepy in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (1.0.1)\nRequirement already satisfied: decorator<5.0,>=4.0.2 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from moviepy) (4.4.0)\nRequirement already satisfied: numpy in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from moviepy) (1.16.4)\nRequirement already satisfied: tqdm<5.0,>=4.11.2 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from moviepy) (4.36.1)\nRequirement already satisfied: requests<3.0,>=2.8.1 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from moviepy) (2.22.0)\nRequirement already satisfied: proglog<=1.0.0 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from moviepy) (0.1.9)\nRequirement already satisfied: imageio-ffmpeg>=0.2.0; python_version >= \"3.4\" in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from moviepy) (0.3.0)\nRequirement already satisfied: imageio<3.0,>=2.5; python_version >= \"3.4\" in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from moviepy) (2.6.1)\nRequirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from requests<3.0,>=2.8.1->moviepy) (3.0.4)\nRequirement already satisfied: idna<2.9,>=2.5 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from requests<3.0,>=2.8.1->moviepy) (2.8)\nRequirement already satisfied: certifi>=2017.4.17 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from requests<3.0,>=2.8.1->moviepy) (2019.9.11)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from requests<3.0,>=2.8.1->moviepy) (1.25.6)\nRequirement already satisfied: pillow in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from imageio<3.0,>=2.5; python_version >= \"3.4\"->moviepy) (6.2.0)\nLooking in indexes: https://pypi.mirrors.ustc.edu.cn/simple/\nRequirement already satisfied: ffmpeg in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (1.4)\n"
],
[
"# ---------------------------------------------------------------------------\r\n# 安装paddlehub环境和下载模型\r\n# ---------------------------------------------------------------------------\r\n\r\ntry:\r\n import paddlehub as hub\r\n\r\nexcept ImportError:\r\n !pip install paddlehub==1.6.0 -i https://pypi.tuna.tsinghua.edu.cn/simple\r\n import paddlehub as hub\r\n\r\ntry:\r\n module = hub.Module(name=\"ultra_light_fast_generic_face_detector_1mb_640\")\r\n # module = hub.Moudle(name=\"ultra_light_fast_generic_face_detector_1mb_320\")\r\nexcept FileNotFoundError:\r\n !hub install ultra_light_fast_generic_face_detector_1mb_640==1.1.2\r\n module = hub.Module(name=\"ultra_light_fast_generic_face_detector_1mb_640\")\r\n # module = hub.Moudle(name=\"ultra_light_fast_generic_face_detector_1mb_320\")",
"\u001b[32m[2020-05-07 14:22:40,518] [ INFO] - Installing ultra_light_fast_generic_face_detector_1mb_640 module\u001b[0m\n\u001b[32m[2020-05-07 14:22:40,527] [ INFO] - Module ultra_light_fast_generic_face_detector_1mb_640 already installed in /home/aistudio/.paddlehub/modules/ultra_light_fast_generic_face_detector_1mb_640\u001b[0m\n"
]
],
[
[
"注:\nUltra-Light-Fast-Generic-Face-Detector-1MB提供了两种预训练模型,ultra_light_fast_generic_face_detector_1mb_320和ultra_light_fast_generic_face_detector_1mb_640。\n\n- ultra_light_fast_generic_face_detector_1mb_320,在预测时会将图片输入缩放为320 * 240,预测速度更快。关于该模型更多介绍, 查看[PaddleHub官网介绍](https://www.paddlepaddle.org.cn/hubdetail?name=ultra_light_fast_generic_face_detector_1mb_320&en_category=ObjectDetection)\n- ultra_light_fast_generic_face_detector_1mb_640,在预测时会将图片输入缩放为640 * 480,预测精度更高。关于该模型更多介绍, 查看[PaddleHub官网介绍](https://www.paddlepaddle.org.cn/hubdetail?name=ultra_light_fast_generic_face_detector_1mb_640&en_category=ObjectDetection)\n\n用户根据需要,选择具体模型。利用PaddleHub使用该模型时,只需更改指定name,即可实现无缝切换。",
"_____no_output_____"
]
],
[
[
"# ---------------------------------------------------------------------------\r\n# 查看黑人抬棺视频的基本信息\r\n# ---------------------------------------------------------------------------\r\nimport os\r\nimport cv2\r\nimport json\r\nimport numpy as np\r\nimport matplotlib.image as mpimg\r\nimport matplotlib.pyplot as plt\r\nfrom tqdm import tqdm\r\n\r\nvideo = cv2.VideoCapture(\"video.flv\")\r\n\r\nfps = video.get(cv2.CAP_PROP_FPS) # 视频帧率\r\nframeCount = video.get(cv2.CAP_PROP_FRAME_COUNT) # 获得视频的总帧数\r\nwidth = video.get(cv2.CAP_PROP_FRAME_WIDTH) # 获得视频的宽度\r\nheight = video.get(cv2.CAP_PROP_FRAME_HEIGHT) # 获得视频的高度\r\n\r\nprint('视频的宽度:{}'.format(width))\r\nprint('视频的高度:{}'.format(height))\r\nprint('视频帧率:{}'.format(fps))\r\nprint('视频的总帧数:{}'.format(frameCount))",
"视频的宽度:852.0\n视频的高度:480.0\n视频帧率:30.06896551724138\n视频的总帧数:1330.0\n"
],
[
"cv2.__version__",
"_____no_output_____"
],
[
"# ---------------------------------------------------------------------------\r\n# 将视频数据变为帧数据, 并且保存\r\n# ---------------------------------------------------------------------------\r\nif not os.path.exists('frame'):\r\n os.mkdir('frame')\r\n\r\nall_img = []\r\nall_img_path_dict = {'image':[]}\r\n\r\nsuccess, frame = video.read()\r\ni = 0\r\nwhile success:\r\n \r\n all_img.append(frame)\r\n i += 1\r\n # if not i % 10:print(i)\r\n success, frame = video.read()\r\n\r\n path = os.path.join('frame', str(i)+'.jpg')\r\n all_img_path_dict['image'].append(path)\r\n cv2.imwrite(path, frame)\r\n\r\nall_img_path_dict['image'].pop()\r\nprint('完毕')",
"完毕\n"
],
[
"# ---------------------------------------------------------------------------\n# 预测并打印输出(或者找到已经保存的文件)\n# ---------------------------------------------------------------------------\n\n# 读取视频所保存的信息文件\ninfo_path = 'info.json'\n\n# hub版本更新后, 其检测精度浮点数太飘了, 这里赶时间, 就暂时不写了(准备期末考试ing...)\n# if os.path.exists(info_path):\n\n # # 读取已经保存的`json`数据\n # with open(info_path, 'r') as f:\n # json_dict = json.load(f)\n # results = json_dict['data']\nif False:\n pass\n\nelse: # 若没有找到`json`数据\n\n # PaddleHub对于支持一键预测的module,可以调用module的相应预测API,完成预测功能。\n results = module.face_detection(data=all_img_path_dict,\n use_gpu=True,\n visualization=True)\n # save_json = {'data':results}\n # with open(info_path, 'w') as f:\n # f.write(json.dumps(save_json))\n",
"\u001b[32m[2020-05-07 14:22:56,227] [ INFO] - 0 pretrained paramaters loaded by PaddleHub\u001b[0m\n"
],
[
"# ---------------------------------------------------------------------------\r\n# 输出制作视频文件的备用文件\r\n# ---------------------------------------------------------------------------\r\n\r\n# 输出视频的size\r\nsize = (int(width), int(height))\r\nsize = (int(height), int(width))\r\n# 创建写视频对象(不好用)\r\n# videoWriter = cv2.VideoWriter(\"a.avi\", cv2.VideoWriter_fourcc('M','J','P','G'), fps, size) \r\n\r\nfor i, info in tqdm(enumerate(results)):\r\n \r\n num_info = info['data']\r\n\r\n if not len(num_info):\r\n # 如果该画面没有人, 则 `frame`变量赋值为原来的图片\r\n frame = all_img[i].copy()[:,:, ::-1]\r\n else:\r\n # frame = mpimg.imread(info['save_path']) # 之前的save_path现在没了......\r\n frame = mpimg.imread(info['path'].replace('frame', 'face_detector_640_predict_output'))\r\n \r\n cv2.putText(frame, 'fps: {:.2f}'.format(fps), (20, 370), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0 ,255), 2)\r\n cv2.putText(frame, 'count: ' + str(len(num_info)), (20, 400), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0 ,255), 2)\r\n cv2.putText(frame, 'frame: ' + str(i), (20, 430), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0 ,255), 2)\r\n # cv2.putText(frame, 'time: {:.2f}s'.format(i / fps), (20,460), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255,0,255), 2)\r\n \r\n plt.imsave('./img_out/{}.jpg'.format(i), frame)\r\n",
"1323it [01:09, 19.03it/s]\n"
],
[
"# ---------------------------------------------------------------------------\r\n# 输出视频文件(没加配乐, 没有灵魂)(找了一堆python工具, 不如ffmpeg好用)\r\n# ---------------------------------------------------------------------------\r\nif os.path.exists('temp.mp4'):\r\n !rm -f temp.mp4\r\n!ffmpeg -f image2 -i img_out/%d.jpg -vcodec libx264 -r 60.0 temp.mp4",
"ffmpeg version 2.8.15-0ubuntu0.16.04.1 Copyright (c) 2000-2018 the FFmpeg developers\n built with gcc 5.4.0 (Ubuntu 5.4.0-6ubuntu1~16.04.10) 20160609\n configuration: --prefix=/usr --extra-version=0ubuntu0.16.04.1 --build-suffix=-ffmpeg --toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --cc=cc --cxx=g++ --enable-gpl --enable-shared --disable-stripping --disable-decoder=libopenjpeg --disable-decoder=libschroedinger --enable-avresample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libmodplug --enable-libmp3lame --enable-libopenjpeg --enable-libopus --enable-libpulse --enable-librtmp --enable-libschroedinger --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxvid --enable-libzvbi --enable-openal --enable-opengl --enable-x11grab --enable-libdc1394 --enable-libiec61883 --enable-libzmq --enable-frei0r --enable-libx264 --enable-libopencv\n libavutil 54. 31.100 / 54. 31.100\n libavcodec 56. 60.100 / 56. 60.100\n libavformat 56. 40.101 / 56. 40.101\n libavdevice 56. 4.100 / 56. 4.100\n libavfilter 5. 40.101 / 5. 40.101\n libavresample 2. 1. 0 / 2. 1. 0\n libswscale 3. 1.101 / 3. 1.101\n libswresample 1. 2.101 / 1. 2.101\n libpostproc 53. 3.100 / 53. 3.100\n\u001b[0;36m[mjpeg @ 0x1c2b720] \u001b[0mChangeing bps to 8\nInput #0, image2, from 'img_out/%d.jpg':\n Duration: 00:00:52.96, start: 0.000000, bitrate: N/A\n Stream #0:0: Video: mjpeg, yuvj420p(pc, bt470bg/unknown/unknown), 852x480 [SAR 100:100 DAR 71:40], 25 fps, 25 tbr, 25 tbn, 25 tbc\n\u001b[0;33mNo pixel format specified, yuvj420p for H.264 encoding chosen.\nUse -pix_fmt yuv420p for compatibility with outdated media players.\n\u001b[0m\u001b[1;36m[libx264 @ 0x1c2d3e0] \u001b[0musing SAR=1/1\n\u001b[1;36m[libx264 @ 0x1c2d3e0] \u001b[0musing cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX FMA3 AVX2 LZCNT BMI2\n\u001b[1;36m[libx264 @ 0x1c2d3e0] \u001b[0mprofile High, level 3.1\n\u001b[1;36m[libx264 @ 0x1c2d3e0] \u001b[0m264 - core 148 r2643 5c65704 - H.264/MPEG-4 AVC codec - Copyleft 2003-2015 - http://www.videolan.org/x264.html - options: cabac=1 ref=3 deblock=1:0:0 analyse=0x3:0x113 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=-2 threads=15 lookahead_threads=2 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=25 scenecut=40 intra_refresh=0 rc_lookahead=40 rc=crf mbtree=1 crf=23.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00\nOutput #0, mp4, to 'temp.mp4':\n Metadata:\n encoder : Lavf56.40.101\n Stream #0:0: Video: h264 (libx264) ([33][0][0][0] / 0x0021), yuvj420p(pc), 852x480 [SAR 100:100 DAR 71:40], q=-1--1, 60 fps, 15360 tbn, 60 tbc\n Metadata:\n encoder : Lavc56.60.100 libx264\nStream mapping:\n Stream #0:0 -> #0:0 (mjpeg (native) -> h264 (libx264))\nPress [q] to stop, [?] for help\nframe= 3177 fps=239 q=-1.0 Lsize= 7810kB time=00:00:52.91 bitrate=1209.0kbits/s dup=1853 drop=0 \nvideo:7776kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.431069%\n\u001b[1;36m[libx264 @ 0x1c2d3e0] \u001b[0mframe I:16 Avg QP:22.93 size: 28273\n\u001b[1;36m[libx264 @ 0x1c2d3e0] \u001b[0mframe P:1725 Avg QP:25.68 size: 4284\n\u001b[1;36m[libx264 @ 0x1c2d3e0] \u001b[0mframe B:1436 Avg QP:34.57 size: 84\n\u001b[1;36m[libx264 @ 0x1c2d3e0] \u001b[0mconsecutive B-frames: 35.6% 8.8% 11.0% 44.6%\n\u001b[1;36m[libx264 @ 0x1c2d3e0] \u001b[0mmb I I16..4: 15.4% 63.4% 21.2%\n\u001b[1;36m[libx264 @ 0x1c2d3e0] \u001b[0mmb P I16..4: 1.5% 4.2% 0.9% P16..4: 21.0% 8.7% 3.8% 0.0% 0.0% skip:60.0%\n\u001b[1;36m[libx264 @ 0x1c2d3e0] \u001b[0mmb B I16..4: 0.0% 0.0% 0.0% B16..8: 4.1% 0.0% 0.0% direct: 0.0% skip:95.9% L0:48.6% L1:50.5% BI: 0.9%\n\u001b[1;36m[libx264 @ 0x1c2d3e0] \u001b[0m8x8 transform intra:63.4% inter:70.0%\n\u001b[1;36m[libx264 @ 0x1c2d3e0] \u001b[0mcoded y,uvDC,uvAC intra: 54.5% 57.4% 11.5% inter: 6.1% 5.4% 0.7%\n\u001b[1;36m[libx264 @ 0x1c2d3e0] \u001b[0mi16 v,h,dc,p: 23% 35% 6% 36%\n\u001b[1;36m[libx264 @ 0x1c2d3e0] \u001b[0mi8 v,h,dc,ddl,ddr,vr,hd,vl,hu: 21% 24% 16% 5% 6% 7% 7% 7% 7%\n\u001b[1;36m[libx264 @ 0x1c2d3e0] \u001b[0mi4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 30% 21% 14% 4% 7% 7% 7% 5% 5%\n\u001b[1;36m[libx264 @ 0x1c2d3e0] \u001b[0mi8c dc,h,v,p: 54% 21% 20% 5%\n\u001b[1;36m[libx264 @ 0x1c2d3e0] \u001b[0mWeighted P-Frames: Y:1.0% UV:0.7%\n\u001b[1;36m[libx264 @ 0x1c2d3e0] \u001b[0mref P L0: 71.4% 17.5% 7.2% 3.9% 0.1%\n\u001b[1;36m[libx264 @ 0x1c2d3e0] \u001b[0mref B L0: 89.8% 9.3% 1.0%\n\u001b[1;36m[libx264 @ 0x1c2d3e0] \u001b[0mref B L1: 96.8% 3.2%\n\u001b[1;36m[libx264 @ 0x1c2d3e0] \u001b[0mkb/s:1202.99\n"
],
[
"# ---------------------------------------------------------------------------\r\n# 抽离源文件配乐\r\n# ---------------------------------------------------------------------------\r\nif os.path.exists('nb.mp3'):\r\n !rm -f nb.mp3\r\n!ffmpeg -i video.flv -f mp3 nb.mp3",
"ffmpeg version 2.8.15-0ubuntu0.16.04.1 Copyright (c) 2000-2018 the FFmpeg developers\n built with gcc 5.4.0 (Ubuntu 5.4.0-6ubuntu1~16.04.10) 20160609\n configuration: --prefix=/usr --extra-version=0ubuntu0.16.04.1 --build-suffix=-ffmpeg --toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --cc=cc --cxx=g++ --enable-gpl --enable-shared --disable-stripping --disable-decoder=libopenjpeg --disable-decoder=libschroedinger --enable-avresample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libmodplug --enable-libmp3lame --enable-libopenjpeg --enable-libopus --enable-libpulse --enable-librtmp --enable-libschroedinger --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxvid --enable-libzvbi --enable-openal --enable-opengl --enable-x11grab --enable-libdc1394 --enable-libiec61883 --enable-libzmq --enable-frei0r --enable-libx264 --enable-libopencv\n libavutil 54. 31.100 / 54. 31.100\n libavcodec 56. 60.100 / 56. 60.100\n libavformat 56. 40.101 / 56. 40.101\n libavdevice 56. 4.100 / 56. 4.100\n libavfilter 5. 40.101 / 5. 40.101\n libavresample 2. 1. 0 / 2. 1. 0\n libswscale 3. 1.101 / 3. 1.101\n libswresample 1. 2.101 / 1. 2.101\n libpostproc 53. 3.100 / 53. 3.100\nInput #0, flv, from 'video.flv':\n Metadata:\n description : Codec by Bilibili XCode Worker v4.8.74(fixed_gap:False)\n metadatacreator : Version 1.9\n hasKeyframes : true\n hasVideo : true\n hasAudio : true\n hasMetadata : true\n canSeekToEnd : true\n datasize : 5630178\n videosize : 4884547\n audiosize : 732715\n lasttimestamp : 44\n lastkeyframetimestamp: 44\n lastkeyframelocation: 5631018\n Duration: 00:00:44.24, start: 0.067000, bitrate: 1018 kb/s\n Stream #0:0: Video: h264 (High), yuv420p, 852x480 [SAR 640:639 DAR 16:9], 883 kb/s, 30.30 fps, 30 tbr, 1k tbn, 60 tbc\n Stream #0:1: Audio: aac (LC), 44100 Hz, stereo, fltp, 128 kb/s\nOutput #0, mp3, to 'nb.mp3':\n Metadata:\n description : Codec by Bilibili XCode Worker v4.8.74(fixed_gap:False)\n metadatacreator : Version 1.9\n hasKeyframes : true\n hasVideo : true\n hasAudio : true\n hasMetadata : true\n canSeekToEnd : true\n datasize : 5630178\n videosize : 4884547\n audiosize : 732715\n lasttimestamp : 44\n lastkeyframetimestamp: 44\n lastkeyframelocation: 5631018\n TSSE : Lavf56.40.101\n Stream #0:0: Audio: mp3 (libmp3lame), 44100 Hz, stereo, fltp\n Metadata:\n encoder : Lavc56.60.100 libmp3lame\nStream mapping:\n Stream #0:1 -> #0:0 (aac (native) -> mp3 (libmp3lame))\nPress [q] to stop, [?] for help\nsize= 691kB time=00:00:44.20 bitrate= 128.1kbits/s \nvideo:0kB audio:691kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.098418%\n"
],
[
"# ---------------------------------------------------------------------------\r\n# 音乐视频合成(由于需要调整视频速度, 使音频和视频时间一样, 命令行不太好调整, 我将合成放在了本地端)\r\n# ---------------------------------------------------------------------------\r\n\r\n# # 去掉temp视频音轨\r\n# !ffmpeg -i temp.mp4 -c:v copy -an temp_new.mp4 \r\n# # 给视频加背景音乐\r\n# !ffmpeg -i temp_new.mp4 -i nb.mp3 -t 52 -y last.mp4",
"_____no_output_____"
]
]
]
| [
"markdown",
"code",
"markdown",
"code"
]
| [
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
]
|
cb606288dd2732fd4180138fabf1d6a9a84d4771 | 453,578 | ipynb | Jupyter Notebook | monte-carlo/Monte_Carlo_Solution.ipynb | its-robotics-ai/rl_exercise | 688aa9bcc4992890138daa432cc60cf8ef623bcc | [
"MIT"
]
| 1 | 2022-02-17T14:15:14.000Z | 2022-02-17T14:15:14.000Z | monte-carlo/Monte_Carlo_Solution.ipynb | its-robotics-ai/rl_exercise | 688aa9bcc4992890138daa432cc60cf8ef623bcc | [
"MIT"
]
| null | null | null | monte-carlo/Monte_Carlo_Solution.ipynb | its-robotics-ai/rl_exercise | 688aa9bcc4992890138daa432cc60cf8ef623bcc | [
"MIT"
]
| null | null | null | 884.167641 | 216,132 | 0.948728 | [
[
[
"# Monte Carlo Methods\n\nIn this notebook, you will write your own implementations of many Monte Carlo (MC) algorithms. \n\nWhile we have provided some starter code, you are welcome to erase these hints and write your code from scratch.\n\n### Part 0: Explore BlackjackEnv\n\nWe begin by importing the necessary packages.",
"_____no_output_____"
]
],
[
[
"import sys\nimport gym\nimport numpy as np\nfrom collections import defaultdict\n\nfrom plot_utils import plot_blackjack_values, plot_policy",
"_____no_output_____"
]
],
[
[
"Use the code cell below to create an instance of the [Blackjack](https://github.com/openai/gym/blob/master/gym/envs/toy_text/blackjack.py) environment.",
"_____no_output_____"
]
],
[
[
"env = gym.make('Blackjack-v1')",
"_____no_output_____"
]
],
[
[
"Each state is a 3-tuple of:\n- the player's current sum $\\in \\{0, 1, \\ldots, 31\\}$,\n- the dealer's face up card $\\in \\{1, \\ldots, 10\\}$, and\n- whether or not the player has a usable ace (`no` $=0$, `yes` $=1$).\n\nThe agent has two potential actions:\n\n```\n STICK = 0\n HIT = 1\n```\nVerify this by running the code cell below.",
"_____no_output_____"
]
],
[
[
"print(env.observation_space)\nprint(env.action_space)",
"Tuple(Discrete(32), Discrete(11), Discrete(2))\nDiscrete(2)\n"
]
],
[
[
"Execute the code cell below to play Blackjack with a random policy. \n\n(_The code currently plays Blackjack three times - feel free to change this number, or to run the cell multiple times. The cell is designed for you to get some experience with the output that is returned as the agent interacts with the environment._)",
"_____no_output_____"
]
],
[
[
"for i_episode in range(3):\n state = env.reset()\n while True:\n print(state)\n action = env.action_space.sample()\n state, reward, done, info = env.step(action)\n if done:\n print('End game! Reward: ', reward)\n print('You won :)\\n') if reward > 0 else print('You lost :(\\n')\n break",
"(20, 10, False)\nEnd game! Reward: -1.0\nYou lost :(\n\n(16, 10, False)\n(17, 10, False)\nEnd game! Reward: 0.0\nYou lost :(\n\n(4, 10, False)\n(14, 10, False)\nEnd game! Reward: -1.0\nYou lost :(\n\n"
]
],
[
[
"### Part 1: MC Prediction\n\nIn this section, you will write your own implementation of MC prediction (for estimating the action-value function). \n\nWe will begin by investigating a policy where the player _almost_ always sticks if the sum of her cards exceeds 18. In particular, she selects action `STICK` with 80% probability if the sum is greater than 18; and, if the sum is 18 or below, she selects action `HIT` with 80% probability. The function `generate_episode_from_limit_stochastic` samples an episode using this policy. \n\nThe function accepts as **input**:\n- `bj_env`: This is an instance of OpenAI Gym's Blackjack environment.\n\nIt returns as **output**:\n- `episode`: This is a list of (state, action, reward) tuples (of tuples) and corresponds to $(S_0, A_0, R_1, \\ldots, S_{T-1}, A_{T-1}, R_{T})$, where $T$ is the final time step. In particular, `episode[i]` returns $(S_i, A_i, R_{i+1})$, and `episode[i][0]`, `episode[i][1]`, and `episode[i][2]` return $S_i$, $A_i$, and $R_{i+1}$, respectively.",
"_____no_output_____"
]
],
[
[
"def generate_episode_from_limit_stochastic(bj_env):\n episode = []\n state = bj_env.reset()\n while True:\n probs = [0.8, 0.2] if state[0] > 18 else [0.2, 0.8]\n action = np.random.choice(np.arange(2), p=probs)\n next_state, reward, done, info = bj_env.step(action)\n episode.append((state, action, reward))\n state = next_state\n if done:\n break\n return episode",
"_____no_output_____"
]
],
[
[
"Execute the code cell below to play Blackjack with the policy. \n\n(*The code currently plays Blackjack three times - feel free to change this number, or to run the cell multiple times. The cell is designed for you to gain some familiarity with the output of the `generate_episode_from_limit_stochastic` function.*)",
"_____no_output_____"
]
],
[
[
"for i in range(5):\n print(generate_episode_from_limit_stochastic(env))",
"[((20, 6, False), 0, 1.0)]\n[((19, 2, False), 0, -1.0)]\n[((19, 2, False), 0, 1.0)]\n[((8, 7, False), 1, 0.0), ((18, 7, False), 0, 0.0)]\n[((14, 10, True), 1, 0.0), ((14, 10, False), 1, -1.0)]\n"
]
],
[
[
"Now, you are ready to write your own implementation of MC prediction. Feel free to implement either first-visit or every-visit MC prediction; in the case of the Blackjack environment, the techniques are equivalent.\n\nYour algorithm has three 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- `generate_episode`: This is a function that returns an episode of interaction.\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`.",
"_____no_output_____"
]
],
[
[
"def mc_prediction_q(env, num_episodes, generate_episode, gamma=1.0):\n # initialize empty dictionaries of arrays\n returns_sum = defaultdict(lambda: np.zeros(env.action_space.n))\n N = defaultdict(lambda: np.zeros(env.action_space.n))\n Q = defaultdict(lambda: np.zeros(env.action_space.n))\n # loop over episodes\n for i_episode in range(1, num_episodes+1):\n # monitor progress\n if i_episode % 1000 == 0:\n print(\"\\rEpisode {}/{}.\".format(i_episode, num_episodes), end=\"\")\n sys.stdout.flush()\n # generate an episode\n episode = generate_episode(env)\n # obtain the states, actions, and rewards\n states, actions, rewards = zip(*episode)\n # prepare for discounting\n discounts = np.array([gamma**i for i in range(len(rewards)+1)])\n # update the sum of the returns, number of visits, and action-value \n # function estimates for each state-action pair in the episode\n\n for i, state in enumerate(states):\n returns_sum[state][actions[i]] += sum(rewards[i:]*discounts[:-(1+i)])\n N[state][actions[i]] += 1.0\n Q[state][actions[i]] = returns_sum[state][actions[i]] / N[state][actions[i]]\n return Q",
"_____no_output_____"
]
],
[
[
"Use the cell below to obtain the action-value function estimate $Q$. We have also plotted the corresponding state-value function.\n\nTo check the accuracy of your implementation, compare the plot below to the corresponding plot in the solutions notebook **Monte_Carlo_Solution.ipynb**.",
"_____no_output_____"
]
],
[
[
"# obtain the action-value function\nQ = mc_prediction_q(env, 500000, generate_episode_from_limit_stochastic)\n\n# obtain the corresponding state-value function\nV_to_plot = dict((k,(k[0]>18)*(np.dot([0.8, 0.2],v)) + (k[0]<=18)*(np.dot([0.2, 0.8],v))) \\\n for k, v in Q.items())\n\n# plot the state-value function\nplot_blackjack_values(V_to_plot)",
"Episode 500000/500000."
]
],
[
[
"### Part 2: MC Control\n\nIn this section, you will write your own implementation of constant-$\\alpha$ MC control. \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- `policy`: This is a dictionary where `policy[s]` returns the action that the agent chooses after observing state `s`.\n\n(_Feel free to define additional functions to help you to organize your code._)",
"_____no_output_____"
]
],
[
[
"def generate_episode_from_Q(env, Q, epsilon, nA):\n \"\"\" generates an episode from following the epsilon-greedy policy \"\"\"\n episode = []\n state = env.reset()\n while True:\n action = np.random.choice(np.arange(nA), p=get_probs(Q[state], epsilon, nA)) \\\n if state in Q else env.action_space.sample()\n next_state, reward, done, info = env.step(action)\n episode.append((state, action, reward))\n state = next_state\n if done:\n break\n return episode\n\ndef get_probs(Q_s, epsilon, nA):\n \"\"\" obtains the action probabilities corresponding to epsilon-greedy policy \"\"\"\n policy_s = np.ones(nA) * epsilon / nA\n best_a = np.argmax(Q_s)\n policy_s[best_a] = 1 - epsilon + (epsilon / nA)\n return policy_s\n\ndef update_Q(env, episode, Q, alpha, gamma):\n \"\"\" updates the action-value function estimate using the most recent episode \"\"\"\n states, actions, rewards = zip(*episode)\n # prepare for discounting\n discounts = np.array([gamma**i for i in range(len(rewards)+1)])\n for i, state in enumerate(states):\n old_Q = Q[state][actions[i]] \n Q[state][actions[i]] = old_Q + alpha*(sum(rewards[i:]*discounts[:-(1+i)]) - old_Q)\n return Q",
"_____no_output_____"
],
[
"def mc_control(env, num_episodes, alpha, gamma=1.0, eps_start=1.0, eps_decay=.99999, eps_min=0.05):\n nA = env.action_space.n\n # initialize empty dictionary of arrays\n Q = defaultdict(lambda: np.zeros(nA))\n epsilon = eps_start\n # loop over episodes\n for i_episode in range(1, num_episodes+1):\n # monitor progress\n if i_episode % 1000 == 0:\n print(\"\\rEpisode {}/{}.\".format(i_episode, num_episodes), end=\"\")\n sys.stdout.flush()\n # set the value of epsilon\n epsilon = max(epsilon*eps_decay, eps_min)\n # generate an episode by following epsilon-greedy policy\n episode = generate_episode_from_Q(env, Q, epsilon, nA)\n # update the action-value function estimate using the episode\n Q = update_Q(env, episode, Q, alpha, gamma)\n # determine the policy corresponding to the final action-value function estimate\n policy = dict((k,np.argmax(v)) for k, v in Q.items())\n return policy, Q",
"_____no_output_____"
]
],
[
[
"Use the cell below to obtain the estimated optimal policy and action-value function. Note that you should fill in your own values for the `num_episodes` and `alpha` parameters.",
"_____no_output_____"
]
],
[
[
"# obtain the estimated optimal policy and action-value function\npolicy, Q = mc_control(env, 500000, 0.02)",
"Episode 500000/500000."
]
],
[
[
"Next, we plot the corresponding state-value function.",
"_____no_output_____"
]
],
[
[
"# obtain the corresponding state-value function\nV = dict((k,np.max(v)) for k, v in Q.items())\n\n# plot the state-value function\nplot_blackjack_values(V)",
"_____no_output_____"
]
],
[
[
"Finally, we visualize the policy that is estimated to be optimal.",
"_____no_output_____"
]
],
[
[
"# plot the policy\nplot_policy(policy)",
"_____no_output_____"
]
],
[
[
"The **true** optimal policy $\\pi_*$ can be found in Figure 5.2 of the [textbook](http://go.udacity.com/rl-textbook) (and appears below). Compare your final estimate to the optimal policy - how close are you able to get? If you are not happy with the performance of your algorithm, take the time to tweak the decay rate of $\\epsilon$, change the value of $\\alpha$, and/or run the algorithm for more episodes to attain better results.\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",
"code",
"markdown"
]
| [
[
"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"
],
[
"markdown"
]
]
|
cb607166c7306f6127801b3a9864a56f2dc28e75 | 293,154 | ipynb | Jupyter Notebook | notebooks/Omics_terms.ipynb | NehaKoppikar/multi-omics-state-of-the-field | b1296c3f487a5f37374d069c5151370f491b780c | [
"MIT"
]
| 10 | 2020-12-13T13:25:02.000Z | 2021-11-19T07:10:58.000Z | notebooks/Omics_terms.ipynb | NehaKoppikar/multi-omics-state-of-the-field | b1296c3f487a5f37374d069c5151370f491b780c | [
"MIT"
]
| 2 | 2020-09-27T21:42:33.000Z | 2020-12-10T10:40:10.000Z | notebooks/Omics_terms.ipynb | NehaKoppikar/multi-omics-state-of-the-field | b1296c3f487a5f37374d069c5151370f491b780c | [
"MIT"
]
| 7 | 2020-09-28T06:09:03.000Z | 2022-03-14T13:04:40.000Z | 82.999434 | 55,183 | 0.784223 | [
[
[
"**Aims**:\n - extract the omics mentioned in multi-omics articles\n\n**NOTE**: the articles not in PMC/with no full text need to be analysed separately, or at least highlighted.",
"_____no_output_____"
]
],
[
[
"%run notebook_setup.ipynb",
"_____no_output_____"
],
[
"import pandas\npandas.set_option('display.max_colwidth', 100)",
"_____no_output_____"
],
[
"%vault from pubmed_derived_data import literature, literature_subjects",
"_____no_output_____"
],
[
"literature['title_abstract_text_subjects'] = (\n literature['title']\n + ' ' + literature['abstract_clean'].fillna('')\n + ' ' + literature_subjects.apply(lambda x: ' '.join(x[x == True].index), axis=1)\n + ' ' + literature['full_text'].fillna('')\n)",
"_____no_output_____"
],
[
"omics_features = literature.index.to_frame().drop(columns='uid').copy()",
"_____no_output_____"
],
[
"from functools import partial\nfrom helpers.text_processing import check_usage\nfrom pandas import Series\n\ncheck_usage_in_input = partial(\n check_usage,\n data=literature,\n column='title_abstract_text_subjects',\n limit=5 # show only first 5 results\n)",
"_____no_output_____"
],
[
"TERM_IN_AT_LEAST_N_ARTICLES = 5",
"_____no_output_____"
]
],
[
[
"# Omics",
"_____no_output_____"
],
[
"## 1. Lookup by words which end with -ome",
"_____no_output_____"
]
],
[
[
"cellular_structures = {\n # organelles\n 'peroxisome',\n 'proteasome',\n 'ribosome',\n 'exosome',\n 'nucleosome',\n 'polysome',\n 'autosome',\n 'autophagosome',\n 'endosome',\n 'lysosome',\n # proteins and molecular complexes\n 'spliceosome',\n 'cryptochrome',\n # chromosmes\n 'autosome',\n 'chromosome',\n 'x-chromosome',\n 'y-chromosome',\n}\n\nspecies = {\n 'trichome'\n}\n\ntools_and_methods = {\n # dry lab\n 'dphenome',\n 'dgenome',\n 'reactome',\n 'rexposome',\n 'phytozome',\n 'rgenome',\n 'igenome', # iGenomes\n # wet lab\n 'microtome'\n}",
"_____no_output_____"
],
[
"not_an_ome = {\n 'outcome',\n 'middle-income',\n 'welcome',\n 'wellcome', # :)\n 'chrome',\n 'some',\n 'cumbersome',\n 'become',\n 'home',\n 'come',\n 'overcome',\n 'cytochrome',\n 'syndrome',\n 'ubiome',\n 'biome', # this IS an ome, but more into envrionmental studies, rather than molecular biology!\n 'fluorochrome',\n 'post-genome',\n 'ubiquitin-proteasome', # UPS\n *tools_and_methods,\n *cellular_structures,\n *species\n}",
"_____no_output_____"
],
[
"from omics import get_ome_regexp\nome_re = get_ome_regexp()\nget_ome_regexp??",
"_____no_output_____"
],
[
"ome_occurrences = (\n literature['title_abstract_text_subjects'].str.lower()\n .str.extractall(ome_re)[0]\n .to_frame('term').reset_index()\n)\nome_occurrences = ome_occurrences[~ome_occurrences.term.isin(not_an_ome)]\nome_occurrences.head(3)",
"_____no_output_____"
]
],
[
[
"### 1.1 Harmonise hyphenation",
"_____no_output_____"
]
],
[
[
"from helpers.text_processing import report_hyphenation_trends, harmonise_hyphenation",
"_____no_output_____"
],
[
"hyphenation_rules = report_hyphenation_trends(ome_occurrences.term)\nhyphenation_rules",
"_____no_output_____"
],
[
"ome_occurrences.term = harmonise_hyphenation(ome_occurrences.term, hyphenation_rules)",
"_____no_output_____"
]
],
[
[
"### 1.2 Fix typos",
"_____no_output_____"
]
],
[
[
"from helpers.text_processing import find_term_typos, create_typos_map",
"_____no_output_____"
],
[
"ome_counts = ome_occurrences.drop_duplicates(['uid', 'term']).term.sorted_value_counts()\npotential_ome_typos = find_term_typos(ome_counts, TERM_IN_AT_LEAST_N_ARTICLES - 1)\npotential_ome_typos",
"_____no_output_____"
],
[
"check_usage_in_input('1-metabolome')",
"_____no_output_____"
],
[
"check_usage_in_input('miRNAome')",
"_____no_output_____"
],
[
"check_usage_in_input('miRome')",
"_____no_output_____"
],
[
"check_usage_in_input('rexposome')",
"_____no_output_____"
],
[
"check_usage_in_input('glycol-proteome')",
"_____no_output_____"
],
[
"check_usage_in_input('rgenome')",
"_____no_output_____"
],
[
"check_usage_in_input('iGenomes')",
"_____no_output_____"
],
[
"check_usage_in_input('cancergenome')",
"_____no_output_____"
],
[
"is_typo_subset_or_variant = {\n ('transcritome', 'transcriptome'): True,\n ('transciptome', 'transcriptome'): True,\n ('tanscriptome', 'transcriptome'): True,\n ('trascriptome', 'transcriptome'): True,\n ('microbome', 'microbiome'): True,\n ('protenome', 'proteome'): True,\n # (neither n- nor o- is frequent enough on its own)\n ('o-glycoproteome', 'glycoproteome'): True,\n ('n-glycoproteome', 'glycoproteome'): True,\n ('glycol-proteome', 'glycoproteome'): True, # note \"glycol\" instead of \"glyco\"\n ('mirome', 'mirnome'): True,\n ('1-metabolome', 'metabolome'): True\n}\nome_typos_map = create_typos_map(potential_ome_typos, is_typo_subset_or_variant)",
"_____no_output_____"
],
[
"replaced = ome_occurrences.term[ome_occurrences.term.isin(ome_typos_map)]\nreplaced.value_counts()",
"_____no_output_____"
],
[
"len(replaced)",
"_____no_output_____"
],
[
"ome_occurrences.term = ome_occurrences.term.replace(ome_typos_map)",
"_____no_output_____"
]
],
[
[
"### 1.3 Replace synonymous and narrow terms",
"_____no_output_____"
]
],
[
[
"ome_replacements = {}",
"_____no_output_____"
]
],
[
[
"#### miRNAomics → miRNomics",
"_____no_output_____"
],
[
"miRNAome is more popular name for -ome, while miRNomics is more popular for -omics.",
"_____no_output_____"
]
],
[
[
"ome_occurrences.term.value_counts().loc[['mirnome', 'mirnaome']]",
"_____no_output_____"
]
],
[
[
"As I use -omcis for later on, for consistency I will change miRNAome → miRNome",
"_____no_output_____"
]
],
[
[
"ome_replacements['miRNAome'] = 'miRNome'",
"_____no_output_____"
]
],
[
[
"#### Cancer genome → genome",
"_____no_output_____"
]
],
[
[
"ome_occurrences.term.value_counts().loc[['genome', 'cancer-genome']]",
"_____no_output_____"
],
[
"ome_replacements['cancer-genome'] = 'genome'",
"_____no_output_____"
]
],
[
[
"#### Host microbiome → microbiome",
"_____no_output_____"
]
],
[
[
"ome_occurrences.term.value_counts().loc[['microbiome', 'host-microbiome']]",
"_____no_output_____"
],
[
"ome_replacements['host-microbiome'] = 'microbiome'",
"_____no_output_____"
]
],
[
[
"#### Replace the values",
"_____no_output_____"
]
],
[
[
"ome_occurrences.term = ome_occurrences.term.replace(\n {k.lower(): v.lower() for k, v in ome_replacements.items()}\n)",
"_____no_output_____"
]
],
[
[
"### 1.4 Summarise popular \\*ome terms",
"_____no_output_____"
]
],
[
[
"ome_counts = ome_occurrences.drop_duplicates(['uid', 'term']).term.sorted_value_counts()\nome_common_counts = ome_counts[ome_counts >= TERM_IN_AT_LEAST_N_ARTICLES]\nome_common_counts",
"_____no_output_____"
],
[
"ome_common_terms = Series(ome_common_counts.index)\nome_common_terms[ome_common_terms.str.endswith('some')]",
"_____no_output_____"
]
],
[
[
"### 2. Lookup by omics and adjectives",
"_____no_output_____"
]
],
[
[
"from omics import get_omics_regexp\n\nomics_re = get_omics_regexp()\nget_omics_regexp??",
"_____no_output_____"
],
[
"check_usage_in_input('integromics')",
"_____no_output_____"
],
[
"check_usage_in_input('meta-omics')",
"_____no_output_____"
],
[
"check_usage_in_input('post-genomic')",
"_____no_output_____"
],
[
"check_usage_in_input('3-omics')",
"_____no_output_____"
],
[
"multi_omic = {\n 'multi-omic',\n 'muti-omic',\n 'mutli-omic',\n 'multiomic',\n 'cross-omic',\n 'panomic',\n 'pan-omic',\n 'trans-omic',\n 'transomic',\n 'four-omic',\n 'multiple-omic',\n 'inter-omic',\n 'poly-omic',\n 'polyomic',\n 'integromic',\n 'integrated-omic',\n 'integrative-omic',\n '3-omic'\n}\n\ntools = {\n # MixOmics\n 'mixomic',\n # MetaRbolomics\n 'metarbolomic',\n # MinOmics\n 'minomic',\n # LinkedOmics - TCGA portal\n 'linkedomic',\n # Mergeomics - https://doi.org/10.1186/s12864-016-3198-9\n 'mergeomic'\n}\n\nvague = {\n 'single-omic'\n}\n\nadjectives = {\n 'economic',\n 'socio-economic',\n 'socioeconomic',\n 'taxonomic',\n 'syndromic',\n 'non-syndromic',\n 'agronomic',\n 'anatomic',\n 'autonomic',\n 'atomic',\n 'palindromic',\n # temporal\n 'postgenomic',\n 'post-genomic'\n}\n\nnot_an_omic = {\n 'non-omic', # this on was straightforward :)\n *adjectives,\n *multi_omic,\n *tools,\n *vague\n}",
"_____no_output_____"
],
[
"omic_occurrences = (\n literature['title_abstract_text_subjects'].str.lower()\n .str.extractall(omics_re)[0]\n .to_frame('term').reset_index()\n)\nomic_occurrences = omic_occurrences[~omic_occurrences.term.isin(not_an_omic)]\nomic_occurrences.head(2)",
"_____no_output_____"
]
],
[
[
"### 2.1 Harmonise hyphenation",
"_____no_output_____"
]
],
[
[
"hyphenation_rules = report_hyphenation_trends(omic_occurrences.term)\nhyphenation_rules",
"_____no_output_____"
],
[
"omic_occurrences.term = harmonise_hyphenation(omic_occurrences.term, hyphenation_rules)",
"_____no_output_____"
]
],
[
[
"### 2.2 Fix typos",
"_____no_output_____"
]
],
[
[
"omic_counts = omic_occurrences.drop_duplicates(['uid', 'term']).term.sorted_value_counts()\npotential_omic_typos = find_term_typos(omic_counts, TERM_IN_AT_LEAST_N_ARTICLES - 1)\npotential_omic_typos",
"_____no_output_____"
],
[
"check_usage_in_input('non-omic')",
"_____no_output_____"
],
[
"check_usage_in_input('C-metabolomics')",
"_____no_output_____"
]
],
[
[
"Not captured in the text abstract, but full version has 13C, so carbon-13, so type of metabolomics.",
"_____no_output_____"
]
],
[
[
"check_usage_in_input('miRNAomics')",
"_____no_output_____"
],
[
"check_usage_in_input('miRomics')",
"_____no_output_____"
],
[
"check_usage_in_input('MinOmics')",
"_____no_output_____"
],
[
"check_usage_in_input('onomic', words=True)",
"_____no_output_____"
],
[
"literature.loc[omic_occurrences[omic_occurrences.term == 'onomic'].uid].title_abstract_text_subjects",
"_____no_output_____"
],
[
"check_usage_in_input(r'\\bonomic', words=False, highlight=' onomic')",
"_____no_output_____"
],
[
"check_usage_in_input(' ionomic', words=False)",
"_____no_output_____"
],
[
"check_usage_in_input('integratomic', words=False)",
"_____no_output_____"
]
],
[
[
"Note: integratomics has literally three hits in PubMed, two because of http://www.integratomics-time.com/",
"_____no_output_____"
]
],
[
[
"is_typo_subset_or_variant = {\n ('phoshphoproteomic', 'phosphoproteomic'): True,\n ('transriptomic', 'transcriptomic'): True,\n ('transcripomic', 'transcriptomic'): True,\n ('transciptomic', 'transcriptomic'): True,\n ('trancriptomic', 'transcriptomic'): True,\n ('trascriptomic', 'transcriptomic'): True,\n ('metageonomic', 'metagenomic'): True,\n ('metaobolomic', 'metabolomic'): True,\n ('metabotranscriptomic', 'metatranscriptomic'): False,\n ('mirnaomic', 'mirnomic'): True,\n ('metranscriptomic', 'metatranscriptomic'): True,\n ('metranscriptomic', 'transcriptomic'): False,\n ('miromic', 'mirnomic'): True,\n ('n-glycoproteomic', 'glycoproteomic'): True,\n ('onomic', 'ionomic'): False,\n ('c-metabolomic', 'metabolomic'): True,\n ('integratomic', 'interactomic'): False,\n ('pharmacoepigenomic', 'pharmacogenomic'): False,\n ('metobolomic', 'metabolomic'): True,\n # how to treat single-cell?\n ('scepigenomic', 'epigenomic'): True,\n #('epitranscriptomic', 'transcriptomic'): False\n ('epigenomomic', 'epigenomic'): True,\n}\nomic_typos_map = create_typos_map(potential_omic_typos, is_typo_subset_or_variant)",
"_____no_output_____"
],
[
"replaced = omic_occurrences.term[omic_occurrences.term.isin(omic_typos_map)]\nreplaced.value_counts()",
"_____no_output_____"
],
[
"len(replaced)",
"_____no_output_____"
],
[
"omic_occurrences.term = omic_occurrences.term.replace(omic_typos_map)",
"_____no_output_____"
]
],
[
[
"### 2.3 Popular *omic(s) terms:",
"_____no_output_____"
]
],
[
[
"omic_counts = omic_occurrences.drop_duplicates(['uid', 'term']).term.sorted_value_counts()\nomic_counts[omic_counts >= TERM_IN_AT_LEAST_N_ARTICLES].add_suffix('s')",
"_____no_output_____"
]
],
[
[
"### Crude overview",
"_____no_output_____"
]
],
[
[
"ome_terms = Series(ome_counts[ome_counts >= TERM_IN_AT_LEAST_N_ARTICLES].index)\nomic_terms = Series(omic_counts[omic_counts >= TERM_IN_AT_LEAST_N_ARTICLES].index)",
"_____no_output_____"
],
[
"assert omics_features.index.name == 'uid'\n\nfor term in ome_terms:\n mentioned_by_uid = set(ome_occurrences[ome_occurrences.term == term].uid)\n omics_features['mentions_' + term] = omics_features.index.isin(mentioned_by_uid)\n\nfor term in omic_terms:\n mentioned_by_uid = set(omic_occurrences[omic_occurrences.term == term].uid)\n omics_features['mentions_' + term] = omics_features.index.isin(mentioned_by_uid)",
"_____no_output_____"
],
[
"from helpers.text_processing import prefix_remover\n\nome_terms_mentioned = omics_features['mentions_' + ome_terms].rename(columns=prefix_remover('mentions_'))\nomic_terms_mentioned = omics_features['mentions_' + omic_terms].rename(columns=prefix_remover('mentions_'))",
"_____no_output_____"
],
[
"%R library(ComplexUpset);",
"_____no_output_____"
],
[
"%%R -i ome_terms_mentioned -w 800 -r 100\n\nupset(ome_terms_mentioned, colnames(ome_terms_mentioned), min_size=10, width_ratio=0.1)",
"[1] \"Dropping 22 empty groups\"\n"
]
],
[
[
"## Merge -ome and -omic terms",
"_____no_output_____"
]
],
[
[
"from warnings import warn\n\nterms_associated_with_omic = {\n omic + 's': [omic]\n for omic in omic_terms\n}\n\nfor ome in ome_terms:\n assert ome.endswith('ome')\n auto_generate_omic_term = ome[:-3] + 'omics'\n omic = auto_generate_omic_term\n if omic not in terms_associated_with_omic:\n if omic in omic_counts.index:\n warn(f'{omic} was removed at thresholding, but it is a frequent -ome!')\n else:\n print(f'Creating omic {omic}')\n terms_associated_with_omic[omic] = []\n\n terms_associated_with_omic[omic].append(ome)",
"Creating omic whole-genomics\nCreating omic exomics\nCreating omic whole-exomics\nCreating omic exposomics\nCreating omic whole-transcriptomics\nCreating omic translatomics\nCreating omic regulomics\nCreating omic immunomics\nCreating omic degradomics\nCreating omic pan-genomics\nCreating omic kinomics\nCreating omic mycobiomics\n"
],
[
"from omics import add_entities_to_features\n\n\nadd_entities_to_omic_features = partial(\n add_entities_to_features,\n features=omics_features,\n omics_terms=terms_associated_with_omic\n)",
"_____no_output_____"
],
[
"omics = {k: [k] for k in terms_associated_with_omic}\nadd_entities_to_omic_features(omics, entity_type='ome_or_omic')",
"_____no_output_____"
],
[
"from omics import omics_by_entity, omics_by_entity_group",
"_____no_output_____"
]
],
[
[
"interactomics is a proper \"omics\", but it is difficult to assign to a single entity - by definition",
"_____no_output_____"
]
],
[
[
"check_usage_in_input('interactomics')",
"_____no_output_____"
]
],
[
[
"phylogenomics is not an omic on its own, but if used in context of metagenomics it can refer to actual omics data",
"_____no_output_____"
]
],
[
[
"check_usage_in_input('phylogenomics')",
"_____no_output_____"
]
],
[
[
"regulomics is both a name of a tool, group (@MIM UW), and omics:",
"_____no_output_____"
]
],
[
[
"check_usage_in_input('regulomics')",
"_____no_output_____"
],
[
"from functools import reduce\nomics_mapped_to_entities = reduce(set.union, omics_by_entity.values())\nset(terms_associated_with_omic) - omics_mapped_to_entities",
"_____no_output_____"
],
[
"assert omics_mapped_to_entities - set(terms_associated_with_omic) == set()",
"_____no_output_____"
],
[
"omics_mapped_to_entities_groups = reduce(set.union, omics_by_entity_group.values())\nset(terms_associated_with_omic) - omics_mapped_to_entities_groups",
"_____no_output_____"
],
[
"add_entities_to_omic_features(omics_by_entity, entity_type='entity')",
"_____no_output_____"
],
[
"add_entities_to_omic_features(omics_by_entity_group, entity_type='entity_group')",
"_____no_output_____"
]
],
[
[
"### Visualize the entities & entities groups",
"_____no_output_____"
]
],
[
[
"omic_entities = omics_features['entity_' + Series(list(omics_by_entity.keys()))].rename(columns=prefix_remover('entity_'))\nomic_entities_groups = omics_features['entity_group_' + Series(list(omics_by_entity_group.keys()))].rename(columns=prefix_remover('entity_group_'))",
"_____no_output_____"
],
[
"%%R -i omic_entities -w 800 -r 100\n\nupset(omic_entities, colnames(omic_entities), min_size=10, width_ratio=0.1)",
"_____no_output_____"
],
[
"%%R -i omic_entities_groups -w 800 -r 100\n\nupset(omic_entities_groups, colnames(omic_entities_groups), min_size=10, width_ratio=0.1)",
"_____no_output_____"
]
],
[
[
"### Number of omics mentioned in abstract vs the multi-omic term used",
"_____no_output_____"
]
],
[
[
"omes_or_omics_df = omics_features['ome_or_omic_' + Series(list(omics.keys()))].rename(columns=prefix_remover('ome_or_omic_'))",
"_____no_output_____"
],
[
"literature['omic_terms_detected'] = omes_or_omics_df.sum(axis=1)",
"_____no_output_____"
],
[
"lt = literature[['term', 'omic_terms_detected']]",
"_____no_output_____"
],
[
"literature.sort_values('omic_terms_detected', ascending=False)[['title', 'omic_terms_detected']].head(10)",
"_____no_output_____"
],
[
"%%R -i lt -w 800\n(\n ggplot(lt, aes(x=term, y=omic_terms_detected))\n + geom_violin(adjust=2)\n + geom_point()\n + theme_bw()\n)",
"_____no_output_____"
],
[
"%vault store omics_features in pubmed_derived_data",
"_____no_output_____"
]
],
[
[
"# Current limitations",
"_____no_output_____"
],
[
"## Patchy coverage",
"_____no_output_____"
],
[
"Currently I only detected omic-describing terms in less than 70% of abstracts:",
"_____no_output_____"
]
],
[
[
"omic_entities.any(axis=1).mean()",
"_____no_output_____"
]
],
[
[
"Potential solution: select a random sample of 50 articles, annotate manually, calculate sensitivity and specificity.\n\nIf any omic is consistently omitted, reconsider how search terms are created.",
"_____no_output_____"
],
[
"## Apostrophes",
"_____no_output_____"
],
[
"Are we missing out on \\*'omic terms, such us meta'omic used in [here](https://doi.org/10.1053/j.gastro.2014.01.049)?",
"_____no_output_____"
]
],
[
[
"check_usage_in_input(\n r'\\w+\\'omic',\n words=False,\n highlight='\\'omic'\n)",
"_____no_output_____"
]
],
[
[
"unlikely (but would be nice to get it in!)",
"_____no_output_____"
],
[
"## Fields of study",
"_____no_output_____"
]
],
[
[
"'genetics', 'epigenetics'",
"_____no_output_____"
]
],
[
[
"Some authors may prefer to say \"we integrated genetic and proteomic data\" rather than \"genomic and proteomic\"",
"_____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"
]
| [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
]
|
cb607ab181af1239ce3c12864343055adadc5a4a | 667 | ipynb | Jupyter Notebook | book_bayes-stats-the-fun-way/00_notes_book_bayes-stats-the-fun-way.ipynb | pydatawrangler/biwp | da8b504b98d1210499a3463b521680376b5163a8 | [
"MIT"
]
| null | null | null | book_bayes-stats-the-fun-way/00_notes_book_bayes-stats-the-fun-way.ipynb | pydatawrangler/biwp | da8b504b98d1210499a3463b521680376b5163a8 | [
"MIT"
]
| null | null | null | book_bayes-stats-the-fun-way/00_notes_book_bayes-stats-the-fun-way.ipynb | pydatawrangler/biwp | da8b504b98d1210499a3463b521680376b5163a8 | [
"MIT"
]
| null | null | null | 18.527778 | 115 | 0.565217 | [
[
[
"# Bayesian Statistics the Fun Way",
"_____no_output_____"
],
[
"## Link to Book\n[Bayesian Statistics the Fun Way](https://nostarch.com/learnbayes)",
"_____no_output_____"
],
[
"## Link to Solutions to Exercises\n[solutions to the book's exercises](https://nostarch.com/download/resources/Bayes_exercise_solutions_new.pdf)",
"_____no_output_____"
]
]
]
| [
"markdown"
]
| [
[
"markdown",
"markdown",
"markdown"
]
]
|
cb6094245129c764907c25904fcbf038dc65af6b | 5,917 | ipynb | Jupyter Notebook | AoC 2019/AoC 2019 - Day 04.ipynb | RubenFixit/AoC | af042a5d6ca230a767862b471400275d2258a116 | [
"MIT"
]
| null | null | null | AoC 2019/AoC 2019 - Day 04.ipynb | RubenFixit/AoC | af042a5d6ca230a767862b471400275d2258a116 | [
"MIT"
]
| null | null | null | AoC 2019/AoC 2019 - Day 04.ipynb | RubenFixit/AoC | af042a5d6ca230a767862b471400275d2258a116 | [
"MIT"
]
| null | null | null | 35.011834 | 317 | 0.560588 | [
[
[
"# [Advent of Code 2019: Day 4](https://adventofcode.com/2019/day/4)",
"_____no_output_____"
],
[
"<h2>--- Day 4: Secure Container ---</h2><p>You arrive at the Venus fuel depot only to discover it's protected by a password. The Elves had written the password on a sticky note, but someone <span title=\"Look on the bright side - isn't it more secure if nobody knows the password?\">threw it out</span>.</p>\n<p>However, they do remember a few key facts about the password:</p>\n<ul>\n<li>It is a six-digit number.</li>\n<li>The value is within the range given in your puzzle input.</li>\n<li>Two adjacent digits are the same (like <code>22</code> in <code>1<em>22</em>345</code>).</li>\n<li>Going from left to right, the digits <em>never decrease</em>; they only ever increase or stay the same (like <code>111123</code> or <code>135679</code>).</li>\n</ul>\n<p>Other than the range rule, the following are true:</p>\n<ul>\n<li><code>111111</code> meets these criteria (double <code>11</code>, never decreases).</li>\n<li><code>2234<em>50</em></code> does not meet these criteria (decreasing pair of digits <code>50</code>).</li>\n<li><code>123789</code> does not meet these criteria (no double).</li>\n</ul>\n<p><em>How many different passwords</em> within the range given in your puzzle input meet these criteria?</p>",
"_____no_output_____"
]
],
[
[
"pass_min = 256310\npass_max = 732736\n\nall_possible_pass = range(pass_min+1, pass_max)",
"_____no_output_____"
],
[
"possible_pass = []\n\ndef password_criteria1(password):\n \"\"\" Returns TRUE if the password meets the password criteria given by the elves in part 1 \"\"\"\n previous_digit = '0'\n has_repeat_digit = False\n \n for digit in str(password):\n if digit < previous_digit:\n return False\n if digit == previous_digit:\n has_repeat_digit = True\n else:\n previous_digit = digit\n \n return has_repeat_digit\n\nfor password in all_possible_pass: \n if password_criteria1(password): \n possible_pass.append(password)\n\nprint(f'Part one answer: {len(possible_pass)}')",
"Part one answer: 979\n"
]
],
[
[
"<h2 id=\"part2\">--- Part Two ---</h2><p>An Elf just remembered one more important detail: the two adjacent matching digits <em>are not part of a larger group of matching digits</em>.</p>\n<p>Given this additional criterion, but still ignoring the range rule, the following are now true:</p>\n<ul>\n<li><code>112233</code> meets these criteria because the digits never decrease and all repeated digits are exactly two digits long.</li>\n<li><code>123<em>444</em></code> no longer meets the criteria (the repeated <code>44</code> is part of a larger group of <code>444</code>).</li>\n<li><code>111122</code> meets the criteria (even though <code>1</code> is repeated more than twice, it still contains a double <code>22</code>).</li>\n</ul>\n<p><em>How many different passwords</em> within the range given in your puzzle input meet all of the criteria?</p>\n",
"_____no_output_____"
]
],
[
[
"possible_pass = []\n\ndef password_criteria2(password):\n \"\"\" Returns TRUE if the password meets the password criteria given by the elves in part 1 & 2 \"\"\"\n previous_digit = '0'\n repeat_len = 0\n repeat_len_list = []\n pass_str = str(password)\n for digit in pass_str:\n if digit < previous_digit:\n return False\n \n if digit == previous_digit:\n repeat_len += 1\n \n if (digit > previous_digit):\n if repeat_len > 0:\n repeat_len_list.append(repeat_len+1)\n repeat_len = 0\n \n previous_digit = digit\n \n # I originally forgot to check the repeat_len after the for loop finished\n # Forgetting this took me a long time to figure out why my answer was wrong\n if repeat_len > 0:\n repeat_len_list.append(repeat_len+1)\n \n return (2 in repeat_len_list)\n\nfor password in all_possible_pass: \n if password_criteria2(password): \n possible_pass.append(password)\n \n\nprint(f'Part two answer: {len(possible_pass)}')",
"Part two answer: 635\n"
]
]
]
| [
"markdown",
"code",
"markdown",
"code"
]
| [
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.