hexsha
stringlengths 40
40
| size
int64 6
14.9M
| ext
stringclasses 1
value | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 6
260
| max_stars_repo_name
stringlengths 6
119
| max_stars_repo_head_hexsha
stringlengths 40
41
| max_stars_repo_licenses
sequence | max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 6
260
| max_issues_repo_name
stringlengths 6
119
| max_issues_repo_head_hexsha
stringlengths 40
41
| max_issues_repo_licenses
sequence | max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 6
260
| max_forks_repo_name
stringlengths 6
119
| max_forks_repo_head_hexsha
stringlengths 40
41
| max_forks_repo_licenses
sequence | max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | avg_line_length
float64 2
1.04M
| max_line_length
int64 2
11.2M
| alphanum_fraction
float64 0
1
| cells
sequence | cell_types
sequence | cell_type_groups
sequence |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d07fd01d65d2c509f2c3b131d7d30872dc5b27de | 3,408 | ipynb | Jupyter Notebook | ui.ipynb | sepal-contrib/bfast_gpu | 22214b0277993835f41f07e6646e6e15deecc9d9 | [
"MIT"
] | null | null | null | ui.ipynb | sepal-contrib/bfast_gpu | 22214b0277993835f41f07e6646e6e15deecc9d9 | [
"MIT"
] | null | null | null | ui.ipynb | sepal-contrib/bfast_gpu | 22214b0277993835f41f07e6646e6e15deecc9d9 | [
"MIT"
] | null | null | null | 28.165289 | 120 | 0.589789 | [
[
[
"from sepal_ui import sepalwidgets as sw\nfrom component.message import cm",
"_____no_output_____"
],
[
"# Create an appBar\napp_bar = sw.AppBar(cm.app.title)",
"_____no_output_____"
],
[
"# load the patial files\n%run 'about_ui.ipynb'\n%run 'bfast_ui.ipynb'\n\n# Gather all the partial tiles that you created previously\napp_content = [bfast_tile, map_tile, about_tile, disclaimer_tile]",
"_____no_output_____"
],
[
"# create a drawer for each group of tile\n# use the DrawerItem widget from sepalwidget (name_of_drawer, icon, the id of the widgets you want to display)\n# use the display_tile() method to link the times with the drawer items\nitems = [\n sw.DrawerItem(cm.app.drawer_item.bfast, \"mdi-cogs\", card=\"bfast_tile\"),\n sw.DrawerItem(cm.app.drawer_item.display, \"mdi-map\", card=\"result_tile\"),\n sw.DrawerItem(cm.app.drawer_item.about, \"mdi-help-circle\", card=\"about_tile\"),\n]\n\n# !!! not mandatory !!!\n# Add the links to the code, wiki and issue tracker of your\ncode_link = \"https://github.com/12rambau/bfast_gpu\"\nwiki_link = \"https://docs.sepal.io/en/latest/modules/dwn/bfast_gpu.html\"\nissue_link = \"https://github.com/12rambau/bfast_gpu/issues/new\"\n\n# Create the side drawer with all its components\n# The display_drawer() method link the drawer with the app bar\napp_drawer = sw.NavDrawer(items=items, code=code_link, wiki=wiki_link, issue=issue_link)",
"_____no_output_____"
],
[
"# build the Html final app by gathering everything\napp = sw.App(tiles=app_content, appBar=app_bar, navDrawer=app_drawer).show_tile(\n \"bfast_tile\"\n) # id of the tile you want to display",
"_____no_output_____"
],
[
"# display the app\n# this final cell will be the only one displaying something in this notebook\n# if you run all this notebook you may see elements displayed on the left side of your screen but it won't work\n# it can only be launched with voila as it's creating a full page javascript interface\napp",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d07fda8fef38314751f8a541989b9911810e6142 | 370,012 | ipynb | Jupyter Notebook | c3_single_layer_networks/least_square_method/least_square_method_demo.ipynb | zhihanyang2022/bishop1995_notes | 7d428726b8fb1afac40c13bd43103a5d672ead91 | [
"MIT"
] | 2 | 2021-01-22T08:29:58.000Z | 2021-12-22T02:12:33.000Z | c3_single_layer_networks/least_square_method/least_square_method_demo.ipynb | zhihanyang2022/bishop1995_notes | 7d428726b8fb1afac40c13bd43103a5d672ead91 | [
"MIT"
] | null | null | null | c3_single_layer_networks/least_square_method/least_square_method_demo.ipynb | zhihanyang2022/bishop1995_notes | 7d428726b8fb1afac40c13bd43103a5d672ead91 | [
"MIT"
] | null | null | null | 296.246597 | 95,844 | 0.928881 | [
[
[
"# Least-squares technique",
"_____no_output_____"
],
[
"## References",
"_____no_output_____"
],
[
"- Statistics in geography: https://archive.org/details/statisticsingeog0000ebdo/",
"_____no_output_____"
],
[
"## Imports",
"_____no_output_____"
]
],
[
[
"from functools import partial\nimport numpy as np\nfrom scipy.stats import multivariate_normal, t\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom ipywidgets import interact, IntSlider\n\ninv = np.linalg.inv",
"_____no_output_____"
],
[
"df = pd.read_csv('regression_data.csv')\ndf.head(3)",
"_____no_output_____"
]
],
[
[
"## Population",
"_____no_output_____"
],
[
"0.5 and 0.2 are NOT the population parameters. Although we used them to generate the population, the population parameters can be different from them.",
"_____no_output_____"
]
],
[
[
"def get_y(x):\n ys = x * 0.5 + 0.2\n noises = 1 * np.random.normal(size=len(ys))\n return ys + noises",
"_____no_output_____"
],
[
"np.random.seed(52)\nxs = np.linspace(0, 10, 10000)\nys = get_y(xs)\n\nnp.random.seed(32)\nnp.random.shuffle(xs)\nnp.random.seed(32)\nnp.random.shuffle(ys)",
"_____no_output_____"
],
[
"plt.scatter(xs, ys, s=5)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Design matrices",
"_____no_output_____"
]
],
[
[
"PHI = xs.reshape(-1, 1)\nPHI = np.hstack([\n PHI,\n np.ones(PHI.shape)\n ])\nT = ys.reshape(-1, 1)",
"_____no_output_____"
]
],
[
[
"## Normal equation with regularization",
"_____no_output_____"
]
],
[
[
"def regularized_least_squares(PHI, T, regularizer=0):\n \n assert PHI.shape[0] == T.shape[0]\n \n pseudo_inv = inv(PHI.T @ PHI + np.eye(PHI.shape[1]) * regularizer)\n \n assert pseudo_inv.shape[0] == pseudo_inv.shape[1]\n \n W = pseudo_inv @ PHI.T @ T\n \n return {'slope' : float(W[0]), 'intercept' : float(W[1])}",
"_____no_output_____"
]
],
[
[
"## Sampling distributions",
"_____no_output_____"
],
[
"### Population parameters",
"_____no_output_____"
]
],
[
[
"pop_params = regularized_least_squares(PHI, T)",
"_____no_output_____"
],
[
"pop_slope, pop_intercept = pop_params['slope'], pop_params['intercept']",
"_____no_output_____"
]
],
[
[
"### Sample statistics",
"_____no_output_____"
],
[
"Verify that the sampling distribution for both regression coefficients are normal. ",
"_____no_output_____"
]
],
[
[
"n = 10 # sample size\nnum_samps = 1000",
"_____no_output_____"
],
[
"def sample(PHI, T, n):\n idxs = np.random.randint(PHI.shape[0], size=n)\n return PHI[idxs], T[idxs]",
"_____no_output_____"
],
[
"samp_slopes, samp_intercepts = [], []\nfor i in range(num_samps):\n PHI_samp, T_samp = sample(PHI, T, n)\n learned_param = regularized_least_squares(PHI_samp, T_samp)\n samp_slopes.append(learned_param['slope']); samp_intercepts.append(learned_param['intercept'])",
"_____no_output_____"
],
[
"np.std(samp_slopes), np.std(samp_intercepts)",
"_____no_output_____"
],
[
"fig = plt.figure(figsize=(12, 4))\n\nfig.add_subplot(121)\nsns.kdeplot(samp_slopes)\nplt.title('Sample distribution of sample slopes')\n\nfig.add_subplot(122)\nsns.kdeplot(samp_intercepts)\nplt.title('Sample distribution of sample intercepts')\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"Note that the two normal distributions above are correlated. This means that we need to be careful when plotting the 95% CI for the regression line, because we can't just plot the regression line with the highest slope and the highest intercept and the regression line with the lowest slope and the lowest intercept.",
"_____no_output_____"
]
],
[
[
"sns.jointplot(samp_slopes, samp_intercepts, s=5)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Confidence interval",
"_____no_output_____"
],
[
"**Caution.** The following computation of confidence intervals does not apply to regularized least squares.",
"_____no_output_____"
],
[
"### Sample one sample",
"_____no_output_____"
]
],
[
[
"n = 500\nPHI_samp, T_samp = sample(PHI, T, n)",
"_____no_output_____"
]
],
[
[
"### Compute sample statistics",
"_____no_output_____"
]
],
[
[
"learned_param = regularized_least_squares(PHI_samp, T_samp)",
"_____no_output_____"
],
[
"samp_slope, samp_intercept = learned_param['slope'], learned_param['intercept']",
"_____no_output_____"
],
[
"samp_slope, samp_intercept",
"_____no_output_____"
]
],
[
[
"### Compute standard errors of sample statistics\n\nStandard error is the estimate of the standard deviation of the sampling distribution.",
"_____no_output_____"
],
[
"$$\\hat\\sigma = \\sqrt{\\frac{\\text{Sum of all squared residuals}}{\\text{Degrees of freedom}}}$$",
"_____no_output_____"
],
[
"Standard error for slope:\n$$\\text{SE}(\\hat\\beta_1)=\\hat\\sigma \\sqrt{\\frac{1}{(n-1)s_X^2}}$$",
"_____no_output_____"
],
[
"Standard error for intercept:\n\n$$\\text{SE}(\\hat\\beta_0)=\\hat\\sigma \\sqrt{\\frac{1}{n} + \\frac{\\bar X^2}{(n-1)s_X^2}}$$",
"_____no_output_____"
],
[
"where $\\bar X$ is the sample mean of the $X$'s and $s_X^2$ is the sample variance of the $X$'s.",
"_____no_output_____"
]
],
[
[
"preds = samp_slope * PHI_samp[:,0] + samp_intercept\nsum_of_squared_residuals = np.sum((T_samp.reshape(-1) - preds) ** 2)\nsamp_sigma_y_give_x = np.sqrt(sum_of_squared_residuals / (n - 2))",
"_____no_output_____"
],
[
"samp_sigma_y_give_x",
"_____no_output_____"
],
[
"samp_mean = np.mean(PHI_samp[:,0])\nsamp_var = np.var(PHI_samp[:,0])",
"_____no_output_____"
],
[
"SE_slope = samp_sigma_y_give_x * np.sqrt(1 / ((n - 1) * samp_var))\nSE_intercept = samp_sigma_y_give_x * np.sqrt(1 / n + samp_mean ** 2 / ((n - 1) * samp_var))",
"_____no_output_____"
],
[
"SE_slope, SE_intercept",
"_____no_output_____"
]
],
[
[
"### Compute confidence intervals for sample statistics",
"_____no_output_____"
]
],
[
[
"slope_lower, slope_upper = samp_slope - 1.96 * SE_slope, samp_slope + 1.96 * SE_slope\nslope_lower, slope_upper",
"_____no_output_____"
],
[
"intercept_lower, intercept_upper = samp_intercept - 1.96 * SE_intercept, samp_intercept + 1.96 * SE_intercept\nintercept_lower, intercept_upper",
"_____no_output_____"
]
],
[
[
"### Compute confidence interval for regression line",
"_____no_output_____"
],
[
"#### Boostrapped solution",
"_____no_output_____"
],
[
"Use a 2-d Guassian to model the joint distribution between boostrapped sample slopes and boostrapped sample intercepts.",
"_____no_output_____"
],
[
"**Fixed.** `samp_slopes` and `samp_intercepts` used in the cell below are not boostrapped; they are directly sampled from the population. Next time, add the boostrapped version. Using `samp_slopes` and `samp_intercepts` still has its value, though; it shows the population regression line lie right in the middle of all sample regression lines. Remember that, when ever you use bootstrapping to estimate the variance / covariance of the sample distribution of some statistic, there might be an equation that you can use from statistical theory. ",
"_____no_output_____"
]
],
[
[
"num_resamples = 10000",
"_____no_output_____"
],
[
"resample_slopes, resample_intercepts = [], []\nfor i in range(num_resamples):\n PHI_resample, T_resample = sample(PHI_samp, T_samp, n=len(PHI_samp))\n learned_params = regularized_least_squares(PHI_resample, T_resample)\n resample_slopes.append(learned_params['slope']); resample_intercepts.append(learned_params['intercept'])",
"_____no_output_____"
]
],
[
[
"**Fixed.** The following steps might improve the results, but I don't think they are part of the standard practice.",
"_____no_output_____"
]
],
[
[
"# means = [np.mean(resample_slopes), np.mean(resample_intercepts)]\n# cov = np.cov(resample_slopes, resample_intercepts)",
"_____no_output_____"
],
[
"# model = multivariate_normal(mean=means, cov=cov)",
"_____no_output_____"
]
],
[
[
"Sample 5000 (slope, intercept) pairs from the Gaussian.",
"_____no_output_____"
]
],
[
[
"# num_pairs_sampled = 10000\n# pairs = model.rvs(num_pairs_sampled)",
"_____no_output_____"
]
],
[
[
"Scatter samples, plot regression lines and CI.",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(20, 10))\n\nplt.scatter(PHI_samp[:,0], T_samp.reshape(-1), s=20) # sample\n\ngranularity = 1000\nxs = np.linspace(0, 10, granularity)\n\nplt.plot(xs, samp_slope * xs + samp_intercept, label='Sample') # sample regression line\nplt.plot(xs, pop_slope * xs + pop_intercept, '--', color='black', label='Population') # population regression line\n\nlines = np.zeros((num_resamples, granularity))\nfor i, (slope, intercept) in enumerate(zip(resample_slopes, resample_intercepts)):\n lines[i] = slope * xs + intercept\n \nconfidence_level = 95\n \nuppers_95 = np.percentile(lines, confidence_level + (100 - confidence_level) / 2, axis=0)\nlowers_95 = np.percentile(lines, (100 - confidence_level) / 2, axis=0)\n\nconfidence_level = 99\n\nuppers_99 = np.percentile(lines, confidence_level + (100 - confidence_level) / 2, axis=0)\nlowers_99 = np.percentile(lines, (100 - confidence_level) / 2, axis=0)\n\nplt.fill_between(xs, lowers_95, uppers_95, color='grey', alpha=0.7, label='95% CI')\nplt.plot(xs, uppers_99, color='grey', label='99% CI')\nplt.plot(xs, lowers_99, color='grey')\n\nplt.legend()\nplt.show()",
"_____no_output_____"
]
],
[
[
"#### Analytic solution",
"_____no_output_____"
],
[
"**Reference.** Page 97, Statistics of Geograph: A Practical Approach, David Ebdon, 1987.",
"_____no_output_____"
],
[
"For a particular value $x_0$ of the independent variable $x$, its confidence interval is given by:\n",
"_____no_output_____"
],
[
"$$\\sqrt{\\frac{\\sum e^{2}}{n-2}\\left[\\frac{1}{n}+\\frac{\\left(x_{0}-\\bar{x}\\right)^{2}}{\\sum x^{2}-n \\bar{x}^{2}}\\right]}$$",
"_____no_output_____"
],
[
"where\n- $\\sum e^2$ is the sum of squares of residuals from regression,\n- $x$ is the independent variables,\n- $\\bar{x}$ is the sample mean of the independent variables.",
"_____no_output_____"
]
],
[
[
"sum_of_squared_xs = np.sum(PHI_samp[:,0] ** 2)",
"_____no_output_____"
],
[
"SEs = np.sqrt(\n (sum_of_squared_residuals / (n - 2)) *\n (1 / n + (xs - samp_mean) ** 2 / (sum_of_squared_xs - n * samp_mean ** 2))\n)",
"_____no_output_____"
],
[
"t_97dot5 = t.ppf(0.975, df=n-2)\nt_99dot5 = t.ppf(0.995, df=n-2)",
"_____no_output_____"
],
[
"yhats = samp_slope * xs + samp_intercept\n\nuppers_95 = yhats + t_97dot5 * SEs\nlowers_95 = yhats - t_97dot5 * SEs\n\nuppers_99 = yhats + t_99dot5 * SEs\nlowers_99 = yhats - t_99dot5 * SEs",
"_____no_output_____"
],
[
"plt.figure(figsize=(20, 10))\n\nplt.scatter(PHI_samp[:,0], T_samp.reshape(-1), s=20) # sample\n\ngranularity = 1000\nxs = np.linspace(0, 10, granularity)\n\nplt.plot(xs, samp_slope * xs + samp_intercept, label='Sample') # sample regression line\nplt.plot(xs, pop_slope * xs + pop_intercept, '--', color='black', label='Population') # population regression line\n\nplt.fill_between(xs, lowers_95, uppers_95, color='grey', alpha=0.7, label='95% CI')\n\nplt.plot(xs, uppers_99, color='grey', label='99% CI')\nplt.plot(xs, lowers_99, color='grey')\n\nplt.legend()\nplt.show()",
"_____no_output_____"
]
],
[
[
"\n## Regularized least squares",
"_____no_output_____"
]
],
[
[
"def plot_regression_line(PHI, T, regularizer):\n \n plt.scatter(PHI[:,0], T, s=5)\n \n params = regularized_least_squares(PHI, T, regularizer)\n \n x_min, x_max = PHI[:,0].min(), PHI[:,0].max()\n xs = np.linspace(x_min, x_max, 2)\n ys = params['slope'] * xs + params['intercept']\n \n plt.plot(xs, ys, color='orange')\n \n plt.ylim(-3, 10)\n \n plt.show()",
"_____no_output_____"
],
[
"plot_regression_line(PHI, T, regularizer=20)",
"_____no_output_____"
],
[
"def plot_regression_line_wrapper(regularizer, num_points):\n plot_regression_line(PHI[:num_points], T[:num_points], regularizer)",
"_____no_output_____"
]
],
[
[
"Yes! The effect of regularization does change with the size of the dataset.",
"_____no_output_____"
]
],
[
[
"_ = interact(\n plot_regression_line_wrapper, \n regularizer=IntSlider(min=0, max=10000, value=5000, continuous_update=False),\n num_points=IntSlider(min=2, max=1000, value=1000, continuous_update=False)\n)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
d07fff0627c29d6efc8bacb894289c0e23d5fa02 | 17,536 | ipynb | Jupyter Notebook | [STUDY]텍스트마이닝_Base.ipynb | kamzzang/ADPStudy | 5676be538c44050bdc3221b6d1eec35cbf95f4c1 | [
"MIT"
] | null | null | null | [STUDY]텍스트마이닝_Base.ipynb | kamzzang/ADPStudy | 5676be538c44050bdc3221b6d1eec35cbf95f4c1 | [
"MIT"
] | null | null | null | [STUDY]텍스트마이닝_Base.ipynb | kamzzang/ADPStudy | 5676be538c44050bdc3221b6d1eec35cbf95f4c1 | [
"MIT"
] | 1 | 2022-02-10T15:59:54.000Z | 2022-02-10T15:59:54.000Z | 27.357254 | 1,461 | 0.461394 | [
[
[
"# 1. 정규 표현식\n* 출처 : 서적 \"잡아라! 텍스트 마이닝 with 파이썬\"\n* 문자열이 주어진 규칙에 일치하는 지, 일치하지 않는지 판단할 수 있다. \n 정규 표현식을 이용하여 특정 패턴을 지니니 문자열을 찾을 수 있어 텍스트 데이터 사전 처리 및 \n 크롤링에서 주로 쓰임",
"_____no_output_____"
]
],
[
[
"string = '기상청은 슈퍼컴퓨터도 서울지역의 집중호우를 제대로 예측하지 못했다고 설명했습니다. 왜 오류가 발생했\\\n습니다. 왜 오류가 발생했는지 자세히 분석해 예측 프로그램을 보완해야 할 대목입니다. 관측 분야는 개선될 여지가\\\n있습니다. 지금 보시는 왼쪽 사진이 현재 천리안 위성이 촬영한 것이고 오른쪽이 올해 말 쏘아 올릴 천리안 2A호가 \\\n촬영한 영상입니다. 오른쪽이 왼쪽보다 태풍의 눈이 좀 더 뚜렷하고 주변 구름도 더 잘 보이죠. 새 위성을 통해 태풍\\\n 구름 등의 움직임을 상세히 분석하면 좀 더 정확한 예측을 할 수 있지 않을까 기대해 봅니다. 정구희 기자([email protected])'",
"_____no_output_____"
],
[
"string",
"_____no_output_____"
],
[
"import re",
"_____no_output_____"
],
[
"re.sub(\"\\([A-Za-z0-9\\._+]+@[A-Za-z]+\\.(com|org|edu|net|co.kr)\\)\", \"\", string)",
"_____no_output_____"
]
],
[
[
"* \\([A-Za-z0-9\\._+]+ : 이메일 주소가 괄호로 시작하여 \\(특수문자를 원래 의미대로 쓰게 함)와 (로 시작 \n 대괄호[ ] 안에 이메일 주소의 패턴을 입력(입력한 것 중 아무거나) \n A-Z = 알파벳 대문자, a-z = 알파벳 소문자, 0-9 = 숫자, ._+ = .나 _나 + \n 마지막 +는 바로 앞에 있는 것이 최소 한번 이상 나와야 한다는 의미 \n* @ : 이메일 주소 다음에 @ \n* [A-Za-z]+ : 도메인 주소에 해당하는 알파벳 대문자나 소문자 \n* \\. : 도메인 주소 다음의 . \n* (com|org|edu|net|co.kr)\\) : |는 or조건, 도메인 주소 마침표 다음의 패턴 마지막 )까지 찾음",
"_____no_output_____"
],
[
"### 파이썬 정규표현식 기호 설명\n* '*' : 바로 앞 문자, 표현식이 0번 이상 반복\n* '+' : 바로 앞 문자, 표현식이 1번 이상 반복\n* '[]' : 대괄호 안의 문자 중 하나\n* '()' : 괄호안의 정규식을 그룹으로 만듬\n* '.' : 어떤 형태든 문자 1자\n* '^' : 바로 뒤 문자, 표현식이 문자열 맨 앞에 나타남\n* '$' : 바로 앞 문자, 표현식이 문자열 맨 뒤에 나타남\n* '{m}' : 바로 앞 문자, 표현식이 m회 반복\n* '{m,n}' : 바로 앞 문자, 표현식이 m번 이상, n번 이하 나타남\n* '|' : |로 분리된 문자, 문자열, 표현식 중 하나가 나타남(or조건)\n* '[^]' : 대괄호 안에 있는 문자를 제외한 문자가 나타남",
"_____no_output_____"
]
],
[
[
"# a문자가 1번 이상 나오고 b 문자가 0번 이상 나오는 문자열 찾기\nr = re.compile(\"a+b*\")\nr.findall(\"aaaa, cc, bbbb, aabbb\")",
"_____no_output_____"
],
[
"# 대괄호를 이용해 대문자로 구성된 문자열 찾기\nr = re.compile(\"[A-Z]+\")\nr.findall(\"HOME, home\")",
"_____no_output_____"
],
[
"# ^와 .을 이용하여 맨 앞에 a가 오고 그 다음에 어떠한 형태든 2개의 문자가 오는 문자열 찾기\nr = re.compile(\"^a..\")\nr.findall(\"abc, cba\")",
"_____no_output_____"
],
[
"# 중괄호 표현식 {m,n}을 이요하여 해당 문자열이 m번 이상 n번 이하 나타나는 패턴 찾기\nr = re.compile(\"a{2,3}b{2,3}\")\nr.findall(\"aabb, aaabb, ab, aab\")",
"_____no_output_____"
],
[
"# compile 메서드에 정규 표현식 패턴 지정, search로 정규 표현식 패턴과 일치하는 문자열의 위치 찾기\n# group을 통해 패턴과 일치하는 문자들을 그룹핑하여 추출\np = re.compile(\".+:\")\nm = p.search(\"http://google.com\")\nm.group()",
"_____no_output_____"
],
[
"# sub : 정규 표현식과 일치하는 부분을 다른 문자로 치환\np = re.compile(\"(내|나의|내꺼)\")\np.sub(\"그의\", \"나의 물건에 손대지 마시오.\")",
"_____no_output_____"
]
],
[
[
"# 2. 전처리",
"_____no_output_____"
],
[
"### 대소문자 통일",
"_____no_output_____"
]
],
[
[
"s = 'Hello World'\nprint(s.lower())\nprint(s.upper())",
"hello world\nHELLO WORLD\n"
]
],
[
[
"### 숫자, 문장부호, 특수문자 제거",
"_____no_output_____"
]
],
[
[
"# 숫자 제거\np = re.compile(\"[0-9]+\")\np.sub(\"\", '서울 부동산 가격이 올해 들어 평균 30% 상승했습니다.')",
"_____no_output_____"
],
[
"# 문장부호, 특수문자 제거\np = re.compile(\"\\W+\")\np.sub(\" \", \"★서울 부동산 가격이 올해 들어 평균 30% 상승했습니다.\")",
"_____no_output_____"
],
[
"s = p.sub(\" \", \"주제_1: 건강한 물과 건강한 정신!\")\ns",
"_____no_output_____"
],
[
"p = re.compile(\"_\")\np.sub(\" \", s)",
"_____no_output_____"
]
],
[
[
"### 불용어 제거",
"_____no_output_____"
]
],
[
[
"words_Korean = ['추석','연휴','민족','대이동','시작','늘어','교통량','교통사고','특히','자동차','고장',\n '상당수','차지','나타','것','기자']\nstopwords = ['가다','늘어','나타','것','기자']",
"_____no_output_____"
],
[
"[i for i in words_Korean if i not in stopwords]",
"_____no_output_____"
],
[
"from nltk.corpus import stopwords\n# 그냥하면 LookupError 발생하므로 다운로드가 필요함\n# import nltk\n# nltk.download() or nltk.download('stopwords')",
"_____no_output_____"
],
[
"words_English = ['chief','justice','roberts',',','president','carter',',','president','clinton',',',\n 'president','bush',',','president','obama',',','fellow','americans','and','people',\n 'of','the','world',',','thank','you','.']\n[w for w in words_English if not w in stopwords.words('english')]",
"_____no_output_____"
]
],
[
[
"### 같은 어근 동일화(stemming)",
"_____no_output_____"
]
],
[
[
"from nltk.tokenize import word_tokenize\nfrom nltk.stem import PorterStemmer\n\nps_stemmer = PorterStemmer()\n\nnew_text = 'It is important to be immersed while you are pythoning with python.\\\nAll pythoners have pothoned poorly at least once.'\n\nwords = word_tokenize(new_text)\n\nfor w in words:\n print(ps_stemmer.stem(w), end=' ')",
"It is import to be immers while you are python with python.al python have pothon poorli at least onc . "
],
[
"from nltk.stem.lancaster import LancasterStemmer\n\nLS_stemmer = LancasterStemmer()\n\nfor w in words:\n print(LS_stemmer.stem(w), end=' ')",
"it is import to be immers whil you ar python with python.all python hav pothon poor at least ont . "
],
[
"from nltk.stem.regexp import RegexpStemmer # 특정한 표현식을 일괄적으로 제거\n\nRS_stemmer = RegexpStemmer('python')\n\nfor w in words:\n print(RS_stemmer.stem(w), end=' ')",
"It is important to be immersed while you are ing with .All ers have pothoned poorly at least once . "
]
],
[
[
"### N-gram\n* n번 연이어 등장하는 단어들의 연쇄\n* 두 번 : 바이그램, 세 번 : 트라이그램(트라이그램 이상은 보편적으로 활용하지 않음)",
"_____no_output_____"
]
],
[
[
"from nltk import ngrams",
"_____no_output_____"
],
[
"sentence = 'Chief Justice Roberts, Preskdent Carter, President Clinton, President Bush, President Obama, \\\nfellow Americans and people of the world, thank you. We, the citizens of America are now joined in a great \\\nnational effort to rebuild our country and restore its promise for all of our people. Together, we will \\\ndetermine the course of America and the world for many, many years to come. We will face challenges. We \\\nwill confront hardships, but we will get the job done.'\n\ngrams = ngrams(sentence.split(), 2)\n\nfor gram in grams:\n print(gram, end=' ')",
"('Chief', 'Justice') ('Justice', 'Roberts,') ('Roberts,', 'Preskdent') ('Preskdent', 'Carter,') ('Carter,', 'President') ('President', 'Clinton,') ('Clinton,', 'President') ('President', 'Bush,') ('Bush,', 'President') ('President', 'Obama,') ('Obama,', 'fellow') ('fellow', 'Americans') ('Americans', 'and') ('and', 'people') ('people', 'of') ('of', 'the') ('the', 'world,') ('world,', 'thank') ('thank', 'you.') ('you.', 'We,') ('We,', 'the') ('the', 'citizens') ('citizens', 'of') ('of', 'America') ('America', 'are') ('are', 'now') ('now', 'joined') ('joined', 'in') ('in', 'a') ('a', 'great') ('great', 'national') ('national', 'effort') ('effort', 'to') ('to', 'rebuild') ('rebuild', 'our') ('our', 'country') ('country', 'and') ('and', 'restore') ('restore', 'its') ('its', 'promise') ('promise', 'for') ('for', 'all') ('all', 'of') ('of', 'our') ('our', 'people.') ('people.', 'Together,') ('Together,', 'we') ('we', 'will') ('will', 'determine') ('determine', 'the') ('the', 'course') ('course', 'of') ('of', 'America') ('America', 'and') ('and', 'the') ('the', 'world') ('world', 'for') ('for', 'many,') ('many,', 'many') ('many', 'years') ('years', 'to') ('to', 'come.') ('come.', 'We') ('We', 'will') ('will', 'face') ('face', 'challenges.') ('challenges.', 'We') ('We', 'will') ('will', 'confront') ('confront', 'hardships,') ('hardships,', 'but') ('but', 'we') ('we', 'will') ('will', 'get') ('get', 'the') ('the', 'job') ('job', 'done.') "
]
],
[
[
"### 품사 분석",
"_____no_output_____"
]
],
[
[
"from konlpy.tag import Hannanum\n\nhannanum = Hannanum()\n\nprint(hannanum.morphs(\"친척들이 모인 이번 추석 차례상에서는 단연 '집값'이 화제에 올랐다.\"))\nprint(hannanum.nouns(\"친척들이 모인 이번 추석 차례상에서는 단연 '집값'이 화제에 올랐다.\"))\nprint(hannanum.pos(\"친척들이 모인 이번 추석 차례상에서는 단연 '집값'이 화제에 올랐다.\", ntags=9))",
"['친척들', '이', '모이', 'ㄴ', '이번', '추석', '차례상', '에서는', '단연', \"'\", '집값', \"'\", '이', '화제', '에', '오르', '아다', '.']\n['친척들', '이번', '추석', '차례상', '집값', '화제']\n[('친척들', 'N'), ('이', 'J'), ('모이', 'P'), ('ㄴ', 'E'), ('이번', 'N'), ('추석', 'N'), ('차례상', 'N'), ('에서는', 'J'), ('단연', 'M'), (\"'\", 'S'), ('집값', 'N'), (\"'\", 'S'), ('이', 'J'), ('화제', 'N'), ('에', 'J'), ('오르', 'P'), ('아다', 'E'), ('.', 'S')]\n"
],
[
"from konlpy.tag import Kkma\nkkma = Kkma()\n\nprint(kkma.morphs(\"친척들이 모인 이번 추석 차례상에서는 단연 '집값'이 화제에 올랐다.\"))\nprint(kkma.nouns(\"친척들이 모인 이번 추석 차례상에서는 단연 '집값'이 화제에 올랐다.\"))\nprint(kkma.pos(\"친척들이 모인 이번 추석 차례상에서는 단연 '집값'이 화제에 올랐다.\"))",
"['친척', '들', '이', '모이', 'ㄴ', '이번', '추석', '차례', '상', '에서', '는', '단연', \"'\", '집', '값', \"'\", '이', '화제', '에', '오르', '았', '다', '.']\n['친척', '이번', '추석', '차례', '차례상', '상', '집', '집값', '값', '화제']\n[('친척', 'NNG'), ('들', 'XSN'), ('이', 'JKS'), ('모이', 'VV'), ('ㄴ', 'ETD'), ('이번', 'NNG'), ('추석', 'NNG'), ('차례', 'NNG'), ('상', 'NNG'), ('에서', 'JKM'), ('는', 'JX'), ('단연', 'MAG'), (\"'\", 'SS'), ('집', 'NNG'), ('값', 'NNG'), (\"'\", 'SS'), ('이', 'MDT'), ('화제', 'NNG'), ('에', 'JKM'), ('오르', 'VV'), ('았', 'EPT'), ('다', 'EFN'), ('.', 'SF')]\n"
],
[
"from konlpy.tag import Twitter\ntwitter = Twitter()\n\nprint(twitter.morphs(\"친척들이 모인 이번 추석 차례상에서는 단연 '집값'이 화제에 올랐다.\"))\nprint(twitter.nouns(\"친척들이 모인 이번 추석 차례상에서는 단연 '집값'이 화제에 올랐다.\"))\nprint(twitter.pos(\"친척들이 모인 이번 추석 차례상에서는 단연 '집값'이 화제에 올랐다.\"))\nprint(twitter.phrases(\"친척들이 모인 이번 추석 차례상에서는 단연 '집값'이 화제에 올랐다.\"))",
"C:\\Anaconda3\\lib\\site-packages\\konlpy\\tag\\_okt.py:16: UserWarning: \"Twitter\" has changed to \"Okt\" since KoNLPy v0.4.5.\n warn('\"Twitter\" has changed to \"Okt\" since KoNLPy v0.4.5.')\n"
],
[
"from nltk import pos_tag\n\ntokens = \"The little yellow dog barked at the Persian cat.\".split()\ntags_en = pos_tag(tokens)\n\nprint(tags_en)",
"[('The', 'DT'), ('little', 'JJ'), ('yellow', 'JJ'), ('dog', 'NN'), ('barked', 'VBD'), ('at', 'IN'), ('the', 'DT'), ('Persian', 'NNP'), ('cat.', 'NN')]\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
d0800a01f44b7a6a9793116df13eb7727c88eb44 | 4,982 | ipynb | Jupyter Notebook | scikit-learn/MNIST_load/MNIST_load.ipynb | starpentagon/python_scripts | 37a484f2657712fe0ea885f58f7f49ee28d077bf | [
"MIT"
] | 2 | 2019-02-22T09:39:58.000Z | 2020-11-19T22:46:02.000Z | scikit-learn/MNIST_load/MNIST_load.ipynb | starpentagon/python_scripts | 37a484f2657712fe0ea885f58f7f49ee28d077bf | [
"MIT"
] | null | null | null | scikit-learn/MNIST_load/MNIST_load.ipynb | starpentagon/python_scripts | 37a484f2657712fe0ea885f58f7f49ee28d077bf | [
"MIT"
] | 7 | 2018-09-10T06:11:16.000Z | 2021-08-16T07:50:02.000Z | 48.843137 | 2,790 | 0.759334 | [
[
[
"from sklearn.datasets import fetch_mldata\n\nimport numpy as np\nfrom PIL import Image\nfrom IPython.core.display import display",
"_____no_output_____"
],
[
"mnist = fetch_mldata('MNIST original', data_home='./mnist_data/')",
"_____no_output_____"
],
[
"# 0-9の画像を表示する\nnumber_printed = {}\nnumber_image_array = None\n\nfor i in range(10):\n number_printed[i] = False\n\nfor i in range(len(mnist.data)):\n label = int(mnist.target[i])\n \n if number_printed[label] == True:\n continue\n \n number_printed[label] = True\n \n image_array = 255 - np.reshape(mnist.data[i], (28, 28))\n \n if number_image_array is None:\n number_image_array = image_array\n else:\n number_image_array = np.concatenate([number_image_array, image_array], axis=1)\n \nimage = Image.fromarray(np.uint8(number_image_array))\ndisplay(image)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code"
]
] |
d0801486a524b351ec0ce96da165390f2c7c6ec8 | 21,089 | ipynb | Jupyter Notebook | Grokker.ipynb | FSchumacher/grok-parser-example | c40b51d0076c362f6480c377d693cf5f6405d44d | [
"Apache-2.0"
] | null | null | null | Grokker.ipynb | FSchumacher/grok-parser-example | c40b51d0076c362f6480c377d693cf5f6405d44d | [
"Apache-2.0"
] | null | null | null | Grokker.ipynb | FSchumacher/grok-parser-example | c40b51d0076c362f6480c377d693cf5f6405d44d | [
"Apache-2.0"
] | null | null | null | 40.323136 | 1,681 | 0.457205 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
d0801cfa462d4f7f182effbcee7e45d6dcc7a563 | 403,816 | ipynb | Jupyter Notebook | Average_RM_YIELD_location.ipynb | hmc-cs-nsuaysom/BigDataProject | ef312213eb1abcc4fcf07f737abbed40259073a2 | [
"MIT"
] | null | null | null | Average_RM_YIELD_location.ipynb | hmc-cs-nsuaysom/BigDataProject | ef312213eb1abcc4fcf07f737abbed40259073a2 | [
"MIT"
] | null | null | null | Average_RM_YIELD_location.ipynb | hmc-cs-nsuaysom/BigDataProject | ef312213eb1abcc4fcf07f737abbed40259073a2 | [
"MIT"
] | null | null | null | 579.362984 | 76,882 | 0.932868 | [
[
[
"# For cross-validation\nFRACTION_TRAINING = 0.5\n\n# For keeping output\ndetailed_output = {}\n\n# dictionary for keeping model\nmodel_dict = {}",
"_____no_output_____"
],
[
"import pandas as pd\nimport pickle\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sklearn\nfrom matplotlib.colors import ListedColormap\nfrom sklearn import linear_model\n%matplotlib inline\nplt.style.use(\"ggplot\")\n\n\"\"\"\nData Preprocessing\n\nEXPERIMENT_DATA - Contain training data\nEVALUATION_DATA - Contain testing data \n\"\"\"\n\nEXPERIMENT_DATA = pickle.load(open('EXPERIMENT_SET_pandas.pkl', 'rb'))\nEVALUATION_SET = pickle.load(open('EVALUATION_SET_pandas.pkl', 'rb'))\n\n# Shuffle Data\nEXPERIMENT_DATA = sklearn.utils.shuffle(EXPERIMENT_DATA)\nEXPERIMENT_DATA = EXPERIMENT_DATA.reset_index(drop=True)\n\n\nTRAINING_DATA = EXPERIMENT_DATA[:int(FRACTION_TRAINING*len(EXPERIMENT_DATA))]\nTESTING_DATA = EXPERIMENT_DATA[int(FRACTION_TRAINING*len(EXPERIMENT_DATA)):]\n\n# Consider only graduated species\nTRAINING_DATA_GRAD = TRAINING_DATA[TRAINING_DATA[\"GRAD\"] == \"YES\"]\nTESTING_DATA_GRAD = TESTING_DATA[TESTING_DATA[\"GRAD\"] == \"YES\"]",
"_____no_output_____"
],
[
"print(\"Graduate Training Data size: {}\".format(len(TRAINING_DATA_GRAD)))\nprint(\"Graduate Testing Data size: {}\".format(len(TESTING_DATA_GRAD)))",
"Graduate Training Data size: 5992\nGraduate Testing Data size: 5940\n"
],
[
"def plotRegression(data):\n plt.figure(figsize=(8,8))\n \n ###########################\n # 1st plot: linear scale\n ###########################\n bagSold = np.asarray(data[\"BAGSOLD\"]).reshape(-1, 1).astype(np.float)\n rm = np.asarray(data[\"RM\"]).reshape(-1,1).astype(np.float)\n bias_term = np.ones_like(rm)\n x_axis = np.arange(rm.min(),rm.max(),0.01)\n \n # Liear Regression\n regr = linear_model.LinearRegression(fit_intercept=True)\n regr.fit(rm, bagSold)\n bagSold_prediction = regr.predict(rm)\n print(\"Coefficients = {}\".format(regr.coef_))\n print(\"Intercept = {}\".format(regr.intercept_))\n \n # Find MSE\n mse = sklearn.metrics.mean_squared_error(bagSold, bagSold_prediction)\n \n# plt.subplot(\"121\")\n plt.title('Linear Regression RM vs. Bagsold')\n true_value = plt.plot(rm, bagSold, 'ro', label='True Value')\n regression_line = plt.plot(x_axis, regr.intercept_[0] + regr.coef_[0][0]*x_axis, color=\"green\")\n plt.legend([\"true_value\", \"Regression Line\\nMSE = {:e}\".format(mse)])\n plt.xlabel(\"RM\")\n plt.ylabel(\"Bagsold\")\n plt.xlim(rm.min(),rm.max())\n detailed_output[\"MSE of linear regression on entire dataset (linear scale)\"] = mse\n plt.savefig(\"linear_reg_entire_dataset_linearscale.png\")\n plt.show()\n \n #######################\n # 2nd plot: log scale\n #######################\n plt.figure(figsize=(8,8))\n bagSold = np.log(bagSold)\n \n # Linear Regression \n regr = linear_model.LinearRegression()\n regr.fit(rm, bagSold)\n bagSold_prediction = regr.predict(rm)\n print(\"Coefficients = {}\".format(regr.coef_))\n print(\"Intercept = {}\".format(regr.intercept_))\n \n # Find MSE\n mse = sklearn.metrics.mean_squared_error(bagSold, bagSold_prediction)\n \n# plt.subplot(\"122\")\n plt.title('Linear Regression RM vs. log of Bagsold')\n true_value = plt.plot(rm,bagSold, 'ro', label='True Value')\n regression_line = plt.plot(x_axis, regr.intercept_[0] + regr.coef_[0][0]*x_axis, color=\"green\")\n plt.legend([\"true_value\", \"Regression Line\\nMSE = {:e}\".format(mse)])\n plt.xlabel(\"RM\")\n plt.ylabel(\"log Bagsold\")\n plt.xlim(rm.min(),rm.max())\n detailed_output[\"MSE of linear regression on entire dataset (log scale)\"] = mse\n# plt.savefig(\"linear_reg_entire_dataset_logscale.png\")\n plt.show()\n",
"_____no_output_____"
],
[
"# Coefficients = [[-14956.36881671]]\n# Intercept = [ 794865.84758174]\nplotRegression(TRAINING_DATA_GRAD)",
"Coefficients = [[-15932.30228111]]\nIntercept = [ 792617.66604889]\n"
]
],
[
[
"## Location-based algorithm",
"_____no_output_____"
]
],
[
[
"location_map = list(set(TRAINING_DATA_GRAD[\"LOCATION\"]))\nlocation_map.sort()\n# print(location_map)",
"_____no_output_____"
],
[
"list_location = []\nlist_avg_rm = []\nlist_avg_yield = []\nfor val in location_map:\n avg_rm = np.average(TRAINING_DATA_GRAD[EXPERIMENT_DATA[\"LOCATION\"] == str(val)][\"RM\"])\n avg_yield = np.average(TRAINING_DATA_GRAD[EXPERIMENT_DATA[\"LOCATION\"] == str(val)][\"YIELD\"])\n list_location.append(str(val))\n list_avg_rm.append(avg_rm)\n list_avg_yield.append(avg_yield)\n # print(\"{} = {},{}\".format(val,avg_rm,avg_yield))",
"/Users/teerapatjenrungrot/anaconda3/lib/python3.5/site-packages/ipykernel/__main__.py:5: UserWarning: Boolean Series key will be reindexed to match DataFrame index.\n/Users/teerapatjenrungrot/anaconda3/lib/python3.5/site-packages/ipykernel/__main__.py:6: UserWarning: Boolean Series key will be reindexed to match DataFrame index.\n"
],
[
"plt.title(\"Average RM and YIELD for each location\")\nplt.plot(list_avg_rm, list_avg_yield, 'ro')\n\nfor i, txt in enumerate(list_location):\n if int(txt) <= 1000:\n plt.annotate(txt, (list_avg_rm[i],list_avg_yield[i]), color=\"blue\")\n elif int(txt) <= 2000:\n plt.annotate(txt, (list_avg_rm[i],list_avg_yield[i]), color=\"red\")\n elif int(txt) <= 3000:\n plt.annotate(txt, (list_avg_rm[i],list_avg_yield[i]), color=\"green\")\n elif int(txt) <= 4000:\n plt.annotate(txt, (list_avg_rm[i],list_avg_yield[i]), color=\"black\")\n elif int(txt) <= 5000:\n plt.annotate(txt, (list_avg_rm[i],list_avg_yield[i]), color=\"orange\")\n else:\n plt.annotate(txt, (list_avg_rm[i],list_avg_yield[i]), color=\"purple\")\nplt.show()\n",
"_____no_output_____"
]
],
[
[
"### Analysis\n\nFrom the preliminary analysis, we find that the number of different locateion in the dataset is 140. The location in the dataset is encoded as a 4-digit number. We first expected that we can group the quality of the species based on the location parameters. We then plot the average of __RM__ and __YIELD__ for each location, which is shown below: ",
"_____no_output_____"
],
[
"## Linear Regression on each group of location\n\nAccording to prior analaysis, it appears that we can possibly categorize species on location. The approach we decide to adopt is to use first digit of the location number as a categorizer. The histogram in the previous section indicates that there exists roughly about 7 groups. Notice that the leftmost and rightmost columns seem to be outliers.",
"_____no_output_____"
]
],
[
[
"# Calculate the number of possible locations\nlocation_set = set(TRAINING_DATA_GRAD[\"LOCATION\"])\nprint(\"The number of possible location is {}.\".format(len(location_set)))\n\nlocation_histogram_list = []\nfor location in sorted(location_set):\n amount = len(TRAINING_DATA_GRAD[TRAINING_DATA_GRAD[\"LOCATION\"] == str(location)])\n for j in range(amount):\n location_histogram_list.append(int(location))\n# print(\"Location {} has {:>3} species\".format(location, amount))\n \nplt.title(\"Histogram of each location\")\nplt.xlabel(\"Location Number\")\nplt.ylabel(\"Amount\")\nplt.hist(location_histogram_list, bins=7, range=(0,7000))\nplt.savefig(\"location_histogram.png\")\nplt.show()",
"The number of possible location is 135.\n"
],
[
"# Convert location column to numeric\nTRAINING_DATA_GRAD[\"LOCATION\"] = TRAINING_DATA_GRAD[\"LOCATION\"].apply(pd.to_numeric)\n\n# Separate training dataset into 7 groups\ndataByLocation = []\nfor i in range(7):\n dataByLocation.append(TRAINING_DATA_GRAD[(TRAINING_DATA_GRAD[\"LOCATION\"] < ((i+1)*1000)) & (TRAINING_DATA_GRAD[\"LOCATION\"] >= (i*1000))])",
"/Users/teerapatjenrungrot/anaconda3/lib/python3.5/site-packages/ipykernel/__main__.py:2: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n from ipykernel import kernelapp as app\n"
],
[
"for i in range(len(dataByLocation)):\n data = dataByLocation[i]\n bagSold = np.log(np.asarray(data[\"BAGSOLD\"]).reshape(-1,1).astype(np.float))\n rm = np.asarray(data[\"RM\"]).reshape(-1,1).astype(np.float)\n \n # Liear Regression\n regr = linear_model.LinearRegression()\n regr.fit(rm, bagSold)\n model_dict[i] = regr\n bagSold_prediction = regr.predict(rm)\n \n x_axis = np.arange(rm.min(), rm.max(), 0.01).reshape(-1,1)\n \n # Find MSE\n mse = sklearn.metrics.mean_squared_error(bagSold, bagSold_prediction)\n print(mse, np.sqrt(mse))\n detailed_output[\"number of data point on location {}xxx\".format(i)] = len(data)\n detailed_output[\"MSE on location {}xxx log scale\".format(i)] = mse\n \n plt.figure(figsize=(8,8))\n# plt.subplot(\"{}\".format(int(str(len(dataByLocation))+str(1)+str(i+1))))\n plt.title(\"Linear Regression RM vs. Log Bagsold on Location {}xxx\".format(i))\n \n true_value = plt.plot(rm,bagSold, 'ro', label='True Value')\n regression_line = plt.plot(x_axis, regr.predict(x_axis), color=\"green\")\n plt.legend([\"true_value\", \"Regression Line\\nMSE = {:e}\".format(mse)])\n# plt.show()\n plt.xlim(rm.min(),rm.max())\n plt.savefig(\"location{}.png\".format(i))\n",
"1.05328277023 1.0262956544\n0.762338198505 0.873119807647\n0.253807203837 0.503792818366\n0.200542622706 0.447819855195\n0.29628093697 0.544316945327\n0.374676270693 0.612108054753\n3.15544362088e-30 1.7763568394e-15\n"
]
],
[
[
"## Test with validation set",
"_____no_output_____"
]
],
[
[
"# Test with validation set\nTESTING_DATA_GRAD = TESTING_DATA_GRAD.reset_index(drop=True)\n\nXtest = np.column_stack((TESTING_DATA_GRAD[\"LOCATION\"], \n TESTING_DATA_GRAD[\"RM\"], \n TESTING_DATA_GRAD[\"YIELD\"]))\nytest = TESTING_DATA_GRAD[\"BAGSOLD\"].astype(np.float)\nlog_ytest = np.log(ytest)",
"_____no_output_____"
],
[
"ypredicted = []\nfor row in Xtest:\n location = row[0]\n rm_val = row[1]\n yield_val = row[2]\n \n model = model_dict[int(location[0])]\n prediction = model.predict(rm_val)[0][0]\n ypredicted.append(prediction)\n \nypredicted = np.array(ypredicted)",
"_____no_output_____"
],
[
"# MSE error\nsklearn.metrics.mean_squared_error(log_ytest, ypredicted)",
"_____no_output_____"
]
],
[
[
"#### Testing Ridge Reg vs. Linear Reg\nBelow is not used. It's for testing the difference between Ridge Regression and Linear Regression.\nThe result is that the MSE is almsot the same",
"_____no_output_____"
]
],
[
[
"bagSold = np.log(np.asarray(TRAINING_DATA_GRAD[\"BAGSOLD\"]).reshape(-1, 1).astype(np.float))\nrm = np.asarray(TRAINING_DATA_GRAD[\"RM\"]).reshape(-1,1).astype(np.float)\nyield_val = np.asarray(TRAINING_DATA_GRAD[\"YIELD\"]).reshape(-1,1).astype(np.float)\n\nx = np.column_stack((rm, yield_val))\n \n# Liear Regression\nregr = linear_model.LinearRegression(fit_intercept=True)\nregr.fit(x, bagSold)\nbagSold_prediction = regr.predict(x)\nprint(\"Coefficients = {}\".format(regr.coef_))\nprint(\"Intercept = {}\".format(regr.intercept_))\n \n# Find MSE\nmse = sklearn.metrics.mean_squared_error(bagSold, bagSold_prediction)\nprint(\"MSE = {}\".format(mse))",
"Coefficients = [[ 0.07116814 0.00414965]]\nIntercept = [ 12.94839385]\nMSE = 0.3469602260718588\n"
],
[
"bagSold = np.log(np.asarray(TRAINING_DATA_GRAD[\"BAGSOLD\"]).reshape(-1, 1).astype(np.float))\nrm = np.asarray(TRAINING_DATA_GRAD[\"RM\"]).reshape(-1,1).astype(np.float)\nyield_val = np.asarray(TRAINING_DATA_GRAD[\"YIELD\"]).reshape(-1,1).astype(np.float)\n\nx = np.column_stack((rm, yield_val))\n \n# Liear Regression\nregr = linear_model.Ridge(alpha=20000)\nregr.fit(x, bagSold)\nbagSold_prediction = regr.predict(x)\nprint(\"Coefficients = {}\".format(regr.coef_))\nprint(\"Intercept = {}\".format(regr.intercept_))\n \n# Find MSE\nmse = sklearn.metrics.mean_squared_error(bagSold, bagSold_prediction)\nprint(\"MSE = {}\".format(mse))",
"Coefficients = [[ 0.0062339 0.00430852]]\nIntercept = [ 13.11871673]\nMSE = 0.3483090550422536\n"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
d08021b353437fc29845c826597b90aaa1003871 | 211,224 | ipynb | Jupyter Notebook | PythonCode/Archive/JorgeBugBuster.ipynb | callinSwitzer/ODE_Python | afb342b335cd3760950d463204bccab257df0a68 | [
"MIT"
] | 1 | 2019-04-02T20:34:03.000Z | 2019-04-02T20:34:03.000Z | PythonCode/Archive/JorgeBugBuster.ipynb | nifti-coe/ODE_Python | afb342b335cd3760950d463204bccab257df0a68 | [
"MIT"
] | null | null | null | PythonCode/Archive/JorgeBugBuster.ipynb | nifti-coe/ODE_Python | afb342b335cd3760950d463204bccab257df0a68 | [
"MIT"
] | null | null | null | 341.786408 | 71,801 | 0.921803 | [
[
[
"# Callin Switzer\n## Modifications to TLD code for ODE system\n___",
"_____no_output_____"
]
],
[
[
"# Jorge BugBuster\n### This is a quick look at Jorge's ODE system for the abdo-flex model. WHOA... be sure to use cgs system!\n### TLD -- based on Code from Jorge Bustamante 2018\n### Python modification of Matlab code. \n### updated: 29 Nov. 2018",
"_____no_output_____"
]
],
[
[
"from matplotlib import pyplot as plt\n%matplotlib inline\nfrom matplotlib import cm\nimport numpy as np\nimport os\nimport scipy.io\nimport seaborn as sb\nimport matplotlib.pylab as pylab\n# forces plots to appear in the ipython notebook\n%matplotlib inline\nfrom scipy.integrate import odeint\nfrom pylab import plot,xlabel,ylabel,title,legend,figure,subplots\nimport random\nimport time\nfrom pylab import cos, pi, arange, sqrt, pi, array\nimport sys",
"_____no_output_____"
],
[
"sb.__version__",
"_____no_output_____"
],
[
"sys.executable\nsys.version",
"_____no_output_____"
],
[
"def FlyTheBug(state,t):\n # unpack the state vector\n x,xd,y,yd,theta,thetad,phi,phid = state # displacement,x and velocity xd etc... You got it?'\n # compute acceleration xdd = x''\n # Jorge's order . x,y,theta,phi,xd,yd,thetad,phid\n # . there is no entry for Q(2) ... which would be y. I wonder why not?\n\n #Reynolds number calculation:\n Re_head = rhoA*(np.sqrt((xd**2)+(yd**2)))*(2*bhead)/muA; #dimensionless number\n Re_butt = rhoA*(np.sqrt((xd**2)+(yd**2)))*(2*bbutt)/muA; #dimensionless number\n\n #Coefficient of drag stuff:\n Cd_head = 24/np.abs(Re_head) + 6/(1 + np.sqrt(np.abs(Re_head))) + 0.4;\n Cd_butt = 24/np.abs(Re_butt) + 6/(1 + np.sqrt(np.abs(Re_butt))) + 0.4;\n \n h1 = m1 + m2;\n h2 = (-1)*L1*m1*np.sin(theta);\n h3 = (-1)*L2*m2*np.sin(phi);\n h4 = L1*m1*np.cos(theta);\n h5 = L2*m2*np.cos(phi);\n h6 = (-1)*F*np.cos(alpha+theta)+(1/2)*Cd_butt*rhoA*S_butt*np.abs(xd)*xd+(1/2)*Cd_head*rhoA*S_head*np.abs(xd)*xd+(-1)*L1*m1*np.cos(theta)*thetad**2+(-1)*L2*m2*np.cos(phi)*phid**2\n h7 = g*(m1+m2)+(1/2)*Cd_butt*rhoA*S_butt*np.abs(yd)*yd+(1/2)*Cd_head*rhoA*S_head*np.abs(yd)*yd+(-1)*L1*m1*thetad**2*np.sin(theta)+(-1)*F*np.sin(alpha+theta)+(-1)*L2*m2*phid**2*np.sin(phi);\n h8 = (-1)*tau0+g*L1*m1*np.cos(theta)+(-1)*K*((-1)*betaR+(-1)*pi+(-1)*theta+phi)+(-1)*c*((-1)*thetad+phid)+(-1)*F*L3*np.sin(alpha);\n h9 = tau0+g*L2*m2*np.cos(phi)+K*((-1)*betaR+(-1)*pi+(-1)*theta+phi)+c*((-1)*thetad+phid);\n h10 = I1+L1**2*m1\n h11 = I2+L2**2*m2\n\n\n xdd = (-1)*(h10*h11*h1**2+(-1)*h11*h1*h2**2+(-1)*h10*h1*h3**2+(-1)*h11*h1*h4**2+h3**2*h4**2+(-2)*h2* \n h3*h4*h5+(-1)*h10*h1*h5**2+h2**2*h5**2)**(-1)*( \n h10*h11*h1*h6+(-1)*h11*h4**2*h6+(-1)*h10*h5**2* \n h6+h11*h2*h4*h7+h10*h3*h5*h7+(-1)*h11*h1*h2* \n h8+(-1)*h3*h4*h5*h8+h2*h5**2*h8+(-1)*h10*h1* \n h3*h9+h3*h4**2*h9+(-1)*h2*h4*h5*h9)\n \n\n ydd = (-1)*((-1)*h10*h11*h1**2+h11*h1*h2**2+h10*h1*\n h3**2+h11*h1*h4**2+(-1)*h3**2*h4**2+2*h2*h3*h4*\n h5+h10*h1*h5**2+(-1)*h2**2*h5**2)**(-1)*((-1)*h11*\n h2*h4*h6+(-1)*h10*h3*h5*h6+(-1)*h10*h11*h1*\n h7+h11*h2**2*h7+h10*h3**2*h7+h11*h1*h4*h8+(-1)*\n h3**2*h4*h8+h2*h3*h5*h8+h2*h3*h4*h9+h10*h1*\n h5*h9+(-1)*h2**2*h5*h9)\n\n thetadd = (-1)*((-1)*h10*h11*h1**2+h11*h1*h2**2+h10*h1*\n h3**2+h11*h1*h4**2+(-1)*h3**2*h4**2+2*h2*h3*h4*\n h5+h10*h1*h5**2+(-1)*h2**2*h5**2)**(-1)*(h11*h1*\n h2*h6+h3*h4*h5*h6+(-1)*h2*h5**2*h6+h11*h1*\n h4*h7+(-1)*h3**2*h4*h7+h2*h3*h5*h7+(-1)*h11*\n h1**2*h8+h1*h3**2*h8+h1*h5**2*h8+(-1)*h1*h2*\n h3*h9+(-1)*h1*h4*h5*h9);\n\n phidd = (-1)*((-1)*h10*h11*h1**2+h11*h1*h2**2+h10*h1*\n h3**2+h11*h1*h4**2+(-1)*h3**2*h4**2+2*h2*h3*h4*\n h5+h10*h1*h5**2+(-1)*h2**2*h5**2)**(-1)*(h10*h1*\n h3*h6+(-1)*h3*h4**2*h6+h2*h4*h5*h6+h2*h3*h4*\n h7+h10*h1*h5*h7+(-1)*h2**2*h5*h7+(-1)*h1*h2*\n h3*h8+(-1)*h1*h4*h5*h8+(-1)*h10*h1**2*h9+h1*\n h2**2*h9+h1*h4**2*h9)\n \n return [xd, xdd,yd,ydd,thetad,thetadd,phid,phidd]",
"_____no_output_____"
],
[
"# Bunches of parameters ... these don't vary from run to run \n#masses and moment of inertias in terms of insect density and eccentricity\n#of the head/thorax & gaster\n# oh.. and I'm offline -- so I just made up a bunch of numbers.\n\nbhead = 0.507\nahead = 0.908\nbbutt = 0.1295\nabutt = 1.7475\nrho = 1 #cgs density of insect \nrhoA = 0.00118 #cgs density of air\nmuA = 0.000186 #cgs viscosity\nL1 = 0.908 #Length from the thorax-abdomen joint to the center of the \n #head-thorax mass in cm\nL2 = 1.7475 #Length from the thorax-abdomen joint to the center of the \n #abdomen mass in cm\nL3 = 0.75 #Length from the thorax-abdomen joint to the aerodynamic force \n #vector in cm\nm1 = rho*(4/3)*pi*(bhead**2)*ahead; #m1 is the mass of the head-thorax\nm2 = rho*(4/3)*pi*(bbutt**2)*abutt; #m2 is the mass of the abdomen \n #(petiole + gaster)\nechead = ahead/bhead; #Eccentricity of head-thorax (unitless)\necbutt = abutt/bbutt; #Eccentricity of gaster (unitless)\nI1 = (1/5)*m1*(bhead**2)*(1 + echead**2); #Moment of inertia of the \n #head-thorax\nI2 = (1/5)*m2*(bbutt**2)*(1 + ecbutt**2); #Moment of inertia of the gaster\n\nS_head = pi*bhead**2; #This is the surface area of the object experiencing drag.\n #In this case, it is modeled as a sphere.\nS_butt = pi*bbutt**2; #This is the surface area of the object experiencing drag.\n #In this case, it is modeled as a sphere.\n\nK = 29.3 #K is the torsional spring constant of the thorax-petiole joint\n #in (cm^2)*g/(rad*(s^2))\nc = 14075.8 #c is the torsional damping constant of the thorax-petiole joint\n #in (cm^2)*g/s\ng = 980.0 #g is the acceleration due to gravity in cm/(s^2)\nbetaR = 0.0 #This is the resting configuration of our \n #torsional spring(s) = Initial abdomen angle - initial head angle - pi\n ",
"_____no_output_____"
],
[
"#This cell just checks to be sure we can run this puppy and graph results. \nstate0 = [0.0, 0.0001, 0.0, 0.0001, np.pi/4, 0.0, np.pi/4 + np.pi, 0.0] #initial conditions [x0 , v0 etc0 ]\nF = 0 # . CAUTION .. .I just set this to zero.\n# By the way --if you give this an initial kick and keep the force low, it has a nice parabolic trajectory\nalpha = 5.75\ntau0 = 100.\n# ti = 0.0 # initial time\n# tf = 8 # final time\n# nstep = 1000\n# t = np.linspace(0, tf, num = nstep, endpoint = True)\ntf = 1.0 # final time\nnstep = 1000\nstep = (tf-ti)/nstep # step\nt = arange(ti, tf, step)\n\nprint(t.shape)\nstate = odeint(FlyTheBug, state0, t)\nx = array(state[:,[0]])\nxd = array(state[:,[1]])\ny = array(state[:,[2]])\nyd = array(state[:,[3]])\ntheta = array(state[:,[4]])\nthetad = array(state[:,[5]])\nphi = array(state[:,[6]])\nphid = array(state[:,[7]])\n# And let's just plot it all\nsb.set()\nprint(x[-1:], y[-1:])\nx100 = [x[-1:], y[-1:]]\nplt.figure()\nplt.plot(t,xd, label = 'Ux vs time')\nplt.plot(t,yd, label = 'Uy vs time')\nplt.legend()\nplt.figure()\nplt.plot(t,theta, label = 'theta vs time')\nplt.legend()\nplt.show()\nplt.plot(t,theta-phi - np.pi, label = 'theta vs time')\nplt.figure()\nplt.plot(x,y, label = 'x vs y')\nplt.legend()\n",
"(1000,)\n[[0.02222083]] [[-0.02017856]]\n"
],
[
"#This cell just checks to be sure we can run this puppy and graph results. \nstate0 = [0.0, 0.0001, 0.0, 0.0001, np.pi/4, 0.0, np.pi/4 + np.pi, 0.0] #initial conditions [x0 , v0 etc0 ]\nF = 40462.5 # . CAUTION .. .I just set this to zero.\n# By the way --if you give this an initial kick and keep the force low, it has a nice parabolic trajectory\nalpha = 5.75\n# tau0 = 69825.\n# ti = 0.0 # initial time\n# tf = 0.02 # final time\n# nstep = 2\n# t = np.linspace(0, tf, num = nstep, endpoint = True)\ntf = 1.0 # final time\nnstep = 1000\nstep = (tf-ti)/nstep # step\nt = arange(ti, tf, step)\n\nprint(t.shape)\nstate = odeint(FlyTheBug, state0, t)\nx = array(state[:,[0]])\nxd = array(state[:,[1]])\ny = array(state[:,[2]])\nyd = array(state[:,[3]])\ntheta = array(state[:,[4]])\nthetad = array(state[:,[5]])\nphi = array(state[:,[6]])\nphid = array(state[:,[7]])\n# And let's just plot it all\nsb.set()\nprint(x[-1:], y[-1:])\n\nplt.figure()\nplt.plot(t,xd, label = 'Ux vs time')\nplt.plot(t,yd, label = 'Uy vs time')\nplt.legend()\nplt.figure()\nplt.plot(t,theta, label = 'theta vs time')\nplt.legend()\nplt.figure()\nplt.plot(x,y, label = 'x vs y')\nplt.legend()\nplt.show()\n",
"(2,)\n[[7.0591585]] [[1.55881305]]\n"
],
[
"x100 - np.array([x[-1:], y[-1:]])",
"_____no_output_____"
],
[
"print(x[99])\nprint(y[99])\nprint(theta[99])",
"[7.23106226]\n[1.76120687]\n[0.8046604]\n"
],
[
"# This cell just tests the random assignmnent of forces and plots the result in the next cell\ntic = time.time()\nti = 0.0 # initial time \ntf = 0.02 # final time \nnstep = 100 # number of time steps.\nstep = (tf-ti)/nstep # duration of the time step\nt = arange(ti, tf, step) # how much time\nnrun = 100 #number of trajectories.\nx = [[0 for x in range(nrun)] for y in range(nstep)] # initialize the matrix of locations\nxd = [[0 for x in range(nrun)] for y in range(nstep)]\ny = [[0 for x in range(nrun)] for y in range(nstep)] \nyd = [[0 for x in range(nrun)] for y in range(nstep)] \ntheta = [[0 for x in range(nrun)] for y in range(nstep)] \nthetad = [[0 for x in range(nrun)] for y in range(nstep)] \nphi = [[0 for x in range(nrun)] for y in range(nstep)] \nphid = [[0 for x in range(nrun)] for y in range(nstep)] \nstate0 = [0.0, 0.1, 0.0, 0.1, 0.0, 0.0, 0.0, 0.0] #initial conditions [x0 , v0 etc0 ]\nfor i in range(0,nrun):\n r = random.random()-0.5 # random number between -0.5 and 0.5\n F = r*100000\n # By the way --if you give this an initial kick and keep the force low, it has a nice parabolic trajectory\n r = random.random()-0.5\n alpha = r*np.pi\n r = random.random()-0.5\n tau0 = r*100\n state = odeint(FlyTheBug, state0, t)\n x[i][:] = array(state[:,[0]])\n xd[i][:] = array(state[:,[1]])\n y[i][:] = array(state[:,[2]])\n yd[i][:] = array(state[:,[3]])\n theta[i][:] = array(state[:,[4]])\n thetad[i][:] = array(state[:,[5]])\n phi[i][:] = array(state[:,[6]])\n phid[i][:] = array(state[:,[7]])\nprint('elapsed time = ',time.time()-tic)",
"elapsed time = 4.4861133098602295\n"
],
[
"plt.figure()\nfor i in range(0,nrun):\n plt.plot(x[i][:],y[i][:], label = 'trajectory x vs y')",
"_____no_output_____"
],
[
"# There are two forks in the road\n# One is to select myriad random ICs and and myriad random Forces/ Torques.. then learn.\n# The other fork generates a tracking beahvior using MPC with MC. In the latter, we want to specify a trajectory\nprint(x[:][nstep-1])",
"[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n"
],
[
"#%Weighting coefficients from Jorge ... hope they're the recent ones.\n#%c1 = xdot, c2 = ydot, c3 = thetadot, c4 = x, c5 = y, c6 = theta\n#c1 = 1*10^-5; c2 = 1*10^-5; c3 = 10^6; c4 = 10^7; c5 = 10^8; c6 = 10^10; \nCostWeights = [10**7,10**-5,10**8,10**-5,10^10,10^6,0,0]\n#EndState = [x[:][nstep-1],xd[:][nstep-1]],y[:][nstep-1],yd[:][nstep-1],theta[:][nstep-1],thetad[:][nstep-1],phi[:][nstep-1],phid[:][nstep-1]\nGoal = [0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01]\nprint(np.dot(CostWeights,np.abs(EndState - Goal)))",
"271089.3357288316\n"
],
[
"import multiprocessing\nmultiprocessing.cpu_count()",
"_____no_output_____"
]
]
] | [
"markdown",
"raw",
"code"
] | [
[
"markdown"
],
[
"raw"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d08022d8c7c50b622f3438d58ac15b875cb8b13f | 4,531 | ipynb | Jupyter Notebook | notebooks_tcc/0.3-BrunoGomesCoelho-Show-Normalization-Doesnt-Work.ipynb | BrunoGomesCoelho/mosquito-networking | 767a77cbe570c3271f5a0695f48c633bb3098543 | [
"FTL"
] | 1 | 2021-07-28T00:39:43.000Z | 2021-07-28T00:39:43.000Z | notebooks_tcc/0.3-BrunoGomesCoelho-Show-Normalization-Doesnt-Work.ipynb | BrunoGomesCoelho/mosquito-networking | 767a77cbe570c3271f5a0695f48c633bb3098543 | [
"FTL"
] | null | null | null | notebooks_tcc/0.3-BrunoGomesCoelho-Show-Normalization-Doesnt-Work.ipynb | BrunoGomesCoelho/mosquito-networking | 767a77cbe570c3271f5a0695f48c633bb3098543 | [
"FTL"
] | null | null | null | 24.229947 | 95 | 0.530567 | [
[
[
"# Analyze the range of values from the audio\n",
"_____no_output_____"
]
],
[
[
"from scipy.io import wavfile",
"_____no_output_____"
],
[
"wav_file = \"../data/raw/dadosBruno/t02/\" + \\\n \"t02_S-ISCA_C1_Aedes female-20-07-2017_1_001_456.wav\"\nwav = wavfile.read(wav_file)",
"_____no_output_____"
],
[
"# OPTIONAL: Load the \"autoreload\" extension so that code can change\n%load_ext autoreload\n\n# OPTIONAL: always reload modules so that as you change code in src, it gets loaded\n%autoreload 2",
"_____no_output_____"
],
[
"import numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom joblib import dump, load\n\nfrom src.data import make_dataset\nfrom src.data import read_dataset\nfrom src.data import util\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()",
"_____no_output_____"
],
[
"# Set seed for reprodubility\nnp.random.seed(42)",
"_____no_output_____"
],
[
"from src.data.read_dataset import read_temperature\n\ndef make_temperatures(conversion, testing=False):\n num_cols = [x for x in range(11025)]\n save_cols = num_cols + [\"label\"]\n \n for i in range(2, 8):\n temperature = f\"t0{i}\"\n df = read_temperature(temperature, conversion)\n\n train_idx = df[\"training\"] == 1 # get train data\n train_data = df.loc[train_idx]\n test_data = df.loc[~train_idx]\n \n # Create validation\n train_data, val_data = train_test_split(train_data, test_size=0.2)\n\n # Train scaler\n scaler = StandardScaler()\n scaler.fit(train_data[num_cols])\n dump(scaler, f\"../data/interim/scaler_{conversion}_{temperature}.pkl\")\n \n # Save the data as compressed numpy arrays\n np.savez_compressed(f\"../data/interim/all_wavs_{conversion}_{temperature}\", \n train=train_data[save_cols].astype(int), \n val=val_data[save_cols].astype(int), \n test=test_data[save_cols].astype(int))",
"_____no_output_____"
],
[
"make_temperatures(\"repeat\")",
"_____no_output_____"
],
[
"make_temperatures(\"zero\")",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d08025dde9a8f1130b8d1c5e363d63ef70b88092 | 123,019 | ipynb | Jupyter Notebook | day2_visualisation.ipynb | Kamila86/dw_matrix | fbf23aea966175d992f9990a0a3cb7e0d107ade6 | [
"Apache-2.0"
] | null | null | null | day2_visualisation.ipynb | Kamila86/dw_matrix | fbf23aea966175d992f9990a0a3cb7e0d107ade6 | [
"Apache-2.0"
] | null | null | null | day2_visualisation.ipynb | Kamila86/dw_matrix | fbf23aea966175d992f9990a0a3cb7e0d107ade6 | [
"Apache-2.0"
] | null | null | null | 297.866828 | 43,076 | 0.902137 | [
[
[
"<a href=\"https://colab.research.google.com/github/Kamila86/dw_matrix/blob/master/day2_visualisation.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"Found existing installation: tables 3.4.4\nUnistalling tables-3.4.4:\nSuccessfully unistalled tables-3.4.4\nSuccessfully installed tables-3.6.1\n",
"_____no_output_____"
],
[
"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport seaborn as sns",
"_____no_output_____"
],
[
"cd \"/content/drive/My Drive/Colab Notebooks/matrix/matrix_two/dw_matrix_car\"",
"/content/drive/My Drive/Colab Notebooks/matrix/matrix_two/dw_matrix_car\n"
],
[
"df = pd.read_hdf('data/car.h5')\ndf.shape",
"_____no_output_____"
],
[
"df.columns.values",
"_____no_output_____"
],
[
"df['price_value'].hist(bins=100);",
"_____no_output_____"
],
[
"df['price_value'].describe()",
"_____no_output_____"
],
[
"def group_and_barplot(feat_groupby, feat_agg='price_value', agg_funcs=[np.mean, np.median, np.size], feat_sort='mean', top=50, subplots=True):\n return (\n df\n .groupby(feat_groupby)[feat_agg]\n .agg(agg_funcs)\n .sort_values(by=feat_sort, ascending=False)\n .head(top)\n \n ).plot(kind='bar', figsize=(15, 5), subplots=subplots)\n",
"_____no_output_____"
],
[
"group_and_barplot('param_marka-pojazdu');\n",
"_____no_output_____"
],
[
"group_and_barplot('param_kraj-pochodzenia', feat_sort='size');",
"_____no_output_____"
],
[
"group_and_barplot('param_kolor', feat_sort='mean');",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d0802605c6f9f0fb0a9651fe791fa433462ed30b | 32,498 | ipynb | Jupyter Notebook | state_equations/with_noise.ipynb | ryuichiueda/probrobo_practice | 4d1d49ef4f01a2b77e61fbdbeed6001a8a25d7c3 | [
"MIT"
] | 51 | 2017-04-08T13:40:19.000Z | 2021-01-12T06:57:57.000Z | state_equations/with_noise.ipynb | ryuichiueda/probrobo_practice | 4d1d49ef4f01a2b77e61fbdbeed6001a8a25d7c3 | [
"MIT"
] | null | null | null | state_equations/with_noise.ipynb | ryuichiueda/probrobo_practice | 4d1d49ef4f01a2b77e61fbdbeed6001a8a25d7c3 | [
"MIT"
] | 11 | 2017-05-01T09:35:47.000Z | 2020-04-24T07:36:34.000Z | 112.840278 | 13,750 | 0.858114 | [
[
[
"# 移動ロボットの状態遷移(ノイズあり)\n\n千葉工業大学 上田 隆一\n\n(c) 2017 Ryuichi Ueda\n\nThis software is released under the MIT License, see LICENSE.\n\n## はじめに\n\nこのコードは、移動ロボットの移動の簡単なモデルです。\n",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport numpy as np\nimport math, random\nimport matplotlib.pyplot as plt # for plotting data",
"_____no_output_____"
]
],
[
[
"### ばらつき\n\nつぎのルールにしたがってロボットの移動量に雑音を混入してみる。\n\n* 指令値を中心に、ガウス分布にしたがって次のようにばらつく\n * 前進するとき\n * 距離が距離に対して10%の標準偏差でばらつく\n * 向きが標準偏差3[deg]でばらつく\n * 向きを変えるとき\n * 変える向きの角度に対して10%の標準偏差でばらつく\n\n\n### 状態方程式に対応する関数\n\n下の例について、関数fを書きましょう。",
"_____no_output_____"
],
[
"```python\nold_x = np.array([0,0,0]) # 今回は不要だがnumpyを使用\nu = np.array([0.1,10/180*math.pi]) # 毎回0.1だけ進めて10[deg]向きを変える\n\ndef f(x_old,u):\n なにかコードを書く\n return x_new\n```",
"_____no_output_____"
],
[
"#### 解答例",
"_____no_output_____"
]
],
[
[
"def f(x_old,u):\n # わかりにくいのでバラす\n pos_x, pos_y, pos_theta = x_old\n act_fw, act_rot = u\n \n act_fw = random.gauss(act_fw,act_fw/10)\n dir_error = random.gauss(0.0, math.pi / 180.0 * 3.0)\n act_rot = random.gauss(act_rot,act_rot/10)\n \n pos_x += act_fw * math.cos(pos_theta + dir_error)\n pos_y += act_fw * math.sin(pos_theta + dir_error)\n pos_theta += act_rot\n \n return np.array([pos_x,pos_y,pos_theta])",
"_____no_output_____"
]
],
[
[
"### 実行!\n\n10ステップ動貸してみましょう。",
"_____no_output_____"
]
],
[
[
"x = np.array([0,0,0])\nu = np.array([0.1,10/180*math.pi]) # 毎回0.1だけ進めて10[deg]向きを変える\nprint(x)\nfor i in range(10):\n x = f(x,u)\n print(x)",
"[0 0 0]\n[ 0.11101391 0.01316534 0.20062588]\n[ 0.21667561 0.03772248 0.36210264]\n[ 0.30714191 0.06797028 0.53692128]\n[ 0.38194774 0.11808143 0.72018441]\n[ 0.45733798 0.17144363 0.89551629]\n[ 0.5062014 0.23616994 1.07167283]\n[ 0.55316268 0.32808052 1.24928927]\n[ 0.59204397 0.42298333 1.41256331]\n[ 0.61068586 0.52827197 1.60383144]\n[ 0.60807198 0.62990338 1.78279156]\n"
]
],
[
[
"### わからんので描画",
"_____no_output_____"
]
],
[
[
"x = np.array([0,0,0])\nu = np.array([0.1,10/180*math.pi]) # 毎回0.1だけ進めて10[deg]向きを変える\n\npath = [x]\nfor i in range(10):\n x = f(x,u)\n path.append(x)\n\nfig = plt.figure(i,figsize=(8, 8))\nsp = fig.add_subplot(111, aspect='equal')\nsp.set_xlim(-1.0,1.0)\nsp.set_ylim(-0.5,1.5)\n \nxs = [e[0] for e in path]\nys = [e[1] for e in path]\nvxs = [math.cos(e[2]) for e in path]\nvys = [math.sin(e[2]) for e in path]\nplt.quiver(xs,ys,vxs,vys,color=\"red\",label=\"actual robot motion\")",
"_____no_output_____"
]
],
[
[
"## 10ステップ後の姿勢のばらつき",
"_____no_output_____"
]
],
[
[
"path = []\n\nfor j in range(100):\n x = np.array([0,0,0])\n u = np.array([0.1,10/180*math.pi]) # 毎回0.1だけ進めて10[deg]向きを変える\n\n for i in range(10):\n x = f(x,u)\n \n path.append(x)\n\nfig = plt.figure(i,figsize=(8, 8))\nsp = fig.add_subplot(111, aspect='equal')\nsp.set_xlim(-1.0,1.0)\nsp.set_ylim(-0.5,1.5)\n \nxs = [e[0] for e in path]\nys = [e[1] for e in path]\nvxs = [math.cos(e[2]) for e in path]\nvys = [math.sin(e[2]) for e in path]\nplt.quiver(xs,ys,vxs,vys,color=\"red\",label=\"actual robot motion\")",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
d0802979b4fceaf125629c4b4f02256ffdac5030 | 56,979 | ipynb | Jupyter Notebook | binder/ApacheSedonaRaster.ipynb | aggunr/incubator-sedona | 12de9260b035801ef1962d4c206a36cb19e0f30c | [
"Apache-2.0"
] | 366 | 2020-07-31T04:31:04.000Z | 2022-03-31T22:32:47.000Z | binder/ApacheSedonaRaster.ipynb | Mr-90-Style/incubator-sedona | 5c7222a5e755b51844db975186984551764d25c7 | [
"Apache-2.0"
] | 55 | 2020-09-03T09:28:49.000Z | 2022-03-21T04:42:48.000Z | binder/ApacheSedonaRaster.ipynb | Mr-90-Style/incubator-sedona | 5c7222a5e755b51844db975186984551764d25c7 | [
"Apache-2.0"
] | 127 | 2020-09-03T02:45:34.000Z | 2022-03-31T12:16:06.000Z | 58.801858 | 2,279 | 0.695414 | [
[
[
"from IPython.display import display, HTML\nfrom pyspark.sql import SparkSession\nfrom pyspark import StorageLevel\nimport pandas as pd\nfrom pyspark.sql.types import StructType, StructField,StringType, LongType, IntegerType, DoubleType, ArrayType\nfrom pyspark.sql.functions import regexp_replace\nfrom sedona.register import SedonaRegistrator\nfrom sedona.utils import SedonaKryoRegistrator, KryoSerializer\nfrom pyspark.sql.functions import col, split, expr\nfrom pyspark.sql.functions import udf, lit\nfrom sedona.utils import SedonaKryoRegistrator, KryoSerializer\nfrom pyspark.sql.functions import col, split, expr\nfrom pyspark.sql.functions import udf, lit\n",
"_____no_output_____"
]
],
[
[
"# Create Spark Session for application",
"_____no_output_____"
]
],
[
[
"spark = SparkSession.\\\n builder.\\\n master(\"local[*]\").\\\n appName(\"Demo-app\").\\\n config(\"spark.serializer\", KryoSerializer.getName).\\\n config(\"spark.kryo.registrator\", SedonaKryoRegistrator.getName) .\\\n config(\"spark.jars.packages\", \"org.apache.sedona:sedona-python-adapter-3.0_2.12:1.1.0-incubating,org.datasyslab:geotools-wrapper:1.1.0-25.2\") .\\\n getOrCreate()\n\nSedonaRegistrator.registerAll(spark)\nsc = spark.sparkContext\n",
"21/10/08 19:55:41 WARN UDTRegistration: Cannot register UDT for org.locationtech.jts.geom.Geometry, which is already registered.\n21/10/08 19:55:41 WARN UDTRegistration: Cannot register UDT for org.locationtech.jts.index.SpatialIndex, which is already registered.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_pointfromtext replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_polygonfromtext replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_linestringfromtext replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_geomfromtext replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_geomfromwkt replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_geomfromwkb replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_geomfromgeojson replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_point replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_polygonfromenvelope replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_contains replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_intersects replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_within replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_distance replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_convexhull replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_npoints replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_buffer replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_envelope replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_length replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_area replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_centroid replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_transform replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_intersection replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_isvalid replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_precisionreduce replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_equals replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_touches replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_overlaps replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_crosses replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_issimple replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_makevalid replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_simplifypreservetopology replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_astext replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_asgeojson replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_geometrytype replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_numgeometries replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_linemerge replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_azimuth replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_x replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_y replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_startpoint replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_boundary replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_minimumboundingradius replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_minimumboundingcircle replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_endpoint replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_exteriorring replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_geometryn replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_interiorringn replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_dump replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_dumppoints replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_isclosed replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_numinteriorrings replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_addpoint replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_removepoint replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_isring replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_flipcoordinates replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_linesubstring replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_lineinterpolatepoint replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_subdivideexplode replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_subdivide replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function rs_normalizeddifference replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function rs_mean replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function rs_mode replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function rs_fetchregion replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function rs_greaterthan replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function rs_greaterthanequal replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function rs_lessthan replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function rs_lessthanequal replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function rs_addbands replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function rs_subtractbands replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function rs_dividebands replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function rs_multiplyfactor replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function rs_multiplybands replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function rs_bitwiseand replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function rs_bitwiseor replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function rs_count replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function rs_modulo replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function rs_getband replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function rs_squareroot replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function rs_logicaldifference replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function rs_logicalover replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function rs_base64 replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function rs_html replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function rs_array replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function rs_normalize replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_union_aggr replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_envelope_aggr replaced a previously registered function.\n21/10/08 19:55:41 WARN SimpleFunctionRegistry: The function st_intersection_aggr replaced a previously registered function.\n"
]
],
[
[
"# Geotiff Loader \n\n1. Loader takes as input a path to directory which contains geotiff files or a parth to particular geotiff file\n2. Loader will read geotiff image in a struct named image which contains multiple fields as shown in the schema below which can be extracted using spark SQL",
"_____no_output_____"
]
],
[
[
"# Path to directory of geotiff images \nDATA_DIR = \"./data/raster/\"",
"_____no_output_____"
],
[
"df = spark.read.format(\"geotiff\").option(\"dropInvalid\",True).load(DATA_DIR)\ndf.printSchema()",
"root\n |-- image: struct (nullable = true)\n | |-- origin: string (nullable = true)\n | |-- wkt: string (nullable = true)\n | |-- height: integer (nullable = true)\n | |-- width: integer (nullable = true)\n | |-- nBands: integer (nullable = true)\n | |-- data: array (nullable = true)\n | | |-- element: double (containsNull = true)\n\n"
],
[
"df = df.selectExpr(\"image.origin as origin\",\"ST_GeomFromWkt(image.wkt) as Geom\", \"image.height as height\", \"image.width as width\", \"image.data as data\", \"image.nBands as bands\")\ndf.show(5)",
"+--------------------+--------------------+------+-----+--------------------+-----+\n| origin| Geom|height|width| data|bands|\n+--------------------+--------------------+------+-----+--------------------+-----+\n|file:///Users/jia...|POLYGON ((-58.702...| 32| 32|[1081.0, 1068.0, ...| 4|\n|file:///Users/jia...|POLYGON ((-58.286...| 32| 32|[1151.0, 1141.0, ...| 4|\n+--------------------+--------------------+------+-----+--------------------+-----+\n\n"
]
],
[
[
"# Extract a particular band from geotiff dataframe using RS_GetBand()\n",
"_____no_output_____"
]
],
[
[
"''' RS_GetBand() will fetch a particular band from given data array which is the concatination of all the bands'''\n\ndf = df.selectExpr(\"Geom\",\"RS_GetBand(data, 1,bands) as Band1\",\"RS_GetBand(data, 2,bands) as Band2\",\"RS_GetBand(data, 3,bands) as Band3\", \"RS_GetBand(data, 4,bands) as Band4\")\ndf.createOrReplaceTempView(\"allbands\")\ndf.show(5)",
"+--------------------+--------------------+--------------------+--------------------+--------------------+\n| Geom| Band1| Band2| Band3| Band4|\n+--------------------+--------------------+--------------------+--------------------+--------------------+\n|POLYGON ((-58.702...|[1081.0, 1068.0, ...|[865.0, 1084.0, 1...|[0.0, 0.0, 0.0, 0...|[0.0, 0.0, 0.0, 0...|\n|POLYGON ((-58.286...|[1151.0, 1141.0, ...|[1197.0, 1163.0, ...|[0.0, 0.0, 0.0, 0...|[0.0, 0.0, 0.0, 0...|\n+--------------------+--------------------+--------------------+--------------------+--------------------+\n\n"
]
],
[
[
"# Map Algebra operations on band values ",
"_____no_output_____"
]
],
[
[
"''' RS_NormalizedDifference can be used to calculate NDVI for a particular geotiff image since it uses same computational formula as ndvi'''\n\nNomalizedDifference = df.selectExpr(\"RS_NormalizedDifference(Band1, Band2) as normDiff\")\nNomalizedDifference.show(5)",
"+--------------------+\n| normDiff|\n+--------------------+\n|[-0.11, 0.01, 0.0...|\n|[0.02, 0.01, -0.0...|\n+--------------------+\n\n"
],
[
"''' RS_Mean() can used to calculate mean of piel values in a particular spatial band '''\nmeanDF = df.selectExpr(\"RS_Mean(Band1) as mean\")\nmeanDF.show(5)",
"+-------+\n| mean|\n+-------+\n|1153.85|\n|1293.77|\n+-------+\n\n"
],
[
"\"\"\" RS_Mode() is used to calculate mode in an array of pixels and returns a array of double with size 1 in case of unique mode\"\"\"\nmodeDF = df.selectExpr(\"RS_Mode(Band1) as mode\")\nmodeDF.show(5)",
"+----------------+\n| mode|\n+----------------+\n| [1011.0, 927.0]|\n|[1176.0, 1230.0]|\n+----------------+\n\n"
],
[
"''' RS_GreaterThan() is used to mask all the values with 1 which are greater than a particular threshold'''\ngreaterthanDF = spark.sql(\"Select RS_GreaterThan(Band1,1000.0) as greaterthan from allbands\")\ngreaterthanDF.show()",
"+--------------------+\n| greaterthan|\n+--------------------+\n|[1.0, 1.0, 1.0, 0...|\n|[1.0, 1.0, 1.0, 1...|\n+--------------------+\n\n"
],
[
"''' RS_GreaterThanEqual() is used to mask all the values with 1 which are greater than a particular threshold'''\n\ngreaterthanEqualDF = spark.sql(\"Select RS_GreaterThanEqual(Band1,360.0) as greaterthanEqual from allbands\")\ngreaterthanEqualDF.show()",
"+--------------------+\n| greaterthanEqual|\n+--------------------+\n|[1.0, 1.0, 1.0, 1...|\n|[1.0, 1.0, 1.0, 1...|\n+--------------------+\n\n"
],
[
"''' RS_LessThan() is used to mask all the values with 1 which are less than a particular threshold'''\nlessthanDF = spark.sql(\"Select RS_LessThan(Band1,1000.0) as lessthan from allbands\")\nlessthanDF.show()",
"+--------------------+\n| lessthan|\n+--------------------+\n|[0.0, 0.0, 0.0, 1...|\n|[0.0, 0.0, 0.0, 0...|\n+--------------------+\n\n"
],
[
"''' RS_LessThanEqual() is used to mask all the values with 1 which are less than equal to a particular threshold'''\nlessthanEqualDF = spark.sql(\"Select RS_LessThanEqual(Band1,2890.0) as lessthanequal from allbands\")\nlessthanEqualDF.show()",
"+--------------------+\n| lessthanequal|\n+--------------------+\n|[1.0, 1.0, 1.0, 1...|\n|[1.0, 1.0, 1.0, 1...|\n+--------------------+\n\n"
],
[
"''' RS_AddBands() can add two spatial bands together'''\nsumDF = df.selectExpr(\"RS_AddBands(Band1, Band2) as sumOfBand\")\nsumDF.show(5)",
"+--------------------+\n| sumOfBand|\n+--------------------+\n|[1946.0, 2152.0, ...|\n|[2348.0, 2304.0, ...|\n+--------------------+\n\n"
],
[
"''' RS_SubtractBands() can subtract two spatial bands together'''\nsubtractDF = df.selectExpr(\"RS_SubtractBands(Band1, Band2) as diffOfBand\")\nsubtractDF.show(5)",
"+--------------------+\n| diffOfBand|\n+--------------------+\n|[-216.0, 16.0, 11...|\n|[46.0, 22.0, -96....|\n+--------------------+\n\n"
],
[
"''' RS_MultiplyBands() can multiple two bands together'''\nmultiplyDF = df.selectExpr(\"RS_MultiplyBands(Band1, Band2) as productOfBand\")\nmultiplyDF.show(5)",
"+--------------------+\n| productOfBand|\n+--------------------+\n|[935065.0, 115771...|\n|[1377747.0, 13269...|\n+--------------------+\n\n"
],
[
"''' RS_DivideBands() can divide two bands together'''\ndivideDF = df.selectExpr(\"RS_DivideBands(Band1, Band2) as divisionOfBand\")\ndivideDF.show(5)",
"+--------------------+\n| divisionOfBand|\n+--------------------+\n|[1.25, 0.99, 0.9,...|\n|[0.96, 0.98, 1.08...|\n+--------------------+\n\n"
],
[
"''' RS_MultiplyFactor() will multiply a factor to a spatial band'''\nmulfacDF = df.selectExpr(\"RS_MultiplyFactor(Band2, 2) as target\")\nmulfacDF.show(5)",
"+--------------------+\n| target|\n+--------------------+\n|[1730.0, 2168.0, ...|\n|[2394.0, 2326.0, ...|\n+--------------------+\n\n"
],
[
"''' RS_BitwiseAND() will return AND between two values of Bands'''\nbitwiseAND = df.selectExpr(\"RS_BitwiseAND(Band1, Band2) as AND\")\nbitwiseAND.show(5)",
"+--------------------+\n| AND|\n+--------------------+\n|[33.0, 1068.0, 10...|\n|[1069.0, 1025.0, ...|\n+--------------------+\n\n"
],
[
"''' RS_BitwiseOR() will return OR between two values of Bands'''\nbitwiseOR = df.selectExpr(\"RS_BitwiseOR(Band1, Band2) as OR\")\nbitwiseOR.show(5)",
"+--------------------+\n| OR|\n+--------------------+\n|[1913.0, 1084.0, ...|\n|[1279.0, 1279.0, ...|\n+--------------------+\n\n"
],
[
"''' RS_Count() will calculate the total number of occurence of a target value'''\ncountDF = df.selectExpr(\"RS_Count(RS_GreaterThan(Band1,1000.0), 1.0) as count\")\ncountDF.show(5)",
"+-----+\n|count|\n+-----+\n| 753|\n| 1017|\n+-----+\n\n"
],
[
"''' RS_Modulo() will calculate the modulus of band value with respect to a given number'''\nmoduloDF = df.selectExpr(\"RS_Modulo(Band1, 21.0) as modulo \")\nmoduloDF.show(5)",
"+--------------------+\n| modulo|\n+--------------------+\n|[10.0, 18.0, 18.0...|\n|[17.0, 7.0, 2.0, ...|\n+--------------------+\n\n"
],
[
"''' RS_SquareRoot() will calculate calculate square root of all the band values upto two decimal places'''\nrootDF = df.selectExpr(\"RS_SquareRoot(Band1) as root\")\nrootDF.show(5)\n",
"+--------------------+\n| root|\n+--------------------+\n|[32.88, 32.68, 32...|\n|[33.93, 33.78, 35...|\n+--------------------+\n\n"
],
[
"''' RS_LogicalDifference() will return value from band1 if value at that particular location is not equal tp band1 else it will return 0'''\nlogDiff = df.selectExpr(\"RS_LogicalDifference(Band1, Band2) as loggDifference\")\nlogDiff.show(5)",
"+--------------------+\n| loggDifference|\n+--------------------+\n|[1081.0, 1068.0, ...|\n|[1151.0, 1141.0, ...|\n+--------------------+\n\n"
],
[
"''' RS_LogicalOver() will iterate over two bands and return value of first band if it is not equal to 0 else it will return value from later band'''\nlogOver = df.selectExpr(\"RS_LogicalOver(Band3, Band2) as logicalOver\")\nlogOver.show(5)",
"+--------------------+\n| logicalOver|\n+--------------------+\n|[865.0, 1084.0, 1...|\n|[1197.0, 1163.0, ...|\n+--------------------+\n\n"
]
],
[
[
"# Visualising Geotiff Images\n\n1. Normalize the bands in range [0-255] if values are greater than 255\n2. Process image using RS_Base64() which converts in into a base64 string\n3. Embedd results of RS_Base64() in RS_HTML() to embedd into IPython notebook\n4. Process results of RS_HTML() as below:",
"_____no_output_____"
]
],
[
[
"''' Plotting images as a dataframe using geotiff Dataframe.'''\n\ndf = spark.read.format(\"geotiff\").option(\"dropInvalid\",True).load(DATA_DIR)\ndf = df.selectExpr(\"image.origin as origin\",\"ST_GeomFromWkt(image.wkt) as Geom\", \"image.height as height\", \"image.width as width\", \"image.data as data\", \"image.nBands as bands\")\n\ndf = df.selectExpr(\"RS_GetBand(data,1,bands) as targetband\", \"height\", \"width\", \"bands\", \"Geom\")\ndf_base64 = df.selectExpr(\"Geom\", \"RS_Base64(height,width,RS_Normalize(targetBand), RS_Array(height*width,0.0), RS_Array(height*width, 0.0)) as red\",\"RS_Base64(height,width,RS_Array(height*width, 0.0), RS_Normalize(targetBand), RS_Array(height*width, 0.0)) as green\", \"RS_Base64(height,width,RS_Array(height*width, 0.0), RS_Array(height*width, 0.0), RS_Normalize(targetBand)) as blue\",\"RS_Base64(height,width,RS_Normalize(targetBand), RS_Normalize(targetBand),RS_Normalize(targetBand)) as RGB\" )\ndf_HTML = df_base64.selectExpr(\"Geom\",\"RS_HTML(red) as RedBand\",\"RS_HTML(blue) as BlueBand\",\"RS_HTML(green) as GreenBand\", \"RS_HTML(RGB) as CombinedBand\")\ndf_HTML.show(5)",
"+--------------------+--------------------+--------------------+--------------------+--------------------+\n| Geom| RedBand| BlueBand| GreenBand| CombinedBand|\n+--------------------+--------------------+--------------------+--------------------+--------------------+\n|POLYGON ((-58.702...|<img src=\"data:im...|<img src=\"data:im...|<img src=\"data:im...|<img src=\"data:im...|\n|POLYGON ((-58.286...|<img src=\"data:im...|<img src=\"data:im...|<img src=\"data:im...|<img src=\"data:im...|\n+--------------------+--------------------+--------------------+--------------------+--------------------+\n\n"
],
[
"display(HTML(df_HTML.limit(2).toPandas().to_html(escape=False)))",
"_____no_output_____"
]
],
[
[
"# User can also create some UDF manually to manipulate Geotiff dataframes",
"_____no_output_____"
]
],
[
[
"''' Sample UDF calculates sum of all the values in a band which are greater than 1000.0 '''\n\ndef SumOfValues(band):\n total = 0.0\n for num in band:\n if num>1000.0:\n total+=1\n return total\n \ncalculateSum = udf(SumOfValues, DoubleType())\nspark.udf.register(\"RS_Sum\", calculateSum)\n\nsumDF = df.selectExpr(\"RS_Sum(targetband) as sum\")\nsumDF.show()",
"+------+\n| sum|\n+------+\n| 753.0|\n|1017.0|\n+------+\n\n"
],
[
"''' Sample UDF to visualize a particular region of a GeoTiff image'''\n\ndef generatemask(band, width,height):\n for (i,val) in enumerate(band):\n if (i%width>=12 and i%width<26) and (i%height>=12 and i%height<26):\n band[i] = 255.0\n else:\n band[i] = 0.0\n return band\n\nmaskValues = udf(generatemask, ArrayType(DoubleType()))\nspark.udf.register(\"RS_MaskValues\", maskValues)\n\n\ndf_base64 = df.selectExpr(\"Geom\", \"RS_Base64(height,width,RS_Normalize(targetband), RS_Array(height*width,0.0), RS_Array(height*width, 0.0), RS_MaskValues(targetband,width,height)) as region\" )\ndf_HTML = df_base64.selectExpr(\"Geom\",\"RS_HTML(region) as selectedregion\")\ndisplay(HTML(df_HTML.limit(2).toPandas().to_html(escape=False)))\n",
"21/10/08 19:55:44 WARN SimpleFunctionRegistry: The function rs_maskvalues replaced a previously registered function.\n"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
d0802ab27bfdef4ce284378ee43ec0a003983eef | 14,805 | ipynb | Jupyter Notebook | Raspberry_Pi_Pico/notebooks/C.08-Stepper-Motors.ipynb | jckantor/cbe61622 | bdc08e6c4f0674c5e991617945cafd1b121d6b4b | [
"MIT"
] | 2 | 2021-11-22T20:36:35.000Z | 2021-12-07T07:52:10.000Z | notebooks/07.01-Stepper-Motors.ipynb | jckantor/cbe-virtual-laboratory | bdc08e6c4f0674c5e991617945cafd1b121d6b4b | [
"MIT"
] | null | null | null | notebooks/07.01-Stepper-Motors.ipynb | jckantor/cbe-virtual-laboratory | bdc08e6c4f0674c5e991617945cafd1b121d6b4b | [
"MIT"
] | 1 | 2021-12-11T20:39:32.000Z | 2021-12-11T20:39:32.000Z | 32.114967 | 514 | 0.528673 | [
[
[
"# Stepper Motors\n\n* [How to use a stepper motor with the Raspberry Pi Pico](https://www.youngwonks.com/blog/How-to-use-a-stepper-motor-with-the-Raspberry-Pi-Pico)\n* [Control 28BYJ-48 Stepper Motor with ULN2003 Driver & Arduino](https://lastminuteengineers.com/28byj48-stepper-motor-arduino-tutorial/) Description of the 27BYJ-48 stepper motor, ULN2003 driver, and Arduino code.\n* [28BYJ-48 stepper motor and ULN2003 Arduino (Quick tutorial for beginners)](https://www.youtube.com/watch?v=avrdDZD7qEQ) Video description.\n* [Stepper Motor - Wikipedia](https://en.wikipedia.org/wiki/Stepper_motor)\n\n<img src=\"https://upload.wikimedia.org/wikipedia/commons/6/66/28BYJ-48_unipolar_stepper_motor_with_ULN2003_driver.jpg\" alt=\"28BYJ-48 unipolar stepper motor with ULN2003 driver.jpg\" height=\"480\" width=\"640\">\n\n<a href=\"https://commons.wikimedia.org/w/index.php?curid=83551720\">Link</a>",
"_____no_output_____"
],
[
"## Stepper Motors\n\n\n[Adafruit](https://learn.adafruit.com/all-about-stepper-motors/types-of-steppers)\n\n\n[Adafruit](https://learn.adafruit.com/all-about-stepper-motors/types-of-steppers)\n\n",
"_____no_output_____"
],
[
"## Unipolar Stepper Motors\n\nThe ubiquitous 28BYJ-48 stepper motor with reduction gears that is manufactured by the millions and widely available at very low cost. [Elegoo, for example, sells kits of 5 motors with ULN2003 5V driver boards](https://www.elegoo.com/products/elegoo-uln2003-5v-stepper-motor-uln2003-driver-board) for less than $15/kit. The [UNL2003](https://en.wikipedia.org/wiki/ULN2003A) is a package of seven NPN Darlington transistors capable of 500ma output at 50 volts, with flyback diodes to drive inductive loads.\n\n\n\n\n\nThe 28BJY-48 has 32 teeth thus each full step corresponds to 360/32 = 11.25 degrees of rotation. A set of four reduction gears yields a 63.68395:1 gear reduction, or 2037.8864 steps per rotation. The maximum speed is 500 steps per second. If half steps are used, then there are 4075.7728 half steps per revolution at a maximum speed of 1000 half steps per second.\n\n(See https://youtu.be/15K9N1yVnhc for a teardown of the 28BYJ-48 motor.)",
"_____no_output_____"
],
[
"## Driving the 28BYJ-48 Stepper Motor\n\n(Also see https://www.youtube.com/watch?v=UJ4JjeCLuaI&ab_channel=TinkerTechTrove)\n\nThe following code assigns four GPIO pins to the four coils. For this code, the pins don't need to be contiguous or in order, but keeping that discipline may help later when we attempt to implement a driver using the PIO state machines of the Raspberry Pi Pico.\n\nNote that the Stepper class maintains an internal parameter corresponding to the current rotor position. This is used to index into the sequence data using modular arithmetic.\n\nSee []() for ideas on a Stepper class.",
"_____no_output_____"
]
],
[
[
"%serialconnect\n\nfrom machine import Pin\nimport time\n\nclass Stepper(object):\n \n step_seq = [[1, 0, 0, 0], \n [1, 1, 0, 0], \n [0, 1, 0, 0],\n [0, 1, 1, 0],\n [0, 0, 1, 0],\n [0, 0, 1, 1], \n [0, 0, 0, 1], \n [1, 0, 0, 1]]\n \n def __init__(self, gpio_pins):\n self.pins = [Pin(pin, Pin.OUT) for pin in gpio_pins]\n self.motor_position = 0\n \n def rotate(self, degrees=360):\n n_steps = abs(int(4075.7728*degrees/360))\n d = 1 if degrees > 0 else -1\n for _ in range(n_steps):\n self.motor_position += d\n phase = self.motor_position % len(self.step_seq)\n for i, value in enumerate(self.step_seq[phase]):\n self.pins[i].value(value)\n time.sleep(0.001) \n \nstepper = Stepper([2, 3, 4, 5])\nstepper.rotate(360)\nstepper.rotate(-360)\nprint(stepper.motor_position)",
"Found serial ports: /dev/cu.usbmodem14401, /dev/cu.Bluetooth-Incoming-Port \n\u001b[34mConnecting to --port=/dev/cu.usbmodem14401 --baud=115200 \u001b[0m\n\u001b[34mReady.\n\u001b[0m.0\n"
]
],
[
[
"Discussion:\n\n* What class methods should we build to support the syringe pump project?\n* Should we simplify and stick with half-step sequence?\n* How will be integrate motor operation with UI buttons and other controls?",
"_____no_output_____"
],
[
"## Programmable Input/Ouput (PIO)\n\n\n* MicroPython (https://datasheets.raspberrypi.org/pico/raspberry-pi-pico-python-sdk.pdf)\n* TinkerTechTrove [[github]](https://github.com/tinkertechtrove/pico-pi-playinghttps://github.com/tinkertechtrove/pico-pi-playing) [[youtube]](https://www.youtube.com/channel/UCnoBIijHK7NnCBVpUojYFTA/videoshttps://www.youtube.com/channel/UCnoBIijHK7NnCBVpUojYFTA/videos)\n* [Raspberry Pi Pico PIO - Ep. 1 - Overview with Pull, Out, and Parallel Port](https://youtu.be/YafifJLNr6I)",
"_____no_output_____"
]
],
[
[
"%serialconnect\n\nfrom machine import Pin\nfrom rp2 import PIO, StateMachine, asm_pio\nfrom time import sleep\nimport sys\n\n@asm_pio(set_init=(PIO.OUT_LOW,) * 4)\ndef prog():\n wrap_target()\n set(pins, 8) [31] # 8\n nop() [31]\n nop() [31]\n nop() [31]\n nop() [31]\n nop() [31]\n nop() [31]\n set(pins, 4) [31] # 4\n nop() [31]\n nop() [31]\n nop() [31]\n nop() [31]\n nop() [31]\n nop() [31]\n set(pins, 2) [31] # 2\n nop() [31]\n nop() [31]\n nop() [31]\n nop() [31]\n nop() [31]\n nop() [31]\n set(pins, 1) [31] # 1\n nop() [31]\n nop() [31]\n nop() [31]\n nop() [31]\n nop() [31]\n nop() [31]\n wrap()\n \n\nsm = StateMachine(0, prog, freq=100000, set_base=Pin(14))\n\n\nsm.active(1)\nsleep(10)\nsm.active(0)\nsm.exec(\"set(pins,0)\")",
"Found serial ports: /dev/cu.usbmodem14201, /dev/cu.Bluetooth-Incoming-Port \n\u001b[34mConnecting to --port=/dev/cu.usbmodem14201 --baud=115200 \u001b[0m\n\u001b[34mReady.\n\u001b[0m.."
],
[
"%serialconnect\n\nfrom machine import Pin\nfrom rp2 import PIO, StateMachine, asm_pio\nfrom time import sleep\nimport sys\n\n@asm_pio(set_init=(PIO.OUT_LOW,) * 4,\n out_init=(PIO.OUT_HIGH,) * 4,\n out_shiftdir=PIO.SHIFT_LEFT)\ndef prog():\n pull()\n mov(y, osr) # step pattern\n \n pull()\n mov(x, osr) # num steps\n \n jmp(not_x, \"end\")\n \n label(\"loop\")\n jmp(not_osre, \"step\") # loop pattern if exhausted\n mov(osr, y)\n \n label(\"step\")\n out(pins, 4) [31]\n nop() [31]\n nop() [31]\n nop() [31]\n\n jmp(x_dec,\"loop\")\n label(\"end\")\n set(pins, 8) [31] # 8\n\nsm = StateMachine(0, prog, freq=10000, set_base=Pin(14), out_base=Pin(14))\n\nsm.active(1)\nsm.put(2216789025) #1000 0100 0010 0001 1000010000100001\nsm.put(1000)\nsleep(10)\nsm.active(0)\nsm.exec(\"set(pins,0)\")\n",
"Found serial ports: /dev/cu.usbmodem14301, /dev/cu.Bluetooth-Incoming-Port \n\u001b[34mConnecting to --port=/dev/cu.usbmodem14301 --baud=115200 \u001b[0m\n\u001b[34mReady.\n\u001b[0m.."
],
[
"%serialconnect\n\nfrom machine import Pin\nfrom rp2 import PIO, StateMachine, asm_pio\nfrom time import sleep\nimport sys\n\n@asm_pio(set_init=(PIO.OUT_LOW,) * 4,\n out_init=(PIO.OUT_LOW,) * 4,\n out_shiftdir=PIO.SHIFT_RIGHT,\n in_shiftdir=PIO.SHIFT_LEFT)\ndef prog():\n pull()\n mov(x, osr) # num steps\n \n pull()\n mov(y, osr) # step pattern\n \n jmp(not_x, \"end\")\n \n label(\"loop\")\n jmp(not_osre, \"step\") # loop pattern if exhausted\n mov(osr, y)\n \n label(\"step\")\n out(pins, 4) [31]\n \n jmp(x_dec,\"loop\")\n label(\"end\")\n \n irq(rel(0))\n\n\nsm = StateMachine(0, prog, freq=10000, set_base=Pin(14), out_base=Pin(14))\ndata = [(1,2,4,8),(2,4,8,1),(4,8,1,2),(8,1,2,4)]\nsteps = 0\n\ndef turn(sm):\n global steps\n global data\n \n idx = steps % 4\n a = data[idx][0] | (data[idx][1] << 4) | (data[idx][2] << 8) | (data[idx][3] << 12)\n a = a << 16 | a\n \n #print(\"{0:b}\".format(a))\n sleep(1)\n \n sm.put(500)\n sm.put(a)\n \n steps += 500\n\nsm.irq(turn)\nsm.active(1)\nturn(sm)\n\nsleep(50)\nprint(\"done\")\nsm.active(0)\nsm.exec(\"set(pins,0)\")\n",
"serial exception on close write failed: [Errno 6] Device not configured\nFound serial ports: /dev/cu.usbmodem14301, /dev/cu.Bluetooth-Incoming-Port \n\u001b[34mConnecting to --port=/dev/cu.usbmodem14301 --baud=115200 \u001b[0m\n\u001b[34mReady.\n\u001b[0m......"
],
[
"%serialconnect\n \nimport time\nimport rp2\n\[email protected]_pio()\ndef irq_test():\n wrap_target()\n nop() [31]\n nop() [31]\n nop() [31]\n nop() [31]\n irq(0)\n nop() [31]\n nop() [31]\n nop() [31]\n nop() [31]\n irq(1)\n wrap()\n\n\nrp2.PIO(0).irq(lambda pio: print(pio.irq().flags()))\n#rp2.PIO(1).irq(lambda pio: print(\"1\"))\n\nsm = rp2.StateMachine(0, irq_test, freq=2000)\nsm1 = rp2.StateMachine(1, irq_test, freq=2000)\nsm.active(1)\n#sm1.active(1)\ntime.sleep(1)\nsm.active(0)\nsm1.active(0)",
"Found serial ports: /dev/cu.usbmodem14201, /dev/cu.Bluetooth-Incoming-Port \n\u001b[34mConnecting to --port=/dev/cu.usbmodem14201 --baud=115200 \u001b[0m\n\u001b[34mReady.\n\u001b[0m256\n512\n256\n512\n256\n512\n256\n512\n256\n512\n256\n512\n256\n512\n256\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
d0802c255f003fa8f6697b10b16938efbd1afe9e | 14,597 | ipynb | Jupyter Notebook | Image/image_smoothing.ipynb | pberezina/earthengine-py-notebooks | 4cbe3c52bcc9ed3f1337bf097aa5799442991a5e | [
"MIT"
] | 1 | 2020-03-20T19:39:34.000Z | 2020-03-20T19:39:34.000Z | Image/image_smoothing.ipynb | pberezina/earthengine-py-notebooks | 4cbe3c52bcc9ed3f1337bf097aa5799442991a5e | [
"MIT"
] | null | null | null | Image/image_smoothing.ipynb | pberezina/earthengine-py-notebooks | 4cbe3c52bcc9ed3f1337bf097aa5799442991a5e | [
"MIT"
] | null | null | null | 81.547486 | 9,064 | 0.840721 | [
[
[
"<table class=\"ee-notebook-buttons\" align=\"left\">\n <td><a target=\"_blank\" href=\"https://github.com/giswqs/earthengine-py-notebooks/tree/master/Image/image_smoothing.ipynb\"><img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /> View source on GitHub</a></td>\n <td><a target=\"_blank\" href=\"https://nbviewer.jupyter.org/github/giswqs/earthengine-py-notebooks/blob/master/Image/image_smoothing.ipynb\"><img width=26px src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png\" />Notebook Viewer</a></td>\n <td><a target=\"_blank\" href=\"https://mybinder.org/v2/gh/giswqs/earthengine-py-notebooks/master?filepath=Image/image_smoothing.ipynb\"><img width=58px src=\"https://mybinder.org/static/images/logo_social.png\" />Run in binder</a></td>\n <td><a target=\"_blank\" href=\"https://colab.research.google.com/github/giswqs/earthengine-py-notebooks/blob/master/Image/image_smoothing.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /> Run in Google Colab</a></td>\n</table>",
"_____no_output_____"
],
[
"## Install Earth Engine API\nInstall the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geehydro](https://github.com/giswqs/geehydro). The **geehydro** Python package builds on the [folium](https://github.com/python-visualization/folium) package and implements several methods for displaying Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, `Map.centerObject()`, and `Map.setOptions()`.\nThe following script checks if the geehydro package has been installed. If not, it will install geehydro, which automatically install its dependencies, including earthengine-api and folium.",
"_____no_output_____"
]
],
[
[
"import subprocess\n\ntry:\n import geehydro\nexcept ImportError:\n print('geehydro package not installed. Installing ...')\n subprocess.check_call([\"python\", '-m', 'pip', 'install', 'geehydro'])",
"_____no_output_____"
]
],
[
[
"Import libraries",
"_____no_output_____"
]
],
[
[
"import ee\nimport folium\nimport geehydro",
"_____no_output_____"
]
],
[
[
"Authenticate and initialize Earth Engine API. You only need to authenticate the Earth Engine API once. ",
"_____no_output_____"
]
],
[
[
"try:\n ee.Initialize()\nexcept Exception as e:\n ee.Authenticate()\n ee.Initialize()",
"_____no_output_____"
]
],
[
[
"## Create an interactive map \nThis step creates an interactive map using [folium](https://github.com/python-visualization/folium). The default basemap is the OpenStreetMap. Additional basemaps can be added using the `Map.setOptions()` function. \nThe optional basemaps can be `ROADMAP`, `SATELLITE`, `HYBRID`, `TERRAIN`, or `ESRI`.",
"_____no_output_____"
]
],
[
[
"Map = folium.Map(location=[40, -100], zoom_start=4)\nMap.setOptions('HYBRID')",
"_____no_output_____"
]
],
[
[
"## Add Earth Engine Python script ",
"_____no_output_____"
]
],
[
[
"image = ee.Image('srtm90_v4')\n\nsmoothed = image.reduceNeighborhood(**{\n 'reducer': ee.Reducer.mean(),\n 'kernel': ee.Kernel.square(3),\n})\n\n# vis_params = {'min': 0, 'max': 3000}\n# Map.addLayer(image, vis_params, 'SRTM original')\n# Map.addLayer(smooth, vis_params, 'SRTM smoothed')\nMap.setCenter(-112.40, 42.53, 12)\nMap.addLayer(ee.Terrain.hillshade(image), {}, 'Original hillshade')\nMap.addLayer(ee.Terrain.hillshade(smoothed), {}, 'Smoothed hillshade')\n",
"_____no_output_____"
]
],
[
[
"## Display Earth Engine data layers ",
"_____no_output_____"
]
],
[
[
"Map.setControlVisibility(layerControl=True, fullscreenControl=True, latLngPopup=True)\nMap",
"_____no_output_____"
]
]
] | [
"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"
]
] |
d080475b95bd50f0ca1638e97f646567f2fd949c | 3,666 | ipynb | Jupyter Notebook | notebooks/regression/esdc_application/old/app_sample_3_experiment.ipynb | IPL-UV/sakame | e660c4ac82ac52d5136d3cd765d59d409b74b4ce | [
"MIT"
] | null | null | null | notebooks/regression/esdc_application/old/app_sample_3_experiment.ipynb | IPL-UV/sakame | e660c4ac82ac52d5136d3cd765d59d409b74b4ce | [
"MIT"
] | null | null | null | notebooks/regression/esdc_application/old/app_sample_3_experiment.ipynb | IPL-UV/sakame | e660c4ac82ac52d5136d3cd765d59d409b74b4ce | [
"MIT"
] | null | null | null | 24.604027 | 217 | 0.561648 | [
[
[
"import sys\nsys.path.insert(0, '/home/emmanuel/code/kernellib')\nsys.path.insert(0, '/home/emmanuel/code/py_esdc')\nsys.path.insert(0, '/home/emmanuel/projects/2019_sakame/src/')\n\nfrom experiments.sampling import SamplingExp\n\n%load_ext autoreload\n%autoreload 2",
"The autoreload extension is already loaded. To reload it, use:\n %reload_ext autoreload\n"
]
],
[
[
"## Run Sampling Experiment (Land Surface Temperature)",
"_____no_output_____"
]
],
[
[
"%%time \n\nstart_time = '2010-06-06T00:00:00.000000000' #'2010-06'\nend_time = '2010-06-06T00:00:00.000000000'#'2010-08'\nnum_training = 2000\nvariables = ['land_surface_temperature']\nwindow_sizes = [3] #, 15] #[3, 5, 7, 9, 11, 13, 15]\nsave_names = 'test'\nsampling_exp = SamplingExp(\n variables=variables,\n window_sizes=window_sizes, \n save_names=save_names,\n start_time=start_time,\n end_time=end_time,\n num_training=num_training)\n\nsampling_exp.run_experiment(True);",
"Extracting minicubes...\n3\nNo data fitted...extracting datacube\n/media/disk/databases/BACI-CABLAB/low_res_data/land_surface_temperature\nVariable: land_surface_temperature\nWindow Size: 3\nInitialize data class\nLoad minicubes\nExtract datacube for plots...\n/media/disk/databases/BACI-CABLAB/low_res_data/land_surface_temperature\nTime Stamp: 2010-06-06T00:00:00.000000000\n"
]
],
[
[
"## Run Sampling Experiment (Gross Primary Productivity)",
"_____no_output_____"
],
[
"### Load Results",
"_____no_output_____"
]
],
[
[
"## Run Sampling Experiment (Land Surface Temperature)",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
]
] |
d0804948190cf8a16e5dedfb2498d26bd7b9b918 | 277,549 | ipynb | Jupyter Notebook | Traffic_Sign_Classifier.ipynb | Ansheel9/Traffic-Sign-Classifier | 99717f415224ce3534b0abc69c24053ef8414ca1 | [
"MIT"
] | null | null | null | Traffic_Sign_Classifier.ipynb | Ansheel9/Traffic-Sign-Classifier | 99717f415224ce3534b0abc69c24053ef8414ca1 | [
"MIT"
] | null | null | null | Traffic_Sign_Classifier.ipynb | Ansheel9/Traffic-Sign-Classifier | 99717f415224ce3534b0abc69c24053ef8414ca1 | [
"MIT"
] | null | null | null | 315.396591 | 238,152 | 0.920183 | [
[
[
"# 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_____"
]
],
[
[
"import pickle\nimport numpy as np\nimport pandas as pd\nimport random\nfrom sklearn.utils import shuffle\nimport tensorflow as tf\nfrom tensorflow.contrib.layers import flatten\nimport cv2\nimport glob\nimport os\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\n\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"---\n## Step 0: Load The Data",
"_____no_output_____"
]
],
[
[
"# TODO: Fill this in based on where you saved the training and testing data\n\ntraining_file = \"../data/train.p\"\nvalidation_file= \"../data/valid.p\"\ntesting_file = \"../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 \nX_train, y_train = train['features'], train['labels']\nX_valid, y_valid = valid['features'], valid['labels']\nX_test, y_test = test['features'], test['labels']",
"_____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\n# TODO: Number of training examples\nn_train = len(X_train)\n\n# TODO: Number of validation examples\nn_validation = len(X_valid)\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 testing examples =\", n_test)\nprint(\"Image data shape =\", image_shape)\nprint(\"Number of classes =\", n_classes)",
"Number of training examples = 34799\nNumber of testing examples = 12630\nImage data shape = (32, 32, 3)\nNumber of classes = 43\n"
]
],
[
[
"### 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_____"
]
],
[
[
"### Data exploration visualization code goes here.\n### Feel free to use as many code cells as needed.\n\nindex = random.randint(0, len(X_train))\nimage = X_train[index].squeeze()\n\nplt.figure(figsize=(1,1))\nplt.imshow(image)\nprint(y_train[index])",
"10\n"
]
],
[
[
"----\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### Feel free to use as many code cells as needed.\n\n#Convert to gray\nX_train_gry = np.sum(X_train/3, axis=3, keepdims=True)\n\nX_valid_gry = np.sum(X_valid/3, axis=3, keepdims=True)\n\nX_test_gry = np.sum(X_test/3, axis=3, keepdims=True)\n\n#Normalize Images\nX_train_norm = (X_train_gry)/255 \nX_valid_norm = (X_valid_gry)/255 \nX_test_norm = (X_test_gry)/255\n\n#Shuffle dataset\nX_train_norm, y_train = shuffle(X_train_gry, y_train)\nX_valid_norm, y_valid = shuffle(X_valid_gry, y_valid)",
"_____no_output_____"
]
],
[
[
"### Model Architecture",
"_____no_output_____"
]
],
[
[
"### Define your architecture here.\n### Feel free to use as many code cells as needed.\n\ndef LeNet(x):\n #HyperParameters\n mu = 0\n sigma = 0.1\n keep_prob = 0.5\n \n # SOLUTION: Layer 1: Convolutional. Input = 32x32x1. Output = 28x28x6.\n conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 1, 6), mean = mu, stddev = sigma))\n conv1_b = tf.Variable(tf.zeros(6))\n conv1 = tf.nn.conv2d(x, conv1_W, strides=[1, 1, 1, 1], padding='VALID') + conv1_b\n conv1 = tf.nn.relu(conv1)\n conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')\n\n # SOLUTION: Layer 2: Convolutional. Output = 10x10x16.\n conv2_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 6, 16), mean = mu, stddev = sigma))\n conv2_b = tf.Variable(tf.zeros(16))\n conv2 = tf.nn.conv2d(conv1, conv2_W, strides=[1, 1, 1, 1], padding='VALID') + conv2_b\n conv2 = tf.nn.relu(conv2)\n conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')\n\n # SOLUTION: Flatten. Input = 5x5x16. Output = 400.\n fc0 = flatten(conv2)\n \n # SOLUTION: Layer 3: Fully Connected. Input = 400. Output = 120.\n fc1_W = tf.Variable(tf.truncated_normal(shape=(400, 120), mean = mu, stddev = sigma))\n fc1_b = tf.Variable(tf.zeros(120))\n fc1 = tf.matmul(fc0, fc1_W) + fc1_b\n fc1 = tf.nn.relu(fc1)\n #fc1 = tf.nn.dropout(fc1, keep_prob)\n\n # SOLUTION: Layer 4: Fully Connected. Input = 120. Output = 84.\n fc2_W = tf.Variable(tf.truncated_normal(shape=(120, 84), mean = mu, stddev = sigma))\n fc2_b = tf.Variable(tf.zeros(84))\n fc2 = tf.matmul(fc1, fc2_W) + fc2_b\n fc2 = tf.nn.relu(fc2)\n #fc2 = tf.nn.dropout(fc2, keep_prob)\n\n # SOLUTION: Layer 5: Fully Connected. Input = 84. Output = 10.\n fc3_W = tf.Variable(tf.truncated_normal(shape=(84, 43), mean = mu, stddev = sigma))\n fc3_b = tf.Variable(tf.zeros(43))\n logits = tf.matmul(fc2, fc3_W) + fc3_b\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.\nx = tf.placeholder(tf.float32, (None, 32, 32, 1))\ny = tf.placeholder(tf.int32, (None))\none_hot_y = tf.one_hot(y, 43)",
"_____no_output_____"
],
[
"#Training Pipeline\nrate = 0.001\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)",
"_____no_output_____"
],
[
"#Model Evaluation\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",
"_____no_output_____"
],
[
"EPOCHS = 30\nBATCH_SIZE = 128\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n num_examples = len(X_train_norm)\n \n print(\"Training...\")\n print()\n for i in range(EPOCHS):\n X_train_norm, y_train = shuffle(X_train_norm, y_train)\n for offset in range(0, num_examples, BATCH_SIZE):\n end = offset + BATCH_SIZE\n batch_x, batch_y = X_train_norm[offset:end], y_train[offset:end]\n sess.run(training_operation, feed_dict={x: batch_x, y: batch_y})\n \n validation_accuracy = evaluate(X_valid_norm, y_valid)\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.792\n\nEPOCH 2 ...\nValidation Accuracy = 0.853\n\nEPOCH 3 ...\nValidation Accuracy = 0.874\n\nEPOCH 4 ...\nValidation Accuracy = 0.889\n\nEPOCH 5 ...\nValidation Accuracy = 0.902\n\nEPOCH 6 ...\nValidation Accuracy = 0.889\n\nEPOCH 7 ...\nValidation Accuracy = 0.894\n\nEPOCH 8 ...\nValidation Accuracy = 0.910\n\nEPOCH 9 ...\nValidation Accuracy = 0.900\n\nEPOCH 10 ...\nValidation Accuracy = 0.919\n\nEPOCH 11 ...\nValidation Accuracy = 0.921\n\nEPOCH 12 ...\nValidation Accuracy = 0.920\n\nEPOCH 13 ...\nValidation Accuracy = 0.913\n\nEPOCH 14 ...\nValidation Accuracy = 0.907\n\nEPOCH 15 ...\nValidation Accuracy = 0.924\n\nEPOCH 16 ...\nValidation Accuracy = 0.918\n\nEPOCH 17 ...\nValidation Accuracy = 0.917\n\nEPOCH 18 ...\nValidation Accuracy = 0.920\n\nEPOCH 19 ...\nValidation Accuracy = 0.930\n\nEPOCH 20 ...\nValidation Accuracy = 0.928\n\nEPOCH 21 ...\nValidation Accuracy = 0.933\n\nEPOCH 22 ...\nValidation Accuracy = 0.934\n\nEPOCH 23 ...\nValidation Accuracy = 0.917\n\nEPOCH 24 ...\nValidation Accuracy = 0.919\n\nEPOCH 25 ...\nValidation Accuracy = 0.931\n\nEPOCH 26 ...\nValidation Accuracy = 0.923\n\nEPOCH 27 ...\nValidation Accuracy = 0.939\n\nEPOCH 28 ...\nValidation Accuracy = 0.937\n\nEPOCH 29 ...\nValidation Accuracy = 0.915\n\nEPOCH 30 ...\nValidation Accuracy = 0.937\n\nModel saved\n"
],
[
"with tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('.'))\n\n test_accuracy = evaluate(X_test_gry, y_test)\n print(\"Test Accuracy = {:.3f}\".format(test_accuracy))\n",
"INFO:tensorflow:Restoring parameters from ./lenet\nTest Accuracy = 0.921\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_____"
]
],
[
[
"### Load the images and plot them here.\n### Feel free to use as many code cells as needed.\n#fig, axs = plt.subplots(2,4, figsize=(4, 2))\n#fig.subplots_adjust(hspace = .2, wspace=.001)\n#axs = axs.ravel()\n#../data/Images/traffic*.png\n\nfig, axes = plt.subplots(1, 5, figsize=(18,4))\nnew_images = []\nfor i, img in enumerate(sorted(glob.glob('../data/Images/traffic*.png'))):\n image = mpimg.imread(img)\n axes[i].imshow(image)\n axes[i].axis('off')\n image = cv2.resize(image, (32, 32))\n image = np.sum(image/3, axis = 2, keepdims = True)\n image = (image - image.mean())/np.std(image)\n new_images.append(image)\n print(image.shape)\n#new_images.shape\nX_new_images = np.asarray(new_images)\ny_new_images = np.array([12, 18, 38, 18, 38])\nprint(X_new_images.shape)",
"(32, 32, 1)\n(32, 32, 1)\n(32, 32, 1)\n(32, 32, 1)\n(32, 32, 1)\n(5, 32, 32, 1)\n"
]
],
[
[
"### 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#my_labels = [35, 12, 11, 24, 16, 14, 1, 4]\nkeep_prob = tf.placeholder(tf.float32)\n\nwith tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('.'))\n \n sess = tf.get_default_session()\n new_images_accuracy = sess.run(accuracy_operation, feed_dict={x: X_new_images, y: y_new_images, keep_prob: 1.0})\n \n print(\"Test Accuracy = {:.3f}\".format(new_images_accuracy))",
"INFO:tensorflow:Restoring parameters from ./lenet\nTest Accuracy = 0.600\n"
]
],
[
[
"### Analyze Performance",
"_____no_output_____"
]
],
[
[
"### Calculate the accuracy for these 5 new images. \n### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.\n\n\nwith tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('.'))\n \n sess = tf.get_default_session()\n prediction = sess.run(logits, feed_dict={x: X_new_images, y: y_new_images, keep_prob: 1.0})\n\n print(np.argmax(prediction,1))",
"INFO:tensorflow:Restoring parameters from ./lenet\n[12 18 12 18 3]\n"
]
],
[
[
"### Output Top 5 Softmax Probabilities For Each Image Found on the Web",
"_____no_output_____"
],
[
"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.\n\nwith tf.Session() as sess:\n print(sess.run(tf.nn.top_k(tf.nn.softmax(prediction), k=5)))",
"TopKV2(values=array([[ 0.13296957, 0.09634399, 0.08997886, 0.06783284, 0.06598242],\n [ 0.13137311, 0.07682533, 0.07135586, 0.06071901, 0.05829126],\n [ 0.16518918, 0.12350544, 0.0783048 , 0.07044089, 0.06533803],\n [ 0.18929006, 0.11967038, 0.07411727, 0.06745335, 0.04894404],\n [ 0.16643417, 0.11010567, 0.09781482, 0.0726616 , 0.05540863]], dtype=float32), indices=array([[12, 9, 5, 10, 38],\n [18, 8, 5, 7, 4],\n [12, 38, 5, 13, 32],\n [18, 4, 26, 8, 7],\n [ 3, 5, 38, 32, 8]], dtype=int32))\n"
]
],
[
[
"### 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",
"code",
"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"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
]
] |
d0804f1acaa8f0298df44ae3a7ce2699078cc23b | 3,230 | ipynb | Jupyter Notebook | examples/example.ipynb | VamshiK-Kasula/CarND-Advanced-Lane-Lines | 94954da887c64aef0deecac1a0638f42f3b39a70 | [
"MIT"
] | null | null | null | examples/example.ipynb | VamshiK-Kasula/CarND-Advanced-Lane-Lines | 94954da887c64aef0deecac1a0638f42f3b39a70 | [
"MIT"
] | null | null | null | examples/example.ipynb | VamshiK-Kasula/CarND-Advanced-Lane-Lines | 94954da887c64aef0deecac1a0638f42f3b39a70 | [
"MIT"
] | null | null | null | 30.186916 | 120 | 0.572136 | [
[
[
"## Advanced Lane Finding Project\n\nThe goals / steps of this project are the following:\n\n* Compute the camera calibration matrix and distortion coefficients given a set of chessboard images.\n* Apply a distortion correction to raw images.\n* Use color transforms, gradients, etc., to create a thresholded binary image.\n* Apply a perspective transform to rectify binary image (\"birds-eye view\").\n* Detect lane pixels and fit to find the lane boundary.\n* Determine the curvature of the lane and vehicle position with respect to center.\n* Warp the detected lane boundaries back onto the original image.\n* Output visual display of the lane boundaries and numerical estimation of lane curvature and vehicle position.\n\n---\n## First, I'll compute the camera calibration using chessboard images",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport cv2\nimport glob\nimport matplotlib.pyplot as plt\n%matplotlib qt\n\n# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)\nobjp = np.zeros((6*9,3), np.float32)\nobjp[:,:2] = np.mgrid[0:9,0:6].T.reshape(-1,2)\n\n# Arrays to store object points and image points from all the images.\nobjpoints = [] # 3d points in real world space\nimgpoints = [] # 2d points in image plane.\n\n# Make a list of calibration images\nimages = glob.glob('../camera_cal/calibration*.jpg')\n\n# Step through the list and search for chessboard corners\nfor fname in images:\n img = cv2.imread(fname)\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n\n # Find the chessboard corners\n ret, corners = cv2.findChessboardCorners(gray, (9,6),None)\n\n # If found, add object points, image points\n if ret == True:\n objpoints.append(objp)\n imgpoints.append(corners)\n\n # Draw and display the corners\n img = cv2.drawChessboardCorners(img, (9,6), corners, ret)\n cv2.imshow('img',img)\n cv2.waitKey(500)\n\ncv2.destroyAllWindows()",
"_____no_output_____"
]
],
[
[
"## And so on and so forth...",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
d08059265696dd0fcaf3e7b08a38988a469a7d15 | 1,872 | ipynb | Jupyter Notebook | notebooks/004_Temario.ipynb | AltamarMx/clase_muestra | 9f369ed1b36be9555602c4a898d45cab7520830d | [
"MIT"
] | 1 | 2022-01-13T23:59:12.000Z | 2022-01-13T23:59:12.000Z | notebooks/004_Temario.ipynb | AltamarMx/clase_muestra | 9f369ed1b36be9555602c4a898d45cab7520830d | [
"MIT"
] | null | null | null | notebooks/004_Temario.ipynb | AltamarMx/clase_muestra | 9f369ed1b36be9555602c4a898d45cab7520830d | [
"MIT"
] | null | null | null | 33.428571 | 123 | 0.64156 | [
[
[
"1. Estructura de trabajo\n1. Calculo de energía solar por día, semana, mes, año\n1. Rosa de los vientos con windrose\n1. Trucos en la libreta de Jupyter\n1. Análisis de clima a partir de un EPW de un sitio con repositorio incluido en jupyter\n1. Heat map de sensación térmica\n1. heat map error diario con calplot\n1. Análisis de datos categóricos\n1. Grafíca de trayectoria solar aparente con interact\n1. Organiza una rifa \n1. Calcula y grafica promedio, desviación estándard, máximo y mínimo de serie de datos del día promedio\n1. Diccionario de diccionario para generar una base de datos\n1. Ambientes virtuales, caso ejemplo pandas y xlsx y xls\n1. Escribe una clase para para calcular métricas de simulaciones y obtener resultados directo a tu tesis en LaTeX\n1. Prepara tu figura para insertarla en LaTeX\n1. Define funciones para facilitar tu flujo de trabajo en Matplotlib, caso sensores de CO2\n1. Introducción a cartopy\n1. Ajuste de polinomios\n1. Ajuste de funciones de distribucion de probabilidad\n1. Gráficas \"compuestas\" \n1. Joy plots\n1. Formato de print caso, guardar archivos\n1. Python en microcontroladores\n1. El ambiente de Joel Grus",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown"
]
] |
d08062292c35e8bb7d4e1eaad732a8ef4334812d | 10,157 | ipynb | Jupyter Notebook | 05. Python for Data Analysis - NumPy/5.19 indexing_selection_np_array.ipynb | shrey-c/DSC-ML-numpy-pandas | e62ab324c3308ed5ef7533ee1d448e146b7a9ab3 | [
"BSD-3-Clause"
] | 1 | 2020-01-25T09:23:53.000Z | 2020-01-25T09:23:53.000Z | 05. Python for Data Analysis - NumPy/5.19 indexing_selection_np_array.ipynb | shrey-c/DSC-ML-numpy-pandas | e62ab324c3308ed5ef7533ee1d448e146b7a9ab3 | [
"BSD-3-Clause"
] | null | null | null | 05. Python for Data Analysis - NumPy/5.19 indexing_selection_np_array.ipynb | shrey-c/DSC-ML-numpy-pandas | e62ab324c3308ed5ef7533ee1d448e146b7a9ab3 | [
"BSD-3-Clause"
] | 6 | 2020-01-25T06:21:54.000Z | 2020-05-31T13:01:52.000Z | 21.937365 | 136 | 0.547406 | [
[
[
"import numpy as np",
"_____no_output_____"
],
[
"arr = np.arange(0,11)",
"_____no_output_____"
],
[
"arr",
"_____no_output_____"
],
[
"# Simplest way to pick an element or some of the elements from an array is similar to indexing in a python list.\narr[8] # Gives value at the index 8",
"_____no_output_____"
],
[
"# Slice Notations [start:stop]\narr[1:5] # 1 inclusive and 5 exclusive",
"_____no_output_____"
],
[
"# Another Example of Slicing\narr[0:5]",
"_____no_output_____"
],
[
"# To have everything from beginning to the index 6 we use the following syntax on a numpy array :\nprint(arr[:6]) # No need to define the starting point and this basically means arr[0:6]\n# To have everything from a 5th index to the last we use the following syntax on a numpy array :\nprint(arr[5:])",
"_____no_output_____"
]
],
[
[
"# Broadcasting the Value\n**Numpy arrays differ from normal python list due to their ability to broadcast.**",
"_____no_output_____"
]
],
[
[
"arr[0:5] = 100 # Broacasts the value 100 to first 5 digits.",
"_____no_output_____"
],
[
"arr",
"_____no_output_____"
],
[
"# Reset the array\narr = np.arange(0,11)",
"_____no_output_____"
],
[
"arr",
"_____no_output_____"
],
[
"slice_of_arr = arr[0:6]",
"_____no_output_____"
],
[
"slice_of_arr",
"_____no_output_____"
],
[
"# To grab everything in the slice \nslice_of_arr[:]",
"_____no_output_____"
],
[
"# Broadcasting after grabbing everything in the array \nslice_of_arr[:] = 99",
"_____no_output_____"
],
[
"slice_of_arr",
"_____no_output_____"
],
[
"arr",
"_____no_output_____"
],
[
"# Notice above how not only slice_of_arr got changed due to the broadcast but the array arr was also changed.\n# Slice and the original array both got changed in terms of values.\n# Data is not copied but rather just copied or pointed from original array.\n# Reason behind such behaviour is that to prevent memory issues while dealing with large arrays.\n# It basically means numpy prefers not setting copies of arrays and would rather point slices to their original parent arrays.\n# Use copy() method which is array_name.copy()",
"_____no_output_____"
],
[
"arr_copy = arr.copy()",
"_____no_output_____"
],
[
"arr_copy",
"_____no_output_____"
],
[
"arr_copy[0:5] = 23",
"_____no_output_____"
],
[
"arr",
"_____no_output_____"
],
[
"arr_copy #Since we have copied now we can see that arr and arr_copy would be different even after broadcasting.\n# Original array remains unaffected despite changes on the copied array.\n# Main idea here is that if you grab the actual slice of the array and set it as variable without calling the method copy\n# on the array then you are just seeing the link to original array and changes on slice would reflect on original/parent array.",
"_____no_output_____"
]
],
[
[
"# 2D Array/Matrix",
"_____no_output_____"
]
],
[
[
"arr_2d = np.array([[5,10,15],[20,25,30],[35,40,45]])",
"_____no_output_____"
],
[
"arr_2d # REMEMBER If having confusion regarding dimensions of the matrix just call shape.",
"_____no_output_____"
],
[
"arr_2d.shape # 3 rows, 3 columns",
"_____no_output_____"
],
[
"# Two general formats for grabbing elements from a 2D array or matrix format :\n# (i) Double Bracket Format (ii) Single Bracket Format with comma (Recommended)\n\n# (i) Double Bracket Format\narr_2d[0][:] # Gives all the elements inside the 0th index of array arr.\n# arr_2d[0][:] Also works",
"_____no_output_____"
],
[
"arr_2d[1][2] # Gives the element at index 2 of the 1st index of arr_2d i.e. 30",
"_____no_output_____"
],
[
"# (ii) Single Bracket Format with comma (Recommended) : Removes [][] 2 square brackets with a tuple kind (x,y) format\n# To print 30 we do the following 1st row and 2nd index\narr_2d[1,2]",
"_____no_output_____"
],
[
"# Say we want sub matrices from the matrix arr_2d\narr_2d[:3,1:] # Everything upto the third row, and anything from column 1 onwards.",
"_____no_output_____"
],
[
"arr_2d[1:,:]",
"_____no_output_____"
]
],
[
[
"# Conditional Selection",
"_____no_output_____"
]
],
[
[
"arr = np.arange(1,11)",
"_____no_output_____"
],
[
"arr",
"_____no_output_____"
],
[
"# Taking the array arr and comapring it using comparison operators to get a full boolean array out of this.\nbool_arr = arr > 5\n'''\n1. Getting the array and using a comparison operator on it will actually return a boolean array.\n2. An array with boolean values in response to our condition.\n3. Now we can use the boolean array to actually index or conditionally select elements from the original array where boolean\narray is true.\n\n'''",
"_____no_output_____"
],
[
"bool_arr",
"_____no_output_____"
],
[
"arr[bool_arr] # Gives us only the results which are only true.",
"_____no_output_____"
],
[
"# Doing what's described above in one line will be \narr[arr<3] # arr[comaprison condition] Get used to this notation we use this a lot especially in Pandas!",
"_____no_output_____"
]
],
[
[
"# Exercise\n\n1. Create a new 2d array np.arange(50).reshape(5,10).\n2. Grab any 2sub matrices from the 5x10 chunk.\n",
"_____no_output_____"
]
],
[
[
"arr_2d = np.arange(50).reshape(5,10)",
"_____no_output_____"
],
[
"arr_2d",
"_____no_output_____"
],
[
"# Selecting 11 to 35\narr_2d[1:4,1:6]# Keep in mind it is exclusive for the end value in the start:end format of indexing.",
"_____no_output_____"
],
[
"# Selecting 5-49\narr_2d[0:,5:]",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"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"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
d0806878a16e071dd1a82eb35dc85a4f27bcf2ca | 426,415 | ipynb | Jupyter Notebook | modules/03_NumPy_Pandas_Matplotlib/03_NumPy_Pandas_Matplotlib_ICESat_exercises.ipynb | UW-GDA/gda_course_2021 | 96bf56c3d299ef8c78f86686838180c8a95537c3 | [
"MIT"
] | 17 | 2021-01-05T05:54:43.000Z | 2022-02-22T23:27:46.000Z | modules/03_NumPy_Pandas_Matplotlib/03_NumPy_Pandas_Matplotlib_ICESat_exercises.ipynb | UW-GDA/gda_course_2021 | 96bf56c3d299ef8c78f86686838180c8a95537c3 | [
"MIT"
] | null | null | null | modules/03_NumPy_Pandas_Matplotlib/03_NumPy_Pandas_Matplotlib_ICESat_exercises.ipynb | UW-GDA/gda_course_2021 | 96bf56c3d299ef8c78f86686838180c8a95537c3 | [
"MIT"
] | 13 | 2021-01-05T21:00:10.000Z | 2022-03-02T22:39:50.000Z | 382.434978 | 107,068 | 0.93644 | [
[
[
"# NumPy, Pandas and Matplotlib with ICESat \nUW Geospatial Data Analysis \nCEE498/CEWA599 \nDavid Shean \n\n## Objectives\n1. Solidify basic skills with NumPy, Pandas, and Matplotlib\n2. Learn basic data manipulation, exploration, and visualizatioin with a relatively small, clean point dataset (65K points)\n3. Learn a bit more about the ICESat mission, the GLAS instrument, and satellite laser altimetry\n4. Explore outlier removal, grouping and clustering",
"_____no_output_____"
],
[
"# ICESat GLAS Background\nThe NASA Ice Cloud and land Elevation Satellite ([ICESat](https://icesat.gsfc.nasa.gov/icesat/)) was a NASA mission carrying the Geosciences Laser Altimeter System (GLAS) instrument: a space laser, pointed down at the Earth (and unsuspecting Earthlings). \n\nIt measured surface elevations by precisely tracking laser pulses emitted from the spacecraft at a rate of 40 Hz (a new pulse every 0.025 seconds). These pulses traveled through the atmosphere, reflected off the surface, back up through the atmosphere, and into space, where some small fraction of that original energy was received by a telescope on the spacecraft. The instrument electronics precisely recorded the time when these intrepid photons left the instrument and when they returned. The position and orientation of the spacecraft was precisely known, so the two-way traveltime (and assumptions about the speed of light and propagation through the atmosphere) allowed for precise forward determination of the spot on the Earth's surface (or cloud tops, as was often the case) where the reflection occurred. The laser spot size varied during the mission, but was ~70 m in diameter. \n\nICESat collected billions of measurements from 2003 to 2009, and was operating in a \"repeat-track\" mode that sacrificed spatial coverage for more observations along the same ground tracks over time. One primary science focus involved elevation change over the Earth's ice sheets. It allowed for early measurements of full Antarctic and Greenland ice sheet elevation change, which offered a detailed look at spatial distribution and rates of mass loss, and total ice sheet contributions to sea level rise. \n\nThere were problems with the lasers during the mission, so it operated in short campaigns lasting only a few months to prolong the full mission lifetime. While the primary measurements focused on the polar regions, many measurements were also collected over lower latitudes, to meet other important science objectives (e.g., estimating biomass in the Earth's forests, observing sea surface height/thickness over time). ",
"_____no_output_____"
],
[
"# Sample GLAS dataset for CONUS\nA few years ago, I wanted to evaluate ICESat coverage of the Continental United States (CONUS). The primary application was to extract a set of accurate control points to co-register a large set of high-resolution digital elevation modoels (DEMs) derived from satellite stereo imagery. I wrote some Python/shell scripts to download, filter, and process all of the [GLAH14 L2 Global Land Surface Altimetry Data](https://nsidc.org/data/GLAH14/versions/34) granules in parallel ([https://github.com/dshean/icesat_tools](https://github.com/dshean/icesat_tools)).\n\nThe high-level workflow is here: https://github.com/dshean/icesat_tools/blob/master/glas_proc.py#L24. These tools processed each HDF5 (H5) file and wrote out csv files containing “good” points. These csv files were concatenated to prepare the single input csv (`GLAH14_tllz_conus_lulcfilt_demfilt.csv`) that we will use for this tutorial. \n\nThe csv contains ICESat GLAS shots that passed the following filters:\n* Within some buffer (~110 km) of mapped glacier polygons from the [Randolph Glacier Inventory (RGI)](https://www.glims.org/RGI/)\n* Returns from exposed bare ground (landcover class 31) or snow/ice (12) according to a 30-m Land-use/Land-cover dataset (2011 NLCD, https://www.mrlc.gov/data?f%5B0%5D=category%3Aland%20cover)\n* Elevation values within some threshold (200 m) of elevations sampled from an external reference DEM (void-filled 1/3-arcsec [30-m] SRTM-GL1, https://lpdaac.usgs.gov/products/srtmgl1v003/), used to remove spurious points and returns from clouds.\n* Various other ICESat-specific quality flags (see comments in `glas_proc.py` for details)\n\nThe final file contains a relatively small subset (~65K) of the total shots in the original GLAH14 data granules from the full mission timeline (2003-2009). The remaining points should represent returns from the Earth's surface with reasonably high quality, and can be used for subsequent analysis.",
"_____no_output_____"
],
[
"# Lab Exercises\nLet's use this dataset to explore some of the NumPy and Pandas functionality, and practice some basic plotting with Matplotlib.\n\nI've provided instructions and hints, and you will need to fill in the code to generate the output results and plots.",
"_____no_output_____"
],
[
"## Import necessary modules",
"_____no_output_____"
]
],
[
[
"#Use shorter names (np, pd, plt) instead of full (numpy, pandas, matplotlib.pylot) for convenience\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"#Magic function to enable interactive plotting (zoom/pan) in Jupyter notebook\n#If running locally, this would be `%matplotlib notebook`, but since we're using Juptyerlab, we use widget\n#%matplotlib widget\n#Use matplotlib inline to render/embed figures in the notebook for upload to github\n%matplotlib inline",
"_____no_output_____"
],
[
"#%matplotlib widget",
"_____no_output_____"
]
],
[
[
"## Define relative path to the GLAS data csv from week 01",
"_____no_output_____"
]
],
[
[
"glas_fn = '../01_Shell_Github/data/GLAH14_tllz_conus_lulcfilt_demfilt.csv'",
"_____no_output_____"
]
],
[
[
"## Do a quick check of file contents\n* Use iPython functionality to run the `head` shell command on the your filename variable",
"_____no_output_____"
],
[
"# NumPy Exercises",
"_____no_output_____"
],
[
"## Load the file\n* NumPy has some convenience functions for loading text files: `loadtxt` and `genfromtxt`\n* Use `loadtxt` here (simpler), but make sure you properly set the delimiter and handle the first row (see the `skiprows` option)\n * Use iPython `?` to look up reference on arguments for `np.loadtxt`\n* Store the NumPy array as variable called `glas_np`",
"_____no_output_____"
],
[
"## Do a quick check to make sure your array looks good\n* Don't use `print(glas_np)` here, just run cell containing `glas_np`\n* Try both - note that the latter returns the object type, in this case `array`",
"_____no_output_____"
],
[
"## How many rows and columns are in your array?",
"_____no_output_____"
],
[
"## What is the datatype of your array?",
"_____no_output_____"
],
[
"Note that a NumPy array typically has a single datatype, while a Pandas DataFrame can contain multiple data types (e.g., `string`, `float64`)",
"_____no_output_____"
],
[
"## Examine the first 3 rows\n* Use slicing here",
"_____no_output_____"
],
[
"## Examine the column with glas_z values\n* You will need to figure out which column number corresponds to these values (can do this manually from header), then slice the array to return all rows, but only that column",
"_____no_output_____"
],
[
"## Compute the mean and standard deviation of the glas_z values",
"_____no_output_____"
],
[
"## Use print formatting to create a formatted string with these values\n* Should be `'GLAS z: mean +/- std meters'` using your `mean` and `std` values, both formatted with 2 decimal places (cm-precision)\n * For example: 'GLAS z: 1234.56 +/- 42.42 meters'",
"_____no_output_____"
],
[
"## Create a Matplotlib scatter plot of the `glas_z` values\n* Careful about correclty defining your x and y with values for latitude and longitude - easy to mix these up\n* Use point color to represent the elevation\n* You should see points that roughly outline the western United States\n* Label the x axis, y axis, and add a descriptive title",
"_____no_output_____"
],
[
"## Use conditionals and fancy indexing to extract points from 2005\n* Design a \"filter\" to isolate the points from 2005\n * Can use boolean indexing\n * Can then extract values from original array using the boolean index\n* Store these points in a new NumPy array",
"_____no_output_____"
],
[
"### How many points were acquired in 2005?",
"_____no_output_____"
],
[
"# Pandas Exercises\n\nA significant portion of the Python data science ecosystem is based on Pandas and/or Pandas data models.\n\n>pandas is a Python package providing fast, flexible, and expressive data structures designed to make working with \"relational\" or \"labeled\" data both easy and intuitive. It aims to be the fundamental high-level building block for doing practical, real world data analysis in Python. Additionally, it has the broader goal of becoming the most powerful and flexible open source data analysis / manipulation tool available in any language. It is already well on its way towards this goal.\n\nhttps://github.com/pandas-dev/pandas#main-features\n\nIf you are working with tabular data, especially time series data, please use pandas.\n* A better way to deal with tabular data, built on top of NumPy arrays\n* With NumPy, we had to remember which column number (e.g., 3, 4) represented each variable (lat, lon, glas_z, etc)\n* Pandas allows you to store data with different types, and then reference using more meaningful labels\n * NumPy: `glas_np[:,4]`\n * Pandas: `glas_df['glas_z']`\n* A good \"10-minute\" reference with examples: https://pandas.pydata.org/pandas-docs/stable/getting_started/10min.html",
"_____no_output_____"
],
[
"## Load the csv file with Pandas\n* Note that pandas has excellent readers for most common file formats: https://pandas.pydata.org/pandas-docs/stable/reference/io.html",
"_____no_output_____"
],
[
"## That was easy. Let's inspect the `DataFrame`",
"_____no_output_____"
],
[
"## Check data types\n* Can use the DataFrame `info` method",
"_____no_output_____"
],
[
"## Get the column labels\n* Can use the DataFrame `columns` attribute",
"_____no_output_____"
],
[
"If you are new to Python and object-oriented programming, take a moment to consider the difference between the methods and attributes of the DataFrame, and how both are accessed. \n\nhttps://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html\n\nIf this is confusing, ask your neighbor or instructor.",
"_____no_output_____"
],
[
"## Preview records using DataFrame `head` and `tail` methods",
"_____no_output_____"
],
[
"## Compute the mean and standard deviation for all values in each column\n* Don't overthink this, should be simple (no loops!)",
"_____no_output_____"
],
[
"## Print quick stats for entire DataFrame with the `describe` method",
"_____no_output_____"
],
[
"Useful, huh? Note that `median` is the `50%` statistic",
"_____no_output_____"
],
[
"## Use the Pandas plotting functionality to create a 2D scatterplot of `glas_z` values\n* https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.scatter.html\n* Note that labels and colorbar are automatically plotted!\n* Adjust the size of the points using the `s=1` keyword\n* Experiment with different color ramps:\n * https://matplotlib.org/examples/color/colormaps_reference.html (I prefer `inferno`)",
"_____no_output_____"
],
[
"#### Color ramps\nInformation on how to choose a good colormap for your data: https://matplotlib.org/3.1.0/tutorials/colors/colormaps.html \nAnother great resource (Thanks @fperez!): https://matplotlib.org/cmocean/ \n**TL;DR** Don't use `jet`, use a perceptually uniform colormap for linear variables like elevation. Use a diverging color ramp for values where sign is important.",
"_____no_output_____"
],
[
"## Experiment by changing the variable represented with the color ramp\n* Try `decyear` or other columns to quickly visualize spatial distribution of these values.",
"_____no_output_____"
],
[
"## Extra Credit: Create a 3D scatterplot\nSee samples here: https://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html\n\nExplore with the interactive tools (click and drag to change perspective). Some lag here considering number of points to be rendered, and maybe useful for visualizing small 3D datasets in the future. There are other 3D plotting packages that are built for performance and efficiency (e.g., `ipyvolume`: https://github.com/maartenbreddels/ipyvolume)",
"_____no_output_____"
],
[
"## Create a histogram that shows the number of points vs time (`decyear`)\n* Should be simple with built-in method for your `DataFrame` \n* Make sure that you use enough bins to avoid aliasing. This could require some trial and error (try 10, 100, 1000, and see if you can find a good compromise)\n * Can also consider some of the options (e.g., 'auto') here: https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram_bin_edges.html#numpy.histogram_bin_edges\n* You should be able to resolve the distinct campaigns during the mission (each ~1-2 months long). There is an extra credit problem at the end to group by years and play with clustering for the campaigns.",
"_____no_output_____"
],
[
"## Create a histogram of all `glas_z` elevation values\n* What do you note about the distribution?\n* Any negative values?",
"_____no_output_____"
],
[
"## Wait a minute...negative elevations!? Who calibrated this thing? C'mon NASA.",
"_____no_output_____"
],
[
"## A note on vertical datums\n\nNote that some elevations are less than 0 m. How can this be?\n\nThe `glas_z` values are height above (or below) the WGS84 ellipsoid. This is not the same vertical datum as mean sea level (roughly approximated by a geoid model).\n\nA good resource explaining the details: https://vdatum.noaa.gov/docs/datums.html",
"_____no_output_____"
],
[
"## Let's check the spatial distribution of points below 0 (height above WGS84 ellipsoid)\n* How many shots have a negative glas_z value?\n* Create a scatterplot only using points with negative values\n* Adjust the color ramp bounds to bring out more detail for these points\n * hint: see the `vmin` and `vmax` arguments for the `plot` function\n* What do you notice about these points? (may be tough without more context, like coastlines and state boundaries or a tiled basemap - we'll learn how to incorporate these soon)",
"_____no_output_____"
],
[
"## Geoid offset\nHeight difference between the WGS84 ellipsoid (simple shape model of the Earth) and a geoid, that approximates a geopotential (gravitational) surface, approximately mean sea level.\n\n\n\nNote values for the Western U.S. ",
"_____no_output_____"
],
[
"### Interpretation\nA lot of the points with elevation < 0 m in your scatterplot are near coastal sites, roughly near mean sea level. We see that the geoid offset (difference between WGS84 ellipsoid and EGM96 geoid in this case) for CONUS is roughly -20 m. So the ICESat GLAS point elevations near the coast will have values of around -20 m relative to the ellipsoid, even though they are around 0 m relative to the geoid (approximately mean sea level).\n\nAnother cluster of points with negative elevations is over Death Valley, CA, which is actually below sea level: https://en.wikipedia.org/wiki/Death_Valley.\n\nIf this is confusing, we will revisit when we explore raster DEMs later in the quarter. We also get into all of this in the Spring Advanced Surveying course (ask me for details).",
"_____no_output_____"
],
[
"## Compute the elevation difference between ICESat `glas_z` and SRTM `dem_z` values\n\nEarlier, I mentioned that I had sampled the SRTM DEM for each GLAS shot. Let's compute the difference and store in a new column in our DataFrame called `glas_srtm_dh`\n\nRemember the order of this calculation (if the difference values are negative, which dataset is higher elevation?)",
"_____no_output_____"
],
[
"## Do a quick `head` to verify that the values in your new column look reasonable",
"_____no_output_____"
],
[
"## Compute the time difference between ICESat point timestamp and the SRTM timestamp\n* Store in a new column named `glas_srtm_dt`\n* The SRTM data were collected between February 11-22, 2000\n * Can assume a constant decimal year value of 2000.112 for now\n* Check values with `head`",
"_____no_output_____"
],
[
"## Compute *apparent* annualized elevation change rates (meters per year) from these new columns\n* This will be rate of change between the SRTM timestamp (2000) and each GLAS point timestamp (2003-2009)\n* Check values with `head`",
"_____no_output_____"
],
[
"## Create a scatterplot of the difference values\n* Use a `RdBu` (Red to Blue) color ramp\n* Set the color ramp limits using `vmin` and `vmax` keyword arguments to be symmetrical about 0 \n * Generate two plots with different color ramp range to bring out detail\n* Do you see outliers (values far outside the expected distribution)?\n* Do you see any coherent spatial patterns in the difference values?",
"_____no_output_____"
],
[
"## Create a histogram of the difference values\n* Increase the number of bins, and limit the range to bring out detail of the distribution",
"_____no_output_____"
],
[
"## Compute the mean, median and standard deviation of the differences\n* Why might we have a non-zero mean/median difference?",
"_____no_output_____"
],
[
"## Create a scatterplot of elevation difference `glas_srtm_dh` values vs elevation values\n* `glas_srtm_dh` should be on the y-axis\n* `glas_z` values on the x-axis",
"_____no_output_____"
],
[
"## Extra Credit: Remove outliers\nThe initial filter in `glas_proc.py` removed GLAS points with absolute elevation difference >200 m compared to the SRTM elevations. We expect most real elevation change signals to be less than this for the given time period. But clearly some outliers remain.\n\nDesign and apply a filter that removes outliers. One option is to define outliers as values outside some absolute threshold. Can set this threshold as some multiple of the standard deviation (e.g., `3*std`). Can also use quantile or percentile values for this.\n\nCreate new plot(s) to visualize the distribution of outliers and inliers. I've included my figure as a reference, but please don't worry about reproducing! Focus on the filtering and create some quick plots to verify that things worked.",
"_____no_output_____"
],
[
"## Active remote sensing sanity check\n\nEven after removing outliers, there are still some big differences between the SRTM and GLAS elevation values. \n\n* Do you see systematic differences between the glas_z and dem_z values?\n* Any clues from the scatterplot? (e.g., do some tracks (north-south lines of points) display systematic bias?)\n* Brainstorm some ideas about what might be going on here. Think about the nature of each sensor:\n * ICESat was a Near-IR laser (1064 nm wavelength) with a big ground spot size (~70 m in diameter)\n * Timestamps span different seasons between 2003-2009\n * SRTM was a C-band radar (5.3 GHz, 5.6 cm wavelength) with approximately 30 m ground sample distance (pixel size)\n * Timestamp was February 2000\n * Data gaps (e.g., radar shadows, steep slopes) were filled with ASTER GDEM2 composite, which blends DEMs acquired over many years ~2000-2014\n* Consider different surfaces and how the laser/radar footprint might be affected:\n * Flat bedrock surface\n * Dry sand dunes\n * Steep montain topography like the Front Range in Colorado \n * Dense vegetation of the Hoh Rainforest in Olympic National Park",
"_____no_output_____"
],
[
"## Let's check to see if differences are due to our land-use/land-cover classes\n* Determine the unique values in the `lulc` column (hint: see the `value_counts` method)\n* In the introduction, I said that I initially preserved only two classes for these points (12 - snow/ice, 31 - barren land), so this isn't going to help us over forests:\n * https://www.mrlc.gov/data/legends/national-land-cover-database-2011-nlcd2011-legend",
"_____no_output_____"
],
[
"## Use Pandas `groupby` to compute stats for the LULC classes\n* This is one of the most powerful features in Pandas, efficient grouping and analysis based on some values\n* Compute mean, median and std of the difference values (glas_z - dem_z) for each LULC class\n* Do you see a difference between values over glaciers vs bare rock?",
"_____no_output_____"
],
[
"## Extra credit: `groupby` year \n* See if you can use Pandas `groupby` to count the number of shots for each year\n* Multiple ways to accomplish this\n* One approach might be to create a new column with integer year, then groupby that column\n * Can modify the `decyear` values (see `floor`), or parse the Python time ordinals\n* Create a bar plot showing number of shots in each year",
"_____no_output_____"
],
[
"## Extra Credit: Cluster by campaign\n* See if you can create an algorithm to cluster the points by campaign\n * Note, spatial coordinates should not be necessary here (remember your histogram earlier that showed the number of points vs time)\n * Can do something involving differences between sorted point timestamps\n * Can also go back and count the number of campaigns in your earlier histogram of `decyear` values, assuming that you used enough bins to discretize!\n * K-Means clustering is a nice option: https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html\n* Compute the number of shots and length (number of days) for each campaign\n* Compare your answer with table here: https://nsidc.org/data/icesat/laser_op_periods.html (remember that we are using a subset of points over CONUS, so the number of days might not match perfectly)",
"_____no_output_____"
],
[
"## Extra Credit: Annual scatterplots\n* Create a figure with multiple subplots showing scatterplots of points for each year",
"_____no_output_____"
],
[
"## Extra Credit: Campaign scatterplots\n* Create a figure with multiple subplots showing scatterplots of points for each campaign",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
d08068a2bda6ed2f89e0225b3de31a0e64392389 | 724 | ipynb | Jupyter Notebook | 001-Jupyter/001-Tutorials/003-IPython-in-Depth/examples/IPython Kernel/nbpackage/nbs/other.ipynb | willirath/jupyter-jsc-notebooks | e64aa9c6217543c4ffb5535e7a478b2c9457629a | [
"BSD-3-Clause"
] | null | null | null | 001-Jupyter/001-Tutorials/003-IPython-in-Depth/examples/IPython Kernel/nbpackage/nbs/other.ipynb | willirath/jupyter-jsc-notebooks | e64aa9c6217543c4ffb5535e7a478b2c9457629a | [
"BSD-3-Clause"
] | null | null | null | 001-Jupyter/001-Tutorials/003-IPython-in-Depth/examples/IPython Kernel/nbpackage/nbs/other.ipynb | willirath/jupyter-jsc-notebooks | e64aa9c6217543c4ffb5535e7a478b2c9457629a | [
"BSD-3-Clause"
] | 1 | 2022-01-13T18:49:12.000Z | 2022-01-13T18:49:12.000Z | 16.837209 | 38 | 0.506906 | [
[
[
"This notebook just defines `bar`",
"_____no_output_____"
]
],
[
[
"def bar(x):\n return \"bar\" * x",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
]
] |
d0808201edd3d4ae1b11fc235b96616e77f36732 | 2,389 | ipynb | Jupyter Notebook | gameofdeeplearning.ipynb | chetanambi/Game-of-Deep-Learning-Hackathon | 0467da7f75d5e14980041a7c0d340374e1b6d4f2 | [
"Apache-2.0"
] | 8 | 2019-06-10T05:56:01.000Z | 2021-09-04T08:15:02.000Z | gameofdeeplearning.ipynb | chetanambi/Game-of-Deep-Learning-Hackathon | 0467da7f75d5e14980041a7c0d340374e1b6d4f2 | [
"Apache-2.0"
] | null | null | null | gameofdeeplearning.ipynb | chetanambi/Game-of-Deep-Learning-Hackathon | 0467da7f75d5e14980041a7c0d340374e1b6d4f2 | [
"Apache-2.0"
] | 2 | 2019-06-10T06:02:46.000Z | 2021-06-02T10:56:29.000Z | 34.128571 | 425 | 0.629552 | [
[
[
"<div class=\"alert alert-danger\" style=\"margin: 10px\"><strong>IMPORTANT NOTE!</strong> For this hackathon, I have used __Keras__ Deep Learning framework. As of this writting I could not figure our how to generate the reproducible results using Keras. I have tried some techniques like setting the seed but it didn't work out. If anyone who is reading this knows how to do it please let me know in the comments.</div>",
"_____no_output_____"
],
[
"### Refer this kernel for the solution\nhttps://www.kaggle.com/chetanambi/gameofdeeplearning ",
"_____no_output_____"
],
[
"Note that Using custom function I have moved test images into another folder as `flow_from_dataframe` requires test images in separate folder ",
"_____no_output_____"
],
[
" Version 3 - Public Leaderboard Score 0.970072639203272\n Version 4 - Public Leaderboard Score 0.968378700080418\n Version 6 - Public Leaderboard Score 0.965499081609965\n Version 7 - Public Leaderboard Score 0.967556739961624\n Ensemble 1 - Ensemble of submisssions of Version 3, 7 & 6 - Score 0.981366649633107\n Version 8 - Public Leaderboard Score 0.970194519950838\n Ensemble 2 - Ensemble of submisssions of Version 8, 3, 4, 7 & 6 - Score 0.983211779195541\n Version 9 - Public Leaderboard Score 0.974857207751877 \n Ensemble 3 - Ensemble of submisssions of Version 9, 8, 3, 4, 7 & 6 - Score 0.984121152848053",
"_____no_output_____"
],
[
"<div class=\"alert alert-info\" style=\"margin: 10px\"> <strong>Final Submission</strong> - Ensemble of Ensemble 1, 2 & 3 - Score 0.985072083832793 </div>",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
d08084b493a26186842f5e4561196ef2b815abd3 | 8,057 | ipynb | Jupyter Notebook | fast-xml-parse.ipynb | Copper-Head/python-experiments | 20b2ba68ed97cebbcd8273091a6382c2a8c007e3 | [
"MIT"
] | null | null | null | fast-xml-parse.ipynb | Copper-Head/python-experiments | 20b2ba68ed97cebbcd8273091a6382c2a8c007e3 | [
"MIT"
] | null | null | null | fast-xml-parse.ipynb | Copper-Head/python-experiments | 20b2ba68ed97cebbcd8273091a6382c2a8c007e3 | [
"MIT"
] | null | null | null | 33.711297 | 183 | 0.597741 | [
[
[
"! pip install lxml",
"Collecting lxml\n\u001b[33m Cache entry deserialization failed, entry ignored\u001b[0m\n Downloading https://files.pythonhosted.org/packages/eb/59/1db3c9c27049e4f832691c6d642df1f5b64763f73942172c44fee22de397/lxml-4.2.4-cp36-cp36m-manylinux1_x86_64.whl (5.8MB)\n\u001b[K 100% |████████████████████████████████| 5.8MB 211kB/s ta 0:00:011\n\u001b[?25hInstalling collected packages: lxml\nSuccessfully installed lxml-4.2.4\n\u001b[33mYou are using pip version 9.0.1, however version 18.0 is available.\nYou should consider upgrading via the 'pip install --upgrade pip' command.\u001b[0m\n"
],
[
"import lxml.etree as ET",
"_____no_output_____"
],
[
"def fast_parse(fname):\n for event, element in ET.iterparse(fname):\n print(\"before yielding\")\n yield event, element\n print(\"after yielding, not cleared\")\n element.clear()\n print(\"cleared after yielding\")",
"_____no_output_____"
],
[
"def checker(element):\n print(\"checking\", element)\n print(element.tag)\n return True\n\ndef proc(element):\n print('processing', element)\n print(element.tag)\n return None",
"_____no_output_____"
],
[
"from more_itertools import take",
"_____no_output_____"
],
[
"xml_dump = \"/home/quickbeam/Downloads/nlwiktionary-20180820-pages-articles-multistream.xml\"",
"_____no_output_____"
],
[
"list(take(10, (proc(el) for _, el in fast_parse(xml_dump) if checker(el))))",
"before yielding\nchecking <Element {http://www.mediawiki.org/xml/export-0.10/}sitename at 0x7f0206fa7308>\n{http://www.mediawiki.org/xml/export-0.10/}sitename\nprocessing <Element {http://www.mediawiki.org/xml/export-0.10/}sitename at 0x7f0206fa7308>\n{http://www.mediawiki.org/xml/export-0.10/}sitename\nafter yielding, not cleared\ncleared after yielding\nbefore yielding\nchecking <Element {http://www.mediawiki.org/xml/export-0.10/}dbname at 0x7f0206fa7288>\n{http://www.mediawiki.org/xml/export-0.10/}dbname\nprocessing <Element {http://www.mediawiki.org/xml/export-0.10/}dbname at 0x7f0206fa7288>\n{http://www.mediawiki.org/xml/export-0.10/}dbname\nafter yielding, not cleared\ncleared after yielding\nbefore yielding\nchecking <Element {http://www.mediawiki.org/xml/export-0.10/}base at 0x7f0206fa7208>\n{http://www.mediawiki.org/xml/export-0.10/}base\nprocessing <Element {http://www.mediawiki.org/xml/export-0.10/}base at 0x7f0206fa7208>\n{http://www.mediawiki.org/xml/export-0.10/}base\nafter yielding, not cleared\ncleared after yielding\nbefore yielding\nchecking <Element {http://www.mediawiki.org/xml/export-0.10/}generator at 0x7f020701ba08>\n{http://www.mediawiki.org/xml/export-0.10/}generator\nprocessing <Element {http://www.mediawiki.org/xml/export-0.10/}generator at 0x7f020701ba08>\n{http://www.mediawiki.org/xml/export-0.10/}generator\nafter yielding, not cleared\ncleared after yielding\nbefore yielding\nchecking <Element {http://www.mediawiki.org/xml/export-0.10/}case at 0x7f020701b908>\n{http://www.mediawiki.org/xml/export-0.10/}case\nprocessing <Element {http://www.mediawiki.org/xml/export-0.10/}case at 0x7f020701b908>\n{http://www.mediawiki.org/xml/export-0.10/}case\nafter yielding, not cleared\ncleared after yielding\nbefore yielding\nchecking <Element {http://www.mediawiki.org/xml/export-0.10/}namespace at 0x7f020701bdc8>\n{http://www.mediawiki.org/xml/export-0.10/}namespace\nprocessing <Element {http://www.mediawiki.org/xml/export-0.10/}namespace at 0x7f020701bdc8>\n{http://www.mediawiki.org/xml/export-0.10/}namespace\nafter yielding, not cleared\ncleared after yielding\nbefore yielding\nchecking <Element {http://www.mediawiki.org/xml/export-0.10/}namespace at 0x7f020701be48>\n{http://www.mediawiki.org/xml/export-0.10/}namespace\nprocessing <Element {http://www.mediawiki.org/xml/export-0.10/}namespace at 0x7f020701be48>\n{http://www.mediawiki.org/xml/export-0.10/}namespace\nafter yielding, not cleared\ncleared after yielding\nbefore yielding\nchecking <Element {http://www.mediawiki.org/xml/export-0.10/}namespace at 0x7f020701b988>\n{http://www.mediawiki.org/xml/export-0.10/}namespace\nprocessing <Element {http://www.mediawiki.org/xml/export-0.10/}namespace at 0x7f020701b988>\n{http://www.mediawiki.org/xml/export-0.10/}namespace\nafter yielding, not cleared\ncleared after yielding\nbefore yielding\nchecking <Element {http://www.mediawiki.org/xml/export-0.10/}namespace at 0x7f020701b708>\n{http://www.mediawiki.org/xml/export-0.10/}namespace\nprocessing <Element {http://www.mediawiki.org/xml/export-0.10/}namespace at 0x7f020701b708>\n{http://www.mediawiki.org/xml/export-0.10/}namespace\nafter yielding, not cleared\ncleared after yielding\nbefore yielding\nchecking <Element {http://www.mediawiki.org/xml/export-0.10/}namespace at 0x7f020701bd08>\n{http://www.mediawiki.org/xml/export-0.10/}namespace\nprocessing <Element {http://www.mediawiki.org/xml/export-0.10/}namespace at 0x7f020701bd08>\n{http://www.mediawiki.org/xml/export-0.10/}namespace\n"
],
[
"gen = fast_parse(xml_dump)",
"_____no_output_____"
],
[
"proc(next(gen))",
"after yielding, not cleared\ncleared after yielding\nbefore yielding\nprocessing ('end', <Element {http://www.mediawiki.org/xml/export-0.10/}base at 0x7f0206ff5748>)\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d0809679c63009586cdde41d0f86f18344b7e577 | 98,834 | ipynb | Jupyter Notebook | Source Code.ipynb | ericblanco/fictional-happiness | f9d38ab6c74d7f8c3ecdaa7b96f4ecdfd8c56246 | [
"CC0-1.0"
] | null | null | null | Source Code.ipynb | ericblanco/fictional-happiness | f9d38ab6c74d7f8c3ecdaa7b96f4ecdfd8c56246 | [
"CC0-1.0"
] | null | null | null | Source Code.ipynb | ericblanco/fictional-happiness | f9d38ab6c74d7f8c3ecdaa7b96f4ecdfd8c56246 | [
"CC0-1.0"
] | null | null | null | 39.080269 | 132 | 0.405033 | [
[
[
"import numpy as np\nimport pandas as pd",
"_____no_output_____"
],
[
"training_data = pd.read_csv(\"hackerrank-predict-email-opens-dataset/training_dataset.csv\")\ntesting_data = pd.read_csv(\"hackerrank-predict-email-opens-dataset/test_dataset.csv\")",
"_____no_output_____"
],
[
"training_data.head()",
"_____no_output_____"
],
[
"training_data.shape",
"_____no_output_____"
],
[
"testing_data.head()",
"_____no_output_____"
],
[
"testing_data.shape",
"_____no_output_____"
],
[
"training_data.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 486048 entries, 0 to 486047\nData columns (total 54 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 user_id 486048 non-null object \n 1 mail_id 486048 non-null object \n 2 mail_category 485623 non-null object \n 3 mail_type 485623 non-null object \n 4 sent_time 486048 non-null int64 \n 5 open_time 161347 non-null float64\n 6 click_time 27084 non-null float64\n 7 unsubscribe_time 1958 non-null float64\n 8 last_online 485471 non-null float64\n 9 hacker_created_at 486048 non-null int64 \n 10 hacker_timezone 479109 non-null float64\n 11 clicked 486048 non-null bool \n 12 contest_login_count 486048 non-null int64 \n 13 contest_login_count_1_days 486048 non-null int64 \n 14 contest_login_count_30_days 486048 non-null int64 \n 15 contest_login_count_365_days 486048 non-null int64 \n 16 contest_login_count_7_days 486048 non-null int64 \n 17 contest_participation_count 486048 non-null int64 \n 18 contest_participation_count_1_days 486048 non-null int64 \n 19 contest_participation_count_30_days 486048 non-null int64 \n 20 contest_participation_count_365_days 486048 non-null int64 \n 21 contest_participation_count_7_days 486048 non-null int64 \n 22 forum_comments_count 486048 non-null int64 \n 23 forum_count 486048 non-null int64 \n 24 forum_expert_count 486048 non-null int64 \n 25 forum_questions_count 486048 non-null int64 \n 26 hacker_confirmation 486048 non-null bool \n 27 ipn_count 486048 non-null int64 \n 28 ipn_count_1_days 486048 non-null int64 \n 29 ipn_count_30_days 486048 non-null int64 \n 30 ipn_count_365_days 486048 non-null int64 \n 31 ipn_count_7_days 486048 non-null int64 \n 32 ipn_read 486048 non-null int64 \n 33 ipn_read_1_days 486048 non-null int64 \n 34 ipn_read_30_days 486048 non-null int64 \n 35 ipn_read_365_days 486048 non-null int64 \n 36 ipn_read_7_days 486048 non-null int64 \n 37 opened 486048 non-null bool \n 38 submissions_count 486048 non-null int64 \n 39 submissions_count_1_days 486048 non-null int64 \n 40 submissions_count_30_days 486048 non-null int64 \n 41 submissions_count_365_days 486048 non-null int64 \n 42 submissions_count_7_days 486048 non-null int64 \n 43 submissions_count_contest 486048 non-null int64 \n 44 submissions_count_contest_1_days 486048 non-null int64 \n 45 submissions_count_contest_30_days 486048 non-null int64 \n 46 submissions_count_contest_365_days 486048 non-null int64 \n 47 submissions_count_contest_7_days 486048 non-null int64 \n 48 submissions_count_master 486048 non-null int64 \n 49 submissions_count_master_1_days 486048 non-null int64 \n 50 submissions_count_master_30_days 486048 non-null int64 \n 51 submissions_count_master_365_days 486048 non-null int64 \n 52 submissions_count_master_7_days 486048 non-null int64 \n 53 unsubscribed 486048 non-null bool \ndtypes: bool(4), float64(5), int64(41), object(4)\nmemory usage: 187.3+ MB\n"
],
[
"testing_data.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 207424 entries, 0 to 207423\nData columns (total 48 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 user_id 207424 non-null object \n 1 mail_id 207424 non-null object \n 2 mail_category 207417 non-null object \n 3 mail_type 207417 non-null object \n 4 sent_time 207424 non-null int64 \n 5 last_online 207291 non-null float64\n 6 hacker_created_at 207424 non-null int64 \n 7 hacker_timezone 199784 non-null float64\n 8 contest_login_count 207424 non-null int64 \n 9 contest_login_count_1_days 207424 non-null int64 \n 10 contest_login_count_30_days 207424 non-null int64 \n 11 contest_login_count_365_days 207424 non-null int64 \n 12 contest_login_count_7_days 207424 non-null int64 \n 13 contest_participation_count 207424 non-null int64 \n 14 contest_participation_count_1_days 207424 non-null int64 \n 15 contest_participation_count_30_days 207424 non-null int64 \n 16 contest_participation_count_365_days 207424 non-null int64 \n 17 contest_participation_count_7_days 207424 non-null int64 \n 18 forum_comments_count 207424 non-null int64 \n 19 forum_count 207424 non-null int64 \n 20 forum_expert_count 207424 non-null int64 \n 21 forum_questions_count 207424 non-null int64 \n 22 hacker_confirmation 207424 non-null bool \n 23 ipn_count 207424 non-null int64 \n 24 ipn_count_1_days 207424 non-null int64 \n 25 ipn_count_30_days 207424 non-null int64 \n 26 ipn_count_365_days 207424 non-null int64 \n 27 ipn_count_7_days 207424 non-null int64 \n 28 ipn_read 207424 non-null int64 \n 29 ipn_read_1_days 207424 non-null int64 \n 30 ipn_read_30_days 207424 non-null int64 \n 31 ipn_read_365_days 207424 non-null int64 \n 32 ipn_read_7_days 207424 non-null int64 \n 33 submissions_count 207424 non-null int64 \n 34 submissions_count_1_days 207424 non-null int64 \n 35 submissions_count_30_days 207424 non-null int64 \n 36 submissions_count_365_days 207424 non-null int64 \n 37 submissions_count_7_days 207424 non-null int64 \n 38 submissions_count_contest 207424 non-null int64 \n 39 submissions_count_contest_1_days 207424 non-null int64 \n 40 submissions_count_contest_30_days 207424 non-null int64 \n 41 submissions_count_contest_365_days 207424 non-null int64 \n 42 submissions_count_contest_7_days 207424 non-null int64 \n 43 submissions_count_master 207424 non-null int64 \n 44 submissions_count_master_1_days 207424 non-null int64 \n 45 submissions_count_master_30_days 207424 non-null int64 \n 46 submissions_count_master_365_days 207424 non-null int64 \n 47 submissions_count_master_7_days 207424 non-null int64 \ndtypes: bool(1), float64(2), int64(41), object(4)\nmemory usage: 74.6+ MB\n"
]
],
[
[
"## Data Preprocessing",
"_____no_output_____"
]
],
[
[
"# drop the following columns as they are only available in training data\n# click_time, clicked, open_time, unsubscribe_time, unsubscribed\n\ntraining_data.drop(['click_time','clicked', 'open_time', 'unsubscribe_time', 'unsubscribed'], axis=1, inplace=True)",
"_____no_output_____"
]
],
[
[
"### Missing Values",
"_____no_output_____"
]
],
[
[
"training_data.isnull().sum()",
"_____no_output_____"
],
[
"training_data['mail_category'].fillna(training_data['mail_category'].value_counts().index[0], inplace=True)\ntraining_data['mail_type'].fillna(training_data['mail_type'].value_counts().index[0],inplace=True)\ntraining_data['hacker_timezone'].fillna(training_data['hacker_timezone'].value_counts().index[0], inplace=True)\ntraining_data['last_online'].fillna(training_data['last_online'].mean(), inplace=True)\n",
"_____no_output_____"
],
[
"testing_data.isnull().sum()",
"_____no_output_____"
],
[
"testing_data['mail_category'].fillna(testing_data['mail_category'].value_counts().index[0], inplace=True)\ntesting_data['mail_type'].fillna(testing_data['mail_type'].value_counts().index[0],inplace=True)\ntesting_data['hacker_timezone'].fillna(testing_data['hacker_timezone'].value_counts().index[0], inplace=True)\ntesting_data['last_online'].fillna(testing_data['last_online'].mean(), inplace=True)",
"_____no_output_____"
]
],
[
[
"### Outliers",
"_____no_output_____"
]
],
[
[
"training_data.describe().T",
"_____no_output_____"
],
[
"min_threshold, max_threshold = training_data.sent_time.quantile([0.001, 0.999])\ntraining_data = training_data[(training_data['sent_time'] > min_threshold) & (training_data['sent_time'] < max_threshold)]",
"_____no_output_____"
],
[
"min_threshold, max_threshold = training_data.last_online.quantile([0.001, 0.999])\ntraining_data = training_data[(training_data['last_online'] > min_threshold) & (training_data['last_online'] < max_threshold)]",
"_____no_output_____"
],
[
"training_data.shape",
"_____no_output_____"
]
],
[
[
"### Encoding Categorical Attributes",
"_____no_output_____"
]
],
[
[
"from sklearn.preprocessing import LabelEncoder\nencode = LabelEncoder()",
"_____no_output_____"
],
[
"# Extract Categorical Attributes\n#cat_training_data = training_data.select_dtypes(include=['object']).copy()\n\n# encode the categorical attributes of training_data\ntraining_data = training_data.apply(encode.fit_transform)\n\n# encode the categorical attribute of testing_data\ntesting_data = testing_data.apply(encode.fit_transform)\n",
"_____no_output_____"
],
[
"training_data.head()",
"_____no_output_____"
],
[
"testing_data.head()",
"_____no_output_____"
]
],
[
[
"### Seperate the Label Column from training_data",
"_____no_output_____"
]
],
[
[
"label = training_data['opened']\n\ntraining_data.drop('opened', inplace=True, axis=1)",
"_____no_output_____"
]
],
[
[
"### Scaling Numerical Features",
"_____no_output_____"
]
],
[
[
"from sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()",
"_____no_output_____"
],
[
"# extract numerical attributes and scale it to have zero mean and unit variance\ntrain_cols = training_data.select_dtypes(include=['float64', 'int64']).columns\ntraining_data = scaler.fit_transform(training_data.select_dtypes(include=['float64','int64']))\n\n# extract numerical attributes and scale it to have zero mean and unit variance\ntest_cols = testing_data.select_dtypes(include=['float64', 'int64']).columns\ntesting_data = scaler.fit_transform(testing_data.select_dtypes(include=['float64','int64']))",
"_____no_output_____"
],
[
"training_data = pd.DataFrame(training_data, columns=train_cols)\ntesting_data = pd.DataFrame(testing_data, columns=test_cols)",
"_____no_output_____"
],
[
"training_data.shape",
"_____no_output_____"
],
[
"testing_data.shape",
"_____no_output_____"
]
],
[
[
"### Split the training_data into training and validaiton data",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import train_test_split\n\nx_train, x_val, y_train, y_val = train_test_split(training_data, label, test_size = 0.2, random_state=2)",
"_____no_output_____"
]
],
[
[
"## Models Training",
"_____no_output_____"
],
[
"### Decision Tree",
"_____no_output_____"
]
],
[
[
"from sklearn import tree\nfrom sklearn import metrics\n",
"_____no_output_____"
],
[
"DT_Classifier = tree.DecisionTreeClassifier(criterion='entropy', random_state=0)\nDT_Classifier.fit(x_train, y_train)",
"_____no_output_____"
]
],
[
[
"#### Accuracy and Confusion Matrix",
"_____no_output_____"
]
],
[
[
"accuracy = metrics.accuracy_score(y_val, DT_Classifier.predict(x_val))\nconfustion_matrix = metrics.confusion_matrix(y_val, DT_Classifier.predict(x_val))",
"_____no_output_____"
],
[
"accuracy",
"_____no_output_____"
],
[
"confustion_matrix",
"_____no_output_____"
]
],
[
[
"### K-Nearest Neighbour",
"_____no_output_____"
]
],
[
[
"from sklearn.neighbors import KNeighborsClassifier",
"_____no_output_____"
],
[
"KNN_Classifier = KNeighborsClassifier(n_jobs=-1)\nKNN_Classifier.fit(x_train, y_train)",
"_____no_output_____"
],
[
"accuracy = metrics.accuracy_score(y_val, KNN_Classifier.predict(x_val))\nconfusion_matrix = metrics.confusion_matrix(y_val, KNN_Classifier.predict(x_val))",
"_____no_output_____"
],
[
"accuracy",
"_____no_output_____"
],
[
"confusion_matrix",
"_____no_output_____"
]
],
[
[
"## Prediction on test data",
"_____no_output_____"
]
],
[
[
"predicted = DT_Classifier.predict(testing_data)",
"_____no_output_____"
],
[
"predicted.shape",
"_____no_output_____"
],
[
"prediction_df = pd.DataFrame(predicted, columns=['Prediction'])",
"_____no_output_____"
],
[
"prediction_df.to_csv('prediction.csv')",
"_____no_output_____"
],
[
"import pickle\n\npkl_filename = \"Decision_Tree_model.pkl\"\nwith open(pkl_filename, 'wb') as file:\n pickle.dump(DT_Classifier, file)",
"_____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"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
d0809df1f908ac1d7cba14e75b504f78cc4be534 | 33,994 | ipynb | Jupyter Notebook | 04-Advanced-Computer-Vision/02-Implement-Sliding-Windows-and-Fit-a-Polynomial.ipynb | vyasparthm/AutonomousDriving | 4a767442a7e661dd71f4e160f3c071dc02614ab6 | [
"MIT"
] | null | null | null | 04-Advanced-Computer-Vision/02-Implement-Sliding-Windows-and-Fit-a-Polynomial.ipynb | vyasparthm/AutonomousDriving | 4a767442a7e661dd71f4e160f3c071dc02614ab6 | [
"MIT"
] | null | null | null | 04-Advanced-Computer-Vision/02-Implement-Sliding-Windows-and-Fit-a-Polynomial.ipynb | vyasparthm/AutonomousDriving | 4a767442a7e661dd71f4e160f3c071dc02614ab6 | [
"MIT"
] | null | null | null | 95.221289 | 19,956 | 0.811643 | [
[
[
"## Implement Sliding Windows and Fit a Polynomial\n\nThis notebook displays how to create a sliding windows on a image using Histogram we did in an earlier notebook.\nwe can use the two highest peaks from our histogram as a starting point for determining where the lane lines are, and then use sliding windows moving upward in the image (further along the road) to determine where the lane lines go. The output should look something like this:\n\n<img src='./img/sliding_window_example.png'/>\n\n<br>\n\n#### Steps: \n1. Split the histogram for the two lines.\n2. Set up windows and window hyper parameters.\n3. Iterate through number of sliding windows to track curvature.\n4. Fit the polynomial.\n5. Plot the image.",
"_____no_output_____"
],
[
"#### 1. Split the histogram for the two lines\n\nThe first step we'll take is to split the histogram into two sides, one for each lane line.\n\nNOTE: You will need an image from the previous notebook: warped-example.jpg\n\nBelow is the pseucode:\n\n**Do not Run the Below Cell it is for explanation only**\n",
"_____no_output_____"
]
],
[
[
"\n\n# Assuming you have created a warped binary image called \"binary_warped\"\n# Take a histogram of the bottom half of the image\n\nhistogram = np.sum(binary_warped[binary_warped.shape[0]//2:,:], axis=0)\n\n# Create an output image to draw on and visualize the result\nout_img = np.dstack((binary_warped, binary_warped, binary_warped))*255\n\n# Find the peak of the left and right halves of the histogram\n# These will be the starting point for the left and right lines\nmidpoint = np.int(histogram.shape[0]//2)\nleftx_base = np.argmax(histogram[:midpoint])\nrightx_base = np.argmax(histogram[midpoint:]) + midpoint",
"_____no_output_____"
]
],
[
[
"#### 2. Set up windows and window hyper parameters.\n\nOur next step is to set a few hyper parameters related to our sliding windows, and set them up to iterate across the binary activations in the image. I have some base hyper parameters below, but don't forget to try out different values in your own implementation to see what works best!\n\nBelow is the pseudocode:<br>\n**Do not run the below Cell, it is for explanation only**",
"_____no_output_____"
]
],
[
[
"# HYPERPARAMETERS\n# Choose the number of sliding windows\nnwindows = 9\n# Set the width of the windows +/- margin\nmargin = 100\n# Set minimum number of pixels found to recenter window\nminpix = 50\n\n# Set height of windows - based on nwindows above and image shape\nwindow_height = np.int(binary_warped.shape[0]//nwindows)\n# Identify the x and y positions of all nonzero (i.e. activated) pixels in the image\nnonzero = binary_warped.nonzero()\nnonzeroy = np.array(nonzero[0])\nnonzerox = np.array(nonzero[1])\n# Current positions to be updated later for each window in nwindows\nleftx_current = leftx_base\nrightx_current = rightx_base\n\n# Create empty lists to receive left and right lane pixel indices\nleft_lane_inds = []\nright_lane_inds = []",
"_____no_output_____"
]
],
[
[
"#### 3. Iterate through number of sliding windows to track curvature\n\nnow that we've set up what the windows look like and have a starting point, we'll want to loop for `nwindows`, with the given window sliding left or right if it finds the mean position of activated pixels within the window to have shifted.\n\nLet's approach this like below:\n\n 1. Loop through each window in `nwindows`\n 2. Find the boundaries of our current window. This is based on a combination of the current window's starting point `(leftx_current` and `rightx_current`), as well as the margin you set in the hyperparameters.\n 3. Use cv2.rectangle to draw these window boundaries onto our visualization image `out_img`.\n 4. Now that we know the boundaries of our window, find out which activated pixels from `nonzeroy` and `nonzerox` above actually fall into the window.\n 5. Append these to our lists `left_lane_inds` and `right_lane_inds`.\n 6. If the number of pixels you found in Step 4 are greater than your hyperparameter `minpix`, re-center our window (i.e. `leftx_current` or `rightx_current`) based on the mean position of these pixels.\n",
"_____no_output_____"
],
[
"#### 4. Fit the polynomial\n\nNow that we have found all our pixels belonging to each line through the sliding window method, it's time to fit a polynomial to the line. First, we have a couple small steps to ready our pixels.\n<br>\nBelow is the pseudocode:<br>\n**Do not run the below Cell, it is for explanation only**",
"_____no_output_____"
]
],
[
[
"# Concatenate the arrays of indices (previously was a list of lists of pixels)\nleft_lane_inds = np.concatenate(left_lane_inds)\nright_lane_inds = np.concatenate(right_lane_inds)\n\n# Extract left and right line pixel positions\nleftx = nonzerox[left_lane_inds]\nlefty = nonzeroy[left_lane_inds] \nrightx = nonzerox[right_lane_inds]\nrighty = nonzeroy[right_lane_inds]\n\n Assuming we have `left_fit` and `right_fit` from `np.polyfit` before\n# Generate x and y values for plotting\nploty = np.linspace(0, binary_warped.shape[0]-1, binary_warped.shape[0])\nleft_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2]\nright_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2]",
"_____no_output_____"
]
],
[
[
"#### 5. Visualize\n\nWe will use subplots to visualize the output.\n\nLets get to coding then.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nimport cv2\n\n# Load our image\nbinary_warped = mpimg.imread('./img/warped-example.jpg')\n\ndef find_lane_pixels(binary_warped):\n # Take a histogram of the bottom half of the image\n histogram = np.sum(binary_warped[binary_warped.shape[0]//2:,:], axis=0)\n # Create an output image to draw on and visualize the result\n out_img = np.dstack((binary_warped, binary_warped, binary_warped))\n # Find the peak of the left and right halves of the histogram\n # These will be the starting point for the left and right lines\n midpoint = np.int(histogram.shape[0]//2)\n leftx_base = np.argmax(histogram[:midpoint])\n rightx_base = np.argmax(histogram[midpoint:]) + midpoint\n\n # HYPERPARAMETERS\n # Choose the number of sliding windows\n nwindows = 9\n # Set the width of the windows +/- margin\n margin = 100\n # Set minimum number of pixels found to recenter window\n minpix = 50\n\n # Set height of windows - based on nwindows above and image shape\n window_height = np.int(binary_warped.shape[0]//nwindows)\n # Identify the x and y positions of all nonzero pixels in the image\n nonzero = binary_warped.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n # Current positions to be updated later for each window in nwindows\n leftx_current = leftx_base\n rightx_current = rightx_base\n\n # Create empty lists to receive left and right lane pixel indices\n left_lane_inds = []\n right_lane_inds = []\n\n # Step through the windows one by one\n for window in range(nwindows):\n # Identify window boundaries in x and y (and right and left)\n win_y_low = binary_warped.shape[0] - (window+1)*window_height\n win_y_high = binary_warped.shape[0] - window*window_height\n win_xleft_low = leftx_current - margin\n win_xleft_high = leftx_current + margin\n win_xright_low = rightx_current - margin\n win_xright_high = rightx_current + margin\n \n # Draw the windows on the visualization image\n cv2.rectangle(out_img,(win_xleft_low,win_y_low),\n (win_xleft_high,win_y_high),(0,255,0), 2) \n cv2.rectangle(out_img,(win_xright_low,win_y_low),\n (win_xright_high,win_y_high),(0,255,0), 2) \n \n # Identify the nonzero pixels in x and y within the window #\n good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & \n (nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0]\n good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & \n (nonzerox >= win_xright_low) & (nonzerox < win_xright_high)).nonzero()[0]\n \n # Append these indices to the lists\n left_lane_inds.append(good_left_inds)\n right_lane_inds.append(good_right_inds)\n \n # If you found > minpix pixels, recenter next window on their mean position\n if len(good_left_inds) > minpix:\n leftx_current = np.int(np.mean(nonzerox[good_left_inds]))\n if len(good_right_inds) > minpix: \n rightx_current = np.int(np.mean(nonzerox[good_right_inds]))\n\n # Concatenate the arrays of indices (previously was a list of lists of pixels)\n try:\n left_lane_inds = np.concatenate(left_lane_inds)\n right_lane_inds = np.concatenate(right_lane_inds)\n except ValueError:\n # Avoids an error if the above is not implemented fully\n pass\n\n # Extract left and right line pixel positions\n leftx = nonzerox[left_lane_inds]\n lefty = nonzeroy[left_lane_inds] \n rightx = nonzerox[right_lane_inds]\n righty = nonzeroy[right_lane_inds]\n\n return leftx, lefty, rightx, righty, out_img\n\n\ndef fit_polynomial(binary_warped):\n # Find our lane pixels first\n leftx, lefty, rightx, righty, out_img = find_lane_pixels(binary_warped)\n\n # Fit a second order polynomial to each using `np.polyfit`\n left_fit = np.polyfit(lefty, leftx, 2)\n right_fit = np.polyfit(righty, rightx, 2)\n\n # Generate x and y values for plotting\n ploty = np.linspace(0, binary_warped.shape[0]-1, binary_warped.shape[0] )\n try:\n left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2]\n right_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2]\n except TypeError:\n # Avoids an error if `left` and `right_fit` are still none or incorrect\n print('The function failed to fit a line!')\n left_fitx = 1*ploty**2 + 1*ploty\n right_fitx = 1*ploty**2 + 1*ploty\n\n ## Visualization ##\n # Colors in the left and right lane regions\n out_img[lefty, leftx] = [255, 0, 0]\n out_img[righty, rightx] = [0, 0, 255]\n\n # Plots the left and right polynomials on the lane lines\n plt.plot(left_fitx, ploty, color='white')\n plt.plot(right_fitx, ploty, color='white')\n print(left_fit)\n print(right_fit)\n\n return out_img\n\n\nout_img = fit_polynomial(binary_warped)\n\nplt.imshow(out_img)\n",
"[ 2.23090058e-04 -3.90812851e-01 4.78139852e+02]\n[ 4.19709859e-04 -4.79568379e-01 1.11522544e+03]\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
d0809e93ef63cf4ea1eef858c6975925f1f43e54 | 29,403 | ipynb | Jupyter Notebook | notebooks/euler_expanding_window.ipynb | CHEN-Zhaohui/geoist | 06a00db3e0ed3d92abf3e45b7b3bfbef6a858a5b | [
"MIT"
] | 53 | 2018-11-17T03:29:55.000Z | 2022-03-18T02:36:25.000Z | notebooks/euler_expanding_window.ipynb | CHEN-Zhaohui/geoist | 06a00db3e0ed3d92abf3e45b7b3bfbef6a858a5b | [
"MIT"
] | 3 | 2018-11-28T11:37:51.000Z | 2019-01-30T01:52:45.000Z | notebooks/euler_expanding_window.ipynb | CHEN-Zhaohui/geoist | 06a00db3e0ed3d92abf3e45b7b3bfbef6a858a5b | [
"MIT"
] | 35 | 2018-11-17T03:29:57.000Z | 2022-03-23T17:57:06.000Z | 207.06338 | 24,668 | 0.895691 | [
[
[
"\"\"\"\n基于扩展窗的欧拉反卷积算法\n\n欧拉反卷积的常用方法是基于滑动窗口:但由于每个窗口是在整个区域仅运行一次解卷积会产生很多虚假的解决方案。\n并且基于滑动窗口的反卷积方法不能出给指定的源的个数。所以发展了基于扩展窗的欧拉反卷积算法。\n其基本思想是:从一个选点的中心点扩展许多窗口进行反卷积。然后只选择其中一个解决方案(最小误差方案)作为最终估计。\n这种方法不仅可以提供单一解决方案,还可以通过可以针对每个异常选择不同的扩展中心实现对多个异常的解释。\n\n扩展窗口方案实现于:geoist.euler_expanding_window.ipynb。\n\"\"\"\nfrom geoist.pfm import sphere, pftrans, euler, giutils\nfrom geoist import gridder\nfrom geoist.inversion import geometry\nfrom geoist.vis import giplt\nimport matplotlib.pyplot as plt\nimport numpy as np\n##合成磁数据测试欧拉反卷积\n# 磁倾角,磁偏角\ninc, dec = -45, 0\n# 制作仅包含感应磁化的两个球体模型\nmodel = [\n geometry.Sphere(x=-1000, y=-1000, z=1500, radius=1000,\n props={'magnetization': giutils.ang2vec(2, inc, dec)}),\n geometry.Sphere(x=1000, y=1500, z=1000, radius=1000,\n props={'magnetization': giutils.ang2vec(1, inc, dec)})]\n# 从模型中生成磁数据\nshape = (100, 100)\narea = [-5000, 5000, -5000, 5000]\nx, y, z = gridder.regular(area, shape, z=-150)\ndata = sphere.tf(x, y, z, model, inc, dec)\n\n# 一阶导数\nxderiv = pftrans.derivx(x, y, data, shape)\nyderiv = pftrans.derivy(x, y, data, shape)\nzderiv = pftrans.derivz(x, y, data, shape)\n\n#通过扩展窗方法实现欧拉反卷积 \n#给出2个解决方案,每一个扩展窗都靠近异常\n#stutural_index=3表明异常源为球体\n'''\n ===================================== ======== =========\n 源类型 SI (磁) SI (重力)\n ===================================== ======== =========\n Point, sphere 3 2\n Line, cylinder, thin bed fault 2 1\n Thin sheet edge, thin sill, thin dyke 1 0\n ===================================== ======== =========\n'''\n\n#制作求解器并使用fit()函数来获取右下角异常的估计值\nprint(\"Euler solutions:\")\nsol1 = euler.EulerDeconvEW(x, y, z, data, xderiv, yderiv, zderiv,\n structural_index=3, center=(-2000, -2000),\n sizes=np.linspace(300, 7000, 20))\nsol1.fit()\nprint(\"Lower right anomaly location:\", sol1.estimate_)\n\n#制作求解器并使用fit()函数来获取左上角异常的估计值\nsol2 = euler.EulerDeconvEW(x, y, z, data, xderiv, yderiv, zderiv,\n structural_index=3, center=(2000, 2000),\n sizes=np.linspace(300, 7000, 20))\nsol2.fit()\nprint(\"Upper left anomaly location:\", sol2.estimate_)\n\nprint(\"Centers of the model spheres:\")\nprint(model[0].center)\nprint(model[1].center)\n\n# 在磁数据上绘制异常估计值结果\n# 异常源的中心的真正深度为1500 m 和1000 m。\nplt.figure(figsize=(6, 5))\nplt.title('Euler deconvolution with expanding windows')\nplt.contourf(y.reshape(shape), x.reshape(shape), data.reshape(shape), 30,\n cmap=\"RdBu_r\")\nplt.scatter([sol1.estimate_[1], sol2.estimate_[1]],\n [sol1.estimate_[0], sol2.estimate_[0]],\n c=[sol1.estimate_[2], sol2.estimate_[2]],\n s=50, cmap='cubehelix')\nplt.colorbar(pad=0).set_label('Depth (m)')\nplt.xlim(area[2:])\nplt.ylim(area[:2])\nplt.tight_layout()\nplt.show()",
"Euler solutions:\nLower right anomaly location: [-1072.04297339 -830.29615323 1428.85976886]\nUpper left anomaly location: [1018.12838822 1576.71821498 1039.07466633]\nCenters of the model spheres:\n[-1000 -1000 1500]\n[1000 1500 1000]\n"
]
]
] | [
"code"
] | [
[
"code"
]
] |
d080c30095244a49ddae7d6a92ae2375d7f6018e | 9,289 | ipynb | Jupyter Notebook | analytics/TweetAnalytics.ipynb | martindavid/amost-twitter-analytics | 91a9f42d5dabc67371da38014dd00a6acda05ac1 | [
"MIT"
] | 1 | 2020-02-24T05:28:47.000Z | 2020-02-24T05:28:47.000Z | analytics/TweetAnalytics.ipynb | martindavid/amost-twitter-analytics | 91a9f42d5dabc67371da38014dd00a6acda05ac1 | [
"MIT"
] | null | null | null | analytics/TweetAnalytics.ipynb | martindavid/amost-twitter-analytics | 91a9f42d5dabc67371da38014dd00a6acda05ac1 | [
"MIT"
] | 2 | 2017-05-13T08:09:48.000Z | 2019-03-19T04:21:29.000Z | 26.769452 | 460 | 0.469265 | [
[
[
"import os\nimport couchdb\nfrom lib.genderComputer.genderComputer import GenderComputer",
"_____no_output_____"
],
[
"server = couchdb.Server(url='http://127.0.0.1:15984/')\ndb = server['tweets']\ngc = GenderComputer(os.path.abspath('./data/nameLists'))",
"_____no_output_____"
],
[
"date_list = []\nfor row in db.view('_design/analytics/_view/conversation-date-breakdown', reduce=True, group=True):\n date_list.append(row.key)\n \nprint(date_list)",
"[u'2017/3/10', u'2017/3/11', u'2017/3/12', u'2017/3/13', u'2017/3/14', u'2017/3/15', u'2017/3/16', u'2017/3/17', u'2017/3/18', u'2017/3/19', u'2017/3/20', u'2017/3/21', u'2017/3/22', u'2017/3/23', u'2017/3/24', u'2017/3/25', u'2017/3/26', u'2017/3/27', u'2017/3/28', u'2017/3/29', u'2017/3/30', u'2017/3/6', u'2017/3/7', u'2017/3/8', u'2017/3/9', u'2017/4/1', u'2017/4/2', u'2017/4/3', u'2017/4/4', u'2017/4/5', u'2017/4/6', u'2017/4/7', u'2017/4/8']\n"
],
[
"from collections import Counter\nview_data = []\nfor row in db.view('_design/analytics/_view/tweets-victoria',startkey=\"2017/3/6\",endkey=\"2017/3/9\"):\n view_data.append(row.value)",
"_____no_output_____"
],
[
"len(view_data)",
"_____no_output_____"
],
[
"try:\n hashtags = server.create[\"twitter-hashtags\"]\nexcept:\n hashtags = server[\"twitter-hashtags\"]\n\nhashtag_count = Counter()\n\nfor row in view_data:\n hashtag_count.update(row[\"hashtags\"])\n\nfor tag in hashtag_count.most_common():\n doc = hashtags.get(tag[0]) # tag[0] -> hashtag, tag[1] -> frequency\n if doc is None:\n data = {}\n data[\"_id\"] = tag[0].replace('\\u','') # use word as an id\n data[\"hashtag\"] = tag[0].replace('\\u','')\n data[\"count\"] = tag[1]\n else:\n data = doc\n data[\"count\"] = data[\"count\"] + tag[1]\n \n hashtags.save(data)",
"_____no_output_____"
],
[
"texts = []\nusers = []\nfor row in view_data:\n text = {}\n text[\"text\"] = row[\"text\"]\n text[\"sentiment\"] = row[\"sentiment\"]\n texts.append(text)\n user = row[\"user\"]\n try:\n gender = gc.resolveGender(user[\"name\"], None)\n user[\"gender\"] = gender\n except:\n continue\n users.append(user)",
"_____no_output_____"
],
[
"print(\"text\",len(texts),\" user\", len(users))",
"('text', 254, ' user', 254)\n"
],
[
"import re\n \nemoticons_str = r\"\"\"\n (?:\n [:=;] # Eyes\n [oO\\-]? # Nose (optional)\n [D\\)\\]\\(\\]/\\\\OpP] # Mouth\n )\"\"\"\n \nregex_str = [\n emoticons_str,\n r'<[^>]+>', # HTML tags\n r'(?:@[\\w_]+)', # @-mentions\n r\"(?:\\#+[\\w_]+[\\w\\'_\\-]*[\\w_]+)\", # hash-tags\n r'http[s]?://(?:[a-z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-f][0-9a-f]))+', # URLs\n r'(?:(?:\\d+,?)+(?:\\.?\\d+)?)', # numbers\n r\"(?:[a-z][a-z'\\-_]+[a-z])\", # words with - and '\n r'(?:[\\w_]+)', # other words\n r'(?:\\S)' # anything else\n]\n \ntokens_re = re.compile(r'('+'|'.join(regex_str)+')', re.VERBOSE | re.IGNORECASE)\nemoticon_re = re.compile(r'^'+emoticons_str+'$', re.VERBOSE | re.IGNORECASE)\n \ndef tokenize(s):\n return tokens_re.findall(s)\n \ndef preprocess(s, lowercase=False):\n tokens = tokenize(s)\n if lowercase:\n tokens = [token if emoticon_re.search(token) else token.lower() for token in tokens]\n return tokens",
"_____no_output_____"
],
[
"## Save Terms Frequency\nimport HTMLParser\nfrom collections import Counter\nfrom nltk.corpus import stopwords\nimport string\npunctuation = list(string.punctuation)\nstop = stopwords.words('english') + punctuation + ['rt', 'via']\ncount_all = Counter()\nhtml_parser = HTMLParser.HTMLParser()\nemoji_pattern = re.compile(\n u\"(\\ud83d[\\ude00-\\ude4f])|\" # emoticons\n u\"(\\ud83c[\\udf00-\\uffff])|\" # symbols & pictographs (1 of 2)\n u\"(\\ud83d[\\u0000-\\uddff])|\" # symbols & pictographs (2 of 2)\n u\"(\\ud83d[\\ude80-\\udeff])|\" # transport & map symbols\n u\"(\\ud83c[\\udde0-\\uddff])\" # flags (iOS)\n \"+\", flags=re.UNICODE)\nfor text in texts:\n cleanText = re.sub(r\"http\\S+\", \"\", text['text'])\n cleanText = html_parser.unescape(cleanText)\n cleanText = emoji_pattern.sub(r'', cleanText)\n terms_stop = [term for term in preprocess(cleanText) if term not in stop]\n count_all.update(terms_stop)\n\ntry:\n words = server.create[\"twitter-words\"]\nexcept:\n words = server[\"twitter-words\"]\n \nfor num in count_all.most_common():\n doc = words.get(num[0]) # num[0] -> word, num[1] -> frequency\n try:\n if doc is None:\n data = {}\n word_text = num[0].decode(\"utf8\").encode('ascii','ignore') # make sure we don't save unsafe character\n data[\"_id\"] = word_text # use word as an id\n data[\"word\"] = word_text\n data[\"count\"] = num[1]\n else:\n data = doc\n data[\"count\"] = data[\"count\"] + num[1]\n words.save(data)\n except:\n continue",
"_____no_output_____"
],
[
"#save user data\n# try create user db\ntry:\n user = server.create[\"twitter-users\"]\nexcept:\n user = server[\"twitter-users\"]\n \nfor row in users:\n id = row[\"id\"]\n doc = user.get(str(id))\n if doc is None:\n row[\"_id\"] = str(row[\"id\"])\n user.save(row)",
"_____no_output_____"
],
[
"\"☕\".decode(\"utf8\").encode('ascii','ignore') == \"\"",
"_____no_output_____"
],
[
"import datetime\ntoday = datetime.date.today()\ntoday = today.strftime('%Y/%-m/%-d')\nprint(today)",
"2017/5/9\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d080c444d2b66f287a5b3fa3242c111420c3b314 | 141,107 | ipynb | Jupyter Notebook | Feature_Engineering_1.ipynb | mmastin/Data-Science | b8bf3e874c38f580bccb2f405fcbac17324970a3 | [
"MIT"
] | null | null | null | Feature_Engineering_1.ipynb | mmastin/Data-Science | b8bf3e874c38f580bccb2f405fcbac17324970a3 | [
"MIT"
] | null | null | null | Feature_Engineering_1.ipynb | mmastin/Data-Science | b8bf3e874c38f580bccb2f405fcbac17324970a3 | [
"MIT"
] | 1 | 2019-10-05T15:07:13.000Z | 2019-10-05T15:07:13.000Z | 45.255613 | 131 | 0.293848 | [
[
[
"import pandas as pd\nimport numpy as np\n\npd.set_option('display.max_columns', None)\n\ndf = pd.read_csv('/Users/mattmastin/Desktop/Valley-Behavioral/vbhsample.csv')",
"_____no_output_____"
],
[
"df.describe()",
"_____no_output_____"
],
[
"columns_drop = ['Unnamed: 15', 'EmploymentInformation', 'HeadOfHousehold']\n\ndf.drop(columns=columns_drop, axis=1)",
"_____no_output_____"
],
[
"df['ClientStatus'] = df['ClientStatus'].map({'Y': 1, 'N': 0})",
"_____no_output_____"
],
[
"df['MilitaryStatus'] = df['MilitaryStatus'].map({'Yes': 1, 'No': 0})",
"_____no_output_____"
],
[
"# df['Ethnicity'].value_counts()\ndf.drop(columns='Ethnicity', axis=1)",
"_____no_output_____"
],
[
"df['HispanicOrigin'] = df['HispanicOrigin'].map({'Not of Hispanic Origin': 0, 'Unknown': 0, \n 'Mexican': 1, 'Other Hispanic Origin': 1, \n 'Puerto Rican': 1, 'Cuban': 1})",
"_____no_output_____"
],
[
"df['HispanicOrigin'] = df['HispanicOrigin'].fillna(0)",
"_____no_output_____"
],
[
"df.drop(columns=['ClientState', 'ClientCounty'], axis=1)",
"_____no_output_____"
],
[
"df['FinanciallyResponsible'] = df['FinanciallyResponsible'].map({'Y': 1, 'N': 0})",
"_____no_output_____"
],
[
"df['LivingArrangement'] = df['LivingArrangement'].map({'Private Residence-Independent': 0,\n 'Private Residence-Dependent': 0,\n 'Institutional Setting': 1,\n '24-hour Residential Care': 1,\n 'Jail or Correctional Facility': 2,\n 'Adult or Child Foster Care': 2,\n 'On Street or in a Homeless Shelter': 3})",
"_____no_output_____"
],
[
"# filling with by far largest class. Wrong choice?\n\ndf['LivingArrangement'].fillna(0, inplace=True)\n\ndf['LivingArrangement'].isna().sum()",
"_____no_output_____"
],
[
"df['MilitaryStatus'].fillna(0, inplace=True)",
"_____no_output_____"
],
[
"df['SmokingStatus'] = df['SmokingStatus'].map({'NEVER SMOKED/VAPED': 0,\n 'CURRENT EVERDAY SMOKER/E-CIG USER': 1,\n 'FORMER SMOKER/E-CIG USER': 1,\n 'NOT APPLICABLE': 0,\n 'CURRENT SOME DAY SMOKER/E-CIG USER': 1,\n 'USE SMOKELESS TOBACCO ONLY (In last 30 days)': 1,\n 'FORMER SMOKING STATUS UNKNOWN': 0})",
"_____no_output_____"
],
[
"df['SmokingStatus'].fillna(0, inplace=True)",
"_____no_output_____"
],
[
"df.drop(columns='AgeOfFirstTobaccoUse', inplace=True)",
"_____no_output_____"
],
[
"df['EducationStatus'].value_counts()",
"_____no_output_____"
],
[
"df['EducationStatus'] = df['EducationStatus'].map({'Not currently enrolled': 0,\n 'Yes currently enrolled': 1,\n 'Unknown': 0})",
"_____no_output_____"
],
[
"df['EducationStatus'].fillna(0, inplace=True)",
"_____no_output_____"
],
[
"df['ForensicTreatment'] = df['ForensicTreatment'].map({'Not applicable': 0,\n 'Declined to answer': 0,\n 'New-(Justice Involved) OLD-Criminal Court Ordered Compelled for Tx': 1,\n 'Criminal court – ordered treatment': 1,\n 'Department of corrections client': 1,\n 'Civil Court ordered – treatment': 1,\n 'Court- ordered evaluation/assessment only': 1})",
"_____no_output_____"
],
[
"df['ForensicTreatment'].fillna(0, inplace=True)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d080c6127fa136d7d026692ff71829be855d2702 | 4,999 | ipynb | Jupyter Notebook | doc/source/cookbook/tipsy_and_yt.ipynb | Kiradorn/yt | d4d833bd773413e776b2c5b0f771e34857c27f74 | [
"BSD-3-Clause-Clear"
] | 360 | 2017-04-24T05:06:04.000Z | 2022-03-31T10:47:07.000Z | doc/source/cookbook/tipsy_and_yt.ipynb | Kiradorn/yt | d4d833bd773413e776b2c5b0f771e34857c27f74 | [
"BSD-3-Clause-Clear"
] | 2,077 | 2017-04-20T20:36:07.000Z | 2022-03-31T16:39:43.000Z | doc/source/cookbook/tipsy_and_yt.ipynb | Kiradorn/yt | d4d833bd773413e776b2c5b0f771e34857c27f74 | [
"BSD-3-Clause-Clear"
] | 257 | 2017-04-19T20:52:28.000Z | 2022-03-29T12:23:52.000Z | 24.033654 | 332 | 0.559712 | [
[
[
"## Loading Files",
"_____no_output_____"
],
[
"Alright, let's start with some basics. Before we do anything, we will need to load a snapshot. You can do this using the ```load_sample``` convenience function. yt will autodetect that you want a tipsy snapshot and download it from the yt hub.",
"_____no_output_____"
]
],
[
[
"import yt",
"_____no_output_____"
]
],
[
[
"We will be looking at a fairly low resolution dataset.",
"_____no_output_____"
],
[
">This dataset is available for download at https://yt-project.org/data/TipsyGalaxy.tar.gz (10 MB).",
"_____no_output_____"
]
],
[
[
"ds = yt.load_sample(\"TipsyGalaxy\")",
"_____no_output_____"
]
],
[
[
"We now have a `TipsyDataset` object called `ds`. Let's see what fields it has.",
"_____no_output_____"
]
],
[
[
"ds.field_list",
"_____no_output_____"
]
],
[
[
"yt also defines so-called \"derived\" fields. These fields are functions of the on-disk fields that live in the `field_list`. There is a `derived_field_list` attribute attached to the `Dataset` object - let's take look at the derived fields in this dataset:",
"_____no_output_____"
]
],
[
[
"ds.derived_field_list",
"_____no_output_____"
]
],
[
[
"All of the field in the `field_list` are arrays containing the values for the associated particles. These haven't been smoothed or gridded in any way. We can grab the array-data for these particles using `ds.all_data()`. For example, let's take a look at a temperature-colored scatterplot of the gas particles in this output.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np",
"_____no_output_____"
],
[
"ad = ds.all_data()\nxcoord = ad[\"Gas\", \"Coordinates\"][:, 0].v\nycoord = ad[\"Gas\", \"Coordinates\"][:, 1].v\nlogT = np.log10(ad[\"Gas\", \"Temperature\"])\nplt.scatter(\n xcoord, ycoord, c=logT, s=2 * logT, marker=\"o\", edgecolor=\"none\", vmin=2, vmax=6\n)\nplt.xlim(-20, 20)\nplt.ylim(-20, 20)\ncb = plt.colorbar()\ncb.set_label(r\"$\\log_{10}$ Temperature\")\nplt.gcf().set_size_inches(15, 10)",
"_____no_output_____"
]
],
[
[
"## Making Smoothed Images",
"_____no_output_____"
],
[
"yt will automatically generate smoothed versions of these fields that you can use to plot. Let's make a temperature slice and a density projection.",
"_____no_output_____"
]
],
[
[
"yt.SlicePlot(ds, \"z\", (\"gas\", \"density\"), width=(40, \"kpc\"), center=\"m\")",
"_____no_output_____"
],
[
"yt.ProjectionPlot(ds, \"z\", (\"gas\", \"density\"), width=(40, \"kpc\"), center=\"m\")",
"_____no_output_____"
]
],
[
[
"Not only are the values in the tipsy snapshot read and automatically smoothed, the auxiliary files that have physical significance are also smoothed. Let's look at a slice of Iron mass fraction.",
"_____no_output_____"
]
],
[
[
"yt.SlicePlot(ds, \"z\", (\"gas\", \"Fe_fraction\"), width=(40, \"kpc\"), center=\"m\")",
"_____no_output_____"
]
]
] | [
"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",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
d080ca7c1b5b79bb9aa26ba026f1781702202d22 | 244,641 | ipynb | Jupyter Notebook | NLP_subreddits_Spacex_v_Boeing.ipynb | MattPat1981/new_space_race_nlp | ced47926b1a4fe7f83e0f1a460e456f4bf5f6b0e | [
"CC0-1.0"
] | 1 | 2021-06-26T21:28:32.000Z | 2021-06-26T21:28:32.000Z | NLP_subreddits_Spacex_v_Boeing.ipynb | MattPat1981/new_space_race_nlp | ced47926b1a4fe7f83e0f1a460e456f4bf5f6b0e | [
"CC0-1.0"
] | null | null | null | NLP_subreddits_Spacex_v_Boeing.ipynb | MattPat1981/new_space_race_nlp | ced47926b1a4fe7f83e0f1a460e456f4bf5f6b0e | [
"CC0-1.0"
] | 1 | 2022-02-11T00:30:58.000Z | 2022-02-11T00:30:58.000Z | 73.753693 | 21,116 | 0.708614 | [
[
[
"### Natural Language Processing, a look at distinguishing subreddit categories by analyzing the text of the comments and posts\n\n**Matt Paterson, [email protected]**\nGeneral Assembly Data Science Immersive, July 2020",
"_____no_output_____"
],
[
"### Abstract\n\n**HireMattPaterson.com has been (fictionally) contracted by Virgin Galactic’s marketing team to build a Natural Language Processing Model that will efficiently predict if reddit posts are being made for the SpaceX subreddit or the Boeing subreddit as a proof of concept to segmenting the targeted markets.**\n\nWe’ve created a model that predicts the silo of the post with nearly 80% accuracy (with a top score of 79.9%). To get there we tried over 2,000 different iterations on a total of 5 different classification modeling algorithms including two versions of Multinomial Naïve Bayes, Random Cut Forest, Extra Trees, and a simple Logistic Regression Classifier. We’d like to use Support Vector Machines as well as Gradient Boosting and a K-Nearest Neighbors model in our follow-up to this presentation.\n\nIf you like our proof of concept, the next iteration of our model will take in to account the trend or frequency in the comments of each user; what other subreddits these users can be found to post to (are they commenting on the Rolex and Gulfstream and Maserati or are they part of the Venture Capital and AI crowd?); and if their comments appear to be professional in nature (are they looking to someday work in aerospace or maybe they already do). These trends will help the marketing team tune their tone, choose words that are trending, and speak directly to each cohort in a narrow-cast fashion thus allowing VG to spend less money on ads and on people over time.\n\nThis notebook shows how we got there.",
"_____no_output_____"
],
[
"### Problem Statement:\n\nVirgin Galactic wants to charge customers USD 250K per voyage to bring customers into outer space on a pleasure cruise in null G\n\nThe potential customers range from more traditional HNWI who have more conservative values, to the Nouveau Riche, and various levels of tech millionaires in between\n\nLarge teams of many Marketing Analysts and Marketing Managers are expensive\n\nIf you can keep your current headcount or only add a few you are better off, since as headcount grows, overall ROI tends to shrink (VG HC ~ 200 ppl)\n\n### Solution:\n\nCreate a machine learning model to identify what type of interests each user has based on their social media and reddit posts\n\nNarrowcast to each smaller cohort with the language, tone, and vocabulary that will push each to purchase the quarter-million dollar flight\n",
"_____no_output_____"
],
[
"## Import libraries",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport nltk\nimport lebowski as dude\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nfrom sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.metrics import confusion_matrix, plot_confusion_matrix\nfrom sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier, AdaBoostClassifier, VotingClassifier\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier",
"_____no_output_____"
]
],
[
[
"## Read in the data. \n\nIn the data_file_creation.ipynb found in this directory, we have already gone to the 'https://api.pushshift.io/reddit/search/' api and pulled subreddit posts and comments from SpaceX, Boeing, BlueOrigin, and VirginGalactic; four specific companies venturing into the outer space exploration business with distinct differences therein. It is the theory of this research team that each subreddit will also have a distinct group of main users, or possible customers that are engaging on each platform. While there will be overlap in the usership, there will also be a clear lexicon that each subreddit thread has. \n\nIn this particular study, we will look specifically at the differences between SpaceX and Boeing, and will create a classification model that predicts whether a post is indeed in the SpaceX subreddit or not in the SpaceX subreddit. \n\nFinally we will test the model against a testing set that is made up of posts from all four companies and measure its ability to predict which posts are SpaceX and which are not.",
"_____no_output_____"
]
],
[
[
"spacex = pd.read_csv('./data/spacex.csv')\nboeing = pd.read_csv('./data/boeing.csv')",
"_____no_output_____"
],
[
"spacex.head()",
"_____no_output_____"
]
],
[
[
"We have already done a lot of cleaning up, but as we see there are still many NaN values and other meaningless values in our data. We'll create a function to remove these values using mapping in our dataframe. \n\nBefore we get there, let's convert our target column into a binary selector.",
"_____no_output_____"
]
],
[
[
"spacex['subreddit'] = spacex['subreddit'].map({'spacex': 1, 'boeing': 0})\nboeing['subreddit'] = boeing['subreddit'].map({'spacex': 1, 'boeing': 0})",
"_____no_output_____"
]
],
[
[
"And drop the null values right off too.",
"_____no_output_____"
]
],
[
[
"print(f\"spacex df has {spacex.isna().sum()} null values not including extraneous words\")\nprint(f\"boeing df has {boeing.isna().sum()} null values not including extraneous words\")",
"spacex df has subreddit 0\nbody 37\npermalink 0\ndtype: int64 null values not including extraneous words\nboeing df has subreddit 0\nbody 24\npermalink 0\ndtype: int64 null values not including extraneous words\n"
]
],
[
[
"we can remove these 61 rows right off",
"_____no_output_____"
]
],
[
[
"spacex = spacex.dropna()\nboeing = boeing.dropna()\nspacex.shape",
"_____no_output_____"
],
[
"boeing.shape",
"_____no_output_____"
]
],
[
[
"## Merge into one dataframe",
"_____no_output_____"
]
],
[
[
"space_wars = pd.concat([spacex, boeing])\nspace_wars.shape",
"_____no_output_____"
]
],
[
[
"## Use TF to break up the dataframes into numbers and then drop the unneeded words",
"_____no_output_____"
]
],
[
[
"tvec = TfidfVectorizer(stop_words = 'english')",
"_____no_output_____"
]
],
[
[
"We will only put the 'body' column in to the count vectorizer",
"_____no_output_____"
]
],
[
[
"X_list = space_wars.body\nnums_df = pd.DataFrame(tvec.fit_transform(X_list).toarray(),\n columns=tvec.get_feature_names())\nnums_df.head()",
"_____no_output_____"
]
],
[
[
"And with credit to Noelle Brown, let's graph the resulting top words:",
"_____no_output_____"
]
],
[
[
"# get count of top-occurring words\ntop_words_tf = {}\nfor i in nums_df.columns:\n top_words_tf[i] = nums_df[i].sum()\n \n# top_words to dataframe sorted by highest occurance\nmost_freq_tf = pd.DataFrame(sorted(top_words_tf.items(), key = lambda x: x[1], reverse = True))\n\nplt.figure(figsize = (10, 5))\n\n# visualize top 10 words\nplt.bar(most_freq_tf[0][:10], most_freq_tf[1][:10]);",
"_____no_output_____"
]
],
[
[
"We can see that if we remove 'replace_me', 'removed', and 'deleted', then we'll be dealing with a much more useful dataset. For the words dataframe, we can just add these words to our stop_words library. For the numeric dataframe we'll drop them here, as well as a few more.",
"_____no_output_____"
]
],
[
[
"dropwords = ['replace_me', 'removed', 'deleted', 'https', 'com', 'don', 'www']\nnums_df = nums_df.drop(columns=dropwords)",
"_____no_output_____"
]
],
[
[
"And we can re-run the graph above for a better look.",
"_____no_output_____"
]
],
[
[
"# get count of top-occurring words\ntop_words_tf = {}\nfor i in nums_df.columns:\n top_words_tf[i] = nums_df[i].sum()\n \n# top_words to dataframe sorted by highest occurance\nmost_freq_tf = pd.DataFrame(sorted(top_words_tf.items(), key = lambda x: x[1], reverse = True))\n\nplt.figure(figsize = (18, 6))\ndude.graph_words('black')\n\n# visualize top 10 words\nplt.bar(most_freq_tf[0][:15], most_freq_tf[1][:15]);",
"_____no_output_____"
]
],
[
[
"If I had more time I'd like to graph the words used most in each company. I can go ahead and try to display which company is more verbose, wordy that is, and which one uses longer words (Credit to Hovanes Gasparian).",
"_____no_output_____"
]
],
[
[
"nums_df = pd.concat([space_wars['subreddit'], nums_df])",
"_____no_output_____"
],
[
"space_wars['word_count'] = space_wars['body'].apply(dude.word_count)\nspace_wars['post_length'] = space_wars['body'].apply(dude.count_chars)",
"_____no_output_____"
],
[
"space_wars[['word_count', 'post_length']].describe().T",
"_____no_output_____"
],
[
"space_wars.groupby(['word_count']).size().sort_values(ascending=False)#.head()\n",
"_____no_output_____"
],
[
"space_wars[space_wars['word_count'] > 1000]",
"_____no_output_____"
],
[
"#space_wars.groupby(['subreddit', 'word_count']).size().sort_values(ascending=False).head()\nspace_wars.subreddit.value_counts()",
"_____no_output_____"
],
[
"plt.figure(figsize=(18,6))\ndude.graph_words('black')\nplt.hist([space_wars[space_wars['subreddit']==0]['word_count'], \n space_wars[space_wars['subreddit']==1]['word_count']],\n bins=3, color=['blue', 'red'], ec='k')\nplt.title('Word Count by Company', fontsize=30)\nplt.legend(['Boeing', 'SpaceX']);",
"_____no_output_____"
]
],
[
[
"## Trouble in parsing-dise\nIt appears that I'm having some issues with manipulating this portion of the data. I will clean this up before final pull request.",
"_____no_output_____"
],
[
"## Create test_train_split with word data",
"_____no_output_____"
],
[
"#### Find the baseline:",
"_____no_output_____"
]
],
[
[
"baseline = space_wars.subreddit.value_counts(normalize=True)[1]\nall_scores = {}\nall_scores['baseline'] = baseline\nall_scores['baseline']",
"_____no_output_____"
],
[
"X_words = space_wars['body']\ny_words = space_wars['subreddit']",
"_____no_output_____"
],
[
"X_train_w, X_test_w, y_train_w, y_test_w = train_test_split(X_words,\n y_words,\n random_state=42,\n test_size=.1,\n stratify=y_words)",
"_____no_output_____"
]
],
[
[
"## Now it's time to train some models!",
"_____no_output_____"
]
],
[
[
"# Modify our stopwords list from the nltk.'english'\nstopwords = nltk.corpus.stopwords.words('english')\n# Above we created a list called dropwords\nfor i in dropwords:\n stopwords.append(i)",
"_____no_output_____"
],
[
"param_cv = {\n 'stop_words' : stopwords,\n 'ngram_range' : (1, 2),\n 'analyzer' : 'word',\n 'max_df' : 0.8,\n 'min_df' : 0.02,\n}",
"_____no_output_____"
],
[
"cntv = CountVectorizer(param_cv)",
"_____no_output_____"
],
[
"# Print y_test for a sanity check\ny_test_w",
"_____no_output_____"
],
[
"# credit Noelle from lecture\ntrain_data_features = cntv.fit_transform(X_train_w, y_train_w)\ntest_data_features = cntv.transform(X_test_w)",
"_____no_output_____"
]
],
[
[
"## Logistic Regression",
"_____no_output_____"
]
],
[
[
"lr = LogisticRegression( max_iter = 10_000)\n\nlr.fit(train_data_features, y_train_w)",
"_____no_output_____"
],
[
"lr.score(train_data_features, y_train_w)",
"_____no_output_____"
],
[
"all_scores['Logistic Regression'] = lr.score(test_data_features, y_test_w)\nall_scores['Logistic Regression']",
"_____no_output_____"
]
],
[
[
"***Using a simple Logistic regression with very little tweaking, a set of stopwords, we created a model that while slightly overfit, is more than 22 points more accurate than the baseline.***\n\n## What does the confusion matrix look like? Is 80% accuracy even good?\n\nPerhaps I can get some help making a confusion matrix with this data?",
"_____no_output_____"
],
[
"## Multinomial Naive Bayes using CountVectorizer\n\nIn this section we will create a Pipeline that starts with the CountVectorizer and ends with the Multinomial Naive Bayes Algorithm. We'll run through 270 possible configurations of this model, and run it in parallel on 3 of the 4 cores on my machine.",
"_____no_output_____"
]
],
[
[
"pipe = Pipeline([\n ('count_v', CountVectorizer()),\n ('nb', MultinomialNB())\n])\n\npipe_params = {\n 'count_v__max_features': [2000, 5000, 9000],\n 'count_v__stop_words': [stopwords],\n 'count_v__min_df': [2, 3, 10],\n 'count_v__max_df': [.9, .8, .7],\n 'count_v__ngram_range': [(1, 1), (1, 2)]\n}\n\ngs = GridSearchCV(pipe,\n pipe_params,\n cv = 5,\n n_jobs=6\n)",
"_____no_output_____"
],
[
"%%time\ngs.fit(X_train_w, y_train_w)",
"Wall time: 53 s\n"
],
[
"gs.best_params_",
"_____no_output_____"
],
[
"all_scores['Naive Bayes'] = gs.best_score_\nall_scores['Naive Bayes']",
"_____no_output_____"
],
[
"gs.best_index_\n# is this the index that has the best indication of being positive?",
"_____no_output_____"
]
],
[
[
"We see that our Naive Bayes model yields an accuracy score just shy of our Logistic Regression model, 79.7%\n\n**What does the confusion matrix look like?**",
"_____no_output_____"
]
],
[
[
"# Get predictions and true/false pos/neg\npreds = gs.predict(X_test_w)\ntn, fp, fn, tp = confusion_matrix(y_test_w, preds).ravel()\n\n# View confusion matrix\ndude.graph_words('black')\nplot_confusion_matrix(gs, X_test_w, y_test_w, cmap='Blues', values_format='d');",
"_____no_output_____"
],
[
"sensitivity = tp / (tp + fp)\nsensitivity",
"_____no_output_____"
],
[
"specificity = tn / (tn + fn)\nspecificity",
"_____no_output_____"
]
],
[
[
"## Naive Bayes using the TFID Vectorizer",
"_____no_output_____"
]
],
[
[
"pipe_tvec = Pipeline([\n ('tvec', TfidfVectorizer()),\n ('nb', MultinomialNB())\n])\n\npipe_params_tvec = {\n 'tvec__max_features': [2000, 9000],\n 'tvec__stop_words' : [None, stopwords],\n 'tvec__ngram_range': [(1, 1), (1, 2)]\n}\n\ngs_tvec = GridSearchCV(pipe_tvec, pipe_params_tvec, cv = 5)",
"_____no_output_____"
],
[
"%%time\ngs_tvec.fit(X_train_w, y_train_w)",
"Wall time: 37.1 s\n"
],
[
"all_scores['Naive Bayes TFID'] = gs_tvec.best_score_\nall_scores['Naive Bayes TFID']",
"_____no_output_____"
],
[
"all_scores",
"_____no_output_____"
],
[
"# Confusion Matrix for tvec\npreds = gs_tvec.predict(X_test_w)\ntn, fp, fn, tp = confusion_matrix(y_test_w, preds).ravel()\n# View confusion matrix\ndude.graph_words('black')\nplot_confusion_matrix(gs_tvec, X_test_w, y_test_w, cmap='Blues', values_format='d');",
"_____no_output_____"
],
[
"specificity = tn / (tn+fn)\nspecificity",
"_____no_output_____"
],
[
"sensitivity = tp / (tp+fp)\nsensitivity",
"_____no_output_____"
]
],
[
[
"Here, the specificity is 4 points higher than the NB using Count Vectorizer, but the sensitity and overall accuracy are about the same.",
"_____no_output_____"
],
[
"## Random Cut Forest and Extra Trees",
"_____no_output_____"
]
],
[
[
"pipe_rf = Pipeline([\n ('count_v', CountVectorizer()),\n ('rf', RandomForestClassifier()),\n])\n\npipe_ef = Pipeline([\n ('count_v', CountVectorizer()),\n ('ef', ExtraTreesClassifier()),\n])\n\npipe_params = {\n 'count_v__max_features': [2000, 5000, 9000],\n 'count_v__stop_words': [stopwords],\n 'count_v__min_df': [2, 3, 10],\n 'count_v__max_df': [.9, .8, .7],\n 'count_v__ngram_range': [(1, 1), (1, 2)]\n}",
"_____no_output_____"
],
[
"%%time\ngs_rf = GridSearchCV(pipe_rf,\n pipe_params,\n cv = 5,\n n_jobs=6)\ngs_rf.fit(X_train_w, y_train_w)\nprint(gs_rf.best_score_)\ngs_rf.best_params_",
"0.7736946482225429\nWall time: 5min 47s\n"
],
[
"gs_rf.best_estimator_",
"_____no_output_____"
],
[
"all_scores['Random Cut Forest'] = gs_rf.best_score_\nall_scores",
"_____no_output_____"
],
[
"# Confusion Matrix for Random Cut Forest\npreds = gs_rf.predict(X_test_w)\ntn, fp, fn, tp = confusion_matrix(y_test_w, preds).ravel()\n# View confusion matrix\ndude.graph_words('black')\nplot_confusion_matrix(gs_rf, X_test_w, y_test_w, cmap='Blues', values_format='d');",
"_____no_output_____"
],
[
"specificity = tn / (tn+fn)\nspecificity",
"_____no_output_____"
],
[
"sensitivity = tp / (tp+fp)\nsensitivity",
"_____no_output_____"
]
],
[
[
"Our original Logistic Regression model is still the winner.",
"_____no_output_____"
],
[
"## What does the matchup look like?",
"_____no_output_____"
]
],
[
[
"score_df = pd.DataFrame([all_scores])\nscore_df.shape",
"_____no_output_____"
],
[
"score_df.head()",
"_____no_output_____"
]
],
[
[
"## Create a Count Vecotorized dataset\nSince the below cells have been troublesome, we'll create a dataset using only the count vectorizer and then use that data in the model as we did above.",
"_____no_output_____"
]
],
[
[
"# Re-establish the subsets using Noelle's starter script again\ntrain_data_features = cntv.fit_transform(X_train_w, y_train_w)\ntest_data_features = cntv.transform(X_test_w)",
"_____no_output_____"
],
[
"pipe_params_tvec = {\n 'tvec__max_features': [2000, 9000],\n 'tvec__stop_words' : [None, stopwords],\n 'tvec__ngram_range': [(1, 1), (1, 2)]\n}\n\nknn_pipe = Pipeline([\n ('ss', StandardScaler()),\n ('knn', KNeighborsClassifier())\n])\n\ntree_pipe = Pipeline([\n ('tvec', TfidfVectorizer()), \n ('tree', DecisionTreeClassifier())\n])\n\nada_pipe = Pipeline([\n ('tvec', TfidfVectorizer()),\n ('ada', AdaBoostClassifier(base_estimator=DecisionTreeClassifier())),\n])\n\ngrad_pipe = Pipeline([\n ('tvec', TfidfVectorizer()),\n ('grad_boost', GradientBoostingClassifier()),\n])",
"_____no_output_____"
]
],
[
[
"### Irreconcilable Error:\n\nAt this time there are still structural issues that are not allowing this last block of code to complete the final model attempts (user error).\n\n***In the next few days, prior to publication, this notebook will be revamped and this final cell will execute.***",
"_____no_output_____"
]
],
[
[
"%%time\n\nvote = VotingClassifier([\n ('ada', AdaBoostClassifier(base_estimator=DecisionTreeClassifier())),\n ('grad_boost', GradientBoostingClassifier()),\n ('tree', DecisionTreeClassifier()),\n ('knn_pipe', knn_pipe)\n])\nparams = {\n 'ada__n_estimators': [50, 51], # since HPO names are common, use dunder from tuple names\n 'grad_boost__n_estimators': [10, 11],\n 'knn_pipe__knn__n_neighbors': [3, 5],\n 'ada__base_estimator__max_depth': [1, 2],\n 'tree__max_depth': [1, 2],\n 'weights':[[.25] * 4, [.3, .3, .3, .1]]\n}\n\ngs = GridSearchCV(vote, param_grid=params, cv=3)\ngs.fit(train_data_features, y_train_w)\nprint(gs.best_score_)\ngs.best_params_",
"C:\\ProgramData\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_validation.py:536: FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details: \nValueError: Cannot center sparse matrices: pass `with_mean=False` instead. See docstring for motivation and alternatives.\n\n FitFailedWarning)\nC:\\ProgramData\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_validation.py:536: FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details: \nValueError: Cannot center sparse matrices: pass `with_mean=False` instead. See docstring for motivation and alternatives.\n\n FitFailedWarning)\nC:\\ProgramData\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_validation.py:536: FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details: \nValueError: Cannot center sparse matrices: pass `with_mean=False` instead. See docstring for motivation and alternatives.\n\n FitFailedWarning)\nC:\\ProgramData\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_validation.py:536: FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details: \nValueError: Cannot center sparse matrices: pass `with_mean=False` instead. See docstring for motivation and alternatives.\n\n FitFailedWarning)\nC:\\ProgramData\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_validation.py:536: FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details: \nValueError: Cannot center sparse matrices: pass `with_mean=False` instead. See docstring for motivation and alternatives.\n\n FitFailedWarning)\nC:\\ProgramData\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_validation.py:536: FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details: \nValueError: Cannot center sparse matrices: pass `with_mean=False` instead. See docstring for motivation and alternatives.\n\n FitFailedWarning)\nC:\\ProgramData\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_validation.py:536: FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details: \nValueError: Cannot center sparse matrices: pass `with_mean=False` instead. See docstring for motivation and alternatives.\n\n FitFailedWarning)\nC:\\ProgramData\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_validation.py:536: FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details: \nValueError: Cannot center sparse matrices: pass `with_mean=False` instead. See docstring for motivation and alternatives.\n\n FitFailedWarning)\nC:\\ProgramData\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_validation.py:536: FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details: \nValueError: Cannot center sparse matrices: pass `with_mean=False` instead. See docstring for motivation and alternatives.\n\n FitFailedWarning)\nC:\\ProgramData\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_validation.py:536: FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details: \nValueError: Cannot center sparse matrices: pass `with_mean=False` instead. See docstring for motivation and alternatives.\n\n FitFailedWarning)\nC:\\ProgramData\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_validation.py:536: FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details: \nValueError: Cannot center sparse matrices: pass `with_mean=False` instead. See docstring for motivation and alternatives.\n\n FitFailedWarning)\nC:\\ProgramData\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_validation.py:536: FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details: \nValueError: Cannot center sparse matrices: pass `with_mean=False` instead. See docstring for motivation and alternatives.\n\n FitFailedWarning)\nC:\\ProgramData\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_validation.py:536: FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details: \nValueError: Cannot center sparse matrices: pass `with_mean=False` instead. See docstring for motivation and alternatives.\n\n FitFailedWarning)\nC:\\ProgramData\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_validation.py:536: FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details: \nValueError: Cannot center sparse matrices: pass `with_mean=False` instead. See docstring for motivation and alternatives.\n\n FitFailedWarning)\nC:\\ProgramData\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_validation.py:536: FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details: \nValueError: Cannot center sparse matrices: pass `with_mean=False` instead. See docstring for motivation and alternatives.\n\n FitFailedWarning)\nC:\\ProgramData\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_validation.py:536: FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details: \nValueError: Cannot center sparse matrices: pass `with_mean=False` instead. See docstring for motivation and alternatives.\n\n FitFailedWarning)\nC:\\ProgramData\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_validation.py:536: FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details: \nValueError: Cannot center sparse matrices: pass `with_mean=False` instead. See docstring for motivation and alternatives.\n\n FitFailedWarning)\nC:\\ProgramData\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_validation.py:536: FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details: \nValueError: Cannot center sparse matrices: pass `with_mean=False` instead. See docstring for motivation and alternatives.\n\n FitFailedWarning)\nC:\\ProgramData\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_validation.py:536: FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details: \nValueError: Cannot center sparse matrices: pass `with_mean=False` instead. See docstring for motivation and alternatives.\n\n FitFailedWarning)\nC:\\ProgramData\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_validation.py:536: FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details: \nValueError: Cannot center sparse matrices: pass `with_mean=False` instead. See docstring for motivation and alternatives.\n\n FitFailedWarning)\nC:\\ProgramData\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_validation.py:536: FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details: \nValueError: Cannot center sparse matrices: pass `with_mean=False` instead. See docstring for motivation and alternatives.\n\n FitFailedWarning)\nC:\\ProgramData\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_validation.py:536: FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details: \nValueError: Cannot center sparse matrices: pass `with_mean=False` instead. See docstring for motivation and alternatives.\n\n FitFailedWarning)\nC:\\ProgramData\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_validation.py:536: FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details: \nValueError: Cannot center sparse matrices: pass `with_mean=False` instead. See docstring for motivation and alternatives.\n\n FitFailedWarning)\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",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
d080d0956c0f4475db66015747f22df1dfb03649 | 82,041 | ipynb | Jupyter Notebook | LatentFactorModel/LatentFactorModel.ipynb | vitutorial/exercises | 429807d6349c0d91d601b21338d80a6fe4450892 | [
"MIT"
] | 1 | 2020-09-05T11:42:47.000Z | 2020-09-05T11:42:47.000Z | LatentFactorModel/LatentFactorModel.ipynb | vitutorial/exercises | 429807d6349c0d91d601b21338d80a6fe4450892 | [
"MIT"
] | null | null | null | LatentFactorModel/LatentFactorModel.ipynb | vitutorial/exercises | 429807d6349c0d91d601b21338d80a6fe4450892 | [
"MIT"
] | 1 | 2020-01-21T10:52:30.000Z | 2020-01-21T10:52:30.000Z | 42.486277 | 796 | 0.544411 | [
[
[
"<a href=\"https://colab.research.google.com/github/vitutorial/exercises/blob/master/LatentFactorModel/LatentFactorModel.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n\nimport os\nimport re\nimport urllib.request\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport matplotlib.pyplot as plt\nimport itertools\n\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\ndevice = torch.device(\"cuda:0\") if torch.cuda.is_available() else torch.device(\"cpu\")",
"_____no_output_____"
]
],
[
[
"In this notebook you will work with a deep generative language model that maps words from a discrete (bit-vector-valued) latent space. We will use text data (we will work on the character level) in Spanish and pytorch. \n\nThe first section concerns data manipulation and data loading classes necessary for our implementation. You do not need to modify anything in this part of the code.",
"_____no_output_____"
],
[
"Let's first download the SIGMORPHON dataset that we will be using for this notebook: these are inflected Spanish words together with some morphosyntactic descriptors. For this notebook we will ignore the morphosyntactic descriptors.",
"_____no_output_____"
]
],
[
[
"url = \"https://raw.githubusercontent.com/ryancotterell/sigmorphon2016/master/data/\"\ntrain_file = \"spanish-task1-train\"\nval_file = \"spanish-task1-dev\"\ntest_file = \"spanish-task1-test\"\n\nprint(\"Downloading data files...\")\nif not os.path.isfile(train_file):\n urllib.request.urlretrieve(url + train_file, filename=train_file)\nif not os.path.isfile(val_file):\n urllib.request.urlretrieve(url + val_file, filename=val_file)\nif not os.path.isfile(test_file):\n urllib.request.urlretrieve(url + test_file, filename=test_file)\nprint(\"Download complete.\")",
"Downloading data files...\nDownload complete.\n"
]
],
[
[
"# Data\n\nIn order to work with text data, we need to transform the text into something that our algorithms can work with. The first step of this process is converting words into word ids. We do this by constructing a vocabulary from the data, assigning a new word id to each new word it encounters.",
"_____no_output_____"
]
],
[
[
"UNK_TOKEN = \"?\"\nPAD_TOKEN = \"_\"\nSOW_TOKEN = \">\"\nEOW_TOKEN = \".\"\n\ndef extract_inflected_word(s):\n \"\"\"\n Extracts the inflected words in the SIGMORPHON dataset.\n \"\"\"\n return s.split()[-1]\n\nclass Vocabulary:\n \n def __init__(self):\n self.idx_to_char = {0: UNK_TOKEN, 1: PAD_TOKEN, 2: SOW_TOKEN, 3: EOW_TOKEN}\n self.char_to_idx = {UNK_TOKEN: 0, PAD_TOKEN: 1, SOW_TOKEN: 2, EOW_TOKEN: 3}\n self.word_freqs = {}\n \n def __getitem__(self, key):\n return self.char_to_idx[key] if key in self.char_to_idx else self.char_to_idx[UNK_TOKEN]\n \n def word(self, idx):\n return self.idx_to_char[idx]\n \n def size(self):\n return len(self.char_to_idx)\n \n @staticmethod\n def from_data(filenames):\n \"\"\"\n Creates a vocabulary from a list of data files. It assumes that the data files have been\n tokenized and pre-processed beforehand.\n \"\"\"\n vocab = Vocabulary()\n for filename in filenames:\n with open(filename) as f:\n for line in f:\n \n # Strip whitespace and the newline symbol.\n word = extract_inflected_word(line.strip())\n \n # Split the words into characters and assign ids to each\n # new character it encounters.\n for char in list(word):\n if char not in vocab.char_to_idx:\n idx = len(vocab.char_to_idx)\n vocab.char_to_idx[char] = idx\n vocab.idx_to_char[idx] = char\n \n return vocab",
"_____no_output_____"
],
[
"# Construct a vocabulary from the training and validation data.\nprint(\"Constructing vocabulary...\")\nvocab = Vocabulary.from_data([train_file, val_file])\nprint(\"Constructed a vocabulary of %d types\" % vocab.size())",
"Constructing vocabulary...\nConstructed a vocabulary of 37 types\n"
],
[
"# some examples\nprint('e', vocab['e'])\nprint('é', vocab['é'])\nprint('ș', vocab['ș']) # something UNKNOWN",
"e 8\né 24\nș 0\n"
]
],
[
[
"We also need to load the data files into memory. We create a simple class `TextDataset` that stores the data as a list of words:",
"_____no_output_____"
]
],
[
[
"class TextDataset(Dataset):\n \"\"\"\n A simple class that loads a list of words into memory from a text file,\n split by newlines. This does not do any memory optimisation, \n so if your dataset is very large, you might want to use an alternative \n class.\n \"\"\"\n \n def __init__(self, text_file, max_len=30):\n self.data = []\n with open(text_file) as f:\n for line in f:\n word = extract_inflected_word(line.strip())\n if len(list(word)) <= max_len:\n self.data.append(word)\n \n def __len__(self):\n return len(self.data)\n \n def __getitem__(self, idx):\n return self.data[idx]",
"_____no_output_____"
],
[
"# Load the training, validation, and test datasets into memory.\ntrain_dataset = TextDataset(train_file)\nval_dataset = TextDataset(val_file)\ntest_dataset = TextDataset(test_file)\n\n# Print some samples from the data:\nprint(\"Sample from training data: \\\"%s\\\"\" % train_dataset[np.random.choice(len(train_dataset))])\nprint(\"Sample from validation data: \\\"%s\\\"\" % val_dataset[np.random.choice(len(val_dataset))])\nprint(\"Sample from test data: \\\"%s\\\"\" % test_dataset[np.random.choice(len(test_dataset))])",
"Sample from training data: \"compiláramos\"\nSample from validation data: \"debutara\"\nSample from test data: \"paginabas\"\n"
]
],
[
[
"Now it's time to write a function that converts a word into a list of character ids using the vocabulary we created before. This function is `create_batch` in the code cell below. This function creates a batch from a list of words, and makes sure that each word starts with a start-of-word symbol and ends with an end-of-word symbol. Because not all words are of equal length in a certain batch, words are padded with padding symbols so that they match the length of the largest word in the batch. The function returns an input batch, an output batch, a mask of 1s for words and 0s for padding symbols, and the sequence lengths of each word in the batch. The output batch is shifted by one character, to reflect the predictions that the model is expected to make. For example, for a word\n\\begin{align}\n \\text{e s p e s e m o s}\n\\end{align}\nthe input sequence is\n\\begin{align}\n \\text{SOW e s p e s e m o s}\n\\end{align}\nand the output sequence is\n\\begin{align}\n \\text{e s p e s e m o s EOW}\n\\end{align}\n\nYou can see the output is shifted wrt the input, that's because we will be computing a distribution for the next character in context of its prefix, and that's why we need to shift the sequence this way.\n\n\nLastly, we create an inverse function `batch_to_words` that recovers the list of words from a padded batch of character ids to use during test time.",
"_____no_output_____"
]
],
[
[
"def create_batch(words, vocab, device, word_dropout=0.):\n \"\"\"\n Converts a list of words to a padded batch of word ids. Returns\n an input batch, an output batch shifted by one, a sequence mask over\n the input batch, and a tensor containing the sequence length of each\n batch element.\n :param words: a list of words, each a list of token ids\n :param vocab: a Vocabulary object for this dataset\n :param device: \n :param word_dropout: rate at which we omit words from the context (input)\n :returns: a batch of padded inputs, a batch of padded outputs, mask, lengths\n \"\"\"\n tok = np.array([[SOW_TOKEN] + list(w) + [EOW_TOKEN] for w in words])\n seq_lengths = [len(w)-1 for w in tok]\n max_len = max(seq_lengths)\n pad_id = vocab[PAD_TOKEN]\n pad_id_input = [\n [vocab[w[t]] if t < seq_lengths[idx] else pad_id for t in range(max_len)]\n for idx, w in enumerate(tok)]\n \n # Replace words of the input with <unk> with p = word_dropout.\n if word_dropout > 0.:\n unk_id = vocab[UNK_TOKEN]\n word_drop = [\n [unk_id if (np.random.random() < word_dropout and t < seq_lengths[idx]) else word_ids[t] for t in range(max_len)] \n for idx, word_ids in enumerate(pad_id_input)]\n \n # The output batch is shifted by 1.\n pad_id_output = [\n [vocab[w[t+1]] if t < seq_lengths[idx] else pad_id for t in range(max_len)]\n for idx, w in enumerate(tok)]\n \n # Convert everything to PyTorch tensors.\n batch_input = torch.tensor(pad_id_input)\n batch_output = torch.tensor(pad_id_output)\n seq_mask = (batch_input != vocab[PAD_TOKEN])\n seq_length = torch.tensor(seq_lengths)\n \n # Move all tensors to the given device.\n batch_input = batch_input.to(device)\n batch_output = batch_output.to(device)\n seq_mask = seq_mask.to(device)\n seq_length = seq_length.to(device)\n \n return batch_input, batch_output, seq_mask, seq_length\n\n\ndef batch_to_words(tensors, vocab: Vocabulary):\n \"\"\"\n Converts a batch of word ids back to words.\n :param tensors: [B, T] word ids\n :param vocab: a Vocabulary object for this dataset\n :returns: an array of strings (each a word).\n \"\"\"\n words = []\n batch_size = tensors.size(0)\n for idx in range(batch_size):\n word = [vocab.word(t.item()) for t in tensors[idx,:]]\n \n # Filter out the start-of-word and padding tokens.\n word = list(filter(lambda t: t != PAD_TOKEN and t != SOW_TOKEN, word))\n \n # Remove the end-of-word token and all tokens following it.\n if EOW_TOKEN in word:\n word = word[:word.index(EOW_TOKEN)]\n \n words.append(\"\".join(word))\n return np.array(words)",
"_____no_output_____"
]
],
[
[
"In PyTorch the RNN functions expect inputs to be sorted from long words to shorter ones. Therefore we create a simple wrapper class for the DataLoader class that sorts words from long to short: ",
"_____no_output_____"
]
],
[
[
"class SortingTextDataLoader:\n \"\"\"\n A wrapper for the DataLoader class that sorts a list of words by their\n lengths in descending order.\n \"\"\"\n\n def __init__(self, dataloader):\n self.dataloader = dataloader\n self.it = iter(dataloader)\n \n def __iter__(self):\n return self\n \n def __next__(self):\n words = None\n for s in self.it:\n words = s\n break\n\n if words is None:\n self.it = iter(self.dataloader)\n raise StopIteration\n \n words = np.array(words)\n sort_keys = sorted(range(len(words)), \n key=lambda idx: len(list(words[idx])), \n reverse=True)\n sorted_words = words[sort_keys]\n return sorted_words",
"_____no_output_____"
]
],
[
[
"# Model\n\n## Deterministic language model\n\nIn language modelling, we model a word $x = \\langle x_1, \\ldots, x_n \\rangle$ of length $n = |x|$ as a sequence of categorical draws:\n\n\\begin{align}\nX_i|x_{<i} & \\sim \\text{Cat}(f(x_{<i}; \\theta)) \n& i = 1, \\ldots, n \\\\\n\\end{align}\n\nwhere we use $x_{<i}$ to denote a (possibly empty) prefix string, and thus the model makes no Markov assumption. We map from the conditioning context, the prefix $x_{<i}$, to the categorical parameters (a $v$-dimensional probability vector, where $v$ denotes the size of the vocabulary, in this case, the size of the character set) using a fixed neural network architecture whose parameters we collectively denote by $\\theta$.\n\nThis assigns the following likelihood to the word\n\\begin{align}\n P(x|\\theta) &= \\prod_{i=1}^n P(x_i|x_{<i}, \\theta) \\\\\n &= \\prod_{i=1}^n \\text{Cat}(x_i|f(x_{<i}; \\theta)) \n\\end{align}\nwhere the categorical pmf is $\\text{Cat}(k|\\pi) = \\prod_{j=1}^v \\pi_j^{[k=j]} = \\pi_k$. \n\n\nSuppose we have a dataset $\\mathcal D = \\{x^{(1)}, \\ldots, x^{(N)}\\}$ containing $N$ i.i.d. observations. Then we can use the log-likelihood function \n\\begin{align}\n\\mathcal L(\\theta|\\mathcal D) &= \\sum_{k=1}^{N} \\log P(x^{(k)}| \\theta) \\\\\n&= \\sum_{k=1}^{N} \\sum_{i=1}^{|x^{(k)}|} \\log \\text{Cat}(x^{(k)}_i|f(x^{(k)}_{<i}; \\theta))\n\\end{align}\n to estimate $\\theta$ by maximisation:\n \\begin{align}\n \\theta^\\star = \\arg\\max_{\\theta \\in \\Theta} \\mathcal L(\\theta|\\mathcal D) ~ .\n \\end{align}\n \n\nWe can use stochastic gradient-ascent to find a local optimum of $\\mathcal L(\\theta|\\mathcal D)$, which only requires a gradient estimate:\n\n\\begin{align}\n\\nabla_\\theta \\mathcal L(\\theta|\\mathcal D) &= \\sum_{k=1}^{|\\mathcal D|} \\nabla_\\theta \\log P(x^{(k)}|\\theta) \\\\ \n&= \\sum_{k=1}^{|\\mathcal D|} \\frac{1}{N} N \\nabla_\\theta \\log P(x^{(k)}| \\theta) \\\\\n&= \\mathbb E_{\\mathcal U(1/N)} \\left[ N \\nabla_\\theta \\log P(x^{(K)}| \\theta) \\right] \\\\\n&\\overset{\\text{MC}}{\\approx} \\frac{N}{M} \\sum_{m=1}^M \\nabla_\\theta \\log P(x^{(k_m)}|\\theta) \\\\\n&\\text{where }K_m \\sim \\mathcal U(1/N)\n\\end{align}\n\nThis is a Monte Carlo (MC) estimate of the gradient computed on $M$ data points selected uniformly at random from $\\mathcal D$.\n\nFor as long as $f$ remains differentiable wrt to its inputs and parameters, we can rely on automatic differentiation to obtain gradient estimates.\n\n\nAn example design for $f$ is:\n\\begin{align}\n\\mathbf x_i &= \\text{emb}(x_i; \\theta_{\\text{emb}}) \\\\\n\\mathbf h_0 &= \\mathbf 0 \\\\\n\\mathbf h_i &= \\text{rnn}(\\mathbf h_{i-1}, \\mathbf x_{i-1}; \\theta_{\\text{rnn}}) \\\\\nf(x_{<i}; \\theta) &= \\text{softmax}(\\text{dense}_v(\\mathbf h_{i}; \\theta_{\\text{out}}))\n\\end{align}\nwhere \n* $\\text{emb}$ is a fixed embedding layer with parameters $\\theta_{\\text{emb}}$;\n* $\\text{rnn}$ is a recurrent architecture with parameters $\\theta_{\\text{rnn}}$, e.g. an LSTM or GRU, and $\\mathbf h_0$ is part of the architecture's parameters;\n* $\\text{dense}_v$ is a dense layer with $v$ outputs (vocabulary size) and parameters $\\theta_{\\text{out}}$.\n\n\n\nIn what follows we show how to extend this model with a continuous latent word embedding.",
"_____no_output_____"
],
[
"## Deep generative language model\n\nWe want to model a word $x$ as a draw from the marginal of deep generative model $P(z, x|\\theta, \\alpha) = P(z|\\alpha)P(x|z, \\theta)$. \n\n\n### Generative model\n\nThe generative story is:\n\\begin{align}\n Z_k & \\sim \\text{Bernoulli}(\\alpha_k) & k=1,\\ldots, K \\\\\n X_i | z, x_{<i} &\\sim \\text{Cat}(f(z, x_{<i}; \\theta)) & i=1, \\ldots, n\n\\end{align}\nwhere $z \\in \\mathbb R^K$ and we impose a product of independent Bernoulli distributions prior. Other choices of prior can induce interesting properties in latent space, for example, the Bernoullis could be correlated, however, in this notebook, we use independent distributions. \n\n\n**About the prior parameter** The parameter of the $k$th Bernoulli distribution is the probability that the $k$th bit in $z$ is set to $1$, and therefore, if we have reasons to believe some bits are more frequent than others (for example, because we expect some bits to capture verb attributes and others to capture noun attributes, and we know nouns are more frequent than verbs) we may be able to have a good guess at $\\alpha_k$ for different $k$, otherwise, we may simply say that bits are about as likely to be on or off a priori, thus setting $\\alpha_k = 0.5$ for every $k$. In this lab, we will treat the prior parameter ($\\alpha$) as *fixed*.\n\n**Architecture** It is easy to design $f$ by a simple modification of the deterministic design shown before:\n\\begin{align}\n\\mathbf x_i &= \\text{emb}(x_i; \\theta_{\\text{emb}}) \\\\\n\\mathbf h_0 &= \\tanh(\\text{dense}(z; \\theta_{\\text{init}})) \\\\\n\\mathbf h_i &= \\text{rnn}(\\mathbf h_{i-1}, \\mathbf x_{i-1}; \\theta_{\\text{rnn}}) \\\\\nf(x_{<i}; \\theta) &= \\text{softmax}(\\text{dense}_v(\\mathbf h_{i}; \\theta_{\\text{out}}))\n\\end{align}\nwhere we just initialise the recurrent cell using $z$. Note we could also use $z$ in other places, for example, as additional input to every update of the recurrent cell $\\mathbf h_i = \\text{rnn}(\\mathbf h_{i-1}, [\\mathbf x_{i-1}, z])$. This is an architecture choice which like many others can only be judged empirically or on the basis of practical convenience.\n\n",
"_____no_output_____"
],
[
"### Parameter estimation\n\nThe marginal likelihood, necessary for parameter estimation, is now no longer tractable:\n\\begin{align}\nP(x|\\theta, \\alpha) &= \\sum_{z \\in \\{0,1\\}^K} P(z|\\alpha)P(x|z, \\theta) \\\\\n&= \\sum_{z \\in \\{0,1\\}^K} \\prod_{k=1}^K \\text{Bernoulli}(z_k|\\alpha_k)\\prod_{i=1}^n \\text{Cat}(x_i|f(z,x_{<i}; \\theta) ) \n\\end{align}\nthe intractability is clear as there is an exponential number of assignments to $z$, namely, $2^K$.\n\nWe turn to variational inference and derive a lowerbound $\\mathcal E(\\theta, \\lambda|\\mathcal D)$ on the log-likelihood function\n\n\\begin{align}\n \\mathcal E(\\theta, \\lambda|\\mathcal D) &= \\sum_{s=1}^{|\\mathcal D|} \\mathcal E_s(\\theta, \\lambda|x^{(s)}) \n\\end{align}\n\nwhich for a single datapoint $x$ is\n\\begin{align}\n \\mathcal E(\\theta, \\lambda|x) &= \\mathbb{E}_{Q(z|x, \\lambda)}\\left[\\log P(x|z, \\theta)\\right] - \\text{KL}\\left(Q(z|x, \\lambda)||P(z|\\alpha)\\right)\\\\\n\\end{align}\nwhere we have introduce an independently parameterised auxiliary distribution $Q(z|x, \\lambda)$. The distribution $Q$ which maximises this *evidence lowerbound* (ELBO) is also the distribution that minimises \n\\begin{align}\n\\text{KL}(Q(z|x, \\lambda)||P(z|x, \\theta, \\alpha)) = \\mathbb E_{Q(z|x, \\lambda)}\\left[\\log \\frac{Q(z|x, \\lambda)}{P(z|x, \\theta, \\alpha)}\\right]\n\\end{align}\n where $P(z|x, \\theta, \\alpha) = \\frac{P(x, z|\\theta, \\alpha)}{P(x|\\theta, \\alpha)}$ is our intractable true posterior. For that reason, we think of $Q(z|x, \\lambda)$ as an *approximate posterior*. \n \n The approximate posterior is an independent model of the latent variable given the data, for that reason we also call it an *inference model*. \n In this notebook, our inference model will be a product of independent Bernoulli distributions, to make sure that we cover the sample space of our latent variable. We will leave at the end of the notebook as an optional exercise to model correlations (thus achieving *structured* inference, rather than mean field inference). Such mean field (MF) approximation takes $K$ Bernoulli variational factors whose parameters we predict with a neural network:\n \n\\begin{align}\n Q(z|x, \\lambda) &= \\prod_{k=1}^K \\text{Bernoulli}(z_k|\\beta_k(x; \\lambda))\n\\end{align}\n \nNote we compute a *fixed* number, namely, $K$, of Bernoulli parameters. This can be done with a neural network that outputs $K$ values and employs a sigmoid activation for the outputs.\n \n \nFor this choice, the KL term in the ELBO is tractable:\n\n\\begin{align}\n\\text{KL}\\left(Q(z|x, \\lambda)||P(z|\\alpha)\\right) &= \\sum_{k=1}^K \\text{KL}\\left(Q(z_k|x, \\lambda)||P(z_k|\\alpha_k)\\right) \\\\\n&= \\sum_{k=1}^K \\text{KL}\\left(\\text{Bernoulli}(\\beta_k(x;\\lambda))|| \\text{Bernoulli}(\\alpha_k)\\right) \\\\\n&= \\sum_{k=1}^K \\beta_k(x;\\lambda) \\log \\frac{\\beta_k(x;\\lambda)}{\\alpha_k} + (1-\\beta_k(x;\\lambda)) \\log \\frac{1-\\beta_k(x;\\lambda)}{1-\\alpha_k}\n\\end{align}\n\n\n \nHere's an example design for our inference model:\n\n\\begin{align}\n\\mathbf x_i &= \\text{emb}(x_i; \\lambda_{\\text{emb}}) \\\\\n\\mathbf f_i &= \\text{rnn}(\\mathbf f_{i-1}, \\mathbf x_{i}; \\lambda_{\\text{fwd}}) \\\\\n\\mathbf b_i &= \\text{rnn}(\\mathbf b_{i+1}, \\mathbf x_{i}; \\lambda_{\\text{bwd}}) \\\\\n\\mathbf h &= \\text{dense}([\\mathbf f_{n}, \\mathbf b_1]; \\lambda_{\\text{hid}}) \\\\\n\\beta(x; \\lambda) &= \\text{sigmoid}(\\text{dense}_K(\\mathbf h; \\lambda_{\\text{out}}))\n\\end{align}\n\nwhere we use the $\\text{sigmoid}$ activation to make sure our probabilities are independently set between $0$ and $1$. \n \nBecause we have neural networks compute the Bernoulli variational factors for us, we call this *amortised* mean field inference.\n\n",
"_____no_output_____"
],
[
"### Gradient estimation\n\nWe have to obtain gradients of the ELBO with respect to $\\theta$ (generative model) and $\\lambda$ (inference model). Recall we will leave $\\alpha$ fixed.\n\nFor the **generative model**\n\n\\begin{align}\n\\nabla_\\theta \\mathcal E(\\theta, \\lambda|x) &=\\nabla_\\theta\\sum_{z} Q(z|x, \\lambda)\\log P(x|z,\\theta) - \\underbrace{\\nabla_\\theta \\sum_{k=1}^K \\text{KL}(Q(z_k|x, \\lambda) || P(z_k|\\alpha_k))}_{\\color{blue}{0}} \\\\\n&=\\sum_{z} Q(z|x, \\lambda)\\nabla_\\theta\\log P(x|z,\\theta) \\\\\n&= \\mathbb E_{Q(z|x, \\lambda)}\\left[\\nabla_\\theta\\log P(x|z,\\theta) \\right] \\\\\n&\\overset{\\text{MC}}{\\approx} \\frac{1}{S} \\sum_{s=1}^S \\nabla_\\theta \\log P(x|z^{(s)}, \\theta) \n\\end{align}\nwhere $z^{(s)} \\sim Q(z|x,\\lambda)$.\nNote there is no difficulty in obtaining gradient estimates precisely because the samples come from the inference model and therefore do not interfere with backpropagation for updates to $\\theta$.\n\nFor the **inference model** the story is less straightforward, and we have to use the *score function estimator* (a.k.a. REINFORCE):\n\n\\begin{align}\n\\nabla_\\lambda \\mathcal E(\\theta, \\lambda|x) &=\\nabla_\\lambda\\sum_{z} Q(z|x, \\lambda)\\log P(x|z,\\theta) - \\nabla_\\lambda \\underbrace{\\sum_{k=1}^K \\text{KL}(Q(z_k|x, \\lambda) || P(z_k|\\alpha_k))}_{ \\color{blue}{\\text{tractable} }} \\\\\n&=\\sum_{z} \\nabla_\\lambda Q(z|x, \\lambda)\\log P(x|z,\\theta) - \\sum_{k=1}^K \\nabla_\\lambda \\text{KL}(Q(z_k|x, \\lambda) || P(z_k|\\alpha_k)) \\\\\n&=\\sum_{z} \\underbrace{Q(z|x, \\lambda) \\nabla_\\lambda \\log Q(z|x, \\lambda)}_{\\nabla_\\lambda Q(z|x, \\lambda)} \\log P(x|z,\\theta) - \\sum_{k=1}^K \\nabla_\\lambda \\text{KL}(Q(z_k|x, \\lambda) || P(z_k|\\alpha_k)) \\\\\n&= \\mathbb E_{Q(z|x, \\lambda)}\\left[ \\log P(x|z,\\theta) \\nabla_\\lambda \\log Q(z|x, \\lambda) \\right] - \\sum_{k=1}^K \\nabla_\\lambda \\text{KL}(Q(z_k|x, \\lambda) || P(z_k|\\alpha_k)) \\\\\n&\\overset{\\text{MC}}{\\approx} \\left(\\frac{1}{S} \\sum_{s=1}^S \\log P(x|z^{(s)}, \\theta) \\nabla_\\lambda \\log Q(z^{(s)}|x, \\lambda) \\right) - \\sum_{k=1}^K \\nabla_\\lambda \\text{KL}(Q(z_k|x, \\lambda) || P(z_k|\\alpha_k)) \n\\end{align}\n\nwhere $z^{(s)} \\sim Q(z|x,\\lambda)$.\n\n",
"_____no_output_____"
],
[
"## Implementation\n\nLet's implement the model and the loss (negative ELBO). We work with the notion of a *surrogate loss*, that is, a computation node whose gradients wrt to parameters are equivalent to the gradients we need.\n\nFor a given sample $z \\sim Q(z|x, \\lambda)$, the following is a single-sample surrogate loss:\n\n\\begin{align}\n\\mathcal S(\\theta, \\lambda|x) = \\log P(x|z, \\theta) + \\color{red}{\\text{detach}(\\log P(x|z, \\theta) )}\\log Q(z|x, \\lambda) - \\sum_{k=1}^K \\text{KL}(Q(z_k|x, \\lambda) || P(z_k|\\alpha_k))\n\\end{align}\n\nCheck the documentation of pytorch's `detach` method.\n\nShow that it's gradients wrt $\\theta$ and $\\lambda$ are exactly what we need:\n",
"_____no_output_____"
],
[
"\\begin{align}\n\\nabla_\\theta \\mathcal S(\\theta, \\lambda|x) = \\color{red}{?}\n\\end{align}\n\n\\begin{align}\n\\nabla_\\lambda \\mathcal S(\\theta, \\lambda|x) = \\color{red}{?}\n\\end{align}",
"_____no_output_____"
],
[
"Let's now turn to the actual implementation in pytorch of the inference model as well as the generative model. \n\nHere and there we will provide helper code for you.",
"_____no_output_____"
]
],
[
[
"def bernoulli_log_probs_from_logits(logits):\n \"\"\"\n Let p be the Bernoulli parameter and q = 1 - p.\n This function is a stable computation of p and q from logit = log(p/q).\n :param logit: log (p/q)\n :return: log_p, log_q\n \"\"\"\n return - F.softplus(-logits), - F.softplus(logits)",
"_____no_output_____"
]
],
[
[
"We start with the implementation of a product of Bernoulli distributions where the parameters are *given* at construction time. That is, for some vector $b_1, \\ldots, b_K$ we have\n\\begin{equation}\n Z_k \\sim \\text{Bernoulli}(b_k)\n\\end{equation}\nand thus the joint probability of $z_1, \\ldots, z_K$ is given by $\\prod_{k=1}^K \\text{Bernoulli}(z_k|b_k)$.",
"_____no_output_____"
]
],
[
[
"class ProductOfBernoullis:\n \"\"\"\n This is class models a product of independent Bernoulli distributions.\n \n Each product of Bernoulli is defined by a D-dimensional vector of logits\n for each independent Bernoulli variable.\n \"\"\"\n \n def __init__(self, logits):\n \"\"\"\n :param p: a tensor of D Bernoulli parameters (logits) for each batch element. [B, D]\n \"\"\"\n pass\n \n def mean(self):\n \"\"\"For Bernoulli variables this is the probability of each Bernoulli being 1.\"\"\"\n return None\n \n def std(self):\n \"\"\"For Bernoulli variables this is p*(1-p) where p\n is the probability of the Bernoulli being 1\"\"\"\n return self.probs * (1.0 - self.probs)\n \n def sample(self):\n \"\"\"\n Returns a sample with the shape of the Bernoulli parameter. # [B, D]\n \"\"\"\n return None\n \n def log_prob(self, x):\n \"\"\"\n Assess the log probability mass of x.\n \n :param x: a tensor of Bernoulli samples (same shape as the Bernoulli parameter) [B, D]\n :returns: tensor of log probabilitie densities [B]\n \"\"\"\n return None\n \n \n def unstable_kl(self, other: 'Bernoulli'):\n \"\"\"\n The straightforward implementation of the KL between two Bernoullis.\n This implementation is unstable, a stable implementation is provided in\n ProductOfBernoullis.kl(self, q)\n \n :returns: a tensor of KL values with the same shape as the parameters of self.\n \"\"\"\n \n return None\n \n def kl(self, other: 'Bernoulli'):\n \"\"\"\n A stable implementation of the KL divergence between two Bernoulli variables.\n \n :returns: a tensor of KL values with the same shape as the parameters of self.\n \"\"\"\n return None",
"_____no_output_____"
]
],
[
[
"Then we should implement the inference model $Q(z | x, \\lambda)$, that is, a module that uses a neural network to map from a data point $x$ to the parameters of a product of Bernoullis.\n\nYou might want to consult the documentation of \n* `torch.nn.Embedding`\n* `torch.nn.LSTM`\n* `torch.nn.Linear`\n* and of our own `ProductOfBernoullis` distribution (see above).",
"_____no_output_____"
]
],
[
[
"class InferenceModel(nn.Module):\n\n def __init__(self, vocab_size, embedder, hidden_size,\n latent_size, pad_idx, bidirectional=False):\n \"\"\"\n Implement the layers in the inference model.\n \n :param vocab_size: size of the vocabulary of the language\n :param embedder: embedding layer\n :param hidden_size: size of recurrent cell\n :param latent_size: size K of the latent variable\n :param pad_idx: id of the -PAD- token\n :param bidirectional: whether we condition on x via a bidirectional or \n unidirectional encoder \n \"\"\"\n super().__init__() # pytorch modules should always start with this\n pass\n # Construct your NN blocks here\n # and make sure every block is an attribute of self\n # or they won't get initialised properly\n # for example, self.my_linear_layer = torch.nn.Linear(...)\n\n def forward(self, x, seq_mask, seq_len) -> ProductOfBernoullis:\n \"\"\"\n Return an inference product of Bernoullis per instance in the mini-batch\n :param x: words [B, T] as token ids\n :param seq_mask: indicates valid positions vs padding positions [B, T]\n :param seq_len: the length of the sequences [B]\n :return: a collection of B ProductOfBernoullis approximate posterior, \n each a distribution over K-dimensional bit vectors\n \"\"\"\n pass",
"_____no_output_____"
],
[
"# tests for inference model\npad_idx = vocab.char_to_idx[PAD_TOKEN]\n\ndummy_inference_model = InferenceModel(\n vocab_size=vocab.size(),\n embedder=nn.Embedding(vocab.size(), 64, padding_idx=pad_idx),\n hidden_size=128, latent_size=16, pad_idx=pad_idx, bidirectional=True\n).to(device=device)\ndummy_batch_size = 32\ndummy_dataloader = SortingTextDataLoader(DataLoader(train_dataset, batch_size=dummy_batch_size))\ndummy_words = next(dummy_dataloader)\n\nx_in, _, seq_mask, seq_len = create_batch(dummy_words, vocab, device)\n\nq_z_given_x = dummy_inference_model.forward(x_in, seq_mask, seq_len)",
"_____no_output_____"
]
],
[
[
"Then we should implement the generative latent factor model. The decoder is a sequence of correlated Categorical draws that condition on a latent factor assignment. \n\nWe will be parameterising categorical distributions, so you might want to check the documentation of `torch.distributions.categorical.Categorical`.\n",
"_____no_output_____"
]
],
[
[
"from torch.distributions import Categorical\n\nclass LatentFactorModel(nn.Module):\n \n def __init__(self, vocab_size, emb_size, hidden_size, latent_size,\n pad_idx, dropout=0.):\n \"\"\"\n :param vocab_size: size of the vocabulary of the language\n :param emb_size: dimensionality of embeddings\n :param hidden_size: dimensionality of recurrent cell\n :param latent_size: this is D the dimensionality of the latent variable z\n :param pad_idx: the id reserved to the -PAD- token\n :param dropout: a dropout rate (you can ignore this for now)\n \"\"\"\n super().__init__()\n # Construct your NN blocks here, \n # remember to assign them to attributes of self\n pass\n\n def init_hidden(self, z):\n \"\"\"\n Returns the hidden state of the LSTM initialized with a projection of a given z.\n :param z: [B, K]\n :returns: [num_layers, B, H] hidden state, [num_layers, B, H] cell state \n \"\"\"\n pass\n \n def step(self, prev_x, z, hidden):\n \"\"\"\n Performs a single LSTM step for a given previous word and hidden state.\n Returns the unnormalized log probabilities (logits) over the vocabulary \n for this time step. \n \n :param prev_x: [B, 1] id of the previous token\n :param z: [B, K] latent variable\n :param hidden: hidden ([num_layers, B, H] state, [num_layers, B, H] cell)\n :returns: [B, V] logits, ([num_layers, B, H] updated state, [num_layers, B, H] updated cell)\n \"\"\"\n pass\n \n def forward(self, x, z) -> Categorical:\n \"\"\"\n Performs an entire forward pass given a sequence of words x and a z.\n This returns a collection of [B, T] categorical distributions, each \n with support over V events.\n\n :param x: [B, T] token ids \n :param z: [B, K] a latent sample\n :returns: Categorical object with shape [B,T,V]\n \"\"\"\n hidden = self.init_hidden(z)\n outputs = []\n for t in range(x.size(1)):\n # [B, 1]\n prev_x = x[:, t].unsqueeze(-1)\n # logits: [B, V]\n logits, hidden = self.step(prev_x, z, hidden)\n outputs.append(logits)\n outputs = torch.cat(outputs, dim=1)\n return Categorical(logits=outputs)\n \n def loss(self, output_distributions, observations, pz, qz, free_nats=0., evaluation=False):\n \"\"\"\n Computes the terms in the loss (negative ELBO) given the \n output Categorical distributions, observations,\n the prior distribution p(z), and the approximate posterior distribution q(z|x).\n \n If free_nats is nonzero it will clamp the KL divergence between the posterior\n and prior to that value, preventing gradient propagation via the KL if it's\n below that value. \n \n If evaluation is set to true, the loss will be summed instead\n of averaged over the batch. \n \n Returns the (surrogate) loss, the ELBO, and the KL. \n \n :returns: \n surrogate loss (scalar),\n ELBO (scalar), \n KL (scalar)\n \"\"\"\n pass",
"_____no_output_____"
]
],
[
[
"The code below is used to assess the model and also investigate what it learned. We implemented it for you, so that you can focus on the VAE part. It's useful however to learn from this example: we do interesting things like computing perplexity and sampling novel words!",
"_____no_output_____"
],
[
"# Evaluation metrics\n\nDuring training we'd like to keep track of some evaluation metrics on the validation data in order to keep track of how our model is doing and to perform early stopping. One simple metric we can compute is the ELBO on all the validation or test data using a single sample from the approximate posterior $Q(z|x, \\lambda)$:",
"_____no_output_____"
]
],
[
[
"def eval_elbo(model, inference_model, eval_dataset, vocab, device, batch_size=128):\n \"\"\"\n Computes a single sample estimate of the ELBO on a given dataset.\n This returns both the average ELBO and the average KL (for inspection).\n \"\"\"\n dl = DataLoader(eval_dataset, batch_size=batch_size)\n sorted_dl = SortingTextDataLoader(dl)\n \n # Make sure the model is in evaluation mode (i.e. disable dropout).\n model.eval()\n \n total_ELBO = 0.\n total_KL = 0.\n num_words = 0\n \n # We don't need to compute gradients for this.\n with torch.no_grad():\n for words in sorted_dl: \n x_in, x_out, seq_mask, seq_len = create_batch(words, vocab, device)\n \n # Infer the approximate posterior and construct the prior.\n qz = inference_model(x_in, seq_mask, seq_len)\n pz = ProductOfBernoullis(torch.ones_like(qz.probs) * 0.5)\n \n # Compute the unnormalized probabilities using a single sample from the\n # approximate posterior.\n z = qz.sample()\n # Compute distributions X_i|z, x_{<i}\n px_z = model(x_in, z)\n \n # Compute the reconstruction loss and KL divergence.\n loss, ELBO, KL = model.loss(px_z, x_out, pz, qz, z,\n free_nats=0.,\n evaluation=True)\n total_ELBO += ELBO\n total_KL += KL\n num_words += x_in.size(0)\n\n # Return the average reconstruction loss and KL.\n avg_ELBO = total_ELBO / num_words\n avg_KL = total_KL / num_words\n return avg_ELBO, avg_KL",
"_____no_output_____"
],
[
"dummy_lm = LatentFactorModel(\n vocab.size(), emb_size=64, hidden_size=128, \n latent_size=16, pad_idx=pad_idx).to(device=device)\n\n!head -n 128 {val_file} > ./dummy_dataset\ndummy_data = TextDataset('./dummy_dataset')\ndummy_ELBO, dummy_kl = eval_elbo(dummy_lm, dummy_inference_model,\n dummy_data, vocab, device)\nprint(dummy_ELBO, dummy_kl)\nassert dummy_kl.item() > 0",
"tensor(-37.6747, device='cuda:0') tensor(0.5302, device='cuda:0')\n"
]
],
[
[
"\nA common metric to evaluate language models is the perplexity per word. The perplexity per word for a dataset is defined as:\n\n\\begin{align}\n \\text{ppl}(\\mathcal{D}|\\theta, \\lambda) = \\exp\\left(-\\frac{1}{\\sum_{k=1}^{|\\mathcal D|} n^{(k)}} \\sum_{k=1}^{|\\mathcal{D}|} \\log P(x^{(k)}|\\theta, \\lambda)\\right) \n\\end{align}\n\nwhere $n^{(k)} = |x^{(k)}|$ is the number of tokens in a word and $P(x^{(k)}|\\theta, \\lambda)$ is the probability that our model assigns to the datapoint $x^{(k)}$. In order to compute $\\log P(x|\\theta, \\lambda)$ for our model we need to evaluate the marginal:\n\n\\begin{align}\n P(x|\\theta, \\lambda) = \\sum_{z \\in \\{0, 1\\}^K} P(x|z,\\theta) P(z|\\alpha)\n\\end{align}\n\nAs this is summation cannot be computed in a reasonable amount of time (due to exponential complexity), we have two options: we can use the earlier derived lower-bound on the log-likelihood, which will give us an upper-bound on the perplexity, or we can make an importance sampling estimate using our approximate posterior distribution. The importance sampling (IS) estimate can be done as:\n\n\\begin{align}\n\\hat P(x|\\theta, \\lambda) &\\overset{\\text{IS}}{\\approx} \\frac{1}{S} \\sum_{s=1}^{S} \\frac{P(z^{(s)}|\\alpha)P(x|z^{(s)}, \\theta)}{Q(z^{(s)}|x)} & \\text{where }z^{(s)} \\sim Q(z|x)\n\\end{align}\n\nwhere $S$ is the number of samples.\n\nThen our perplexity becomes:\n\\begin{align}\n &\\frac{1}{\\sum_{k=1}^{|\\mathcal D|} n^{(k)}} \\sum_{k=1}^{|\\mathcal D|} \\log P(x^{(k)}|\\theta) \\\\\n &\\approx \\frac{1}{\\sum_{k=1}^{|\\mathcal D|} n^{(k)}} \\sum_{k=1}^{|\\mathcal D|} \\log \\frac{1}{S} \\sum_{s=1}^{S} \\frac{P(z^{(s)}|\\alpha)P(x^{(k)}|z^{(s)}, \\theta)}{Q(z^{(s)}|x^{(k)})} \\\\\n\\end{align}\n\nWe define the function `eval_perplexity` below that implements this importance sampling estimate:",
"_____no_output_____"
]
],
[
[
"def eval_perplexity(model, inference_model, eval_dataset, vocab, device, \n n_samples, batch_size=128):\n \"\"\"\n Estimates the per-word perplexity using importance sampling with the\n given number of samples.\n \"\"\"\n \n dl = DataLoader(eval_dataset, batch_size=batch_size)\n sorted_dl = SortingTextDataLoader(dl)\n \n # Make sure the model is in evaluation mode (i.e. disable dropout).\n model.eval()\n \n log_px = 0.\n num_predictions = 0\n num_words = 0\n \n # We don't need to compute gradients for this.\n with torch.no_grad():\n for words in sorted_dl:\n x_in, x_out, seq_mask, seq_len = create_batch(words, vocab, device)\n \n # Infer the approximate posterior and construct the prior.\n qz = inference_model(x_in, seq_mask, seq_len)\n pz = ProductOfBernoullis(torch.ones_like(qz.probs) * 0.5) # TODO different prior\n\n # Create an array to hold all samples for this batch.\n batch_size = x_in.size(0)\n log_px_samples = torch.zeros(n_samples, batch_size)\n \n # Sample log P(x) n_samples times.\n for s in range(n_samples):\n \n # Sample a z^s from the posterior.\n z = qz.sample()\n \n # Compute log P(x^k|z^s)\n px_z = model(x_in, z)\n # [B, T]\n cond_log_prob = px_z.log_prob(x_out) \n cond_log_prob = torch.where(seq_mask, cond_log_prob, torch.zeros_like(cond_log_prob))\n # [B]\n cond_log_prob = cond_log_prob.sum(-1)\n \n # Compute log p(z^s) and log q(z^s|x^k)\n prior_log_prob = pz.log_prob(z) # B\n posterior_log_prob = qz.log_prob(z) # B\n \n # Store the sample for log P(x^k) importance weighted with p(z^s)/q(z^s|x^k).\n log_px_sample = cond_log_prob + prior_log_prob - posterior_log_prob\n log_px_samples[s] = log_px_sample\n \n # Average over the number of samples and count the number of predictions made this batch.\n log_px_batch = torch.logsumexp(log_px_samples, dim=0) - \\\n torch.log(torch.Tensor([n_samples]))\n log_px += log_px_batch.sum()\n num_predictions += seq_len.sum()\n num_words += seq_len.size(0)\n\n # Compute and return the perplexity per word.\n perplexity = torch.exp(-log_px / num_predictions)\n NLL = -log_px / num_words\n return perplexity, NLL",
"_____no_output_____"
]
],
[
[
"Lastly, we want to occasionally qualitatively see the performance of the model during training, by letting it reconstruct a given word from the latent space. This gives us an idea of whether the model is using the latent space to encode some semantics about the data. For this we use a deterministic greedy decoding algorithm, that chooses the word with maximum probability at every time step, and feeds that word into the next time step.",
"_____no_output_____"
]
],
[
[
"def greedy_decode(model, z, vocab, max_len=50):\n \"\"\"\n Greedily decodes a word from a given z, by picking the word with\n maximum probability at each time step.\n \"\"\"\n \n # Disable dropout.\n model.eval()\n \n # Don't compute gradients.\n with torch.no_grad():\n batch_size = z.size(0)\n \n # We feed the model the start-of-word symbol at the first time step.\n prev_x = torch.ones(batch_size, 1, dtype=torch.long).fill_(vocab[SOW_TOKEN]).to(z.device)\n \n # Initialize the hidden state from z.\n hidden = model.init_hidden(z)\n\n predictions = [] \n for t in range(max_len):\n logits, hidden = model.step(prev_x, z, hidden)\n \n # Choose the argmax of the unnnormalized probabilities as the\n # prediction for this time step.\n prediction = torch.argmax(logits, dim=-1)\n predictions.append(prediction)\n \n prev_x = prediction.view(batch_size, 1)\n \n return torch.cat(predictions, dim=1)",
"_____no_output_____"
]
],
[
[
"# Training\n\nNow it's time to train the model. We use early stopping on the validation perplexity for model selection.",
"_____no_output_____"
]
],
[
[
"# Define the model hyperparameters.\nemb_size = 256\nhidden_size = 256 \nlatent_size = 16\nbidirectional_encoder = True\nfree_nats = 0 # 5.\nannealing_steps = 0 # 11400\ndropout = 0.6\nword_dropout = 0 # 0.75\nbatch_size = 64\nlearning_rate = 0.001\nnum_epochs = 20\nn_importance_samples = 3 # 50\n\n# Create the training data loader.\ndl = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\nsorted_dl = SortingTextDataLoader(dl)\n\n# Create the generative model.\nmodel = LatentFactorModel(vocab_size=vocab.size(), \n emb_size=emb_size, \n hidden_size=hidden_size, \n latent_size=latent_size, \n pad_idx=vocab[PAD_TOKEN],\n dropout=dropout)\nmodel = model.to(device)\n\n# Create the inference model.\ninference_model = InferenceModel(vocab_size=vocab.size(),\n embedder=model.embedder,\n hidden_size=hidden_size,\n latent_size=latent_size,\n pad_idx=vocab[PAD_TOKEN],\n bidirectional=bidirectional_encoder)\ninference_model = inference_model.to(device)\n\n# Create the optimizer.\noptimizer = optim.Adam(itertools.chain(model.parameters(), \n inference_model.parameters()), \n lr=learning_rate)\n\n# Save the best model (early stopping).\nbest_model = \"./best_model.pt\"\nbest_val_ppl = float(\"inf\")\nbest_epoch = 0\n\n# Keep track of some statistics to plot later.\ntrain_ELBOs = []\ntrain_KLs = []\nval_ELBOs = []\nval_KLs = []\nval_perplexities = []\nval_NLLs = []\n\nstep = 0\ntraining_ELBO = 0.\ntraining_KL = 0.\nnum_batches = 0\nfor epoch_num in range(1, num_epochs+1): \n for words in sorted_dl:\n\n # Make sure the model is in training mode (for dropout).\n model.train()\n\n # Transform the words to input, output, seq_len, seq_mask batches.\n x_in, x_out, seq_mask, seq_len = create_batch(words, vocab, device,\n word_dropout=word_dropout)\n\n # Compute the multiplier for the KL term if we do annealing.\n if annealing_steps > 0:\n KL_weight = min(1., (1.0 / annealing_steps) * step)\n else:\n KL_weight = 1.\n \n # Do a forward pass through the model and compute the training loss. We use\n # a reparameterized sample from the approximate posterior during training.\n qz = inference_model(x_in, seq_mask, seq_len)\n pz = ProductOfBernoullis(torch.ones_like(qz.probs) * 0.5)\n z = qz.sample()\n px_z = model(x_in, z)\n loss, ELBO, KL = model.loss(px_z, x_out, pz, qz, z, free_nats=free_nats) \n\n # Backpropagate and update the model weights.\n loss.backward()\n optimizer.step()\n optimizer.zero_grad()\n\n # Update some statistics to track for the training loss.\n training_ELBO += ELBO\n training_KL += KL\n num_batches += 1\n \n # Every 100 steps we evaluate the model and report progress.\n if step % 100 == 0:\n val_ELBO, val_KL = eval_elbo(model, inference_model, val_dataset, vocab, device) \n print(\"(%d) step %d: training ELBO (KL) = %.2f (%.2f) --\"\n \" KL weight = %.2f --\"\n \" validation ELBO (KL) = %.2f (%.2f)\" % \n (epoch_num, step, training_ELBO/num_batches, \n training_KL/num_batches, KL_weight, val_ELBO, val_KL))\n \n # Update some statistics for plotting later.\n train_ELBOs.append((step, (training_ELBO/num_batches).item()))\n train_KLs.append((step, (training_KL/num_batches).item()))\n val_ELBOs.append((step, val_ELBO.item()))\n val_KLs.append((step, val_KL.item()))\n \n # Reset the training statistics.\n training_ELBO = 0.\n training_KL = 0.\n num_batches = 0\n \n step += 1\n\n # After an epoch we'll compute validation perplexity and save the model\n # for early stopping if it's better than previous models.\n print(\"Finished epoch %d\" % (epoch_num))\n val_perplexity, val_NLL = eval_perplexity(model, inference_model, val_dataset, vocab, device, \n n_importance_samples)\n val_ELBO, val_KL = eval_elbo(model, inference_model, val_dataset, vocab, device) \n \n # Keep track of the validation perplexities / NLL.\n val_perplexities.append((epoch_num, val_perplexity.item()))\n val_NLLs.append((epoch_num, val_NLL.item()))\n \n # If validation perplexity is better, store this model for early stopping.\n if val_perplexity < best_val_ppl:\n best_val_ppl = val_perplexity\n best_epoch = epoch_num\n torch.save(model.state_dict(), best_model)\n \n # Print epoch statistics.\n print(\"Evaluation epoch %d:\\n\"\n \" - validation perplexity: %.2f\\n\"\n \" - validation NLL: %.2f\\n\"\n \" - validation ELBO (KL) = %.2f (%.2f)\"\n % (epoch_num, val_perplexity, val_NLL, val_ELBO, val_KL))\n\n # Also show some qualitative results by reconstructing a word from the\n # validation data. Use the mean of the approximate posterior and greedy\n # decoding.\n random_word = val_dataset[np.random.choice(len(val_dataset))]\n x_in, _, seq_mask, seq_len = create_batch([random_word], vocab, device)\n qz = inference_model(x_in, seq_mask, seq_len)\n z = qz.mean()\n reconstruction = greedy_decode(model, z, vocab)\n reconstruction = batch_to_words(reconstruction, vocab)[0]\n print(\"-- Original word: \\\"%s\\\"\" % random_word)\n print(\"-- Model reconstruction: \\\"%s\\\"\" % reconstruction)",
"(1) step 0: training ELBO (KL) = -39.02 (0.43) -- KL weight = 1.00 -- validation ELBO (KL) = -38.29 (0.43)\n(1) step 100: training ELBO (KL) = -27.68 (1.20) -- KL weight = 1.00 -- validation ELBO (KL) = -23.76 (1.28)\nFinished epoch 1\nEvaluation epoch 1:\n - validation perplexity: 7.88\n - validation NLL: 21.97\n - validation ELBO (KL) = -22.52 (1.25)\n-- Original word: \"interpretarían\"\n-- Model reconstruction: \"acontaren\"\n(2) step 200: training ELBO (KL) = -24.03 (1.33) -- KL weight = 1.00 -- validation ELBO (KL) = -22.47 (1.23)\n(2) step 300: training ELBO (KL) = -23.19 (1.33) -- KL weight = 1.00 -- validation ELBO (KL) = -22.19 (1.47)\nFinished epoch 2\nEvaluation epoch 2:\n - validation perplexity: 7.41\n - validation NLL: 21.32\n - validation ELBO (KL) = -21.99 (1.57)\n-- Original word: \"subtítulos\"\n-- Model reconstruction: \"acarrarían\"\n(3) step 400: training ELBO (KL) = -23.07 (1.66) -- KL weight = 1.00 -- validation ELBO (KL) = -22.02 (1.65)\n(3) step 500: training ELBO (KL) = -23.00 (1.85) -- KL weight = 1.00 -- validation ELBO (KL) = -22.06 (1.91)\nFinished epoch 3\nEvaluation epoch 3:\n - validation perplexity: 7.34\n - validation NLL: 21.22\n - validation ELBO (KL) = -22.09 (2.12)\n-- Original word: \"antojó\"\n-- Model reconstruction: \"acontaran\"\n(4) step 600: training ELBO (KL) = -22.87 (1.95) -- KL weight = 1.00 -- validation ELBO (KL) = -22.17 (2.22)\n(4) step 700: training ELBO (KL) = -23.29 (2.55) -- KL weight = 1.00 -- validation ELBO (KL) = -22.70 (2.85)\nFinished epoch 4\nEvaluation epoch 4:\n - validation perplexity: 7.77\n - validation NLL: 21.83\n - validation ELBO (KL) = -22.74 (3.02)\n-- Original word: \"cosquillearé\"\n-- Model reconstruction: \"acontaran\"\n(5) step 800: training ELBO (KL) = -23.54 (2.97) -- KL weight = 1.00 -- validation ELBO (KL) = -22.73 (3.01)\n(5) step 900: training ELBO (KL) = -23.41 (2.98) -- KL weight = 1.00 -- validation ELBO (KL) = -22.54 (2.93)\nFinished epoch 5\nEvaluation epoch 5:\n - validation perplexity: 7.69\n - validation NLL: 21.71\n - validation ELBO (KL) = -22.73 (3.19)\n-- Original word: \"chutases\"\n-- Model reconstruction: \"acalaran\"\n(6) step 1000: training ELBO (KL) = -23.44 (3.05) -- KL weight = 1.00 -- validation ELBO (KL) = -22.70 (3.17)\n(6) step 1100: training ELBO (KL) = -23.34 (3.12) -- KL weight = 1.00 -- validation ELBO (KL) = -22.49 (3.04)\nFinished epoch 6\nEvaluation epoch 6:\n - validation perplexity: 7.44\n - validation NLL: 21.37\n - validation ELBO (KL) = -22.37 (3.00)\n-- Original word: \"diversificaciones\"\n-- Model reconstruction: \"acarraría\"\n(7) step 1200: training ELBO (KL) = -23.31 (3.03) -- KL weight = 1.00 -- validation ELBO (KL) = -22.49 (3.12)\n(7) step 1300: training ELBO (KL) = -23.24 (3.18) -- KL weight = 1.00 -- validation ELBO (KL) = -22.34 (3.03)\nFinished epoch 7\nEvaluation epoch 7:\n - validation perplexity: 7.37\n - validation NLL: 21.27\n - validation ELBO (KL) = -22.33 (3.08)\n-- Original word: \"entrelazado\"\n-- Model reconstruction: \"acontaran\"\n(8) step 1400: training ELBO (KL) = -23.08 (3.04) -- KL weight = 1.00 -- validation ELBO (KL) = -22.40 (3.16)\n(8) step 1500: training ELBO (KL) = -23.23 (3.27) -- KL weight = 1.00 -- validation ELBO (KL) = -22.68 (3.49)\nFinished epoch 8\nEvaluation epoch 8:\n - validation perplexity: 7.65\n - validation NLL: 21.66\n - validation ELBO (KL) = -22.78 (3.63)\n-- Original word: \"comulgaríamos\"\n-- Model reconstruction: \"abarraría\"\n(9) step 1600: training ELBO (KL) = -23.46 (3.54) -- KL weight = 1.00 -- validation ELBO (KL) = -22.72 (3.58)\n(9) step 1700: training ELBO (KL) = -23.47 (3.69) -- KL weight = 1.00 -- validation ELBO (KL) = -22.88 (3.83)\nFinished epoch 9\nEvaluation epoch 9:\n - validation perplexity: 7.98\n - validation NLL: 22.11\n - validation ELBO (KL) = -23.19 (4.19)\n-- Original word: \"coleccionarás\"\n-- Model reconstruction: \"acontaran\"\n(10) step 1800: training ELBO (KL) = -23.82 (4.08) -- KL weight = 1.00 -- validation ELBO (KL) = -23.18 (4.15)\n(10) step 1900: training ELBO (KL) = -23.79 (4.08) -- KL weight = 1.00 -- validation ELBO (KL) = -23.11 (4.15)\nFinished epoch 10\nEvaluation epoch 10:\n - validation perplexity: 7.87\n - validation NLL: 21.96\n - validation ELBO (KL) = -23.06 (4.13)\n-- Original word: \"conmemoraran\"\n-- Model reconstruction: \"acarraría\"\n(11) step 2000: training ELBO (KL) = -23.79 (4.17) -- KL weight = 1.00 -- validation ELBO (KL) = -23.03 (4.10)\n(11) step 2100: training ELBO (KL) = -23.59 (3.99) -- KL weight = 1.00 -- validation ELBO (KL) = -22.82 (3.94)\nFinished epoch 11\nEvaluation epoch 11:\n - validation perplexity: 7.71\n - validation NLL: 21.74\n - validation ELBO (KL) = -22.98 (4.14)\n-- Original word: \"esculpieren\"\n-- Model reconstruction: \"acontaran\"\n(12) step 2200: training ELBO (KL) = -23.73 (4.10) -- KL weight = 1.00 -- validation ELBO (KL) = -22.90 (4.07)\n(12) step 2300: training ELBO (KL) = -23.64 (4.15) -- KL weight = 1.00 -- validation ELBO (KL) = -22.97 (4.22)\nFinished epoch 12\nEvaluation epoch 12:\n - validation perplexity: 7.60\n - validation NLL: 21.59\n - validation ELBO (KL) = -22.87 (4.16)\n-- Original word: \"cansándose\"\n-- Model reconstruction: \"acontrastaría\"\n(13) step 2400: training ELBO (KL) = -23.68 (4.25) -- KL weight = 1.00 -- validation ELBO (KL) = -23.02 (4.29)\n(13) step 2500: training ELBO (KL) = -23.56 (4.16) -- KL weight = 1.00 -- validation ELBO (KL) = -22.87 (4.16)\nFinished epoch 13\nEvaluation epoch 13:\n - validation perplexity: 7.78\n - validation NLL: 21.84\n - validation ELBO (KL) = -22.99 (4.33)\n-- Original word: \"desmoldasen\"\n-- Model reconstruction: \"acontermaría\"\n(14) step 2600: training ELBO (KL) = -23.61 (4.29) -- KL weight = 1.00 -- validation ELBO (KL) = -23.00 (4.37)\n(14) step 2700: training ELBO (KL) = -23.76 (4.42) -- KL weight = 1.00 -- validation ELBO (KL) = -23.24 (4.63)\nFinished epoch 14\nEvaluation epoch 14:\n - validation perplexity: 7.79\n - validation NLL: 21.85\n - validation ELBO (KL) = -23.09 (4.50)\n-- Original word: \"homenajearemos\"\n-- Model reconstruction: \"aconterraría\"\n(15) step 2800: training ELBO (KL) = -23.89 (4.59) -- KL weight = 1.00 -- validation ELBO (KL) = -23.20 (4.63)\n(15) step 2900: training ELBO (KL) = -23.97 (4.77) -- KL weight = 1.00 -- validation ELBO (KL) = -23.48 (4.97)\nFinished epoch 15\nEvaluation epoch 15:\n - validation perplexity: 7.99\n - validation NLL: 22.12\n - validation ELBO (KL) = -23.23 (4.75)\n-- Original word: \"pisotearan\"\n-- Model reconstruction: \"acontaran\"\n(16) step 3000: training ELBO (KL) = -23.90 (4.76) -- KL weight = 1.00 -- validation ELBO (KL) = -23.19 (4.70)\n(16) step 3100: training ELBO (KL) = -24.00 (4.88) -- KL weight = 1.00 -- validation ELBO (KL) = -23.60 (5.16)\nFinished epoch 16\nEvaluation epoch 16:\n - validation perplexity: 8.32\n - validation NLL: 22.56\n - validation ELBO (KL) = -23.78 (5.34)\n-- Original word: \"coexistid\"\n-- Model reconstruction: \"acondiciaren\"\n(17) step 3200: training ELBO (KL) = -24.46 (5.36) -- KL weight = 1.00 -- validation ELBO (KL) = -24.00 (5.60)\n(17) step 3300: training ELBO (KL) = -24.72 (5.64) -- KL weight = 1.00 -- validation ELBO (KL) = -23.92 (5.55)\nFinished epoch 17\nEvaluation epoch 17:\n - validation perplexity: 8.33\n - validation NLL: 22.57\n - validation ELBO (KL) = -23.87 (5.53)\n-- Original word: \"ensamblamos\"\n-- Model reconstruction: \"aconderaría\"\n(18) step 3400: training ELBO (KL) = -24.50 (5.45) -- KL weight = 1.00 -- validation ELBO (KL) = -23.74 (5.41)\n(18) step 3500: training ELBO (KL) = -23.51 (4.53) -- KL weight = 1.00 -- validation ELBO (KL) = -23.71 (5.42)\nFinished epoch 18\nEvaluation epoch 18:\n - validation perplexity: 8.29\n - validation NLL: 22.52\n - validation ELBO (KL) = -23.95 (5.68)\n-- Original word: \"caro\"\n-- Model reconstruction: \"aconternaría\"\n(19) step 3600: training ELBO (KL) = -24.57 (5.59) -- KL weight = 1.00 -- validation ELBO (KL) = -23.96 (5.73)\n(19) step 3700: training ELBO (KL) = -24.55 (5.68) -- KL weight = 1.00 -- validation ELBO (KL) = -23.59 (5.36)\nFinished epoch 19\nEvaluation epoch 19:\n - validation perplexity: 8.22\n - validation NLL: 22.43\n - validation ELBO (KL) = -23.70 (5.50)\n-- Original word: \"captáremos\"\n-- Model reconstruction: \"aconderaría\"\n(20) step 3800: training ELBO (KL) = -24.24 (5.44) -- KL weight = 1.00 -- validation ELBO (KL) = -23.66 (5.45)\n(20) step 3900: training ELBO (KL) = -24.25 (5.42) -- KL weight = 1.00 -- validation ELBO (KL) = -23.49 (5.34)\nFinished epoch 20\nEvaluation epoch 20:\n - validation perplexity: 8.11\n - validation NLL: 22.28\n - validation ELBO (KL) = -23.60 (5.46)\n-- Original word: \"endeudado\"\n-- Model reconstruction: \"acondiciaría\"\n"
]
],
[
[
"# Let's plot the training and validation statistics:",
"_____no_output_____"
]
],
[
[
"steps, training_ELBO = list(zip(*train_ELBOs))\n_, training_KL = list(zip(*train_KLs))\n_, val_ELBO = list(zip(*val_ELBOs))\n_, val_KL = list(zip(*val_KLs))\nepochs, val_ppl = list(zip(*val_perplexities))\n_, val_NLL = list(zip(*val_NLLs))\n\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 5))\n\n# Plot training ELBO and KL\nax1.set_title(\"Training ELBO\")\nax1.plot(steps, training_ELBO, \"-o\")\nax2.set_title(\"Training KL\")\nax2.plot(steps, training_KL, \"-o\")\nplt.show()\n\n# Plot validation ELBO and KL\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 5))\nax1.set_title(\"Validation ELBO\")\nax1.plot(steps, val_ELBO, \"-o\", color=\"orange\")\nax2.set_title(\"Validation KL\")\nax2.plot(steps, val_KL, \"-o\", color=\"orange\")\nplt.show()\n\n# Plot validation perplexities.\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 5))\nax1.set_title(\"Validation perplexity\")\nax1.plot(epochs, val_ppl, \"-o\", color=\"orange\")\nax2.set_title(\"Validation NLL\")\nax2.plot(epochs, val_NLL, \"-o\", color=\"orange\")\nplt.show()\nprint()",
"_____no_output_____"
]
],
[
[
"Let's load the best model according to validation perplexity and compute its perplexity on the test data:",
"_____no_output_____"
]
],
[
[
"# Load the best model from disk.\nmodel = LatentFactorModel(vocab_size=vocab.size(), \n emb_size=emb_size, \n hidden_size=hidden_size, \n latent_size=latent_size, \n pad_idx=vocab[PAD_TOKEN],\n dropout=dropout)\nmodel.load_state_dict(torch.load(best_model))\nmodel = model.to(device)\n\n# Compute test perplexity and ELBO.\ntest_perplexity, test_NLL = eval_perplexity(model, inference_model, test_dataset, vocab, \n device, n_importance_samples)\ntest_ELBO, test_KL = eval_elbo(model, inference_model, test_dataset, vocab, device)\nprint(\"test ELBO (KL) = %.2f (%.2f) -- test perplexity = %.2f -- test NLL = %.2f\" % \n (test_ELBO, test_KL, test_perplexity, test_NLL))",
"test ELBO (KL) = -25.34 (5.46) -- test perplexity = 9.56 -- test NLL = 24.05\n"
]
],
[
[
"# Qualitative analysis\n\nLet's have a look at what how our trained model interacts with the learned latent space. First let's greedily decode some samples from the prior to assess the diversity of the model:",
"_____no_output_____"
]
],
[
[
"# Generate 10 samples from the standard normal prior.\nnum_prior_samples = 10\npz = ProductOfBernoullis(torch.ones(num_prior_samples, latent_size) * 0.5)\nz = pz.sample()\nz = z.to(device)\n\n# Use the greedy decoding algorithm to generate words.\npredictions = greedy_decode(model, z, vocab)\npredictions = batch_to_words(predictions, vocab)\nfor num, prediction in enumerate(predictions):\n print(\"%d: %s\" % (num+1, prediction))",
"_____no_output_____"
]
],
[
[
"Let's now have a look how good the model is at reconstructing words from the test dataset using the approximate posterior mean and a couple of samples:",
"_____no_output_____"
]
],
[
[
"# Pick a random test word.\ntest_word = test_dataset[np.random.choice(len(test_dataset))]\n\n# Infer q(z|x).\nx_in, _, seq_mask, seq_len = create_batch([test_word], vocab, device)\nqz = inference_model(x_in, seq_mask, seq_len)\n\n# Decode using the mean.\nz_mean = qz.mean()\nmean_reconstruction = greedy_decode(model, z_mean, vocab)\nmean_reconstruction = batch_to_words(mean_reconstruction, vocab)[0]\n\nprint(\"Original: \\\"%s\\\"\" % test_word)\nprint(\"Posterior mean reconstruction: \\\"%s\\\"\" % mean_reconstruction)\n\n# Decode a couple of samples from the approximate posterior.\nfor s in range(3):\n z = qz.sample()\n sample_reconstruction = greedy_decode(model, z, vocab)\n sample_reconstruction = batch_to_words(sample_reconstruction, vocab)[0]\n print(\"Posterior sample reconstruction (%d): \\\"%s\\\"\" % (s+1, sample_reconstruction))",
"_____no_output_____"
]
],
[
[
"We can also qualitatively assess the smoothness of the learned latent space by interpolating between two words in the test set:",
"_____no_output_____"
]
],
[
[
"# Pick a random test word.\ntest_word_1 = test_dataset[np.random.choice(len(test_dataset))]\n\n# Infer q(z|x).\nx_in, _, seq_mask, seq_len = create_batch([test_word_1], vocab, device)\nqz = inference_model(x_in, seq_mask, seq_len)\nqz_1 = qz.mean()\n\n# Pick a random second test word.\ntest_word_2 = test_dataset[np.random.choice(len(test_dataset))]\n\n# Infer q(z|x) again.\nx_in, _, seq_mask, seq_len = create_batch([test_word_2], vocab, device)\nqz = inference_model(x_in, seq_mask, seq_len)\nqz_2 = qz.mean()\n\n# Now interpolate between the two means and generate words between those.\nnum_words = 5\nprint(\"Word 1: \\\"%s\\\"\" % test_word_1)\nfor alpha in np.linspace(start=0., stop=1., num=num_words):\n z = (1-alpha) * qz_1 + alpha * qz_2\n reconstruction = greedy_decode(model, z, vocab)\n reconstruction = batch_to_words(reconstruction, vocab)[0]\n print(\"(1-%.2f) * qz1.mean + %.2f qz2.mean: \\\"%s\\\"\" % (alpha, alpha, reconstruction))\nprint(\"Word 2: \\\"%s\\\"\" % test_word_2)",
"_____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",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
d080dde6157c4377e82d1f41416e5835a0f1210a | 5,370 | ipynb | Jupyter Notebook | bus/bus-checkpoint.ipynb | oscarledesma16/bcn-feb-2019-prework | a85fec78de225f4c522cfae745292847b8ffe04e | [
"Unlicense"
] | null | null | null | bus/bus-checkpoint.ipynb | oscarledesma16/bcn-feb-2019-prework | a85fec78de225f4c522cfae745292847b8ffe04e | [
"Unlicense"
] | null | null | null | bus/bus-checkpoint.ipynb | oscarledesma16/bcn-feb-2019-prework | a85fec78de225f4c522cfae745292847b8ffe04e | [
"Unlicense"
] | null | null | null | 25.817308 | 299 | 0.511359 | [
[
[
"<img src=\"https://bit.ly/2VnXWr2\" width=\"100\" align=\"left\">",
"_____no_output_____"
],
[
"# Bus\n\nThis bus has a passenger entry and exit control system to monitor the number of occupants it carries and thus detect when there are too many.\n\nAt each stop, the entry and exit of passengers is represented by a tuple consisting of two integer numbers.\n```\nbus_stop = (in, out)\n```\nThe succession of stops is represented by a list of these tuples.\n```\nstops = [(in1, out1), (in2, out2), (in3, out3), (in4, out4)]\n```\n\n## Tools\nYou don't necessarily need to use all the tools. Maybe you opt to use some of them or completely different ones, they are given to help you shape the exercise. Programming exercises can be solved in many different ways.\n* Data structures: **lists, tuples**\n* Loop: **while/for loops**\n* Functions: **min, max, len**\n\n## Tasks",
"_____no_output_____"
]
],
[
[
"# Variables\nstops = [(10, 0), (4, 1), (3, 5), (3, 4), (5, 1), (1, 5), (5, 8), (4, 6), (2, 3)]",
"_____no_output_____"
]
],
[
[
"#### 1. Calculate the number of stops.",
"_____no_output_____"
]
],
[
[
"stops = [(10, 0), (4, 1), (3, 5), (3, 4), (5, 1), (1, 5), (5, 8), (4, 6), (2, 3)]\n\nprint(len(stops))",
"9\n"
]
],
[
[
"#### 2. Assign to a variable a list whose elements are the number of passengers at each stop (in-out).\nEach item depends on the previous item in the list + in - out.",
"_____no_output_____"
]
],
[
[
"stops = [(10, 0), (4, 1), (3, 5), (3, 4), (5, 1), (1, 5), (5, 8), (4, 6), (2, 3)]\n\nfor_stop = [(stops[0][0]) - (stops[0][1]), (stops[1][0]) - (stops[1][1]), (stops[2][0]) - (stops[2][1]), (stops[3][0]) - (stops[3][1]), (stops[4][0]) - (stops[4][1]), (stops[5][0]) - (stops[5][1]), (stops[6][0]) - (stops[6][1]), (stops[7][0]) - (stops[7][1]), (stops[8][0]) - (stops[8][1])]\n\npassengers = 0\n\nfor i in (for_stop):\n passengers += i\n print(\"Total passengers for stop \", passengers)\n",
"Total passengers for stop 10\nTotal passengers for stop 13\nTotal passengers for stop 11\nTotal passengers for stop 10\nTotal passengers for stop 14\nTotal passengers for stop 10\nTotal passengers for stop 7\nTotal passengers for stop 5\nTotal passengers for stop 4\n"
]
],
[
[
"#### 3. Find the maximum occupation of the bus.",
"_____no_output_____"
]
],
[
[
"from itertools import accumulate \n\naccumulate_for_stops = (list(accumulate(for_stop)))\n\nprint(accumulate_for_stops)\nprint(\"Maximum occupation of the bus is:\", (max(accumulate_for_stops)))",
"[10, 13, 11, 10, 14, 10, 7, 5, 4]\nMaximum occupation of the bus is: 14\n"
]
],
[
[
"#### 4. Calculate the average occupation. And the standard deviation.",
"_____no_output_____"
]
],
[
[
"average_occupation = sum(accumulate_for_stops)/len(accumulate_for_stops)\n\nprint(\"Average occupation:\", average_occupation)\n\nfrom math import sqrt\n\nsuma = 0\n\nfor i in for_stop:\n suma += (i - average_occupation) ** 2\n \nradicando = suma / (len(for_stop) - 1)\n \nstandard_deviation = sqrt(radicando)\n \nprint(\"Standard deviation:\", standard_deviation)",
"Average occupation: 9.333333333333334\nStandard deviation: 10.424330514074594\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
d080ed0aae9ede3d3e83762121d4b5fde82b2c19 | 106,324 | ipynb | Jupyter Notebook | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning | 07ef1587e426e7557198e857c355dcab7ba98ab2 | [
"MIT"
] | null | null | null | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning | 07ef1587e426e7557198e857c355dcab7ba98ab2 | [
"MIT"
] | null | null | null | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning | 07ef1587e426e7557198e857c355dcab7ba98ab2 | [
"MIT"
] | null | null | null | 46.127549 | 13,016 | 0.643937 | [
[
[
"# Lambda School Data Science - Recurrent Neural Networks and LSTM\n\n> \"Yesterday's just a memory - tomorrow is never what it's supposed to be.\" -- Bob Dylan",
"_____no_output_____"
],
[
"# Lecture\n\nWish you could save [Time In A Bottle](https://www.youtube.com/watch?v=AnWWj6xOleY)? With statistics you can do the next best thing - understand how data varies over time (or any sequential order), and use the order/time dimension predictively.\n\nA sequence is just any enumerated collection - order counts, and repetition is allowed. Python lists are a good elemental example - `[1, 2, 2, -1]` is a valid list, and is different from `[1, 2, -1, 2]`. The data structures we tend to use (e.g. NumPy arrays) are often built on this fundamental structure.\n\nA time series is data where you have not just the order but some actual continuous marker for where they lie \"in time\" - this could be a date, a timestamp, [Unix time](https://en.wikipedia.org/wiki/Unix_time), or something else. All time series are also sequences, and for some techniques you may just consider their order and not \"how far apart\" the entries are (if you have particularly consistent data collected at regular intervals it may not matter).",
"_____no_output_____"
],
[
"## Time series with plain old regression\n\nRecurrences are fancy, and we'll get to those later - let's start with something simple. Regression can handle time series just fine if you just set them up correctly - let's try some made-up stock data. And to make it, let's use a few list comprehensions!",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom random import random\ndays = np.array((range(28)))\nstock_quotes = np.array([random() + day * random() for day in days])",
"_____no_output_____"
],
[
"stock_quotes",
"_____no_output_____"
]
],
[
[
"Let's take a look with a scatter plot:",
"_____no_output_____"
]
],
[
[
"from matplotlib.pyplot import scatter\nscatter(days, stock_quotes)",
"_____no_output_____"
]
],
[
[
"Looks pretty linear, let's try a simple OLS regression.\n\nFirst, these need to be NumPy arrays:",
"_____no_output_____"
]
],
[
[
"days = days.reshape(-1, 1) # X needs to be column vectors",
"_____no_output_____"
]
],
[
[
"Now let's use good old `scikit-learn` and linear regression:",
"_____no_output_____"
]
],
[
[
"from sklearn.linear_model import LinearRegression\nols_stocks = LinearRegression()\nols_stocks.fit(days, stock_quotes)\nols_stocks.score(days, stock_quotes)",
"_____no_output_____"
]
],
[
[
"That seems to work pretty well, but real stocks don't work like this.\n\nLet's make *slightly* more realistic data that depends on more than just time:",
"_____no_output_____"
]
],
[
[
"# Not everything is best as a comprehension\nstock_data = np.empty([len(days), 4])\nfor day in days:\n asset = random()\n liability = random()\n quote = random() + ((day * random()) + (20 * asset) - (15 * liability))\n quote = max(quote, 0.01) # Want positive quotes\n stock_data[day] = np.array([quote, day, asset, liability])",
"_____no_output_____"
],
[
"stock_data",
"_____no_output_____"
]
],
[
[
"Let's look again:",
"_____no_output_____"
]
],
[
[
"stock_quotes = stock_data[:,0]\nscatter(days, stock_quotes)",
"_____no_output_____"
]
],
[
[
"How does our old model do?",
"_____no_output_____"
]
],
[
[
"days = np.array(days).reshape(-1, 1)\nols_stocks.fit(days, stock_quotes)\nols_stocks.score(days, stock_quotes)",
"_____no_output_____"
]
],
[
[
"Not bad, but can we do better?",
"_____no_output_____"
]
],
[
[
"ols_stocks.fit(stock_data[:,1:], stock_quotes)\nols_stocks.score(stock_data[:,1:], stock_quotes)",
"_____no_output_____"
]
],
[
[
"Yep - unsurprisingly, the other covariates (assets and liabilities) have info.\n\nBut, they do worse without the day data.",
"_____no_output_____"
]
],
[
[
"ols_stocks.fit(stock_data[:,2:], stock_quotes)\nols_stocks.score(stock_data[:,2:], stock_quotes)",
"_____no_output_____"
]
],
[
[
"## Time series jargon\n\nThere's a lot of semi-standard language and tricks to talk about this sort of data. [NIST](https://www.itl.nist.gov/div898/handbook/pmc/section4/pmc4.htm) has an excellent guidebook, but here are some highlights:",
"_____no_output_____"
],
[
"### Moving average\n\nMoving average aka rolling average aka running average.\n\nConvert a series of data to a series of averages of continguous subsets:",
"_____no_output_____"
]
],
[
[
"stock_quotes_rolling = [sum(stock_quotes[i:i+3]) / 3\n for i in range(len(stock_quotes - 2))]\nstock_quotes_rolling",
"_____no_output_____"
]
],
[
[
"Pandas has nice series related functions:",
"_____no_output_____"
]
],
[
[
"import pandas as pd\ndf = pd.DataFrame(stock_quotes)\ndf.rolling(3).mean()",
"_____no_output_____"
]
],
[
[
"### Forecasting\n\nForecasting - at it's simplest, it just means \"predict the future\":",
"_____no_output_____"
]
],
[
[
"ols_stocks.fit(stock_data[:,1:], stock_quotes)\nols_stocks.predict([[29, 0.5, 0.5]])",
"_____no_output_____"
]
],
[
[
"One way to predict if you just have the series data is to use the prior observation. This can be pretty good (if you had to pick one feature to model the temperature for tomorrow, the temperature today is a good choice).",
"_____no_output_____"
]
],
[
[
"temperature = np.array([30 + random() * day\n for day in np.array(range(365)).reshape(-1, 1)])\ntemperature_next = temperature[1:].reshape(-1, 1)\ntemperature_ols = LinearRegression()\ntemperature_ols.fit(temperature[:-1], temperature_next)\ntemperature_ols.score(temperature[:-1], temperature_next)",
"_____no_output_____"
]
],
[
[
"But you can often make it better by considering more than one prior observation.",
"_____no_output_____"
]
],
[
[
"temperature_next_next = temperature[2:].reshape(-1, 1)\ntemperature_two_past = np.concatenate([temperature[:-2], temperature_next[:-1]],\n axis=1)\ntemperature_ols.fit(temperature_two_past, temperature_next_next)\ntemperature_ols.score(temperature_two_past, temperature_next_next)",
"_____no_output_____"
]
],
[
[
"### Exponential smoothing\n\nExponential smoothing means using exponentially decreasing past weights to predict the future.\n\nYou could roll your own, but let's use Pandas.",
"_____no_output_____"
]
],
[
[
"temperature_df = pd.DataFrame(temperature)\ntemperature_df.ewm(halflife=7).mean()",
"_____no_output_____"
]
],
[
[
"Halflife is among the parameters we can play with:",
"_____no_output_____"
]
],
[
[
"sse_1 = ((temperature_df - temperature_df.ewm(halflife=7).mean())**2).sum()\nsse_2 = ((temperature_df - temperature_df.ewm(halflife=3).mean())**2).sum()\nprint(sse_1)\nprint(sse_2)",
"0 1.212862e+06\ndtype: float64\n0 987212.470691\ndtype: float64\n"
]
],
[
[
"Note - the first error being higher doesn't mean it's necessarily *worse*. It's *smoother* as expected, and if that's what we care about - great!",
"_____no_output_____"
],
[
"### Seasonality\n\nSeasonality - \"day of week\"-effects, and more. In a lot of real world data, certain time periods are systemically different, e.g. holidays for retailers, weekends for restaurants, seasons for weather.\n\nLet's try to make some seasonal data - a store that sells more later in a week:",
"_____no_output_____"
]
],
[
[
"sales = np.array([random() + (day % 7) * random() for day in days])\nscatter(days, sales)",
"_____no_output_____"
]
],
[
[
"How does linear regression do at fitting this?",
"_____no_output_____"
]
],
[
[
"sales_ols = LinearRegression()\nsales_ols.fit(days, sales)\nsales_ols.score(days, sales)",
"_____no_output_____"
]
],
[
[
"That's not great - and the fix depends on the domain. Here, we know it'd be best to actually use \"day of week\" as a feature.",
"_____no_output_____"
]
],
[
[
"day_of_week = days % 7\nsales_ols.fit(day_of_week, sales)\nsales_ols.score(day_of_week, sales)",
"_____no_output_____"
]
],
[
[
"Note that it's also important to have representative data across whatever seasonal feature(s) you use - don't predict retailers based only on Christmas, as that won't generalize well.",
"_____no_output_____"
],
[
"## Recurrent Neural Networks\n\nThere's plenty more to \"traditional\" time series, but the latest and greatest technique for sequence data is recurrent neural networks. A recurrence relation in math is an equation that uses recursion to define a sequence - a famous example is the Fibonacci numbers:\n\n$F_n = F_{n-1} + F_{n-2}$\n\nFor formal math you also need a base case $F_0=1, F_1=1$, and then the rest builds from there. But for neural networks what we're really talking about are loops:\n\n\n\nThe hidden layers have edges (output) going back to their own input - this loop means that for any time `t` the training is at least partly based on the output from time `t-1`. The entire network is being represented on the left, and you can unfold the network explicitly to see how it behaves at any given `t`.\n\nDifferent units can have this \"loop\", but a particularly successful one is the long short-term memory unit (LSTM):\n\n\n\nThere's a lot going on here - in a nutshell, the calculus still works out and backpropagation can still be implemented. The advantage (ane namesake) of LSTM is that it can generally put more weight on recent (short-term) events while not completely losing older (long-term) information.\n\nAfter enough iterations, a typical neural network will start calculating prior gradients that are so small they effectively become zero - this is the [vanishing gradient problem](https://en.wikipedia.org/wiki/Vanishing_gradient_problem), and is what RNN with LSTM addresses. Pay special attention to the $c_t$ parameters and how they pass through the unit to get an intuition for how this problem is solved.\n\nSo why are these cool? One particularly compelling application is actually not time series but language modeling - language is inherently ordered data (letters/words go one after another, and the order *matters*). [The Unreasonable Effectiveness of Recurrent Neural Networks](https://karpathy.github.io/2015/05/21/rnn-effectiveness/) is a famous and worth reading blog post on this topic.\n\nFor our purposes, let's use TensorFlow and Keras to train RNNs with natural language. Resources:\n\n- https://github.com/keras-team/keras/blob/master/examples/imdb_lstm.py\n- https://keras.io/layers/recurrent/#lstm\n- http://adventuresinmachinelearning.com/keras-lstm-tutorial/\n\nNote that `tensorflow.contrib` [also has an implementation of RNN/LSTM](https://www.tensorflow.org/tutorials/sequences/recurrent).",
"_____no_output_____"
],
[
"### RNN/LSTM Sentiment Classification with Keras",
"_____no_output_____"
]
],
[
[
"'''\n#Trains an LSTM model on the IMDB sentiment classification task.\nThe dataset is actually too small for LSTM to be of any advantage\ncompared to simpler, much faster methods such as TF-IDF + LogReg.\n**Notes**\n- RNNs are tricky. Choice of batch size is important,\nchoice of loss and optimizer is critical, etc.\nSome configurations won't converge.\n- LSTM loss decrease patterns during training can be quite different\nfrom what you see with CNNs/MLPs/etc.\n'''\nfrom __future__ import print_function\n\nfrom keras.preprocessing import sequence\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Embedding\nfrom keras.layers import LSTM\nfrom keras.datasets import imdb\n\nmax_features = 20000\n# cut texts after this number of words (among top max_features most common words)\nmaxlen = 80\nbatch_size = 32\n\nprint('Loading data...')\n(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)\nprint(len(x_train), 'train sequences')\nprint(len(x_test), 'test sequences')\n\nprint('Pad sequences (samples x time)')\nx_train = sequence.pad_sequences(x_train, maxlen=maxlen)\nx_test = sequence.pad_sequences(x_test, maxlen=maxlen)\nprint('x_train shape:', x_train.shape)\nprint('x_test shape:', x_test.shape)\n\nprint('Build model...')\nmodel = Sequential()\nmodel.add(Embedding(max_features, 128))\nmodel.add(LSTM(128, dropout=0.2, recurrent_dropout=0.2))\nmodel.add(Dense(1, activation='sigmoid'))\n\n# try using different optimizers and different optimizer configs\nmodel.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\nprint('Train...')\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=15,\n validation_data=(x_test, y_test))\nscore, acc = model.evaluate(x_test, y_test,\n batch_size=batch_size)\nprint('Test score:', score)\nprint('Test accuracy:', acc)",
"Using TensorFlow backend.\n"
]
],
[
[
"### RNN Text generation with NumPy\n\nWhat else can we do with RNN? Since we're analyzing the *sequence*, we can do more than classify - we can *generate* text. We'll pull some news stories using [newspaper](https://github.com/codelucas/newspaper/).",
"_____no_output_____"
],
[
"#### Initialization",
"_____no_output_____"
]
],
[
[
"!pip install newspaper3k",
"Collecting newspaper3k\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/d7/b9/51afecb35bb61b188a4b44868001de348a0e8134b4dfa00ffc191567c4b9/newspaper3k-0.2.8-py3-none-any.whl (211kB)\n\u001b[K 100% |████████████████████████████████| 215kB 25.8MB/s \n\u001b[?25hCollecting feedfinder2>=0.0.4 (from newspaper3k)\n Downloading https://files.pythonhosted.org/packages/35/82/1251fefec3bb4b03fd966c7e7f7a41c9fc2bb00d823a34c13f847fd61406/feedfinder2-0.0.4.tar.gz\nCollecting feedparser>=5.2.1 (from newspaper3k)\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/91/d8/7d37fec71ff7c9dbcdd80d2b48bcdd86d6af502156fc93846fb0102cb2c4/feedparser-5.2.1.tar.bz2 (192kB)\n\u001b[K 100% |████████████████████████████████| 194kB 25.7MB/s \n\u001b[?25hRequirement already satisfied: beautifulsoup4>=4.4.1 in /usr/local/lib/python3.6/dist-packages (from newspaper3k) (4.6.3)\nCollecting cssselect>=0.9.2 (from newspaper3k)\n Downloading https://files.pythonhosted.org/packages/7b/44/25b7283e50585f0b4156960691d951b05d061abf4a714078393e51929b30/cssselect-1.0.3-py2.py3-none-any.whl\nCollecting jieba3k>=0.35.1 (from newspaper3k)\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/a9/cb/2c8332bcdc14d33b0bedd18ae0a4981a069c3513e445120da3c3f23a8aaa/jieba3k-0.35.1.zip (7.4MB)\n\u001b[K 100% |████████████████████████████████| 7.4MB 6.6MB/s \n\u001b[?25hCollecting tldextract>=2.0.1 (from newspaper3k)\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/1e/90/18ac0e5340b6228c25cc8e79835c3811e7553b2b9ae87296dfeb62b7866d/tldextract-2.2.1-py2.py3-none-any.whl (48kB)\n\u001b[K 100% |████████████████████████████████| 51kB 18.7MB/s \n\u001b[?25hRequirement already satisfied: requests>=2.10.0 in /usr/local/lib/python3.6/dist-packages (from newspaper3k) (2.18.4)\nRequirement already satisfied: lxml>=3.6.0 in /usr/local/lib/python3.6/dist-packages (from newspaper3k) (4.2.6)\nCollecting tinysegmenter==0.3 (from newspaper3k)\n Downloading https://files.pythonhosted.org/packages/17/82/86982e4b6d16e4febc79c2a1d68ee3b707e8a020c5d2bc4af8052d0f136a/tinysegmenter-0.3.tar.gz\nRequirement already satisfied: nltk>=3.2.1 in /usr/local/lib/python3.6/dist-packages (from newspaper3k) (3.2.5)\nRequirement already satisfied: Pillow>=3.3.0 in /usr/local/lib/python3.6/dist-packages (from newspaper3k) (4.1.1)\nRequirement already satisfied: python-dateutil>=2.5.3 in /usr/local/lib/python3.6/dist-packages (from newspaper3k) (2.5.3)\nRequirement already satisfied: PyYAML>=3.11 in /usr/local/lib/python3.6/dist-packages (from newspaper3k) (3.13)\nRequirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from feedfinder2>=0.0.4->newspaper3k) (1.11.0)\nCollecting requests-file>=1.4 (from tldextract>=2.0.1->newspaper3k)\n Downloading https://files.pythonhosted.org/packages/23/9c/6e63c23c39e53d3df41c77a3d05a49a42c4e1383a6d2a5e3233161b89dbf/requests_file-1.4.3-py2.py3-none-any.whl\nRequirement already satisfied: idna in /usr/local/lib/python3.6/dist-packages (from tldextract>=2.0.1->newspaper3k) (2.6)\nRequirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from tldextract>=2.0.1->newspaper3k) (40.9.0)\nRequirement already satisfied: urllib3<1.23,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests>=2.10.0->newspaper3k) (1.22)\nRequirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests>=2.10.0->newspaper3k) (3.0.4)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests>=2.10.0->newspaper3k) (2019.3.9)\nRequirement already satisfied: olefile in /usr/local/lib/python3.6/dist-packages (from Pillow>=3.3.0->newspaper3k) (0.46)\nBuilding wheels for collected packages: feedfinder2, feedparser, jieba3k, tinysegmenter\n Building wheel for feedfinder2 (setup.py) ... \u001b[?25ldone\n\u001b[?25h Stored in directory: /root/.cache/pip/wheels/de/03/ca/778e3a7a627e3d98836cc890e7cb40c7575424cfd3340f40ed\n Building wheel for feedparser (setup.py) ... \u001b[?25ldone\n\u001b[?25h Stored in directory: /root/.cache/pip/wheels/8c/69/b7/f52763c41c5471df57703a0ef718a32a5e81ee35dcf6d4f97f\n Building wheel for jieba3k (setup.py) ... \u001b[?25ldone\n\u001b[?25h Stored in directory: /root/.cache/pip/wheels/83/15/9c/a3f1f67e7f7181170ad37d32e503c35da20627c013f438ed34\n Building wheel for tinysegmenter (setup.py) ... \u001b[?25ldone\n\u001b[?25h Stored in directory: /root/.cache/pip/wheels/81/2b/43/a02ede72324dd40cdd7ca53aad718c7710628e91b8b0dc0f02\nSuccessfully built feedfinder2 feedparser jieba3k tinysegmenter\nInstalling collected packages: feedfinder2, feedparser, cssselect, jieba3k, requests-file, tldextract, tinysegmenter, newspaper3k\nSuccessfully installed cssselect-1.0.3 feedfinder2-0.0.4 feedparser-5.2.1 jieba3k-0.35.1 newspaper3k-0.2.8 requests-file-1.4.3 tinysegmenter-0.3 tldextract-2.2.1\n"
],
[
"import newspaper",
"_____no_output_____"
],
[
"ap = newspaper.build('https://www.apnews.com')\nlen(ap.articles)",
"_____no_output_____"
],
[
"article_text = ''\n\nfor article in ap.articles[:1]:\n try:\n article.download()\n article.parse()\n article_text += '\\n\\n' + article.text\n except:\n print('Failed: ' + article.url)\n \narticle_text = article_text.split('\\n\\n')[1]\nprint(article_text)",
"California Democrats again are trying to mandate the abortion pill be stocked in campus clinics across the Golden State’s university system, and this time they’ve got a friend in the governor’s office.\n"
],
[
"# Based on \"The Unreasonable Effectiveness of RNN\" implementation\nimport numpy as np\n\nchars = list(set(article_text)) # split and remove duplicate characters. convert to list.\n\nnum_chars = len(chars) # the number of unique characters\ntxt_data_size = len(article_text)\n\nprint(\"unique characters : \", num_chars)\nprint(\"txt_data_size : \", txt_data_size)",
"unique characters : 29\ntxt_data_size : 201\n"
],
[
"# one hot encode\nchar_to_int = dict((c, i) for i, c in enumerate(chars)) # \"enumerate\" retruns index and value. Convert it to dictionary\nint_to_char = dict((i, c) for i, c in enumerate(chars))\nprint(char_to_int)\nprint(\"----------------------------------------------------\")\nprint(int_to_char)\nprint(\"----------------------------------------------------\")\n# integer encode input data\ninteger_encoded = [char_to_int[i] for i in article_text] # \"integer_encoded\" is a list which has a sequence converted from an original data to integers.\nprint(integer_encoded)\nprint(\"----------------------------------------------------\")\nprint(\"data length : \", len(integer_encoded))",
"{',': 0, 't': 1, 's': 2, 'm': 3, 'd': 4, 'h': 5, 'y': 6, 'o': 7, 'l': 8, 'S': 9, 'a': 10, 'i': 11, 'D': 12, 'p': 13, 'e': 14, 'k': 15, 'c': 16, 'g': 17, 'b': 18, 'v': 19, 'n': 20, 'G': 21, 'u': 22, 'C': 23, '’': 24, 'r': 25, 'f': 26, '.': 27, ' ': 28}\n----------------------------------------------------\n{0: ',', 1: 't', 2: 's', 3: 'm', 4: 'd', 5: 'h', 6: 'y', 7: 'o', 8: 'l', 9: 'S', 10: 'a', 11: 'i', 12: 'D', 13: 'p', 14: 'e', 15: 'k', 16: 'c', 17: 'g', 18: 'b', 19: 'v', 20: 'n', 21: 'G', 22: 'u', 23: 'C', 24: '’', 25: 'r', 26: 'f', 27: '.', 28: ' '}\n----------------------------------------------------\n[23, 10, 8, 11, 26, 7, 25, 20, 11, 10, 28, 12, 14, 3, 7, 16, 25, 10, 1, 2, 28, 10, 17, 10, 11, 20, 28, 10, 25, 14, 28, 1, 25, 6, 11, 20, 17, 28, 1, 7, 28, 3, 10, 20, 4, 10, 1, 14, 28, 1, 5, 14, 28, 10, 18, 7, 25, 1, 11, 7, 20, 28, 13, 11, 8, 8, 28, 18, 14, 28, 2, 1, 7, 16, 15, 14, 4, 28, 11, 20, 28, 16, 10, 3, 13, 22, 2, 28, 16, 8, 11, 20, 11, 16, 2, 28, 10, 16, 25, 7, 2, 2, 28, 1, 5, 14, 28, 21, 7, 8, 4, 14, 20, 28, 9, 1, 10, 1, 14, 24, 2, 28, 22, 20, 11, 19, 14, 25, 2, 11, 1, 6, 28, 2, 6, 2, 1, 14, 3, 0, 28, 10, 20, 4, 28, 1, 5, 11, 2, 28, 1, 11, 3, 14, 28, 1, 5, 14, 6, 24, 19, 14, 28, 17, 7, 1, 28, 10, 28, 26, 25, 11, 14, 20, 4, 28, 11, 20, 28, 1, 5, 14, 28, 17, 7, 19, 14, 25, 20, 7, 25, 24, 2, 28, 7, 26, 26, 11, 16, 14, 27]\n----------------------------------------------------\ndata length : 201\n"
],
[
"# hyperparameters\n\niteration = 1000\nsequence_length = 40\nbatch_size = round((txt_data_size /sequence_length)+0.5) # = math.ceil\nhidden_size = 500 # size of hidden layer of neurons. \nlearning_rate = 1e-1\n\n\n# model parameters\n\nW_xh = np.random.randn(hidden_size, num_chars)*0.01 # weight input -> hidden. \nW_hh = np.random.randn(hidden_size, hidden_size)*0.01 # weight hidden -> hidden\nW_hy = np.random.randn(num_chars, hidden_size)*0.01 # weight hidden -> output\n\nb_h = np.zeros((hidden_size, 1)) # hidden bias\nb_y = np.zeros((num_chars, 1)) # output bias\n\nh_prev = np.zeros((hidden_size,1)) # h_(t-1)",
"_____no_output_____"
]
],
[
[
"#### Forward propagation",
"_____no_output_____"
]
],
[
[
"def forwardprop(inputs, targets, h_prev):\n \n # Since the RNN receives the sequence, the weights are not updated during one sequence.\n xs, hs, ys, ps = {}, {}, {}, {} # dictionary\n hs[-1] = np.copy(h_prev) # Copy previous hidden state vector to -1 key value.\n loss = 0 # loss initialization\n \n for t in range(len(inputs)): # t is a \"time step\" and is used as a key(dic). \n \n xs[t] = np.zeros((num_chars,1)) \n xs[t][inputs[t]] = 1\n hs[t] = np.tanh(np.dot(W_xh, xs[t]) + np.dot(W_hh, hs[t-1]) + b_h) # hidden state. \n ys[t] = np.dot(W_hy, hs[t]) + b_y # unnormalized log probabilities for next chars\n ps[t] = np.exp(ys[t]) / np.sum(np.exp(ys[t])) # probabilities for next chars. \n # Softmax. -> The sum of probabilities is 1 even without the exp() function, but all of the elements are positive through the exp() function.\n \n loss += -np.log(ps[t][targets[t],0]) # softmax (cross-entropy loss). Efficient and simple code\n\n# y_class = np.zeros((num_chars, 1)) \n# y_class[targets[t]] =1\n# loss += np.sum(y_class*(-np.log(ps[t]))) # softmax (cross-entropy loss) \n\n return loss, ps, hs, xs",
"_____no_output_____"
]
],
[
[
"#### Backward propagation",
"_____no_output_____"
]
],
[
[
"def backprop(ps, inputs, hs, xs):\n\n dWxh, dWhh, dWhy = np.zeros_like(W_xh), np.zeros_like(W_hh), np.zeros_like(W_hy) # make all zero matrices.\n dbh, dby = np.zeros_like(b_h), np.zeros_like(b_y)\n dhnext = np.zeros_like(hs[0]) # (hidden_size,1) \n\n # reversed\n for t in reversed(range(len(inputs))):\n dy = np.copy(ps[t]) # shape (num_chars,1). \"dy\" means \"dloss/dy\"\n dy[targets[t]] -= 1 # backprop into y. After taking the soft max in the input vector, subtract 1 from the value of the element corresponding to the correct label.\n dWhy += np.dot(dy, hs[t].T)\n dby += dy \n dh = np.dot(W_hy.T, dy) + dhnext # backprop into h. \n dhraw = (1 - hs[t] * hs[t]) * dh # backprop through tanh nonlinearity #tanh'(x) = 1-tanh^2(x)\n dbh += dhraw\n dWxh += np.dot(dhraw, xs[t].T)\n dWhh += np.dot(dhraw, hs[t-1].T)\n dhnext = np.dot(W_hh.T, dhraw)\n for dparam in [dWxh, dWhh, dWhy, dbh, dby]: \n np.clip(dparam, -5, 5, out=dparam) # clip to mitigate exploding gradients. \n \n return dWxh, dWhh, dWhy, dbh, dby",
"_____no_output_____"
]
],
[
[
"#### Training",
"_____no_output_____"
]
],
[
[
"%%time\n\ndata_pointer = 0\n\n# memory variables for Adagrad\nmWxh, mWhh, mWhy = np.zeros_like(W_xh), np.zeros_like(W_hh), np.zeros_like(W_hy)\nmbh, mby = np.zeros_like(b_h), np.zeros_like(b_y) \n\nfor i in range(iteration):\n h_prev = np.zeros((hidden_size,1)) # reset RNN memory\n data_pointer = 0 # go from start of data\n \n for b in range(batch_size):\n \n inputs = [char_to_int[ch] for ch in article_text[data_pointer:data_pointer+sequence_length]]\n targets = [char_to_int[ch] for ch in article_text[data_pointer+1:data_pointer+sequence_length+1]] # t+1 \n \n if (data_pointer+sequence_length+1 >= len(article_text) and b == batch_size-1): # processing of the last part of the input data. \n# targets.append(char_to_int[txt_data[0]]) # When the data doesn't fit, add the first char to the back.\n targets.append(char_to_int[\" \"]) # When the data doesn't fit, add space(\" \") to the back.\n\n\n # forward\n loss, ps, hs, xs = forwardprop(inputs, targets, h_prev)\n# print(loss)\n \n # backward\n dWxh, dWhh, dWhy, dbh, dby = backprop(ps, inputs, hs, xs) \n \n \n # perform parameter update with Adagrad\n for param, dparam, mem in zip([W_xh, W_hh, W_hy, b_h, b_y], \n [dWxh, dWhh, dWhy, dbh, dby], \n [mWxh, mWhh, mWhy, mbh, mby]):\n mem += dparam * dparam # elementwise\n param += -learning_rate * dparam / np.sqrt(mem + 1e-8) # adagrad update \n \n data_pointer += sequence_length # move data pointer\n \n if i % 100 == 0:\n print ('iter %d, loss: %f' % (i, loss)) # print progress",
"iter 0, loss: 1.921729\niter 100, loss: 0.000758\niter 200, loss: 0.000377\niter 300, loss: 0.000219\niter 400, loss: 0.000141\niter 500, loss: 0.000096\niter 600, loss: 0.000062\niter 700, loss: 0.000043\niter 800, loss: 0.000031\niter 900, loss: 0.000024\nCPU times: user 5min 53s, sys: 3min 26s, total: 9min 20s\nWall time: 4min 44s\n"
]
],
[
[
"#### Prediction",
"_____no_output_____"
]
],
[
[
"def predict(test_char, length):\n x = np.zeros((num_chars, 1)) \n x[char_to_int[test_char]] = 1\n ixes = []\n h = np.zeros((hidden_size,1))\n\n for t in range(length):\n h = np.tanh(np.dot(W_xh, x) + np.dot(W_hh, h) + b_h) \n y = np.dot(W_hy, h) + b_y\n p = np.exp(y) / np.sum(np.exp(y)) \n ix = np.random.choice(range(num_chars), p=p.ravel()) # ravel -> rank0\n # \"ix\" is a list of indexes selected according to the soft max probability.\n x = np.zeros((num_chars, 1)) # init\n x[ix] = 1 \n ixes.append(ix) # list\n txt = test_char + ''.join(int_to_char[i] for i in ixes)\n print ('----\\n %s \\n----' % (txt, ))",
"_____no_output_____"
],
[
"predict('C', 50)",
"----\n Califor Gooffic te nofft ove yke Gocr’sdlliamoffico \n----\n"
]
],
[
[
"Well... that's *vaguely* language-looking. Can you do better?",
"_____no_output_____"
],
[
"# Assignment\n\n\n\nIt is said that [infinite monkeys typing for an infinite amount of time](https://en.wikipedia.org/wiki/Infinite_monkey_theorem) will eventually type, among other things, the complete works of Wiliam Shakespeare. Let's see if we can get there a bit faster, with the power of Recurrent Neural Networks and LSTM.\n\nThis text file contains the complete works of Shakespeare: https://www.gutenberg.org/files/100/100-0.txt\n\nUse it as training data for an RNN - you can keep it simple and train character level, and that is suggested as an initial approach.\n\nThen, use that trained RNN to generate Shakespearean-ish text. Your goal - a function that can take, as an argument, the size of text (e.g. number of characters or lines) to generate, and returns generated text of that size.\n\nNote - Shakespeare wrote an awful lot. It's OK, especially initially, to sample/use smaller data and parameters, so you can have a tighter feedback loop when you're trying to get things running. Then, once you've got a proof of concept - start pushing it more!",
"_____no_output_____"
]
],
[
[
"# TODO - Words, words, mere words, no matter from the heart.",
"_____no_output_____"
]
],
[
[
"# Resources and Stretch Goals",
"_____no_output_____"
],
[
"## Stretch goals:\n- Refine the training and generation of text to be able to ask for different genres/styles of Shakespearean text (e.g. plays versus sonnets)\n- Train a classification model that takes text and returns which work of Shakespeare it is most likely to be from\n- Make it more performant! Many possible routes here - lean on Keras, optimize the code, and/or use more resources (AWS, etc.)\n- Revisit the news example from class, and improve it - use categories or tags to refine the model/generation, or train a news classifier\n- Run on bigger, better data\n\n## Resources:\n- [The Unreasonable Effectiveness of Recurrent Neural Networks](https://karpathy.github.io/2015/05/21/rnn-effectiveness/) - a seminal writeup demonstrating a simple but effective character-level NLP RNN\n- [Simple NumPy implementation of RNN](https://github.com/JY-Yoon/RNN-Implementation-using-NumPy/blob/master/RNN%20Implementation%20using%20NumPy.ipynb) - Python 3 version of the code from \"Unreasonable Effectiveness\"\n- [TensorFlow RNN Tutorial](https://github.com/tensorflow/models/tree/master/tutorials/rnn) - code for training a RNN on the Penn Tree Bank language dataset\n- [4 part tutorial on RNN](http://www.wildml.com/2015/09/recurrent-neural-networks-tutorial-part-1-introduction-to-rnns/) - relates RNN to the vanishing gradient problem, and provides example implementation\n- [RNN training tips and tricks](https://github.com/karpathy/char-rnn#tips-and-tricks) - some rules of thumb for parameterizing and training your RNN",
"_____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"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
d080f75b69ec54aecb761bca5a05035d1ad289e9 | 2,336 | ipynb | Jupyter Notebook | step1_generate_labels.ipynb | danzelmo/dstl-competition | ef09d67ebc5ff754dc83a1908202a300ed2055b2 | [
"MIT"
] | 15 | 2017-04-25T20:19:57.000Z | 2021-04-13T19:26:59.000Z | step1_generate_labels.ipynb | storyofblue/dstl-competition | ef09d67ebc5ff754dc83a1908202a300ed2055b2 | [
"MIT"
] | 1 | 2017-08-06T13:26:10.000Z | 2017-08-17T14:47:40.000Z | step1_generate_labels.ipynb | storyofblue/dstl-competition | ef09d67ebc5ff754dc83a1908202a300ed2055b2 | [
"MIT"
] | 7 | 2017-05-26T07:46:25.000Z | 2021-05-27T03:35:19.000Z | 26.545455 | 106 | 0.552226 | [
[
[
"import pandas as pd\nimport numpy as np\nimport tifffile as tif\nimport os\n\nimport utils\nimport global_vars",
"_____no_output_____"
]
],
[
[
"#### Label Generation\nUses code written by visoft and posted on kaggle to generate four different resolutions of labels\n",
"_____no_output_____"
]
],
[
[
"grid_sizes = pd.read_csv(os.path.join(global_vars.DATA_DIR,'grid_sizes.csv'), index_col=0)\ntrain_labels = pd.read_csv(os.path.join(global_vars.DATA_DIR,'train_wkt_v4.csv'), index_col=0)\ntrain_names = list(train_labels.index.unique())",
"_____no_output_____"
],
[
"base_size= 835\nlabel_sizes = [base_size, base_size*2, base_size*4] \nfor im_name in train_names:\n for i in range(1, 11):\n polys = utils.get_polygon_list(train_labels, im_name, i)\n x_max = grid_sizes.loc[im_name,'Xmax']\n y_min = grid_sizes.loc[im_name,'Ymin']\n for size in label_sizes:\n plist, ilist = utils.get_and_convert_contours(polys, (size,size), x_max, y_min)\n im_mask = utils.plot_mask((size,size), plist, ilist)\n im_mask = im_mask.reshape((size, size, 1))\n tif.imsave(os.path.join(global_vars.DATA_DIR,'labels',\n im_name + '_' + str(size)+ '_class_' +str(i)+'.tif'), im_mask)",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
d0810efd0694947a992e3a0c30d61680702831cd | 993,337 | ipynb | Jupyter Notebook | assignments/Assignment1.ipynb | christianpoulsen/socialdata2021 | eee14811f59b68dabf56115b2e46d885b270a4d0 | [
"MIT"
] | null | null | null | assignments/Assignment1.ipynb | christianpoulsen/socialdata2021 | eee14811f59b68dabf56115b2e46d885b270a4d0 | [
"MIT"
] | null | null | null | assignments/Assignment1.ipynb | christianpoulsen/socialdata2021 | eee14811f59b68dabf56115b2e46d885b270a4d0 | [
"MIT"
] | null | null | null | 1,291.725618 | 856,778 | 0.788092 | [
[
[
"# Assignment 1.\n\n## Formalia:\n\nPlease read the [assignment overview page](https://github.com/suneman/socialdata2021/wiki/Assignment-1-and-2) carefully before proceeding. This page contains information about formatting (including formats etc), group sizes, and many other aspects of handing in the assignment. \n\n_If you fail to follow these simple instructions, it will negatively impact your grade!_\n\n**Due date and time**: The assignment is due on Monday March 1st, 2021 at 23:55. Hand in your files via [`http://peergrade.io`](http://peergrade.io/).\n\n**Peergrading date and time**: _Remember that after handing in you have 1 week to evaluate a few assignments written by other members of the class_. Thus, the peer evaluations are due on Monday March 8th, 2021 at 23:55.",
"_____no_output_____"
],
[
"## Part 1: Temporal Patterns\n\nWe look only at the focus-crimes in the exercise below",
"_____no_output_____"
]
],
[
[
"focuscrimes = set(['WEAPON LAWS', 'PROSTITUTION', 'DRIVING UNDER THE INFLUENCE', 'ROBBERY', 'BURGLARY', 'ASSAULT', 'DRUNKENNESS', 'DRUG/NARCOTIC', 'TRESPASS', 'LARCENY/THEFT', 'VANDALISM', 'VEHICLE THEFT', 'STOLEN PROPERTY', 'DISORDERLY CONDUCT'])",
"_____no_output_____"
]
],
[
[
"*Exercise*: More temporal patterns. During week 1, we plotted some crime development over time (how each of the focus-crimes changed over time, year-by-year). \n\nIn this exercise, please generate the visualizations described below. Use the same date-ranges as in Week 1. For each set of plots, describe the plots (as you would in the figure text in a report or paper), and pick a few aspects that stand out to you and comment on those (a couple of ideas below for things that could be interesting to comment on ... but it's OK to chose something else).\n\n* *Weekly patterns*. Basically, we'll forget about the yearly variation and just count up what happens during each weekday. [Here's what my version looks like](https://raw.githubusercontent.com/suneman/socialdata2021/master/files/weekdays.png). Hint for comment: Some things make sense - for example `drunkenness` and the weekend. But there are some aspects that were surprising to me. Check out `prostitution` and mid-week behavior, for example!?\n* *The months*. We can also check if some months are worse by counting up number of crimes in Jan, Feb, ..., Dec. Did you see any surprises there?\n* *The 24 hour cycle*. We'll can also forget about weekday and simply count up the number of each crime-type that occurs in the entire dataset from midnight to 1am, 1am - 2am ... and so on. Again: Give me a couple of comments on what you see. \n* *Hours of the week*. But by looking at just 24 hours, we may be missing some important trends that can be modulated by week-day, so let's also check out the 168 hours of the week. So let's see the number of each crime-type Monday night from midninght to 1am, Monday night from 1am-2am - all the way to Sunday night from 11pm to midnight.\n",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport matplotlib.pyplot as plt\n\ndf = pd.read_csv(\"../incidents.csv\")",
"_____no_output_____"
],
[
"df = df[df[\"Category\"].isin(focuscrimes)]\ndf[\"Date_Time\"] = pd.to_datetime(df[\"Date\"] + \" \" + df[\"Time\"])",
"_____no_output_____"
],
[
"df.sort_values(by=[\"Date_Time\"], inplace=True, ascending=True)\ndf.head()",
"_____no_output_____"
],
[
"weeks = [\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"]\ndf1 = pd.DataFrame(df, columns=[\"Category\", \"DayOfWeek\"])\n\nwdf = pd.DataFrame(index=weeks, columns=focuscrimes)\n\nfor crime in focuscrimes:\n crime_df = df1[df1[\"Category\"] == crime]\n for week_day in weeks:\n wdf.at[week_day, crime] = len(crime_df[crime_df[\"DayOfWeek\"] == week_day])\n \n\nplt.figure(1, figsize=(18,27))\ncount = 1\nfor crime in wdf.columns:\n plt.subplot(7, 2, count)\n wdf[crime].plot(kind=\"bar\", subplots=True, figsize=(9, 6), rot=0)\n count += 1",
"_____no_output_____"
]
],
[
[
"## Part 2: Thinking about data and visualization",
"_____no_output_____"
],
[
"*Excercise:* Questions for the [second video lecture](https://www.youtube.com/watch?v=yiU56codNlI).\n* As mentioned earlier, visualization is not the only way to test for correlation. We can (for example) calculate the Pearson correlation. Explain in your own words how the Pearson correlation works and write down it's mathematical formulation. Can you think of an example where it fails (and visualization works)?\n* What is the difference between a bar-chart and a histogram?\n* I mention in the video that it's important to choose the right bin-size in histograms. But how do you do that? Do a Google search to find a criterion you like and explain it. ",
"_____no_output_____"
],
[
"## Part 3: Generating important plot types\n\n*Excercise*: Let us recreate some plots from DAOST but using our own favorite dataset.\n\n* First, let's make a jitter-plot (that is, code up something like **Figure 2-1** from DAOST from scratch), but based on SF Police data. My hunch from inspecting the file is that the police-folks might be a little bit lazy in noting down the **exact** time down to the second. So choose a crime-type and a suitable time interval (somewhere between a month and 6 months depending on the crime-type) and create a jitter plot of the arrest times during a single hour (like 13-14, for example). So let time run on the $x$-axis and create vertical jitter.\n\n* Now for some histograms (please create a crime-data based versions of the plot-type shown in DAOST **Figure 2-2**). (I think the GPS data could be fun to understand from this perspective.) \n * This time, pick two crime-types with different geographical patterns **and** a suitable time-interval for each (you want between 1000 and 10000 points in your histogram)\n * Then take the latitude part of the GPS coordinates for each crime and bin the latitudes so that you have around 50 bins across the city of SF. You can use your favorite method for binning. I like `numpy.histogram`. This function gives you the counts and then you do your own plotting. ",
"_____no_output_____"
],
[
"## Part 4: A bit of geo-data",
"_____no_output_____"
],
[
"*Exercise*: A new take on geospatial data using Folium (see the Week 4 exercises for full info and tutorials). \n\nNow we look at studying geospatial data by plotting raw data points as well as heatmaps on top of actual maps.\n\n* First start by plotting a map of San Francisco with a nice tight zoom. Simply use the command `folium.Map([lat, lon], zoom_start=13)`, where you'll have to look up San Francisco's longitude and latitude.\n* Next, use the the coordinates for SF City Hall `37.77919, -122.41914` to indicate its location on the map with a nice, pop-up enabled maker. (In the screenshot below, I used the black & white Stamen tiles, because they look cool).\n\n* Now, let's plot some more data (no need for popups this time). Select a couple of months of data for `'DRUG/NARCOTIC'` and draw a little dot for each arrest for those two months. You could, for example, choose June-July 2016, but you can choose anything you like - the main concern is to not have too many points as this uses a lot of memory and makes Folium behave non-optimally. \nWe can call this a kind of visualization a *point scatter plot*.",
"_____no_output_____"
]
],
[
[
"import numpy as np # linear algebra\nimport folium\nimport datetime as dt\n\nSF = folium.Map([37.773972, -122.431297], zoom_start=13, tiles=\"Stamen Toner\")\n\n\nfolium.Marker([37.77919, -122.41914], popup='City Hall').add_to(SF)",
"_____no_output_____"
],
[
"# Address, location, X, Y\n\nndf = df[df[\"Category\"] == \"DRUG/NARCOTIC\"]\n\nstart = ndf[\"Date_Time\"].searchsorted(dt.datetime(2016, 6, 1))\nend = ndf[\"Date_Time\"].searchsorted(dt.datetime(2016, 7, 1))\n \n\nfor i, case in ndf[start : end].iterrows():\n folium.CircleMarker(location=[case[\"Y\"], case[\"X\"]], radius=2,weight=5).add_to(SF)\n\nSF",
"_____no_output_____"
]
],
[
[
"## Part 5: Errors in the data. The importance of looking at raw (or close to raw) data.\n\nWe started the course by plotting simple histogram plots that showed a lot of cool patterns. But sometimes the binning can hide imprecision, irregularity, and simple errors in the data that could be misleading. In the work we've done so far, we've already come across at least three examples of this in the SF data. \n\n1. In the hourly activity for `PROSTITUTION` something surprising is going on on Thursday. Remind yourself [**here**](https://raw.githubusercontent.com/suneman/socialdata2021/master/files/prostitution_hourly.png), where I've highlighted the phenomenon I'm talking about.\n1. When we investigated the details of how the timestamps are recorded using jitter-plots, we saw that many more crimes were recorded e.g. on the hour, 15 minutes past the hour, and to a lesser in whole increments of 10 minutes. Crimes didn't appear to be recorded as frequently in between those round numbers. Remind yourself [**here**](https://raw.githubusercontent.com/suneman/socialdata2021/master/files/jitter_plot.png), where I've highlighted the phenomenon I'm talking about.\n1. And finally, today we saw that the Hall of Justice seemed to be an unlikely hotspot for sex offences. Remind yourself [**here**](https://raw.githubusercontent.com/suneman/socialdata2021/master/files/crime_hot_spot.png).\n\n> *Exercise*: Data errors. The data errors we discovered above become difficult to notice when we aggregate data (and when we calculate mean values, as well as statistics more generally). Thus, when we visualize, errors become difficult to notice when when we bin the data. We explore this process in the exercise below.\n>\n> The exercise is simply this:\n> * For each of the three examples above, describe in your own words how the data-errors I call attention to above can bias the binned versions of the data. Also briefly mention how not noticing these errors can result in misconceptions about the underlying patterns of what's going on in San Francisco (and our modeling).",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
d0811136957690f7c1e9e3e5ba57a0574ee9cc17 | 13,545 | ipynb | Jupyter Notebook | notebooks/AUP110_W11_Notebook.ipynb | htchu/AU110Programming | 6c22e3d202afb0ba90ef02378900270ab7ab657b | [
"MIT"
] | 1 | 2021-09-13T11:49:58.000Z | 2021-09-13T11:49:58.000Z | notebooks/AUP110_W11_Notebook.ipynb | htchu/AU110Programming | 6c22e3d202afb0ba90ef02378900270ab7ab657b | [
"MIT"
] | null | null | null | notebooks/AUP110_W11_Notebook.ipynb | htchu/AU110Programming | 6c22e3d202afb0ba90ef02378900270ab7ab657b | [
"MIT"
] | null | null | null | 21.364353 | 108 | 0.514064 | [
[
[
"# AU Fundamentals of Python Programming-W10X\n\n",
"_____no_output_____"
],
[
"## Topic 1(主題1)-字串和print()的參數",
"_____no_output_____"
],
[
"### Step 1: Hello World with 其他參數\nsep = \"...\" 列印分隔 end=\"\" 列印結尾\n* sep: string inserted between values, default a space.\n* end: string appended after the last value, default a newline.",
"_____no_output_____"
]
],
[
[
"print('Hello World!') #'Hello World!' is the same as \"Hello World!\"",
"_____no_output_____"
],
[
"help(print) #註解是不會執行的",
"_____no_output_____"
],
[
"print('Hello '+'World!')\nprint(\"Hello\",\"World\", sep=\"+\")",
"_____no_output_____"
],
[
"print(\"Hello\"); print(\"World!\")\nprint(\"Hello\", end=' ');print(\"World\")\n",
"_____no_output_____"
]
],
[
[
"### Step 2: Escape Sequence (逸出序列)\n* \\newline\tIgnored\n* \\\\\tBackslash (\\)\n* \\'\tSingle quote (')\n* \\\"\tDouble quote (\")\n* \\a\tASCII Bell (BEL)\n* \\b\tASCII Backspace (BS)\n* \\n\tASCII Linefeed (LF)\n* \\r\tASCII Carriage Return (CR)\n* \\t\tASCII Horizontal Tab (TAB)\n* \\ooo\tASCII character with octal value ooo\n* \\xhh...\tASCII character with hex value hh...",
"_____no_output_____"
]
],
[
[
"print(\"Hello\\nWorld!\")\nprint(\"Hello\",\"World!\", sep=\"\\n\")",
"_____no_output_____"
],
[
"txt = \"We are the so-called \\\"Vikings\\\" from the north.\"\nprint(txt)",
"_____no_output_____"
]
],
[
[
"### Step 3: 使用 字串尾部的\\來建立長字串",
"_____no_output_____"
]
],
[
[
"iPhone11='iPhone 11是由蘋果公司設計和銷售的智能手機,為第13代iPhone系列智能手機之一,亦是iPhone XR的後繼機種。\\\n其在2019年9月10日於蘋果園區史蒂夫·喬布斯劇院由CEO蒂姆·庫克隨iPhone 11 Pro及iPhone 11 Pro Max一起發佈,\\\n並於2019年9月20日在世界大部分地區正式發售。其採用類似iPhone XR的玻璃配鋁金屬設計;\\\n具有6.1英吋Liquid Retina HD顯示器,配有Face ID;並採用由蘋果自家設計的A13仿生晶片,\\\n帶有第三代神經網絡引擎。機器能夠防濺、耐水及防塵,在最深2米的水下停留時間最長可達30分鐘。'\nprint(iPhone11)",
"_____no_output_____"
]
],
[
[
"### Step 4: 使用六個雙引號來建立長字串 ''' ... ''' 或 \"\"\" ... \"\"\"",
"_____no_output_____"
]
],
[
[
"iPhone11='''\niPhone 11是由蘋果公司設計和銷售的智能手機,為第13代iPhone系列智能手機之一,亦是iPhone XR的後繼機種。\n其在2019年9月10日於蘋果園區史蒂夫·喬布斯劇院由CEO蒂姆·庫克隨iPhone 11 Pro及iPhone 11 Pro Max一起發佈,\n並於2019年9月20日在世界大部分地區正式發售。其採用類似iPhone XR的玻璃配鋁金屬設計;\n具有6.1英吋Liquid Retina HD顯示器,配有Face ID;並採用由蘋果自家設計的A13仿生晶片,\n帶有第三代神經網絡引擎。機器能夠防濺、耐水及防塵,在最深2米的水下停留時間最長可達30分鐘。'''\nprint(iPhone11)",
"_____no_output_____"
],
[
"iPhone11=\"\"\"\niPhone 11是由蘋果公司設計和銷售的智能手機,為第13代iPhone系列智能手機之一,亦是iPhone XR的後繼機種。\n其在2019年9月10日於蘋果園區史蒂夫·喬布斯劇院由CEO蒂姆·庫克隨iPhone 11 Pro及iPhone 11 Pro Max一起發佈,\n並於2019年9月20日在世界大部分地區正式發售。其採用類似iPhone XR的玻璃配鋁金屬設計;\n具有6.1英吋Liquid Retina HD顯示器,配有Face ID;並採用由蘋果自家設計的A13仿生晶片,\n帶有第三代神經網絡引擎。機器能夠防濺、耐水及防塵,在最深2米的水下停留時間最長可達30分鐘。\"\"\"\nprint(iPhone11)",
"_____no_output_____"
]
],
[
[
"## Topic 2(主題2)-型別轉換函數\n",
"_____no_output_____"
],
[
"### Step 5: 輸入變數的值",
"_____no_output_____"
]
],
[
[
"name = input('Please input your name:')\nprint('Hello, ', name)\nprint(type(name)) #列印變數的型別",
"_____no_output_____"
]
],
[
[
"### Step 6: Python 型別轉換函數\n* int() #變整數\n* float() #變浮點數\n* str() #變字串\n* 變數名稱=int(字串變數)\n* 變數名稱=str(數值變數",
"_____no_output_____"
]
],
[
[
"#變數宣告\nvarA = 66 #宣告一個整數變數\nvarB = 1.68 #宣告一個有小數的變數(電腦叫浮點數)\nvarC = 'GoPython' #宣告一個字串變數\nvarD = str(varA) #將整數88轉成字串的88\nvarE = str(varB) #將浮點數1.68轉成字串的1.68\nvarF = int('2019') #將字串2019轉作整數數值的2019\nvarG = float('3.14') #將字串3.14轉作浮點數數值的3.14\n",
"_____no_output_____"
],
[
"score = input('Please input your score:')\nscore = int(score)\nprint(type(score)) #列印變數的型別",
"_____no_output_____"
]
],
[
[
"## Topic 3(主題3)-索引和切片\n```\na = \"Hello, World!\"\nprint(a[1]) #Indexing\nprint(a[2:5]) #Slicing\n```",
"_____no_output_____"
],
[
"### Step 8: 索引(Indexing)",
"_____no_output_____"
]
],
[
[
"a = \"Hello Wang\"\nd = \"0123456789\"\nprint(a[3]) #Indexing",
"_____no_output_____"
],
[
"a = \"Hello Wang\"\nd = \"0123456789\"\nprint(a[-3]) #Negative Indexing",
"_____no_output_____"
]
],
[
[
"### Step 9: 切片(Slicing)",
"_____no_output_____"
]
],
[
[
"a = \"Hello Wang\"\nd = \"0123456789\"\nprint(a[2:5]) #Slicing",
"_____no_output_____"
],
[
"a = \"Hello Wang\"\nd = \"0123456789\"\nprint(a[2:]) #Slicing",
"_____no_output_____"
],
[
"a = \"Hello Wang\"\nd = \"0123456789\"\nprint(a[:5]) #Slicing",
"_____no_output_____"
],
[
"a = \"Hello Wang\"\nd = \"0123456789\"\nprint(a[-6:-2]) #Slicing",
"_____no_output_____"
],
[
"a = \"Hello Wang\"\nd = \"0123456789\"\nprint(a[-4:]) #Slicing",
"_____no_output_____"
]
],
[
[
"## Topic 4(主題4)-格式化輸出\n```\nA = 435; B = 59.058\nprint('Art: %5d, Price per Unit: %8.2f' % (A, B)) #%-formatting 格式化列印\nprint(\"Art: {0:5d}, Price per Unit: {1:8.2f}\".format(A,B)) #str-format(Python 2.6+)\nprint(f\"Art:{A:5d}, Price per Unit: {B:8.2f}\") #f-string (Python 3.6+)\n```",
"_____no_output_____"
],
[
"### Step 10: %-formatting 格式化列印\n透過% 運算符號,將在元組(tuple)中的一組變量依照指定的格式化方式輸出。如 %s(字串)、%d (十進位整數)、 %f(浮點數)",
"_____no_output_____"
]
],
[
[
"A = 435; B = 59.058\nprint('Art: %5d, Price per Unit: %8.2f' % (A, B))",
"_____no_output_____"
],
[
"FirstName = \"Mary\"; LastName= \"Lin\"\nprint(\"She is %s %s\" %(FirstName, LastName))",
"She is Mary Lin\n"
]
],
[
[
"### Step 11: str-format(Python 2.6+)格式化列印",
"_____no_output_____"
]
],
[
[
"A = 435; B = 59.058\nprint(\"Art: {0:5d}, Price per Unit: {1:8.2f}\".format(435, 59.058))",
"_____no_output_____"
],
[
"FirstName = \"Mary\"; LastName= \"Lin\"\nprint(\"She is {} {}\".format(FirstName, LastName))",
"She is Mary Lin\n"
]
],
[
[
"### Step 12: f-string (Python 3.6+)格式化列印",
"_____no_output_____"
]
],
[
[
"A = 435; B = 59.058\nprint(f\"Art:{A:5d}, Price per Unit: {B:8.2f}\")",
"_____no_output_____"
],
[
"FirstName = \"Mary\"; LastName= \"Lin\"\nprint(f\"She is {FirstName} {LastName}\")",
"She is Mary Lin\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
d08112571af4c69d36aae01a4c2cd53da5015abc | 4,147 | ipynb | Jupyter Notebook | examples/insolver_pipeline/predict.ipynb | MindSetLib/Insolver | decca7f0c03943a253a9af09ed60f0fbeff6e7f5 | [
"MIT"
] | 7 | 2021-01-28T10:49:14.000Z | 2021-11-17T19:48:27.000Z | examples/insolver_pipeline/predict.ipynb | MindSetLib/Insolver | decca7f0c03943a253a9af09ed60f0fbeff6e7f5 | [
"MIT"
] | 3 | 2021-11-13T14:47:51.000Z | 2021-12-03T13:42:23.000Z | examples/insolver_pipeline/predict.ipynb | MindSetLib/Insolver | decca7f0c03943a253a9af09ed60f0fbeff6e7f5 | [
"MIT"
] | null | null | null | 24.684524 | 85 | 0.561611 | [
[
[
"import pandas as pd\nfrom insolver.wrappers import InsolverGLMWrapper",
"_____no_output_____"
],
[
"test = pd.read_csv('data/test.csv', low_memory=False)",
"_____no_output_____"
],
[
"iglm = InsolverGLMWrapper(backend='sklearn', load_path='data/GLM.model')",
"_____no_output_____"
],
[
"predict_glm = iglm.predict(test)\n\nprint(predict_glm)",
"[2436.79705752 2383.88496771 1960.93471514 ... 1888.28571723 2231.56034088\n 2193.73967469]"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code"
]
] |
d0811b960f4182941945669591510fe724d67d09 | 8,567 | ipynb | Jupyter Notebook | 3-b.ipynb | ANadali/PR-HW4 | c88c8db24c6e28de6302acb8b5646376948276c2 | [
"MIT"
] | null | null | null | 3-b.ipynb | ANadali/PR-HW4 | c88c8db24c6e28de6302acb8b5646376948276c2 | [
"MIT"
] | null | null | null | 3-b.ipynb | ANadali/PR-HW4 | c88c8db24c6e28de6302acb8b5646376948276c2 | [
"MIT"
] | null | null | null | 25.726727 | 104 | 0.391386 | [
[
[
"import csv\nfrom sklearn import preprocessing\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import stats\n%matplotlib inline",
"_____no_output_____"
],
[
"datContent = [i.strip().split() for i in open(\"./doughs.dat\").readlines()]",
"_____no_output_____"
],
[
"y=np.array(datContent[1:])",
"_____no_output_____"
],
[
"labels = y[:,7].astype(np.float32)\ny = y[:,1:7].astype(np.float32)",
"_____no_output_____"
],
[
"labels",
"_____no_output_____"
],
[
"class pca:\n def __init__(self,k,scaling = False, ratio = False):\n \n self.k = k\n \n self.scaling = scaling\n \n self.ratio = ratio\n \n \n def EV(self,y):\n \n if self.scaling:\n \n scaler = preprocessing.StandardScaler().fit(y)\n \n y=scaler.transform(y)\n \n else:\n \n y = y - y.mean(axis=0)\n \n self.y = y\n \n s = (y.shape[0]-1)*np.cov(y.T)\n \n l, v = np.linalg.eig(s)\n \n self.v = v[:self.k]\n \n if self.ratio:\n \n print(l[:self.k]/np.sum(l))\n \n \n return l[:self.k],v[:self.k]\n \n def pdata(self):\n \n self.pdata1 = np.dot(self.y,np.array(self.v).T)\n \n return self.pdata1\n \n def mse(self):\n \n self.pdata1 = np.dot(self.y,np.array(self.v).T)\n \n e = (self.y - np.dot(self.pdata1,self.v))**2\n \n e = e.mean()\n \n return e\n \n def Scatter3D(self,labels):\n \n l = np.ones(labels.shape[0])\n \n for i in range(labels.shape[0]):\n \n if labels[i] >= 5:\n \n l[i]=0\n \n fig = plt.figure()\n \n ax = fig.add_subplot(111, projection='3d')\n \n for i in range(self.pdata1.shape[0]):\n \n if l[i]==1:\n m='^'\n c='b'\n else:\n m='o'\n c='r'\n ax.scatter(self.pdata1[i,0], self.pdata1[i,1], self.pdata1[i,2], marker=m, color=c)\n \n def Scatter2D(self,labels):\n \n l = np.ones(labels.shape[0])\n \n for i in range(labels.shape[0]):\n \n if labels[i] >= 5:\n \n l[i]=0\n \n fig = plt.figure()\n \n ax = fig.add_subplot(131)\n \n for i in range(self.pdata1.shape[0]):\n \n if l[i]==1:\n m='^'\n c='b'\n else:\n m='o'\n c='r'\n ax.scatter(self.pdata1[i,0],self.pdata1[i,1], marker=m, color=c)\n \n ax1 = fig.add_subplot(132)\n \n for i in range(self.pdata1.shape[0]):\n \n if l[i]==1:\n m='^'\n c='b'\n else:\n m='o'\n c='r'\n ax1.scatter(self.pdata1[i,0], self.pdata1[i,2], marker=m, color=c)\n \n ax2 = fig.add_subplot(133)\n \n for i in range(self.pdata1.shape[0]):\n \n if l[i]==1:\n m='^'\n c='b'\n else:\n m='o'\n c='r'\n ax2.scatter(self.pdata1[i,1], self.pdata1[i,2],marker=m, color=c)",
"_____no_output_____"
],
[
"p = pca(6)",
"_____no_output_____"
],
[
"p.__init__(8,scaling=False,ratio=True)",
"_____no_output_____"
],
[
"p.EV(y)",
"[7.27853968e-01 2.65871191e-01 4.58266614e-03 1.39994859e-03\n 2.40478634e-04 5.17475048e-05]\n"
],
[
"p.mse()",
"_____no_output_____"
],
[
"x = p.pdata()",
"_____no_output_____"
],
[
"k2, p = stats.normaltest(x)\np",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d08125dce24cde1030940178586f65c7442659b5 | 90,070 | ipynb | Jupyter Notebook | topic_modelling_secondary.ipynb | Living-with-machines/lwm_ARTIDIGH_2020_OCR_impact_downstream_NLP_tasks | 1b2027f624f457bda734e547378ec725bb5a0881 | [
"CC-BY-4.0"
] | 5 | 2020-04-26T20:34:02.000Z | 2021-06-17T12:34:24.000Z | topic_modelling_secondary.ipynb | alan-turing-institute/lwm_ARTIDIGH_2020_OCR_impact_downstream_NLP_tasks | 1b2027f624f457bda734e547378ec725bb5a0881 | [
"CC-BY-4.0"
] | null | null | null | topic_modelling_secondary.ipynb | alan-turing-institute/lwm_ARTIDIGH_2020_OCR_impact_downstream_NLP_tasks | 1b2027f624f457bda734e547378ec725bb5a0881 | [
"CC-BY-4.0"
] | 1 | 2020-06-12T12:26:20.000Z | 2020-06-12T12:26:20.000Z | 259.567723 | 42,596 | 0.910681 | [
[
[
"## Topic Modelling (joint plots by quality band)\n\nShorter notebook just for Figures 9 and 10 in the paper.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport matplotlib.pyplot as plt\n\n# magics and warnings\n%load_ext autoreload\n%autoreload 2\nimport warnings; warnings.simplefilter('ignore')\n\nimport os, random\nfrom tqdm import tqdm\nimport pandas as pd\nimport numpy as np\n\nseed = 43\nrandom.seed(seed)\nnp.random.seed(seed)\n\nimport nltk, gensim, sklearn, spacy\nfrom gensim.models import CoherenceModel\nimport matplotlib.pyplot as plt\nimport pyLDAvis.gensim\nimport seaborn as sns\nsns.set(style=\"white\")",
"_____no_output_____"
]
],
[
[
"### Load the dataset\n\nCreated with the main Topic Modelling notebook.",
"_____no_output_____"
]
],
[
[
"bands_data = {x:dict() for x in range(1,5)}",
"_____no_output_____"
],
[
"import pickle, os\n\nfor band in range(1,5):\n with open(\"trove_overproof/models/hum_band_%d.pkl\"%band, 'rb') as handle:\n bands_data[band][\"model_human\"] = pickle.load(handle)\n with open(\"trove_overproof/models/corpus_hum_band_%d.pkl\"%band, 'rb') as handle:\n bands_data[band][\"corpus_human\"] = pickle.load(handle)\n with open(\"trove_overproof/models/dictionary_hum_band_%d.pkl\"%band, 'rb') as handle:\n bands_data[band][\"dictionary_human\"] = pickle.load(handle)\n with open(\"trove_overproof/models/ocr_band_%d.pkl\"%band, 'rb') as handle:\n bands_data[band][\"model_ocr\"] = pickle.load(handle)\n with open(\"trove_overproof/models/corpus_ocr_band_%d.pkl\"%band, 'rb') as handle:\n bands_data[band][\"corpus_ocr\"] = pickle.load(handle)\n with open(\"trove_overproof/models/dictionary_ocr_band_%d.pkl\"%band, 'rb') as handle:\n bands_data[band][\"dictionary_ocr\"] = pickle.load(handle)",
"_____no_output_____"
]
],
[
[
"### Evaluation",
"_____no_output_____"
],
[
"#### Intrinsic eval\n\nSee http://qpleple.com/topic-coherence-to-evaluate-topic-models.",
"_____no_output_____"
]
],
[
[
"for band in range(1,5):\n \n print(\"Quality band\",band)\n # Human\n # Compute Perplexity\n print('\\nPerplexity (Human): ', bands_data[band][\"model_human\"].log_perplexity(bands_data[band][\"corpus_human\"])) # a measure of how good the model is. The lower the better.\n\n # Compute Coherence Score\n coherence_model_lda = CoherenceModel(model=bands_data[band][\"model_human\"], corpus=bands_data[band][\"corpus_human\"], dictionary=bands_data[band][\"dictionary_human\"], coherence='u_mass')\n coherence_lda = coherence_model_lda.get_coherence()\n print('\\nCoherence Score (Human): ', coherence_lda)\n \n # OCR\n # Compute Perplexity\n print('\\nPerplexity (OCR): ', bands_data[band][\"model_ocr\"].log_perplexity(bands_data[band][\"corpus_ocr\"])) # a measure of how good the model is. The lower the better.\n\n # Compute Coherence Score\n coherence_model_lda = CoherenceModel(model=bands_data[band][\"model_ocr\"], corpus=bands_data[band][\"corpus_ocr\"], dictionary=bands_data[band][\"dictionary_ocr\"], coherence='u_mass')\n coherence_lda = coherence_model_lda.get_coherence()\n print('\\nCoherence Score (OCR): ', coherence_lda)\n print(\"==========\\n\")",
"Quality band 1\n\nPerplexity (Human): -8.103261158627364\n\nCoherence Score (Human): -1.636788533548382\n\nPerplexity (OCR): -8.602782438888957\n\nCoherence Score (OCR): -1.744833949213988\n==========\n\nQuality band 2\n\nPerplexity (Human): -8.210335723784008\n\nCoherence Score (Human): -1.717423902243484\n\nPerplexity (OCR): -8.960456087224186\n\nCoherence Score (OCR): -1.8652779401051685\n==========\n\nQuality band 3\n\nPerplexity (Human): -7.945579058932222\n\nCoherence Score (Human): -2.2853392147627445\n\nPerplexity (OCR): -8.57412651382853\n\nCoherence Score (OCR): -2.1544280903218933\n==========\n\nQuality band 4\n\nPerplexity (Human): -7.610617401464275\n\nCoherence Score (Human): -2.6515871055832645\n\nPerplexity (OCR): -7.973356022098555\n\nCoherence Score (OCR): -2.8655108395602737\n==========\n\n"
]
],
[
[
"#### Match of topics\n\nWe match every topic in the OCR model with a topic in the human model (by best matching), and assess the overall distance between the two using the weighted total distance over a set of N top words (from the human model to the ocr model). The higher this value, the closest two topics are.\n\nNote that to find a matching, we create a weighted network and find the maximal bipartite matching using NetworkX.\n\nAfterwards, we can measure the distance of the best match, e.g., using the KL divergence (over the same set of words).",
"_____no_output_____"
]
],
[
[
"import networkx as nx\nfrom scipy.stats import entropy\nfrom collections import defaultdict\n\n# analyse matches\n\ndistances = {x:list() for x in range(1,5)}\nn_words_in_common = {x:list() for x in range(1,5)}\nmatches = {x:defaultdict(int) for x in range(1,5)}\ntop_n = 500\n\nfor band in range(1,5):\n \n G = nx.Graph()\n model_human = bands_data[band][\"model_human\"]\n model_ocr = bands_data[band][\"model_ocr\"]\n\n # add bipartite nodes\n G.add_nodes_from(['h_'+str(t_h[0]) for t_h in model_human.show_topics(num_topics = -1, formatted=False, num_words=1)], bipartite=0)\n G.add_nodes_from(['o_'+str(t_o[0]) for t_o in model_ocr.show_topics(num_topics = -1, formatted=False, num_words=1)], bipartite=1)\n\n # add weighted edges\n for t_h in model_human.show_topics(num_topics = -1, formatted=False, num_words=top_n):\n for t_o in model_ocr.show_topics(num_topics = -1, formatted=False, num_words=top_n):\n # note that the higher the weight, the shorter the distance between the two distributions, so we do 1-weight to then do minimal matching\n words_of_h = [x[0] for x in t_h[1]]\n words_of_o = [x[0] for x in t_o[1]]\n weights_of_o = {x[0]:x[1] for x in t_o[1]}\n words_in_common = list(set(words_of_h).intersection(set(words_of_o)))\n # sum the weighted joint probability of every shared word in the two models\n avg_weight = 1 - sum([x[1]*weights_of_o[x[0]] for x in t_h[1] if x[0] in words_in_common])\n G.add_edge('h_'+str(t_h[0]),'o_'+str(t_o[0]),weight=avg_weight)\n G.add_edge('o_'+str(t_o[0]),'h_'+str(t_h[0]),weight=avg_weight)\n \n bipartite_solution = nx.bipartite.matching.minimum_weight_full_matching(G)\n \n # calculate distances\n for match_h,match_o in bipartite_solution.items():\n if match_h.startswith('o'): # to avoid repeating the matches (complete graph!)\n break\n matches[band][int(match_h.split(\"_\")[1])] = int(match_o.split(\"_\")[1])\n m_h = model_human.show_topic(int(match_h.split(\"_\")[1]), topn=top_n)\n m_o = model_ocr.show_topic(int(match_o.split(\"_\")[1]), topn=top_n)\n weights_of_o = {x[0]:x[1] for x in m_o}\n words_of_h = [x[0] for x in m_h]\n words_of_o = [x[0] for x in m_o]\n words_in_common = list(set(words_of_h).intersection(set(words_of_o)))\n n_words_in_common[band].append(len(words_in_common)/top_n)\n dist_h = list()\n dist_o = list()\n for w in m_h:\n if w[0] in words_in_common:\n dist_h.append(w[1])\n dist_o.append(weights_of_o[w[0]])\n # normalize\n dist_h = dist_h/sum(dist_h)\n dist_o = dist_o/sum(dist_o)\n dist = entropy(dist_h,dist_o)\n distances[band].append(dist)",
"_____no_output_____"
],
[
"sns.set_context(\"notebook\", font_scale=1.2, rc={\"lines.linewidth\": 2.5})",
"_____no_output_____"
],
[
"# Figure 9\nfor band in range(1,5):\n sns.distplot(distances[band], hist=False, label=\"Quality band %d\"%band)\nplt.xlim((0,1))\nplt.xlabel(\"KL divergence between topics, V=%d.\"%top_n)\nplt.tight_layout()\nplt.savefig(\"figures/topic_modelling/KL_divergence_topics.pdf\")",
"_____no_output_____"
],
[
"# Figure 10\nfor band in range(1,5):\n sns.distplot(n_words_in_common[band], hist=False, label=\"Quality band %d\"%band)\nplt.xlim((0,1))\nplt.tight_layout()\nplt.savefig(\"figures/topic_modelling/Words_in_common_topics.pdf\")",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
d08129d469930a40eee2ecacec560432ab87d438 | 4,233 | ipynb | Jupyter Notebook | WCAStats/Choking.ipynb | albertkyou/CubingStats | c3f7ed933eeea2c9f56af5e281972adf0734cbbd | [
"MIT"
] | null | null | null | WCAStats/Choking.ipynb | albertkyou/CubingStats | c3f7ed933eeea2c9f56af5e281972adf0734cbbd | [
"MIT"
] | null | null | null | WCAStats/Choking.ipynb | albertkyou/CubingStats | c3f7ed933eeea2c9f56af5e281972adf0734cbbd | [
"MIT"
] | null | null | null | 37.131579 | 1,356 | 0.606426 | [
[
[
"import numpy as np \nimport matplotlib.pyplot as plt \nimport scipy.stats as stats \nimport pandas as pd \n\nrankings = pd.read_csv('WCA_export_RanksAverage.tsv', '\\t')\nrankings.eventId = rankings.eventId.astype(str)\nthreespeedrankings = rankings.loc[rankings['eventId']=='333']\n\n# get the personIds for the top 10 cubers in the world\nbestcubers = threespeedrankings['personId'][7400:7500].to_numpy()\n\nprint(bestcubers) # (numpy) list of best cuber IDs\n\n# load complete 3x3 averages \n\ndf = pd.read_csv('WCA_export_Results.tsv','\\t')\nthreespeed = df.loc[df.eventId=='333']\ntoptimes = []\n\nfor cuber in bestcubers:\n temp = threespeed.loc[threespeed.personId==cuber]\n\n temp_times = []\n for round in range(temp.shape[0]):\n if np.min(temp.iloc[round,10:15])>0:\n temp_times.append(temp.iloc[round,np.r_[5,10:15]].to_numpy()/100)\n\n toptimes.append(temp_times)\n\n",
"['2018LAMD02' '2017EATO03' '2018MONT38' '2011MAUL02' '2011HANG01'\n '2019RAMA10' '2018RIYA01' '2018TAIR02' '2018GRAC01' '2015HEFF01'\n '2017SHUL03' '2019CHEN52' '2019ALCH01' '2016SONU01' '2018CRUS01'\n '2010STEV02' '2019MELN01' '2018LIXI12' '2015GAYL01' '2014ZHAN27'\n '2017KHIZ01' '2011DIRK01' '2019KAMA04' '2016HUAN35' '2017JAIN14'\n '2014HUAN07' '2009WOLF01' '2018PARK09' '2016TAKE02' '2019SHIS07'\n '2016TAIH01' '2018VALE16' '2016YILO02' '2017HERN22' '2019BERE05'\n '2019SENG03' '2014RAKS01' '2018AUBR01' '2015MART40' '2017NANC01'\n '2009KASA01' '2017CATI01' '2018JOHN09' '2016BAYA02' '2018LANZ03'\n '2018HERM07' '2018CATU01' '2017RENS02' '2010KEHR01' '2009ADLA01'\n '2018HUNG06' '2016SARM07' '2015ZHUW02' '2015KALR01' '2017PALE01'\n '2016JAYV01' '2017FATH02' '2009SMIT01' '2018MIKL02' '2017VERA03'\n '2008CHEN06' '2019MUNO03' '2017WANK05' '2018YANG76' '2010BENI02'\n '2017NAMH03' '2016LAHT01' '2019MEND01' '2016WANB02' '2018BOGN01'\n '2016MEND07' '2015WUMI01' '2016BOCK01' '2015SIAM01' '2018CHEN84'\n '2008BELL02' '2018LUDE01' '2016CHAN26' '2019GUOM02' '2014SHAS02'\n '2012TORR07' '2016DERM01' '2018GLAD05' '2013WIND01' '2016JIME02'\n '2019RUBE01' '2018HOAN05' '2014REID01' '2017PRAA01' '2017WOOD01'\n '2016LIUJ10' '2017RAMI08' '2016MAIL01' '2017MIKH01' '2017ADIT02'\n '2017GARC55' '2015WANG28' '2019NGUY04' '2016DENE01' '2016MACH01']\n"
],
[
"faz = toptimes[10]\nfazmin=[]\nfazmax = []\nfor round in range(len(faz)):\n faz[round] = faz[round]/faz[round][0]\n temp_min = np.where(faz[round]==np.min(faz[round]))\n fazmin.append(temp_min[0][0])\n\n temp_max = np.where(faz[round]==np.max(faz[round]))\n fazmax.append(temp_max[0][0])\nfaznp = np.array(faz,dtype=float)\n\nplt.subplot(121)\nplt.hist(fazmin)\nplt.title('Best Time')\nplt.subplot(122)\nplt.hist(fazmax)\nplt.title('Worst Time')",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code"
]
] |
d08142c3a2390d03914f938269c65bee89c81694 | 30,162 | ipynb | Jupyter Notebook | h2o-py/demos/deeplearning.ipynb | jbentleyEG/h2o-3 | 93f1084b5e244beca517b0a1fc8b0c02061d597f | [
"Apache-2.0"
] | 6,098 | 2015-05-22T02:46:12.000Z | 2022-03-31T16:54:51.000Z | h2o-py/demos/deeplearning.ipynb | jbentleyEG/h2o-3 | 93f1084b5e244beca517b0a1fc8b0c02061d597f | [
"Apache-2.0"
] | 2,517 | 2015-05-23T02:10:54.000Z | 2022-03-30T17:03:39.000Z | h2o-py/demos/deeplearning.ipynb | jbentleyEG/h2o-3 | 93f1084b5e244beca517b0a1fc8b0c02061d597f | [
"Apache-2.0"
] | 2,199 | 2015-05-22T04:09:55.000Z | 2022-03-28T22:20:45.000Z | 32.927948 | 196 | 0.377627 | [
[
[
"import h2o\nfrom h2o.estimators.deeplearning import H2ODeepLearningEstimator",
"_____no_output_____"
],
[
"h2o.init()",
"Warning: Version mismatch. H2O is version 3.5.0.99999, but the python package is version UNKNOWN.\n"
],
[
"from h2o.utils.shared_utils import _locate # private function. used to find files within h2o git project directory.\n\nprostate = h2o.upload_file(path=_locate(\"smalldata/logreg/prostate.csv\"))\nprostate.describe()",
"\nParse Progress: [##################################################] 100%\nUploaded py2a71800e-2ec6-4f71-b955-854a4f22aeb3 into cluster with 380 rows and 9 cols\nRows: 380 Cols: 9\n\nChunk compression summary:\n"
],
[
"prostate[\"CAPSULE\"] = prostate[\"CAPSULE\"].asfactor()\nmodel = H2ODeepLearningEstimator(activation = \"Tanh\", hidden = [10, 10, 10], epochs = 10000)\nmodel.train(x = list(set(prostate.columns) - set([\"ID\",\"CAPSULE\"])), y =\"CAPSULE\", training_frame = prostate)\nmodel.show()",
"\ndeeplearning Model Build Progress: [##################################################] 100%\nModel Details\n=============\nH2ODeepLearningEstimator : Deep Learning\nModel Key: DeepLearning_model_python_1445544453075_137\n\nStatus of Neuron Layers: predicting CAPSULE, 2-class classification, bernoulli distribution, CrossEntropy loss, 322 weights/biases, 8.5 KB, 3,800,000 training samples, mini-batch size 1\n\n"
],
[
"predictions = model.predict(prostate)\npredictions.show()",
"H2OFrame with 380 rows and 3 columns: \n"
],
[
"performance = model.model_performance(prostate)\nperformance.show()",
"\nModelMetricsBinomial: deeplearning\n** Reported on test data. **\n\nMSE: 0.010708193224\nR^2: 0.955478877615\nLogLoss: 0.0689458344205\nAUC: 0.996804007947\nGini: 0.993608015894\n\nConfusion Matrix (Act/Pred) for max f1 @ threshold = 0.85259659057:\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d0814755da86b7ed1321be609fc277faa0a4c364 | 31,105 | ipynb | Jupyter Notebook | samples/nucleus/inspect_nucleus_data.ipynb | zgle-fork/Mask_RCNN | 7f3956d1d702e0f63485f841255222af40ee7799 | [
"MIT"
] | null | null | null | samples/nucleus/inspect_nucleus_data.ipynb | zgle-fork/Mask_RCNN | 7f3956d1d702e0f63485f841255222af40ee7799 | [
"MIT"
] | null | null | null | samples/nucleus/inspect_nucleus_data.ipynb | zgle-fork/Mask_RCNN | 7f3956d1d702e0f63485f841255222af40ee7799 | [
"MIT"
] | null | null | null | 35.028153 | 319 | 0.567369 | [
[
[
"# Inspect Nucleus Training Data\n\nInspect and visualize data loading and pre-processing code.\n\nhttps://www.kaggle.com/c/data-science-bowl-2018",
"_____no_output_____"
]
],
[
[
"import os\nimport sys\nimport itertools\nimport math\nimport logging\nimport json\nimport re\nimport random\nimport time\nimport concurrent.futures\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport matplotlib.lines as lines\nfrom matplotlib.patches import Polygon\nimport imgaug\nfrom imgaug import augmenters as iaa\n\n# Root directory of the project\nROOT_DIR = os.getcwd()\nprint(\"ROOT_DIR\",ROOT_DIR) \n\nif ROOT_DIR.endswith(\"nucleus\"):\n # Go up two levels to the repo root\n ROOT_DIR = os.path.dirname(os.path.dirname(ROOT_DIR))\nprint(\"ROOT_DIR\",ROOT_DIR) \n\n# Import Mask RCNN\nsys.path.append(ROOT_DIR)\nfrom mrcnn import utils\nfrom mrcnn import visualize\nfrom mrcnn.visualize import display_images\nfrom mrcnn import model as modellib\nfrom mrcnn.model import log\n\nimport nucleus\n\n%matplotlib inline ",
"ROOT_DIR C:\\_me\\Code\\2_github\\3_zglezgle\\AI-Generic\\Mask-R-CNN\\Mask_RCNN\\samples\\nucleus\nROOT_DIR C:\\_me\\Code\\2_github\\3_zglezgle\\AI-Generic\\Mask-R-CNN\\Mask_RCNN\n"
],
[
"# Comment out to reload imported modules if they change\n# %load_ext autoreload\n# %autoreload 2",
"_____no_output_____"
]
],
[
[
"## Configurations",
"_____no_output_____"
]
],
[
[
"# Dataset directory\nDATASET_DIR = os.path.join(ROOT_DIR, \"datasets/nucleus\")\n\n# Use configuation from nucleus.py, but override\n# image resizing so we see the real sizes here\nclass NoResizeConfig(nucleus.NucleusConfig):\n IMAGE_RESIZE_MODE = \"none\"\n \nconfig = NoResizeConfig()",
"_____no_output_____"
]
],
[
[
"## Notebook Preferences",
"_____no_output_____"
]
],
[
[
"def get_ax(rows=1, cols=1, size=16):\n \"\"\"Return a Matplotlib Axes array to be used in\n all visualizations in the notebook. Provide a\n central point to control graph sizes.\n \n Adjust the size attribute to control how big to render images\n \"\"\"\n _, ax = plt.subplots(rows, cols, figsize=(size*cols, size*rows))\n return ax",
"_____no_output_____"
]
],
[
[
"## Dataset\n\nDownload the dataset from the competition Website. Unzip it and save it in `mask_rcnn/datasets/nucleus`. If you prefer a different directory then change the `DATASET_DIR` variable above.\n\nhttps://www.kaggle.com/c/data-science-bowl-2018/data",
"_____no_output_____"
]
],
[
[
"# Load dataset\ndataset = nucleus.NucleusDataset()\n# The subset is the name of the sub-directory, such as stage1_train,\n# stage1_test, ...etc. You can also use these special values:\n# train: loads stage1_train but excludes validation images\n# val: loads validation images from stage1_train. For a list\n# of validation images see nucleus.py\ndataset.load_nucleus(DATASET_DIR, subset=\"train\")\n\n# Must call before using the dataset\ndataset.prepare()\n\nprint(\"Image Count: {}\".format(len(dataset.image_ids)))\nprint(\"Class Count: {}\".format(dataset.num_classes))\nfor i, info in enumerate(dataset.class_info):\n print(\"{:3}. {:50}\".format(i, info['name']))",
"_____no_output_____"
]
],
[
[
"## Display Samples",
"_____no_output_____"
]
],
[
[
"# Load and display random samples\nimage_ids = np.random.choice(dataset.image_ids, 4)\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, limit=1)",
"_____no_output_____"
],
[
"# Example of loading a specific image by its source ID\nsource_id = \"ed5be4b63e9506ad64660dd92a098ffcc0325195298c13c815a73773f1efc279\"\n\n# Map source ID to Dataset image_id\n# Notice the nucleus prefix: it's the name given to the dataset in NucleusDataset\nimage_id = dataset.image_from_source_map[\"nucleus.{}\".format(source_id)]\n\n# Load and display\nimage, image_meta, class_ids, bbox, mask = modellib.load_image_gt(\n dataset, config, image_id, use_mini_mask=False)\nlog(\"molded_image\", image)\nlog(\"mask\", mask)\nvisualize.display_instances(image, bbox, mask, class_ids, dataset.class_names,\n show_bbox=False)",
"_____no_output_____"
]
],
[
[
"## Dataset Stats\n\nLoop through all images in the dataset and collect aggregate stats.",
"_____no_output_____"
]
],
[
[
"def image_stats(image_id):\n \"\"\"Returns a dict of stats for one image.\"\"\"\n image = dataset.load_image(image_id)\n mask, _ = dataset.load_mask(image_id)\n bbox = utils.extract_bboxes(mask)\n # Sanity check\n assert mask.shape[:2] == image.shape[:2]\n # Return stats dict\n return {\n \"id\": image_id,\n \"shape\": list(image.shape),\n \"bbox\": [[b[2] - b[0], b[3] - b[1]]\n for b in bbox\n # Uncomment to exclude nuclei with 1 pixel width\n # or height (often on edges)\n # if b[2] - b[0] > 1 and b[3] - b[1] > 1\n ],\n \"color\": np.mean(image, axis=(0, 1)),\n }\n\n# Loop through the dataset and compute stats over multiple threads\n# This might take a few minutes\nt_start = time.time()\nwith concurrent.futures.ThreadPoolExecutor() as e:\n stats = list(e.map(image_stats, dataset.image_ids))\nt_total = time.time() - t_start\nprint(\"Total time: {:.1f} seconds\".format(t_total))",
"_____no_output_____"
]
],
[
[
"### Image Size Stats",
"_____no_output_____"
]
],
[
[
"# Image stats\nimage_shape = np.array([s['shape'] for s in stats])\nimage_color = np.array([s['color'] for s in stats])\nprint(\"Image Count: \", image_shape.shape[0])\nprint(\"Height mean: {:.2f} median: {:.2f} min: {:.2f} max: {:.2f}\".format(\n np.mean(image_shape[:, 0]), np.median(image_shape[:, 0]),\n np.min(image_shape[:, 0]), np.max(image_shape[:, 0])))\nprint(\"Width mean: {:.2f} median: {:.2f} min: {:.2f} max: {:.2f}\".format(\n np.mean(image_shape[:, 1]), np.median(image_shape[:, 1]),\n np.min(image_shape[:, 1]), np.max(image_shape[:, 1])))\nprint(\"Color mean (RGB): {:.2f} {:.2f} {:.2f}\".format(*np.mean(image_color, axis=0)))\n\n# Histograms\nfig, ax = plt.subplots(1, 3, figsize=(16, 4))\nax[0].set_title(\"Height\")\n_ = ax[0].hist(image_shape[:, 0], bins=20)\nax[1].set_title(\"Width\")\n_ = ax[1].hist(image_shape[:, 1], bins=20)\nax[2].set_title(\"Height & Width\")\n_ = ax[2].hist2d(image_shape[:, 1], image_shape[:, 0], bins=10, cmap=\"Blues\")",
"_____no_output_____"
]
],
[
[
"### Nuclei per Image Stats",
"_____no_output_____"
]
],
[
[
"# Segment by image area\nimage_area_bins = [256**2, 600**2, 1300**2]\n\nprint(\"Nuclei/Image\")\nfig, ax = plt.subplots(1, len(image_area_bins), figsize=(16, 4))\narea_threshold = 0\nfor i, image_area in enumerate(image_area_bins):\n nuclei_per_image = np.array([len(s['bbox']) \n for s in stats \n if area_threshold < (s['shape'][0] * s['shape'][1]) <= image_area])\n area_threshold = image_area\n if len(nuclei_per_image) == 0:\n print(\"Image area <= {:4}**2: None\".format(np.sqrt(image_area)))\n continue\n print(\"Image area <= {:4.0f}**2: mean: {:.1f} median: {:.1f} min: {:.1f} max: {:.1f}\".format(\n np.sqrt(image_area), nuclei_per_image.mean(), np.median(nuclei_per_image), \n nuclei_per_image.min(), nuclei_per_image.max()))\n ax[i].set_title(\"Image Area <= {:4}**2\".format(np.sqrt(image_area)))\n _ = ax[i].hist(nuclei_per_image, bins=10)",
"_____no_output_____"
]
],
[
[
"### Nuclei Size Stats",
"_____no_output_____"
]
],
[
[
"# Nuclei size stats\nfig, ax = plt.subplots(1, len(image_area_bins), figsize=(16, 4))\narea_threshold = 0\nfor i, image_area in enumerate(image_area_bins):\n nucleus_shape = np.array([\n b \n for s in stats if area_threshold < (s['shape'][0] * s['shape'][1]) <= image_area\n for b in s['bbox']])\n nucleus_area = nucleus_shape[:, 0] * nucleus_shape[:, 1]\n area_threshold = image_area\n\n print(\"\\nImage Area <= {:.0f}**2\".format(np.sqrt(image_area)))\n print(\" Total Nuclei: \", nucleus_shape.shape[0])\n print(\" Nucleus Height. mean: {:.2f} median: {:.2f} min: {:.2f} max: {:.2f}\".format(\n np.mean(nucleus_shape[:, 0]), np.median(nucleus_shape[:, 0]),\n np.min(nucleus_shape[:, 0]), np.max(nucleus_shape[:, 0])))\n print(\" Nucleus Width. mean: {:.2f} median: {:.2f} min: {:.2f} max: {:.2f}\".format(\n np.mean(nucleus_shape[:, 1]), np.median(nucleus_shape[:, 1]),\n np.min(nucleus_shape[:, 1]), np.max(nucleus_shape[:, 1])))\n print(\" Nucleus Area. mean: {:.2f} median: {:.2f} min: {:.2f} max: {:.2f}\".format(\n np.mean(nucleus_area), np.median(nucleus_area),\n np.min(nucleus_area), np.max(nucleus_area)))\n\n # Show 2D histogram\n _ = ax[i].hist2d(nucleus_shape[:, 1], nucleus_shape[:, 0], bins=20, cmap=\"Blues\")",
"_____no_output_____"
],
[
"# Nuclei height/width ratio\nnucleus_aspect_ratio = nucleus_shape[:, 0] / nucleus_shape[:, 1]\nprint(\"Nucleus Aspect Ratio. mean: {:.2f} median: {:.2f} min: {:.2f} max: {:.2f}\".format(\n np.mean(nucleus_aspect_ratio), np.median(nucleus_aspect_ratio),\n np.min(nucleus_aspect_ratio), np.max(nucleus_aspect_ratio)))\nplt.figure(figsize=(15, 5))\n_ = plt.hist(nucleus_aspect_ratio, bins=100, range=[0, 5])",
"_____no_output_____"
]
],
[
[
"## Image Augmentation\n\nTest out different augmentation methods",
"_____no_output_____"
]
],
[
[
"# List of augmentations\n# http://imgaug.readthedocs.io/en/latest/source/augmenters.html\naugmentation = iaa.Sometimes(0.9, [\n iaa.Fliplr(0.5),\n iaa.Flipud(0.5),\n iaa.Multiply((0.8, 1.2)),\n iaa.GaussianBlur(sigma=(0.0, 5.0))\n])",
"_____no_output_____"
],
[
"# Load the image multiple times to show augmentations\nlimit = 4\nax = get_ax(rows=2, cols=limit//2)\nfor i in range(limit):\n image, image_meta, class_ids, bbox, mask = modellib.load_image_gt(\n dataset, config, image_id, use_mini_mask=False, augment=False, augmentation=augmentation)\n visualize.display_instances(image, bbox, mask, class_ids,\n dataset.class_names, ax=ax[i//2, i % 2],\n show_mask=False, show_bbox=False)",
"_____no_output_____"
]
],
[
[
"## Image Crops\n\nMicroscoy images tend to be large, but nuclei are small. So it's more efficient to train on random crops from large images. This is handled by `config.IMAGE_RESIZE_MODE = \"crop\"`.\n\n",
"_____no_output_____"
]
],
[
[
"class RandomCropConfig(nucleus.NucleusConfig):\n IMAGE_RESIZE_MODE = \"crop\"\n IMAGE_MIN_DIM = 256\n IMAGE_MAX_DIM = 256\n\ncrop_config = RandomCropConfig()",
"_____no_output_____"
],
[
"# Load the image multiple times to show augmentations\nlimit = 4\nimage_id = np.random.choice(dataset.image_ids, 1)[0]\nax = get_ax(rows=2, cols=limit//2)\nfor i in range(limit):\n image, image_meta, class_ids, bbox, mask = modellib.load_image_gt(\n dataset, crop_config, image_id, use_mini_mask=False)\n visualize.display_instances(image, bbox, mask, class_ids,\n dataset.class_names, ax=ax[i//2, i % 2],\n show_mask=False, show_bbox=False)",
"_____no_output_____"
]
],
[
[
"## Mini Masks\n\nInstance binary masks can get large when training with high resolution images. For example, if training with 1024x1024 image then the mask of a single instance requires 1MB of memory (Numpy uses bytes for boolean values). If an image has 100 instances then that's 100MB for the masks alone. \n\nTo improve training speed, we optimize masks:\n* We store mask pixels that are inside the object bounding box, rather than a mask of the full image. Most objects are small compared to the image size, so we save space by not storing a lot of zeros around the object.\n* We resize the mask to a smaller size (e.g. 56x56). For objects that are larger than the selected size we lose a bit of accuracy. But most object annotations are not very accuracy to begin with, so this loss is negligable for most practical purposes. Thie size of the mini_mask can be set in the config class.\n\nTo visualize the effect of mask resizing, and to verify the code correctness, we visualize some examples.",
"_____no_output_____"
]
],
[
[
"# Load random image and mask.\nimage_id = np.random.choice(dataset.image_ids, 1)[0]\nimage = dataset.load_image(image_id)\nmask, class_ids = dataset.load_mask(image_id)\noriginal_shape = image.shape\n# Resize\nimage, window, scale, padding, _ = utils.resize_image(\n image, \n min_dim=config.IMAGE_MIN_DIM, \n max_dim=config.IMAGE_MAX_DIM,\n mode=config.IMAGE_RESIZE_MODE)\nmask = utils.resize_mask(mask, scale, padding)\n# Compute Bounding box\nbbox = utils.extract_bboxes(mask)\n\n# Display image and additional stats\nprint(\"image_id: \", image_id, dataset.image_reference(image_id))\nprint(\"Original shape: \", original_shape)\nlog(\"image\", image)\nlog(\"mask\", mask)\nlog(\"class_ids\", class_ids)\nlog(\"bbox\", bbox)\n# Display image and instances\nvisualize.display_instances(image, bbox, mask, class_ids, dataset.class_names)",
"_____no_output_____"
],
[
"image_id = np.random.choice(dataset.image_ids, 1)[0]\nimage, image_meta, class_ids, bbox, mask = modellib.load_image_gt(\n dataset, config, image_id, use_mini_mask=False)\n\nlog(\"image\", image)\nlog(\"image_meta\", image_meta)\nlog(\"class_ids\", class_ids)\nlog(\"bbox\", bbox)\nlog(\"mask\", mask)\n\ndisplay_images([image]+[mask[:,:,i] for i in range(min(mask.shape[-1], 7))])",
"_____no_output_____"
],
[
"visualize.display_instances(image, bbox, mask, class_ids, dataset.class_names)",
"_____no_output_____"
],
[
"# Add augmentation and mask resizing.\nimage, image_meta, class_ids, bbox, mask = modellib.load_image_gt(\n dataset, config, image_id, augment=True, use_mini_mask=True)\nlog(\"mask\", mask)\ndisplay_images([image]+[mask[:,:,i] for i in range(min(mask.shape[-1], 7))])",
"_____no_output_____"
],
[
"mask = utils.expand_mask(bbox, mask, image.shape)\nvisualize.display_instances(image, bbox, mask, class_ids, dataset.class_names)",
"_____no_output_____"
]
],
[
[
"## Anchors\n\nFor an FPN network, the anchors must be ordered in a way that makes it easy to match anchors to the output of the convolution layers that predict anchor scores and shifts. \n* Sort by pyramid level first. All anchors of the first level, then all of the second and so on. This makes it easier to separate anchors by level.\n* Within each level, sort anchors by feature map processing sequence. Typically, a convolution layer processes a feature map starting from top-left and moving right row by row. \n* For each feature map cell, pick any sorting order for the anchors of different ratios. Here we match the order of ratios passed to the function.",
"_____no_output_____"
]
],
[
[
"## Visualize anchors of one cell at the center of the feature map\n\n# Load and display random image\nimage_id = np.random.choice(dataset.image_ids, 1)[0]\nimage, image_meta, _, _, _ = modellib.load_image_gt(dataset, crop_config, image_id)\n\n# Generate Anchors\nbackbone_shapes = modellib.compute_backbone_shapes(config, image.shape)\nanchors = utils.generate_pyramid_anchors(config.RPN_ANCHOR_SCALES, \n config.RPN_ANCHOR_RATIOS,\n backbone_shapes,\n config.BACKBONE_STRIDES, \n config.RPN_ANCHOR_STRIDE)\n\n# Print summary of anchors\nnum_levels = len(backbone_shapes)\nanchors_per_cell = len(config.RPN_ANCHOR_RATIOS)\nprint(\"Count: \", anchors.shape[0])\nprint(\"Scales: \", config.RPN_ANCHOR_SCALES)\nprint(\"ratios: \", config.RPN_ANCHOR_RATIOS)\nprint(\"Anchors per Cell: \", anchors_per_cell)\nprint(\"Levels: \", num_levels)\nanchors_per_level = []\nfor l in range(num_levels):\n num_cells = backbone_shapes[l][0] * backbone_shapes[l][1]\n anchors_per_level.append(anchors_per_cell * num_cells // config.RPN_ANCHOR_STRIDE**2)\n print(\"Anchors in Level {}: {}\".format(l, anchors_per_level[l]))\n\n# Display\nfig, ax = plt.subplots(1, figsize=(10, 10))\nax.imshow(image)\nlevels = len(backbone_shapes)\n\nfor level in range(levels):\n colors = visualize.random_colors(levels)\n # Compute the index of the anchors at the center of the image\n level_start = sum(anchors_per_level[:level]) # sum of anchors of previous levels\n level_anchors = anchors[level_start:level_start+anchors_per_level[level]]\n print(\"Level {}. Anchors: {:6} Feature map Shape: {}\".format(level, level_anchors.shape[0], \n backbone_shapes[level]))\n center_cell = backbone_shapes[level] // 2\n center_cell_index = (center_cell[0] * backbone_shapes[level][1] + center_cell[1])\n level_center = center_cell_index * anchors_per_cell \n center_anchor = anchors_per_cell * (\n (center_cell[0] * backbone_shapes[level][1] / config.RPN_ANCHOR_STRIDE**2) \\\n + center_cell[1] / config.RPN_ANCHOR_STRIDE)\n level_center = int(center_anchor)\n\n # Draw anchors. Brightness show the order in the array, dark to bright.\n for i, rect in enumerate(level_anchors[level_center:level_center+anchors_per_cell]):\n y1, x1, y2, x2 = rect\n p = patches.Rectangle((x1, y1), x2-x1, y2-y1, linewidth=2, facecolor='none',\n edgecolor=(i+1)*np.array(colors[level]) / anchors_per_cell)\n ax.add_patch(p)\n",
"_____no_output_____"
]
],
[
[
"## Data Generator",
"_____no_output_____"
]
],
[
[
"# Create data generator\nrandom_rois = 2000\ng = modellib.data_generator(\n dataset, crop_config, shuffle=True, random_rois=random_rois, \n batch_size=4,\n detection_targets=True)",
"_____no_output_____"
],
[
"# Uncomment to run the generator through a lot of images\n# to catch rare errors\n# for i in range(1000):\n# print(i)\n# _, _ = next(g)",
"_____no_output_____"
],
[
"# Get Next Image\nif random_rois:\n [normalized_images, image_meta, rpn_match, rpn_bbox, gt_class_ids, gt_boxes, gt_masks, rpn_rois, rois], \\\n [mrcnn_class_ids, mrcnn_bbox, mrcnn_mask] = next(g)\n \n log(\"rois\", rois)\n log(\"mrcnn_class_ids\", mrcnn_class_ids)\n log(\"mrcnn_bbox\", mrcnn_bbox)\n log(\"mrcnn_mask\", mrcnn_mask)\nelse:\n [normalized_images, image_meta, rpn_match, rpn_bbox, gt_boxes, gt_masks], _ = next(g)\n \nlog(\"gt_class_ids\", gt_class_ids)\nlog(\"gt_boxes\", gt_boxes)\nlog(\"gt_masks\", gt_masks)\nlog(\"rpn_match\", rpn_match, )\nlog(\"rpn_bbox\", rpn_bbox)\nimage_id = modellib.parse_image_meta(image_meta)[\"image_id\"][0]\nprint(\"image_id: \", image_id, dataset.image_reference(image_id))\n\n# Remove the last dim in mrcnn_class_ids. It's only added\n# to satisfy Keras restriction on target shape.\nmrcnn_class_ids = mrcnn_class_ids[:,:,0]",
"_____no_output_____"
],
[
"b = 0\n\n# Restore original image (reverse normalization)\nsample_image = modellib.unmold_image(normalized_images[b], config)\n\n# Compute anchor shifts.\nindices = np.where(rpn_match[b] == 1)[0]\nrefined_anchors = utils.apply_box_deltas(anchors[indices], rpn_bbox[b, :len(indices)] * config.RPN_BBOX_STD_DEV)\nlog(\"anchors\", anchors)\nlog(\"refined_anchors\", refined_anchors)\n\n# Get list of positive anchors\npositive_anchor_ids = np.where(rpn_match[b] == 1)[0]\nprint(\"Positive anchors: {}\".format(len(positive_anchor_ids)))\nnegative_anchor_ids = np.where(rpn_match[b] == -1)[0]\nprint(\"Negative anchors: {}\".format(len(negative_anchor_ids)))\nneutral_anchor_ids = np.where(rpn_match[b] == 0)[0]\nprint(\"Neutral anchors: {}\".format(len(neutral_anchor_ids)))\n\n# ROI breakdown by class\nfor c, n in zip(dataset.class_names, np.bincount(mrcnn_class_ids[b].flatten())):\n if n:\n print(\"{:23}: {}\".format(c[:20], n))\n\n# Show positive anchors\nfig, ax = plt.subplots(1, figsize=(16, 16))\nvisualize.draw_boxes(sample_image, boxes=anchors[positive_anchor_ids], \n refined_boxes=refined_anchors, ax=ax)",
"_____no_output_____"
],
[
"# Show negative anchors\nvisualize.draw_boxes(sample_image, boxes=anchors[negative_anchor_ids])",
"_____no_output_____"
],
[
"# Show neutral anchors. They don't contribute to training.\nvisualize.draw_boxes(sample_image, boxes=anchors[np.random.choice(neutral_anchor_ids, 100)])",
"_____no_output_____"
]
],
[
[
"## ROIs\n\nTypically, the RPN network generates region proposals (a.k.a. Regions of Interest, or ROIs). The data generator has the ability to generate proposals as well for illustration and testing purposes. These are controlled by the `random_rois` parameter.",
"_____no_output_____"
]
],
[
[
"if random_rois:\n # Class aware bboxes\n bbox_specific = mrcnn_bbox[b, np.arange(mrcnn_bbox.shape[1]), mrcnn_class_ids[b], :]\n\n # Refined ROIs\n refined_rois = utils.apply_box_deltas(rois[b].astype(np.float32), bbox_specific[:,:4] * config.BBOX_STD_DEV)\n\n # Class aware masks\n mask_specific = mrcnn_mask[b, np.arange(mrcnn_mask.shape[1]), :, :, mrcnn_class_ids[b]]\n\n visualize.draw_rois(sample_image, rois[b], refined_rois, mask_specific, mrcnn_class_ids[b], dataset.class_names)\n \n # Any repeated ROIs?\n rows = np.ascontiguousarray(rois[b]).view(np.dtype((np.void, rois.dtype.itemsize * rois.shape[-1])))\n _, idx = np.unique(rows, return_index=True)\n print(\"Unique ROIs: {} out of {}\".format(len(idx), rois.shape[1]))",
"_____no_output_____"
],
[
"if random_rois:\n # Dispalay ROIs and corresponding masks and bounding boxes\n ids = random.sample(range(rois.shape[1]), 8)\n\n images = []\n titles = []\n for i in ids:\n image = visualize.draw_box(sample_image.copy(), rois[b,i,:4].astype(np.int32), [255, 0, 0])\n image = visualize.draw_box(image, refined_rois[i].astype(np.int64), [0, 255, 0])\n images.append(image)\n titles.append(\"ROI {}\".format(i))\n images.append(mask_specific[i] * 255)\n titles.append(dataset.class_names[mrcnn_class_ids[b,i]][:20])\n\n display_images(images, titles, cols=4, cmap=\"Blues\", interpolation=\"none\")",
"_____no_output_____"
],
[
"# Check ratio of positive ROIs in a set of images.\nif random_rois:\n limit = 10\n temp_g = modellib.data_generator(\n dataset, crop_config, shuffle=True, random_rois=10000, \n batch_size=1, detection_targets=True)\n total = 0\n for i in range(limit):\n _, [ids, _, _] = next(temp_g)\n positive_rois = np.sum(ids[0] > 0)\n total += positive_rois\n print(\"{:5} {:5.2f}\".format(positive_rois, positive_rois/ids.shape[1]))\n print(\"Average percent: {:.2f}\".format(total/(limit*ids.shape[1])))",
"_____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",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
d0817070e3b2f912e0ca3991413706d96bbfad06 | 32,932 | ipynb | Jupyter Notebook | 1_Exploration.ipynb | kdonbekci/fashion-flow | 2b0321769f4d0b8f55fe0715aab5c09ad5255945 | [
"MIT"
] | null | null | null | 1_Exploration.ipynb | kdonbekci/fashion-flow | 2b0321769f4d0b8f55fe0715aab5c09ad5255945 | [
"MIT"
] | null | null | null | 1_Exploration.ipynb | kdonbekci/fashion-flow | 2b0321769f4d0b8f55fe0715aab5c09ad5255945 | [
"MIT"
] | null | null | null | 156.075829 | 23,076 | 0.910907 | [
[
[
"from utils import *\nimport h5py",
"_____no_output_____"
],
[
"path = os.path.join(DATA_DIR, 'DeepFashion', 'Fashion Synthesis', 'G2.h5')\nf = h5py.File(path, 'r')",
"_____no_output_____"
],
[
"f.keys()",
"_____no_output_____"
],
[
"segmentation = f.get('b_')",
"_____no_output_____"
],
[
"segmentation.shape",
"_____no_output_____"
],
[
"plt.imshow(segmentation[6, 0].T)",
"_____no_output_____"
],
[
"mean_image = f.get('ih_mean')",
"_____no_output_____"
],
[
"images = f.get('ih')",
"_____no_output_____"
],
[
"images.shape",
"_____no_output_____"
],
[
"plt.imshow((mean_image[()] + images[6]).T)",
"Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d08184d131f1bf4b007448640204ffdb2c84a427 | 59,490 | ipynb | Jupyter Notebook | .ipynb_checkpoints/Untitled1-checkpoint.ipynb | sudhanshu817/advanced_lane_finding | a92a8942359a7de720036571571b3d6f8c6cc6dc | [
"MIT"
] | null | null | null | .ipynb_checkpoints/Untitled1-checkpoint.ipynb | sudhanshu817/advanced_lane_finding | a92a8942359a7de720036571571b3d6f8c6cc6dc | [
"MIT"
] | null | null | null | .ipynb_checkpoints/Untitled1-checkpoint.ipynb | sudhanshu817/advanced_lane_finding | a92a8942359a7de720036571571b3d6f8c6cc6dc | [
"MIT"
] | null | null | null | 49.165289 | 19,120 | 0.66786 | [
[
[
"import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport matplotlib.patches as patches\nfrom moviepy.editor import VideoFileClip\nfrom IPython.display import HTML\nimport glob\n%matplotlib inline\n",
"_____no_output_____"
],
[
"objp = np.zeros((6*9,3), np.float32)\nobjp[:,:2] = np.mgrid[0:9,0:6].T.reshape(-1,2)\n\nnx = 9\nny = 6\n# Arrays to store object points and image points from all the images.\nobjpoints = [] # 3d points in real world space\nimgpoints = [] # 2d points in image plane.\n\n# Make a list of calibration images\nimages = glob.glob('camera_cal/calibration*.jpg')\n\n# Step through the list and search for chessboard corners\nfor fname in images:\n img = cv2.imread(fname)\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n\n # Find the chessboard corners\n ret, corners = cv2.findChessboardCorners(gray, (nx,ny),None)\n\n # If found, add object points, image points\n if ret == True:\n objpoints.append(objp)\n imgpoints.append(corners)\n\n # Draw and display the corners\n img = cv2.drawChessboardCorners(img, (nx,ny), corners, ret)\n #cv2.imshow('img',img)\n #cv2.waitKey(500)\n\n#cv2.destroyAllWindows()",
"_____no_output_____"
],
[
"def get_camera_calibration(img, objpoints, imgpoints):\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)\n return mtx, dist\n ",
"_____no_output_____"
],
[
"img = cv2.imread('camera_cal/calibration1.jpg')\nmtx, dist = get_camera_calibration(img, objpoints, imgpoints)",
"_____no_output_____"
],
[
"def get_undistorted_image(img, mtx, dist):\n undist = cv2.undistort(img, mtx, dist, None, mtx)\n return undist",
"_____no_output_____"
],
[
"def abs_sobel_thresh(img, orient, sobel_kernel, thresh):\n thresh_min, thresh_max = thresh\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n if orient == 'x':\n sobel = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)\n else:\n sobel = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)\n abs_sobel = np.absolute(sobel)\n scaled_sobel = np.uint8(255*abs_sobel/np.max(abs_sobel))\n masked_sobel = np.zeros_like(scaled_sobel)\n masked_sobel[(scaled_sobel >= thresh_min) & (scaled_sobel <= thresh_max)] = 1\n return masked_sobel\n\ndef mag_thresh(img, sobel_kernel=3, mag_thresh=(0, 255)):\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n sobel_x = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)\n sobel_y = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)\n sobel_mag = np.sqrt(np.power(sobel_x, 2)+np.power(sobel_y, 2))\n sobel_scaled = np.uint8(255*sobel_mag/np.max(sobel_mag))\n sobel_mask = np.zeros_like(sobel_scaled)\n sobel_mask[(sobel_scaled>mag_thresh[0]) & (sobel_scaled<mag_thresh[1])] =1\n return sobel_mask\n\ndef dir_threshold(img, sobel_kernel=3, thresh=(0, np.pi/2)):\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n abs_sobel_x = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel))\n abs_sobel_y = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel))\n grad_dir = np.arctan2(abs_sobel_y, abs_sobel_x)\n binary_output = np.zeros_like(grad_dir)\n binary_output[(grad_dir > thresh[0]) & (grad_dir < thresh[1])] = 1\n return binary_output\n\ndef hls_select(img, thresh=(0, 255)):\n hls = cv2.cvtColor(image, cv2.COLOR_RGB2HLS)\n s = hls[:,:,2]\n binary_output = np.zeros_like(s)\n binary_output[(s>thresh[0]) & (s<=thresh[1])] = 1\n return binary_output\n\ndef get_thresholded_binary_image(image, ksize = 15):\n gradx = abs_sobel_thresh(image, orient='x', sobel_kernel=ksize, thresh=(20, 100))\n grady = abs_sobel_thresh(image, orient='y', sobel_kernel=ksize, thresh=(20, 100))\n mag_binary = mag_thresh(image, sobel_kernel=ksize, mag_thresh=(30, 100))\n dir_binary = dir_threshold(image, sobel_kernel=ksize, thresh=(0.7, 1.3))\n hls_binary = hls_select(image, thresh=(120, 255))\n combined = np.zeros_like(dir_binary)\n combined[ ((dir_binary == 1) &(grady==1) &(mag_binary==1)) |(hls_binary==1) ] = 1\n return combined\n",
"_____no_output_____"
],
[
"def get_warp_matrix(undist_img):\n gray = cv2.cvtColor(undist_img, cv2.COLOR_BGR2GRAY)\n img_size = (gray.shape[1], gray.shape[0])\n # For source points I'm grabbing the outer four detected corners\n src = np.float32([[img_size[0]//7+20,img_size[1]],#img_size[0]//7, img_size[1]],\n [(6*img_size[0])//7+30, img_size[1]],\n [img_size[0]//2+60, img_size[1]//2+100],\n [img_size[0]//2-60, img_size[1]//2+100]])\n print(src)\n # For destination points, I'm arbitrarily choosing some points to be\n # a nice fit for displaying our warped result \n # again, not exact, but close enough for our purposes\n offset=200\n dst = np.float32([[offset, img_size[1]], \n [img_size[0]-offset, img_size[1]],\n [img_size[0]-offset,0],\n [offset, 0]])\n # Given src and dst points, calculate the perspective transform matrix\n M = cv2.getPerspectiveTransform(src, dst)\n Minv = cv2.getPerspectiveTransform(dst, src)\n # Warp the image using OpenCV warpPerspective()\n warped = cv2.warpPerspective(undist_img, M, img_size)\n return warped, M, Minv, src, dst",
"_____no_output_____"
],
[
"image = cv2.imread('test_images/straight_lines1.jpg')\nundist_img = get_undistorted_image(image, mtx, dist)\nwarped_img, perspective_M, perspective_Minv, _, dst = get_warp_matrix(undist_img)",
"[[ 202. 720.]\n [ 1127. 720.]\n [ 700. 460.]\n [ 580. 460.]]\n"
],
[
"#perspective_M, perspective_Minv\ndef get_transformed_image(img, perspective_M):\n img_size = (img.shape[1], img.shape[0])\n warped_img = cv2.warpPerspective(img, perspective_M, img_size)\n return warped_img",
"_____no_output_____"
],
[
"def find_lane_pixels(binary_warped):\n histogram = np.sum(binary_warped[binary_warped.shape[0]//2:,:], axis=0)\n out_img = np.dstack((binary_warped, binary_warped, binary_warped))\n midpoint = np.int(histogram.shape[0]//2)\n leftx_base = np.argmax(histogram[:midpoint])\n rightx_base = np.argmax(histogram[midpoint:]) + midpoint\n nwindows = 9\n margin = 100\n minpix = 50\n window_height = np.int(binary_warped.shape[0]//nwindows)\n nonzero = binary_warped.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n leftx_current = leftx_base\n rightx_current = rightx_base\n left_lane_inds = []\n right_lane_inds = []\n for window in range(nwindows):\n win_y_low = binary_warped.shape[0] - (window+1)*window_height\n win_y_high = binary_warped.shape[0] - window*window_height\n win_xleft_low = leftx_current-margin # Update this\n win_xleft_high = leftx_current+margin # Update this\n win_xright_low = rightx_current-margin # Update this\n win_xright_high = rightx_current+margin # Update this\n cv2.rectangle(out_img,(win_xleft_low,win_y_low),\n (win_xleft_high,win_y_high),(0,255,0), 2) \n cv2.rectangle(out_img,(win_xright_low,win_y_low),\n (win_xright_high,win_y_high),(0,255,0), 2) \n good_left_inds =((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & \n (nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0]\n good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & \n (nonzerox >= win_xright_low) & (nonzerox < win_xright_high)).nonzero()[0]\n left_lane_inds.append(good_left_inds)\n right_lane_inds.append(good_right_inds)\n if len(good_left_inds)>minpix:\n leftx_current = np.int(np.mean(nonzerox[good_left_inds]))\n \n if len(good_right_inds)>minpix:\n rightx_current = np.int(np.mean(nonzerox[good_right_inds]))\n try:\n left_lane_inds = np.concatenate(left_lane_inds)\n right_lane_inds = np.concatenate(right_lane_inds)\n except ValueError:\n pass\n leftx = nonzerox[left_lane_inds]\n lefty = nonzeroy[left_lane_inds] \n rightx = nonzerox[right_lane_inds]\n righty = nonzeroy[right_lane_inds]\n\n return leftx, lefty, rightx, righty, out_img\n\n\ndef fit_polynomial(binary_warped):\n binary_warped = binary_warped.copy()\n leftx, lefty, rightx, righty, out_img = find_lane_pixels(binary_warped)\n\n left_fit = np.polyfit(lefty, leftx, 2)\n right_fit = np.polyfit(righty, rightx, 2)\n \n ploty = np.linspace(0, binary_warped.shape[0]-1, binary_warped.shape[0] )\n try:\n left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2]\n right_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2]\n except TypeError:\n # Avoids an error if `left` and `right_fit` are still none or incorrect\n print('The function failed to fit a line!')\n left_fitx = 1*ploty**2 + 1*ploty\n right_fitx = 1*ploty**2 + 1*ploty\n\n out_img[lefty, leftx] = [255, 0, 0]\n out_img[righty, rightx] = [0, 0, 255]\n\n # Plots the left and right polynomials on the lane lines\n plt.plot(left_fitx, ploty, color='yellow')\n plt.plot(right_fitx, ploty, color='yellow')\n\n return out_img, left_fit, right_fit, ploty, left_fitx, right_fitx\n\n",
"_____no_output_____"
],
[
"\ndef fit_poly(img_shape, leftx, lefty, rightx, righty):\n ### TO-DO: Fit a second order polynomial to each with np.polyfit() ###\n left_fit = np.polyfit(lefty, leftx, 2)\n right_fit = np.polyfit(righty, rightx, 2)\n # Generate x and y values for plotting\n ploty = np.linspace(0, img_shape[0]-1, img_shape[0])\n ### TO-DO: Calc both polynomials using ploty, left_fit and right_fit ###\n ploty = np.linspace(0, img_shape[0]-1, img_shape[0] )\n\n left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2]\n right_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2]\n\n # left_fitx = None\n # right_fitx = None\n \n return left_fitx, right_fitx, ploty, left_fit, right_fit\n\ndef search_around_poly(binary_warped, left_fit, right_fit):\n # HYPERPARAMETER\n # Choose the width of the margin around the previous polynomial to search\n # The quiz grader expects 100 here, but feel free to tune on your own!\n binary_warped = binary_warped.copy()\n margin = 100\n\n # Grab activated pixels\n nonzero = binary_warped.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n \n ### TO-DO: Set the area of search based on activated x-values ###\n ### within the +/- margin of our polynomial function ###\n ### Hint: consider the window areas for the similarly named variables ###\n ### in the previous quiz, but change the windows to our new search area ###\n left_lane_inds = ((nonzerox > (left_fit[0]*(nonzeroy**2) + left_fit[1]*nonzeroy + \n left_fit[2] - margin)) & (nonzerox < (left_fit[0]*(nonzeroy**2) + \n left_fit[1]*nonzeroy + left_fit[2] + margin)))\n right_lane_inds = ((nonzerox > (right_fit[0]*(nonzeroy**2) + right_fit[1]*nonzeroy + \n right_fit[2] - margin)) & (nonzerox < (right_fit[0]*(nonzeroy**2) + \n right_fit[1]*nonzeroy + right_fit[2] + margin)))\n \n # Again, extract left and right line pixel positions\n leftx = nonzerox[left_lane_inds]\n lefty = nonzeroy[left_lane_inds] \n rightx = nonzerox[right_lane_inds]\n righty = nonzeroy[right_lane_inds]\n\n # Fit new polynomials\n left_fitx, right_fitx, ploty , left_fit, right_fit= fit_poly(binary_warped.shape, leftx, lefty, rightx, righty)\n \n ## Visualization ##\n # Create an image to draw on and an image to show the selection window\n out_img = np.dstack((binary_warped, binary_warped, binary_warped))*255\n window_img = np.zeros_like(out_img)\n # Color in left and right line pixels\n out_img[nonzeroy[left_lane_inds], nonzerox[left_lane_inds]] = [255, 0, 0]\n out_img[nonzeroy[right_lane_inds], nonzerox[right_lane_inds]] = [0, 0, 255]\n\n # Generate a polygon to illustrate the search window area\n # And recast the x and y points into usable format for cv2.fillPoly()\n left_line_window1 = np.array([np.transpose(np.vstack([left_fitx-margin, ploty]))])\n left_line_window2 = np.array([np.flipud(np.transpose(np.vstack([left_fitx+margin, \n ploty])))])\n left_line_pts = np.hstack((left_line_window1, left_line_window2))\n right_line_window1 = np.array([np.transpose(np.vstack([right_fitx-margin, ploty]))])\n right_line_window2 = np.array([np.flipud(np.transpose(np.vstack([right_fitx+margin, \n ploty])))])\n right_line_pts = np.hstack((right_line_window1, right_line_window2))\n\n # Draw the lane onto the warped blank image\n cv2.fillPoly(window_img, np.int_([left_line_pts]), (0,255, 0))\n cv2.fillPoly(window_img, np.int_([right_line_pts]), (0,255, 0))\n result = cv2.addWeighted(out_img, 1, window_img, 0.3, 0)\n \n # Plot the polynomial lines onto the image\n #plt.plot(left_fitx, ploty, color='yellow')\n #plt.plot(right_fitx, ploty, color='yellow')\n ## End visualization steps ##\n \n return result, left_fitx, right_fitx, ploty, left_fit, right_fit\n\n",
"_____no_output_____"
],
[
"def measure_curvature_real(ploty, left_fit_cr, right_fit_cr):\n ym_per_pix = 30/720 # meters per pixel in y dimension\n xm_per_pix = 3.7/700 # meters per pixel in x dimension\n \n y_eval = np.max(ploty)\n ##### TO-DO: Implement the calculation of R_curve (radius of curvature) #####\n left_curverad = np.power(1+(2*left_fit_cr[0]*y_eval*ym_per_pix + left_fit_cr[1])**2, 3/2)/(2*np.absolute(left_fit_cr[0])) ## Implement the calculation of the left line here\n right_curverad = np.power(1+(2*right_fit_cr[0]*y_eval*ym_per_pix + right_fit_cr[1])**2, 3/2)/(2*np.absolute(right_fit_cr[0])) ## Implement the calculation of the right line here\n \n return left_curverad, right_curverad\n",
"_____no_output_____"
],
[
"def plot_lanes(warped, undist, left_fitx, right_fitx, ploty, Minv):\n # Create an image to draw the lines on\n warp_zero = np.zeros_like(warped).astype(np.uint8)\n color_warp = np.dstack((warp_zero, warp_zero, warp_zero))\n\n # Recast the x and y points into usable format for cv2.fillPoly()\n pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))])\n pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))])\n pts = np.hstack((pts_left, pts_right))\n\n # Draw the lane onto the warped blank image\n cv2.fillPoly(color_warp, np.int_([pts]), (0,255, 0))\n\n # Warp the blank back to original image space using inverse perspective matrix (Minv)\n newwarp = cv2.warpPerspective(color_warp, Minv, (image.shape[1], image.shape[0])) \n # Combine the result with the original image\n result = cv2.addWeighted(undist, 1, newwarp, 0.3, 0)\n return result",
"_____no_output_____"
],
[
"class Line():\n def __init__(self):\n self.detected = False \n self.recent_xfitted = [] \n self.bestx = None \n self.best_fit = None \n self.current_fit = [np.array([False])] \n self.radius_of_curvature = None \n self.line_base_pos = None \n self.diffs = np.array([0,0,0], dtype='float') \n self.allx = None \n self.ally = None ",
"_____no_output_____"
],
[
"class Pipeline():\n \n def __init__(self):\n self.mtx = mtx\n self.dist = dist\n self.perspective_M = perspective_M\n self.perspective_Minv = perspective_Minv\n self.left_lines = []\n self.right_lines = []\n self.xm_per_pix = 3.7/700\n self.ym_per_pix = 30/720 \n \n def get_undistorted_image(self, img):\n undist = cv2.undistort(img, self.mtx, self.dist, None, self.mtx)\n return undist\n\n def get_thresholded_binary_image(self, image, ksize = 15):\n gradx = abs_sobel_thresh(image, orient='x', sobel_kernel=ksize, thresh=(20, 100))\n grady = abs_sobel_thresh(image, orient='y', sobel_kernel=ksize, thresh=(20, 100))\n mag_binary = mag_thresh(image, sobel_kernel=ksize, mag_thresh=(30, 100))\n dir_binary = dir_threshold(image, sobel_kernel=ksize, thresh=(0.7, 1.3))\n hls_binary = hls_select(image, thresh=(120, 255))\n combined = np.zeros_like(dir_binary)\n combined[ ((dir_binary == 1) &(grady==1) &(mag_binary==1)) |(hls_binary==1) ] = 1\n return combined\n \n def get_transformed_image(self, img):\n img_size = (img.shape[1], img.shape[0])\n warped_img = cv2.warpPerspective(img, self.perspective_M, img_size)\n return warped_img\n \n def get_vehicle_offset(self, left_fitx, right_fitx, img_size):\n left_dist = img_size[1]//2 - left_fitx[-1]\n right_dist = right_fitx[-1] - img_size[1]//2\n return left_dist, right_dist\n \n def get_vehicle_dist_from_centre(self, left_fitx, right_fitx, img_size):\n lane_midpoint = (right_fitx[-1]+left_fitx[-1])//2\n img_mid_point = img_size[1]//2\n return round((lane_midpoint - img_mid_point)*self.xm_per_pix,4)\n \n def check_last_line(self):\n if abs(self.left_lines[-1].radius_of_curvature - self.right_lines[-1].radius_of_curvature) > 200:\n flag = False\n else:\n dist_bet_lines = self.left_lines[-1].line_base_pos + self.left_lines[-1].line_base_pos\n if dist_bet_lines > 1000 or dist_bet_lines < 1:#change this values later\n flag = False\n else:\n flag = True#Add function to check if lanes are parallel\n return flag\n \n \n def get_lines_from_scratch(self, warped_img, undist_img):\n #change result to out_img\n result, left_fit, right_fit, ploty, left_fitx, right_fitx = fit_polynomial(warped_img)\n new_left_line = Line()\n new_right_line = Line()\n new_left_line.current_fit = left_fit\n new_right_line.current_fit = right_fit\n left_radius, right_radius = measure_curvature_real(ploty, left_fit, right_fit)\n new_left_line.radius_of_curvature = left_radius\n new_right_line.radius_of_curvature = right_radius\n left_dist, right_dist = self.get_vehicle_offset(left_fitx, right_fitx, warped_img.shape)\n new_left_line.line_base_pos = left_dist\n new_right_line.line_base_pos = right_dist\n new_left_line.allx = left_fitx\n new_left_line.ally = ploty\n new_right_line.allx = right_fitx\n new_right_line.ally = ploty\n self.left_lines.append(new_left_line)\n self.right_lines.append(new_right_line)\n #result = plot_lanes(warped_img, undist_img, left_fitx, right_fitx, ploty, self.perspective_Minv)\n\n result = cv2.putText(result,'Radius of curvature=' + str(right_radius) + '(m)', (0, 100), 0, \n 2, (255, 255, 255), 5, cv2.LINE_AA)\n\n vehicle_dist = self.get_vehicle_dist_from_centre(left_fitx, right_fitx, warped_img.shape)\n \n if vehicle_dist > 0:\n result = cv2.putText(result,'Vehicle is ' + str(vehicle_dist) + 'm left of center', (0, 200), 0, \n 2, (255, 255, 255), 5, cv2.LINE_AA)\n else:\n result = cv2.putText(result,'Vehicle is ' + str(-1*vehicle_dist) + 'm right of center', (0, 200), 0, \n 2, (255, 255, 255), 5, cv2.LINE_AA)\n print(left_radius, right_radius)\n return result\n \n def get_lines_from_previous(self, warped_img, undist_img, flag):\n result, left_fitx, right_fitx, ploty, left_fit, right_fit = search_around_poly(warped_img, \n self.left_lines[-1].current_fit,\n self.right_lines[-1].current_fit)\n new_left_line = Line()\n new_right_line = Line()\n if flag:\n new_left_line.detected=True\n new_right_line.detected = True\n \n new_left_line.current_fit = left_fit\n new_right_line.current_fit = right_fit\n left_radius, right_radius = measure_curvature_real(ploty, left_fit, right_fit)\n new_left_line.radius_of_curvature = left_radius\n new_right_line.radius_of_curvature = right_radius\n left_dist, right_dist = self.get_vehicle_offset(left_fitx, right_fitx, warped_img.shape)\n new_left_line.line_base_pos = left_dist\n new_right_line.line_base_pos = right_dist\n new_left_line.allx = left_fitx\n new_left_line.ally = ploty\n new_right_line.allx = right_fitx\n new_right_line.ally = ploty\n self.left_lines.append(new_left_line)\n self.right_lines.append(new_right_line)\n result = plot_lanes(warped_img, undist_img, left_fitx, right_fitx, ploty, self.perspective_Minv)\n result = cv2.putText(result,'Radius of curvature=' + str(left_radius) + '(m)', (0, 100), 0, \n 2, (255, 255, 255), 5, cv2.LINE_AA)\n\n vehicle_dist = self.get_vehicle_dist_from_centre(left_fitx, right_fitx, warped_img.shape)\n \n if vehicle_dist > 0:\n result = cv2.putText(result,'Vehicle is ' + str(vehicle_dist) + 'm left of center', (0, 200), 0, \n 2, (255, 255, 255), 5, cv2.LINE_AA)\n else:\n result = cv2.putText(result,'Vehicle is ' + str(-1*vehicle_dist) + 'm right of center', (0, 200), 0, \n 2, (255, 255, 255), 5, cv2.LINE_AA)\n print(left_radius, right_radius)\n return result\n\n def process_frame(self, image):\n #plt.imshow(image)\n undist_img = self.get_undistorted_image(image)\n combined = self.get_thresholded_binary_image(undist_img)\n warped_img = self.get_transformed_image(combined)\n #return np.dstack((np.zeros_like(warped_img), warped_img, np.zeros_like(warped_img)))*255\n result = self.get_lines_from_scratch(warped_img, undist_img)\n return result\n# if len(self.left_lines) == 0:\n# result = self.get_lines_from_scratch(warped_img, undist_img)\n# return result\n# else:\n# flag = self.check_last_line\n# if not flag:\n# result = self.get_lines_from_scratch(warped_img, undist_img)\n# return result\n# else:\n# result = self.get_lines_from_previous(warped_img, undist_img, flag)\n# return result",
"_____no_output_____"
],
[
"pipeline_object = Pipeline()\nimg = cv2.imread('test_images/test6.jpg')\nresult = pipeline_object.process_frame(img)\nplt.imshow(result)",
"1048.5575712 3629.22412798\n"
],
[
"pipeline_object = Pipeline()\nwhite_output = 'project_video_output_combined.mp4'\n## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video\n## To do so add .subclip(start_second,end_second) to the end of the line below\n## Where start_second and end_second are integer values representing the start and end of the subclip\n## You may also uncomment the following line for a subclip of the first 5 seconds\n##clip1 = VideoFileClip(\"test_videos/solidWhiteRight.mp4\").subclip(0,5)\nclip1 = VideoFileClip(\"project_video.mp4\").subclip(0, 1)\nwhite_clip = clip1.fl_image(pipeline_object.process_frame) #NOTE: this function expects color images!!\n%time white_clip.write_videofile(white_output, audio=False)",
"5429.72086451 4973.75530882\n[MoviePy] >>>> Building video project_video_output_combined.mp4\n[MoviePy] Writing video project_video_output_combined.mp4\n"
],
[
"HTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n <source src=\"{0}\">\n</video>\n\"\"\".format(white_output))",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d08186328b000226cf03d5530477c2b46e7d6849 | 3,009 | ipynb | Jupyter Notebook | ipynb/positional_encoding_0x01.ipynb | mindscan-de/FluentGenesis-Classifier | 07d7d5cd7a3798c413379bf57cf99a2ea9aec873 | [
"MIT"
] | 2 | 2020-08-19T05:09:48.000Z | 2022-03-08T11:24:43.000Z | ipynb/positional_encoding_0x01.ipynb | mindscan-de/FluentGenesis-Classifier | 07d7d5cd7a3798c413379bf57cf99a2ea9aec873 | [
"MIT"
] | null | null | null | ipynb/positional_encoding_0x01.ipynb | mindscan-de/FluentGenesis-Classifier | 07d7d5cd7a3798c413379bf57cf99a2ea9aec873 | [
"MIT"
] | null | null | null | 22.125 | 105 | 0.547026 | [
[
[
"# Positional Encoding",
"_____no_output_____"
]
],
[
[
"import math\nimport numpy as np\n\n%matplotlib inline\nfrom matplotlib import pyplot as plt\nimport matplotlib as mpl\n\nmpl.rcParams['figure.dpi']=130\n",
"_____no_output_____"
],
[
"def get_positional_watermark(max_sequence_length, embedding_dimensions):\n pe_matrix = np.zeros((max_sequence_length, embedding_dimensions), dtype=np.float32)\n \n for pos in range(max_sequence_length):\n for i in range(0, embedding_dimensions, 2):\n pe_matrix[pos,i] = math.sin( pos / math.pow( 10000, (i) / embedding_dimensions ) )\n pe_matrix[pos,i+1] = math.cos( pos / math.pow( 10000, (i) / embedding_dimensions ) )\n \n return pe_matrix",
"_____no_output_____"
],
[
"plt.imshow(get_positional_watermark(512, 1280), interpolation='nearest',cmap='ocean')\nplt.show()",
"_____no_output_____"
],
[
"print ( get_positional_watermark( 8, 24 ) )",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
d0818f00f50e56f1051912e1a14ccf457d169423 | 9,095 | ipynb | Jupyter Notebook | _math/MIT_OCW_18_06_Linear_algebra/I_08_Solving_homogeneous_systems_Pivot_variables_Special_solutions.ipynb | aixpact/data-science | f04a54595fbc2d797918d450b979fd4c2eabac15 | [
"MIT"
] | 2 | 2020-07-22T23:12:39.000Z | 2020-07-25T02:30:48.000Z | _math/MIT_OCW_18_06_Linear_algebra/I_08_Solving_homogeneous_systems_Pivot_variables_Special_solutions.ipynb | aixpact/data-science | f04a54595fbc2d797918d450b979fd4c2eabac15 | [
"MIT"
] | null | null | null | _math/MIT_OCW_18_06_Linear_algebra/I_08_Solving_homogeneous_systems_Pivot_variables_Special_solutions.ipynb | aixpact/data-science | f04a54595fbc2d797918d450b979fd4c2eabac15 | [
"MIT"
] | null | null | null | 35.527344 | 708 | 0.530621 | [
[
[
"+ This notebook is part of lecture 7 *Solving Ax=0, pivot variables, and special solutions* in the OCW MIT course 18.06 by Prof Gilbert Strang [1]\n+ Created by me, Dr Juan H Klopper\n + Head of Acute Care Surgery\n + Groote Schuur Hospital\n + University Cape Town\n + <a href=\"mailto:[email protected]\">Email me with your thoughts, comments, suggestions and corrections</a> \n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc/4.0/\"><img alt=\"Creative Commons Licence\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc/4.0/88x31.png\" /></a><br /><span xmlns:dct=\"http://purl.org/dc/terms/\" href=\"http://purl.org/dc/dcmitype/InteractiveResource\" property=\"dct:title\" rel=\"dct:type\">Linear Algebra OCW MIT18.06</span> <span xmlns:cc=\"http://creativecommons.org/ns#\" property=\"cc:attributionName\">IPython notebook [2] study notes by Dr Juan H Klopper</span> is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc/4.0/\">Creative Commons Attribution-NonCommercial 4.0 International License</a>.\n\n+ [1] <a href=\"http://ocw.mit.edu/courses/mathematics/18-06sc-linear-algebra-fall-2011/index.htm\">OCW MIT 18.06</a>\n+ [2] Fernando Pérez, Brian E. Granger, IPython: A System for Interactive Scientific Computing, Computing in Science and Engineering, vol. 9, no. 3, pp. 21-29, May/June 2007, doi:10.1109/MCSE.2007.53. URL: http://ipython.org",
"_____no_output_____"
]
],
[
[
"from IPython.core.display import HTML, Image\ncss_file = 'style.css'\nHTML(open(css_file, 'r').read())",
"_____no_output_____"
],
[
"#import numpy as np\nfrom sympy import init_printing, Matrix, symbols\n#import matplotlib.pyplot as plt\n#import seaborn as sns\n#from IPython.display import Image\nfrom warnings import filterwarnings\n\ninit_printing(use_latex = 'mathjax')\n%matplotlib inline\nfilterwarnings('ignore')",
"_____no_output_____"
]
],
[
[
"# Solving homogeneous systems\n# Pivot variables\n# Special solutions",
"_____no_output_____"
],
[
"* We are trying to solve a system of linear equations\n* For homogeneous systems the right-hand side is the zero vector\n* Consider the example below",
"_____no_output_____"
]
],
[
[
"A = Matrix([[1, 2, 2, 2], [2, 4, 6, 8], [3, 6, 8, 10]])\nA # A 3x4 matrix",
"_____no_output_____"
],
[
"x1, x2, x3, x4 = symbols('x1, x2, x3, x4')\n\nx_vect = Matrix([x1, x2, x3, x4]) # A 4x1 matrix\nx_vect",
"_____no_output_____"
],
[
"b = Matrix([0, 0, 0])\nb # A 3x1 matrix",
"_____no_output_____"
]
],
[
[
"* The **x** column vector is a set of all the solutions to this homogeneous equation\n* It forms the nullspace\n* Note that the column vectors in A are not linearly independent",
"_____no_output_____"
],
[
"* Performing elementary row operations leaves us with the matrix below\n* It has two pivots, which is termed **rank** 2",
"_____no_output_____"
]
],
[
[
"A.rref() # rref being reduced row echelon form",
"_____no_output_____"
]
],
[
[
"* Which represents the following\n$$ { x }_{ 1 }\\begin{bmatrix} 1 \\\\ 0 \\\\ 0 \\end{bmatrix}+{ x }_{ 2 }\\begin{bmatrix} 2 \\\\ 0 \\\\ 0 \\end{bmatrix}+{ x }_{ 3 }\\begin{bmatrix} 0 \\\\ 1 \\\\ 0 \\end{bmatrix}+{ x }_{ 4 }\\begin{bmatrix} -2 \\\\ 2 \\\\ 0 \\end{bmatrix}=\\begin{bmatrix} 0 \\\\ 0 \\\\ 0 \\end{bmatrix}\\\\ { x }_{ 1 }+2{ x }_{ 2 }+0{ x }_{ 3 }-2{ x }_{ 4 }=0\\\\ 0{ x }_{ 1 }+0{ x }_{ 2 }+{ x }_{ 3 }+2{ x }_{ 4 }=0\\\\ { x }_{ 1 }+0{ x }_{ 2 }+0{ x }_{ 3 }+0{ x }_{ 4 }=0 $$",
"_____no_output_____"
],
[
"* We are free set a value for *x*<sub>4</sub>, let's sat *t*\n$$ { x }_{ 1 }+2{ x }_{ 2 }+0{ x }_{ 3 }-2{ x }_{ 4 }=0\\\\ 0{ x }_{ 1 }+0{ x }_{ 2 }+{ x }_{ 3 }+2t=0\\\\ { x }_{ 1 }+0{ x }_{ 2 }+0{ x }_{ 3 }+0{ x }_{ 4 }=0\\\\ \\therefore \\quad { x }_{ 3 }=-2t $$",
"_____no_output_____"
],
[
"* We will have to make *x*<sub>2</sub> equal to another variable, say *s*\n$$ { x }_{ 1 }+2s+0{ x }_{ 3 }-2t=0 $$\n$$ \\therefore \\quad {x}_{1}=2t-2s $$",
"_____no_output_____"
],
[
"* This results in the following, which is the complete nullspace and has dimension 2\n$$ \\begin{bmatrix} { x }_{ 1 } \\\\ { x }_{ 2 } \\\\ { x }_{ 3 } \\\\ { x }_{ 4 } \\end{bmatrix}=\\begin{bmatrix} -2s+2t \\\\ s \\\\ -2t \\\\ t \\end{bmatrix}=\\begin{bmatrix} -2s \\\\ s \\\\ 0 \\\\ 0 \\end{bmatrix}+\\begin{bmatrix} 2t \\\\ 0 \\\\ -2t \\\\ t \\end{bmatrix}=s\\begin{bmatrix} -2 \\\\ 1 \\\\ 0 \\\\ 0 \\end{bmatrix}+t\\begin{bmatrix} 2 \\\\ 0 \\\\ -2 \\\\ 1 \\end{bmatrix} $$\n* From the above, we clearly have two vectors in the solution and we can take constant multiples of these to fill up our solution space (our nullspace)",
"_____no_output_____"
],
[
"* We can easily calculate how many free variables we will have by subtracting the number of pivots (rank) from the number of variables (*x*) in **x**\n* Here we have 4 - 2 = 2",
"_____no_output_____"
],
[
"#### Example problem",
"_____no_output_____"
],
[
"* Calculate **x** for the transpose of A above",
"_____no_output_____"
],
[
"#### Solution",
"_____no_output_____"
]
],
[
[
"A_trans = A.transpose() # Creating a new matrix called A_trans and giving it the value of the inverse of A\nA_trans",
"_____no_output_____"
],
[
"A_trans.rref() # In reduced row echelon form this would be the following matrix",
"_____no_output_____"
]
],
[
[
"* Remember this is 4 equations in 3 unknowns, i.e.\n$$ { x }_{ 1 }\\begin{bmatrix} 1 \\\\ 0 \\\\ 0 \\\\ 0 \\end{bmatrix}+{ x }_{ 2 }\\begin{bmatrix} 0 \\\\ 1 \\\\ 0 \\\\ 0 \\end{bmatrix}+{ x }_{ 3 }\\begin{bmatrix} 1 \\\\ 1 \\\\ 0 \\\\ 0 \\end{bmatrix}=\\begin{bmatrix} 0 \\\\ 0 \\\\ 0 \\\\ 0 \\end{bmatrix}\\\\ { x }_{ 1 }+0{ x }_{ 2 }+{ x }_{ 3 }=0\\\\ 0{ x }_{ 1 }+{ x }_{ 2 }+{ x }_{ 3 }=0\\\\ 0{ x }_{ 1 }+0{ x }_{ 2 }+0{ x }_{ 3 }=0\\\\ 0{ x }_{ 1 }+0{ x }_{ 2 }+0{ x }_{ 3 }=0 $$",
"_____no_output_____"
],
[
"* It seems we are free to choose a value for *x*<sub>3</sub>\n* Let's make is *t*\n$$ t\\begin{bmatrix} 1 \\\\ 0 \\\\ 0 \\\\ 0 \\end{bmatrix}-t\\begin{bmatrix} 0 \\\\ 1 \\\\ 0 \\\\ 0 \\end{bmatrix}+t\\begin{bmatrix} 1 \\\\ 1 \\\\ 0 \\\\ 0 \\end{bmatrix}=\\begin{bmatrix} 0 \\\\ 0 \\\\ 0 \\\\ 0 \\end{bmatrix}\\\\ { x }_{ 3 }=t\\\\ { x }_{ 1 }+0{ x }_{ 2 }+t=0\\\\ 0{ x }_{ 1 }+{ x }_{ 2 }+t=0\\\\ \\therefore \\quad { x }_{ 2 }=-t\\\\ \\therefore \\quad { x }_{ 1 }=-t\\\\ \\begin{bmatrix} { x }_{ 1 } \\\\ { x }_{ 2 } \\\\ { x }_{ 3 } \\end{bmatrix}=\\begin{bmatrix} t \\\\ -t \\\\ t \\end{bmatrix}=t\\begin{bmatrix} 1 \\\\ -1 \\\\ 1 \\end{bmatrix} $$",
"_____no_output_____"
],
[
"* We had *n* = 3 unknowns and *r* (rank) = 2 pivots\n* The solution set (nullspace) will thus have 1 variable (*t*) (3-2=1)",
"_____no_output_____"
],
[
"* The third column is the sum of the first two, so only 2 columns are linearly independent\n* We thus expect 2 pivots and can predict the nullspace to have only 1 variable (i.e. it is one-dimensional)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
d08191b30e273019e32beebf4700e8fb897ec39d | 34,613 | ipynb | Jupyter Notebook | notebooks/images_dedup.ipynb | leoyuholo/bad-vis-images | 941ae5459fbb301fdbd58fbf5560c7ec3359ea52 | [
"CC-BY-4.0"
] | 3 | 2020-08-03T12:41:36.000Z | 2021-01-04T10:32:36.000Z | notebooks/images_dedup.ipynb | leoyuholo/bad-vis-images | 941ae5459fbb301fdbd58fbf5560c7ec3359ea52 | [
"CC-BY-4.0"
] | null | null | null | notebooks/images_dedup.ipynb | leoyuholo/bad-vis-images | 941ae5459fbb301fdbd58fbf5560c7ec3359ea52 | [
"CC-BY-4.0"
] | null | null | null | 31.211001 | 187 | 0.531274 | [
[
[
"# !pip install simplejson",
"_____no_output_____"
],
[
"from pymongo import MongoClient\nfrom pathlib import Path\nfrom tqdm.notebook import tqdm\nimport numpy as np\nimport simplejson as json\nimport itertools\nfrom functools import cmp_to_key\nimport networkx as nx\n\nfrom IPython.display import display, Image, JSON\nfrom ipywidgets import widgets, Image, HBox, VBox, Button, ButtonStyle, Layout, Box\n\nfrom lib.image_dedup import make_hashes, calculate_distance, hashes_diff\nfrom lib.PersistentSet import PersistentSet\nfrom lib.sort_things import post_score, sort_posts, sort_images\nfrom lib.parallel import parallel",
"_____no_output_____"
],
[
"images_dir = Path('../images')\nhandmade_dir = Path('./handmade')\nhandmade_dir.mkdir(exist_ok=True)",
"_____no_output_____"
],
[
"mongo_uri = json.load(open('./credentials/mongodb_credentials.json'))['uri']\nmongo = MongoClient(mongo_uri)\ndb = mongo['bad-vis']\nposts = db['posts']\nimagefiles = db['imagefiles']\nimagemeta = db['imagemeta']\nimagededup = db['imagededup']",
"_____no_output_____"
],
[
"imagededup.drop()\nfor i in imagemeta.find():\n imagededup.insert_one(i)",
"_____no_output_____"
]
],
[
[
"# Load image metadata",
"_____no_output_____"
]
],
[
[
"imageDedup = [m for m in imagemeta.find()]\nimageDedup.sort(key=lambda x: x['image_id'])",
"_____no_output_____"
],
[
"phash_to_idx_mapping = {}\nfor i in range(len(imageDedup)):\n phash = imageDedup[i]['phash']\n l = phash_to_idx_mapping.get(phash, [])\n l.append(i)\n phash_to_idx_mapping[phash] = l\ndef phash_to_idx (phash):\n return phash_to_idx_mapping.get(phash, None)",
"_____no_output_____"
],
[
"image_id_to_idx_mapping = {imageDedup[i]['image_id']:i for i in range(len(imageDedup))}\ndef image_id_to_idx (image_id):\n return image_id_to_idx_mapping.get(image_id, None)",
"_____no_output_____"
]
],
[
[
"# Calculate distance",
"_____no_output_____"
],
[
"## Hash distance",
"_____no_output_____"
]
],
[
[
"image_hashes = [make_hashes(m) for m in imageDedup]",
"_____no_output_____"
],
[
"# distance = calculate_distance(image_hashes)\ndistance = calculate_distance(image_hashes, hash_type='phash')",
"_____no_output_____"
],
[
"# distance2 = np.ndarray([len(image_hashes), len(image_hashes)])\n# for i in tqdm(range(len(image_hashes))):\n# for j in range(i+1):\n# diff = hashes_diff(image_hashes[i], image_hashes[j])\n# distance2[i, j] = diff\n# distance2[j, i] = diff\n# np.array_equal(distance, distance2)",
"_____no_output_____"
],
[
"# pdistance = calculate_distance(image_hashes, hash_type='phash')",
"_____no_output_____"
]
],
[
[
"## Find duplicated pairs from distance matrix",
"_____no_output_____"
]
],
[
[
"def set_distance (hashes, value, mat=distance):\n phash_x = hashes[0]\n phash_y = phash_x if len(hashes) == 1 else hashes[1]\n idx_x = phash_to_idx(phash_x)\n idx_y = phash_to_idx(phash_y)\n if idx_x == None or idx_y == None:\n return\n for s in itertools.product(idx_x, idx_y):\n i, j = s\n mat[i, j] = value\n mat[j, i] = value\n\ndef set_distance_pairs (phash_pairs, value, mat=distance):\n for p in phash_pairs:\n set_distance(list(p), value, mat=mat)",
"_____no_output_____"
],
[
"auto_duplicated_image_phash_pairs = PersistentSet()\nauto_duplicated_image_phash_pairs.set_file(handmade_dir/'auto_duplicated_image_phash_pairs.json')",
"_____no_output_____"
],
[
"for i in tqdm(range(distance.shape[0])):\n for j in range(i):\n if distance[i, j] <= 1: # checked, all distance <= 1 are duplicated\n auto_duplicated_image_phash_pairs.add(frozenset([imageDedup[i]['phash'], imageDedup[j]['phash']]))",
"_____no_output_____"
],
[
"# for i in tqdm(range(pdistance.shape[0])):\n# for j in range(i):\n# if pdistance[i, j] <= 1: # checked, all distance <= 1 are duplicated\n# auto_duplicated_image_phash_pairs.add(frozenset([imageDedup[i]['phash'], imageDedup[j]['phash']]))",
"_____no_output_____"
],
[
"auto_duplicated_image_phash_pairs.save()",
"_____no_output_____"
]
],
[
[
"## Apply information from meta data",
"_____no_output_____"
]
],
[
[
"duplicated_post_image_phash_pairs = PersistentSet()\nduplicated_post_image_phash_pairs.set_file(handmade_dir/'duplicated_post_image_phash_pairs.json')\n\nfor p in tqdm(posts.find()):\n if len(p.get('duplicated_posts', [])) == 0:\n continue\n\n dp_phashes = {i['phash']\n for dp in p['duplicated_posts']\n for i in imagemeta.find({'post_id': dp})}\n if len(dp_phashes) > 1:\n# print(f\"More than 1 dp image {p['post_id']}\")\n# print(f\"{p['duplicated_posts']} {dp_phashes}\")\n continue\n\n phashes = [i['phash'] for i in imagemeta.find({'post_id': p['post_id']})]\n if len(phashes) > 1:\n# print(f\"More than 1 image {p['post_id']} {phashes}\")\n continue\n for s in itertools.product(dp_phashes, phashes):\n fs = frozenset(s)\n if len(fs) > 1:\n duplicated_post_image_phash_pairs.add(fs)\n\nduplicated_post_image_phash_pairs.save()",
"_____no_output_____"
],
[
"related_album_image_phash_pairs = PersistentSet()\nrelated_album_image_phash_pairs.set_file(handmade_dir/'related_album_image_phash_pairs.json')\n\nfor album in tqdm({i['album'] for i in imagemeta.find({'album': {'$exists': True, '$ne': ''}})}):\n ra_phashes = [i['phash'] for i in imagemeta.find({'album': album})]\n if len(ra_phashes) <= 1:\n print(f\"Only 1 or less image {album} {ra_phashes}\")\n\n for s in itertools.product(ra_phashes, ra_phashes):\n fs = frozenset(s)\n if len(fs) > 1:\n related_album_image_phash_pairs.add(fs)\n\nrelated_album_image_phash_pairs.save()",
"_____no_output_____"
]
],
[
[
"## Apply manual labeled data",
"_____no_output_____"
]
],
[
[
"duplicated_image_phash_pairs = PersistentSet.load_set(handmade_dir/'duplicated_image_phash_pairs.json')\nnot_duplicated_image_phash_pairs = PersistentSet.load_set(handmade_dir/'not_duplicated_image_phash_pairs.json')\nrelated_image_phash_pairs = PersistentSet.load_set(handmade_dir/'related_image_phash_pairs.json')\ninvalid_image_phashes = PersistentSet.load_set(handmade_dir/'invalid_image_phashes.json')",
"_____no_output_____"
],
[
"set_distance_pairs(auto_duplicated_image_phash_pairs, 0)\nset_distance_pairs(duplicated_post_image_phash_pairs, 0)\nset_distance_pairs(duplicated_image_phash_pairs, 0)\nset_distance_pairs(not_duplicated_image_phash_pairs, 60)\nset_distance_pairs(related_album_image_phash_pairs, 60)\nset_distance_pairs(related_image_phash_pairs, 60)\n\nrelated_distance = np.full(distance.shape, 60)\nset_distance_pairs(related_album_image_phash_pairs, 0, mat=related_distance)\nset_distance_pairs(related_image_phash_pairs, 0, mat=related_distance)",
"_____no_output_____"
]
],
[
[
"# Human in the Loop",
"_____no_output_____"
]
],
[
[
"def make_dedup_box (idx_x, idx_y, default=None):\n image_x = imageDedup[idx_x]\n phash_x = image_x['phash']\n image_y = imageDedup[idx_y]\n phash_y = image_y['phash']\n hash_pair = frozenset([phash_x, phash_y])\n\n yes_btn = widgets.Button(description=\"Duplicated\", button_style='success')\n no_btn = widgets.Button(description=\"Not\", button_style='info')\n related_btn = widgets.Button(description=\"Related\", button_style='warning')\n invalid_x_btn = widgets.Button(description=\"X Invalid\")\n invalid_y_btn = widgets.Button(description=\"Y Invalid\")\n reset_btn = widgets.Button(description=\"Reset\")\n output = widgets.Output()\n\n def on_yes (btn):\n with output:\n if hash_pair in not_duplicated_image_phash_pairs:\n not_duplicated_image_phash_pairs.persist_remove(hash_pair)\n print('-Not')\n duplicated_image_phash_pairs.persist_add(hash_pair)\n print('Duplicated')\n\n def on_no (btn):\n with output:\n if hash_pair in duplicated_image_phash_pairs:\n duplicated_image_phash_pairs.persist_remove(hash_pair)\n print('-Duplicated')\n not_duplicated_image_phash_pairs.persist_add(hash_pair)\n print('Not')\n\n def on_related (btn):\n with output:\n if hash_pair in not_duplicated_image_phash_pairs:\n not_duplicated_image_phash_pairs.persist_remove(hash_pair)\n print('-Not')\n related_image_phash_pairs.persist_add(hash_pair)\n print('Related')\n\n def on_invalid_x (btn):\n invalid_image_phashes.persist_add(phash_x)\n with output:\n print('Invalid X')\n\n def on_invalid_y (btn):\n invalid_image_phashes.persist_add(phash_y)\n with output:\n print('Invalid Y')\n\n def on_reset (btn):\n with output:\n if hash_pair in duplicated_image_phash_pairs:\n duplicated_image_phash_pairs.persist_remove(hash_pair)\n print('-Duplicated')\n if hash_pair in not_duplicated_image_phash_pairs:\n not_duplicated_image_phash_pairs.persist_remove(hash_pair)\n print('-Not')\n if hash_pair in related_image_phash_pairs:\n related_image_phash_pairs.persist_remove(hash_pair)\n print('-Related')\n if phash_x in invalid_image_phashes:\n invalid_image_phashes.persist_remove(phash_x)\n print('-Invalid X')\n if phash_y in invalid_image_phashes:\n invalid_image_phashes.persist_remove(phash_y)\n print('-Invalid Y')\n print('Reset')\n\n yes_btn.on_click(on_yes)\n no_btn.on_click(on_no)\n related_btn.on_click(on_related)\n invalid_x_btn.on_click(on_invalid_x)\n invalid_y_btn.on_click(on_invalid_y)\n reset_btn.on_click(on_reset)\n\n if default == 'no':\n on_no(None)\n elif default == 'yes':\n on_yes(None)\n\n return HBox([VBox([yes_btn, no_btn, related_btn, invalid_x_btn, invalid_y_btn, reset_btn, output]),\n widgets.Image(value=open(image_x['file_path'], 'rb').read(), width=250, height=150),\n widgets.Image(value=open(image_y['file_path'], 'rb').read(), width=250, height=150)])",
"_____no_output_____"
],
[
"def potential_duplicates (threshold):\n for i in range(distance.shape[0]):\n for j in range(i):\n if distance[i, j] <= threshold:\n phash_pair = frozenset([imageDedup[i]['phash'], imageDedup[j]['phash']])\n if (phash_pair not in auto_duplicated_image_phash_pairs and\n phash_pair not in duplicated_post_image_phash_pairs and\n phash_pair not in duplicated_image_phash_pairs and\n phash_pair not in not_duplicated_image_phash_pairs and\n phash_pair not in related_album_image_phash_pairs and\n phash_pair not in related_image_phash_pairs):\n yield (i, j)",
"_____no_output_____"
],
[
"distance_threshold = 10",
"_____no_output_____"
],
[
"pdup = potential_duplicates(distance_threshold)",
"_____no_output_____"
],
[
"for i in range(10):\n try:\n next_pdup = next(pdup)\n except StopIteration:\n print('StopIteration')\n break\n\n idx_x, idx_y = next_pdup\n image_x = imageDedup[idx_x]\n image_y = imageDedup[idx_y]\n print(f\"{idx_x} {idx_y} {distance[idx_x, idx_y]} {image_x['phash']} {image_y['phash']} {image_x['width']} {image_y['width']} {image_x['image_id']} {image_y['image_id']}\")\n display(make_dedup_box(idx_x, idx_y, default=None if distance[idx_x, idx_y] < 6 else 'no'))\n # display(make_dedup_box(idx_x, idx_y, default='yes' if distance[idx_x, idx_y] < 9 else 'no'))",
"StopIteration\n"
]
],
[
[
"# Visually check images",
"_____no_output_____"
],
[
"## Images with high variability",
"_____no_output_____"
]
],
[
[
"# interested_phashes = set()",
"_____no_output_____"
],
[
"# def potential_duplicates_high (threshold):\n# for i in range(distance.shape[0]):\n# for j in range(i):\n# if distance[i, j] >= threshold:\n# phash_pair = frozenset([imageDedup[i]['phash'], imageDedup[j]['phash']])\n# if (phash_pair in duplicated_image_phash_pairs):\n# interested_phashes.add(imageDedup[i]['phash'])\n# interested_phashes.add(imageDedup[j]['phash'])\n# yield (i, j)",
"_____no_output_____"
],
[
"# pduph = potential_duplicates_high(13)",
"_____no_output_____"
],
[
"# for i in range(100):\n# try:\n# next_pdup = next(pduph)\n# except StopIteration:\n# print('StopIteration')\n# break\n\n# idx_x, idx_y = next_pdup\n# image_x = imageDedup[idx_x]\n# image_y = imageDedup[idx_y]\n# print(f\"{idx_x} {idx_y} {distance[idx_x, idx_y]} {image_x['phash']} {image_y['phash']} {image_x['width']} {image_y['width']} {image_x['image_id']} {image_y['image_id']}\")\n# display(make_dedup_box(idx_x, idx_y))",
"_____no_output_____"
],
[
"# invalid_image_phashes = set(json.load(open('handmade/invalid_image_phashes.json')))",
"_____no_output_____"
],
[
"# examined_images = [\n# 'reddit/dataisugly/2o08rl_0', # manually downloaded\n# 'reddit/dataisugly/2nwubr_0', # manually downloaded\n# 'reddit/dataisugly/beivt8_0', # manually downloaded\n# 'reddit/dataisugly/683b4i_0', # manually downloaded\n# 'reddit/dataisugly/3zcw30_0', # manually downloaded\n# 'reddit/dataisugly/1oxrh5_0', # manually downloaded a higher resolution image\n# 'reddit/dataisugly/3or2g0_0', # manually downloaded\n# 'reddit/dataisugly/5iobqn_0', # manually downloaded\n# 'reddit/dataisugly/29fpuo_0', # manually downloaded\n# 'reddit/dataisugly/5xux1f_0', # manually downloaded\n# 'reddit/dataisugly/35lrw1_0', # manually downloaded\n# 'reddit/dataisugly/1bxhv2_0', # manually downloaded a higher resolution image\n# 'reddit/dataisugly/3peais_0', # manually downloaded\n# 'reddit/dataisugly/2vdk71_0', # manually downloaded\n# 'reddit/dataisugly/6b8w73_0', # manually downloaded\n# 'reddit/dataisugly/2w8pnr_0', # manually downloaded an image with more context\n# 'reddit/dataisugly/2dt19h_0', # manually downloaded\n# 'reddit/dataisugly/31tj8a_0', # manually downloaded\n# 'reddit/dataisugly/30smxr_0', # manually downloaded\n# 'reddit/dataisugly/30dbx6_0', # manually downloaded\n# 'reddit/dataisugly/561ytm_0', # manually downloaded\n# 'reddit/dataisugly/6q4tre_0', # manually downloaded\n# 'reddit/dataisugly/3icm4g_0', # manually downloaded\n# 'reddit/dataisugly/6z5v98_0', # manually downloaded\n# 'reddit/dataisugly/5fucjm_0', # manually downloaded\n# 'reddit/dataisugly/99bczz_0', # manually downloaded\n# 'reddit/dataisugly/2662wv_0', # manually downloaded\n# 'reddit/dataisugly/26otpi_0', # manually downloaded a higher resolution image\n# 'reddit/dataisugly/68scgb_0', # manually downloaded\n# 'reddit/dataisugly/et75qp_0', # manually downloaded\n# 'reddit/dataisugly/4c9zc1_0', # manually downloaded an image with more context\n# 'reddit/dataisugly/2525a5_0', # manually downloaded more images, but does not matched with the one with more context\n# 'reddit/dataisugly/2la7zt_0', # thumbnail alt\n# ]",
"_____no_output_____"
]
],
[
[
"## Invalid images",
"_____no_output_____"
]
],
[
[
"# invalids = []\n# for h in invalid_image_phashes:\n# invalid_images = [f for f in imagefiles.find({'phash': h})]\n# if len(invalid_images) > 0:\n# invalids.append(invalid_images[0])\n\n# display(Box([widgets.Image(value=open(i['file_path'], 'rb').read(), width=100, height=100) for i in invalids],\n# layout=Layout(display='flex', flex_flow='row wrap')))",
"_____no_output_____"
]
],
[
[
"# Consolidate",
"_____no_output_____"
],
[
"## Related images",
"_____no_output_____"
]
],
[
[
"related_images = [[imageDedup[idx]['image_id'] for idx in c]\n for c in nx.components.connected_components(nx.Graph(related_distance <= 1))\n if len(c) > 1]\nlen(related_images)",
"_____no_output_____"
],
[
"for ids in related_images:\n for i in ids:\n imageMeta = imageDedup[image_id_to_idx(i)]\n ri = [r for r in set(imageMeta.get('related_images', []) + ids) if r != i]\n imagededup.update_one({'image_id': i}, {'$set': {'related_images': ri}})",
"_____no_output_____"
]
],
[
[
"## Duplicated images",
"_____no_output_____"
]
],
[
[
"excluding_image_phashes = PersistentSet.load_set(handmade_dir/'excluding_image_phashes.json')",
"_____no_output_____"
],
[
"excluding_image_phashes.persist_add('c13e3ae10e70fd86')\nexcluding_image_phashes.persist_add('fe81837a94e3807e')\nexcluding_image_phashes.persist_add('af9da24292fae149')\nexcluding_image_phashes.persist_add('ad87d2696738ca4c')\nexcluding_image_phashes.persist_add('d25264dfa9659392')\nexcluding_image_phashes.persist_add('964e3b3160e14f8f')",
"_____no_output_____"
],
[
"class ImageDedup ():\n _attrs = [\n 'id',\n 'post_id',\n 'datetime',\n 'url',\n 'title',\n 'content',\n 'author',\n 'removed',\n 'ups',\n 'num_comments',\n 'external_link',\n 'source',\n 'source_platform',\n 'source_url',\n 'tags',\n 'labels',\n 'media_type',\n 'thumbnail_url',\n 'preview_url',\n 'external_link_url',\n 'archive_url',\n\n 'thumbnail',\n 'preview',\n 'external_link',\n 'archive',\n 'manual',\n\n 'image_id',\n 'short_image_id',\n 'album',\n 'index_in_album',\n 'image_type',\n 'file_path',\n 'ext',\n 'animated',\n 'size',\n 'width',\n 'height',\n 'pixels',\n 'image_order',\n 'ahash',\n 'phash',\n 'pshash',\n 'dhash',\n 'whash',\n\n 'duplicated_posts',\n 'related_images',\n 'duplicated_images',\n 'popularity_score'\n ]\n\n def __init__ (self, imageMetas=[]):\n # print(imageMetas)\n if len(imageMetas) == 0:\n raise Exception('Empty imageFiles array.')\n\n self._imageMetas = imageMetas\n self._image_ids = [i['image_id'] for i in imageMetas]\n self._image_order = sort_images(self._imageMetas)\n\n self._post_ids = {i['post_id'] for i in imageMetas}\n self._posts = [posts.find_one({'post_id': i}) for i in self._post_ids]\n dpost = []\n for p in self._posts:\n if 'duplicated_posts' in p:\n for i in p['duplicated_posts']:\n if i not in self._post_ids:\n dpost.append(posts.find_one({'post_id': i}))\n self._posts += dpost\n if None in self._posts:\n print(self._post_ids)\n self._post_order = sort_posts(self._posts)\n\n for k, v in self.main_image.items():\n if k in ['duplicated_posts', 'related_images']:\n continue\n setattr(self, k, v)\n\n for k, v in self.main_post.items():\n if k in ['duplicated_posts', 'related_images']:\n continue\n if k in ['preview', 'thumbnail', 'external_link', 'archive', 'manual']:\n setattr(self, f\"{k}_url\", v)\n else:\n setattr(self, k, v)\n\n def digest (self):\n return {a:getattr(self, a) for a in ImageDedup._attrs if hasattr(self, a)}\n\n @property\n def duplicated_posts (self):\n post_ids = self._post_ids.union(*[set(p.get('duplicated_posts', [])) for p in self._posts])\n return [i for i in post_ids if i != self.post_id]\n\n @property\n def duplicated_images (self):\n return [i for i in self._image_ids if i != self.image_id]\n\n @property\n def related_images (self):\n return [ri for i in self._imageMetas for ri in i.get('related_images', []) if ri != self.image_id]\n\n @property\n def main_post (self):\n# if len(self._post_order) > 1 and self._post_order[0]['source_platform'] != 'reddit':\n# print(f\"main post warning: {[p['post_id'] for p in self._post_order]}\")\n return self._post_order[0]\n\n @property\n def popularity_score (self):\n return sum([post_score(p) for p in self._posts if p['source'] == 'dataisugly'])\n\n @property\n def main_image (self):\n# if len(self._image_order) > 1 and self._image_order[0]['source_platform'] != 'reddit':\n# print(f\"main image warning: {[i['image_id'] for i in self._image_order]}\")\n mi = [i for i in self._image_order if i['phash'] not in excluding_image_phashes][0]\n return mi",
"_____no_output_____"
],
[
"duplicated_images = [list(set([imageDedup[idx]['image_id'] for idx in c]))\n for c in nx.components.connected_components(nx.Graph(distance <= 1))]",
"_____no_output_____"
],
[
"# imageDedup[image_id_to_idx('reddit/AusFinance/fman6b_0')]",
"_____no_output_____"
],
[
"def dedup_image (ids):\n imagedd = ImageDedup([imageDedup[image_id_to_idx(i)] for i in set(ids)])\n # if imagedd.main_post['source'] != 'dataisugly':\n # print(f\"Image not from dataisugly: {imagedd.main_post['post_id']}\")\n for i in imagedd.duplicated_images:\n imagededup.delete_one({'image_id': i})\n imagededup.replace_one({'image_id': imagedd.image_id}, imagedd.digest(), upsert=True)\n return imagedd",
"_____no_output_____"
],
[
"imagedds = parallel(dedup_image, duplicated_images, n_jobs=-1)",
"_____no_output_____"
],
[
"# duplicated_image_ids = [c\n# for c in nx.components.connected_components(nx.Graph(distance <= 1))\n# if len(c) > 1]\n# start = 0",
"_____no_output_____"
],
[
"# # len(duplicated_image_ids)\n# cnt = 0\n# end = start + 50\n# for idxs in duplicated_image_ids:\n# # print(f\"{[imageDedup[i]['image_id'] for i in idxs]}\")\n# # if len(idxs) == 2:\n# if len(idxs) >= 4:\n# if cnt >= start:\n# print(*[imageDedup[i]['image_id'] for i in idxs])\n# print(*[imageDedup[i]['phash'] for i in idxs])\n# display(HBox([\n# widgets.Image(value=open(imageDedup[i]['file_path'], 'rb').read(), width=100, height=100)\n# for i in idxs]))\n# cnt += 1\n# if cnt >= end:\n# print(end)\n# start = end\n# break",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d081b40b42ce90660de72f84eced82fa4a87f242 | 154,142 | ipynb | Jupyter Notebook | tutorials/full_pta_gwb/pe_extensions.ipynb | AaronDJohnson/12p5yr_stochastic_analysis | 07335cc456e3a022f7fe90fca3ad4dba36ab5da3 | [
"MIT"
] | null | null | null | tutorials/full_pta_gwb/pe_extensions.ipynb | AaronDJohnson/12p5yr_stochastic_analysis | 07335cc456e3a022f7fe90fca3ad4dba36ab5da3 | [
"MIT"
] | null | null | null | tutorials/full_pta_gwb/pe_extensions.ipynb | AaronDJohnson/12p5yr_stochastic_analysis | 07335cc456e3a022f7fe90fca3ad4dba36ab5da3 | [
"MIT"
] | null | null | null | 367.004762 | 123,206 | 0.934658 | [
[
[
"# Using enterprise_extensions to analyze PTA data\n\nIn this notebook you will learn:\n* How to use `enterprise_extensions` to create `enterprise` models,\n* How to search in PTA data for a isotropic stochastic gravitational wave background using multiple pulsars,\n* How to implement a HyperModel object to sample a `model_2a` model,\n* How to post-process your results.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n%load_ext autoreload\n%autoreload 2\n\nimport os, glob, json, pickle\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom enterprise.pulsar import Pulsar\nfrom enterprise_extensions import models, hypermodel\n\nimport sys\nsys.path.append(\"..\")\nfrom settings import fd_bins",
"WARNING: AstropyDeprecationWarning: The private astropy._erfa module has been made into its own package, pyerfa, which is a dependency of astropy and can be imported directly using \"import erfa\" [astropy._erfa]\n"
]
],
[
[
"## Get par, tim, and noise files",
"_____no_output_____"
]
],
[
[
"psrlist = None # define a list of pulsar name strings that can be used to filter.\n# set the data directory\ndatadir = '../data'\nif not os.path.isdir(datadir):\n datadir = '../../data'\nprint('datadir =', datadir)",
"datadir = ../../data\n"
],
[
"# for the entire pta\nparfiles = sorted(glob.glob(datadir + '/par/*par'))\ntimfiles = sorted(glob.glob(datadir + '/tim/*tim'))\n\n# filter\nif psrlist is not None:\n parfiles = [x for x in parfiles if x.split('/')[-1].split('.')[0] in psrlist]\n timfiles = [x for x in timfiles if x.split('/')[-1].split('.')[0] in psrlist]\n\n# Make sure you use the tempo2 parfile for J1713+0747!!\n# ...filtering out the tempo parfile... \nparfiles = [x for x in parfiles if 'J1713+0747_NANOGrav_12yv3.gls.par' not in x]",
"_____no_output_____"
]
],
[
[
"## Read par and tim files into `enterprise` `Pulsar` objects\n",
"_____no_output_____"
]
],
[
[
"# check for file and load pickle if it exists:\npickle_loc = datadir + '/psrs.pkl'\nif os.path.exists(pickle_loc):\n with open(pickle_loc, 'rb') as f:\n psrs = pickle.load(f)\n\n# else: load them in slowly:\nelse:\n psrs = []\n ephemeris = 'DE438'\n for p, t in zip(parfiles, timfiles):\n psr = Pulsar(p, t, ephem=ephemeris)\n psrs.append(psr)\n\n# Make your own pickle of these loaded objects to reduce load times significantly\n# at the cost of some space on your computer (~1.8 GB).\nwith open(datadir + '/psrs.pkl', 'wb') as f:\n pickle.dump(psrs, f)",
"_____no_output_____"
],
[
"## Get parameter noise dictionary\nnoise_ng12 = datadir + '/channelized_12p5yr_v3_full_noisedict.json'\n\nparams = {}\nwith open(noise_ng12, 'r') as fp:\n params.update(json.load(fp))",
"_____no_output_____"
]
],
[
[
"### Set up PTA model\n\n* This model_2a includes everything from the verbose version in these tutorials:\n * fixed white noise parameters based on noisedict `params`,\n * common red noise signal (no correlation function) with 5 frequencies,\n * and a spectral index of 13/3",
"_____no_output_____"
]
],
[
[
"pta = models.model_2a(psrs,\n psd='powerlaw',\n noisedict=params,\n n_gwbfreqs=5, # modify the number of common red noise frequencies used here\n gamma_common=13/3) # remove this line for a varying spectral index",
"_____no_output_____"
]
],
[
[
"### Setup an instance of a HyperModel.\n* This doesn't mean we are doing model selection (yet!), but the\n hypermodel module gives access to some nifty sampling schemes.",
"_____no_output_____"
]
],
[
[
"super_model = hypermodel.HyperModel({0: pta})",
"_____no_output_____"
]
],
[
[
"### Setup PTMCMCSampler",
"_____no_output_____"
]
],
[
[
"outDir = '../../chains/extensions_chains'\n\nsampler = super_model.setup_sampler(resume=True,\n outdir=outDir,\n sample_nmodel=False,)",
"Adding red noise prior draws...\n\nAdding GWB uniform distribution draws...\n\nAdding gw param prior draws...\n\n"
],
[
"# sampler for N steps\nN = int(5e6)\nx0 = super_model.initial_sample()",
"_____no_output_____"
],
[
"# Sampling this will take a very long time. If you want to sample it yourself, uncomment the next line:\n# sampler.sample(x0, N, SCAMweight=30, AMweight=15, DEweight=50, )",
"_____no_output_____"
]
],
[
[
"### Plot Output",
"_____no_output_____"
]
],
[
[
"# Uncomment this one to load the chain if you have sampled with PTMCMCSampler:\n# chain = np.loadtxt(os.path.join(outDir, 'chain_1.txt'))\n\n# This will load the chain that we have provided:\nchain = np.load(os.path.join(outDir, 'chain_1.npz'))['arr_0']\nburn = int(0.25 * chain.shape[0]) # remove burn in segment of sampling",
"_____no_output_____"
],
[
"ind = list(pta.param_names).index('gw_log10_A')",
"_____no_output_____"
],
[
"# Make trace-plot to diagnose sampling\nplt.figure(figsize=(12, 5))\nplt.plot(chain[burn:, ind])\nplt.xlabel('Sample Number')\nplt.ylabel('log10_A_gw')\nplt.title('Trace Plot')\nplt.grid(b=True)\nplt.show()",
"_____no_output_____"
],
[
"# Plot a histogram of the marginalized posterior distribution\nbins = fd_bins(chain[:, ind], logAmin=-18, logAmax=-12) # let FD rule decide bins (in ../settings.py)\nplt.figure(figsize=(12, 5))\nplt.title('Histogram')\nplt.hist(chain[:, ind], bins=bins, histtype='stepfilled',\n lw=2, color='C0', alpha=0.5, density=True)\nplt.xlabel('log10_A_gw')\nplt.show()",
"_____no_output_____"
],
[
"# Compute maximum posterior value\nhist = np.histogram(chain[burn:, pta.param_names.index('gw_log10_A')],\n bins=bins,\n density=True)\nmax_ind = np.argmax(hist[0])\nprint('our_max =', hist[1][max_ind]) # from our computation",
"our_max = -14.707808651660155\n"
]
],
[
[
"This analysis is consistent with the verbose version.\nHere we have introduced some convenient methods:\n* Using a HyperModel object for a single model,\n* Using `enterprise_extensions` to create the model,\n* Sampling a `HyperModel` with `PTMCMCSampler`.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
d081b59f9d59b4edf983323e78db0f89fe8df079 | 2,378 | ipynb | Jupyter Notebook | physics-lab/Tests.ipynb | xypnox/jupyter-notebooks | 5ff4fcd0b71cff82da096abb0de53f472d289d4b | [
"MIT"
] | null | null | null | physics-lab/Tests.ipynb | xypnox/jupyter-notebooks | 5ff4fcd0b71cff82da096abb0de53f472d289d4b | [
"MIT"
] | null | null | null | physics-lab/Tests.ipynb | xypnox/jupyter-notebooks | 5ff4fcd0b71cff82da096abb0de53f472d289d4b | [
"MIT"
] | null | null | null | 16.865248 | 52 | 0.420942 | [
[
[
"import numpy as np\nx = [1, 3, 4, 5]\n\ny = [i*i for i in x]\n\ny2 = []\nfor i in x:\n y2.append(i*i)\n\nprint(x, y, y2)",
"[1, 3, 4, 5] [1, 9, 16, 25] [1, 9, 16, 25]\n"
],
[
"print(np.divide(y, x))\nprint(np.divide(2, 3))\n\ndiv = []\nfor i in range(len(x)):\n div.append(y[i]/x[i])\n \nprint(div)",
"[1. 3. 4. 5.]\n0.6666666666666666\n[1.0, 3.0, 4.0, 5.0]\n"
],
[
"[2, 3, 4] + [3, 5, 6]",
"_____no_output_____"
],
[
"45.53+45.66+45.53\n_/3",
"_____no_output_____"
],
[
"(66+28+50)/3\n",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code"
]
] |
d081b8a39a6ffe2bb4c841df170bfab2c78dd4da | 118,431 | ipynb | Jupyter Notebook | ML_Files/Cross_Strip_8Fam/.ipynb_checkpoints/Pixelated_32Features_DNN_Time_Label-checkpoint.ipynb | nananasiri/Multiple-Interaction-Photon-Events | af3950d70f07020650f3674ae03244234917a11d | [
"MIT"
] | null | null | null | ML_Files/Cross_Strip_8Fam/.ipynb_checkpoints/Pixelated_32Features_DNN_Time_Label-checkpoint.ipynb | nananasiri/Multiple-Interaction-Photon-Events | af3950d70f07020650f3674ae03244234917a11d | [
"MIT"
] | null | null | null | ML_Files/Cross_Strip_8Fam/.ipynb_checkpoints/Pixelated_32Features_DNN_Time_Label-checkpoint.ipynb | nananasiri/Multiple-Interaction-Photon-Events | af3950d70f07020650f3674ae03244234917a11d | [
"MIT"
] | null | null | null | 108.752066 | 29,104 | 0.71982 | [
[
[
"### This Notebook is done for Pixelated Data for 1 Compton, 2 PhotoElectric with 2 more Ambiguity!\n#### I got 89% Accuracy on Test set!\n##### I am getting X from Blurred Dataset, y as labels from Ground Truth",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nfrom keras.utils import to_categorical\nimport math\n\ndf = {'Label':[],\n 'Theta_P1':[], 'Theta_E1':[], 'Theta_P2':[], 'Theta_E2':[], 'Theta_P3':[], 'Theta_E3':[], 'Theta_P4':[], 'Theta_E4':[],\n 'Theta_P5':[], 'Theta_E5':[], 'Theta_P6':[], 'Theta_E6':[], 'Theta_P7':[], 'Theta_E7':[], 'Theta_P8':[], 'Theta_E8':[],\n 'y': []}\n\nwith open(\"Data/test_Output_8.csv\", 'r') as f:\n counter = 0\n counter_Theta_E = 0\n for line in f:\n sline = line.split('\\t')\n\n if len(sline) == 12:\n df['Label'].append(int(sline[0]))\n df['Theta_P1'].append(float(sline[1]))\n df['Theta_E1'].append(float(sline[4]))\n df['Theta_P2'].append(float(sline[5]))\n df['Theta_E2'].append(float(sline[6])) \n df['Theta_P3'].append(float(sline[7]))\n df['Theta_E3'].append(float(sline[8]))\n df['Theta_P4'].append(float(sline[9]))\n df['Theta_E4'].append(float(sline[10]))\n df['y'].append(int(sline[11]))\n\n \n# df.info() Counts Nan in the dataset\n\ndf = pd.DataFrame(df)\ndf.to_csv('GroundTruth.csv', index=False)\ndf[0:4]",
"_____no_output_____"
],
[
"X = []\ny = []\n\n\ndf = pd.read_csv('GroundTruth.csv')\nfor i in range(0, len(df)-1, 1): # these are from Blurred Data!\n features = df.loc[i, 'Theta_P1':'Theta_E4'].values.tolist()\n label = df.loc[i, 'y':'y'].values.tolist()\n X.append(features)\n y.append(label)\nX = np.array(X)\ny = np.array(y)\ny = to_categorical(y, num_classes=None, dtype='float32')\nprint(y[0])\n\n# ID = df.loc[i,'ID'] # get family ID from blurred dataframe\n# gt_temp_rows = df[df['ID'] == ID] # find corresponding rows in grund truth dataframe\n \n# count = 0\n# if (len(gt_temp_rows)==0) or(len(gt_temp_rows)==1): # yani exactly we have 2 lines!\n# count += 1\n# continue\n\n# idx = gt_temp_rows.index.tolist()[0] # read the first row's index\n \n# # print(len(gt_temp_rows))\n# # print(gt_temp_rows.index.tolist())\n# # # set the target value\n# # print('********************')\n# # print('eventID_label:', int(sline[0]))\n# # print(gt_temp_rows)\n# if (gt_temp_rows.loc[idx, 'DDA':'DDA'].item() <= gt_temp_rows.loc[idx+1, 'DDA':'DDA'].item()):\n# label = 1\n# else:\n# label = 0\n\n# X.append(row1)\n# y.append(label)\n\n \n# X = np.array(X)\n# y = np.array(y)\n# # print(y)\n# y = to_categorical(y, num_classes=None, dtype='float32')\n# # print(y)\n\n",
"[0. 1. 0. 0.]\n"
]
],
[
[
"# Define the Model",
"_____no_output_____"
]
],
[
[
"# Define the keras model\nfrom keras.models import Sequential\nfrom keras.layers import Dense\n\nmodel = Sequential()\nmodel.add(Dense(128, input_dim=X.shape[1], activation='relu')) #8, 8: 58 12, 8:64 32,16: 66 16,16: 67\nmodel.add(Dense(64, activation='relu'))\nmodel.add(Dense(64, activation='relu'))\n\n\nmodel.add(Dense(y.shape[1], activation='softmax'))\nmodel.summary()#CNN, LSTM, RNN, Residual, dense\n\nprint(model)",
"Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense (Dense) (None, 128) 1152 \n_________________________________________________________________\ndense_1 (Dense) (None, 64) 8256 \n_________________________________________________________________\ndense_2 (Dense) (None, 64) 4160 \n_________________________________________________________________\ndense_3 (Dense) (None, 4) 260 \n=================================================================\nTotal params: 13,828\nTrainable params: 13,828\nNon-trainable params: 0\n_________________________________________________________________\n<tensorflow.python.keras.engine.sequential.Sequential object at 0x0000013B61F23EF0>\n"
],
[
"# compile the keras model\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n#loss: categorical_crossentropy (softmax output vector mide: multi class classification) \n#binary_crossentropy (sigmoid output: binary classification)\n#mean_squared_error MSE",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)",
"_____no_output_____"
],
[
"# fit the keras model on the dataset\nhistory = model.fit(X_train, y_train, epochs=220, batch_size=10, validation_split=0.15)",
"Epoch 1/220\n2454/2454 [==============================] - 2s 688us/step - loss: 0.8415 - accuracy: 0.6654 - val_loss: 0.6692 - val_accuracy: 0.7107\nEpoch 2/220\n2454/2454 [==============================] - 1s 594us/step - loss: 0.5653 - accuracy: 0.7582 - val_loss: 0.5379 - val_accuracy: 0.7850\nEpoch 3/220\n2454/2454 [==============================] - 1s 595us/step - loss: 0.5054 - accuracy: 0.7859 - val_loss: 0.4627 - val_accuracy: 0.8121\nEpoch 4/220\n2454/2454 [==============================] - 1s 602us/step - loss: 0.4633 - accuracy: 0.8077 - val_loss: 0.4740 - val_accuracy: 0.8040\nEpoch 5/220\n2454/2454 [==============================] - 2s 620us/step - loss: 0.4354 - accuracy: 0.8174 - val_loss: 0.4228 - val_accuracy: 0.8264\nEpoch 6/220\n2454/2454 [==============================] - 1s 594us/step - loss: 0.4179 - accuracy: 0.8265 - val_loss: 0.4048 - val_accuracy: 0.8338\nEpoch 7/220\n2454/2454 [==============================] - 1s 603us/step - loss: 0.4049 - accuracy: 0.8334 - val_loss: 0.4097 - val_accuracy: 0.8395\nEpoch 8/220\n2454/2454 [==============================] - 1s 601us/step - loss: 0.3880 - accuracy: 0.8390 - val_loss: 0.4002 - val_accuracy: 0.8317\nEpoch 9/220\n2454/2454 [==============================] - 1s 591us/step - loss: 0.3792 - accuracy: 0.8433 - val_loss: 0.4097 - val_accuracy: 0.8324\nEpoch 10/220\n2454/2454 [==============================] - 1s 597us/step - loss: 0.3670 - accuracy: 0.8499 - val_loss: 0.4094 - val_accuracy: 0.8356\nEpoch 11/220\n2454/2454 [==============================] - 1s 598us/step - loss: 0.3670 - accuracy: 0.8490 - val_loss: 0.3698 - val_accuracy: 0.8474\nEpoch 12/220\n2454/2454 [==============================] - 2s 620us/step - loss: 0.3562 - accuracy: 0.8556 - val_loss: 0.3657 - val_accuracy: 0.8557\nEpoch 13/220\n2454/2454 [==============================] - 1s 600us/step - loss: 0.3539 - accuracy: 0.8573 - val_loss: 0.4043 - val_accuracy: 0.8395\nEpoch 14/220\n2454/2454 [==============================] - 1s 595us/step - loss: 0.3456 - accuracy: 0.8578 - val_loss: 0.3665 - val_accuracy: 0.8631\nEpoch 15/220\n2454/2454 [==============================] - 1s 595us/step - loss: 0.3411 - accuracy: 0.8601 - val_loss: 0.3850 - val_accuracy: 0.8538\nEpoch 16/220\n2454/2454 [==============================] - 1s 595us/step - loss: 0.3373 - accuracy: 0.8624 - val_loss: 0.3905 - val_accuracy: 0.8485\nEpoch 17/220\n2454/2454 [==============================] - 1s 594us/step - loss: 0.3356 - accuracy: 0.8641 - val_loss: 0.3600 - val_accuracy: 0.8573\nEpoch 18/220\n2454/2454 [==============================] - 1s 599us/step - loss: 0.3315 - accuracy: 0.8645 - val_loss: 0.3703 - val_accuracy: 0.8506\nEpoch 19/220\n2454/2454 [==============================] - 2s 629us/step - loss: 0.3265 - accuracy: 0.8687 - val_loss: 0.3563 - val_accuracy: 0.8578\nEpoch 20/220\n2454/2454 [==============================] - 1s 597us/step - loss: 0.3252 - accuracy: 0.8701 - val_loss: 0.3461 - val_accuracy: 0.8642\nEpoch 21/220\n2454/2454 [==============================] - 1s 599us/step - loss: 0.3163 - accuracy: 0.8704 - val_loss: 0.3580 - val_accuracy: 0.8605\nEpoch 22/220\n2454/2454 [==============================] - 1s 599us/step - loss: 0.3182 - accuracy: 0.8697 - val_loss: 0.3640 - val_accuracy: 0.8592\nEpoch 23/220\n2454/2454 [==============================] - 1s 597us/step - loss: 0.3137 - accuracy: 0.8754 - val_loss: 0.3668 - val_accuracy: 0.8566\nEpoch 24/220\n2454/2454 [==============================] - 1s 597us/step - loss: 0.3087 - accuracy: 0.8764 - val_loss: 0.3819 - val_accuracy: 0.8532\nEpoch 25/220\n2454/2454 [==============================] - 1s 602us/step - loss: 0.3084 - accuracy: 0.8744 - val_loss: 0.3375 - val_accuracy: 0.8725\nEpoch 26/220\n2454/2454 [==============================] - 2s 615us/step - loss: 0.3074 - accuracy: 0.8755 - val_loss: 0.3529 - val_accuracy: 0.8707\nEpoch 27/220\n2454/2454 [==============================] - 1s 602us/step - loss: 0.3083 - accuracy: 0.8770 - val_loss: 0.3352 - val_accuracy: 0.8686\nEpoch 28/220\n2454/2454 [==============================] - 1s 607us/step - loss: 0.3023 - accuracy: 0.8762 - val_loss: 0.3529 - val_accuracy: 0.8695\nEpoch 29/220\n2454/2454 [==============================] - 1s 596us/step - loss: 0.2997 - accuracy: 0.8803 - val_loss: 0.3144 - val_accuracy: 0.8836\nEpoch 30/220\n2454/2454 [==============================] - 2s 619us/step - loss: 0.2954 - accuracy: 0.8830 - val_loss: 0.3730 - val_accuracy: 0.8580\nEpoch 31/220\n2454/2454 [==============================] - 1s 605us/step - loss: 0.2943 - accuracy: 0.8799 - val_loss: 0.3638 - val_accuracy: 0.8594\nEpoch 32/220\n2454/2454 [==============================] - 1s 600us/step - loss: 0.2921 - accuracy: 0.8818 - val_loss: 0.3469 - val_accuracy: 0.8631\nEpoch 33/220\n2454/2454 [==============================] - 2s 628us/step - loss: 0.2939 - accuracy: 0.8801 - val_loss: 0.3399 - val_accuracy: 0.8719\nEpoch 34/220\n2454/2454 [==============================] - 1s 607us/step - loss: 0.2888 - accuracy: 0.8838 - val_loss: 0.3810 - val_accuracy: 0.8622\nEpoch 35/220\n2454/2454 [==============================] - 1s 602us/step - loss: 0.2902 - accuracy: 0.8829 - val_loss: 0.3454 - val_accuracy: 0.8686\nEpoch 36/220\n2454/2454 [==============================] - 1s 599us/step - loss: 0.2862 - accuracy: 0.8856 - val_loss: 0.3528 - val_accuracy: 0.8631\nEpoch 37/220\n2454/2454 [==============================] - 1s 597us/step - loss: 0.2891 - accuracy: 0.8874 - val_loss: 0.4206 - val_accuracy: 0.8411\nEpoch 38/220\n2454/2454 [==============================] - 1s 602us/step - loss: 0.2881 - accuracy: 0.8846 - val_loss: 0.3407 - val_accuracy: 0.8691\nEpoch 39/220\n2454/2454 [==============================] - 1s 594us/step - loss: 0.2875 - accuracy: 0.8847 - val_loss: 0.3448 - val_accuracy: 0.8758\nEpoch 40/220\n2454/2454 [==============================] - 2s 613us/step - loss: 0.2795 - accuracy: 0.8901 - val_loss: 0.3306 - val_accuracy: 0.8790\nEpoch 41/220\n2454/2454 [==============================] - 1s 606us/step - loss: 0.2813 - accuracy: 0.8867 - val_loss: 0.3220 - val_accuracy: 0.8836\nEpoch 42/220\n2454/2454 [==============================] - 1s 602us/step - loss: 0.2849 - accuracy: 0.8860 - val_loss: 0.3200 - val_accuracy: 0.8737\nEpoch 43/220\n2454/2454 [==============================] - 1s 597us/step - loss: 0.2771 - accuracy: 0.8905 - val_loss: 0.3142 - val_accuracy: 0.8834\nEpoch 44/220\n2454/2454 [==============================] - 1s 600us/step - loss: 0.2771 - accuracy: 0.8901 - val_loss: 0.3222 - val_accuracy: 0.8797\nEpoch 45/220\n2454/2454 [==============================] - 1s 604us/step - loss: 0.2771 - accuracy: 0.8899 - val_loss: 0.3365 - val_accuracy: 0.8767\nEpoch 46/220\n2454/2454 [==============================] - 1s 606us/step - loss: 0.2778 - accuracy: 0.8914 - val_loss: 0.3102 - val_accuracy: 0.8878\nEpoch 47/220\n2454/2454 [==============================] - 2s 619us/step - loss: 0.2705 - accuracy: 0.8927 - val_loss: 0.3235 - val_accuracy: 0.8834\nEpoch 48/220\n2454/2454 [==============================] - 1s 593us/step - loss: 0.2728 - accuracy: 0.8921 - val_loss: 0.3401 - val_accuracy: 0.8730\nEpoch 49/220\n2454/2454 [==============================] - 1s 605us/step - loss: 0.2697 - accuracy: 0.8935 - val_loss: 0.3416 - val_accuracy: 0.8788\nEpoch 50/220\n2454/2454 [==============================] - 1s 594us/step - loss: 0.2717 - accuracy: 0.8952 - val_loss: 0.3277 - val_accuracy: 0.8755\nEpoch 51/220\n2454/2454 [==============================] - 1s 598us/step - loss: 0.2713 - accuracy: 0.8909 - val_loss: 0.3128 - val_accuracy: 0.8906\nEpoch 52/220\n2454/2454 [==============================] - 1s 600us/step - loss: 0.2740 - accuracy: 0.8938 - val_loss: 0.3410 - val_accuracy: 0.8719\nEpoch 53/220\n2454/2454 [==============================] - 1s 603us/step - loss: 0.2673 - accuracy: 0.8966 - val_loss: 0.3262 - val_accuracy: 0.8866\nEpoch 54/220\n2454/2454 [==============================] - 2s 622us/step - loss: 0.2675 - accuracy: 0.8951 - val_loss: 0.3211 - val_accuracy: 0.8864\nEpoch 55/220\n2454/2454 [==============================] - 1s 601us/step - loss: 0.2645 - accuracy: 0.8973 - val_loss: 0.3205 - val_accuracy: 0.8901\nEpoch 56/220\n2454/2454 [==============================] - 1s 597us/step - loss: 0.2662 - accuracy: 0.8964 - val_loss: 0.3228 - val_accuracy: 0.8827\nEpoch 57/220\n2454/2454 [==============================] - 1s 588us/step - loss: 0.2703 - accuracy: 0.8945 - val_loss: 0.3270 - val_accuracy: 0.8818\nEpoch 58/220\n2454/2454 [==============================] - 1s 596us/step - loss: 0.2614 - accuracy: 0.8976 - val_loss: 0.3286 - val_accuracy: 0.8825\nEpoch 59/220\n2454/2454 [==============================] - 1s 599us/step - loss: 0.2612 - accuracy: 0.8970 - val_loss: 0.3346 - val_accuracy: 0.8753\nEpoch 60/220\n2454/2454 [==============================] - 1s 600us/step - loss: 0.2642 - accuracy: 0.8970 - val_loss: 0.3244 - val_accuracy: 0.8834\nEpoch 61/220\n2454/2454 [==============================] - 1s 606us/step - loss: 0.2632 - accuracy: 0.8973 - val_loss: 0.2852 - val_accuracy: 0.9023\nEpoch 62/220\n2454/2454 [==============================] - 1s 596us/step - loss: 0.2554 - accuracy: 0.9002 - val_loss: 0.3242 - val_accuracy: 0.8834\nEpoch 63/220\n2454/2454 [==============================] - 1s 606us/step - loss: 0.2567 - accuracy: 0.8988 - val_loss: 0.3047 - val_accuracy: 0.8873\nEpoch 64/220\n2454/2454 [==============================] - 1s 597us/step - loss: 0.2534 - accuracy: 0.8995 - val_loss: 0.3550 - val_accuracy: 0.8742\nEpoch 65/220\n2454/2454 [==============================] - 1s 593us/step - loss: 0.2627 - accuracy: 0.8972 - val_loss: 0.3401 - val_accuracy: 0.8760\nEpoch 66/220\n2454/2454 [==============================] - 1s 597us/step - loss: 0.2565 - accuracy: 0.9002 - val_loss: 0.3479 - val_accuracy: 0.8739\nEpoch 67/220\n2454/2454 [==============================] - 1s 587us/step - loss: 0.2548 - accuracy: 0.8998 - val_loss: 0.3414 - val_accuracy: 0.8772\nEpoch 68/220\n2454/2454 [==============================] - 1s 594us/step - loss: 0.2562 - accuracy: 0.8993 - val_loss: 0.3248 - val_accuracy: 0.8910\nEpoch 69/220\n2454/2454 [==============================] - 2s 619us/step - loss: 0.2565 - accuracy: 0.8998 - val_loss: 0.3950 - val_accuracy: 0.8735\nEpoch 70/220\n2454/2454 [==============================] - 1s 595us/step - loss: 0.2569 - accuracy: 0.9003 - val_loss: 0.3499 - val_accuracy: 0.8744\nEpoch 71/220\n2454/2454 [==============================] - 1s 597us/step - loss: 0.2565 - accuracy: 0.9003 - val_loss: 0.3454 - val_accuracy: 0.8829\nEpoch 72/220\n2454/2454 [==============================] - 1s 598us/step - loss: 0.2520 - accuracy: 0.9011 - val_loss: 0.3537 - val_accuracy: 0.8804\nEpoch 73/220\n2454/2454 [==============================] - 1s 596us/step - loss: 0.2580 - accuracy: 0.9000 - val_loss: 0.3229 - val_accuracy: 0.8855\nEpoch 74/220\n2454/2454 [==============================] - 1s 591us/step - loss: 0.2533 - accuracy: 0.9024 - val_loss: 0.3445 - val_accuracy: 0.8827\nEpoch 75/220\n2454/2454 [==============================] - 1s 596us/step - loss: 0.2511 - accuracy: 0.9013 - val_loss: 0.3190 - val_accuracy: 0.8929\nEpoch 76/220\n2454/2454 [==============================] - 2s 621us/step - loss: 0.2491 - accuracy: 0.9033 - val_loss: 0.3187 - val_accuracy: 0.8882\nEpoch 77/220\n2454/2454 [==============================] - 1s 593us/step - loss: 0.2479 - accuracy: 0.9026 - val_loss: 0.3116 - val_accuracy: 0.8975\nEpoch 78/220\n2454/2454 [==============================] - 1s 598us/step - loss: 0.2602 - accuracy: 0.9013 - val_loss: 0.3428 - val_accuracy: 0.8746\nEpoch 79/220\n2454/2454 [==============================] - 2s 616us/step - loss: 0.2440 - accuracy: 0.9058 - val_loss: 0.3607 - val_accuracy: 0.8760\nEpoch 80/220\n2454/2454 [==============================] - 1s 603us/step - loss: 0.2573 - accuracy: 0.9003 - val_loss: 0.3614 - val_accuracy: 0.8732\nEpoch 81/220\n2454/2454 [==============================] - 1s 602us/step - loss: 0.2468 - accuracy: 0.9036 - val_loss: 0.3203 - val_accuracy: 0.8855\nEpoch 82/220\n2454/2454 [==============================] - 1s 599us/step - loss: 0.2487 - accuracy: 0.9015 - val_loss: 0.3208 - val_accuracy: 0.8924\nEpoch 83/220\n2454/2454 [==============================] - 2s 625us/step - loss: 0.2494 - accuracy: 0.9029 - val_loss: 0.3304 - val_accuracy: 0.8929\nEpoch 84/220\n2454/2454 [==============================] - 1s 591us/step - loss: 0.2475 - accuracy: 0.9026 - val_loss: 0.3187 - val_accuracy: 0.8889\nEpoch 85/220\n2454/2454 [==============================] - 1s 599us/step - loss: 0.2458 - accuracy: 0.9053 - val_loss: 0.3307 - val_accuracy: 0.8903\nEpoch 86/220\n2454/2454 [==============================] - 1s 598us/step - loss: 0.2453 - accuracy: 0.9051 - val_loss: 0.3361 - val_accuracy: 0.8899\nEpoch 87/220\n2454/2454 [==============================] - 1s 606us/step - loss: 0.2468 - accuracy: 0.9038 - val_loss: 0.3428 - val_accuracy: 0.8866\nEpoch 88/220\n2454/2454 [==============================] - 1s 600us/step - loss: 0.2537 - accuracy: 0.9030 - val_loss: 0.3438 - val_accuracy: 0.8894\nEpoch 89/220\n2454/2454 [==============================] - 1s 600us/step - loss: 0.2452 - accuracy: 0.9064 - val_loss: 0.3408 - val_accuracy: 0.8781\nEpoch 90/220\n2454/2454 [==============================] - 2s 617us/step - loss: 0.2371 - accuracy: 0.9064 - val_loss: 0.3478 - val_accuracy: 0.8758\nEpoch 91/220\n2454/2454 [==============================] - 1s 598us/step - loss: 0.2385 - accuracy: 0.9078 - val_loss: 0.3352 - val_accuracy: 0.8864\nEpoch 92/220\n2454/2454 [==============================] - 1s 600us/step - loss: 0.2470 - accuracy: 0.9038 - val_loss: 0.3823 - val_accuracy: 0.8765\nEpoch 93/220\n2454/2454 [==============================] - 1s 594us/step - loss: 0.2506 - accuracy: 0.9082 - val_loss: 0.3345 - val_accuracy: 0.8903\nEpoch 94/220\n2454/2454 [==============================] - 1s 594us/step - loss: 0.2413 - accuracy: 0.9073 - val_loss: 0.3233 - val_accuracy: 0.8922\nEpoch 95/220\n2454/2454 [==============================] - 1s 597us/step - loss: 0.2415 - accuracy: 0.9057 - val_loss: 0.3053 - val_accuracy: 0.8894\nEpoch 96/220\n2454/2454 [==============================] - 1s 602us/step - loss: 0.2404 - accuracy: 0.9097 - val_loss: 0.3080 - val_accuracy: 0.8966\nEpoch 97/220\n2454/2454 [==============================] - 2s 633us/step - loss: 0.2388 - accuracy: 0.9068 - val_loss: 0.3305 - val_accuracy: 0.8857\nEpoch 98/220\n2454/2454 [==============================] - 1s 603us/step - loss: 0.2442 - accuracy: 0.9059 - val_loss: 0.3332 - val_accuracy: 0.8850\nEpoch 99/220\n2454/2454 [==============================] - 1s 603us/step - loss: 0.2419 - accuracy: 0.9069 - val_loss: 0.3460 - val_accuracy: 0.8832\nEpoch 100/220\n2454/2454 [==============================] - 1s 605us/step - loss: 0.2449 - accuracy: 0.9046 - val_loss: 0.3528 - val_accuracy: 0.8922\nEpoch 101/220\n2454/2454 [==============================] - 1s 603us/step - loss: 0.2378 - accuracy: 0.9083 - val_loss: 0.3646 - val_accuracy: 0.8700\nEpoch 102/220\n2454/2454 [==============================] - 1s 591us/step - loss: 0.2379 - accuracy: 0.9077 - val_loss: 0.3153 - val_accuracy: 0.8977\nEpoch 103/220\n2454/2454 [==============================] - 1s 606us/step - loss: 0.2349 - accuracy: 0.9077 - val_loss: 0.3543 - val_accuracy: 0.8818\nEpoch 104/220\n2454/2454 [==============================] - 2s 625us/step - loss: 0.2349 - accuracy: 0.9079 - val_loss: 0.3582 - val_accuracy: 0.8795\nEpoch 105/220\n2454/2454 [==============================] - 1s 603us/step - loss: 0.2397 - accuracy: 0.9076 - val_loss: 0.3843 - val_accuracy: 0.8702\nEpoch 106/220\n2454/2454 [==============================] - 1s 597us/step - loss: 0.2397 - accuracy: 0.9061 - val_loss: 0.3732 - val_accuracy: 0.8816\nEpoch 107/220\n2454/2454 [==============================] - 1s 602us/step - loss: 0.2360 - accuracy: 0.9086 - val_loss: 0.3170 - val_accuracy: 0.8979\nEpoch 108/220\n2454/2454 [==============================] - 1s 606us/step - loss: 0.2391 - accuracy: 0.9086 - val_loss: 0.3495 - val_accuracy: 0.8802\nEpoch 109/220\n2454/2454 [==============================] - 1s 597us/step - loss: 0.2355 - accuracy: 0.9075 - val_loss: 0.3353 - val_accuracy: 0.8908\nEpoch 110/220\n2454/2454 [==============================] - 1s 598us/step - loss: 0.2397 - accuracy: 0.9072 - val_loss: 0.3281 - val_accuracy: 0.8899\nEpoch 111/220\n"
],
[
"import matplotlib.pyplot as plt\n# Plot training & validation loss values\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Valid'], loc='upper left')\nplt.grid(True)\n# plt.xticks(np.arange(1, 100, 5))\nplt.show()\n\n\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('Model Accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Valid'], loc='upper left')\nplt.grid(True)\n# plt.xticks(np.arange(1, 100, 5))\nplt.show()\n\n",
"_____no_output_____"
],
[
"# Evaluating trained model on test set. This Accuracy came from DDA Labeling\n_, accuracy = model.evaluate(X_test, y_test)\nprint('Accuracy: %.2f' % (accuracy*100))",
"226/226 [==============================] - 0s 540us/step - loss: 0.3584 - accuracy: 0.8997\nAccuracy: 89.97\n"
]
],
[
[
"# HyperParameterOptimization",
"_____no_output_____"
]
],
[
[
"def create_model(hyperParams):\n \n hidden_layers = hyperParams['hidden_layers']\n activation = hyperParams['activation']\n dropout = hyperParams['dropout']\n output_activation = hyperParams['output_activation']\n loss = hyperParams['loss']\n input_size = hyperParams['input_size']\n output_size = hyperParams['output_size']\n \n model = Sequential()\n \n model.add(Dense(hidden_layers[0], input_shape=(input_size,), activation=activation))\n model.add(Dropout(dropout))\n for i in range(len(hidden_layers)-1):\n model.add(Dense(hidden_layers[i], activation=activation))\n model.add(Dropout(dropout))\n model.add(Dense(output_size, activation=output_activation))\n model.compile(loss=loss, optimizer='adam', metrics=['accuracy'])\n # categorical_crossentropy, binary_crossentropy\n \n return model",
"_____no_output_____"
],
[
"def cv_model_fit(X, y, hyperParams):\n \n kfold = KFold(n_splits=10, shuffle=True)\n scores=[]\n for train_idx, test_idx in kfold.split(X):\n model = create_model(hyperParams)\n model.fit(X[train_idx], y[train_idx], batch_size=hyperParams['batch_size'], \n epochs=hyperParams['epochs'], verbose=0)\n score = model.evaluate(X[test_idx], y[test_idx], verbose=0)\n \n scores.append(score*100) # f_score\n# print('fold ', len(scores), ' score: ', scores[-1])\n del model\n \n return scores",
"_____no_output_____"
],
[
"# hyper parameter optimization\nfrom itertools import product\nfrom sklearn.model_selection import KFold\nfrom keras.layers import Activation, Conv2D, Input, Embedding, Reshape, MaxPool2D, Concatenate, Flatten, Dropout, Dense, Conv1D\n\n# default parameter setting:\nhyperParams = {'input_size': 4, 'output_size': 2, 'batch_size': 32, 'epochs': 100, 'hidden_layers': [512, 512, 128],\n 'activation': 'relu', 'dropout': 0.5, 'output_activation': 'softmax', 'loss': 'categorical_crossentropy'}\n\n# parameter search space:\nbatch_chices = [32]\nepochs_choices = [100]\nhidden_layers_choices = [[4, 4], [16, 32],\n [8, 8, 8], [4, 8, 16], \n [4, 4, 4]]\nactivation_choices = ['relu', 'sigmoid'] #, 'tanh'\ndropout_choices = [ 0.5]\n\ns = [batch_chices, epochs_choices, hidden_layers_choices, activation_choices, dropout_choices]\nperms = list(product(*s)) # permutations\n\n# Linear search:\nbest_score = 0\nfor row in perms:\n hyperParams['batch_size'] = row[0]\n hyperParams['epochs'] = row[1]\n hyperParams['hidden_layers'] = row[2]\n hyperParams['activation'] = row[3]\n hyperParams['dropout'] = row[4]\n print('10-fold cross validation on these hyperparameters: ', hyperParams, '\\n')\n cvscores = cv_model_fit(X, y, hyperParams)\n print('\\n-------------------------------------------')\n mean_score = np.mean(cvscores)\n std_score = np.std(cvscores)\n # Update the best parameter setting:\n print('CV mean: {0:0.4f}, CV std: {1:0.4f}'.format(mean_score, std_score))\n if mean_score > best_score: # later I should incorporate std in best model selection\n best_score = mean_score\n print('****** Best model so far ******')\n best_params = hyperParams\n print('-------------------------------------------\\n')",
"10-fold cross validation on these hyperparameters: {'input_size': 4, 'output_size': 2, 'batch_size': 32, 'epochs': 100, 'hidden_layers': [4, 4], 'activation': 'relu', 'dropout': 0.5, 'output_activation': 'softmax', 'loss': 'categorical_crossentropy'} \n\n\n-------------------------------------------\nCV mean: 0.6174, CV std: 0.0522\n****** Best model so far ******\n-------------------------------------------\n\n10-fold cross validation on these hyperparameters: {'input_size': 4, 'output_size': 2, 'batch_size': 32, 'epochs': 100, 'hidden_layers': [4, 4], 'activation': 'sigmoid', 'dropout': 0.5, 'output_activation': 'softmax', 'loss': 'categorical_crossentropy'} \n\n\n-------------------------------------------\nCV mean: 0.6339, CV std: 0.0198\n****** Best model so far ******\n-------------------------------------------\n\n10-fold cross validation on these hyperparameters: {'input_size': 4, 'output_size': 2, 'batch_size': 32, 'epochs': 100, 'hidden_layers': [16, 32], 'activation': 'relu', 'dropout': 0.5, 'output_activation': 'softmax', 'loss': 'categorical_crossentropy'} \n\n\n-------------------------------------------\nCV mean: 0.6068, CV std: 0.0979\n-------------------------------------------\n\n10-fold cross validation on these hyperparameters: {'input_size': 4, 'output_size': 2, 'batch_size': 32, 'epochs': 100, 'hidden_layers': [16, 32], 'activation': 'sigmoid', 'dropout': 0.5, 'output_activation': 'softmax', 'loss': 'categorical_crossentropy'} \n\n\n-------------------------------------------\nCV mean: 0.6069, CV std: 0.0850\n-------------------------------------------\n\n10-fold cross validation on these hyperparameters: {'input_size': 4, 'output_size': 2, 'batch_size': 32, 'epochs': 100, 'hidden_layers': [8, 8, 8], 'activation': 'relu', 'dropout': 0.5, 'output_activation': 'softmax', 'loss': 'categorical_crossentropy'} \n\n\n-------------------------------------------\nCV mean: 0.6117, CV std: 0.0422\n-------------------------------------------\n\n10-fold cross validation on these hyperparameters: {'input_size': 4, 'output_size': 2, 'batch_size': 32, 'epochs': 100, 'hidden_layers': [8, 8, 8], 'activation': 'sigmoid', 'dropout': 0.5, 'output_activation': 'softmax', 'loss': 'categorical_crossentropy'} \n\n\n-------------------------------------------\nCV mean: 0.6086, CV std: 0.0277\n-------------------------------------------\n\n10-fold cross validation on these hyperparameters: {'input_size': 4, 'output_size': 2, 'batch_size': 32, 'epochs': 100, 'hidden_layers': [4, 8, 16], 'activation': 'relu', 'dropout': 0.5, 'output_activation': 'softmax', 'loss': 'categorical_crossentropy'} \n\n\n-------------------------------------------\nCV mean: 0.6153, CV std: 0.0682\n-------------------------------------------\n\n10-fold cross validation on these hyperparameters: {'input_size': 4, 'output_size': 2, 'batch_size': 32, 'epochs': 100, 'hidden_layers': [4, 8, 16], 'activation': 'sigmoid', 'dropout': 0.5, 'output_activation': 'softmax', 'loss': 'categorical_crossentropy'} \n\n\n-------------------------------------------\nCV mean: 0.6379, CV std: 0.0211\n****** Best model so far ******\n-------------------------------------------\n\n10-fold cross validation on these hyperparameters: {'input_size': 4, 'output_size': 2, 'batch_size': 32, 'epochs': 100, 'hidden_layers': [4, 4, 4], 'activation': 'relu', 'dropout': 0.5, 'output_activation': 'softmax', 'loss': 'categorical_crossentropy'} \n\n\n-------------------------------------------\nCV mean: 0.6043, CV std: 0.0690\n-------------------------------------------\n\n10-fold cross validation on these hyperparameters: {'input_size': 4, 'output_size': 2, 'batch_size': 32, 'epochs': 100, 'hidden_layers': [4, 4, 4], 'activation': 'sigmoid', 'dropout': 0.5, 'output_activation': 'softmax', 'loss': 'categorical_crossentropy'} \n\n\n-------------------------------------------\nCV mean: 0.6374, CV std: 0.0246\n-------------------------------------------\n\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
d081bfbf420e9b77b9db4a7a989b7e285578ffc2 | 4,226 | ipynb | Jupyter Notebook | class7/class-7-Selenium.ipynb | JunjieLeiCoe/MSAE-fall2020-CodePrep | 8ee9200b3ba008380155b72b891d608ee946af04 | [
"MIT"
] | 4 | 2021-08-25T13:04:49.000Z | 2021-10-09T04:27:12.000Z | class7/class-7-Selenium.ipynb | JunjieLeiCoe/MSAE-fall2020-CodePrep | 8ee9200b3ba008380155b72b891d608ee946af04 | [
"MIT"
] | 1 | 2021-10-20T04:42:51.000Z | 2021-10-20T04:42:51.000Z | class7/class-7-Selenium.ipynb | JunjieLeiCoe/MSAE-fall2021-CodePrep | 5c5f67e188086f14d09f9fdcae295d238585bdd0 | [
"MIT"
] | null | null | null | 23.477778 | 190 | 0.547563 | [
[
[
"import os",
"_____no_output_____"
],
[
"os.getcwd()",
"_____no_output_____"
],
[
"from selenium import webdriver",
"_____no_output_____"
],
[
"driver = webdriver.Chrome('/Users/leijunjie/Downloads/chromedriver')",
"/var/folders/ys/98s0q77d0bl4mpqsp4lf7c740000gn/T/ipykernel_3361/2163997480.py:1: DeprecationWarning: executable_path has been deprecated, please pass in a Service object\n driver = webdriver.Chrome('/Users/leijunjie/Downloads/chromedriver')\n"
],
[
"url = 'https://www.youtube.com/channel/UCuDWqzSSHgHkD0zBwrIXSNQ/videos'\ndriver.get(url)",
"_____no_output_____"
],
[
"videos=driver.find_elements_by_class_name('style-scope ytd-grid-video-renderer')",
"/var/folders/ys/98s0q77d0bl4mpqsp4lf7c740000gn/T/ipykernel_3361/1992392603.py:1: DeprecationWarning: find_elements_by_* commands are deprecated. Please use find_elements() instead\n videos=driver.find_elements_by_class_name('style-scope ytd-grid-video-renderer')\n"
],
[
"video_list = []\nfor video in videos:\n title = video.find_element_by_xpath('.//*[@id=\"video-title\"]').text\n views = video.find_element_by_xpath('.//*[@id=\"metadata-line\"]/span[1]').text\n when = video.find_element_by_xpath('.//*[@id=\"metadata-line\"]/span[2]').text \n video_item = {\n 'title':title, \n 'views': views, \n 'posted': when\n }\n video_list.append(video_item)\n ",
"/usr/local/lib/python3.9/site-packages/selenium/webdriver/remote/webelement.py:392: UserWarning: find_element_by_* commands are deprecated. Please use find_element() instead\n warnings.warn(\"find_element_by_* commands are deprecated. Please use find_element() instead\")\n"
],
[
"import pandas as pd\ndf =pd.DataFrame(video_list)",
"_____no_output_____"
],
[
"import pandas as pd\ndf.to_csv('test_tmp.csv')",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d081c970f55083889ae056ba105dd569b7ffdafb | 156,682 | ipynb | Jupyter Notebook | Regression/Linear Models/LassoLars_Scale.ipynb | surya2365/ds-seed | 74ef58479333fed95522f7b691f1209f7d70fc95 | [
"Apache-2.0"
] | null | null | null | Regression/Linear Models/LassoLars_Scale.ipynb | surya2365/ds-seed | 74ef58479333fed95522f7b691f1209f7d70fc95 | [
"Apache-2.0"
] | null | null | null | Regression/Linear Models/LassoLars_Scale.ipynb | surya2365/ds-seed | 74ef58479333fed95522f7b691f1209f7d70fc95 | [
"Apache-2.0"
] | null | null | null | 202.431525 | 72,887 | 0.877829 | [
[
[
"# LassoLars Regression with Scale\n",
"_____no_output_____"
],
[
"This Code template is for the regression analysis using a simple LassoLars Regression. It is a lasso model implemented using the LARS algorithm and feature scaling.",
"_____no_output_____"
],
[
"### Required Packages",
"_____no_output_____"
]
],
[
[
"import warnings\r\nimport numpy as np \r\nimport pandas as pd \r\nimport seaborn as se \r\nimport matplotlib.pyplot as plt \r\nfrom sklearn.model_selection import train_test_split \r\nfrom sklearn.pipeline import make_pipeline\r\nfrom sklearn import preprocessing\r\nfrom sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error \r\nfrom sklearn.linear_model import LassoLars\r\nwarnings.filterwarnings('ignore')",
"_____no_output_____"
]
],
[
[
"### Initialization\n\nFilepath of CSV file",
"_____no_output_____"
]
],
[
[
"#filepath\r\nfile_path= \"\"",
"_____no_output_____"
]
],
[
[
"List of features which are required for model training .",
"_____no_output_____"
]
],
[
[
"#x_values\r\nfeatures=[]",
"_____no_output_____"
]
],
[
[
"Target feature for prediction.",
"_____no_output_____"
]
],
[
[
"#y_value\r\ntarget=''",
"_____no_output_____"
]
],
[
[
"### Data Fetching\n\nPandas is an open-source, BSD-licensed library providing high-performance, easy-to-use data manipulation and data analysis tools.\n\nWe will use panda's library to read the CSV file using its storage path.And we use the head function to display the initial row or entry.",
"_____no_output_____"
]
],
[
[
"df=pd.read_csv(file_path)\r\ndf.head()",
"_____no_output_____"
]
],
[
[
"### Feature Selections\n\nIt is the process of reducing the number of input variables when developing a predictive model. Used to reduce the number of input variables to both reduce the computational cost of modelling and, in some cases, to improve the performance of the model.\n\nWe will assign all the required input features to X and target/outcome to Y.",
"_____no_output_____"
]
],
[
[
"X=df[features]\r\nY=df[target]",
"_____no_output_____"
]
],
[
[
"### Data Preprocessing\n\nSince the majority of the machine learning models in the Sklearn library doesn't handle string category data and Null value, we have to explicitly remove or replace null values. The below snippet have functions, which removes the null value if any exists. And convert the string classes data in the datasets by encoding them to integer classes.\n",
"_____no_output_____"
]
],
[
[
"def NullClearner(df):\r\n if(isinstance(df, pd.Series) and (df.dtype in [\"float64\",\"int64\"])):\r\n df.fillna(df.mean(),inplace=True)\r\n return df\r\n elif(isinstance(df, pd.Series)):\r\n df.fillna(df.mode()[0],inplace=True)\r\n return df\r\n else:return df\r\ndef EncodeX(df):\r\n return pd.get_dummies(df)",
"_____no_output_____"
]
],
[
[
"Calling preprocessing functions on the feature and target set.\n",
"_____no_output_____"
]
],
[
[
"x=X.columns.to_list()\r\nfor i in x:\r\n X[i]=NullClearner(X[i])\r\nX=EncodeX(X)\r\nY=NullClearner(Y)\r\nX.head()",
"_____no_output_____"
]
],
[
[
"#### Correlation Map\n\nIn order to check the correlation between the features, we will plot a correlation matrix. It is effective in summarizing a large amount of data where the goal is to see patterns.",
"_____no_output_____"
]
],
[
[
"f,ax = plt.subplots(figsize=(18, 18))\r\nmatrix = np.triu(X.corr())\r\nse.heatmap(X.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax, mask=matrix)\r\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Data Splitting\n\nThe train-test split is a procedure for evaluating the performance of an algorithm. The procedure involves taking a dataset and dividing it into two subsets. The first subset is utilized to fit/train the model. The second subset is used for prediction. The main motive is to estimate the performance of the model on new data.",
"_____no_output_____"
]
],
[
[
"x_train,x_test,y_train,y_test=train_test_split(X,Y,test_size=0.2,random_state=123)",
"_____no_output_____"
]
],
[
[
"###Data Scaling \nStandardize a dataset along any axis.\n\nCenter to the mean and component wise scale to unit variance.<br>\nFor more information... [click here](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.scale.html)",
"_____no_output_____"
]
],
[
[
"\r\nx_train = preprocessing.scale(x_train)\r\nx_test = preprocessing.scale(x_test)",
"_____no_output_____"
]
],
[
[
"### Model\n\nLassoLars is a lasso model implemented using the LARS algorithm, and unlike the implementation based on coordinate descent, this yields the exact solution, which is piecewise linear as a function of the norm of its coefficients.\n\n### Tuning parameters\n\n> **fit_intercept** -> whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations\n\n> **alpha** -> Constant that multiplies the penalty term. Defaults to 1.0. alpha = 0 is equivalent to an ordinary least square, solved by LinearRegression. For numerical reasons, using alpha = 0 with the LassoLars object is not advised and you should prefer the LinearRegression object.\n\n> **eps** -> The machine-precision regularization in the computation of the Cholesky diagonal factors. Increase this for very ill-conditioned systems. Unlike the tol parameter in some iterative optimization-based algorithms, this parameter does not control the tolerance of the optimization.\n\n> **max_iter** -> Maximum number of iterations to perform.\n\n> **positive** -> Restrict coefficients to be >= 0. Be aware that you might want to remove fit_intercept which is set True by default. Under the positive restriction the model coefficients will not converge to the ordinary-least-squares solution for small values of alpha. Only coefficients up to the smallest alpha value (alphas_[alphas_ > 0.].min() when fit_path=True) reached by the stepwise Lars-Lasso algorithm are typically in congruence with the solution of the coordinate descent Lasso estimator.\n\n> **precompute** -> Whether to use a precomputed Gram matrix to speed up calculations. \n\n\n",
"_____no_output_____"
]
],
[
[
"model=LassoLars() \r\nmodel.fit(x_train,y_train)",
"_____no_output_____"
]
],
[
[
"#### Model Accuracy\n\nWe will use the trained model to make a prediction on the test set.Then use the predicted value for measuring the accuracy of our model.\n\nscore: The score function returns the coefficient of determination R2 of the prediction.\n",
"_____no_output_____"
]
],
[
[
"print(\"Accuracy score {:.2f} %\\n\".format(model.score(x_test,y_test)*100))",
"Accuracy score 79.47 %\n\n"
]
],
[
[
"> **r2_score**: The **r2_score** function computes the percentage variablility explained by our model, either the fraction or the count of correct predictions. \n\n> **mae**: The **mean abosolute error** function calculates the amount of total error(absolute average distance between the real data and the predicted data) by our model. \n\n> **mse**: The **mean squared error** function squares the error(penalizes the model for large errors) by our model. ",
"_____no_output_____"
]
],
[
[
"y_pred=model.predict(x_test)\r\nprint(\"R2 Score: {:.2f} %\".format(r2_score(y_test,y_pred)*100))\r\nprint(\"Mean Absolute Error {:.2f}\".format(mean_absolute_error(y_test,y_pred)))\r\nprint(\"Mean Squared Error {:.2f}\".format(mean_squared_error(y_test,y_pred)))",
"R2 Score: 79.47 %\nMean Absolute Error 3923.32\nMean Squared Error 31383167.17\n"
]
],
[
[
"#### Prediction Plot\n\nFirst, we make use of a plot to plot the actual observations, with x_train on the x-axis and y_train on the y-axis.\nFor the regression line, we will use x_train on the x-axis and then the predictions of the x_train observations on the y-axis.",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(14,10))\r\nplt.plot(range(20),y_test[0:20], color = \"green\")\r\nplt.plot(range(20),model.predict(x_test[0:20]), color = \"red\")\r\nplt.legend([\"Actual\",\"prediction\"]) \r\nplt.title(\"Predicted vs True Value\")\r\nplt.xlabel(\"Record number\")\r\nplt.ylabel(target)\r\nplt.show()",
"_____no_output_____"
]
],
[
[
"#### Creator: Anu Rithiga , Github: [Profile](https://github.com/iamgrootsh7)\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
d081d31e81b68e8b63a02c7a554a1a3b16110e55 | 487,180 | ipynb | Jupyter Notebook | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python | 2b21c2d4a6275d5aaf40f09df9cbb8b09f87eed9 | [
"CC-BY-4.0"
] | null | null | null | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python | 2b21c2d4a6275d5aaf40f09df9cbb8b09f87eed9 | [
"CC-BY-4.0"
] | null | null | null | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python | 2b21c2d4a6275d5aaf40f09df9cbb8b09f87eed9 | [
"CC-BY-4.0"
] | null | null | null | 131.741482 | 44,944 | 0.864851 | [
[
[
"[Table of Contents](./table_of_contents.ipynb)",
"_____no_output_____"
],
[
"# Discrete Bayes Filter",
"_____no_output_____"
],
[
"# 离散贝叶斯滤波",
"_____no_output_____"
]
],
[
[
"%matplotlib inline",
"_____no_output_____"
],
[
"#format the book\nimport book_format\nbook_format.set_style()",
"_____no_output_____"
]
],
[
[
"The Kalman filter belongs to a family of filters called *Bayesian filters*. Most textbook treatments of the Kalman filter present the Bayesian formula, perhaps shows how it factors into the Kalman filter equations, but mostly keeps the discussion at a very abstract level. \n\nThat approach requires a fairly sophisticated understanding of several fields of mathematics, and it still leaves much of the work of understanding and forming an intuitive grasp of the situation in the hands of the reader.\n\nI will use a different way to develop the topic, to which I owe the work of Dieter Fox and Sebastian Thrun a great debt. It depends on building an intuition on how Bayesian statistics work by tracking an object through a hallway - they use a robot, I use a dog. I like dogs, and they are less predictable than robots which imposes interesting difficulties for filtering. The first published example of this that I can find seems to be Fox 1999 [1], with a fuller example in Fox 2003 [2]. Sebastian Thrun also uses this formulation in his excellent Udacity course Artificial Intelligence for Robotics [3]. In fact, if you like watching videos, I highly recommend pausing reading this book in favor of first few lessons of that course, and then come back to this book for a deeper dive into the topic.\n\nLet's now use a simple thought experiment, much like we did with the g-h filter, to see how we might reason about the use of probabilities for filtering and tracking.",
"_____no_output_____"
],
[
"卡爾曼濾波器屬於一個名為“貝葉斯濾波器”的大家族。許多教材将卡爾曼濾波器作為貝葉斯公式的範例講授,例如展示貝葉斯公式是如何組成卡爾曼濾波器公式的。這些討論往往停留在抽象层面。\n\n這種學習方法需要讀者理解許多複雜的數學知識,而且無助於讀者直觀地理解卡爾曼濾波器。\n\n我會用不一樣的方式展開這個主題。對此,我首先要感謝Dieter Fox和Sebastian Thrun的工作,從他們那裡我獲益良多。具體来說,我會以如何跟踪走廊上的一個目標為例來為你建立對貝葉斯統計方法的直覺上的理解——別人使用機器人作為目標,而我則喜欢用狗。原因是狗的運動比機器人的更難預測,這為濾波任務帶來許多有趣的挑戰。我找到的關於這類例子最早的記錄見於Fox於1999年所作的【1】,隨後他在2003年的【2】中增加了更多細節。Sebastian Thrun在他的優達學城的“面向机器人学的人工智能”课程上引用了這個例子。如果你喜欢看視頻,我强烈建議你在閱讀本書之前先學一學該課程的前面几節,然后再回来繼續深入了解這個問題。\n\n像先前g-h濾波器一章中那樣,讓我們从一个簡單的思想實驗開始,看看如何用概率工具来解释濾波器和跟蹤器。",
"_____no_output_____"
],
[
"## Tracking a Dog\n\nLet's begin with a simple problem. We have a dog friendly workspace, and so people bring their dogs to work. Occasionally the dogs wander out of offices and down the halls. We want to be able to track them. So during a hackathon somebody invented a sonar sensor to attach to the dog's collar. It emits a signal, listens for the echo, and based on how quickly an echo comes back we can tell whether the dog is in front of an open doorway or not. It also senses when the dog walks, and reports in which direction the dog has moved. It connects to the network via wifi and sends an update once a second.\n\nI want to track my dog Simon, so I attach the device to his collar and then fire up Python, ready to write code to track him through the building. At first blush this may appear impossible. If I start listening to the sensor of Simon's collar I might read **door**, **hall**, **hall**, and so on. How can I use that information to determine where Simon is?\n\nTo keep the problem small enough to plot easily we will assume that there are only 10 positions in the hallway, which we will number 0 to 9, where 1 is to the right of 0. For reasons that will be clear later, we will also assume that the hallway is circular or rectangular. If you move right from position 9, you will be at position 0. \n\nWhen I begin listening to the sensor I have no reason to believe that Simon is at any particular position in the hallway. From my perspective he is equally likely to be in any position. There are 10 positions, so the probability that he is in any given position is 1/10. \n\nLet's represent our belief of his position in a NumPy array. I could use a Python list, but NumPy arrays offer functionality that we will be using soon.",
"_____no_output_____"
],
[
"## 狗的跟蹤問題\n我们先从一个简单的问题开始。因为我们的工作室是宠物友好型,所以同事们会带狗狗到工作场所来。偶尔狗会从办公室跑出来,到走廊去玩。因為我们希望能跟踪狗的运动,所以在一次黑客马拉松上,某个人提出在狗狗的项圈上装一个超声波传感器。传感器能发出声波,并接受回声。根据回声的速度,传感器能够输出狗是否來到了開放的門道前。它能够在狗运动的时候给出信号,报告运动的方向。它还能通过无线网络连接以每秒钟一次的频率上传数据。\n\n我想要跟踪我的狗,西蒙。于是我打开Python,准备編寫代码来实现在建筑内跟踪狗狗的功能。乍看起来这似乎不可能。如果我监听西蒙项圈传来的信号,能得到類似於**门、走廊、走廊**這樣的一连串信号。但我们如何才能使用这些信号确定西蒙的位置呢?\n\n為控制問題的規模以便於繪圖,我們假設走廊中一共僅有10個不同的地點,從0到9標號。1號在0號右側。我們還假設走廊是圓形或矩形的環,其中理由隨後自明。於是當你從9號地點向右移動,你就會回到0點。\n\n我開始監聽傳感器時,我並沒有任何理由相信西蒙現在位於某個具體地點。從這一角度看,他在任意位置的可能性都是均等的。一共有10個位置,所以每個位置的概率都是1/10.\n\n首先,我们将狗狗在各个位置的置信度表示为一个NumPy数组。雖然用Python提供的list也可以,但NumPy数组提供了一些我們需要的功能。",
"_____no_output_____"
]
],
[
[
"import numpy as np\nbelief = np.array([1/10]*10)\nprint(belief)",
"[0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1]\n"
]
],
[
[
"In [Bayesian statistics](https://en.wikipedia.org/wiki/Bayesian_probability) this is called a [*prior*](https://en.wikipedia.org/wiki/Prior_probability). It is the probability prior to incorporating measurements or other information. More completely, this is called the *prior probability distribution*. A [*probability distribution*](https://en.wikipedia.org/wiki/Probability_distribution) is a collection of all possible probabilities for an event. Probability distributions always sum to 1 because something had to happen; the distribution lists all possible events and the probability of each.\n\nI'm sure you've used probabilities before - as in \"the probability of rain today is 30%\". The last paragraph sounds like more of that. But Bayesian statistics was a revolution in probability because it treats probability as a belief about a single event. Let's take an example. I know that if I flip a fair coin infinitely many times I will get 50% heads and 50% tails. This is called [*frequentist statistics*](https://en.wikipedia.org/wiki/Frequentist_inference) to distinguish it from Bayesian statistics. Computations are based on the frequency in which events occur.\n\nI flip the coin one more time and let it land. Which way do I believe it landed? Frequentist probability has nothing to say about that; it will merely state that 50% of coin flips land as heads. In some ways it is meaningless to assign a probability to the current state of the coin. It is either heads or tails, we just don't know which. Bayes treats this as a belief about a single event - the strength of my belief or knowledge that this specific coin flip is heads is 50%. Some object to the term \"belief\"; belief can imply holding something to be true without evidence. In this book it always is a measure of the strength of our knowledge. We'll learn more about this as we go.\n\nBayesian statistics takes past information (the prior) into account. We observe that it rains 4 times every 100 days. From this I could state that the chance of rain tomorrow is 1/25. This is not how weather prediction is done. If I know it is raining today and the storm front is stalled, it is likely to rain tomorrow. Weather prediction is Bayesian.\n\nIn practice statisticians use a mix of frequentist and Bayesian techniques. Sometimes finding the prior is difficult or impossible, and frequentist techniques rule. In this book we can find the prior. When I talk about the probability of something I am referring to the probability that some specific thing is true given past events. When I do that I'm taking the Bayesian approach.\n\nNow let's create a map of the hallway. We'll place the first two doors close together, and then another door further away. We will use 1 for doors, and 0 for walls:",
"_____no_output_____"
],
[
"在[贝叶斯统计学](https://en.wikipedia.org/wiki/Bayesian_probability)中这被称为[先验](https://en.wikipedia.org/wiki/Prior_probability). 它是在考虑测量结果或其它信息之前的概率。更完整的说,这叫做“先验概率”。 所谓[“先验概率”](https://en.wikipedia.org/wiki/Probability_distribution)是某个事件所有可能概率的集合。由于所有可能之中必有其一真实发生,所以概率分布的总和恆等於1。概率分布列出了所有可能的事件及每个事件的对应概率。\n\n我知道你肯定有使用过概率——比如“今天下雨的概率是30%”。這句話與上一段文字有相似的含義。贝叶斯统计是概率论的一场革命,是因为它将概率视作是每个事件的置信度。举例来说,如果我多次抛掷一个理想的硬币,我将得到50%正面,50%反面的统计结果。这叫做[频率统计](https://en.wikipedia.org/wiki/Frequentist_inference)。同贝叶斯统计不同,频率统计的計算基於事件發生的頻率。\n\n假如我再掷一次硬币,我相信它是哪一面落地?频率學派對此沒有什麼建議。它唯一能回答的是,有50%的硬币正面朝上。然而從某些方面看,像這樣为硬币的当前状态赋予概率是无意义的。它要么正要么反,只是我們不確定罷了。贝叶斯学派則將此視為单个事件的信念——它表示我们对该硬币正面朝上的概率是50%的信念或者知识。“信念”一词的含义是,在没有充分的证据的情况下相信某种情况属实。本书中,始终使用置信度来作为对知识的强度的度量。随着阅读的继续,我们将了解更多细节。\n\n贝叶斯统计学考虑過去的信息(先验概率)。通过觀察我们知道过去100天内有4天下雨,据此推出明天下雨的概率是1/25. 当然天气预报不是这么做的。如果我知道今天是雨天,而风暴的边沿移动迟缓,于是我猜测明天继续下雨。这才是天气预报的做法,属于贝叶斯方法。\n\n实践中频率统计和贝叶斯方法常常混合使用。有时候先验难以取得,或者无法取得,就使用频率统计的方法。本书中,先验是提供了的。当我们提到某事的概率时,我们指的是已知过去的系列事件的條件下,某事为真的概率。这时我们使用的是贝叶斯方法。\n\n现在,我们来为走廊建一个地图。我们将两个门靠近放在一起,另一个门放远一些。用1表示门,0表示墙壁。",
"_____no_output_____"
]
],
[
[
"hallway = np.array([1, 1, 0, 0, 0, 0, 0, 0, 1, 0])",
"_____no_output_____"
]
],
[
[
"I start listening to Simon's transmissions on the network, and the first data I get from the sensor is **door**. For the moment assume the sensor always returns the correct answer. From this I conclude that he is in front of a door, but which one? I have no reason to believe he is in front of the first, second, or third door. What I can do is assign a probability to each door. All doors are equally likely, and there are three of them, so I assign a probability of 1/3 to each door. ",
"_____no_output_____"
],
[
"我开始监听西蒙发送到网络的信号,得到的第一个数据是**门**。假設传感器返回的信号永远准确,於是我知道西蒙就在某道门前。但是是哪一道门?我没有理由去相信它现在是在第一道门前。对于第二三道门也是如此。我唯一能做的是为各个门的赋予一个置信度。因为每个门看起来都是等可能的,而有三道门,故我为每道门赋予$1/3$的置信度。",
"_____no_output_____"
]
],
[
[
"import kf_book.book_plots as book_plots\nfrom kf_book.book_plots import figsize, set_figsize\nimport matplotlib.pyplot as plt\n\nbelief = np.array([1/3, 1/3, 0, 0, 0, 0, 0, 0, 1/3, 0])\nbook_plots.bar_plot(belief)",
"_____no_output_____"
]
],
[
[
"This distribution is called a [*categorical distribution*](https://en.wikipedia.org/wiki/Categorical_distribution), which is a discrete distribution describing the probability of observing $n$ outcomes. It is a [*multimodal distribution*](https://en.wikipedia.org/wiki/Multimodal_distribution) because we have multiple beliefs about the position of our dog. Of course we are not saying that we think he is simultaneously in three different locations, merely that we have narrowed down our knowledge to one of these three locations. My (Bayesian) belief is that there is a 33.3% chance of being at door 0, 33.3% at door 1, and a 33.3% chance of being at door 8.\n\nThis is an improvement in two ways. I've rejected a number of hallway positions as impossible, and the strength of my belief in the remaining positions has increased from 10% to 33%. This will always happen. As our knowledge improves the probabilities will get closer to 100%.\n\nA few words about the [*mode*](https://en.wikipedia.org/wiki/Mode_%28statistics%29)\nof a distribution. Given a list of numbers, such as {1, 2, 2, 2, 3, 3, 4}, the *mode* is the number that occurs most often. For this set the mode is 2. A distribution can contain more than one mode. The list {1, 2, 2, 2, 3, 3, 4, 4, 4} contains the modes 2 and 4, because both occur three times. We say the former list is [*unimodal*](https://en.wikipedia.org/wiki/Unimodality), and the latter is *multimodal*.\n\nAnother term used for this distribution is a [*histogram*](https://en.wikipedia.org/wiki/Histogram). Histograms graphically depict the distribution of a set of numbers. The bar chart above is a histogram.\n\nI hand coded the `belief` array in the code above. How would we implement this in code? We represent doors with 1, and walls as 0, so we will multiply the hallway variable by the percentage, like so;",
"_____no_output_____"
],
[
"此分布称为[**分类分布**](https://en.wikipedia.org/wiki/Categorical_distribution),它是描述了$n$个输出的离散分布。它还是[**多峰分布(multimodal distribution)**](https://en.wikipedia.org/wiki/Multimodal_distribution) ,因为它为狗的多种可能位置给出了置信度。当然这不是说我们认为它可以同时出现在三个不同的位置,我们只是根据知识将范围缩小到三个位置之一。我们的(贝叶斯)置信度认为狗狗有33.3%的概率出现在0号门,有33.3%的方式出现在1号门,还有33.3%的方式出现在8号门。\n\n我们的改进体现在两个方面。一是我们拒绝了狗狗在一些位置出现的可能性,二是我们将余下位置的置信度从10%增长到33%。随着我们知识的增加,这种差别会更加明显。\n\n这里要说一說分布的[**众数(mode)**](https://en.wikipedia.org/wiki/Mode_%28statistics%29)。给定一个数组,比如{1, 2, 2, 2, 3, 3, 4}, **众数**是其中出现次数最多的数。对于该例,众数是2. 一个分布可以有多个众数。例如{1, 2, 2, 2, 3, 3, 4, 4, 4}的众数是2和4,因为它们都出现三次。所以第一个数组是[**单峰分布**](https://en.wikipedia.org/wiki/Unimodality),后一个数组是**多峰分布**。\n\n另一个重要的概念是[**直方图**](https://en.wikipedia.org/wiki/Histogram)。直方图通过图像的形式了一系列数组分布。上面那个图就是直方图的一个例子。\n\n上面的置信度数组`belief`是我手算的。如何用代码来实现这个过程呢?我们用1表示门,用0表示墙。我们用一个比例乘以这个数组,如下所示。",
"_____no_output_____"
]
],
[
[
"belief = hallway * (1/3)\nprint(belief)",
"[0.333 0.333 0. 0. 0. 0. 0. 0. 0.333 0. ]\n"
]
],
[
[
"## Extracting Information from Sensor Readings\n\nLet's put Python aside and think about the problem a bit. Suppose we were to read the following from Simon's sensor:\n\n * door\n * move right\n * door\n \n\nCan we deduce Simon's location? Of course! Given the hallway's layout there is only one place from which you can get this sequence, and that is at the left end. Therefore we can confidently state that Simon is in front of the second doorway. If this is not clear, suppose Simon had started at the second or third door. After moving to the right, his sensor would have returned 'wall'. That doesn't match the sensor readings, so we know he didn't start there. We can continue with that logic for all the remaining starting positions. The only possibility is that he is now in front of the second door. Our belief is:",
"_____no_output_____"
],
[
"## 从传感器读数中提取信息\n我们先抛开Python来思考这个问题。假如我们从西蒙的传感器读取到如下数据:\n * 门\n * 右移\n * 门\n \n我们可以推导出西蒙的位置吗?当然可以!根据走廊的地图,只有一个位置可以产生测得的序列,即地图的最左端。因此我们非常肯定西蒙在第二道门前。如果这还不够清晰,可以试着假定西蒙从第二道门或第三道门出发,向右走。这样它的传感器会返回“墙”这个信号。这与传感器实际读数不匹配,所以我们知道这两处不是真正的起点。我们也可以在其它可能起点重复这样的推理。唯一的可能是西蒙目前在第二道门前。我们的置信度是:",
"_____no_output_____"
]
],
[
[
"belief = np.array([0., 1., 0., 0., 0., 0., 0., 0., 0., 0.])",
"_____no_output_____"
]
],
[
[
"I designed the hallway layout and sensor readings to give us an exact answer quickly. Real problems are not so clear cut. But this should trigger your intuition - the first sensor reading only gave us low probabilities (0.333) for Simon's location, but after a position update and another sensor reading we know more about where he is. You might suspect, correctly, that if you had a very long hallway with a large number of doors that after several sensor readings and positions updates we would either be able to know where Simon was, or have the possibilities narrowed down to a small number of possibilities. This is possible when a set of sensor readings only matches one to a few starting locations.\n\nWe could implement this solution now, but instead let's consider a real world complication to the problem.",
"_____no_output_____"
],
[
"我特意将走廊的地图以及传感器的读数设计成这样以方便快速得到准确的答案。但现实问题往往没有这么清晰。但这个例子可以帮助你建立一种直觉——当收到第一个传感器信号的时候,我们只能以一个较低的置信度(0.333)猜测西蒙的位置,但是当第二个传感器数据到来时,我们就获得了更多关于西蒙位置的信息。你猜得对,就算有一道很长的走廊和许多道门,只要我们有一段足够长的传感器读数和位置更新的信息,我们就能定位西蒙,或者将可能性缩小到有限的几种情况。因为有可能一系列传感器读数只能通过个别起始点获得。\n\n我们现在就可以实现该解法,但在此之前,让我们再考虑考虑这个问题在现实世界中的复杂性。",
"_____no_output_____"
],
[
"## Noisy Sensors\n\nPerfect sensors are rare. Perhaps the sensor would not detect a door if Simon sat in front of it while scratching himself, or misread if he is not facing down the hallway. Thus when I get **door** I cannot use 1/3 as the probability. I have to assign less than 1/3 to each door, and assign a small probability to each blank wall position. Something like\n\n```Python\n[.31, .31, .01, .01, .01, .01, .01, .01, .31, .01]\n```\n\nAt first this may seem insurmountable. If the sensor is noisy it casts doubt on every piece of data. How can we conclude anything if we are always unsure?\n\nThe answer, as for the problem above, is with probabilities. We are already comfortable assigning a probabilistic belief to the location of the dog; now we have to incorporate the additional uncertainty caused by the sensor noise. \n\nSay we get a reading of **door**, and suppose that testing shows that the sensor is 3 times more likely to be right than wrong. We should scale the probability distribution by 3 where there is a door. If we do that the result will no longer be a probability distribution, but we will learn how to fix that in a moment.\n\nLet's look at that in Python code. Here I use the variable `z` to denote the measurement. `z` or `y` are customary choices in the literature for the measurement. As a programmer I prefer meaningful variable names, but I want you to be able to read the literature and/or other filtering code, so I will start introducing these abbreviated names now.",
"_____no_output_____"
],
[
"## 传感器噪声\n不存在有理想的傳感器。傳感器有可能在西蒙坐在門前撓癢癢的時候無法給出正确定位,也有可能在沒有正面朝向走廊時候給出錯誤讀數。因此當傳感器傳來“門”這一數據时,我不能使用$1/3$作为其概率,而應使用比$1/3$小的数作为門的概率,然后用一个较小的值作为其它位置的概率。一个可能的情况是:\n\n```Python\n[.31, .31, .01, .01, .01, .01, .01, .01, .31, .01]\n```\n\n乍看之下,问题似乎是无解的。如果传感器含有噪声,那么每一段数据都值得怀疑。在我們無法確定任何事情的情況下,如何下結論呢?\n\n同上面那個問題的回答一樣,我們應該使用概率。我們對於為每個可能的位置賦予一定概率的做法已經習慣了。那麼現在我們需要將傳感器噪聲導致的額外的不確定性考慮進來。\n\n假如我們得到傳感器數據“門”,同時假設根據測試,該類數據正確的概率是錯誤的概率的三倍。在此情況下,概率分佈上對應門的位置應當放大三倍。如果我們這麼做,原來的數據就不再是概率分佈了,但我們後面會介紹修復這個問題的方法。\n\n讓我們看看這種做法用Python怎麼寫。我們這裡用`z`表示測量值。`z`或`y`常常在文獻中用來代表測量值。作為程序員我喜歡更有意義的名字,但我還希望能方便你閱讀有關文獻和查看其它濾波器的代碼,因此我這裡會使用這些簡化的變量名。",
"_____no_output_____"
]
],
[
[
"def update_belief(hall, belief, z, correct_scale):\n for i, val in enumerate(hall):\n if val == z:\n belief[i] *= correct_scale\n\nbelief = np.array([0.1] * 10)\nreading = 1 # 1 is 'door'\nupdate_belief(hallway, belief, z=reading, correct_scale=3.)\nprint('belief:', belief)\nprint('sum =', sum(belief))\nplt.figure()\nbook_plots.bar_plot(belief)",
"belief: [0.3 0.3 0.1 0.1 0.1 0.1 0.1 0.1 0.3 0.1]\nsum = 1.6000000000000003\n"
]
],
[
[
"This is not a probability distribution because it does not sum to 1.0. But the code is doing mostly the right thing - the doors are assigned a number (0.3) that is 3 times higher than the walls (0.1). All we need to do is normalize the result so that the probabilities correctly sum to 1.0. Normalization is done by dividing each element by the sum of all elements in the list. That is easy with NumPy:",
"_____no_output_____"
],
[
"該數組的和不為1,因而不構成一個概率分佈。但代碼所作的事情大致還是對的——門對應的置信度(0.3)是其它位置的置信度(0,1)的三倍。我們只需做一個歸一化,就能使數組的和為1. 所謂歸一化,是將數組的各個元素除以自身的總和。這很容易用NumPy實現:",
"_____no_output_____"
]
],
[
[
"belief / sum(belief)",
"_____no_output_____"
]
],
[
[
"FilterPy implements this with the `normalize` function:\n\n```Python\nfrom filterpy.discrete_bayes import normalize\nnormalize(belief)\n```\n\nIt is a bit odd to say \"3 times as likely to be right as wrong\". We are working in probabilities, so let's specify the probability of the sensor being correct, and compute the scale factor from that. The equation for that is\n\n$$scale = \\frac{prob_{correct}}{prob_{incorrect}} = \\frac{prob_{correct}} {1-prob_{correct}}$$\n\n\n\nAlso, the `for` loop is cumbersome. As a general rule you will want to avoid using `for` loops in NumPy code. NumPy is implemented in C and Fortran, so if you avoid for loops the result often runs 100x faster than the equivalent loop.\n\nHow do we get rid of this `for` loop? NumPy lets you index arrays with boolean arrays. You create a boolean array with logical operators. We can find all the doors in the hallway with:",
"_____no_output_____"
],
[
"FilterPy實現了該歸一化函數`normalize`:\n\n```Python\nfrom filterpy.discrete_bayes import normalize\nnormalize(belief)\n```\n\n“正確概率是錯誤概率三倍”這樣的說法很奇怪。我們既然以概率論為工具,那麼更好的做法還是為指定傳感器正確的概率,並據此計算縮放係數。公式如下\n\n$$scale = \\frac{prob_{correct}}{prob_{incorrect}} = \\frac{prob_{correct}} {1-prob_{correct}}$$\n\n另外,`for`循環也很多餘。通常你需要避免在使用NumPy時寫`for`循環。NumPy是用C和Fortran實現的,如果你能避免經常使用for循環,那麼程序往往能加快100倍。\n\n如何避免`for`循環呢?NumPy可以使用布爾值作為數組的索引。布爾值可以用邏輯運算符得到。我們可以通過如下方式獲得所有門的位置:",
"_____no_output_____"
]
],
[
[
"hallway == 1",
"_____no_output_____"
]
],
[
[
"When you use the boolean array as an index to another array it returns only the elements where the index is `True`. Thus we can replace the `for` loop with\n\n```python\nbelief[hall==z] *= scale\n```\nand only the elements which equal `z` will be multiplied by `scale`.\n\nTeaching you NumPy is beyond the scope of this book. I will use idiomatic NumPy constructs and explain them the first time I present them. If you are new to NumPy there are many blog posts and videos on how to use NumPy efficiently and idiomatically.\n\nHere is our improved version:",
"_____no_output_____"
],
[
"當你使用布爾類型數組作為其他數組的索引的時候,就會得到對應值為真的位置。根據這個原理我們可以用下面的代碼替換掉前面使用的`for`循環\n\n```python\nbelief[hall==z] *= scale\n```\n\n這樣,只有對應`z`的位置的元素會被縮放`scale`倍。\n\n本書的目的不是NumPy教學。我只會使用常見的NumPy寫法,並且在引入新用法的時候做介紹。如果你是NumPy的新手,網絡上又許多介紹如何高效、規範使用NumPy的文章和視頻。\n\n經過改進的代碼如下:",
"_____no_output_____"
]
],
[
[
"from filterpy.discrete_bayes import normalize\n\ndef scaled_update(hall, belief, z, z_prob): \n scale = z_prob / (1. - z_prob)\n belief[hall==z] *= scale\n normalize(belief)\n\nbelief = np.array([0.1] * 10)\nscaled_update(hallway, belief, z=1, z_prob=.75)\n\nprint('sum =', sum(belief))\nprint('probability of door =', belief[0])\nprint('probability of wall =', belief[2])\nbook_plots.bar_plot(belief, ylim=(0, .3))",
"sum = 1.0\nprobability of door = 0.1875\nprobability of wall = 0.06249999999999999\n"
]
],
[
[
" We can see from the output that the sum is now 1.0, and that the probability of a door vs wall is still three times larger. The result also fits our intuition that the probability of a door must be less than 0.333, and that the probability of a wall must be greater than 0.0. Finally, it should fit our intuition that we have not yet been given any information that would allow us to distinguish between any given door or wall position, so all door positions should have the same value, and the same should be true for wall positions.\n \nThis result is called the [*posterior*](https://en.wikipedia.org/wiki/Posterior_probability), which is short for *posterior probability distribution*. All this means is a probability distribution *after* incorporating the measurement information (posterior means 'after' in this context). To review, the *prior* is the probability distribution before including the measurement's information. \n\nAnother term is the [*likelihood*](https://en.wikipedia.org/wiki/Likelihood_function). When we computed `belief[hall==z] *= scale` we were computing how *likely* each position was given the measurement. The likelihood is not a probability distribution because it does not sum to one.\n\nThe combination of these gives the equation\n\n$$\\mathtt{posterior} = \\frac{\\mathtt{likelihood} \\times \\mathtt{prior}}{\\mathtt{normalization}}$$ \n\nWhen we talk about the filter's output we typically call the state after performing the prediction the *prior* or *prediction*, and we call the state after the update either the *posterior* or the *estimated state*. \n\nIt is very important to learn and internalize these terms as most of the literature uses them extensively.\n\nDoes `scaled_update()` perform this computation? It does. Let me recast it into this form:",
"_____no_output_____"
],
[
"我們可以通過程序輸出看到數組的和為1.0,同時對應于門的概率是墻壁的概率的三倍。同時,結果顯示對應門的概率小於0.333,這是符合我們直覺的。除此之外,由於我們沒有任何信息能幫助我們對各個門、墻進行內部區分,因此所有墻壁具有一樣的概率,所有門具有一樣的概率,這也是符合我們認識的。\n\n這個結果即所謂的[**後驗**](https://en.wikipedia.org/wiki/Posterior_probability),是**後驗概率分佈**的縮寫。這表示該概率分佈是在考慮測量結果信息**之後**得到的(英文的posterior在此上下文中意思等同於after)。複習一下,**先驗**概率是考慮測量結果信息之前的概率分佈。\n\n另一個術語是[**似然**](https://en.wikipedia.org/wiki/Likelihood_function). 當我們計算`belief[hall==z] *= scale`時,我們計算的是給定測量結果後每個位置的**似然**程度。似然度不是概率分佈,因為其和不必等於1. \n\n結合上述步驟可以得到如下公式\n\n$$\\mathtt{posterior} = \\frac{\\mathtt{likelihood} \\times \\mathtt{prior}}{\\mathtt{normalization}}$$ \n\n當我們討論濾波器的輸出的時候,我們一般將更新前的狀態叫做**先驗**或者**預測**,將更新後的狀態叫做**後驗**或者**估計**。\n\n大多數相關文獻廣泛使用類似術語,因此學習和內化這些術語非常重要。\n\n函數`scaled_update()`包含了此操作了嗎?答案是肯定的。我們可以將其轉化為如下形式:",
"_____no_output_____"
]
],
[
[
"def scaled_update(hall, belief, z, z_prob): \n scale = z_prob / (1. - z_prob)\n likelihood = np.ones(len(hall))\n likelihood[hall==z] *= scale\n return normalize(likelihood * belief)",
"_____no_output_____"
]
],
[
[
"This function is not fully general. It contains knowledge about the hallway, and how we match measurements to it. We always strive to write general functions. Here we will remove the computation of the likelihood from the function, and require the caller to compute the likelihood themselves.\n\nHere is a full implementation of the algorithm:\n\n```python\ndef update(likelihood, prior):\n return normalize(likelihood * prior)\n```\n\nComputation of the likelihood varies per problem. For example, the sensor might not return just 1 or 0, but a `float` between 0 and 1 indicating the probability of being in front of a door. It might use computer vision and report a blob shape that you then probabilistically match to a door. It might use sonar and return a distance reading. In each case the computation of the likelihood will be different. We will see many examples of this throughout the book, and learn how to perform these calculations.\n\nFilterPy implements `update`. Here is the previous example in a fully general form:",
"_____no_output_____"
],
[
"這個函數還不夠通用。它包含有關於走廊問題以及測量方法的知識。而我們總是盡可能寫通用的函數。這裡我們要從函數中移除似然度的計算,要求函數調用者計算似然度。\n\n算法的完整實現如下:\n\n```python\ndef update(likelihood, prior):\n return normalize(likelihood * prior)\n```\n\n對於不同問題,似然度計算方法不盡相同。例如,傳感器可能返回的不是0、1信號,而是返回一個出於0和1之間的浮點型小數用於表示目標出於門前的概率。它可能採用計算機視覺的方法去檢測團塊的外形來計算目標物體是門的概率。它也可能通過傳感器獲得距離的讀數。在不同的案例中,計算似然度的方式也不相同。本書中會介紹許多種不同的例子及對應的計算方式。\n\nFilterPy也實現了`update`函數。前面的例子用完全通用的形式寫出來會是這樣:",
"_____no_output_____"
]
],
[
[
"from filterpy.discrete_bayes import update\n\ndef lh_hallway(hall, z, z_prob):\n \"\"\" compute likelihood that a measurement matches\n positions in the hallway.\"\"\"\n \n try:\n scale = z_prob / (1. - z_prob)\n except ZeroDivisionError:\n scale = 1e8\n\n likelihood = np.ones(len(hall))\n likelihood[hall==z] *= scale\n return likelihood\n\nbelief = np.array([0.1] * 10)\nlikelihood = lh_hallway(hallway, z=1, z_prob=.75)\nupdate(likelihood, belief) ",
"_____no_output_____"
]
],
[
[
"## Incorporating Movement\n\nRecall how quickly we were able to find an exact solution when we incorporated a series of measurements and movement updates. However, that occurred in a fictional world of perfect sensors. Might we be able to find an exact solution with noisy sensors?\n\nUnfortunately, the answer is no. Even if the sensor readings perfectly match an extremely complicated hallway map, we cannot be 100% certain that the dog is in a specific position - there is, after all, a tiny possibility that every sensor reading was wrong! Naturally, in a more typical situation most sensor readings will be correct, and we might be close to 100% sure of our answer, but never 100% sure. This may seem complicated, but let's go ahead and program the math.\n\nFirst let's deal with the simple case - assume the movement sensor is perfect, and it reports that the dog has moved one space to the right. How would we alter our `belief` array?\n\nI hope that after a moment's thought it is clear that we should shift all the values one space to the right. If we previously thought there was a 50% chance of Simon being at position 3, then after he moved one position to the right we should believe that there is a 50% chance he is at position 4. The hallway is circular, so we will use modulo arithmetic to perform the shift.",
"_____no_output_____"
],
[
"## 考慮運動模型\n\n回想一下之前我們是如何通過同時考慮一系列測量值和運動模型來快速找出準確解的。但是,該解法只存在於可以使用理想傳感器的幻想世界中。我們是否可以通過帶有噪聲的傳感器獲得精確解呢?\n\n不幸的是,答案是否定的。即使傳感器讀數和複雜的走廊地圖完美吻合,我們還是無法百分百確定狗的確切位置——畢竟每個傳感器讀書都有小概率出錯!自然,在典型的環境中,大多數傳感器數據都是正確的,這使得我們的推理正確的概率接近100%,但也永遠達不到100%。這看起來有點複雜,我們且繼續前進,把數學代碼寫出來。\n\n我們先解決一個簡單的問題——假如運動傳感器是準確的,它回報說狗向右移動一步。此時我們應如何更新`belief`數組?\n\n略經思考,你已明白,我們應當將所有數值向右移動一步。假如我們先前認為西蒙處於位置3的概率為50%,那麼現在它處於位置4的概率為50%。走廊是環形的,所以我們使用取模運算來執行此操作。",
"_____no_output_____"
]
],
[
[
"def perfect_predict(belief, move):\n \"\"\" move the position by `move` spaces, where positive is \n to the right, and negative is to the left\n \"\"\"\n n = len(belief)\n result = np.zeros(n)\n for i in range(n):\n result[i] = belief[(i-move) % n]\n return result\n \nbelief = np.array([.35, .1, .2, .3, 0, 0, 0, 0, 0, .05])\nplt.subplot(121)\nbook_plots.bar_plot(belief, title='Before prediction', ylim=(0, .4))\n\nbelief = perfect_predict(belief, 1)\nplt.subplot(122)\nbook_plots.bar_plot(belief, title='After prediction', ylim=(0, .4))",
"_____no_output_____"
]
],
[
[
"We can see that we correctly shifted all values one position to the right, wrapping from the end of the array back to the beginning. \n\nThe next cell animates this so you can see it in action. Use the slider to move forwards and backwards in time. This simulates Simon walking around and around the hallway. It does not yet incorporate new measurements so the probability distribution does not change shape, only position.",
"_____no_output_____"
],
[
"可見我們正確地將所有數值都向右移動了一步,最右邊的數組回到了數組的左側。\n\n下一個單元格輸出一個動畫。你可以用滑塊在時間上前移或後移。這就好像西蒙在走廊上四處遊走一般。因為沒有新的測量結果進來,分佈只是發生平移,形狀沒有改變。",
"_____no_output_____"
]
],
[
[
"from ipywidgets import interact, IntSlider\n\nbelief = np.array([.35, .1, .2, .3, 0, 0, 0, 0, 0, .05])\nperfect_beliefs = []\n\nfor _ in range(20):\n # Simon takes one step to the right\n belief = perfect_predict(belief, 1)\n perfect_beliefs.append(belief)\n\ndef simulate(time_step):\n book_plots.bar_plot(perfect_beliefs[time_step], ylim=(0, .4))\n \ninteract(simulate, time_step=IntSlider(value=0, max=len(perfect_beliefs)-1));",
"_____no_output_____"
]
],
[
[
"## Terminology\n\nLet's pause a moment to review terminology. I introduced this terminology in the last chapter, but let's take a second to help solidify your knowledge. \n\nThe *system* is what we are trying to model or filter. Here the system is our dog. The *state* is its current configuration or value. In this chapter the state is our dog's position. We rarely know the actual state, so we say our filters produce the *estimated state* of the system. In practice this often gets called the state, so be careful to understand the context.\n \nOne cycle of prediction and updating with a measurement is called the state or system *evolution*, which is short for *time evolution* [7]. Another term is *system propagation*. It refers to how the state of the system changes over time. For filters, time is usually a discrete step, such as 1 second. For our dog tracker the system state is the position of the dog, and the state evolution is the position after a discrete amount of time has passed.\n\nWe model the system behavior with the *process model*. Here, our process model is that the dog moves one or more positions at each time step. This is not a particularly accurate model of how dogs behave. The error in the model is called the *system error* or *process error*. \n\nThe prediction is our new *prior*. Time has moved forward and we made a prediction without benefit of knowing the measurements. \n\nLet's work an example. The current position of the dog is 17 m. Our epoch is 2 seconds long, and the dog is traveling at 15 m/s. Where do we predict he will be in two seconds? \n\nClearly,\n\n$$ \\begin{aligned}\n\\bar x &= 17 + (15*2) \\\\\n&= 47\n\\end{aligned}$$\n\nI use bars over variables to indicate that they are priors (predictions). We can write the equation for the process model like this:\n\n$$ \\bar x_{k+1} = f_x(\\bullet) + x_k$$\n\n$x_k$ is the current position or state. If the dog is at 17 m then $x_k = 17$.\n\n$f_x(\\bullet)$ is the state propagation function for x. It describes how much the $x_k$ changes over one time step. For our example it performs the computation $15 \\cdot 2$ so we would define it as \n\n$$f_x(v_x, t) = v_k t$$.",
"_____no_output_____"
],
[
"## 術語\n我們暫停複習一下術語。我上一章已經介紹過這些術語,但我們稍微花幾秒鐘鞏固一下知識。\n\n所谓**系統**是我們嘗試建模和濾波的對象。這裡,系統指的是那隻狗。**狀態**表示當前的配置或數值。本章中,狀態是狗的位置。我們一般無法知道真實的狀態,所以我們說濾波器得到的是**狀態估計**。實踐中我們往往也將其稱為狀態,所以你要小心理解上下文。\n\n一個預測步和一個根據測量更新狀態的更新步構成一個循環,這個循環被稱為狀態的**演化**,或系統的演化,它是**時間演化**【7】的縮寫。另一個術語是**系統傳播**。他指的是狀態是如何隨著時間改變的。對於濾波器,時間步是離散的,例如一秒的時間。對於我們的狗的跟蹤問題而言,系統的狀態是狗的位置,狀態的演化是經過一段離散的時間步後狗的位置的改變。\n\n我們用“過程模型”來建模系統的行為。這裡,我們的過程模型是夠經過每個時間步都會移動一段距離。這個模型並不精確地建模狗的運動。模型的誤差稱為“系統誤差”或者“過程誤差”。\n\n每個預測結果都給我們一個新的“先驗”。隨著時間的推進,我們在無測量結果輔助的情況下做出下一時刻的預測。\n\n讓我們看一個例子。當前狗的位置是17m。一個時間步是兩秒,狗的速度是15米每秒。我們預測它兩秒後的位置會在哪裡。\n\n顯而易見,\n\n$$ \\begin{aligned}\n\\bar x &= 17 + (15*2) \\\\\n&= 47\n\\end{aligned}$$\n\n我通過在符號上加一橫表示先驗(即預測結果)。我們將過程模型用公式表示出來,如下所示:\n\n$$ \\bar x_{k+1} = f_x(\\bullet) + x_k$$\n\n$x_k$是當前位置或狀態,如果狗在17 m處,那麼$x_k = 17$.\n\n$f_x(\\bullet)$是x的狀態傳播函數。它描述了$x_k$經過一個時間步的改變程度。對於這個例子,它執行了此計算$15 \\cdot 2$,所以我們將它定義為 \n\n$$f_x(v_x, t) = v_k t$$",
"_____no_output_____"
],
[
"## Adding Uncertainty to the Prediction\n\n`perfect_predict()` assumes perfect measurements, but all sensors have noise. What if the sensor reported that our dog moved one space, but he actually moved two spaces, or zero? This may sound like an insurmountable problem, but let's model it and see what happens.\n\nAssume that the sensor's movement measurement is 80% likely to be correct, 10% likely to overshoot one position to the right, and 10% likely to undershoot to the left. That is, if the movement measurement is 4 (meaning 4 spaces to the right), the dog is 80% likely to have moved 4 spaces to the right, 10% to have moved 3 spaces, and 10% to have moved 5 spaces.\n\nEach result in the array now needs to incorporate probabilities for 3 different situations. For example, consider the reported movement of 2. If we are 100% certain the dog started from position 3, then there is an 80% chance he is at 5, and a 10% chance for either 4 or 6. Let's try coding that:",
"_____no_output_____"
],
[
"## 在預測中考慮不確定性\n\n`perfect_predict()`函數假定測量是完美的,但實際上所有傳感器都有噪聲。如果傳感器顯示狗移動了一位,但實際上移動了兩位,會發生什麼?又或者實際上沒有移動呢?雖然這個問題乍看之下是無法解決的,但我們還是先建模一下問題,看看會發生什麼。\n\n設傳感器測量的位移有80%的幾率是正確的,10%的幾率給出右偏一位的值,10%的概率給出左偏一位的值。即是說,如果傳感器測得的位移是4(向右移4位),那麼狗有80%的概率向右移4位,有10%的概率向右移3位,有10%的概率向右移5位。\n\n對於數組中的每一個結果,我們都需要考慮三種情況的概率。例如,若傳感器報告位移為2,且我們百分百確定狗是從位置3起步的,那麼此時狗有80%的概率位於位置5,各有10%的概率位於4或6.\n我們試著用代碼的形式表達這個問題:",
"_____no_output_____"
]
],
[
[
"def predict_move(belief, move, p_under, p_correct, p_over):\n n = len(belief)\n prior = np.zeros(n)\n for i in range(n):\n prior[i] = (\n belief[(i-move) % n] * p_correct +\n belief[(i-move-1) % n] * p_over +\n belief[(i-move+1) % n] * p_under) \n return prior\n\nbelief = [0., 0., 0., 1., 0., 0., 0., 0., 0., 0.]\nprior = predict_move(belief, 2, .1, .8, .1)\nbook_plots.plot_belief_vs_prior(belief, prior)",
"_____no_output_____"
]
],
[
[
"It appears to work correctly. Now what happens when our belief is not 100% certain?",
"_____no_output_____"
],
[
"看起來代碼工作正常。現在我們看看置信度不是100%的情況會是怎樣?",
"_____no_output_____"
]
],
[
[
"belief = [0, 0, .4, .6, 0, 0, 0, 0, 0, 0]\nprior = predict_move(belief, 2, .1, .8, .1)\nbook_plots.plot_belief_vs_prior(belief, prior)\nprior",
"_____no_output_____"
]
],
[
[
"Here the results are more complicated, but you should still be able to work it out in your head. The 0.04 is due to the possibility that the 0.4 belief undershot by 1. The 0.38 is due to the following: the 80% chance that we moved 2 positions (0.4 $\\times$ 0.8) and the 10% chance that we undershot (0.6 $\\times$ 0.1). Overshooting plays no role here because if we overshot both 0.4 and 0.6 would be past this position. **I strongly suggest working some examples until all of this is very clear, as so much of what follows depends on understanding this step.**\n\nIf you look at the probabilities after performing the update you might be dismayed. In the example above we started with probabilities of 0.4 and 0.6 in two positions; after performing the update the probabilities are not only lowered, but they are strewn out across the map.\n\nThis is not a coincidence, or the result of a carefully chosen example - it is always true of the prediction. If the sensor is noisy we lose some information on every prediction. Suppose we were to perform the prediction an infinite number of times - what would the result be? If we lose information on every step, we must eventually end up with no information at all, and our probabilities will be equally distributed across the `belief` array. Let's try this with 100 iterations. The plot is animated; use the slider to change the step number.",
"_____no_output_____"
],
[
"儘管現在情況更加複雜了,但你還是能夠用你的大腦的理解它。0.04是對應0.4置信度的信念被高估的可能性。而0.38是這樣算來的:有80%的概率移動了兩步 (0.4 $\\times$ 0.8)和10%概率高估了位移(0.6 $\\times$ 0.1)。低估的情況不參與計算,因為這種情況下對應於0.4和0.6的信念都會跳過該點。**我強烈建議你多使幾個例子,直到你深刻理解它們,這是因為後面許多內容都依賴於這一步。**\n\n如果你看過更新後的概率,那你可能會感覺失望。上面的例子中,我們開始時對兩個位置各有0.4和0.6的置信度;在更新後,置信度不僅減小了,它們還在地圖上分散開來。\n\n這不是偶然,也不是特意挑選的例子才能產生的結果——不論如何,預測的結果永遠會像這樣。如果傳感器包含噪聲,我們每次預測就都會丟失信息。假如我們在無限的時間裡無數次預測——結果會是怎樣?如果我們每次預測都丟失信息,我們最終會什麼信息都無法留下,我們的`belief`數組上的概率分佈將會處處均等。我們試試迭代100次。下面是繪製的動畫。你可以用滑塊來逐步瀏覽。\n",
"_____no_output_____"
]
],
[
[
"belief = np.array([1.0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\npredict_beliefs = []\n \nfor i in range(100):\n belief = predict_move(belief, 1, .1, .8, .1)\n predict_beliefs.append(belief)\n\nprint('Final Belief:', belief)\n\n# make interactive plot\ndef show_prior(step):\n book_plots.bar_plot(predict_beliefs[step-1])\n plt.title(f'Step {step}')\n\ninteract(show_prior, step=IntSlider(value=1, max=len(predict_beliefs)));",
"Final Belief: [0.104 0.103 0.101 0.099 0.097 0.096 0.097 0.099 0.101 0.103]\n"
],
[
"print('Final Belief:', belief)",
"Final Belief: [0.104 0.103 0.101 0.099 0.097 0.096 0.097 0.099 0.101 0.103]\n"
]
],
[
[
"After 100 iterations we have lost almost all information, even though we were 100% sure that we started in position 0. Feel free to play with the numbers to see the effect of differing number of updates. For example, after 100 updates a small amount of information is left, after 50 a lot is left, but by 200 iterations essentially all information is lost.",
"_____no_output_____"
],
[
"儘管我們以100%的置信度相信我們從0點開始,100次迭代後我們仍然幾乎丟失了所有信息。請隨意改變數目,觀察步數的影響。例如,經過100次更新,仍存在有一小部分信息;50次更新後,留下的信息較多;而200次更新後基本上所有數據都丟失了。",
"_____no_output_____"
],
[
"And, if you are viewing this online here is an animation of that output.\n<img src=\"animations/02_no_info.gif\">\n\nI will not generate these standalone animations through the rest of the book. Please see the preface for instructions to run this book on the web, for free, or install IPython on your computer. This will allow you to run all of the cells and see the animations. It's very important that you practice with this code, not just read passively.",
"_____no_output_____"
],
[
"另外,如果你通過線上方式閱讀本書,你會看到這裡有輸出的動圖。\n<img src=\"animations/02_no_info.gif\">\n\n這之後我就不會再生成單獨的動圖了。請遵循本前言部分的介紹在網頁上,或者在你電腦上配置IPython以免費運行本書內容。這樣你就能運行所有單元格並且看到動圖。為了能練習本書代碼而不僅僅是被動閱讀,這點非常重要。",
"_____no_output_____"
],
[
"## Generalizing with Convolution\n\nWe made the assumption that the movement error is at most one position. But it is possible for the error to be two, three, or more positions. As programmers we always want to generalize our code so that it works for all cases. \n\nThis is easily solved with [*convolution*](https://en.wikipedia.org/wiki/Convolution). Convolution modifies one function with another function. In our case we are modifying a probability distribution with the error function of the sensor. The implementation of `predict_move()` is a convolution, though we did not call it that. Formally, convolution is defined as",
"_____no_output_____"
],
[
"## 在卷積的幫助下推廣該方法\n\n我們先前假設位移的誤差最多不差過一位。但實際上可能有兩位、三位、甚至更多。作為程序員,我們總希望能將我們的代碼推廣到適應所有情況。\n\n這可以藉助[**卷積**](https://en.wikipedia.org/wiki/Convolution)工具輕鬆解決。卷積通過一個函數來修改另一個函數。在我們的案例中,我們用傳感器的誤差函數修改概率分佈。雖然我們之前沒這麼稱呼它,但`predict_move()`函數的實現就是一個卷積。卷積的正式定義如下:",
"_____no_output_____"
],
[
"$$ (f \\ast g) (t) = \\int_0^t \\!f(\\tau) \\, g(t-\\tau) \\, \\mathrm{d}\\tau$$",
"_____no_output_____"
],
[
"where $f\\ast g$ is the notation for convolving f by g. It does not mean multiply.\n\nIntegrals are for continuous functions, but we are using discrete functions. We replace the integral with a summation, and the parenthesis with array brackets.\n\n$$ (f \\ast g) [t] = \\sum\\limits_{\\tau=0}^t \\!f[\\tau] \\, g[t-\\tau]$$\n\nComparison shows that `predict_move()` is computing this equation - it computes the sum of a series of multiplications.\n\n[Khan Academy](https://www.khanacademy.org/math/differential-equations/laplace-transform/convolution-integral/v/introduction-to-the-convolution) [4] has a good introduction to convolution, and Wikipedia has some excellent animations of convolutions [5]. But the general idea is already clear. You slide an array called the *kernel* across another array, multiplying the neighbors of the current cell with the values of the second array. In our example above we used 0.8 for the probability of moving to the correct location, 0.1 for undershooting, and 0.1 for overshooting. We make a kernel of this with the array `[0.1, 0.8, 0.1]`. All we need to do is write a loop that goes over each element of our array, multiplying by the kernel, and summing the results. To emphasize that the belief is a probability distribution I have named it `pdf`.",
"_____no_output_____"
],
[
"其中 $f\\ast g$ 表示f和g的卷積。它不代表乘法。\n\n積分對應於連續函數,但我們使用的是離散函數。我們將積分替換為求和符號,將圓括號換成數組使用的方括號。\n\n$$ (f \\ast g) [t] = \\sum\\limits_{\\tau=0}^t \\!f[\\tau] \\, g[t-\\tau]$$\n\n比較發現`predict_move()`是在實行該計算——即一系列數值的積的和。\n\n[可汗學院](https://www.khanacademy.org/math/differential-equations/laplace-transform/convolution-integral/v/introduction-to-the-convolution) 【4】很好地介紹了卷積。維基百科提供了描繪卷積的優美動圖【5】。不論如何,卷積的大概思想是清除易懂的。你將一個稱為“核(kernel)”的數組劃過另一個數組,連同當前單元格的鄰接單元格與對應數組上的單元格相乘。在上面的例子中,我們用0.8作為正確估計的概率,0.1作為高估的概率,0.1作為低估的概率。這可以用數組`[0.1, 0.8, 0.1]`構成的核來表示。我們所要做的事情循環遍歷數組的每一元素,與核對應相乘,對結果求和。為強調置信度是一個概率分佈,我用`pdf`作為變量名。",
"_____no_output_____"
]
],
[
[
"def predict_move_convolution(pdf, offset, kernel):\n N = len(pdf)\n kN = len(kernel)\n width = int((kN - 1) / 2)\n\n prior = np.zeros(N)\n for i in range(N):\n for k in range (kN):\n index = (i + (width-k) - offset) % N\n prior[i] += pdf[index] * kernel[k]\n return prior",
"_____no_output_____"
]
],
[
[
"This illustrates the algorithm, but it runs very slow. SciPy provides a convolution routine `convolve()` in the `ndimage.filters` module. We need to shift the pdf by `offset` before convolution; `np.roll()` does that. The move and predict algorithm can be implemented with one line:\n\n```python\nconvolve(np.roll(pdf, offset), kernel, mode='wrap')\n```\n\nFilterPy implements this with `discrete_bayes`' `predict()` function.",
"_____no_output_____"
],
[
"雖然該函數演示了算法執行流程,然而它執行得很慢。SciPy庫在`ndimage.filters`包中提供了卷積操作`convolve()`。我們要在作卷積前先將pdf平移`offset`步,這可以通過`np.roll()`函數實現。移動操作和預測操作可以由一行代碼實現:\n```python\nconvolve(np.roll(pdf, offset), kernel, mode='wrap')\n```\nFilterPy在`discrete_bayes`的`predict()`函數中實現了此操作。",
"_____no_output_____"
]
],
[
[
"from filterpy.discrete_bayes import predict\n\nbelief = [.05, .05, .05, .05, .55, .05, .05, .05, .05, .05]\nprior = predict(belief, offset=1, kernel=[.1, .8, .1])\nbook_plots.plot_belief_vs_prior(belief, prior, ylim=(0,0.6))",
"_____no_output_____"
]
],
[
[
"All of the elements are unchanged except the middle ones. The values in position 4 and 6 should be \n$$(0.1 \\times 0.05)+ (0.8 \\times 0.05) + (0.1 \\times 0.55) = 0.1$$\n\nPosition 5 should be $$(0.1 \\times 0.05) + (0.8 \\times 0.55)+ (0.1 \\times 0.05) = 0.45$$\n\nLet's ensure that it shifts the positions correctly for movements greater than one and for asymmetric kernels.",
"_____no_output_____"
],
[
"除去中部的幾個數值外,其它數保持不變。位於4和6除的概率應為 \n$$(0.1 \\times 0.05)+ (0.8 \\times 0.05) + (0.1 \\times 0.55) = 0.1$$\n\n位置5處的概率應為$$(0.1 \\times 0.05) + (0.8 \\times 0.55)+ (0.1 \\times 0.05) = 0.45$$\n\n接著,我們來確認一下對於移動量大於1,且非對稱的核,它也能正確地移動位置。\n",
"_____no_output_____"
]
],
[
[
"prior = predict(belief, offset=3, kernel=[.05, .05, .6, .2, .1])\nbook_plots.plot_belief_vs_prior(belief, prior, ylim=(0,0.6))",
"_____no_output_____"
]
],
[
[
"The position was correctly shifted by 3 positions and we give more weight to the likelihood of an overshoot vs an undershoot, so this looks correct.\n\nMake sure you understand what we are doing. We are making a prediction of where the dog is moving, and convolving the probabilities to get the prior.\n\nIf we weren't using probabilities we would use this equation that I gave earlier:\n\n$$ \\bar x_{k+1} = x_k + f_{\\mathbf x}(\\bullet)$$\n\nThe prior, our prediction of where the dog will be, is the amount the dog moved plus his current position. The dog was at 10, he moved 5 meters, so he is now at 15 m. It couldn't be simpler. But we are using probabilities to model this, so our equation is:\n\n$$ \\bar{ \\mathbf x}_{k+1} = \\mathbf x_k \\ast f_{\\mathbf x}(\\bullet)$$\n\nWe are *convolving* the current probabilistic position estimate with a probabilistic estimate of how much we think the dog moved. It's the same concept, but the math is slightly different. $\\mathbf x$ is bold to denote that it is an array of numbers. ",
"_____no_output_____"
],
[
"预测位置正确移动了三步,且我们为偏大的位移给出了更高的似然权重,所以结果看起来是正确的。\n\n你要保证确实理解我们在做的事情。我们在预测狗的位移,通过对概率分布做卷积来给出先验:\n\n如果我们使用的不是概率分布,那么我们需要使用前面给出的公式\n\n$$ \\bar x_{k+1} = x_k + f_{\\mathbf x}(\\bullet)$$\n\n先验等于狗的当前位置加上狗的位移(这里先验指的是狗的预测位置)。如果狗在位置10,位移了5米,那么它现在出现在15米的位置。简单到不能再简单了。但现在我们使用概率分布来建模,于是我们的公式变为:\n\n$$ \\bar{ \\mathbf x}_{k+1} = \\mathbf x_k \\ast f_{\\mathbf x}(\\bullet)$$",
"_____no_output_____"
],
[
"## Integrating Measurements and Movement Updates\n\nThe problem of losing information during a prediction may make it seem as if our system would quickly devolve into having no knowledge. However, each prediction is followed by an update where we incorporate the measurement into the estimate. The update improves our knowledge. The output of the update step is fed into the next prediction. The prediction degrades our certainty. That is passed into another update, where certainty is again increased.\n\nLet's think about this intuitively. Consider a simple case - you are tracking a dog while he sits still. During each prediction you predict he doesn't move. Your filter quickly *converges* on an accurate estimate of his position. Then the microwave in the kitchen turns on, and he goes streaking off. You don't know this, so at the next prediction you predict he is in the same spot. But the measurements tell a different story. As you incorporate the measurements your belief will be smeared along the hallway, leading towards the kitchen. On every epoch (cycle) your belief that he is sitting still will get smaller, and your belief that he is inbound towards the kitchen at a startling rate of speed increases.\n\nThat is what intuition tells us. What does the math tell us?\n\nWe have already programmed the update and predict steps. All we need to do is feed the result of one into the other, and we will have implemented a dog tracker!!! Let's see how it performs. We will input measurements as if the dog started at position 0 and moved right one position each epoch. As in a real world application, we will start with no knowledge of his position by assigning equal probability to all positions. ",
"_____no_output_____"
],
[
"## 在位移更新过程中结合测量值\n\n因為在预测过程中存在信息丢失的问题,所以看起來似乎我们的系统会迅速退化到没有任何信息的状态。然而並非如此,因為每次預測後面都會緊跟著一個更新操作。有了更新操作,我們就可以在作估計時將測量結果納入考量。更新操作能改善信息的質量。更新的結果作為下一次預測的輸入。經過預測,確定性降低了。其結果傳遞給下一次更新,確定性又再一次得到增強。\n\n讓我們從直覺上思考這個問題。考慮一個簡單的例子:你需要跟蹤一條狗,而這條狗永遠坐在那裡不動。每次預測,你給出的結果都是它原地不動。於是你的濾波器迅速“收斂”到其位置的精確估計。這時候廚房的微波爐打開了,狗狗飛奔出去。你不知道這件事,所以下一次預測,你還是預言它原地不動。而這時測量值則傳遞出相悖的信息。如果你結合測量結果去做更新,那你關於位置的信念起始時散佈在走廊上各處,總體向著廚房移動。每一輪迭代(循環),你對狗原地不動的信念俞弱,俞相信狗在以驚人的速度向廚房進發。\n\n這是直覺上我們所能理解的。那麼我們是否能從數學中得到什麼呢?\n\n我們已編寫好更新和預測操作。我們所要做的只是將其中一步的結果傳給下一步,這樣我們就實現了一個狗跟蹤器!!!我們看下它表現如何。我們輸入測量值,假裝狗從位置0開始移動,每次向右移動一步。如果是在真實世界的應用中,起始狀態下我們沒有任何關於其位置的知識,這時我們就為每種可能位置賦予相等的概率。\n",
"_____no_output_____"
]
],
[
[
"from filterpy.discrete_bayes import update\n\nhallway = np.array([1, 1, 0, 0, 0, 0, 0, 0, 1, 0])\nprior = np.array([.1] * 10)\nlikelihood = lh_hallway(hallway, z=1, z_prob=.75)\nposterior = update(likelihood, prior)\nbook_plots.plot_prior_vs_posterior(prior, posterior, ylim=(0,.5))",
"_____no_output_____"
]
],
[
[
"After the first update we have assigned a high probability to each door position, and a low probability to each wall position. ",
"_____no_output_____"
],
[
"第一次更新後,我们为每个门的位置分配了更高的权重,而为墙壁的位置赋予了较低的权重。",
"_____no_output_____"
]
],
[
[
"kernel = (.1, .8, .1)\nprior = predict(posterior, 1, kernel)\nbook_plots.plot_prior_vs_posterior(prior, posterior, True, ylim=(0,.5))",
"_____no_output_____"
]
],
[
[
"The predict step shifted these probabilities to the right, smearing them about a bit. Now let's look at what happens at the next sense.",
"_____no_output_____"
],
[
"预测操作使得概率分布右移,并且使分布散得更开。现在让我们看看下一个读入传感器的读数会发生什么。",
"_____no_output_____"
]
],
[
[
"likelihood = lh_hallway(hallway, z=1, z_prob=.75)\nposterior = update(likelihood, prior)\nbook_plots.plot_prior_vs_posterior(prior, posterior, ylim=(0,.5))",
"_____no_output_____"
]
],
[
[
"Notice the tall bar at position 1. This corresponds with the (correct) case of starting at position 0, sensing a door, shifting 1 to the right, and sensing another door. No other positions make this set of observations as likely. Now we will add an update and then sense the wall.",
"_____no_output_____"
],
[
"注意看位置1处的高峰。它对应的(正確)情況是:以位置0为起点出發,傳感器感應到門,向右移一步,然後傳感器再次感應到門。除此以外的情形則不太可能產生同樣的觀測結果。現在我們增加一個更新操作,這個更新操作中傳感器感應到墻壁。",
"_____no_output_____"
]
],
[
[
"prior = predict(posterior, 1, kernel)\nlikelihood = lh_hallway(hallway, z=0, z_prob=.75)\nposterior = update(likelihood, prior)\nbook_plots.plot_prior_vs_posterior(prior, posterior, ylim=(0,.5))",
"_____no_output_____"
]
],
[
[
"This is exciting! We have a very prominent bar at position 2 with a value of around 35%. It is over twice the value of any other bar in the plot, and is about 4% larger than our last plot, where the tallest bar was around 31%. Let's see one more cycle.",
"_____no_output_____"
],
[
"結果真是令人激動!條形圖在位置2處的數值顯著突出,其值為35%,其高度在其它任意一柱高度的兩倍以上。上一張圖的最高高度約為31%,所以經過本次操作高度提高的量約為4%。我們再觀察一輪。",
"_____no_output_____"
]
],
[
[
"prior = predict(posterior, 1, kernel)\nlikelihood = lh_hallway(hallway, z=0, z_prob=.75)\nposterior = update(likelihood, prior)\nbook_plots.plot_prior_vs_posterior(prior, posterior, ylim=(0,.5))",
"_____no_output_____"
]
],
[
[
"I ignored an important issue. Earlier I assumed that we had a motion sensor for the predict step; then, when talking about the dog and the microwave I assumed that you had no knowledge that he suddenly began running. I mentioned that your belief that the dog is running would increase over time, but I did not provide any code for this. In short, how do we detect and/or estimate changes in the process model if we aren't directly measuring it?\n\nFor now I want to ignore this problem. In later chapters we will learn the mathematics behind this estimation; for now it is a large enough task just to learn this algorithm. It is profoundly important to solve this problem, but we haven't yet built enough of the mathematical apparatus that is required, and so for the remainder of the chapter we will ignore the problem by assuming we have a sensor that senses movement.",
"_____no_output_____"
],
[
"我忽略了一個重要問題。起初我們為預測步提供了運動傳感器,可是之後談及狗與微波爐的例子的時候,我卻假定你沒有關於狗突然開始運動的知識。我斷言道即使如此你仍會越來越相信狗處於運動狀態,但我未提供任何證明該斷言的代碼。簡而言之,在不直接測量的條件下,我們如何才能檢測或估計過程模型狀態的改變呢?\n\n我想暫時擱置這一問題。後續章節會介紹估計方法幕後的數學原理。而現在,僅僅是學習算法就已經是一個大任務。雖然解決這個問題很重要,但是我們還缺乏解決該問題所需的數學工具。那麼本章的後續部分會暫時忽略這個問題,仍然假設我們有一個專門用於測量運動的傳感器。",
"_____no_output_____"
],
[
"## The Discrete Bayes Algorithm\n\nThis chart illustrates the algorithm:",
"_____no_output_____"
],
[
"## 離散貝葉斯算法\n\n下圖顯示了算法的流程:",
"_____no_output_____"
]
],
[
[
"book_plots.predict_update_chart()",
"_____no_output_____"
]
],
[
[
"This filter is a form of the g-h filter. Here we are using the percentages for the errors to implicitly compute the $g$ and $h$ parameters. We could express the discrete Bayes algorithm as a g-h filter, but that would obscure the logic of this filter.\n\nThe filter equations are:\n\n$$\\begin{aligned} \\bar {\\mathbf x} &= \\mathbf x \\ast f_{\\mathbf x}(\\bullet)\\, \\, &\\text{Predict Step} \\\\\n\\mathbf x &= \\|\\mathcal L \\cdot \\bar{\\mathbf x}\\|\\, \\, &\\text{Update Step}\\end{aligned}$$\n\n$\\mathcal L$ is the usual way to write the likelihood function, so I use that. The $\\|\\|$ notation denotes taking the norm. We need to normalize the product of the likelihood with the prior to ensure $x$ is a probability distribution that sums to one.\n\nWe can express this in pseudocode.\n\n**Initialization**\n\n 1. Initialize our belief in the state\n \n**Predict**\n\n 1. Based on the system behavior, predict state for the next time step\n 2. Adjust belief to account for the uncertainty in prediction\n \n**Update**\n\n 1. Get a measurement and associated belief about its accuracy\n 2. Compute how likely it is the measurement matches each state\n 3. Update state belief with this likelihood\n\nWhen we cover the Kalman filter we will use this exact same algorithm; only the details of the computation will differ.\n\nAlgorithms in this form are sometimes called *predictor correctors*. We make a prediction, then correct them.\n\nLet's animate this. First Let's write functions to perform the filtering and to plot the results at any step. I've plotted the position of the doorways in black. Prior are drawn in orange, and the posterior in blue. I draw a thick vertical line to indicate where Simon really is. This is not an output of the filter - we know where Simon is only because we are simulating his movement.",
"_____no_output_____"
],
[
"如圖所示的濾波器是g-h濾波器的一種特殊形式。這裡我們用誤差的百分比隱式計算g和h參數。我們也可以將貝葉斯濾波器用g-h濾波器的形式該寫出來,但這麼做會使得濾波器所遵循的邏輯變得模糊。\n\n濾波器的公式如下:\n\n$$\\begin{aligned} \\bar {\\mathbf x} &= \\mathbf x \\ast f_{\\mathbf x}(\\bullet)\\, \\, &\\text{預測操作} \\\\\n\\mathbf x &= \\|\\mathcal L \\cdot \\bar{\\mathbf x}\\|\\, \\, &\\text{更新操作}\\end{aligned}$$\n\n遵循慣例,我是用$\\mathcal L$來代表似然函數。$\\|\\|$符號表示取模。我們需要對似然與先驗的乘積作歸一化來確保$x$是和為1的概率分佈。\n\n我們可以用如下的偽代碼來表達這個過程。\n\n**初始化**\n\n 1. 為狀態的置信度賦予初始值。\n \n**預測**\n\n 1. 基於系統的行為預測下一時間步的狀態;\n 2. 根據預測操作的不確定性調整置信度;\n \n**更新**\n\n 1. 得到測量值和對測量精度的置信度;\n 2. 計算測量值與真實狀態相符的似然程度;\n 3. 根據似然更新狀態置信度;\n\n在卡爾曼濾波的章節,我們會使用完全一致的算法;只在於計算的細節上有所不同。\n\n這類算法有時候被稱為“預測校準器”,因為它們先做預測,再修正預測的值。\n\n讓我們用動畫來展示這個算法。我們先實現濾波函數,然後將每一步結果繪製出來。我用黑色來指示門道的位置。用橙色來繪製先驗,用藍色繪製後驗。縱向粗線用於指示西蒙的實際位置。注意它不是濾波器的輸出——之所以我們能知道西蒙的真實位置是因為我們在用程序模擬這個過程。",
"_____no_output_____"
]
],
[
[
"def discrete_bayes_sim(prior, kernel, measurements, z_prob, hallway):\n posterior = np.array([.1]*10)\n priors, posteriors = [], []\n for i, z in enumerate(measurements):\n prior = predict(posterior, 1, kernel)\n priors.append(prior)\n\n likelihood = lh_hallway(hallway, z, z_prob)\n posterior = update(likelihood, prior)\n posteriors.append(posterior)\n return priors, posteriors\n\n\ndef plot_posterior(hallway, posteriors, i):\n plt.title('Posterior')\n book_plots.bar_plot(hallway, c='k')\n book_plots.bar_plot(posteriors[i], ylim=(0, 1.0))\n plt.axvline(i % len(hallway), lw=5) \n \ndef plot_prior(hallway, priors, i):\n plt.title('Prior')\n book_plots.bar_plot(hallway, c='k')\n book_plots.bar_plot(priors[i], ylim=(0, 1.0), c='#ff8015')\n plt.axvline(i % len(hallway), lw=5) \n\ndef animate_discrete_bayes(hallway, priors, posteriors):\n def animate(step):\n step -= 1\n i = step // 2 \n if step % 2 == 0:\n plot_prior(hallway, priors, i)\n else:\n plot_posterior(hallway, posteriors, i)\n \n return animate",
"_____no_output_____"
]
],
[
[
"Let's run the filter and animate it.",
"_____no_output_____"
],
[
"讓我們運行濾波器,並觀察運行結果。",
"_____no_output_____"
]
],
[
[
"# change these numbers to alter the simulation\nkernel = (.1, .8, .1)\nz_prob = 1.0\nhallway = np.array([1, 1, 0, 0, 0, 0, 0, 0, 1, 0])\n\n# measurements with no noise\nzs = [hallway[i % len(hallway)] for i in range(50)]\n\npriors, posteriors = discrete_bayes_sim(prior, kernel, zs, z_prob, hallway)\ninteract(animate_discrete_bayes(hallway, priors, posteriors), step=IntSlider(value=1, max=len(zs)*2));",
"_____no_output_____"
]
],
[
[
"Now we can see the results. You can see how the prior shifts the position and reduces certainty, and the posterior stays in the same position and increases certainty as it incorporates the information from the measurement. I've made the measurement perfect with the line `z_prob = 1.0`; we will explore the effect of imperfect measurements in the next section. Finally, \n\nAnother thing to note is how accurate our estimate becomes when we are in front of a door, and how it degrades when in the middle of the hallway. This should make intuitive sense. There are only a few doorways, so when the sensor tells us we are in front of a door this boosts our certainty in our position. A long stretch of no doors reduces our certainty.",
"_____no_output_____"
],
[
"現在,我們可以觀察到結果。你可以看到先驗是如何發生移動的,其不確定性是如何減少的。還注意到雖然先驗與後驗的極大值點重合,但後驗的確定性更高,這是後驗結合了測量信息的緣故。這裡通過令`z_prob = 1.0`使得測量是完全準確的。後續小節我們會探索不完美的測量造成的影響。\n\n最後一個值得注意的事是,當狗處於門前時估計的準確度是如何增加的,以及當狗位於走廊中心時它是如何退化的。你可以從直覺上理解這個問題。門的數量很少,所以一旦傳感器感應到門,我們對位置的確定性就增加。成片的非門區域則會降低確定性。",
"_____no_output_____"
],
[
"## The Effect of Bad Sensor Data\n\nYou may be suspicious of the results above because I always passed correct sensor data into the functions. However, we are claiming that this code implements a *filter* - it should filter out bad sensor measurements. Does it do that?\n\nTo make this easy to program and visualize I will change the layout of the hallway to mostly alternating doors and hallways, and run the algorithm on 6 correct measurements:",
"_____no_output_____"
],
[
"## 不良傳感器數據的影響\n\n你可能會對上面的結果表示懷疑,畢竟我一直只給函數傳入正確的傳感器數據。然而,既然我們聲稱自己實現了“濾波器”,那麼它應當能過濾不良傳感器數據。那麼它確實能做到這一點嗎?\n\n為使得問題易於編程實現和方便可視化,我要改變走廊的佈局,使門道和走廊均勻交替分佈。以六個正確測量結果為輸入運行算法:",
"_____no_output_____"
]
],
[
[
"hallway = np.array([1, 0, 1, 0, 0]*2)\nkernel = (.1, .8, .1)\nprior = np.array([.1] * 10)\nzs = [1, 0, 1, 0, 0, 1]\nz_prob = 0.75\npriors, posteriors = discrete_bayes_sim(prior, kernel, zs, z_prob, hallway)\ninteract(animate_discrete_bayes(hallway, priors, posteriors), step=IntSlider(value=12, max=len(zs)*2));",
"_____no_output_____"
]
],
[
[
"We have identified the likely cases of having started at position 0 or 5, because we saw this sequence of doors and walls: 1,0,1,0,0. Now I inject a bad measurement. The next measurement should be 0, but instead we get a 1:",
"_____no_output_____"
],
[
"我們看到最可能的起始位置是0或5。這是因為傳感器的讀數序列為:1、0、1、0、0.現在我插入一個錯誤的測量值。原本下一個讀數應當是0,但我將其替換為1.",
"_____no_output_____"
]
],
[
[
"measurements = [1, 0, 1, 0, 0, 1, 1]\npriors, posteriors = discrete_bayes_sim(prior, kernel, measurements, z_prob, hallway);\nplot_posterior(hallway, posteriors, 6)",
"_____no_output_____"
]
],
[
[
"That one bad measurement has significantly eroded our knowledge. Now let's continue with a series of correct measurements.",
"_____no_output_____"
],
[
"一個不良傳感器數據的插入嚴重污染了我們的知識。接著,我們在正確測量數據上繼續運行。",
"_____no_output_____"
]
],
[
[
"with figsize(y=5.5):\n measurements = [1, 0, 1, 0, 0, 1, 1, 1, 0, 0]\n for i, m in enumerate(measurements):\n likelihood = lh_hallway(hallway, z=m, z_prob=.75)\n posterior = update(likelihood, prior)\n prior = predict(posterior, 1, kernel)\n plt.subplot(5, 2, i+1)\n book_plots.bar_plot(posterior, ylim=(0, .4), title=f'step {i+1}')\n plt.tight_layout()",
"_____no_output_____"
]
],
[
[
"We quickly filtered out the bad sensor reading and converged on the most likely positions for our dog.",
"_____no_output_____"
],
[
"我們很快就濾除了不良傳感器讀數,並且概率分佈收斂在狗的最可能位置上。",
"_____no_output_____"
],
[
"## Drawbacks and Limitations\n\nDo not be mislead by the simplicity of the examples I chose. This is a robust and complete filter, and you may use the code in real world solutions. If you need a multimodal, discrete filter, this filter works.\n\nWith that said, this filter it is not used often because it has several limitations. Getting around those limitations is the motivation behind the chapters in the rest of this book.\n\nThe first problem is scaling. Our dog tracking problem used only one variable, $pos$, to denote the dog's position. Most interesting problems will want to track several things in a large space. Realistically, at a minimum we would want to track our dog's $(x,y)$ coordinate, and probably his velocity $(\\dot{x},\\dot{y})$ as well. We have not covered the multidimensional case, but instead of an array we use a multidimensional grid to store the probabilities at each discrete location. Each `update()` and `predict()` step requires updating all values in the grid, so a simple four variable problem would require $O(n^4)$ running time *per time step*. Realistic filters can have 10 or more variables to track, leading to exorbitant computation requirements.\n\nThe second problem is that the filter is discrete, but we live in a continuous world. The histogram requires that you model the output of your filter as a set of discrete points. A 100 meter hallway requires 10,000 positions to model the hallway to 1cm accuracy. So each update and predict operation would entail performing calculations for 10,000 different probabilities. It gets exponentially worse as we add dimensions. A 100x100 m$^2$ courtyard requires 100,000,000 bins to get 1cm accuracy.\n\nA third problem is that the filter is multimodal. In the last example we ended up with strong beliefs that the dog was in position 4 or 9. This is not always a problem. Particle filters, which we will study later, are multimodal and are often used because of this property. But imagine if the GPS in your car reported to you that it is 40% sure that you are on D street, and 30% sure you are on Willow Avenue. \n\nA forth problem is that it requires a measurement of the change in state. We need a motion sensor to detect how much the dog moves. There are ways to work around this problem, but it would complicate the exposition of this chapter, so, given the aforementioned problems, I will not discuss it further.\n\nWith that said, if I had a small problem that this technique could handle I would choose to use it; it is trivial to implement, debug, and understand, all virtues.",
"_____no_output_____"
],
[
"## 缺點和局限\n\n不要受我選的這個示例的簡單性所誤導。這是一個穩健的完整濾波器,可以應用於現實世界的解決方案。如果你需要一個多峰的,離散的濾波器,那麼這個濾波器可以為你所用。\n\n說是這麼說。實際上由於一些限制,這種濾波器也不是經常使用。餘下的章節就主要圍繞如何克服這些限制展開。\n\n第一個問題在於其伸縮性。我們的狗跟蹤問題只使用一個變量$pos$來表示狗的位置。許多有趣的問題都需要在一個大的向量空間中跟蹤多個變量。比如在現實中我們往往需要跟蹤狗的位置$(x,y)$,有時還需跟蹤其速度$(\\dot{x},\\dot{y})$ 。我們還沒有處理過多維的情況。在高維空間中,我們不再使用一維數組表示狀態,而是使用一個多維的網格來存儲各離散位置的對應概率。每個`update()`和`predict()`步都需要更新網格上的所有位置。那麼一個含有四個變量**每一步**運算都需要$O(n^4)$的運行時間。現實世界中的濾波器往往有超過10個需要跟蹤的變量,這需要極多的計算資源。\n\n第二個問題是這種濾波器是離散的,但我們生活的世界是連續的。這種基於直方圖的方式要求你將濾波器的輸出建模為一些列離散點。要在100米的走廊上達到1cm的定位精度需要10000個點。情況隨著維度的增加指數惡化。要在100平方米的庭院內達到1cm的精確度需要尺寸為一億的直方圖。\n\n第三個問題是,這種濾波器是多峰的。上一個問題中,程序以堅信狗處於位置4或9的狀態結束。這並不總成問題。我們後面將介紹粒子濾波器。粒子濾波器正是因為其具有多峰的性質而被廣泛應用。但你可以想象看你車里的GPS報告說你有40%的概率位於D街,又有30%的概率位於柳樹大道嗎。\n\n第四個問題是它需要狀態改變程度的測量值。我們需要運動傳感器以測量狗的運動量。有許多應對該問題的方法,但為不使本章的闡述過於複雜這裡就不再介紹。總之基於上述所有原因,我們不再做進一步的討論。\n\n話雖如此,如果我手頭有一個可以由這項技術處理的小問題,我就會使用它。易於實現、調試和理解都是它的優點。\n",
"_____no_output_____"
],
[
"## Tracking and Control\n\nWe have been passively tracking an autonomously moving object. But consider this very similar problem. I am automating a warehouse and want to use robots to collect all of the items for a customer's order. Perhaps the easiest way to do this is to have the robots travel on a train track. I want to be able to send the robot a destination and have it go there. But train tracks and robot motors are imperfect. Wheel slippage and imperfect motors means that the robot is unlikely to travel to exactly the position you command. There is more than one robot, and we need to know where they all are so we do not cause them to crash.\n\nSo we add sensors. Perhaps we mount magnets on the track every few feet, and use a Hall sensor to count how many magnets are passed. If we count 10 magnets then the robot should be at the 10th magnet. Of course it is possible to either miss a magnet or to count it twice, so we have to accommodate some degree of error. We can use the code from the previous section to track our robot since magnet counting is very similar to doorway sensing.\n\nBut we are not done. We've learned to never throw information away. If you have information you should use it to improve your estimate. What information are we leaving out? We know what control inputs we are feeding to the wheels of the robot at each moment in time. For example, let's say that once a second we send a movement command to the robot - move left 1 unit, move right 1 unit, or stand still. If I send the command 'move left 1 unit' I expect that in one second from now the robot will be 1 unit to the left of where it is now. This is a simplification because I am not taking acceleration into account, but I am not trying to teach control theory. Wheels and motors are imperfect. The robot might end up 0.9 units away, or maybe 1.2 units. \n\nNow the entire solution is clear. We assumed that the dog kept moving in whatever direction he was previously moving. That is a dubious assumption for my dog! Robots are far more predictable. Instead of making a dubious prediction based on assumption of behavior we will feed in the command that we sent to the robot! In other words, when we call `predict()` we will pass in the commanded movement that we gave the robot along with a kernel that describes the likelihood of that movement.",
"_____no_output_____"
],
[
"## 跟蹤和控制\n\n我們已經實現了對單個自主移動目標的被動跟蹤。但請你考慮一個十分相似的問題。我要實現仓库自動化,希望使用机器人收集客户訂的所有貨。或許一個最簡單的辦法是讓機器人在火車軌道上行駛。我希望我能讓機器人去到我所指定的目的地。但是鐵軌和機器人的發動機都不是完美的。輪胎打滑和發動機不完美決定了機器人不太可能準確移動到你指定的位置。機器人不止一個,我需要知道所有機器人的位置以免它們碰撞。\n\n所以我们增加了传感器。也许我们每隔几英尺就在轨道上安装一块磁铁,并使用霍尔传感器来计算經過的磁铁数。如果我們數到10個磁鐵,那麼機器人應在第10個磁鐵處。當然,有可能會發生漏掉一塊磁鐵沒統計,或者一塊磁鐵被數了兩次的情況,所以我們需要能適應一定程度的誤差。因為磁鐵計數和走廊傳感器相似,所以我們可以使用前面的代碼來跟蹤機器人。\n\n但這還沒有完成。我們學到一句話:永遠不要丟掉任何信息。如果信息存在,就應當用來改善你的估計。有什麼信息是為我們忽略的呢?我們能即時獲得對機器輪的控制信號輸入。比如,不妨設我們每秒傳遞一個信號給機器人——左一步,右一步,站住不動。我一送出命令“左一步”,我就預期一秒後機器人將位於當前位置的左邊一步。我沒有考慮加速度,所以這隻是一個簡化的問題。但我也不打算在這裡教控制論。車輪和發動機都是不完美的。機器人可能只移動0.9步,也可能移動1.2步。\n\n現在整個問題的解清晰了。我們先前假定狗總是保持之前的移動方向。這個假設對於我的狗來說是不可靠的。但機器人的行為就容易預測得多。預期使用假設得到一個不準確的預測,不如將我們送給機器人的命令作為輸入!換句話說,當調用`predict()`函數時,我們將送給機器人的移動命令,同描述移動的似然度的卷積核一起作為函數的輸入。",
"_____no_output_____"
],
[
"### Simulating the Train Behavior\n\nWe need to simulate an imperfect train. When we command it to move it will sometimes make a small mistake, and its sensor will sometimes return the incorrect value.",
"_____no_output_____"
],
[
"## 列車的行為模擬\n我們要模擬一個不完美的列車。當我們命令它移動時,它偶爾會犯一些小錯,它的傳感器有時會返回錯誤的值。",
"_____no_output_____"
]
],
[
[
"class Train(object):\n\n def __init__(self, track_len, kernel=[1.], sensor_accuracy=.9):\n self.track_len = track_len\n self.pos = 0\n self.kernel = kernel\n self.sensor_accuracy = sensor_accuracy\n\n def move(self, distance=1):\n \"\"\" move in the specified direction\n with some small chance of error\"\"\"\n\n self.pos += distance\n # insert random movement error according to kernel\n r = random.random()\n s = 0\n offset = -(len(self.kernel) - 1) / 2\n for k in self.kernel:\n s += k\n if r <= s:\n break\n offset += 1\n self.pos = int((self.pos + offset) % self.track_len)\n return self.pos\n\n def sense(self):\n pos = self.pos\n # insert random sensor error\n if random.random() > self.sensor_accuracy:\n if random.random() > 0.5:\n pos += 1\n else:\n pos -= 1\n return pos",
"_____no_output_____"
]
],
[
[
"With that we are ready to write the filter. We will put it in a function so that we can run it with different assumptions. I will assume that the robot always starts at the beginning of the track. The track is implemented as being 10 units long, but think of it as a track of length, say 10,000, with the magnet pattern repeated every 10 units. A length of 10 makes it easier to plot and inspect.",
"_____no_output_____"
],
[
"有了這個我們就可以實現濾波器了。我們將其封裝為一個函數,以便我們可以在不同假設條件下運行這段代碼。我假設機器人總是從軌道的起點出發。我們實現的軌道長度為10個單位。你可以想象他是一個每10單位長度就放置一塊磁鐵的10000單位長度的軌道。令長度為10有利於繪圖和分析。",
"_____no_output_____"
]
],
[
[
"def train_filter(iterations, kernel, sensor_accuracy, \n move_distance, do_print=True):\n track = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n prior = np.array([.9] + [0.01]*9)\n posterior = prior[:]\n normalize(prior)\n \n robot = Train(len(track), kernel, sensor_accuracy)\n for i in range(iterations):\n # move the robot and\n robot.move(distance=move_distance)\n\n # peform prediction\n prior = predict(posterior, move_distance, kernel) \n\n # and update the filter\n m = robot.sense()\n likelihood = lh_hallway(track, m, sensor_accuracy)\n posterior = update(likelihood, prior)\n index = np.argmax(posterior)\n\n if do_print:\n print(f'time {i}: pos {robot.pos}, sensed {m}, at position {track[robot.pos]}')\n conf = posterior[index] * 100\n print(f' estimated position is {index} with confidence {conf:.4f}%:') \n\n book_plots.bar_plot(posterior)\n if do_print:\n print()\n print('final position is', robot.pos)\n index = np.argmax(posterior)\n print('''Estimated position is {} with '''\n '''confidence {:.4f}%:'''.format(\n index, posterior[index]*100))",
"_____no_output_____"
]
],
[
[
"Read the code and make sure you understand it. Now let's do a run with no sensor or movement error. If the code is correct it should be able to locate the robot with no error. The output is a bit tedious to read, but if you are at all unsure of how the update/predict cycle works make sure you read through it carefully to solidify your understanding.",
"_____no_output_____"
],
[
"請閱讀代碼并且保证你确实理解它。我們先在沒有傳感器誤差和運動誤差的情況下運行代码。如果代码正确,那么它应当能正确无误地检出目标机器人。虽然程序输出有点冗长难读,但若你对更新/预测循环的工作方式完全不确顶,你务必通读这些文字以巩固你的理解。",
"_____no_output_____"
]
],
[
[
"import random\n\nrandom.seed(3)\nnp.set_printoptions(precision=2, suppress=True, linewidth=60)\ntrain_filter(4, kernel=[1.], sensor_accuracy=.999,\n move_distance=4, do_print=True)",
"time 0: pos 4, sensed 4, at position 4\n estimated position is 4 with confidence 99.9900%:\ntime 1: pos 8, sensed 8, at position 8\n estimated position is 8 with confidence 100.0000%:\ntime 2: pos 2, sensed 2, at position 2\n estimated position is 2 with confidence 100.0000%:\ntime 3: pos 6, sensed 6, at position 6\n estimated position is 6 with confidence 100.0000%:\n\nfinal position is 6\nEstimated position is 6 with confidence 100.0000%:\n"
]
],
[
[
"We can see that the code was able to perfectly track the robot so we should feel reasonably confident that the code is working. Now let's see how it fairs with some errors. ",
"_____no_output_____"
],
[
"我们可以看到程序完美无误地实现了对机器人的跟踪,所以我们相当有信心相信代码在正常工作。现在我们来看一些失败案例和几个错误。",
"_____no_output_____"
]
],
[
[
"random.seed(5)\ntrain_filter(4, kernel=[.1, .8, .1], sensor_accuracy=.9,\n move_distance=4, do_print=True)",
"time 0: pos 4, sensed 4, at position 4\n estimated position is 4 with confidence 96.0390%:\ntime 1: pos 8, sensed 9, at position 8\n estimated position is 9 with confidence 52.1180%:\ntime 2: pos 3, sensed 3, at position 3\n estimated position is 3 with confidence 88.3993%:\ntime 3: pos 7, sensed 8, at position 7\n estimated position is 8 with confidence 49.3174%:\n\nfinal position is 7\nEstimated position is 8 with confidence 49.3174%:\n"
]
],
[
[
"There was a sensing error at time 1, but we are still quite confident in our position. \n\nNow let's run a very long simulation and see how the filter responds to errors.",
"_____no_output_____"
],
[
"在时刻1有一个传感器异常,但我们仍然对预测的位置有相当高的置信度。\n\n现在加長模擬時間,看看滤波器是如何应对错误的。",
"_____no_output_____"
]
],
[
[
"with figsize(y=5.5):\n for i in range (4):\n random.seed(3)\n plt.subplot(221+i)\n train_filter(148+i, kernel=[.1, .8, .1], \n sensor_accuracy=.8,\n move_distance=4, do_print=False)\n plt.title (f'iteration {148 + i}')",
"_____no_output_____"
]
],
[
[
"We can see that there was a problem on iteration 149 as the confidence degrades. But within a few iterations the filter is able to correct itself and regain confidence in the estimated position.",
"_____no_output_____"
],
[
"我们可以看到虽然第149次迭代出现问题,导致置信度降低,但是数次迭代后,滤波器能自我校正,使其对预测位置的置信度再次提升。",
"_____no_output_____"
],
[
"## Bayes Theorem and the Total Probability Theorem",
"_____no_output_____"
],
[
"## 贝叶斯理论和全概率定理",
"_____no_output_____"
],
[
"We developed the math in this chapter merely by reasoning about the information we have at each moment. In the process we discovered [*Bayes' Theorem*](https://en.wikipedia.org/wiki/Bayes%27_theorem) and the [*Total Probability Theorem*](https://en.wikipedia.org/wiki/Law_of_total_probability).\n\nBayes theorem tells us how to compute the probability of an event given previous information. \n\nWe implemented the `update()` function with this probability calculation:\n\n$$ \\mathtt{posterior} = \\frac{\\mathtt{likelihood}\\times \\mathtt{prior}}{\\mathtt{normalization\\, factor}}$$ \n\nWe haven't developed the mathematics to discuss Bayes yet, but this is Bayes' theorem. Every filter in this book is an expression of Bayes' theorem. In the next chapter we will develop the mathematics, but in many ways that obscures the simple idea expressed in this equation:\n\n$$ updated\\,knowledge = \\big\\|likelihood\\,of\\,new\\,knowledge\\times prior\\, knowledge \\big\\|$$\n\nwhere $\\| \\cdot\\|$ expresses normalizing the term.\n\nWe came to this with simple reasoning about a dog walking down a hallway. Yet, as we will see the same equation applies to a universe of filtering problems. We will use this equation in every subsequent chapter.\n\nLikewise, the `predict()` step computes the total probability of multiple possible events. This is known as the *Total Probability Theorem* in statistics, and we will also cover this in the next chapter after developing some supporting math.\n\nFor now I need you to understand that Bayes' theorem is a formula to incorporate new information into existing information.",
"_____no_output_____"
],
[
"我们仅通过利用每个时刻的现有信息作推理就引出了本章的所有数学公式。这个过程中,我们发现了[贝叶斯理论](https://en.wikipedia.org/wiki/Bayes%27_theorem)和[全概率定理](https://en.wikipedia.org/wiki/Law_of_total_probability).\n\n贝叶斯理论告诉我们如何基于给定历史信息的计算某一事件的概率。\n\n我们实现了`update()`函数以执行如下的概率计算:\n\n$$ \\mathtt{後验} = \\frac{\\mathtt{似然}\\times \\mathtt{先验}}{\\mathtt{归一化系数}}$$ \n\n我们还没有用数学推导讨论过贝叶斯,但这就是贝叶斯定理。本书的每个滤波器都是贝叶斯定理的表达形式。下一章我们会用多种方式推导数学公式,这个过程中,如下等式所表示的简单思想会从各方面掩藏起来。\n\n$$ 更新後的知识 = \\big\\|新知识的似然度\\times 先验知识 \\big\\|$$\n\n其中 $\\| \\cdot\\|$ 表示归一化。\n\n我们通过关于狗跟踪问题的简单推理得到这一式子。然而,我们将会看到这一式子适用于一些列滤波问题。在接下来的每一章中我们都会用到它。\n\n类似的,`predict()`步骤计算多个可能事件的总概率。这在统计学中被称为“全概率定理”,在下一章中,我们会在一系列数学推导後讲授此定理。\n\n当下我想要你理解的是,贝叶斯公式所做的是将新信息合并到现有信息中去。\n",
"_____no_output_____"
],
[
"## Summary\n\nThe code is very short, but the result is impressive! We have implemented a form of a Bayesian filter. We have learned how to start with no information and derive information from noisy sensors. Even though the sensors in this chapter are very noisy (most sensors are more than 80% accurate, for example) we quickly converge on the most likely position for our dog. We have learned how the predict step always degrades our knowledge, but the addition of another measurement, even when it might have noise in it, improves our knowledge, allowing us to converge on the most likely result.\n\nThis book is mostly about the Kalman filter. The math it uses is different, but the logic is exactly the same as used in this chapter. It uses Bayesian reasoning to form estimates from a combination of measurements and process models. \n\n**If you can understand this chapter you will be able to understand and implement Kalman filters.** I cannot stress this enough. If anything is murky, go back and reread this chapter and play with the code. The rest of this book will build on the algorithms that we use here. If you don't understand why this filter works you will have little success with the rest of the material. However, if you grasp the fundamental insight - multiplying probabilities when we measure, and shifting probabilities when we update leads to a converging solution - then after learning a bit of math you are ready to implement a Kalman filter.",
"_____no_output_____"
],
[
"## 总结\n\n虽然代码很短,但它的运行结果让人映像深刻!我们实现了贝叶斯滤波器的一种具体形式。我们学会了如何从没有任何信息的状态开始,从带有噪声的传感器中推理出信息。虽然本章所用的传感器大多包含许多噪声(举例来说,大多数的传感器的准确率在80%以上),我们还是能快速收敛到狗的最可能位置。我们学到,预测操作总是减少我们的知识,但一旦引入额外的测量值我们就能改善我们的知识,加快收敛到最可能結果的速度。即使引入的测量值中包含噪声也是如此。\n\n本書的主旨是卡爾曼濾波。卡爾曼濾波使用的數學工具有些不同,但其邏輯同本章所用的是一樣的。它使用貝葉斯推理結合測量與過程模型構造估計。\n\n**如果你能理解本章的內容,你就能理解和實現卡爾曼濾波。**我怎么强调这一点都不为过。 如果有任何不清楚的地方,可以重新阅读本章,跑一跑代码。 本书的其余部分将建立在我们在这里使用的算法之上。 如果你不理解此濾波器的工作原理,你也无法順利學習後續內容。 但是,如果你掌握了基本知识——測量時測量分佈乘上概率分佈,更新時平移概率分佈,這樣我們就能收斂於解——那么在学习一些数学原理后,就可以准备实施卡尔曼滤波器了。",
"_____no_output_____"
],
[
"## References\n\n * [1] D. Fox, W. Burgard, and S. Thrun. \"Monte carlo localization: Efficient position estimation for mobile robots.\" In *Journal of Artifical Intelligence Research*, 1999.\n \n http://www.cs.cmu.edu/afs/cs/project/jair/pub/volume11/fox99a-html/jair-localize.html\n\n\n * [2] Dieter Fox, et. al. \"Bayesian Filters for Location Estimation\". In *IEEE Pervasive Computing*, September 2003.\n \n http://swarmlab.unimaas.nl/wp-content/uploads/2012/07/fox2003bayesian.pdf\n \n \n * [3] Sebastian Thrun. \"Artificial Intelligence for Robotics\".\n \n https://www.udacity.com/course/cs373\n \n \n * [4] Khan Acadamy. \"Introduction to the Convolution\"\n \n https://www.khanacademy.org/math/differential-equations/laplace-transform/convolution-integral/v/introduction-to-the-convolution\n \n \n* [5] Wikipedia. \"Convolution\"\n\n http://en.wikipedia.org/wiki/Convolution\n\n* [6] Wikipedia. \"Law of total probability\"\n\n http://en.wikipedia.org/wiki/Law_of_total_probability\n \n* [7] Wikipedia. \"Time Evolution\"\n\n https://en.wikipedia.org/wiki/Time_evolution\n \n* [8] We need to rethink how we teach statistics from the ground up\n \n http://www.statslife.org.uk/opinion/2405-we-need-to-rethink-how-we-teach-statistics-from-the-ground-up",
"_____no_output_____"
],
[
"## 參考資料\n\n * [1] D. Fox, W. Burgard, and S. Thrun. \"Monte carlo localization: Efficient position estimation for mobile robots.\" In *Journal of Artifical Intelligence Research*, 1999.\n \n http://www.cs.cmu.edu/afs/cs/project/jair/pub/volume11/fox99a-html/jair-localize.html\n\n\n * [2] Dieter Fox, et. al. \"Bayesian Filters for Location Estimation\". In *IEEE Pervasive Computing*, September 2003.\n \n http://swarmlab.unimaas.nl/wp-content/uploads/2012/07/fox2003bayesian.pdf\n \n \n * [3] Sebastian Thrun. \"Artificial Intelligence for Robotics\".\n \n https://www.udacity.com/course/cs373\n \n \n * [4] Khan Acadamy. \"Introduction to the Convolution\"\n \n https://www.khanacademy.org/math/differential-equations/laplace-transform/convolution-integral/v/introduction-to-the-convolution\n \n \n* [5] Wikipedia. \"Convolution\"\n\n http://en.wikipedia.org/wiki/Convolution\n\n* [6] Wikipedia. \"Law of total probability\"\n\n http://en.wikipedia.org/wiki/Law_of_total_probability\n \n* [7] Wikipedia. \"Time Evolution\"\n\n https://en.wikipedia.org/wiki/Time_evolution\n \n* [8] We need to rethink how we teach statistics from the ground up\n \n http://www.statslife.org.uk/opinion/2405-we-need-to-rethink-how-we-teach-statistics-from-the-ground-up",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
d081d6e68eb890e092a9383845dd34b0387b9f05 | 7,036 | ipynb | Jupyter Notebook | colorgen.ipynb | artificialsoph/sophiaray.github.io | 7345f29368383004bc3c83734c2d495eb872faf1 | [
"MIT"
] | null | null | null | colorgen.ipynb | artificialsoph/sophiaray.github.io | 7345f29368383004bc3c83734c2d495eb872faf1 | [
"MIT"
] | null | null | null | colorgen.ipynb | artificialsoph/sophiaray.github.io | 7345f29368383004bc3c83734c2d495eb872faf1 | [
"MIT"
] | null | null | null | 29.07438 | 1,044 | 0.630756 | [
[
[
"%pylab inline\n\nimport seaborn as sns",
"Populating the interactive namespace from numpy and matplotlib\n"
],
[
"sns.palplot(sns.color_palette(\"coolwarm\", 7))",
"_____no_output_____"
],
[
"pallette = sns.color_palette(\"coolwarm\", 7)",
"_____no_output_____"
],
[
"pallette.as_hex()",
"_____no_output_____"
],
[
"classes = [\"Constant\", \"Log\", \"Linear\", \"Log-Linear\", \"Square\", \"Polynomial\", \"Exponential\", \"Factorial\"]\nn_classes = len(classes)\npallette = sns.diverging_palette(130, 20, l=65,n=n_classes)\nsns.palplot(pallette)",
"_____no_output_____"
],
[
"\ncolors = pallette.as_hex()\ncss = \"\"\nfor i,c in enumerate(classes):\n css += f\"\"\"\n.{c.lower()} {{\n background-color: {colors[i]}\n}}\"\"\"\nprint(css)",
"\n.constant {\n background-color: #4db258\n}\n.log {\n background-color: #7cc684\n}\n.linear {\n background-color: #addbb2\n}\n.log-linear {\n background-color: #dcf0de\n}\n.square {\n background-color: #fbe0db\n}\n.polynomial {\n background-color: #f6c0b5\n}\n.exponential {\n background-color: #f19f8e\n}\n.factorial {\n background-color: #ed7e69\n}\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d081dac4068547b31520f31ebfe0af6c7cb09db0 | 64,485 | ipynb | Jupyter Notebook | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz | f862111060c63abced8d69c9f3fd095cc7e1a262 | [
"Apache-2.0"
] | null | null | null | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz | f862111060c63abced8d69c9f3fd095cc7e1a262 | [
"Apache-2.0"
] | null | null | null | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz | f862111060c63abced8d69c9f3fd095cc7e1a262 | [
"Apache-2.0"
] | null | null | null | 64,485 | 64,485 | 0.748112 | [
[
[
"# House Prices: Advanced Regression Techniques\n\nThis goal of this project was to predict sales prices and practice feature engineering, RFs, and gradient boosting. The dataset was part of the [House Prices Kaggle Competition](https://www.kaggle.com/c/house-prices-advanced-regression-techniques). \n\n<br>\n\n### Table of Contents\n* [1 Summary](#1-Summary)\n\n* [2 Introduction](#2-Introduction) \n* [3 Loading & Exploring the Data](#3-Loading-&-Exploring-the-Data-Structure)\n * [3.1 Loading Required Libraries and Reading the Data into Python](#3.1-Loading-Required-Libraries-and-Reading-the-Data-into-Python)\n * [3.2 Data Structure](#3.2-Data-Structure)\n \n\n* [4 Exploring the Variables](#4-Exploring-the-Variables)\n * [4.1 Exploring the Response Variable: SalePrice](#4.1-Exploring-the-Response-Variable:-SalePrice)\n * [4.2 Log-Transformation of the Response Variable](#4.2-Log-Transformation-of-the-Response-Variable)\n \n\n* [5 Data Imputation](#5-Data-Imputation)\n * [5.1 Completeness of the Data](#5.1-Completeness-of-the-Data)\n * [5.2 Impute the Missing Data](#5.2-Impute-the-Missing-Data)\n * [5.2.1 Missing Values Corresponding to Lack of Specific Feature](#5.2.1-Missing-Values-Corresponding-to-Lack-of-Specific-Feature)\n * [5.2.2 Mode Imputation: Replacing Missing Values with Most Frequent Value](#5.2.2-Mode-Imputation:-Replacing-Missing-Values-with-Most-Frequent-Value)\n\n \n* [6 Feature Engineering](#6-Feature-Engineering)\n * [6.1 Mixed Conditions](#6.1-Mixed-Conditions)\n * [6.2 Mixed Exterior](#6.2-Mixed-Exterior)\n * [6.3 Total Square Feet](#6.3-Total-Square-Feet)\n * [6.4 Total Number of Bathrooms](#6.4-Total-Number-of-Bathrooms)\n * [6.5 Binning the Neighbourhoods](#6.5-Binning-the-Neighbourhoods)\n\n \n* [7 LotFrontage Imputation](#7-LotFrontage-Imputation)\n * [7.1 LotFrontage Data Structure](#7.1-LotFrontage-Data-Structure)\n * [7.2 Outlier Detection & Removal](#7.2-Outlier-Detection-&-Removal)\n * [7.3 Determining Relevant Variables of LotFrontage](#7.3-Determining-Relevant-Variables-of-LotFrontage)\n * [7.4 LotFrontage Model Building and Evaluation](#7.4-LotFrontage-Model-Building-and-Evaluation)\n\n \n* [8 Preparing the Data for Modelling](#8-Preparing-the-Data-for-Modelling)\n * [8.1 Removing Outliers](#8.1-Removing-Outliers)\n * [8.2 Correlation Between Numeric Predictors](#8.2-Correlation-Between-Numeric-Predictors)\n * [8.3 Label Encoding](#8.3-Label-Encoding)\n * [8.4 Skewness & Normalization of Numeric Variables](#8.4-Skewness-&-Normalization-of-Numeric-Variables)\n * [8.5 One Hot Encoding the Categorical Variables](#8.5-One-Hot-Encoding-the-Categorical-Variables)\n\n \n* [9 SalePrice Modelling](#9-SalePrice-Modelling)\n * [9.1 Obtaining Final Train and Test Sets](#9.1-Obtaining-Final-Train-and-Test-Sets)\n * [9.2 Defining a Cross Validation Strategy](#9.2-Defining-a-Cross-Validation-Strategy)\n * [9.3 Lasso Regression Model](#9.3-Lasso-Regression-Model)\n * [9.4 Ridge Regression Model](#9.4-Ridge-Regression-Model)\n * [9.5 XGBoost Model](#9.5-XGBoost-Model)\n * [9.6 Ensemble Model](#9.6-Ensemble-Model)\n\n\n<br>\n\n### Ensemble Model Accuracy: (RMSE = 0.12220)\n\n### Competition Description\n> Ask a home buyer to describe their dream house, and they probably won't begin with the height of the basement ceiling or the proximity to an east-west railroad. But this playground competition's dataset proves that much more influences price negotiations than the number of bedrooms or a white-picket fence.\n\n>With 79 explanatory variables describing (almost) every aspect of residential homes in Ames, Iowa, this competition challenges you to predict the final price of each home.\n\n### Competition Evaluation\nAs part of a Kaggle competition dataset, the accuracy of the sales prices was evaluated on [Root-Mean-Squared-Error (RMSE)](https://en.wikipedia.org/wiki/Root-mean-square_deviation) between the logarithm of the predicted value and the logarithm of the observed sales price.",
"_____no_output_____"
],
[
"# 1 Summary\n\nI started this competition by focusing on getting a thorough understanding of the dataset. Particular attention was paid to impute the missing values within the dataset. The EDA process is detailed as well as visualized.\n\nIn this project, I created a predictive model that has been trained on data collected from homes in Ames, Iowa. Three algorithms were used, and their validation set RMSE and test set RMSE are listed below:\n\n\n| Regression Model | Validation RMSE | Test RMSE |\n|------------------|-----------------|-----------|\n| Ridge | 0.1130 | 0.12528 |\n| Lasso | 0.1125 | 0.12679 |\n| XGBoost | 0.1238 | 0.12799 |\n| |\n| <b>Ensemble</b> | | 0.12220 |\n\nThe Ridge regression model performed the best as a single model, likely due to the high multicollinearity. However, combining it with the Lasso and XGBoost regression models resulting in a higher prediction accuracy and a lower RMSE (<i>0.12220</i> vs <i>0.12528</i>). ",
"_____no_output_____"
],
[
"# 2 Introduction\n\nThe dataset used for this project is the [Ames Housing dataset](https://amstat.tandfonline.com/doi/abs/10.1080/10691898.2011.11889627) that was compiled by <i>Dean De Cock</i> for use in data science education. It is an alternative to the popular but older [Boston Housing dataset](http://lib.stat.cmu.edu/datasets/boston). \n\nThe Ames Housing dataset is also used in the [Advanced Regression Techniques challenge](https://www.kaggle.com/c/house-prices-advanced-regression-techniques) on the Kaggle Website. These competitions is a great way to improve my skills and measure my progress as a data scientist. \n\nKaggle describes the competition as follows:\n\n> Ask a home buyer to describe their dream house, and they probably won't begin with the height of the basement ceiling or the proximity to an east-west railroad. But this playground competition's dataset proves that much more influences price negotiations than the number of bedrooms or a white-picket fence.\n\n>With 79 explanatory variables describing (almost) every aspect of residential homes in Ames, Iowa, this competition challenges you to predict the final price of each home.\n\n<img src=\"https://i.imgur.com/vOg5fOF.jpg\">",
"_____no_output_____"
],
[
"# 3 Loading & Exploring the Data Structure",
"_____no_output_____"
],
[
"## 3.1 Loading Required Libraries and Reading the Data into Python",
"_____no_output_____"
],
[
"Loading Python packages used in the project",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport missingno as msno\nfrom time import time\n\nfrom math import sqrt\nimport statsmodels.api as sm\nfrom statsmodels.formula.api import ols\nimport scipy.stats as st\nfrom scipy.special import boxcox1p\n\nfrom sklearn.cluster import KMeans\nfrom sklearn import svm\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error\nfrom sklearn.model_selection import train_test_split, KFold, cross_val_score, GridSearchCV\nfrom sklearn.preprocessing import RobustScaler, LabelEncoder, StandardScaler\nfrom sklearn.linear_model import Lasso, Ridge\nfrom sklearn.pipeline import make_pipeline\nfrom xgboost.sklearn import XGBRegressor\n\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"Now, we read in the csv's as datarames into Python.",
"_____no_output_____"
]
],
[
[
"train = pd.read_csv('../input/train.csv')\ntest = pd.read_csv('../input/test.csv')",
"_____no_output_____"
]
],
[
[
"## 3.2 Data Structure\n\nIn total, there are 81 columns/variables in the train dataset, including the response variable (SalePrice). I am only displaying a subset of the variables, as all of them will be discussed in more detail throughout the notebook.\n\nThe train dataset consists of character and integer variables. Many of these variables are ordinal factors, despite being represented as character or integer variables. These will require cleaning and/or feature engineering later.",
"_____no_output_____"
]
],
[
[
"print(\"Dimensions of Train Dataset:\" + str(train.shape))\nprint(\"Dimensions of Test Dataset:\" + str(test.shape))",
"_____no_output_____"
],
[
"train.iloc[:,0:10].info()",
"_____no_output_____"
]
],
[
[
"Next, we are going to define a few variables that will be used in later analyses as well as being required for the submission file.",
"_____no_output_____"
]
],
[
[
"y_train = train['SalePrice']\ntest_id = test['Id']\n\nntrain = train.shape[0]\nntest = test.shape[0]",
"_____no_output_____"
]
],
[
[
"Lastly, we are going to merge the train and test datasets to explore the data as well as impute any missing values.",
"_____no_output_____"
]
],
[
[
"all_data = pd.concat((train, test), sort=True).reset_index(drop=True)\nall_data['Dataset'] = np.repeat(['Train', 'Test'], [ntrain, ntest], axis=0)\nall_data.drop('Id', axis=1,inplace=True)",
"_____no_output_____"
]
],
[
[
"# 4 Exploring the Variables",
"_____no_output_____"
],
[
"## 4.1 Exploring the Response Variable: SalePrice",
"_____no_output_____"
],
[
"The probability distribution plot show that the sale prices are right skewed. This is to be expected as few people can afford very expensive houses. ",
"_____no_output_____"
]
],
[
[
"sns.set_style('whitegrid')\nsns.distplot(all_data['SalePrice'][~all_data['SalePrice'].isnull()], axlabel=\"Normal Distribution\", fit=st.norm, fit_kws={\"color\":\"red\"})\nplt.title('Distribution of Sales Price in Dollars')\n(mu, sigma) = st.norm.fit(train['SalePrice'])\nplt.legend(['Normal Distribution \\n ($\\mu=$ {:.2f} and $\\sigma=$ {:.2f} )'.format(mu, sigma)],\n loc='best', fancybox=True)\nplt.show()\n\nst.probplot(all_data['SalePrice'][~all_data['SalePrice'].isnull()], plot=plt)\nplt.show()",
"_____no_output_____"
]
],
[
[
"Linear models tend to work better with normally distributed data. As such, we need to transform the response variable to make it more normally distributed.",
"_____no_output_____"
],
[
"## 4.2 Log-Transformation of the Response Variable",
"_____no_output_____"
]
],
[
[
"all_data['SalePrice'] = np.log1p(all_data['SalePrice'])\n\nsns.distplot(all_data['SalePrice'][~all_data['SalePrice'].isnull()], axlabel=\"Normal Distribution\", fit=st.norm, fit_kws={\"color\":\"red\"})\n\nplt.title('Distribution of Transformed Sales Price in Dollars')\n(mu, sigma) = st.norm.fit(train['SalePrice'])\nplt.legend(['Normal Distribution \\n ($\\mu=$ {:.2f} and $\\sigma=$ {:.2f} )'.format(mu, sigma)],\n loc='best', fancybox=True)\nplt.show()\n\nst.probplot(all_data['SalePrice'][~all_data['SalePrice'].isnull()], plot=plt)\nplt.show()",
"_____no_output_____"
]
],
[
[
"The skew is highly corrected and the distribution of the log-transformed sale prices appears more normally distributed.",
"_____no_output_____"
],
[
"# 5 Data Imputation",
"_____no_output_____"
],
[
"## 5.1 Completeness of the Data",
"_____no_output_____"
],
[
"We first need to find which variables contain missing values.",
"_____no_output_____"
]
],
[
[
"cols_with_missing_values = all_data.isnull().sum().sort_values(ascending=False)\ndisplay(pd.DataFrame(cols_with_missing_values[cols_with_missing_values[cols_with_missing_values > 0].index], \n columns=[\"Number of Missing Values\"]))",
"_____no_output_____"
],
[
"cols_with_missing_values = all_data.isnull().sum().sort_values(ascending=False)\ncols_with_missing_values = all_data[cols_with_missing_values[cols_with_missing_values > 0].index]\nmsno.bar(cols_with_missing_values)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## 5.2 Impute the Missing Data",
"_____no_output_____"
],
[
"### 5.2.1 Missing Values Corresponding to Lack of Specific Feature",
"_____no_output_____"
],
[
"* <b>PoolQC</b>: data description of the variables states that NA represents \"no pool\". This makes sense given the vast number of missing values (>99%) and that a majority of houses do not have a pool.",
"_____no_output_____"
]
],
[
[
"all_data['PoolQC'].replace(np.nan, 'None', regex=True, inplace=True)",
"_____no_output_____"
]
],
[
[
"* <b>MiscFeature</b>: data description of the variables states that NA represents \"no miscellaneous feature\". ",
"_____no_output_____"
]
],
[
[
"all_data['MiscFeature'].replace(np.nan, 'None', regex=True, inplace=True)",
"_____no_output_____"
]
],
[
[
"* <b>Alley</b>: data description of the variables states that NA represents \"no alley access\". ",
"_____no_output_____"
]
],
[
[
"all_data['Alley'].replace(np.nan, 'None', regex=True, inplace=True)",
"_____no_output_____"
]
],
[
[
"* <b>Fence</b>: data description of the variables states that NA represents \"no fence\". ",
"_____no_output_____"
]
],
[
[
"all_data['Fence'].replace(np.nan, 'None', regex=True, inplace=True)",
"_____no_output_____"
]
],
[
[
"* <b>FireplaceQU</b>: data description of the variables states that NA represents \"no fireplace\". ",
"_____no_output_____"
]
],
[
[
"all_data['FireplaceQu'].replace(np.nan, 'None', regex=True, inplace=True)",
"_____no_output_____"
]
],
[
[
"* <b>GarageType, GarageFinish, GarageQual, and GarageCond</b>: Missing values are likely due to lack of a garage. Replacing missing data with None.",
"_____no_output_____"
]
],
[
[
"garage_categorical = ['GarageType', 'GarageFinish', 'GarageQual', 'GarageCond']\nfor variable in garage_categorical:\n all_data[variable].replace(np.nan, 'None', regex=True, inplace=True)",
"_____no_output_____"
]
],
[
[
"* <b>GarageYrBlt, GarageCars, and GarageArea</b>: Missing values are likely due to lack of a basement. Replacing missing data with 0 (since no garage means no cars in a garage).",
"_____no_output_____"
]
],
[
[
"garage_numeric = ['GarageYrBlt', 'GarageCars', 'GarageArea']\nfor variable in garage_numeric:\n all_data[variable].replace(np.nan, 0, regex=True, inplace=True)",
"_____no_output_____"
]
],
[
[
"* <b>BsmtQual, BsmtCond, BsmtExposure, BsmtFinType1, and BsmtFinType2</b>: Missing values are likely due to lack of a basement. Replacing missing data with None.",
"_____no_output_____"
]
],
[
[
"basement_categorical = ['BsmtQual','BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2']\nfor variable in basement_categorical:\n all_data[variable].replace(np.nan, 'None', regex=True, inplace=True)",
"_____no_output_____"
]
],
[
[
"* <b>BsmtFinSF1, BsmtFinSF2, BsmtUnfSF, TotalBsmtSF, BsmtFullBath, and BsmtHalfBath</b>: Missing values are likely due to lack of a basement. Replacing missing data with 0.",
"_____no_output_____"
]
],
[
[
"basement_numeric = ['BsmtFinSF1', 'BsmtFinSF2', 'BsmtUnfSF', 'TotalBsmtSF', 'BsmtFullBath', 'BsmtHalfBath']\nfor variable in basement_numeric:\n all_data[variable].replace(np.nan, 0, regex=True, inplace=True)",
"_____no_output_____"
]
],
[
[
"* <b>MasVnrType and MasVnrArea</b>: Missing values are likely due to lack of masonry vaneer. We will replace the missing values with None for the type and 0 for the area.",
"_____no_output_____"
]
],
[
[
"all_data['MasVnrType'].replace(np.nan, 'None', regex=True, inplace=True)\nall_data['MasVnrArea'].replace(np.nan, 0, regex=True, inplace=True)",
"_____no_output_____"
]
],
[
[
"* <b>Functional</b>: data description of the variables states that NA represents \"typical\".",
"_____no_output_____"
]
],
[
[
"all_data['Functional'].replace(np.nan, 'Typ', regex=True, inplace=True)",
"_____no_output_____"
]
],
[
[
"### 5.2.2 Mode Imputation: Replacing Missing Values with Most Frequent Value",
"_____no_output_____"
],
[
"Using a mode imputation, we replace the missing values of a categorical variable with the mode of the non-missing cases of that variable. While it does have the advantage of being fast, it comes at the cost of a reduction in variance within the dataset.\n\nDue to the low number of missing values imputed using this method, the bias introduced on the mean and standard deviation, as well as correlations with other variables are minimal.\n\n<br>\n\nFirst, we define a function \"<b>mode_impute_and_plot</b>\" to simplify the process of visualizing the categorical variables and replacing the missing variables with the most frequent value.",
"_____no_output_____"
]
],
[
[
"def mode_impute_and_plot(variable):\n print('# of missing values: ' + str(all_data[variable].isna().sum()))\n plt.figure(figsize=(8,4))\n ax = sns.countplot(all_data[variable])\n ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha=\"right\")\n plt.tight_layout()\n plt.show()\n \n all_data[variable].replace(np.nan, all_data[variable].mode()[0], regex=True, inplace=True)",
"_____no_output_____"
]
],
[
[
"Now we can proceed to replace the missing values for the following variables:\n\n[]() | \n------|------\n[MSZoning](#MSZoning) | [Utilities](#Utilities) | [Electrical](#Electrical) | [Exterior1st and Exterior2nd](#Exterior1st and Exterior2nd) | [KitchenQual](#KitchenQual) | [SaleType](#SaleType)",
"_____no_output_____"
],
[
"<a id=\"MSZoning\"></a>",
"_____no_output_____"
],
[
"* <b>MSZoning</b>: \"RL\" is by far the most common value. Missing values will be replace with \"RL\".",
"_____no_output_____"
]
],
[
[
"mode_impute_and_plot('MSZoning')",
"_____no_output_____"
]
],
[
[
"<a id=\"Utilities\"></a>",
"_____no_output_____"
],
[
"* <b>Utilities</b>: With the exception of one \"NoSeWa\" value, all records for this variable are \"AllPub\". Since \"NoSeWa\" is only in the training set, <b>this feature will not help in predictive modelling</b>. As such, we can safely remove it.",
"_____no_output_____"
]
],
[
[
"mode_impute_and_plot('Utilities')\n\nall_data = all_data.drop('Utilities', axis=1)",
"_____no_output_____"
]
],
[
[
"<a id=\"Electrical\"></a>",
"_____no_output_____"
],
[
"* <b>Electrical</b>: Only one missing value, replace it with \"SBrkr\", the most common value.",
"_____no_output_____"
]
],
[
[
"mode_impute_and_plot('Electrical')",
"_____no_output_____"
]
],
[
[
"<a id=\"Exterior1st and Exterior2nd\"></a>",
"_____no_output_____"
],
[
"* <b>Exterior1st and Exterior2nd</b>: There is only one missing value for both Exterior 1 & 2. Missing values will be replaced by the most common value.",
"_____no_output_____"
]
],
[
[
"mode_impute_and_plot('Exterior1st')",
"_____no_output_____"
],
[
"mode_impute_and_plot('Exterior2nd')",
"_____no_output_____"
]
],
[
[
"<a id=\"KitchenQual\"></a>",
"_____no_output_____"
],
[
"* <b>KitchenQual</b>: Only one missing value, replace it with \"TA\", the most common value.",
"_____no_output_____"
]
],
[
[
"mode_impute_and_plot('KitchenQual')",
"_____no_output_____"
]
],
[
[
"<a id=\"SaleType\"></a>",
"_____no_output_____"
],
[
"* <b>SaleType</b>: Replace missing values with \"WD\", the most common value.",
"_____no_output_____"
]
],
[
[
"mode_impute_and_plot('SaleType')",
"_____no_output_____"
]
],
[
[
"Are there any remaining missing values?",
"_____no_output_____"
]
],
[
[
"cols_with_missing_values = all_data.isnull().sum().sort_values(ascending=False)\ndisplay(pd.DataFrame(cols_with_missing_values[cols_with_missing_values[cols_with_missing_values > 0].index], columns=[\"Number of Missing Values\"]))\n",
"_____no_output_____"
]
],
[
[
"Due to its numeric nature and the large number of missing values, the LotFrontage variable will be imputed separately using an SVM algorithm (See Section [7 LotFrontage Imputation](#7-Lot-Frontage-Imputation)). \n\n<br>\nThe remaining variables are all complete! Now to move on to feature engineering.",
"_____no_output_____"
],
[
"# 6 Feature Engineering",
"_____no_output_____"
],
[
"## 6.1 Mixed Conditions\n\nIn order to simplify and boost the accuracy of the preditive models, we will merge the two conditions into one variable: <b>MixedConditions</b>\n\nThe data descriptions states:\n* <b>Condition1</b> represents proximity to various conditions.\n* <b>Condition2</b> represents proximity to various conditions (if more than one is present).\n\nIf a property does not have one or multiple conditions, then it is classified as normal. However, designation of \"normal\" are condition 1 or condition 2 is strictly alphabetical.\n\nFor example, if a property is in proximity to a feeder street (\"Feedr\") and no other condition, then the data would appear as follows:\n\nCondition1 | Condition2\n-----------|-------------\n Feedr | Norm\n\n<br>\n \nHowever, if a property is within 200' of East-West Railroad (RRNe) and no other condition, then the data would appear as follows:\n\nCondition1 | Condition2\n-----------|-------------\n Norm | RRNe\n\n\n<br><br>\n\nOnce we merge Conditions 1 & 2 into the <b>MixedConditions</b> variable, we will remove them from the analysis.",
"_____no_output_____"
]
],
[
[
"all_data['MixedConditions'] = all_data['Condition1'] + ' - ' + all_data['Condition2']\nall_data.drop(labels=['Condition1', 'Condition2'], axis=1, inplace=True)",
"_____no_output_____"
]
],
[
[
"## 6.2 Mixed Exterior\nThe Exterior1st and Exterior2nd features are similar to the Conditions feature we merged and remove above. Properties with multiple types of exterior covering the house are assigned to Exterior1st or Exterior2nd alphabetically.\n\nAs such, we will conduct the same process to merge the two columns into a single <b>MixedExterior</b> variable and remove them from the analysis.",
"_____no_output_____"
]
],
[
[
"all_data['MixedExterior'] = all_data['Exterior1st'] + ' - ' + all_data['Exterior2nd']\nall_data.drop(labels=['Exterior1st', 'Exterior2nd'], axis=1, inplace=True)",
"_____no_output_____"
]
],
[
[
"## 6.3 Total Square Feet\nOne of the important factors that people consider when buying a house is the total living space in square feet. Since the total square feet is not explicitly listed, we will add a new variable by adding up the square footage of the basement, first floor, and the second floor.",
"_____no_output_____"
]
],
[
[
"SF_df = all_data[['TotalBsmtSF', '1stFlrSF', '2ndFlrSF', 'SalePrice']]\nSF_df = SF_df[~SF_df['SalePrice'].isnull()]\nSF_vars = list(SF_df)\ndel SF_vars[-1]\n\nSF_summary = []\n\nfor SF_type in SF_vars:\n corr_val = np.corrcoef(SF_df[SF_type], SF_df['SalePrice'])[1][0]\n SF_summary.append(corr_val)\n \npd.DataFrame([SF_summary], columns=SF_vars, index=['SalePrice Correlation'])",
"_____no_output_____"
],
[
"all_data['TotalSF'] = all_data['TotalBsmtSF'] + all_data['1stFlrSF'] + all_data['2ndFlrSF']\n\nplt.figure(figsize=(10,6))\nax = sns.regplot(all_data['TotalSF'], all_data['SalePrice'], line_kws={'color': 'red'})\nax.set(ylabel='ln(SalePrice)')\nplt.show()\n\nprint(\"Pearson Correlation Coefficient: %.3f\" % (np.corrcoef(all_data['TotalSF'].iloc[:ntrain], train['SalePrice']))[1][0])",
"_____no_output_____"
]
],
[
[
"There is a very strong correlation (r = 0.78) between the TotalSF and the SalePrice, with the exception of two outliers. These outliers should be removed to increase the accuracy of our model.",
"_____no_output_____"
],
[
"## 6.4 Total Number of Bathrooms\n\nThere are 4 bathroom variables. Individually, these variables are not very important. Together, however, these predictors are likely to become a strong one.\n\nA full bath is made up of four parts: a sink, shower, a bathtub, and a toilet. A half-bath, also called a powder room or guest bath, only has a sink and a toilet. As such, half-bathrooms will have half the value of a full bath. ",
"_____no_output_____"
]
],
[
[
"bath_df = all_data[['BsmtFullBath', 'BsmtHalfBath', 'FullBath', 'HalfBath', 'SalePrice']]\nbath_df = bath_df[~bath_df['SalePrice'].isnull()]\nbath_vars = list(bath_df)\ndel bath_vars[-1]\n\nbath_summary = []\n\nfor bath_type in bath_vars:\n corr_val = np.corrcoef(bath_df[bath_type], bath_df['SalePrice'])[1][0]\n bath_summary.append(corr_val)\n \npd.DataFrame([bath_summary], columns=bath_vars, index=['SalePrice Correlation'])",
"_____no_output_____"
],
[
"all_data['TotalBath'] = all_data['BsmtFullBath'] + (all_data['BsmtHalfBath']*0.5) + all_data['FullBath'] + (all_data['HalfBath']*0.5)\n\nplt.figure(figsize=(10,4))\nsns.countplot(all_data['TotalBath'], color='grey')\nplt.tight_layout()\nplt.show()\n\nplt.figure(figsize=(10,6))\nsns.regplot(all_data['TotalBath'].iloc[:ntrain], train['SalePrice'], line_kws={'color': 'red'})\nax.set(ylabel='ln(SalePrice)')\nplt.show()\n\nprint(\"Pearson Correlation Coefficient: %.3f\" % (np.corrcoef(all_data['TotalBath'].iloc[:ntrain], train['SalePrice']))[1][0])",
"_____no_output_____"
]
],
[
[
"We can see a high positive correlation (r = 0.67) between TotalBath and SalePrice. The new variable correlation is much higher than any of the four original bathroom variables.",
"_____no_output_____"
],
[
"## 6.5 Binning the Neighbourhoods",
"_____no_output_____"
]
],
[
[
"neighborhood_prices = all_data.iloc[:ntrain].copy()\nneighborhood_prices['SalePrice'] = np.exp(all_data['SalePrice'])\nneighborhood_prices = neighborhood_prices[['Neighborhood', 'SalePrice']].groupby('Neighborhood').median().sort_values('SalePrice')\n\nplt.figure(figsize=(15,7))\nax = sns.barplot(x= neighborhood_prices.index, y=neighborhood_prices['SalePrice'], color='grey')\nax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha=\"right\")\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"In order to bin the neighbourhoods into approriate clusters, we will use K-Mean clustering. <b>K-Means</b> is an unsupervised machine learning algorithm that groups a dataset into a user-specified number (<i>k</i>) of clusters. One potential issue with the algorithm is that it will cluster the data into <i>k</i> clusters, even if <i>k</i> is not the right number of cluster to use.\n\nTherefore, we need to identity the optimal number of k clusters to use. To do so, we will use the <i>Elbow Method</i>. \n\nBriefly, the idea of the elbow method is to run k-means clustering for a range of values and calculate the sum of squared errors (SSE). We then plot a line chart of the SSE for each value of <i>k</i>. Each additional <i>k</i> cluster will result in a lower SSE, but will eventually exhibit significantly diminished return. \n\nThe goal is the choose a small value of k with a low SSE, after which the subsequent k values exhibit diminishing returns. If the line plot looks like an arm, then the \"elbow\" of the arm is the optimal <i>k</i> value. \n\nThe plot below indicates that the optimal number of neighbourhood clusters is <i>k</i> = 3.",
"_____no_output_____"
]
],
[
[
"SS_distances = []\nK = range(1,10)\nfor k in K:\n km = KMeans(n_clusters=k)\n km = km.fit(neighborhood_prices)\n SS_distances.append(km.inertia_)\n \n\nplt.plot(K, SS_distances, 'bx-')\nplt.xlabel('k')\nplt.ylabel('Sum of squared distances')\nplt.title('Elbow Method For Optimal k')\nplt.show()",
"_____no_output_____"
]
],
[
[
"Now let's see how the binned neighborhoods look like.",
"_____no_output_____"
]
],
[
[
"neighborhood_prices['Cluster'] = KMeans(n_clusters=3).fit(neighborhood_prices).labels_\n\nplt.figure(figsize=(15,7))\nax = sns.barplot(x= neighborhood_prices.index, y=neighborhood_prices['SalePrice'], \n hue=neighborhood_prices['Cluster'])\nax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha=\"right\")\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"Lastly, we have to create a new variable in the dataset based on the new cluster labels.",
"_____no_output_____"
]
],
[
[
"neighborhood_dict = dict(zip(neighborhood_prices.index, neighborhood_prices.Cluster))\nall_data['Neighborhood_Class'] = all_data['Neighborhood']\nall_data['Neighborhood_Class'].replace(neighborhood_dict, inplace = True)",
"_____no_output_____"
]
],
[
[
"# 7 LotFrontage Imputation\n\nDue to the numeric nature and sheer number of missing values in the <i>LotFrontage</i> column, we will impute the missing values using an SVM Regressor algorithm to predict the missing values.\n\nThe first step is to subset the dataset into two groups. The <i>train</i> dataset (train_LotFrontage) contains the complete records while the <i>test</i> dataset (test_LotFrontage) contains the missing values. Next, we examine the structure of the newly created datasets. There are 486 missing values in the full dataset, or roughly 16% of the data.",
"_____no_output_____"
],
[
"## 7.1 LotFrontage Data Structure",
"_____no_output_____"
]
],
[
[
"train_LotFrontage = all_data[~all_data.LotFrontage.isnull()]\ntest_LotFrontage = all_data[all_data.LotFrontage.isnull()]\n\nprint(\"Dimensions of Train LotFrontage Dataset:\" + str(train_LotFrontage.shape))\nprint(\"Dimensions of Test LotFrontage Dataset:\" + str(test_LotFrontage.shape))\ndisplay(pd.DataFrame(all_data['LotFrontage'].describe()).transpose())",
"_____no_output_____"
]
],
[
[
"Now let's examine the distribution of LotFrontages values in the Train LotFrontage dataset through a boxplot and distribution plot. Through these graphs, we can see several interesting observations appear:\n* There is a cluster of low <i>LotFrontage</i> value properties, shown as a peak on the far left of the distribution plot. The boxplot indicates these values may be outliers, shown as outlier points on the left of the whisker of the boxplot.\n* There is a long tail of high <i>LotFrontage</i> value properties. These values extend beyond the Median + 1.5IQR range.\n\nIn other words, there are outliers on both ends of the <i>LotFrontage</i> value distributions.",
"_____no_output_____"
]
],
[
[
"fig, ax = plt.subplots(1,2, figsize=(16,4))\nsns.boxplot(train_LotFrontage['LotFrontage'], ax=ax[0])\n\nsns.distplot(train_LotFrontage['LotFrontage'], ax=ax[1], fit=st.norm, fit_kws={\"color\":\"red\"})\n(mu, sigma) = st.norm.fit(train_LotFrontage['LotFrontage'])\nplt.legend(['Normal Distribution \\n ($\\mu=$ {:.2f} and $\\sigma=$ {:.2f} )'.format(mu, sigma)],\n loc='best', fancybox=True)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## 7.2 Outlier Detection & Removal\nBefore we examine the correlations between <i>LotFrontage</i> and other variables, we should remove the outliers seen above. \n\nTo do so, we will use the Interquartile Range (IQR) method, where values outside the <i>Median ± 1.5IQR</i> are considered to be outliers. These outliers are then removed from the <i>LotFrontage</i> datasets.",
"_____no_output_____"
]
],
[
[
"def outlier_detection(data):\n Q1, Q3 = np.percentile(data, [25,75])\n IQR = Q3-Q1\n lower_cutoff = Q1 - (IQR * 1.5)\n upper_cutoff = Q3 + (IQR * 1.5)\n outliers = (data > Q3+1.5*IQR) | (data < Q1-1.5*IQR)\n return outliers",
"_____no_output_____"
],
[
"train_LotFrontage_no_outliers = train_LotFrontage[~outlier_detection(train_LotFrontage.LotFrontage)]\nfig, ax = plt.subplots(1,2, figsize=(16,4))\nsns.boxplot(train_LotFrontage_no_outliers['LotFrontage'], ax=ax[0])\n\nsns.distplot(train_LotFrontage_no_outliers['LotFrontage'], ax=ax[1], fit=st.norm, fit_kws={\"color\":\"red\"})\n(mu, sigma) = st.norm.fit(train_LotFrontage_no_outliers['LotFrontage'])\nplt.legend(['Normal Distribution \\n ($\\mu=$ {:.2f} and $\\sigma=$ {:.2f} )'.format(mu, sigma)],\n loc='best', fancybox=True)\nplt.show()",
"_____no_output_____"
]
],
[
[
"Two new values previously not deemed outliers by the first iteration of the IQR range method are now shown as potential outliers in the boxplot. This is caused by having a new smaller IQR value after removing the first batch of outliers. As such, we will keep these values.",
"_____no_output_____"
],
[
"## 7.3 Determining Relevant Variables of LotFrontage\nNow we can explore the relationship between the <i>LotFrontage</i> target variable and other features. In order to confirm a relationship between these key features and we will conduct an <b>ANOVA</b> (Analysis of Variance) test to determine statistical significance (in this case, <i>p < 0.01</i>).\n\n\n<br>\nUsing the type III ANOVA, we are confident the variables listed in the table below are correlated with LotFrontage.\n\n* Note: Variables that begin with a number (<i>1stFlrSF</i>, <i>2ndFlrSF</i>, and <i>3SsnPorch</i>) cause a syntax error within the ols formula input. I briefly converted them to an appropriate name in the <i>temp_train</i> dataset for the purpose of the ANOVA.",
"_____no_output_____"
]
],
[
[
"temp_train = train_LotFrontage_no_outliers.copy()\ntemp_train.rename(columns={'1stFlrSF':'X1stFlrSF', '2ndFlrSF': 'X2ndFlrSF', '3SsnPorch': 'X3SsnPorch'}, inplace=True)\n\nmod = ols('LotFrontage ~ X1stFlrSF + X2ndFlrSF + X3SsnPorch + Alley + BedroomAbvGr + BldgType + BsmtCond + BsmtExposure + BsmtFinSF1 + BsmtFinSF2 + BsmtFinType1 + BsmtFinType2 + BsmtFullBath + BsmtHalfBath + BsmtQual + BsmtUnfSF + CentralAir + Electrical + EnclosedPorch + ExterCond + ExterQual + Fence + FireplaceQu + Fireplaces + Foundation + FullBath + Functional + GarageArea + GarageCars + GarageCond + GarageFinish + GarageQual + GarageType + GarageYrBlt + GrLivArea + HalfBath + Heating + HeatingQC + HouseStyle + KitchenAbvGr + KitchenQual + LandContour + LandSlope + LotArea + LotConfig + LotShape + LowQualFinSF + MSSubClass + MSZoning + MasVnrArea + MasVnrType + MiscFeature + MiscVal + MoSold + Neighborhood + OpenPorchSF + OverallCond + OverallQual + PavedDrive + PoolArea + PoolQC + RoofMatl + RoofStyle + SaleCondition + SaleType + ScreenPorch + Street + TotRmsAbvGrd + TotalBsmtSF + WoodDeckSF + YearBuilt + YearRemodAdd + YrSold + MixedConditions + MixedExterior + TotalSF + TotalBath + Neighborhood_Class', data=temp_train).fit()\naov_table = sm.stats.anova_lm(mod, typ=3)\ndisplay(aov_table[aov_table['PR(>F)'] < 0.01])",
"_____no_output_____"
]
],
[
[
"## 7.4 LotFrontage Model Building and Evaluation\nNow let's build a model using the relevant variables selected above. We will be using Support Vector Regressor to build the model.\n\nThe first step is to seperate the target variable, <i>LotFrontage</i>, select the relevant variables, and dummifying the categorical variables.",
"_____no_output_____"
]
],
[
[
"X = train_LotFrontage_no_outliers[aov_table[aov_table['PR(>F)'] < 0.01].index]\ny = train_LotFrontage_no_outliers['LotFrontage']\n\nX = pd.get_dummies(X)\ntransformer = StandardScaler().fit(X)\nX = transformer.transform(X)",
"_____no_output_____"
]
],
[
[
"In order to determine the accuracy of our predictive model, we will create a <i>Validation</i> dataset. This dataset will have known values for the target <i>LotFrontage</i> variable which can we compare our model's prediction against. Using the mean absolute error, we can measure the difference between our predicted <i>LotFrontage</i> values with the true values.\n\n<img src=\"https://i.imgur.com/jswcCd8.png\">",
"_____no_output_____"
]
],
[
[
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=1234)\n\nclf = svm.SVR(kernel='rbf', C=100, gamma=0.001)\nclf.fit(X_train, y_train)\npreds = clf.predict(X_test)\nprint('Mean Absolute Error: %.3f' % mean_absolute_error(y_test, preds))",
"_____no_output_____"
]
],
[
[
"These results show that using the SVR model to impute <i>LotFrontage</i> gives an average rror of less than 7 feet.\n\nWe will now use the same SVR model to predict the unknown <i>LotFrontage</i> values in the test_Frontage dataset.",
"_____no_output_____"
]
],
[
[
"model_data = train_LotFrontage_no_outliers.copy()\nmodel_data= model_data.append(test_LotFrontage)\ny = model_data['LotFrontage']\nmodel_data = model_data[['MSZoning', 'Alley', 'LotArea', 'LotShape', 'LotConfig', 'Neighborhood', 'MixedConditions', 'GarageType', 'GarageCars', 'GarageArea']]\n\nmodel_data = pd.get_dummies(model_data)\nmodel_X_train = model_data[~y.isnull()]\nmodel_X_test = model_data[y.isnull()]\nmodel_y_train = y[~y.isnull()]\n\ntransformer = StandardScaler().fit(model_X_train)\nmodel_X_train = transformer.transform(model_X_train)\nmodel_X_test = transformer.transform(model_X_test)\n\nclf = svm.SVR(kernel='rbf', C=100, gamma=0.001)\nclf.fit(model_X_train, model_y_train)\nLotFrontage_preds = clf.predict(model_X_test)",
"_____no_output_____"
]
],
[
[
"Now that we have the newly predicted <i>LotFrontage</i> values, we can examine the distribution of predicted values relative to the known <i>LotFrontage</i> values in the training dataset. Both distributions have a mean around 70 feet with similar tail lengths on either end. ",
"_____no_output_____"
]
],
[
[
"sns.distplot(model_y_train)\nsns.distplot(LotFrontage_preds)",
"_____no_output_____"
]
],
[
[
"Lastly, we need to add the predicted values back into the original dataset.",
"_____no_output_____"
]
],
[
[
"all_data.LotFrontage[all_data.LotFrontage.isnull()] = LotFrontage_preds",
"_____no_output_____"
]
],
[
[
"# 8 Preparing the Data for Modelling",
"_____no_output_____"
],
[
"## 8.1 Removing Outliers\nAlthough we could be more in depth in our outliet detection and removal, we are only going to remove the two outliers found in the TotalSF variable. These properties exhibited large total square feet values with low SalePrice.",
"_____no_output_____"
]
],
[
[
"all_data.drop(all_data['TotalSF'].iloc[:ntrain].nlargest().index[:2], axis=0, inplace=True) \nntrain = train.shape[0]-2",
"_____no_output_____"
]
],
[
[
"## 8.2 Correlation Between Numeric Predictors\n\nWe can see a large correlation between many variables, suggesting a high level of multicollinearity. There are two options to consider:\n1. Use a regression model that deals well with multicollinearity, such as a ridge regression.\n2. Remove highly correlated predictors from the model.",
"_____no_output_____"
]
],
[
[
"corr = all_data.corr()\nmask = np.zeros_like(corr, dtype=np.bool)\nmask[np.triu_indices_from(mask)] = True\n\nf, ax = plt.subplots(figsize=(15, 15))\ncmap = sns.diverging_palette(220, 10, as_cmap=True)\n\nsns.heatmap(corr, mask=mask, cmap=cmap,\n center=0, square=True, linewidths = .5)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## 8.3 Label Encoding\nMany of the ordinal variables are presented as numeric values. Therefore we need to label encode these numeric characters into strings.",
"_____no_output_____"
]
],
[
[
"num_to_str_columns = ['MSSubClass', 'OverallQual', 'OverallCond', 'MoSold', 'YrSold']\n\nfor col in num_to_str_columns:\n all_data[col] = all_data[col].astype('str')",
"_____no_output_____"
],
[
"cat_cols = ['OverallQual', 'OverallCond', 'ExterQual', 'ExterCond', 'BsmtQual', 'BsmtCond', 'BsmtExposure', 'BsmtFinType1', \n 'BsmtFinType2', 'BsmtFinSF2', 'HeatingQC', 'BsmtFullBath', 'BsmtHalfBath', 'FullBath', 'HalfBath', 'BedroomAbvGr', \n 'KitchenAbvGr', 'KitchenQual', 'TotRmsAbvGrd', 'Fireplaces', 'FireplaceQu', 'GarageFinish', 'GarageCars',\n 'GarageQual', 'GarageCond', 'PoolQC', 'Fence', 'YearBuilt', 'YearRemodAdd', 'GarageYrBlt', 'MoSold', 'YrSold']\n\nfor col in cat_cols:\n label = LabelEncoder()\n label.fit(list(all_data[col].values))\n all_data[col] = label.transform(list(all_data[col].values))\n\nprint('Shape all_data: {}'.format(all_data.shape))\nall_data.head()",
"_____no_output_____"
]
],
[
[
"## 8.4 Skewness & Normalization of Numeric Variables\n\n<b>Skewness</b> is a measure of asymmetry of a distribution, and can be used to define the extent to which the distribution differs from a normal distribution. Therefore, a normal distribution will have a skewness of 0. As a rule of thumb, if skewness is less than -1 or greater than 1, the distribution is highly skewed. \n\nIn order to account for skewness, we will transform the (highly) skewed data into normality using a Log Transformation. We define highly skewed data as variables with a skewness greater than 0.85. This method is similar to the approach used to normalize the [SalePrice Response Variable](#4.2-Log-Transformation-of-the-Response-Variable), except we will use log+1 to avoid division by zero issues.",
"_____no_output_____"
]
],
[
[
"numeric_feats = ['LotFrontage', 'LotArea', 'BsmtFinSF1', 'BsmtUnfSF', 'TotalBsmtSF', '1stFlrSF', '2ndFlrSF', \n 'LowQualFinSF', 'GrLivArea', 'GarageArea', 'WoodDeckSF', 'OpenPorchSF', 'EnclosedPorch',\n '3SsnPorch', 'ScreenPorch', 'PoolArea', 'MiscVal', 'TotalSF']\n\nskewed_feats = all_data[numeric_feats].apply(lambda x: st.skew(x.dropna())).sort_values(ascending=False)\nskewness = pd.DataFrame({'Skew Before Transformation' :skewed_feats})\n\nskewness = skewness[abs(skewness) > 1].dropna(axis=0)\nskewed_features = skewness.index\nfor feat in skewed_features:\n all_data[feat] = np.log1p(all_data[feat]+1)\n\nskewed_feats = all_data[skewed_features].apply(lambda x: st.skew(x.dropna())).sort_values(ascending=False)\nskewness['Skew After Transformation'] = skewed_feats\nskewness",
"_____no_output_____"
]
],
[
[
"## 8.5 One Hot Encoding the Categorical Variables\nThe last step needed to prepare the data is to make sure that all categorical predictor variables are converted into a form that is usable by machine learning algorithms. This process is known as 'one-hot encoding' the categorical variables.\n\nThe process involved all non-ordinal factors receiving their own separate column with 1's and 0's, and is required by most ML algorithms.",
"_____no_output_____"
]
],
[
[
"all_data = pd.get_dummies(all_data)\nprint(all_data.shape)\nall_data.head(3)",
"_____no_output_____"
]
],
[
[
"# 9 SalePrice Modelling\nNow that the data is correctly processed, we are ready to begin building our predictive models. ",
"_____no_output_____"
],
[
"## 9.1 Obtaining Final Train and Test Sets",
"_____no_output_____"
]
],
[
[
"final_y_train = all_data['SalePrice'][~all_data['SalePrice'].isnull()]\nfinal_X_train = all_data[all_data['Dataset_Train'] == 1].drop(['Dataset_Train', 'Dataset_Test', 'SalePrice'], axis=1)\nfinal_X_test = all_data[all_data['Dataset_Test'] == 1].drop(['Dataset_Train', 'Dataset_Test', 'SalePrice'], axis=1)",
"_____no_output_____"
]
],
[
[
"## 9.2 Defining a Cross Validation Strategy\nWe will use the [cross_val_score](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross_val_score.html) function of Sklearn and calculate the Root-Mean-Squared Error (RMSE) as a measure of accuracy.",
"_____no_output_____"
]
],
[
[
"n_folds = 10\n\ndef rmse_cv(model):\n kf = KFold(n_folds, shuffle=True, random_state=1234).get_n_splits(final_X_train.values)\n rmse= np.sqrt(-cross_val_score(model, final_X_train.values, final_y_train, scoring=\"neg_mean_squared_error\", cv = kf))\n return(rmse)",
"_____no_output_____"
]
],
[
[
"## 9.3 Lasso Regression Model\n\nThis model may be senstitive to outliers, so we need to make it more robust. This will be done using the <b>RobustScaler</b> function on pipeline.",
"_____no_output_____"
]
],
[
[
"lasso = make_pipeline(RobustScaler(), Lasso(alpha = 0.0005, random_state = 1234))",
"_____no_output_____"
]
],
[
[
"Next, we tested out multiple alpha values and compared their accuracy using the <b>rmse_cv</b> function above. The results below show that using a value of 0.00025 is the optimal value of alpha for a Lasso Regression.",
"_____no_output_____"
]
],
[
[
"lasso_alpha = [1, 0.5, 0.25, 0.1, 0.05, 0.025, 0.01, 0.005, 0.0025, 0.001, 0.0005, 0.00025, 0.0001]\nlasso_rmse = []\n\nfor value in lasso_alpha:\n lasso = make_pipeline(RobustScaler(), Lasso(alpha = value, max_iter=3000, random_state = 1234))\n lasso_rmse.append(rmse_cv(lasso).mean())\n \nlasso_score_table = pd.DataFrame(lasso_rmse,lasso_alpha,columns=['RMSE'])\ndisplay(lasso_score_table.transpose())\n\nplt.semilogx(lasso_alpha, lasso_rmse)\nplt.xlabel('alpha')\nplt.ylabel('score')\nplt.show()\n\nprint(\"\\nLasso Score: {:.4f} (alpha = {:.5f})\\n\".format(min(lasso_score_table['RMSE']), lasso_score_table.idxmin()[0]))",
"_____no_output_____"
]
],
[
[
"Using the newly defined alpha value, we can optimize the model and predict the missing values of <i>SalePrice</i>. The predictions are then formatted in a appropriate layout for submission to Kaggle.",
"_____no_output_____"
]
],
[
[
"lasso = make_pipeline(RobustScaler(), Lasso(alpha = 0.00025, random_state = 1234))\nlasso.fit(final_X_train, final_y_train)\nlasso_preds = np.expm1(lasso.predict(final_X_test))\n\nsub = pd.DataFrame()\nsub['Id'] = test_id\nsub['SalePrice'] = lasso_preds\n#sub.to_csv('Lasso Submission 2.csv',index=False)",
"_____no_output_____"
]
],
[
[
"\n### LASSO Regression Score: 0.12679\n\n<br>",
"_____no_output_____"
],
[
"## 9.4 Ridge Regression Model\nIdentical steps were taken for the ridge regression model as we took for the [Lasso Regression Model](#9.3-Lasso-Regression-Model). In the case of the Ridge model, the optimal alpha value was 6.",
"_____no_output_____"
]
],
[
[
"ridge_alpha = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]\nridge_rmse = []\n\nfor value in ridge_alpha:\n ridge = make_pipeline(RobustScaler(), Ridge(alpha = value, random_state = 1234))\n ridge_rmse.append(rmse_cv(ridge).mean())\n \nridge_score_table = pd.DataFrame(ridge_rmse,ridge_alpha,columns=['RMSE'])\ndisplay(ridge_score_table.transpose())\n\nplt.semilogx(ridge_alpha, ridge_rmse)\nplt.xlabel('alpha')\nplt.ylabel('score')\nplt.show()\n\nprint(\"\\nRidge Score: {:.4f} (alpha = {:.4f})\\n\".format(min(ridge_score_table['RMSE']), ridge_score_table.idxmin()[0]))",
"_____no_output_____"
],
[
"ridge = make_pipeline(RobustScaler(), Ridge(alpha = 6, random_state = 1234))\nridge.fit(final_X_train, final_y_train)\nridge_preds = np.expm1(ridge.predict(final_X_test))\n\nsub = pd.DataFrame()\nsub['Id'] = test_id\nsub['SalePrice'] = ridge_preds\n#sub.to_csv('Ridge Submission.csv',index=False)",
"_____no_output_____"
]
],
[
[
"\n### Ridge Regression Score: 0.12528\n\n<br>",
"_____no_output_____"
],
[
"## 9.5 XGBoost Model\nSince there are multiple hyperparameters to tune in the XGBoost model, we will use the [GridSearchCV](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html) function of Sklearn to determine the optimal values. Next, I used the [train_test_split](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html) function to generate a validation set and find the RMSE of the models. This method is used in lieu of the [rmse_cv](#9.2-Defining-a-Cross-Validation-Strategy)\n function used above for the Lasso and Ridge Regression models.",
"_____no_output_____"
]
],
[
[
"xg_X_train, xg_X_test, xg_y_train, xg_y_test = train_test_split(final_X_train, final_y_train, test_size=0.33, random_state=1234)\n\nxg_model = XGBRegressor(n_estimators=100, seed = 1234)\nparam_dict = {'max_depth': [3,4,5],\n 'min_child_weight': [2,3,4],\n 'learning_rate': [0.05, 0.1,0.15],\n 'gamma': [0.0, 0.1, 0.2]\n}\n\nstart = time()\ngrid_search = GridSearchCV(xg_model, param_dict)\ngrid_search.fit(xg_X_train, xg_y_train)\nprint(\"GridSearch took %.2f seconds to complete.\" % (time()-start))\ndisplay(grid_search.best_params_)",
"_____no_output_____"
]
],
[
[
"Now that the hyperparameter have been chosen, we can calculate the validation RMSE of the XGBoost model.",
"_____no_output_____"
]
],
[
[
"xg_model = XGBRegressor(n_estimators = 1000,\n learning_rate = 0.1,\n max_depth = 4,\n min_child_weight = 4,\n gamma = 0,\n seed = 1234)\nstart = time()\nxg_model.fit(xg_X_train, xg_y_train)\nxg_preds = xg_model.predict(xg_X_test)\nprint(\"Model took %.2f seconds to complete.\" % (time()-start))\nprint(\"RMSE: %.4f\" % sqrt(mean_squared_error(xg_y_test, xg_preds)))",
"_____no_output_____"
]
],
[
[
"Lastly, we predict the <i>SalePrice</i> using the test data. The predictions are then formatted in a appropriate layout for submission to Kaggle.",
"_____no_output_____"
]
],
[
[
"xg_model = XGBRegressor(n_estimators = 1000,\n learning_rate = 0.1,\n max_depth = 4,\n min_child_weight = 4,\n gamma = 0,\n seed = 1234)\nxg_model.fit(final_X_train, final_y_train)\nxg_preds = np.expm1(xg_model.predict(final_X_test))",
"_____no_output_____"
],
[
"sub = pd.DataFrame()\nsub['Id'] = test_id\nsub['SalePrice'] = xg_preds\n#sub.to_csv('XGBoost Submission.csv',index=False)",
"_____no_output_____"
]
],
[
[
"\n### XGBoost Regression Model: 0.12799\n\n<br>",
"_____no_output_____"
],
[
"## 9.6 Ensemble Model\nSince the Lasso, Ridge, XGBoost algorithms so different, averaging the final <i>Saleprice</i> predictions may improve the accuracy. Since the Ridge regression performed the best with regards to the final RMSE (0.125 vs 0.126 and 0.127), I will assign it's weight to be double that of the other two models.\n\nOur final ensemble model performed better than any individual regression model (<b>RMSE = 0.12220</b>).",
"_____no_output_____"
]
],
[
[
"lasso = make_pipeline(RobustScaler(), Lasso(alpha = 0.00025, random_state = 1234))\nlasso.fit(final_X_train, final_y_train)\nlasso_preds = np.expm1(lasso.predict(final_X_test))\n\nridge = make_pipeline(RobustScaler(), Ridge(alpha = 6, random_state = 1234))\nridge.fit(final_X_train, final_y_train)\nridge_preds = np.expm1(ridge.predict(final_X_test))\n\nxg_model = XGBRegressor(n_estimators = 1000,\n learning_rate = 0.1,\n max_depth = 4,\n min_child_weight = 4,\n gamma = 0,\n seed = 1234)\nxg_model.fit(final_X_train, final_y_train)\nxg_preds = np.expm1(xg_model.predict(final_X_test))\n\nweights = [0.5, 0.25, 0.25]\n\nsub = pd.DataFrame()\nsub['Id'] = test_id\nsub['SalePrice'] = (ridge_preds*weights[0]) + (lasso_preds*weights[1]) + (xg_preds*weights[2])\nsub.to_csv('Ensemble Submission.csv',index=False)",
"_____no_output_____"
]
],
[
[
"\n### Ensemble Regression Score: 0.12220\n\n<br>",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
d081dca052c3da5551eae70d9b790fbc87394bab | 11,573 | ipynb | Jupyter Notebook | RL_with_CALVIN.ipynb | lucys0/calvin | e29ceb66d0744923f9d952977792f19b431cc7c4 | [
"MIT"
] | 70 | 2021-12-08T12:41:39.000Z | 2022-03-17T14:58:25.000Z | RL_with_CALVIN.ipynb | lucys0/calvin | e29ceb66d0744923f9d952977792f19b431cc7c4 | [
"MIT"
] | 11 | 2021-12-15T04:37:02.000Z | 2022-03-31T11:33:03.000Z | RL_with_CALVIN.ipynb | lucys0/calvin | e29ceb66d0744923f9d952977792f19b431cc7c4 | [
"MIT"
] | 12 | 2021-12-09T13:13:32.000Z | 2022-02-16T10:53:13.000Z | 36.623418 | 245 | 0.509807 | [
[
[
"<a href=\"https://colab.research.google.com/github/mees/calvin/blob/main/RL_with_CALVIN.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"<h1>Reinforcement Learning with CALVIN</h1>\n\nThe **CALVIN** simulated benchmark is perfectly suited for training agents with reinforcement learning, in this notebook we will demonstrate how to integrate your agents to these environments.",
"_____no_output_____"
],
[
"## Installation\nThe first step is to install the CALVIN github repository such that we have access to the packages",
"_____no_output_____"
]
],
[
[
"# Download repo\n%mkdir /content/calvin\n%cd /content/calvin\n!git clone https://github.com/mees/calvin_env.git\n%cd /content/calvin/calvin_env\n!git clone https://github.com/lukashermann/tacto.git\n# Install packages \n%cd /content/calvin/calvin_env/tacto/\n!pip3 install -e .\n%cd /content/calvin/calvin_env\n!pip3 install -e .\n!pip3 install -U numpy",
"_____no_output_____"
],
[
"# Run this to check if the installation was succesful\nfrom calvin_env.envs.play_table_env import PlayTableSimEnv",
"_____no_output_____"
]
],
[
[
"## Loading the environment\nAfter the installation has finished successfully, we can start using the environment for reinforcement Learning.\nTo be able to use the environment we need to have the appropriate configuration that define the desired features, for this example, we will load the static and gripper camera.",
"_____no_output_____"
]
],
[
[
"%cd /content/calvin\nfrom hydra import initialize, compose\n\nwith initialize(config_path=\"./calvin_env/conf/\"):\n cfg = compose(config_name=\"config_data_collection.yaml\", overrides=[\"cameras=static_and_gripper\"])\n cfg.env[\"use_egl\"] = False\n cfg.env[\"show_gui\"] = False\n cfg.env[\"use_vr\"] = False\n cfg.env[\"use_scene_info\"] = True\n print(cfg.env)",
"_____no_output_____"
]
],
[
[
"The environment has similar structure to traditional OpenAI Gym environments.\n\n* We can restart the simulation with the *reset* function.\n* We can perform an action in the environment with the *step* function.\n* We can visualize images taken from the cameras in the environment by using the *render* function.\n\n\n\n",
"_____no_output_____"
]
],
[
[
"import time\nimport hydra\nimport numpy as np\nfrom google.colab.patches import cv2_imshow\n\nenv = hydra.utils.instantiate(cfg.env)\nobservation = env.reset()\n#The observation is given as a dictionary with different values\nprint(observation.keys())\nfor i in range(5):\n # The action consists in a pose displacement (position and orientation)\n action_displacement = np.random.uniform(low=-1, high=1, size=6)\n # And a binary gripper action, -1 for closing and 1 for oppening\n action_gripper = np.random.choice([-1, 1], size=1)\n action = np.concatenate((action_displacement, action_gripper), axis=-1)\n observation, reward, done, info = env.step(action)\n rgb = env.render(mode=\"rgb_array\")[:,:,::-1]\n cv2_imshow(rgb)",
"_____no_output_____"
]
],
[
[
"## Custom environment for Reinforcement Learning\nThere are some aspects that needs to be defined to be able to use it for reinforcement learning, including:\n\n1. Observation space\n2. Action space\n3. Reward function\n\nWe are going to create a Custom environment that extends the **PlaytableSimEnv** to add these requirements. <br/>\nThe specific task that will be solved is called \"move_slider_left\", here you can find a [list of possible tasks](https://github.com/mees/calvin_env/blob/main/conf/tasks/new_playtable_tasks.yaml) that can be evaluated using CALVIN.\n\n",
"_____no_output_____"
]
],
[
[
"from gym import spaces\nfrom calvin_env.envs.play_table_env import PlayTableSimEnv\n\nclass SlideEnv(PlayTableSimEnv):\n def __init__(self,\n tasks: dict = {},\n **kwargs):\n super(SlideEnv, self).__init__(**kwargs)\n # For this example we will modify the observation to\n # only retrieve the end effector pose\n self.action_space = spaces.Box(low=-1, high=1, shape=(7,))\n self.observation_space = spaces.Box(low=-1, high=1, shape=(7,))\n # We can use the task utility to know if the task was executed correctly\n self.tasks = hydra.utils.instantiate(tasks)\n\n def reset(self):\n obs = super().reset()\n self.start_info = self.get_info()\n return obs\n\n def get_obs(self):\n \"\"\"Overwrite robot obs to only retrieve end effector position\"\"\"\n robot_obs, robot_info = self.robot.get_observation()\n return robot_obs[:7]\n\n def _success(self):\n \"\"\" Returns a boolean indicating if the task was performed correctly \"\"\"\n current_info = self.get_info()\n task_filter = [\"move_slider_left\"]\n task_info = self.tasks.get_task_info_for_set(self.start_info, current_info, task_filter)\n return 'move_slider_left' in task_info\n\n def _reward(self):\n \"\"\" Returns the reward function that will be used \n for the RL algorithm \"\"\"\n reward = int(self._success()) * 10\n r_info = {'reward': reward}\n return reward, r_info\n\n def _termination(self):\n \"\"\" Indicates if the robot has reached a terminal state \"\"\"\n success = self._success()\n done = success\n d_info = {'success': success} \n return done, d_info\n\n def step(self, action):\n \"\"\" Performing a relative action in the environment\n input:\n action: 7 tuple containing\n Position x, y, z. \n Angle in rad x, y, z. \n Gripper action\n each value in range (-1, 1)\n output:\n observation, reward, done info\n \"\"\"\n # Transform gripper action to discrete space\n env_action = action.copy()\n env_action[-1] = (int(action[-1] >= 0) * 2) - 1\n self.robot.apply_action(env_action)\n for i in range(self.action_repeat):\n self.p.stepSimulation(physicsClientId=self.cid)\n obs = self.get_obs()\n info = self.get_info()\n reward, r_info = self._reward()\n done, d_info = self._termination()\n info.update(r_info)\n info.update(d_info)\n return obs, reward, done, info",
"_____no_output_____"
]
],
[
[
"# Training an RL agent\nAfter generating the wrapper training a reinforcement learning agent is straightforward, for this example we will use stable baselines 3 agents",
"_____no_output_____"
]
],
[
[
"!pip3 install stable_baselines3",
"_____no_output_____"
]
],
[
[
"To train the agent we create an instance of our new environment and send it to the stable baselines agent to learn a policy.\n\n\n> Note: the example uses Soft Actor Critic (SAC) which is one of the state of the art algorithm for off-policy RL.\n\n",
"_____no_output_____"
]
],
[
[
"import gym\nimport numpy as np\nfrom stable_baselines3 import SAC\n\nnew_env_cfg = {**cfg.env}\nnew_env_cfg[\"tasks\"] = cfg.tasks\nnew_env_cfg.pop('_target_', None)\nnew_env_cfg.pop('_recursive_', None)\nenv = SlideEnv(**new_env_cfg)\nmodel = SAC(\"MlpPolicy\", env, verbose=1)\nmodel.learn(total_timesteps=10000, log_interval=4)\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
d081e380f25a07b4b9773536fbeecedfa849d52f | 236,440 | ipynb | Jupyter Notebook | notebooks/weather_energy_combine.ipynb | Cpizzle1/Texas_energy_use_weather_proj | 9fd97ebdd76846853b0dfda807c16ff4991a5848 | [
"MIT"
] | null | null | null | notebooks/weather_energy_combine.ipynb | Cpizzle1/Texas_energy_use_weather_proj | 9fd97ebdd76846853b0dfda807c16ff4991a5848 | [
"MIT"
] | null | null | null | notebooks/weather_energy_combine.ipynb | Cpizzle1/Texas_energy_use_weather_proj | 9fd97ebdd76846853b0dfda807c16ff4991a5848 | [
"MIT"
] | null | null | null | 52.647517 | 39,656 | 0.445305 | [
[
[
"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.style.use('ggplot')\nimport seaborn as sbn\nimport scipy.stats as stats\nfrom pandas.plotting import scatter_matrix\nimport statsmodels.api as sm\nimport datetime as dt\nimport pandasql as ps",
"_____no_output_____"
],
[
"data = pd.read_csv('~/Downloads/EIA930_BALANCE_2020_Jan_Jun.csv')\ndata_2 = pd.read_csv('~/Downloads/EIA930_BALANCE_2020_Jul_Dec.csv')",
"/Users/cp/opt/anaconda3/lib/python3.7/site-packages/IPython/core/interactiveshell.py:3147: DtypeWarning: Columns (11,14,15,16,17,19,20,21) have mixed types.Specify dtype option on import or set low_memory=False.\n interactivity=interactivity, compiler=compiler, result=result)\n/Users/cp/opt/anaconda3/lib/python3.7/site-packages/IPython/core/interactiveshell.py:3147: DtypeWarning: Columns (11,14,16,17,19,20,21) have mixed types.Specify dtype option on import or set low_memory=False.\n interactivity=interactivity, compiler=compiler, result=result)\n"
],
[
"def change_cols_to_floats(dataframe,lst):\n \n for i in lst:\n dataframe[i] = dataframe[i].str.replace(',', '')\n dataframe[i] = dataframe[i].astype(float)\n return dataframe\ndef make_date_time_col(df):\n df['Hour Number'] = df_total['Hour Number'].replace(24, 0)\n df['Hour Number'] = df_total['Hour Number'].replace(25, 0)\n df['Data Date']= df['Data Date'].astype(str)\n df['Hour Number'] = df['Hour Number'].astype(str)\n df['New_datetime'] = df['Data Date'].map(str) + \" \" + df['Hour Number']\n df['Hour Number'] = df['Hour Number'].astype(int)\n \n return df\n\ndef make_hourly_demand_means(df,lst):\n d = {}\n for i in lst:\n filt =df['Hour Number']==i\n d[i] = df.loc[filt]['Demand (MW)'].mean()\n return d\n\ndef graph_maker_for_energy_type_by_hour(df,column, lst = np.arange(0,24)):\n \n d= {}\n for i in lst:\n filt =df['Hour Number']==i\n hour_avg = df.loc[filt][column].mean()\n d[i]=hour_avg\n x = d.keys()\n y = d.values()\n fig, ax =plt.subplots(figsize = (8,8))\n ax.plot(x, y)\n ax.set_title(column)\n ax.set_xlabel('Hours in Day')\n ax.set_xticks(lst)\n \n \n plt.show()",
"_____no_output_____"
],
[
"lst_cols = ['Demand (MW)','Net Generation (MW) from Natural Gas', 'Net Generation (MW) from Nuclear','Net Generation (MW) from All Petroleum Products','Net Generation (MW) from Hydropower and Pumped Storage', 'Net Generation (MW) from Solar', 'Net Generation (MW) from Wind', 'Net Generation (MW) from Other Fuel Sources','Net Generation (MW)','Demand Forecast (MW)', 'Total Interchange (MW)', 'Net Generation (MW) (Adjusted)','Net Generation (MW) from Coal','Sum(Valid DIBAs) (MW)','Demand (MW) (Imputed)', 'Net Generation (MW) (Imputed)','Demand (MW) (Adjusted)']\ndata_convert = change_cols_to_floats(data, lst_cols)\ndata_2_convert = change_cols_to_floats(data_2, lst_cols)",
"_____no_output_____"
],
[
"lst_data = [data_convert,data_2_convert]\ndf_total = pd.concat(lst_data)",
"_____no_output_____"
],
[
"make_date_time_col(df_total)",
"_____no_output_____"
],
[
"df_total['New_datetime']= df_total['New_datetime'].apply(lambda x:f'{x}:00:00')",
"_____no_output_____"
],
[
"df_total['New_datetime'] = pd.to_datetime(df_total['New_datetime'],infer_datetime_format=True, format ='%m/%d/%Y %H')",
"_____no_output_____"
],
[
"df_total['Demand Delta'] = df_total['Demand Forecast (MW)']- df_total['Demand (MW)']",
"_____no_output_____"
],
[
"df_total['Net Generation Delta'] = df_total['Net Generation (MW)']- df_total['Demand (MW)']",
"_____no_output_____"
],
[
"lst_hours = np.arange(0,24) \n\n",
"_____no_output_____"
],
[
"make_hourly_demand_means(df_total, lst_hours)",
"_____no_output_____"
],
[
"graph_maker_for_energy_type_by_hour(df_total,'Net Generation (MW) from Nuclear') ",
"_____no_output_____"
]
],
[
[
"# TEXAS ERCOT",
"_____no_output_____"
]
],
[
[
"filter_1 = df_total['Balancing Authority'] == 'ERCO'\ndf_texas = df_total[filter_1]\ndf_texas",
"_____no_output_____"
],
[
"catagories_lst = ['Demand Forecast (MW)''Net Generation (MW) (Imputed)',\n 'Demand (MW) (Adjusted)', 'Net Generation (MW) (Adjusted)',\n 'Net Generation (MW) from Coal', 'Net Generation (MW) from Natural Gas',\n 'Net Generation (MW) from Nuclear',\n 'Net Generation (MW) from All Petroleum Products',\n 'Net Generation (MW) from Hydropower and Pumped Storage',\n 'Net Generation (MW) from Solar', 'Net Generation (MW) from Wind','Demand Delta', 'Net Generation Delta']",
"_____no_output_____"
],
[
"del df_texas['UTC Time at End of Hour']\ndel df_texas['Balancing Authority']\ndel df_texas['Net Generation (MW) (Imputed)']\ndel df_texas['Demand (MW) (Imputed)']\ndel df_texas['Net Generation (MW) from All Petroleum Products']\ndel df_texas['Net Generation (MW) from Unknown Fuel Sources']\ndel df_texas['Data Date']\ndel df_texas['Hour Number']\ndel df_texas['Local Time at End of Hour']\ndf_texas",
"_____no_output_____"
],
[
"df_texas.info()",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 8784 entries, 66924 to 70668\nData columns (total 20 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Data Date 8784 non-null object \n 1 Hour Number 8784 non-null int64 \n 2 Local Time at End of Hour 8784 non-null object \n 3 Demand Forecast (MW) 8784 non-null float64 \n 4 Demand (MW) 8784 non-null float64 \n 5 Net Generation (MW) 8784 non-null float64 \n 6 Total Interchange (MW) 8784 non-null float64 \n 7 Sum(Valid DIBAs) (MW) 8784 non-null float64 \n 8 Demand (MW) (Adjusted) 8784 non-null float64 \n 9 Net Generation (MW) (Adjusted) 8784 non-null float64 \n 10 Net Generation (MW) from Coal 8784 non-null float64 \n 11 Net Generation (MW) from Natural Gas 8784 non-null float64 \n 12 Net Generation (MW) from Nuclear 8784 non-null float64 \n 13 Net Generation (MW) from Hydropower and Pumped Storage 8784 non-null float64 \n 14 Net Generation (MW) from Solar 8784 non-null float64 \n 15 Net Generation (MW) from Wind 8784 non-null float64 \n 16 Net Generation (MW) from Other Fuel Sources 8784 non-null float64 \n 17 New_datetime 8784 non-null datetime64[ns]\n 18 Demand Delta 8784 non-null float64 \n 19 Net Generation Delta 8784 non-null float64 \ndtypes: datetime64[ns](1), float64(16), int64(1), object(2)\nmemory usage: 1.4+ MB\n"
],
[
"df_texas\n",
"_____no_output_____"
],
[
"df_texas.to_csv (r'/Users/cp/Desktop/capstone2/DF_TEXAS_FINAL_ENERGY_cleanv1.csv', index = False, header=True)",
"_____no_output_____"
],
[
"df_dallas =pd.read_csv('/Users/cp/Desktop/capstone2/DALLASV1_FINAL_WEATHER.csv')",
"_____no_output_____"
],
[
"df_texas.info()",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 8784 entries, 66924 to 70668\nData columns (total 17 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Demand Forecast (MW) 8784 non-null float64 \n 1 Demand (MW) 8784 non-null float64 \n 2 Net Generation (MW) 8784 non-null float64 \n 3 Total Interchange (MW) 8784 non-null float64 \n 4 Sum(Valid DIBAs) (MW) 8784 non-null float64 \n 5 Demand (MW) (Adjusted) 8784 non-null float64 \n 6 Net Generation (MW) (Adjusted) 8784 non-null float64 \n 7 Net Generation (MW) from Coal 8784 non-null float64 \n 8 Net Generation (MW) from Natural Gas 8784 non-null float64 \n 9 Net Generation (MW) from Nuclear 8784 non-null float64 \n 10 Net Generation (MW) from Hydropower and Pumped Storage 8784 non-null float64 \n 11 Net Generation (MW) from Solar 8784 non-null float64 \n 12 Net Generation (MW) from Wind 8784 non-null float64 \n 13 Net Generation (MW) from Other Fuel Sources 8784 non-null float64 \n 14 New_datetime 8784 non-null datetime64[ns]\n 15 Demand Delta 8784 non-null float64 \n 16 Net Generation Delta 8784 non-null float64 \ndtypes: datetime64[ns](1), float64(16)\nmemory usage: 1.2 MB\n"
],
[
"df_dallas['New_datetime'] = pd.to_datetime(df_dallas['New_datetime'],infer_datetime_format=True,format ='%m/%d/%Y %H')",
"_____no_output_____"
],
[
"Energy_Houston_weather=df_texas.merge(df_dallas, left_on ='New_datetime', right_on='New_datetime' )",
"_____no_output_____"
],
[
"Energy_Houston_weather",
"_____no_output_____"
],
[
"Energy_Houston_weather['Cloud_numerical'] = Energy_Houston_weather['cloud']",
"_____no_output_____"
],
[
"Energy_Houston_weather['cloud'].value_counts()",
"_____no_output_____"
],
[
"d1 = {\n 'Fair':0\n ,'Mostly Cloudy':2\n ,'Cloudy':1\n ,'Partly Cloudy':1\n ,'Light Rain':2\n , 'Light Drizzle':2\n ,'Rain':2\n ,'Light Rain with Thunder':2\n ,'Heavy T-Storm':2\n ,'Thunder':2\n , 'Heavy Rain':2\n ,'T-Storm':2\n , 'Fog':2\n , 'Mostly Cloudy / Windy':2\n , 'Cloudy / Windy':2\n , 'Haze':1\n , 'Fair / Windy':0\n , 'Partly Cloudy / Windy':1\n , 'Light Rain / Windy':2\n , 'Heavy T-Storm / Windy':2\n , 'Heavy Rain / Windy':2\n , 'Widespread Dust':1\n , 'Thunder and Hail':2\n ,'Thunder / Windy':2\n ,'Blowing Dust':1\n , 'Patches of Fog':1\n , 'Blowing Dust / Windy':1\n , 'Rain / Windy':2\n , 'Fog / Windy':2\n , 'Light Drizzle / Windy':2\n , 'Haze / Windy':1\n \n}",
"_____no_output_____"
],
[
"Energy_Houston_weather['Cloud_numerical'].replace(d1, inplace= True)\nEnergy_Houston_weather['Cloud_numerical']",
"_____no_output_____"
],
[
"# Energy_Houston_weather.replace({'Cloud_numerical':d1})",
"_____no_output_____"
],
[
"Energy_Houston_weather.info()",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 9328 entries, 0 to 9327\nData columns (total 28 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Demand Forecast (MW) 9328 non-null float64 \n 1 Demand (MW) 9328 non-null float64 \n 2 Net Generation (MW) 9328 non-null float64 \n 3 Total Interchange (MW) 9328 non-null float64 \n 4 Sum(Valid DIBAs) (MW) 9328 non-null float64 \n 5 Demand (MW) (Adjusted) 9328 non-null float64 \n 6 Net Generation (MW) (Adjusted) 9328 non-null float64 \n 7 Net Generation (MW) from Coal 9328 non-null float64 \n 8 Net Generation (MW) from Natural Gas 9328 non-null float64 \n 9 Net Generation (MW) from Nuclear 9328 non-null float64 \n 10 Net Generation (MW) from Hydropower and Pumped Storage 9328 non-null float64 \n 11 Net Generation (MW) from Solar 9328 non-null float64 \n 12 Net Generation (MW) from Wind 9328 non-null float64 \n 13 Net Generation (MW) from Other Fuel Sources 9328 non-null float64 \n 14 New_datetime 9328 non-null datetime64[ns]\n 15 Demand Delta 9328 non-null float64 \n 16 Net Generation Delta 9328 non-null float64 \n 17 temp 9328 non-null object \n 18 dew 9328 non-null object \n 19 humidity 9328 non-null object \n 20 wind_speed 9328 non-null object \n 21 pressure 9328 non-null object \n 22 precip 9328 non-null object \n 23 cloud 9327 non-null object \n 24 New_datetime2 9328 non-null object \n 25 time_rounded4 9328 non-null object \n 26 Cloud_numerical 9327 non-null float64 \n 27 humdity1 9328 non-null float64 \ndtypes: datetime64[ns](1), float64(18), object(9)\nmemory usage: 2.4+ MB\n"
],
[
"Energy_Houston_weather",
"_____no_output_____"
],
[
"Energy_Houston_weather['cloud'].value_counts()",
"_____no_output_____"
],
[
"Energy_Houston_weather.info()",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 9328 entries, 0 to 9327\nData columns (total 28 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Demand Forecast (MW) 9328 non-null float64 \n 1 Demand (MW) 9328 non-null float64 \n 2 Net Generation (MW) 9328 non-null float64 \n 3 Total Interchange (MW) 9328 non-null float64 \n 4 Sum(Valid DIBAs) (MW) 9328 non-null float64 \n 5 Demand (MW) (Adjusted) 9328 non-null float64 \n 6 Net Generation (MW) (Adjusted) 9328 non-null float64 \n 7 Net Generation (MW) from Coal 9328 non-null float64 \n 8 Net Generation (MW) from Natural Gas 9328 non-null float64 \n 9 Net Generation (MW) from Nuclear 9328 non-null float64 \n 10 Net Generation (MW) from Hydropower and Pumped Storage 9328 non-null float64 \n 11 Net Generation (MW) from Solar 9328 non-null float64 \n 12 Net Generation (MW) from Wind 9328 non-null float64 \n 13 Net Generation (MW) from Other Fuel Sources 9328 non-null float64 \n 14 New_datetime 9328 non-null datetime64[ns]\n 15 Demand Delta 9328 non-null float64 \n 16 Net Generation Delta 9328 non-null float64 \n 17 temp 9328 non-null object \n 18 dew 9328 non-null object \n 19 humidity 9328 non-null object \n 20 wind_speed 9328 non-null object \n 21 pressure 9328 non-null object \n 22 precip 9328 non-null object \n 23 cloud 9327 non-null object \n 24 New_datetime2 9328 non-null object \n 25 time_rounded4 9328 non-null object \n 26 Cloud_numerical 9327 non-null float64 \n 27 humdity1 9328 non-null float64 \ndtypes: datetime64[ns](1), float64(18), object(9)\nmemory usage: 2.4+ MB\n"
],
[
" Energy_Houston_weather.loc[:,'temp']",
"_____no_output_____"
],
[
"# Energy_Houston_weather['temp1'] =Energy_Houston_weather['temp'].str[:3]\nEnergy_Houston_weather['temp'].value_counts()",
"_____no_output_____"
],
[
"Energy_Houston_weather['humdity1'] =Energy_Houston_weather['humidity'].str[:2]\n# Energy_Houston_weather['humidity'].str[:3]",
"_____no_output_____"
],
[
"Energy_Houston_weather.info()",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 9328 entries, 0 to 9327\nData columns (total 28 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Demand Forecast (MW) 9328 non-null float64 \n 1 Demand (MW) 9328 non-null float64 \n 2 Net Generation (MW) 9328 non-null float64 \n 3 Total Interchange (MW) 9328 non-null float64 \n 4 Sum(Valid DIBAs) (MW) 9328 non-null float64 \n 5 Demand (MW) (Adjusted) 9328 non-null float64 \n 6 Net Generation (MW) (Adjusted) 9328 non-null float64 \n 7 Net Generation (MW) from Coal 9328 non-null float64 \n 8 Net Generation (MW) from Natural Gas 9328 non-null float64 \n 9 Net Generation (MW) from Nuclear 9328 non-null float64 \n 10 Net Generation (MW) from Hydropower and Pumped Storage 9328 non-null float64 \n 11 Net Generation (MW) from Solar 9328 non-null float64 \n 12 Net Generation (MW) from Wind 9328 non-null float64 \n 13 Net Generation (MW) from Other Fuel Sources 9328 non-null float64 \n 14 New_datetime 9328 non-null datetime64[ns]\n 15 Demand Delta 9328 non-null float64 \n 16 Net Generation Delta 9328 non-null float64 \n 17 temp 9328 non-null object \n 18 dew 9328 non-null object \n 19 humidity 9328 non-null object \n 20 wind_speed 9328 non-null object \n 21 pressure 9328 non-null object \n 22 precip 9328 non-null object \n 23 cloud 9327 non-null object \n 24 New_datetime2 9328 non-null object \n 25 time_rounded4 9328 non-null object \n 26 Cloud_numerical 9327 non-null float64 \n 27 humdity1 9328 non-null object \ndtypes: datetime64[ns](1), float64(17), object(10)\nmemory usage: 2.4+ MB\n"
],
[
"Energy_Houston_weather['humdity1'] = Energy_Houston_weather['humdity1'].astype(float)",
"_____no_output_____"
],
[
"Energy_Houston_weather.info()",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 9328 entries, 0 to 9327\nData columns (total 28 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Demand Forecast (MW) 9328 non-null float64 \n 1 Demand (MW) 9328 non-null float64 \n 2 Net Generation (MW) 9328 non-null float64 \n 3 Total Interchange (MW) 9328 non-null float64 \n 4 Sum(Valid DIBAs) (MW) 9328 non-null float64 \n 5 Demand (MW) (Adjusted) 9328 non-null float64 \n 6 Net Generation (MW) (Adjusted) 9328 non-null float64 \n 7 Net Generation (MW) from Coal 9328 non-null float64 \n 8 Net Generation (MW) from Natural Gas 9328 non-null float64 \n 9 Net Generation (MW) from Nuclear 9328 non-null float64 \n 10 Net Generation (MW) from Hydropower and Pumped Storage 9328 non-null float64 \n 11 Net Generation (MW) from Solar 9328 non-null float64 \n 12 Net Generation (MW) from Wind 9328 non-null float64 \n 13 Net Generation (MW) from Other Fuel Sources 9328 non-null float64 \n 14 New_datetime 9328 non-null datetime64[ns]\n 15 Demand Delta 9328 non-null float64 \n 16 Net Generation Delta 9328 non-null float64 \n 17 temp 9328 non-null object \n 18 dew 9328 non-null object \n 19 humidity 9328 non-null object \n 20 wind_speed 9328 non-null object \n 21 pressure 9328 non-null object \n 22 precip 9328 non-null object \n 23 cloud 9327 non-null object \n 24 New_datetime2 9328 non-null object \n 25 time_rounded4 9328 non-null object \n 26 Cloud_numerical 9327 non-null float64 \n 27 humdity1 9328 non-null float64 \ndtypes: datetime64[ns](1), float64(18), object(9)\nmemory usage: 2.4+ MB\n"
],
[
"Energy_Houston_weather['Cloud_numerical'] = Energy_Houston_weather['Cloud_numerical'].astype(float)",
"_____no_output_____"
],
[
"# Energy_Houston_weather[Energy_Houston_weather['Cloud_numerical']=='Cloudy']",
"_____no_output_____"
],
[
"Energy_Houston_weather.info()",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 9328 entries, 0 to 9327\nData columns (total 28 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Demand Forecast (MW) 9328 non-null float64 \n 1 Demand (MW) 9328 non-null float64 \n 2 Net Generation (MW) 9328 non-null float64 \n 3 Total Interchange (MW) 9328 non-null float64 \n 4 Sum(Valid DIBAs) (MW) 9328 non-null float64 \n 5 Demand (MW) (Adjusted) 9328 non-null float64 \n 6 Net Generation (MW) (Adjusted) 9328 non-null float64 \n 7 Net Generation (MW) from Coal 9328 non-null float64 \n 8 Net Generation (MW) from Natural Gas 9328 non-null float64 \n 9 Net Generation (MW) from Nuclear 9328 non-null float64 \n 10 Net Generation (MW) from Hydropower and Pumped Storage 9328 non-null float64 \n 11 Net Generation (MW) from Solar 9328 non-null float64 \n 12 Net Generation (MW) from Wind 9328 non-null float64 \n 13 Net Generation (MW) from Other Fuel Sources 9328 non-null float64 \n 14 New_datetime 9328 non-null datetime64[ns]\n 15 Demand Delta 9328 non-null float64 \n 16 Net Generation Delta 9328 non-null float64 \n 17 temp 9328 non-null object \n 18 dew 9328 non-null object \n 19 humidity 9328 non-null object \n 20 wind_speed 9328 non-null object \n 21 pressure 9328 non-null object \n 22 precip 9328 non-null object \n 23 cloud 9327 non-null object \n 24 New_datetime2 9328 non-null object \n 25 time_rounded4 9328 non-null object \n 26 Cloud_numerical 9327 non-null float64 \n 27 humdity1 9328 non-null float64 \ndtypes: datetime64[ns](1), float64(18), object(9)\nmemory usage: 2.4+ MB\n"
],
[
"# Energy_Houston_weather['humdity1'] =Energy_Houston_weather['humidity'].str[:2]\nEnergy_Houston_weather['precip1'] = Energy_Houston_weather['precip'].str[:2]",
"_____no_output_____"
],
[
"Energy_Houston_weather['precip1']= Energy_Houston_weather['precip1'].astype(float)",
"_____no_output_____"
],
[
"Energy_Houston_weather['pressure1'] = Energy_Houston_weather['pressure'].str[:5]\n# Energy_Houston_weather['pressure'].unique()",
"_____no_output_____"
],
[
"x =Energy_Houston_weather['pressure1']\nx.unique()",
"_____no_output_____"
],
[
"def column_convert_float(pd_series):\n lst = []\n for i in pd_series:\n lst1 = i.split('\\\\')\n \n lst.append(lst1[0])\n \n results = pd.Series(lst)\n return results \n ",
"_____no_output_____"
],
[
"def temp_column_convert_float2(pd_series):\n lst = []\n for string in pd_series:\n string = string.replace(u'\\xa0F','')\n \n lst.append(string)\n \n results = pd.Series(lst)\n return results ",
"_____no_output_____"
],
[
"temp2 = Energy_Houston_weather['temp']",
"_____no_output_____"
],
[
"temp2.unique()",
"_____no_output_____"
],
[
"timevar1 = temp_column_convert_float2(temp2)",
"_____no_output_____"
],
[
"timevar1.unique()",
"_____no_output_____"
],
[
"Energy_Houston_weather['temp1']= timevar1",
"_____no_output_____"
],
[
"Energy_Houston_weather['temp1']= Energy_Houston_weather['temp1'].astype(float)",
"_____no_output_____"
],
[
"Energy_Houston_weather['pressure1'].unique()",
"_____no_output_____"
],
[
"def press_column_convert_float2(pd_series):\n lst = []\n for string in pd_series:\n string = string.replace(u'\\xa0in','')\n if string == '0.00\\xa0':\n string = '0.00'\n lst.append(string)\n \n results = pd.Series(lst)\n# results2 = results.astype(float)\n return results",
"_____no_output_____"
],
[
"press1 = Energy_Houston_weather['pressure'] ",
"_____no_output_____"
],
[
"press1_convert = press_column_convert_float2(press1)",
"_____no_output_____"
],
[
"Energy_Houston_weather['pressure1'].unique()",
"_____no_output_____"
],
[
"filt = Energy_Houston_weather['pressure1'].str[:3] =='0.0'",
"_____no_output_____"
],
[
"press1[filt] = '0.00'",
"/Users/cp/opt/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:1: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n \"\"\"Entry point for launching an IPython kernel.\n"
],
[
"press1.unique()",
"_____no_output_____"
],
[
"press_series = press_column_convert_float2(press1)",
"_____no_output_____"
],
[
"press_series.unique()",
"_____no_output_____"
],
[
"Energy_Houston_weather['pressure1'] = press_series",
"_____no_output_____"
],
[
"Energy_Houston_weather['pressure1']= Energy_Houston_weather['pressure1'].astype(float)",
"_____no_output_____"
],
[
"Energy_Houston_weather.info()",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 9328 entries, 0 to 9327\nData columns (total 31 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Demand Forecast (MW) 9328 non-null float64 \n 1 Demand (MW) 9328 non-null float64 \n 2 Net Generation (MW) 9328 non-null float64 \n 3 Total Interchange (MW) 9328 non-null float64 \n 4 Sum(Valid DIBAs) (MW) 9328 non-null float64 \n 5 Demand (MW) (Adjusted) 9328 non-null float64 \n 6 Net Generation (MW) (Adjusted) 9328 non-null float64 \n 7 Net Generation (MW) from Coal 9328 non-null float64 \n 8 Net Generation (MW) from Natural Gas 9328 non-null float64 \n 9 Net Generation (MW) from Nuclear 9328 non-null float64 \n 10 Net Generation (MW) from Hydropower and Pumped Storage 9328 non-null float64 \n 11 Net Generation (MW) from Solar 9328 non-null float64 \n 12 Net Generation (MW) from Wind 9328 non-null float64 \n 13 Net Generation (MW) from Other Fuel Sources 9328 non-null float64 \n 14 New_datetime 9328 non-null datetime64[ns]\n 15 Demand Delta 9328 non-null float64 \n 16 Net Generation Delta 9328 non-null float64 \n 17 temp 9328 non-null object \n 18 dew 9328 non-null object \n 19 humidity 9328 non-null object \n 20 wind_speed 9328 non-null object \n 21 pressure 9328 non-null object \n 22 precip 9328 non-null object \n 23 cloud 9327 non-null object \n 24 New_datetime2 9328 non-null object \n 25 time_rounded4 9328 non-null object \n 26 Cloud_numerical 9327 non-null float64 \n 27 humdity1 9328 non-null float64 \n 28 precip1 9328 non-null float64 \n 29 pressure1 9328 non-null float64 \n 30 temp1 9328 non-null float64 \ndtypes: datetime64[ns](1), float64(21), object(9)\nmemory usage: 2.6+ MB\n"
],
[
"Energy_Houston_weather['wind_speed'].unique()",
"_____no_output_____"
],
[
"def wind_column_convert(pd_series):\n lst = []\n for string in pd_series:\n string = string.replace(u'\\xa0mph','')\n if string == '0.00\\xa0':\n string = '0.00'\n lst.append(string)\n \n results = pd.Series(lst)\n# results2 = results.astype(float)\n return results",
"_____no_output_____"
],
[
"wind1 = Energy_Houston_weather['wind_speed']",
"_____no_output_____"
],
[
"wind_convert = wind_column_convert(wind1)",
"_____no_output_____"
],
[
"wind_convert.unique()",
"_____no_output_____"
],
[
"Energy_Houston_weather['wind1'] = wind_convert",
"_____no_output_____"
],
[
"Energy_Houston_weather['wind1']= Energy_Houston_weather['wind1'].astype(float)",
"_____no_output_____"
],
[
"Energy_Houston_weather.info()",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 9328 entries, 0 to 9327\nData columns (total 32 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Demand Forecast (MW) 9328 non-null float64 \n 1 Demand (MW) 9328 non-null float64 \n 2 Net Generation (MW) 9328 non-null float64 \n 3 Total Interchange (MW) 9328 non-null float64 \n 4 Sum(Valid DIBAs) (MW) 9328 non-null float64 \n 5 Demand (MW) (Adjusted) 9328 non-null float64 \n 6 Net Generation (MW) (Adjusted) 9328 non-null float64 \n 7 Net Generation (MW) from Coal 9328 non-null float64 \n 8 Net Generation (MW) from Natural Gas 9328 non-null float64 \n 9 Net Generation (MW) from Nuclear 9328 non-null float64 \n 10 Net Generation (MW) from Hydropower and Pumped Storage 9328 non-null float64 \n 11 Net Generation (MW) from Solar 9328 non-null float64 \n 12 Net Generation (MW) from Wind 9328 non-null float64 \n 13 Net Generation (MW) from Other Fuel Sources 9328 non-null float64 \n 14 New_datetime 9328 non-null datetime64[ns]\n 15 Demand Delta 9328 non-null float64 \n 16 Net Generation Delta 9328 non-null float64 \n 17 temp 9328 non-null object \n 18 dew 9328 non-null object \n 19 humidity 9328 non-null object \n 20 wind_speed 9328 non-null object \n 21 pressure 9328 non-null object \n 22 precip 9328 non-null object \n 23 cloud 9327 non-null object \n 24 New_datetime2 9328 non-null object \n 25 time_rounded4 9328 non-null object \n 26 Cloud_numerical 9327 non-null float64 \n 27 humdity1 9328 non-null float64 \n 28 precip1 9328 non-null float64 \n 29 pressure1 9328 non-null float64 \n 30 temp1 9328 non-null float64 \n 31 wind1 9328 non-null float64 \ndtypes: datetime64[ns](1), float64(22), object(9)\nmemory usage: 2.7+ MB\n"
],
[
"Energy_Houston_weather['dew'].unique()",
"_____no_output_____"
],
[
"def dew_column_convert_float2(pd_series):\n lst = []\n for string in pd_series:\n string = string.replace(u'\\xa0F','')\n \n lst.append(string)\n \n results = pd.Series(lst)\n return results ",
"_____no_output_____"
],
[
"dew1 = Energy_Houston_weather['dew']",
"_____no_output_____"
],
[
"dew_convert = dew_column_convert_float2(dew1)",
"_____no_output_____"
],
[
"Energy_Houston_weather['dew1']= dew_convert",
"_____no_output_____"
],
[
"Energy_Houston_weather['dew1']= Energy_Houston_weather['dew1'].astype(float)",
"_____no_output_____"
],
[
"Energy_Houston_weather.info()",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 9328 entries, 0 to 9327\nData columns (total 33 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Demand Forecast (MW) 9328 non-null float64 \n 1 Demand (MW) 9328 non-null float64 \n 2 Net Generation (MW) 9328 non-null float64 \n 3 Total Interchange (MW) 9328 non-null float64 \n 4 Sum(Valid DIBAs) (MW) 9328 non-null float64 \n 5 Demand (MW) (Adjusted) 9328 non-null float64 \n 6 Net Generation (MW) (Adjusted) 9328 non-null float64 \n 7 Net Generation (MW) from Coal 9328 non-null float64 \n 8 Net Generation (MW) from Natural Gas 9328 non-null float64 \n 9 Net Generation (MW) from Nuclear 9328 non-null float64 \n 10 Net Generation (MW) from Hydropower and Pumped Storage 9328 non-null float64 \n 11 Net Generation (MW) from Solar 9328 non-null float64 \n 12 Net Generation (MW) from Wind 9328 non-null float64 \n 13 Net Generation (MW) from Other Fuel Sources 9328 non-null float64 \n 14 New_datetime 9328 non-null datetime64[ns]\n 15 Demand Delta 9328 non-null float64 \n 16 Net Generation Delta 9328 non-null float64 \n 17 temp 9328 non-null object \n 18 dew 9328 non-null object \n 19 humidity 9328 non-null object \n 20 wind_speed 9328 non-null object \n 21 pressure 9328 non-null object \n 22 precip 9328 non-null object \n 23 cloud 9327 non-null object \n 24 New_datetime2 9328 non-null object \n 25 time_rounded4 9328 non-null object \n 26 Cloud_numerical 9327 non-null float64 \n 27 humdity1 9328 non-null float64 \n 28 precip1 9328 non-null float64 \n 29 pressure1 9328 non-null float64 \n 30 temp1 9328 non-null float64 \n 31 wind1 9328 non-null float64 \n 32 dew1 9328 non-null float64 \ndtypes: datetime64[ns](1), float64(23), object(9)\nmemory usage: 2.7+ MB\n"
],
[
"Energy_Houston_weather.to_csv (r'/Users/cp/Desktop/capstone2/WEATHER_CONVERTED&ENERGY_cleanv1.csv', index = False, header=True)\n",
"_____no_output_____"
]
]
] | [
"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",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d081f2f0e60864d6fd04756891b2acf93c6b471e | 7,702 | ipynb | Jupyter Notebook | _notebooks/2021-04-29-phonetic-comparison.ipynb | jimregan/notes | 24e374d326b4e96b7d31d08a808f9f19fe473e76 | [
"Apache-2.0"
] | 1 | 2021-08-25T08:08:45.000Z | 2021-08-25T08:08:45.000Z | _notebooks/2021-04-29-phonetic-comparison.ipynb | jimregan/notes | 24e374d326b4e96b7d31d08a808f9f19fe473e76 | [
"Apache-2.0"
] | null | null | null | _notebooks/2021-04-29-phonetic-comparison.ipynb | jimregan/notes | 24e374d326b4e96b7d31d08a808f9f19fe473e76 | [
"Apache-2.0"
] | null | null | null | 23.129129 | 298 | 0.507141 | [
[
[
"# Polish phonetic comparison\n\n> \"Transcript matching for E2E ASR with phonetic post-processing\"\n\n- toc: false\n- branch: master\n- hidden: true\n- categories: [asr, polish, phonetic, todo]\n",
"_____no_output_____"
]
],
[
[
"from difflib import SequenceMatcher\nimport icu",
"_____no_output_____"
],
[
"plipa = icu.Transliterator.createInstance('pl-pl_FONIPA')",
"_____no_output_____"
]
],
[
[
"The errors in E2E models are quite often phonetic confusions, so we do the opposite of traditional ASR and generate the phonetic representation from the output as a basis for comparison.",
"_____no_output_____"
]
],
[
[
"def phonetic_check(word1, word2, ignore_spaces=False):\n \"\"\"Uses ICU's IPA transliteration to check if words are the same\"\"\"\n tl1 = plipa.transliterate(word1) if not ignore_spaces else plipa.transliterate(word1.replace(' ', ''))\n tl2 = plipa.transliterate(word2) if not ignore_spaces else plipa.transliterate(word2.replace(' ', ''))\n return tl1 == tl2",
"_____no_output_____"
],
[
"phonetic_check(\"jórz\", \"jusz\", False)",
"_____no_output_____"
]
],
[
[
"The Polish `y` is phonetically a raised schwa; like the schwa in English, it's often deleted in fast speech. This function returns true if the only differences between the first word and the second is are deletions of `y`, except at the end of the word (which is typically the plural ending).",
"_____no_output_____"
]
],
[
[
"def no_igrek(word1, word2):\n \"\"\"Checks if a word-internal y has been deleted\"\"\"\n sm = SequenceMatcher(None, word1, word2)\n for oc in sm.get_opcodes():\n if oc[0] == 'equal':\n continue\n elif oc[0] == 'delete' and word1[oc[1]:oc[2]] != 'y':\n return False\n elif oc[0] == 'delete' and word1[oc[1]:oc[2]] == 'y' and oc[2] == len(word1):\n return False\n elif oc[0] == 'insert' or oc[0] == 'replace':\n return False\n return True",
"_____no_output_____"
],
[
"no_igrek('uniwersytet', 'uniwerstet')",
"_____no_output_____"
],
[
"no_igrek('uniwerstety', 'uniwerstet')",
"_____no_output_____"
],
[
"phonetic_alternatives = [ ['u', 'ó'], ['rz', 'ż'] ]\ndef reverse_alts(phonlist):\n return [ [i[1], i[0]] for i in phonlist ]\n",
"_____no_output_____"
],
[
"sm = SequenceMatcher(None, \"już\", \"jurz\")\nfor oc in sm.get_opcodes():\n print(oc)",
"('equal', 0, 2, 0, 2)\n('replace', 2, 3, 2, 4)\n"
]
],
[
[
"Reads a `CTM`-like file, returning a list of lists containing the filename, start time, end time, and word.",
"_____no_output_____"
]
],
[
[
"def read_ctmish(filename):\n output = []\n with open(filename, 'r') as f:\n for line in f.readlines():\n pieces = line.strip().split(' ')\n if len(pieces) <= 4:\n continue\n for piece in pieces[4:]:\n output.append([pieces[0], pieces[2], pieces[3], piece])\n return output",
"_____no_output_____"
]
],
[
[
"Returns the contents of a plain text file as a list of lists containing the line number and the word, for use in locating mismatches",
"_____no_output_____"
]
],
[
[
"def read_text(filename):\n output = []\n counter = 0\n with open(filename, 'r') as f:\n for line in f.readlines():\n counter += 1\n for word in line.strip().split(' ')\n output.append([counter, word])\n return output",
"_____no_output_____"
],
[
"ctmish = read_ctmish(\"/mnt/c/Users/Jim O\\'Regan/git/notes/PlgU9JyTLPE.ctm\")",
"_____no_output_____"
],
[
"rec_words = [i[3] for i in ctmish]",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
d0821198d1af6b76d9af2eb542481266e0c1bd89 | 8,051 | ipynb | Jupyter Notebook | HW9/HW9-sunspots.ipynb | mtlam/ASTP-720_F2020 | 788acf1660beb918dbea138b294942bf15f9cd42 | [
"BSD-3-Clause"
] | null | null | null | HW9/HW9-sunspots.ipynb | mtlam/ASTP-720_F2020 | 788acf1660beb918dbea138b294942bf15f9cd42 | [
"BSD-3-Clause"
] | null | null | null | HW9/HW9-sunspots.ipynb | mtlam/ASTP-720_F2020 | 788acf1660beb918dbea138b294942bf15f9cd42 | [
"BSD-3-Clause"
] | 1 | 2022-01-25T05:15:30.000Z | 2022-01-25T05:15:30.000Z | 28.249123 | 511 | 0.552478 | [
[
[
"# HW9: Forecasting Solar Cycles\n\nBelow is the notebook associated with HW\\#9. You can run the notebook in two modes. If you have the `emcee` and `corner` packages installed on your machine, along with the data files, just keep the following variable set to `False`. If you are running it in a Google colab notebook, set it to `True` so that it will grab the packages and files. Remember that the Google colab environment will shutdown after ~1 hour of inactivity, so you'll need to keep interacting with it or else will lose the data.\n\nA script version of this file will also be provided to you, but you cannot use this in a Google colab environment",
"_____no_output_____"
]
],
[
[
"COLAB = False",
"_____no_output_____"
],
[
"if COLAB:\n # Install emcee package\n !pip install emcee\n # Install corner package\n !pip install corner \n # Grab sunspot data file\n !wget -O SN_m_tot_V2.0.txt https://raw.githubusercontent.com/mtlam/ASTP-720_F2020/master/HW9/SN_m_tot_V2.0.txt",
"_____no_output_____"
],
[
"import numpy as np\nfrom matplotlib.pyplot import *\nfrom matplotlib import rc\nimport emcee\nimport corner\n%matplotlib inline\n\n# Make more readable plots\nrc('font',**{'size':14})\nrc('xtick',**{'labelsize':16})\nrc('ytick',**{'labelsize':16})\nrc('axes',**{'labelsize':18,'titlesize':18})",
"_____no_output_____"
]
],
[
[
"## Define the (log-)priors\n\nHere, the function should take a vector of parameters, `theta`, and return `0.0` if the it is in the prior range and `-np.inf` if it is outside. This is equivalent to a uniform prior over the parameters. You can, of course, define a different set of priors if you so choose!",
"_____no_output_____"
]
],
[
[
"def lnprior(theta):\n \"\"\"\n Parameters\n ----------\n theta : np.ndarray\n Array of parameters.\n \n Returns\n -------\n Value of log-prior. \n \"\"\"\n pass",
"_____no_output_____"
]
],
[
[
"## Define the (log-)likelihood",
"_____no_output_____"
]
],
[
[
"def lnlike(theta, data):\n \"\"\"\n Parameters\n ----------\n theta : np.ndarray\n Array of parameters.\n data : np.ndarray\n \n \n Returns\n -------\n Value of log-likelihood \n \"\"\"\n residuals = None\n pass",
"_____no_output_____"
]
],
[
[
"## Define total (log-)probability\n\nNo need to change this if the other two functions work as described.",
"_____no_output_____"
]
],
[
[
"def lnprob(theta, data):\n lp = lnprior(theta)\n if not np.isfinite(lp):\n return -np.inf\n return lp + lnlike(theta, data)",
"_____no_output_____"
]
],
[
[
"## Set up the MCMC sampler here",
"_____no_output_____"
]
],
[
[
"# Number of walkers to search through parameter space\nnwalkers = 10\n# Number of iterations to run the sampler for\nniter = 50000\n# Initial guess of parameters. For example, if you had a model like\n# s(t) = a + bt + ct^2\n# and your initial guesses for a, b, and c were 5, 3, and 8, respectively, then you would write\n# pinit = np.array([5, 3, 8])\n# Make sure the guesses are allowed inside your lnprior range!\npinit = np.array([])\n# Number of dimensions of parameter space\nndim = len(pinit)\n# Perturbed set of initial guesses. Have your walkers all start out at\n# *slightly* different starting values\np0 = [pinit + 1e-4*pinit*np.random.randn(ndim) for i in range(nwalkers)]",
"_____no_output_____"
]
],
[
[
"## Load the data, plot to show",
"_____no_output_____"
]
],
[
[
"# Data: decimal year, sunspot number\ndecyear, ssn = np.loadtxt(\"SN_m_tot_V2.0.txt\", unpack=True, usecols=(2, 3))\nplot(decyear, ssn, 'k.')\nxlabel('Year')\nylabel('Sunspot Number')\nshow()",
"_____no_output_____"
]
],
[
[
"## Run the sampler",
"_____no_output_____"
]
],
[
[
"# Number of CPU threads to use. Reduce if you are running on your own machine\n# and don't want to use too many cores\nnthreads = 4\n# Set up the sampler\nsampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=(ssn,), threads=nthreads)\n# Run the sampler. May take a while! You might consider changing the \n# number of iterations to a much smaller value when you're testing. Or use a \n# larger value when you're trying to get your final results out!\nsampler.run_mcmc(p0, niter, progress=True)",
"_____no_output_____"
]
],
[
[
"## Get the samples in the appropriate format, with a burn value",
"_____no_output_____"
]
],
[
[
"# Burn-in value = 1/4th the number of iterations. Feel free to change!\nburn = int(0.25*niter)\n# Reshape the chains for input to corner.corner()\nsamples = sampler.chain[:, burn:, :].reshape((-1, ndim))",
"_____no_output_____"
]
],
[
[
"## Make a corner plot\n\nYou should feel free to adjust the parameters to the `corner` function. You **should** also add labels, which should just be a list of the names of the parameters. So, if you had two parameters, $\\phi_1$ and $\\phi_2$, then you could write:\n\n```\nlabels = [r\"$\\phi_1$\", r\"$\\phi_2$\"]\n```\n\nand that will make the appropriate label in LaTeX (if the distribution is installed correctly) for the two 1D posteriors of the corner plot.",
"_____no_output_____"
]
],
[
[
"fig = corner.corner(samples, bins=50, color='C0', smooth=0.5, plot_datapoints=False, plot_density=True, \\\n plot_contours=True, fill_contour=False, show_titles=True)#, labels=labels)\nfig.savefig(\"corner.png\")\nshow()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
d082211f7990dfa65ee5c7475413d91837e26459 | 187,225 | ipynb | Jupyter Notebook | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer | 2994760222e1cae4c30ff3fc83d671b4bfc78780 | [
"Apache-2.0"
] | 21 | 2017-07-22T10:08:03.000Z | 2022-01-11T08:53:14.000Z | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer | 2994760222e1cae4c30ff3fc83d671b4bfc78780 | [
"Apache-2.0"
] | 127 | 2017-07-22T10:19:45.000Z | 2021-11-04T01:23:43.000Z | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer | 2994760222e1cae4c30ff3fc83d671b4bfc78780 | [
"Apache-2.0"
] | 18 | 2017-04-27T17:02:06.000Z | 2021-07-25T18:13:56.000Z | 41.522511 | 1,779 | 0.497823 | [
[
[
"from biothings_explorer.user_query_dispatcher import FindConnection\nfrom biothings_explorer.hint import Hint\nht = Hint()\n",
"_____no_output_____"
],
[
"ace2 = ht.query(\"ACE2\")['Gene'][0]",
"_____no_output_____"
],
[
"fc = FindConnection(input_obj=ace2, output_obj='ChemicalSubstance', intermediate_nodes=['BiologicalEntity'])\nfc.connect(verbose=True)",
"==========\n========== QUERY PARAMETER SUMMARY ==========\n==========\n\nBTE will find paths that join 'ACE2' and 'ChemicalSubstance'. Paths will have 1 intermediate node.\n\nIntermediate node #1 will have these type constraints: BiologicalEntity\n\n\n\n========== QUERY #1 -- fetch all Biological Entities linked to ACE2 ==========\n==========\n\n==== Step #1: Query path planning ====\n\nBecause ACE2 is of type 'Gene', BTE will query our meta-KG for APIs that can take 'Gene' as input and 'None' as output\n\nBTE found 18 apis:\n\nAPI 1. biolink_gene2disease(1 API call)\nAPI 2. biolink_geneinteraction(1 API call)\nAPI 3. biolink_gene2anatomy(1 API call)\nAPI 4. mygene.info(4 API calls)\nAPI 5. DISEASES(1 API call)\nAPI 6. mychem.info(3 API calls)\nAPI 7. mydisease.info(1 API call)\nAPI 8. myvariant.info(1 API call)\nAPI 9. robokop_gene2chemical(1 API call)\nAPI 10. ebigene2phenotype(1 API call)\nAPI 11. pfocr(1 API call)\nAPI 12. robokop_gene2genefamily(1 API call)\nAPI 13. semmedgene(11 API calls)\nAPI 14. ctd_gene2disease(1 API call)\nAPI 15. opentarget(1 API call)\nAPI 16. dgidb_gene2chemical(1 API call)\nAPI 17. biolink_gene2phenotype(1 API call)\nAPI 18. semmeddisease(7 API calls)\n\n\n==== Step #2: Query path execution ====\nNOTE: API requests are dispatched in parallel, so the list of APIs below is ordered by query time.\n\nAPI 4.1: http://mygene.info/v3/query (POST \"q=ENSG00000130234&scopes=ensembl.gene&fields=ensembl.protein,ensembl.transcript,uniprot.Swiss-Prot&species=human&size=100\")\nAPI 6.1: http://mychem.info/v1/query (POST \"q=ACE2&scopes=drugbank.enzymes.gene_name&fields=drugbank.id&species=human&size=100\")\nAPI 4.2: http://mygene.info/v3/query (POST \"q=59272&scopes=entrezgene&fields=pantherdb.ortholog.Ensembl,go.CC.id,pantherdb.ortholog.TAIR,pantherdb.ortholog.FlyBase,go.MF.id,pantherdb.ortholog.PomBase,pantherdb.ortholog.dictyBase,pantherdb.ortholog.ZFIN,pantherdb.ortholog.HGNC,pantherdb.ortholog.RGD,pantherdb.ortholog.SGD,pathway.wikipathways.id,pathway.reactome.id,go.BP.id,pantherdb.ortholog.MGI&species=human&size=100\")\nAPI 6.3: http://mychem.info/v1/query (POST \"q=ACE2&scopes=drugcentral.bioactivity.uniprot.gene_symbol&fields=chembl.molecule_chembl_id&species=human&size=100\")\nAPI 6.2: http://mychem.info/v1/query (POST \"q=ACE2&scopes=drugbank.targets.gene_name&fields=drugbank.id&species=human&size=100\")\nAPI 4.4: http://mygene.info/v3/query (POST \"q=13557&scopes=pantherdb.ortholog.HGNC&fields=entrezgene&species=human&size=100\")\nAPI 4.3: http://mygene.info/v3/query (POST \"q=ENSG00000130234&scopes=pantherdb.ortholog.Ensembl&fields=entrezgene&species=human&size=100\")\nAPI 7.1: http://mydisease.info/v1/query (POST \"q=59272&scopes=disgenet.genes_related_to_disease.gene_id&fields=mondo.xrefs.umls,disgenet.xrefs.umls&species=human&size=100\")\nAPI 16.1: http://www.dgidb.org/api/v2/interactions.json?genes=ACE2\nAPI 15.1: https://platform-api.opentargets.io/v3/platform/public/evidence/filter?target=ENSG00000130234&datasource=chembl&size=15&fields=drug\nAPI 8.1: http://myvariant.info/v1/query (POST \"q=59272&scopes=dbsnp.gene.geneid&fields=dbsnp.rsid&species=human&size=100\")\nAPI 18.3: http://pending.biothings.io/semmed/query (POST \"q=C1422064&scopes=AFFECTS_reverse.gene.umls&fields=umls&species=human&size=100\")\nAPI 18.4: http://pending.biothings.io/semmed/query (POST \"q=C1422064&scopes=AFFECTS_reverse.protein.umls&fields=umls&species=human&size=100\")\nAPI 18.2: http://pending.biothings.io/semmed/query (POST \"q=C1422064&scopes=AFFECTS.protein.umls&fields=umls&species=human&size=100\")\nAPI 18.1: http://pending.biothings.io/semmed/query (POST \"q=C1422064&scopes=AFFECTS.gene.umls&fields=umls&species=human&size=100\")\nAPI 3.1: https://api.monarchinitiative.org/api/bioentity/gene/NCBIGene:59272/anatomy?rows=100\n0, message='Attempt to decode JSON with unexpected mimetype: text/html'\nbiolink_gene2anatomy failed\nAPI 17.1: https://api.monarchinitiative.org/api/bioentity/gene/NCBIGene:59272/phenotypes?rows=100\n0, message='Attempt to decode JSON with unexpected mimetype: text/html'\nbiolink_gene2phenotype failed\nAPI 2.1: https://api.monarchinitiative.org/api/bioentity/gene/NCBIGene:59272/interactions?rows=100\n0, message='Attempt to decode JSON with unexpected mimetype: text/html'\nbiolink_geneinteraction failed\nAPI 1.1: https://api.monarchinitiative.org/api/bioentity/gene/NCBIGene:59272/diseases?rows=100\n0, message='Attempt to decode JSON with unexpected mimetype: text/html'\nbiolink_gene2disease failed\nAPI 18.6: http://pending.biothings.io/semmed/query (POST \"q=C1422064&scopes=ASSOCIATED_WITH_reverse.gene.umls&fields=umls&species=human&size=100\")\nAPI 18.7: http://pending.biothings.io/semmed/query (POST \"q=C1422064&scopes=CAUSES_reverse.gene.umls&fields=umls&species=human&size=100\")\nAPI 18.5: http://pending.biothings.io/semmed/query (POST \"q=C1422064&scopes=ASSOCIATED_WITH.gene.umls&fields=umls&species=human&size=100\")\nAPI 13.3: https://pending.biothings.io/semmedgene/query (POST \"q=C1422064&scopes=associated_with.gene.umls&fields=umls&species=human&size=100\")\nAPI 13.5: https://pending.biothings.io/semmedgene/query (POST \"q=C1422064&scopes=disrupts.protein.umls&fields=umls&species=human&size=100\")\nAPI 13.2: https://pending.biothings.io/semmedgene/query (POST \"q=C1422064&scopes=affects.protein.umls&fields=umls&species=human&size=100\")\nAPI 13.4: https://pending.biothings.io/semmedgene/query (POST \"q=C1422064&scopes=disrupts.gene.umls&fields=umls&species=human&size=100\")\nAPI 13.6: https://pending.biothings.io/semmedgene/query (POST \"q=C1422064&scopes=inhibits.gene.umls&fields=umls&species=human&size=100\")\nAPI 13.9: https://pending.biothings.io/semmedgene/query (POST \"q=C1422064&scopes=interacts_with.protein.umls&fields=umls&species=human&size=100\")\nAPI 13.7: https://pending.biothings.io/semmedgene/query (POST \"q=C1422064&scopes=inhibits.protein.umls&fields=umls&species=human&size=100\")\nAPI 13.1: https://pending.biothings.io/semmedgene/query (POST \"q=C1422064&scopes=affects.gene.umls&fields=umls&species=human&size=100\")\nAPI 13.8: https://pending.biothings.io/semmedgene/query (POST \"q=C1422064&scopes=interacts_with.gene.umls&fields=umls&species=human&size=100\")\nAPI 13.11: https://pending.biothings.io/semmedgene/query (POST \"q=C1422064&scopes=umls&fields=stimulates.protein.umls,disrupts.cell.umls,affects.phenotypic_feature.umls,affects.anatomical_entity.umls,inhibits.biological_process_or_activity.umls,interacts_with.gene.umls,associated_with.anatomical_entity.umls,associated_with.cell.umls,affects.cell_component.umls,inhibits.cell_component.umls,associated_with_reverse.anatomical_entity.umls,affects_reverse.cell_component.umls,affects_reverse.cell.umls,stimulates.anatomical_entity.umls,affects.cell.umls,inhibits.phenotypic_feature.umls,interacts_with.protein.umls,disrupts.phenotypic_feature.umls,associated_with.gene.umls,interacts_with.cell_component.umls,affects_reverse.biological_process_or_activity.umls,interacts_with.biological_process_or_activity.umls,associated_with.chemical_substance.umls,inhibits.gene.umls,stimulates.cell.umls,disrupts.biological_process_or_activity.umls,affects.gene.umls,associated_with_reverse.chemical_substance.umls,associated_with.phenotypic_feature.umls,affects_reverse.chemical_substance.umls,interacts_with_reverse.cell.umls,affects.chemical_substance.umls,interacts_with_reverse.biological_process_or_activity.umls,inhibits.protein.umls,stimulates.biological_process_or_activity.umls,associated_with_reverse.biological_process_or_activity.umls,affects.protein.umls,interacts_with_reverse.chemical_substance.umls,stimulates.cell_component.umls,associated_with.biological_process_or_activity.umls,affects.biological_process_or_activity.umls,disrupts.protein.umls,interacts_with.cell.umls,interacts_with.chemical_substance.umls,disrupts.gene.umls,interacts_with_reverse.cell_component.umls,stimulates.phenotypic_feature.umls,disrupts.cell_component.umls&species=human&size=100\")\nAPI 13.10: https://pending.biothings.io/semmedgene/query (POST \"q=C1422064&scopes=stimulates.protein.umls&fields=umls&species=human&size=100\")\nAPI 5.1: https://pending.biothings.io/DISEASES/query (POST \"q=ACE2&scopes=DISEASES.associatedWith.symbol&fields=_id&species=human&size=100\")\nAPI 10.1: https://pending.biothings.io/ebigene2phenotype/query (POST \"q=13557&scopes=_id&fields=gene2phenotype.phenotypes&species=human&size=100\")\nAPI 11.1: https://pending.biothings.io/pfocr/query (POST \"q=59272&scopes=associatedWith.genes&fields=_id&species=human&size=100\")\n"
],
[
"df = fc.display_table_view()",
"_____no_output_____"
]
],
[
[
"### No. 2 NELFINAVIR MESYLATE",
"_____no_output_____"
]
],
[
[
"df.loc[df['output_name'] == 'NELFINAVIR']",
"_____no_output_____"
]
],
[
[
"### No. 3 AMOPYROQUINE",
"_____no_output_____"
]
],
[
[
"df.loc[df['output_name'] == 'C0051735']",
"_____no_output_____"
]
],
[
[
"### No. 7 HANFANGCHIN A",
"_____no_output_____"
]
],
[
[
"df.loc[df['output_name'] == 'C0076316']",
"_____no_output_____"
]
],
[
[
"### No. 11 FERROQUINE",
"_____no_output_____"
]
],
[
[
"df.loc[df['output_name'] == 'C1313506']",
"_____no_output_____"
]
],
[
[
"### No. 13 ASTEMIZOLE",
"_____no_output_____"
]
],
[
[
"df.loc[df['output_name'] == 'ASTEMIZOLE']",
"_____no_output_____"
]
],
[
[
"### No. 14 amodiaquine",
"_____no_output_____"
]
],
[
[
"df.loc[df['output_name'] == 'AMODIAQUINE']",
"_____no_output_____"
]
],
[
[
"### No. 22 (+)-MEFLOQUINE",
"_____no_output_____"
]
],
[
[
"df.loc[df['output_name'] == 'C0208248']",
"_____no_output_____"
]
],
[
[
"ABOVE REFERS TO: name(Mefloquine Hydrochloride) umls(C0282398)",
"_____no_output_____"
]
],
[
[
"df.loc[df['output_name'] == 'C0208248']",
"_____no_output_____"
]
],
[
[
"ABOVE REFERS TO: name(mefloquine-sulfadoxine-pyrimethamine) umls(C0208248)",
"_____no_output_____"
],
[
"### No. 27 CEPHARANTHINE",
"_____no_output_____"
]
],
[
[
"df.loc[df['output_name'] == 'C0055082']",
"_____no_output_____"
]
],
[
[
"### No. 33 ANDROGRAPHOLIDE",
"_____no_output_____"
]
],
[
[
"df.loc[df['output_name'] == 'C0051821']",
"_____no_output_____"
]
],
[
[
"### No. 39 NAFOXIDINE",
"_____no_output_____"
]
],
[
[
"df.loc[df['output_name'] == 'C0027328']",
"_____no_output_____"
]
],
[
[
"### No. 48 RETINALDEHYDE",
"_____no_output_____"
]
],
[
[
"df.loc[df['output_name'] == 'C0035331']",
"_____no_output_____"
]
],
[
[
"### No. 59 CLOFAZIMINE",
"_____no_output_____"
]
],
[
[
"df.loc[df['output_name'] == 'CLOFAZIMINE']",
"_____no_output_____"
]
],
[
[
"### No. 63 PERHEXILINE",
"_____no_output_____"
]
],
[
[
"df.loc[df['output_name'] == 'PERHEXILINE']",
"_____no_output_____"
]
],
[
[
"### No. 65 resiniferatoxin",
"_____no_output_____"
]
],
[
[
"df.loc[df['output_name'] == 'C0073081']",
"_____no_output_____"
]
],
[
[
"### No. 69 EBASTINE",
"_____no_output_____"
]
],
[
[
"df.loc[df['output_name'] == 'EBASTINE']",
"_____no_output_____"
]
],
[
[
"### No. 73 5-Azacytidine",
"_____no_output_____"
]
],
[
[
"df.loc[df['output_name'] == 'AZACITIDINE']",
"_____no_output_____"
]
],
[
[
"### No. 76 AMIODARONE",
"_____no_output_____"
]
],
[
[
"df.loc[df['output_name'] == 'AMIODARONE']",
"_____no_output_____"
],
[
"df.loc[df['output_name'] == 'C0700442']",
"_____no_output_____"
]
],
[
[
"Above refers to Amiodarone hydrochloride",
"_____no_output_____"
],
[
"### No. 79 NSP 805",
"_____no_output_____"
]
],
[
[
"df.loc[df['output_name'] == 'C0660146']",
"_____no_output_____"
]
],
[
[
"### No. 81 CLORICROMENE",
"_____no_output_____"
]
],
[
[
"df.loc[df['output_name'] == 'C0050066']",
"_____no_output_____"
]
],
[
[
"### No. 82 TIFLUADOM",
"_____no_output_____"
]
],
[
[
"df.loc[df['output_name'] == 'C0076670']",
"_____no_output_____"
]
],
[
[
"### No. 85 SCH-28080",
"_____no_output_____"
]
],
[
[
"df.loc[df['output_name'] == 'C0074142']",
"_____no_output_____"
]
],
[
[
"### NO. 96 IMMUNOMYCIN",
"_____no_output_____"
]
],
[
[
"df.loc[df['output_name'] == 'C0123418']",
"_____no_output_____"
]
],
[
[
"### NO.97 ARGLABIN",
"_____no_output_____"
]
],
[
[
"df.loc[df['output_name'] == 'C0661380']",
"_____no_output_____"
]
],
[
[
"### NO.100 TRETINOIN",
"_____no_output_____"
]
],
[
[
"df.loc[df['output_name'] == 'TRETINOIN']",
"_____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",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"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",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
d08233b84582ffa87cb7f3fdec94e4d03b9ed506 | 4,035 | ipynb | Jupyter Notebook | 01_TrainOnLocal.ipynb | notanaha/oh4ml-lite | fa8c662a11e2d5ff0153cb840c4e2db591af5e27 | [
"MIT"
] | null | null | null | 01_TrainOnLocal.ipynb | notanaha/oh4ml-lite | fa8c662a11e2d5ff0153cb840c4e2db591af5e27 | [
"MIT"
] | null | null | null | 01_TrainOnLocal.ipynb | notanaha/oh4ml-lite | fa8c662a11e2d5ff0153cb840c4e2db591af5e27 | [
"MIT"
] | null | null | null | 25.377358 | 80 | 0.541512 | [
[
[
"!pip install statsmodels==0.12.2",
"_____no_output_____"
],
[
"import os\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport json\nimport joblib\n\nfrom pandas import Grouper\nfrom statsmodels.graphics.tsaplots import plot_acf\nfrom statsmodels.graphics.tsaplots import plot_pacf\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import r2_score\nfrom statsmodels.tsa.stattools import adfuller\nfrom statsmodels.tsa.arima_model import ARIMA\n\nfrom azureml.core import Workspace, Experiment, Dataset\nws = Workspace.from_config()",
"_____no_output_____"
],
[
"dataset1 = Dataset.get_by_name(workspace=ws, name='transaction_ts2013')\ndf = dataset1.to_pandas_dataframe()\n\ndf.set_index('TransactionDate',inplace=True)\ndf.columns = ['PaidAmount']\nseries = pd.Series(df['PaidAmount'])\n\ndef mean_and_variance(X):\n split = int(len(X) / 2)\n X1, X2 = X[0:split], X[split:]\n mean1, mean2 = X1.mean(), X2.mean()\n var1, var2 = X1.var(), X2.var()\n print('mean1=%f, mean2=%f' % (mean1, mean2))\n print('variance1=%f, variance2=%f' % (var1, var2))\n \nmean_and_variance(series.values)\n\ndef fuller_test(X):\n result = adfuller(X)\n print('ADF Statistic: %f' % result[0])\n print('p-value: %f' % result[1])\n print('Critical Values:')\n for key, value in result[4].items():\n \tprint('\\t%s: %.3f' % (key, value))\n \nfuller_test(series.values)",
"_____no_output_____"
],
[
"#plot_acf(series)\n#plot_pacf(series)\nX = series.values\nsize = int(len(X) * 0.9)\ntrain, test = X[0:size], X[size:len(X)]",
"_____no_output_____"
],
[
"model = ARIMA(train, order=(2,0,2))\nmodel_fit = model.fit(disp=0) \nprint(model_fit.summary())",
"_____no_output_____"
],
[
"residuals = pd.DataFrame(model_fit.resid)\nresiduals.plot(title=\"Residuals Error Plot\")\nplt.show()",
"_____no_output_____"
],
[
"predictions=model_fit.forecast(steps=test.size)[0] \n\nmse = mean_squared_error(test, predictions)\nrmse = np.sqrt(mse)\nr2 = r2_score(test,predictions)\nprint('Test RMSE: %.3f' % rmse)\nprint('Test R2: %.3f' % r2)\n\n# plot\nplt.plot(test)\nplt.plot(predictions, color='red')\nplt.title(\"Test Data Vs. Predictions\")\nplt.show()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d08237a544ffed140d277b85b36e902181d25c99 | 6,958 | ipynb | Jupyter Notebook | demos/gpu/horovod/cpu/image-classification/01-load-data-cats-n-dogs.ipynb | omesser/tutorials | 4ffa0cc474ffe3bb6c673e89aa1361990fdf5bd7 | [
"Apache-2.0"
] | null | null | null | demos/gpu/horovod/cpu/image-classification/01-load-data-cats-n-dogs.ipynb | omesser/tutorials | 4ffa0cc474ffe3bb6c673e89aa1361990fdf5bd7 | [
"Apache-2.0"
] | null | null | null | demos/gpu/horovod/cpu/image-classification/01-load-data-cats-n-dogs.ipynb | omesser/tutorials | 4ffa0cc474ffe3bb6c673e89aa1361990fdf5bd7 | [
"Apache-2.0"
] | null | null | null | 24.414035 | 142 | 0.572722 | [
[
[
"# Load Cats and Dogs Images",
"_____no_output_____"
],
[
"## Install Packages",
"_____no_output_____"
]
],
[
[
"!pip install --upgrade keras==2.2.4\n!pip install --upgrade tensorflow==1.13.1 \n!pip install --upgrade 'numpy<1.15.0'",
"_____no_output_____"
]
],
[
[
"> **Note:** After running the pip command you should restart the Jupyter kernel.<br>\n> To restart the kernel, click on the kernel-restart button in the notebook menu toolbar (the refresh icon next to the **Code** button).",
"_____no_output_____"
],
[
"## Import Library",
"_____no_output_____"
]
],
[
[
"# This Python 3 environment comes with many helpful analytics libraries installed.\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python.\n# For example, here are several helpful packages to load:\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom keras.preprocessing.image import load_img\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running the following (by selecting 'Run' or pressing Shift+Enter) will list the files in the input directory:\n\nimport matplotlib.pyplot as plt\nimport random\n\nimport os\nimport zipfile\n\n# Define locations\nBASE_PATH = os.getcwd()\nDATA_PATH = BASE_PATH + \"/cats_and_dogs_filtered/\"\n!mkdir model\nMODEL_PATH = BASE_PATH + '/model/'\n\n# Define image parameters\nFAST_RUN = False\nIMAGE_WIDTH=128\nIMAGE_HEIGHT=128\nIMAGE_SIZE=(IMAGE_WIDTH, IMAGE_HEIGHT)\nIMAGE_CHANNELS=3 # RGB color\n\n# Any results you write to the current directory are saved as output.",
"Using TensorFlow backend.\n"
],
[
"DATA_PATH + 'catsndogs.zip'",
"_____no_output_____"
]
],
[
[
"## Download the Data",
"_____no_output_____"
]
],
[
[
"!mkdir cats_and_dogs_filtered\n# Download a sample stocks file from Iguazio demo bucket in AWS S3\n!curl -L \"iguazio-sample-data.s3.amazonaws.com/catsndogs.zip\" > ./cats_and_dogs_filtered/catsndogs.zip",
"_____no_output_____"
],
[
"zip_ref = zipfile.ZipFile(DATA_PATH + 'catsndogs.zip', 'r')\nzip_ref.extractall('cats_and_dogs_filtered')\nzip_ref.close()",
"_____no_output_____"
]
],
[
[
"## Prepare the Traning Data",
"_____no_output_____"
]
],
[
[
"import json",
"_____no_output_____"
],
[
"def build_prediction_map(categories_map):\n return {v:k for k ,v in categories_map.items()}",
"_____no_output_____"
],
[
"# Create a file-names list (JPG image-files only)\nfilenames = [file for file in os.listdir(DATA_PATH+\"/cats_n_dogs\") if file.endswith('jpg')]\ncategories = []\n\n# Categories and prediction-classes map\ncategories_map = {\n 'dog': 1,\n 'cat': 0,\n}\nprediction_map = build_prediction_map(categories_map)\nwith open(MODEL_PATH + 'prediction_classes_map.json', 'w') as f:\n json.dump(prediction_map, f)\n\n# Create a pandas DataFrame for the full sample\nfor filename in filenames:\n category = filename.split('.')[0]\n categories.append([categories_map[category]])\n\ndf = pd.DataFrame({\n 'filename': filenames,\n 'category': categories\n})\ndf['category'] = df['category'].astype('str');",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"df.tail()",
"_____no_output_____"
]
],
[
[
"## Check the Total Image Count\n\nCheck the total image count for each category.<br>\nThe data set has 12,000 cat images and 12,000 dog images.",
"_____no_output_____"
]
],
[
[
"df['category'].value_counts().plot.bar()",
"_____no_output_____"
]
],
[
[
"## Display the Sample Image",
"_____no_output_____"
]
],
[
[
"sample = random.choice(filenames)\nimage = load_img(DATA_PATH+\"/cats_n_dogs/\"+sample)\nplt.imshow(image)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
d08253042ea50ed3c31afa29e44dcd54f795a083 | 62,281 | ipynb | Jupyter Notebook | Fairness_Survey/ALGORITHMS/BaseLine/gbm and LogReg/German.ipynb | DEHO-OSCAR-BLESSED/Evaluation-of-Fairness-Algorithms | ce0dfce70bacecab93dd30ba4a34bdeb835ffce5 | [
"MIT"
] | null | null | null | Fairness_Survey/ALGORITHMS/BaseLine/gbm and LogReg/German.ipynb | DEHO-OSCAR-BLESSED/Evaluation-of-Fairness-Algorithms | ce0dfce70bacecab93dd30ba4a34bdeb835ffce5 | [
"MIT"
] | null | null | null | Fairness_Survey/ALGORITHMS/BaseLine/gbm and LogReg/German.ipynb | DEHO-OSCAR-BLESSED/Evaluation-of-Fairness-Algorithms | ce0dfce70bacecab93dd30ba4a34bdeb835ffce5 | [
"MIT"
] | null | null | null | 62,281 | 62,281 | 0.563992 | [
[
[
"\n# INSTALLATION",
"_____no_output_____"
]
],
[
[
"!pip install aif360\n!pip install fairlearn",
"Collecting aif360\n Downloading aif360-0.4.0-py3-none-any.whl (175 kB)\n\u001b[?25l\r\u001b[K |█▉ | 10 kB 21.9 MB/s eta 0:00:01\r\u001b[K |███▊ | 20 kB 25.3 MB/s eta 0:00:01\r\u001b[K |█████▋ | 30 kB 13.4 MB/s eta 0:00:01\r\u001b[K |███████▌ | 40 kB 9.8 MB/s eta 0:00:01\r\u001b[K |█████████▍ | 51 kB 5.3 MB/s eta 0:00:01\r\u001b[K |███████████▎ | 61 kB 5.4 MB/s eta 0:00:01\r\u001b[K |█████████████ | 71 kB 6.0 MB/s eta 0:00:01\r\u001b[K |███████████████ | 81 kB 6.7 MB/s eta 0:00:01\r\u001b[K |████████████████▉ | 92 kB 6.8 MB/s eta 0:00:01\r\u001b[K |██████████████████▊ | 102 kB 5.3 MB/s eta 0:00:01\r\u001b[K |████████████████████▋ | 112 kB 5.3 MB/s eta 0:00:01\r\u001b[K |██████████████████████▌ | 122 kB 5.3 MB/s eta 0:00:01\r\u001b[K |████████████████████████▎ | 133 kB 5.3 MB/s eta 0:00:01\r\u001b[K |██████████████████████████▏ | 143 kB 5.3 MB/s eta 0:00:01\r\u001b[K |████████████████████████████ | 153 kB 5.3 MB/s eta 0:00:01\r\u001b[K |██████████████████████████████ | 163 kB 5.3 MB/s eta 0:00:01\r\u001b[K |███████████████████████████████▉| 174 kB 5.3 MB/s eta 0:00:01\r\u001b[K |████████████████████████████████| 175 kB 5.3 MB/s \n\u001b[?25hRequirement already satisfied: scikit-learn>=0.22.1 in /usr/local/lib/python3.7/dist-packages (from aif360) (0.22.2.post1)\nRequirement already satisfied: scipy<1.6.0,>=1.2.0 in /usr/local/lib/python3.7/dist-packages (from aif360) (1.4.1)\nRequirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from aif360) (3.2.2)\nRequirement already satisfied: numpy>=1.16 in /usr/local/lib/python3.7/dist-packages (from aif360) (1.19.5)\nCollecting tempeh\n Downloading tempeh-0.1.12-py3-none-any.whl (39 kB)\nRequirement already satisfied: pandas>=0.24.0 in /usr/local/lib/python3.7/dist-packages (from aif360) (1.1.5)\nRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24.0->aif360) (2018.9)\nRequirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24.0->aif360) (2.8.1)\nRequirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas>=0.24.0->aif360) (1.15.0)\nRequirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.22.1->aif360) (1.0.1)\nRequirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->aif360) (0.10.0)\nRequirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->aif360) (1.3.1)\nRequirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->aif360) (2.4.7)\nCollecting shap\n Downloading shap-0.39.0.tar.gz (356 kB)\n\u001b[K |████████████████████████████████| 356 kB 9.7 MB/s \n\u001b[?25hRequirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from tempeh->aif360) (2.23.0)\nRequirement already satisfied: pytest in /usr/local/lib/python3.7/dist-packages (from tempeh->aif360) (3.6.4)\nCollecting memory-profiler\n Downloading memory_profiler-0.58.0.tar.gz (36 kB)\nRequirement already satisfied: psutil in /usr/local/lib/python3.7/dist-packages (from memory-profiler->tempeh->aif360) (5.4.8)\nRequirement already satisfied: py>=1.5.0 in /usr/local/lib/python3.7/dist-packages (from pytest->tempeh->aif360) (1.10.0)\nRequirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from pytest->tempeh->aif360) (57.2.0)\nRequirement already satisfied: pluggy<0.8,>=0.5 in /usr/local/lib/python3.7/dist-packages (from pytest->tempeh->aif360) (0.7.1)\nRequirement already satisfied: attrs>=17.4.0 in /usr/local/lib/python3.7/dist-packages (from pytest->tempeh->aif360) (21.2.0)\nRequirement already satisfied: more-itertools>=4.0.0 in /usr/local/lib/python3.7/dist-packages (from pytest->tempeh->aif360) (8.8.0)\nRequirement already satisfied: atomicwrites>=1.0 in /usr/local/lib/python3.7/dist-packages (from pytest->tempeh->aif360) (1.4.0)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->tempeh->aif360) (1.24.3)\nRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->tempeh->aif360) (3.0.4)\nRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->tempeh->aif360) (2.10)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->tempeh->aif360) (2021.5.30)\nRequirement already satisfied: tqdm>4.25.0 in /usr/local/lib/python3.7/dist-packages (from shap->tempeh->aif360) (4.41.1)\nCollecting slicer==0.0.7\n Downloading slicer-0.0.7-py3-none-any.whl (14 kB)\nRequirement already satisfied: numba in /usr/local/lib/python3.7/dist-packages (from shap->tempeh->aif360) (0.51.2)\nRequirement already satisfied: cloudpickle in /usr/local/lib/python3.7/dist-packages (from shap->tempeh->aif360) (1.3.0)\nRequirement already satisfied: llvmlite<0.35,>=0.34.0.dev0 in /usr/local/lib/python3.7/dist-packages (from numba->shap->tempeh->aif360) (0.34.0)\nBuilding wheels for collected packages: memory-profiler, shap\n Building wheel for memory-profiler (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for memory-profiler: filename=memory_profiler-0.58.0-py3-none-any.whl size=30189 sha256=6f3f2faa9406796cdd822533abf126c3429d1b9e65c77ee8d46ea29f7cca17a2\n Stored in directory: /root/.cache/pip/wheels/56/19/d5/8cad06661aec65a04a0d6785b1a5ad035cb645b1772a4a0882\n Building wheel for shap (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for shap: filename=shap-0.39.0-cp37-cp37m-linux_x86_64.whl size=491642 sha256=a7bc0224212cac02ac0b8e55ed440c183229abeb8519361941c318ac11edd44e\n Stored in directory: /root/.cache/pip/wheels/ca/25/8f/6ae5df62c32651cd719e972e738a8aaa4a87414c4d2b14c9c0\nSuccessfully built memory-profiler shap\nInstalling collected packages: slicer, shap, memory-profiler, tempeh, aif360\nSuccessfully installed aif360-0.4.0 memory-profiler-0.58.0 shap-0.39.0 slicer-0.0.7 tempeh-0.1.12\nCollecting fairlearn\n Downloading fairlearn-0.7.0-py3-none-any.whl (177 kB)\n\u001b[K |████████████████████████████████| 177 kB 5.2 MB/s \n\u001b[?25hRequirement already satisfied: pandas>=0.25.1 in /usr/local/lib/python3.7/dist-packages (from fairlearn) (1.1.5)\nRequirement already satisfied: scipy>=1.4.1 in /usr/local/lib/python3.7/dist-packages (from fairlearn) (1.4.1)\nRequirement already satisfied: scikit-learn>=0.22.1 in /usr/local/lib/python3.7/dist-packages (from fairlearn) (0.22.2.post1)\nRequirement already satisfied: numpy>=1.17.2 in /usr/local/lib/python3.7/dist-packages (from fairlearn) (1.19.5)\nRequirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.25.1->fairlearn) (2.8.1)\nRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.25.1->fairlearn) (2018.9)\nRequirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas>=0.25.1->fairlearn) (1.15.0)\nRequirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.22.1->fairlearn) (1.0.1)\nInstalling collected packages: fairlearn\nSuccessfully installed fairlearn-0.7.0\n"
],
[
"!apt-get install -jre\n!java -version",
"E: Command line option 'j' [from -jre] is not understood in combination with the other options.\nopenjdk version \"11.0.11\" 2021-04-20\nOpenJDK Runtime Environment (build 11.0.11+9-Ubuntu-0ubuntu2.18.04)\nOpenJDK 64-Bit Server VM (build 11.0.11+9-Ubuntu-0ubuntu2.18.04, mixed mode, sharing)\n"
],
[
"!pip install h2o",
"Collecting h2o\n Downloading h2o-3.32.1.5.tar.gz (164.8 MB)\n\u001b[K |████████████████████████████████| 164.8 MB 4.4 kB/s \n\u001b[?25hRequirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from h2o) (2.23.0)\nRequirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from h2o) (0.8.9)\nRequirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from h2o) (0.16.0)\nCollecting colorama>=0.3.8\n Downloading colorama-0.4.4-py2.py3-none-any.whl (16 kB)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->h2o) (1.24.3)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->h2o) (2021.5.30)\nRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->h2o) (2.10)\nRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->h2o) (3.0.4)\nBuilding wheels for collected packages: h2o\n Building wheel for h2o (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for h2o: filename=h2o-3.32.1.5-py2.py3-none-any.whl size=164886106 sha256=aa002055af4e95dd546609091d0265eea942fec641fe11e9ef79b465cfc5afbf\n Stored in directory: /root/.cache/pip/wheels/2f/f4/f6/7115a720596f0b6c377b3d82c28242585c7bb7ab27d430f97c\nSuccessfully built h2o\nInstalling collected packages: colorama, h2o\nSuccessfully installed colorama-0.4.4 h2o-3.32.1.5\n"
],
[
"!pip install xlsxwriter",
"Collecting xlsxwriter\n Downloading XlsxWriter-2.0.0-py2.py3-none-any.whl (149 kB)\n\u001b[?25l\r\u001b[K |██▏ | 10 kB 19.1 MB/s eta 0:00:01\r\u001b[K |████▍ | 20 kB 20.9 MB/s eta 0:00:01\r\u001b[K |██████▋ | 30 kB 16.7 MB/s eta 0:00:01\r\u001b[K |████████▊ | 40 kB 5.6 MB/s eta 0:00:01\r\u001b[K |███████████ | 51 kB 4.5 MB/s eta 0:00:01\r\u001b[K |█████████████▏ | 61 kB 5.2 MB/s eta 0:00:01\r\u001b[K |███████████████▎ | 71 kB 5.8 MB/s eta 0:00:01\r\u001b[K |█████████████████▌ | 81 kB 6.4 MB/s eta 0:00:01\r\u001b[K |███████████████████▊ | 92 kB 6.6 MB/s eta 0:00:01\r\u001b[K |█████████████████████▉ | 102 kB 5.2 MB/s eta 0:00:01\r\u001b[K |████████████████████████ | 112 kB 5.2 MB/s eta 0:00:01\r\u001b[K |██████████████████████████▎ | 122 kB 5.2 MB/s eta 0:00:01\r\u001b[K |████████████████████████████▌ | 133 kB 5.2 MB/s eta 0:00:01\r\u001b[K |██████████████████████████████▋ | 143 kB 5.2 MB/s eta 0:00:01\r\u001b[K |████████████████████████████████| 149 kB 5.2 MB/s \n\u001b[?25hInstalling collected packages: xlsxwriter\nSuccessfully installed xlsxwriter-2.0.0\n"
]
],
[
[
"#IMPORTS",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom mlxtend.feature_selection import ExhaustiveFeatureSelector\nfrom xgboost import XGBClassifier\n# import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport openpyxl\nimport xlsxwriter\nfrom openpyxl import load_workbook\n\nimport shap\n#suppress setwith copy warning\npd.set_option('mode.chained_assignment',None)\nfrom sklearn.feature_selection import VarianceThreshold\nfrom sklearn.feature_selection import SelectKBest, SelectFwe, SelectPercentile,SelectFdr, SelectFpr, SelectFromModel\nfrom sklearn.feature_selection import chi2, mutual_info_classif\n# from skfeature.function.similarity_based import fisher_score\nimport aif360\nimport matplotlib.pyplot as plt\nfrom aif360.metrics.classification_metric import ClassificationMetric\n\nfrom aif360.metrics import BinaryLabelDatasetMetric\nfrom aif360.datasets import StandardDataset , BinaryLabelDataset\nfrom sklearn.preprocessing import MinMaxScaler \nMM= MinMaxScaler()\nimport h2o\nfrom h2o.automl import H2OAutoML\nfrom h2o.estimators.glm import H2OGeneralizedLinearEstimator\n\nimport sys\nsys.path.append(\"../\")\nimport os\n",
"/usr/local/lib/python3.7/dist-packages/sklearn/externals/joblib/__init__.py:15: FutureWarning: sklearn.externals.joblib is deprecated in 0.21 and will be removed in 0.23. Please import this functionality directly from joblib, which can be installed with: pip install joblib. If this warning is raised when loading pickled models, you may need to re-serialize those models with scikit-learn 0.21+.\n warnings.warn(msg, category=FutureWarning)\n"
],
[
"h2o.init()",
"Checking whether there is an H2O instance running at http://localhost:54321 ..... not found.\nAttempting to start a local H2O server...\n Java Version: openjdk version \"11.0.11\" 2021-04-20; OpenJDK Runtime Environment (build 11.0.11+9-Ubuntu-0ubuntu2.18.04); OpenJDK 64-Bit Server VM (build 11.0.11+9-Ubuntu-0ubuntu2.18.04, mixed mode, sharing)\n Starting server from /usr/local/lib/python3.7/dist-packages/h2o/backend/bin/h2o.jar\n Ice root: /tmp/tmpr8vm4o15\n JVM stdout: /tmp/tmpr8vm4o15/h2o_unknownUser_started_from_python.out\n JVM stderr: /tmp/tmpr8vm4o15/h2o_unknownUser_started_from_python.err\n Server is running at http://127.0.0.1:54321\nConnecting to H2O server at http://127.0.0.1:54321 ... successful.\n"
]
],
[
[
"#**************************LOADING DATASET*******************************",
"_____no_output_____"
]
],
[
[
"from google.colab import drive \ndrive.mount('/content/gdrive')",
"Drive already mounted at /content/gdrive; to attempt to forcibly remount, call drive.mount(\"/content/gdrive\", force_remount=True).\n"
],
[
"for i in range(1,51,1):\n\n train_url=r'/content/gdrive/MyDrive/Datasets/SurveyData/DATASET/German/Train'\n train_path= os.path.join(train_url ,(\"Train\"+ str(i)+ \".csv\"))\n train= pd.read_csv(train_path)\n\n test_url=r'/content/gdrive/MyDrive/Datasets/SurveyData/DATASET/German/Test'\n test_path= os.path.join(test_url ,(\"Test\"+ str(i)+ \".csv\"))\n test= pd.read_csv(test_path)\n\n # normalization of train and test sets\n Fitter= MM.fit(train)\n transformed_train=Fitter.transform(train)\n train=pd.DataFrame(transformed_train, columns= train.columns)\n\n #test normalization\n transformed_test=Fitter.transform(test)\n test=pd.DataFrame(transformed_test, columns= test.columns)\n\n # *************CHECKING FAIRNESS IN DATASET**************************\n ## ****************CONVERTING TO BLD FORMAT******************************\n\n\n #Transforming the Train and Test Set to BinaryLabel\n advantagedGroup= [{'age':1}]\n disadvantagedGroup= [{'age':0}]\n\n # class Train(StandardDataset):\n # def __init__(self,label_name= 'default',\n # favorable_classes= [1],protected_attribute_names=['age'], privileged_classes=[[1]], ):\n\n\n # super(Train, self).__init__(df=train , label_name=label_name ,\n # favorable_classes=favorable_classes , protected_attribute_names=protected_attribute_names ,\n # privileged_classes=privileged_classes ,\n # )\n\n\n\n\n\n # BLD_Train= Train(protected_attribute_names= ['age'],\n # privileged_classes= [[1]])\n\n class Test(StandardDataset):\n def __init__(self,label_name= 'default',\n favorable_classes= [1],protected_attribute_names=['age'], privileged_classes=[[1]], ):\n\n\n super(Test, self).__init__(df=test , label_name=label_name ,\n favorable_classes=favorable_classes , protected_attribute_names=protected_attribute_names ,\n privileged_classes=privileged_classes ,\n )\n\n BLD_Test= Test(protected_attribute_names= ['age'],\n privileged_classes= [[1]])\n ## ********************Checking Bias in Data********************************\n DataBias_Checker = BinaryLabelDatasetMetric(BLD_Test , unprivileged_groups= disadvantagedGroup, privileged_groups= advantagedGroup)\n\n dsp= DataBias_Checker .statistical_parity_difference() \n dif= DataBias_Checker.consistency() \n ddi= DataBias_Checker.disparate_impact() \n\n print('The Statistical Parity diference is = {diff}'.format(diff= dsp ))\n print('Individual Fairness is = {IF}'.format( IF= dif ))\n print('Disparate Impact is = {IF}'.format( IF= ddi ))\n # ********************SETTING TO H20 FRAME AND MODEL TRAINING*******************************\n x = list(train.columns)\n y = \"default\"\n x.remove(y)\n Train=h2o.H2OFrame(train)\n Test= h2o.H2OFrame(test)\n Train[y] = Train[y].asfactor()\n Test[y] = Test[y].asfactor()\n aml = H2OAutoML(max_models=10, nfolds=10, include_algos=['GBM'] , stopping_metric='AUTO') #verbosity='info',,'GBM', 'DRF'\n aml.train(x=x, y=y, training_frame=Train)\n best_model= aml.leader\n # a.model_performance()\n #**********************REPLACE LABELS OF DUPLICATED TEST SET WITH PREDICTIONS****************************\n #predicted labels\n gbm_Predictions= best_model.predict(Test)\n gbm_Predictions= gbm_Predictions.as_data_frame()\n predicted_df= test.copy()\n predicted_df['default']= gbm_Predictions.predict.to_numpy()\n\n # ********************COMPUTE DISCRIMINATION*****************************\n\n advantagedGroup= [{'age':1}]\n disadvantagedGroup= [{'age':0}]\n\n class PredTest(StandardDataset):\n def __init__(self,label_name= 'default',\n favorable_classes= [1],protected_attribute_names=['age'], privileged_classes=[[1]], ):\n\n\n super(PredTest, self).__init__(df=predicted_df , label_name=label_name ,\n favorable_classes=favorable_classes , protected_attribute_names=protected_attribute_names ,\n privileged_classes=privileged_classes ,\n )\n\n BLD_PredTest= PredTest(protected_attribute_names= ['age'],\n privileged_classes= [[1]])\n\n # # Workbook= pd.ExcelFile(r'/content/gdrive/MyDrive/Datasets/SurveyData/RESULTS/BaseLines/GBM/gbm_Results.xlsx')\n # excelBook= load_workbook('/content/gdrive/MyDrive/Datasets/SurveyData/RESULTS/BaseLines/GBM/gbm_Results.xlsx')\n # OldDF= excelBook.get_sheet_by_name(\"German\")#pd.read_excel(Workbook,sheet_name='German')\n #load workbook\n excelBook= load_workbook('/content/gdrive/MyDrive/Datasets/SurveyData/RESULTS/BaseLines/GBM/gbm_Results.xlsx')\n German= excelBook['German']\n data= German.values\n\n # Get columns\n columns = next(data)[0:]\n 10# Create a DataFrame based on the second and subsequent lines of data\n OldDF = pd.DataFrame(data, columns=columns)\n\n ClassifierBias = ClassificationMetric( BLD_Test,BLD_PredTest , unprivileged_groups= disadvantagedGroup, privileged_groups= advantagedGroup)\n Accuracy= ClassifierBias.accuracy()\n TPR= ClassifierBias.true_positive_rate()\n TNR= ClassifierBias.true_negative_rate()\n NPV= ClassifierBias.negative_predictive_value()\n PPV= ClassifierBias.positive_predictive_value()\n SP=ClassifierBias .statistical_parity_difference() \n IF=ClassifierBias.consistency()\n DI=ClassifierBias.disparate_impact()\n EOP=ClassifierBias.true_positive_rate_difference()\n EO=ClassifierBias.average_odds_difference()\n FDR= ClassifierBias.false_discovery_rate(privileged=False)- ClassifierBias.false_discovery_rate(privileged=True)\n NPV_diff=ClassifierBias.negative_predictive_value(privileged=False)-ClassifierBias.negative_predictive_value(privileged=True)\n FOR=ClassifierBias.false_omission_rate(privileged=False)-ClassifierBias.false_omission_rate(privileged=True)\n PPV_diff=ClassifierBias.positive_predictive_value(privileged=False) -ClassifierBias.positive_predictive_value(privileged=True)\n BGE = ClassifierBias.between_group_generalized_entropy_index()\n WGE = ClassifierBias.generalized_entropy_index()-ClassifierBias.between_group_generalized_entropy_index()\n BGTI = ClassifierBias.between_group_theil_index()\n WGTI = ClassifierBias.theil_index() -ClassifierBias.between_group_theil_index()\n EDF= ClassifierBias.differential_fairness_bias_amplification()\n\n newdf= pd.DataFrame(index = [0], data= { 'ACCURACY': Accuracy,'TPR': TPR, 'PPV':PPV, 'TNR':TNR,'NPV':NPV,'SP':SP,'CONSISTENCY':IF,'DI':DI,'EOP':EOP,'EO':EO,'FDR':FDR,'NPV_diff':NPV_diff, \n 'FOR':FOR,'PPV_diff':PPV_diff,'BGEI':BGE,'WGEI':WGE,'BGTI':BGTI,'WGTI':WGTI,'EDF':EDF,\n 'DATA_SP':dsp,'DATA_CONS':dif,'DATA_DI':ddi})\n newdf=pd.concat([OldDF,newdf])\n\n pathway= r\"/content/gdrive/MyDrive/Datasets/SurveyData/RESULTS/BaseLines/GBM/gbm_Results.xlsx\"\n\n with pd.ExcelWriter(pathway, engine='openpyxl') as writer:\n #load workbook base as for writer\n writer.book= excelBook\n writer.sheets=dict((ws.title, ws) for ws in excelBook.worksheets)\n newdf.to_excel(writer, sheet_name='German', index=False)\n # newdf.to_excel(writer, sheet_name='Adult', index=False)\n\n print('Accuracy', Accuracy)",
"_____no_output_____"
]
],
[
[
"#LOGISTIC REGRESSION",
"_____no_output_____"
]
],
[
[
"for i in range(1,51,1):\n\n train_url=r'/content/gdrive/MyDrive/Datasets/SurveyData/DATASET/German/Train'\n train_path= os.path.join(train_url ,(\"Train\"+ str(i)+ \".csv\"))\n train= pd.read_csv(train_path)\n\n test_url=r'/content/gdrive/MyDrive/Datasets/SurveyData/DATASET/German/Test'\n test_path= os.path.join(test_url ,(\"Test\"+ str(i)+ \".csv\"))\n test= pd.read_csv(test_path)\n\n # normalization of train and test sets\n Fitter= MM.fit(train)\n transformed_train=Fitter.transform(train)\n train=pd.DataFrame(transformed_train, columns= train.columns)\n\n #test normalization\n transformed_test=Fitter.transform(test)\n test=pd.DataFrame(transformed_test, columns= test.columns)\n\n # *************CHECKING FAIRNESS IN DATASET**************************\n ## ****************CONVERTING TO BLD FORMAT******************************\n\n\n #Transforming the Train and Test Set to BinaryLabel\n advantagedGroup= [{'age':1}]\n disadvantagedGroup= [{'age':0}]\n\n # class Train(StandardDataset):\n # def __init__(self,label_name= 'default',\n # favorable_classes= [1],protected_attribute_names=['age'], privileged_classes=[[1]], ):\n\n\n # super(Train, self).__init__(df=train , label_name=label_name ,\n # favorable_classes=favorable_classes , protected_attribute_names=protected_attribute_names ,\n # privileged_classes=privileged_classes ,\n # )\n\n\n\n\n\n # BLD_Train= Train(protected_attribute_names= ['age'],\n # privileged_classes= [[1]])\n\n class Test(StandardDataset):\n def __init__(self,label_name= 'default',\n favorable_classes= [1],protected_attribute_names=['age'], privileged_classes=[[1]], ):\n\n\n super(Test, self).__init__(df=test , label_name=label_name ,\n favorable_classes=favorable_classes , protected_attribute_names=protected_attribute_names ,\n privileged_classes=privileged_classes ,\n )\n\n BLD_Test= Test(protected_attribute_names= ['age'],\n privileged_classes= [[1]])\n ## ********************Checking Bias in Data********************************\n DataBias_Checker = BinaryLabelDatasetMetric(BLD_Test , unprivileged_groups= disadvantagedGroup, privileged_groups= advantagedGroup)\n\n dsp= DataBias_Checker .statistical_parity_difference() \n dif= DataBias_Checker.consistency() \n ddi= DataBias_Checker.disparate_impact() \n\n print('The Statistical Parity diference is = {diff}'.format(diff= dsp ))\n print('Individual Fairness is = {IF}'.format( IF= dif ))\n print('Disparate Impact is = {IF}'.format( IF= ddi ))\n # ********************SETTING TO H20 FRAME AND MODEL TRAINING*******************************\n x = list(train.columns)\n y = \"default\"\n x.remove(y)\n Train=h2o.H2OFrame(train)\n Test= h2o.H2OFrame(test)\n Train[y] = Train[y].asfactor()\n Test[y] = Test[y].asfactor()\n LogReg = H2OGeneralizedLinearEstimator(family= \"binomial\", lambda_ = 0)\n LogReg.train(x=x, y=y, training_frame=Train)\n\n LogReg_Predictions= LogReg.predict(Test)\n LogReg_Predictions= LogReg_Predictions.as_data_frame()\n # *************************REPLACE LABELS OF DUPLICATED TEST SET WITH PREDICTIONS**************************************\n predicted_df= test.copy()\n predicted_df['default']= LogReg_Predictions.predict.to_numpy()\n\n # ***************************COMPUTE DISCRIMINATION********************************\n\n advantagedGroup= [{'age':1}]\n disadvantagedGroup= [{'age':0}]\n\n class PredTest(StandardDataset):\n def __init__(self,label_name= 'default',\n favorable_classes= [1],protected_attribute_names=['age'], privileged_classes=[[1]], ):\n\n\n super(PredTest, self).__init__(df=predicted_df , label_name=label_name ,\n favorable_classes=favorable_classes , protected_attribute_names=protected_attribute_names ,\n privileged_classes=privileged_classes ,\n )\n\n BLD_PredTest= PredTest(protected_attribute_names= ['age'],\n privileged_classes= [[1]])\n\n\n excelBook= load_workbook(r\"/content/gdrive/MyDrive/Datasets/SurveyData/RESULTS/BaseLines/LogReg/LR_Results.xlsx\")\n German= excelBook['German']\n data= German.values\n\n # Get columns\n columns = next(data)[0:]\n \n OldDF = pd.DataFrame(data, columns=columns)\n\n ClassifierBias = ClassificationMetric( BLD_Test,BLD_PredTest , unprivileged_groups= disadvantagedGroup, privileged_groups= advantagedGroup)\n Accuracy= ClassifierBias.accuracy()\n TPR= ClassifierBias.true_positive_rate()\n TNR= ClassifierBias.true_negative_rate()\n NPV= ClassifierBias.negative_predictive_value()\n PPV= ClassifierBias.positive_predictive_value()\n SP=ClassifierBias .statistical_parity_difference() \n IF=ClassifierBias.consistency()\n DI=ClassifierBias.disparate_impact()\n EOP=ClassifierBias.true_positive_rate_difference()\n EO=ClassifierBias.average_odds_difference()\n FDR= ClassifierBias.false_discovery_rate(privileged=False)- ClassifierBias.false_discovery_rate(privileged=True)\n NPV_diff=ClassifierBias.negative_predictive_value(privileged=False)-ClassifierBias.negative_predictive_value(privileged=True)\n FOR=ClassifierBias.false_omission_rate(privileged=False)-ClassifierBias.false_omission_rate(privileged=True)\n PPV_diff=ClassifierBias.positive_predictive_value(privileged=False) -ClassifierBias.positive_predictive_value(privileged=True)\n BGE = ClassifierBias.between_group_generalized_entropy_index()\n WGE = ClassifierBias.generalized_entropy_index()-ClassifierBias.between_group_generalized_entropy_index()\n BGTI = ClassifierBias.between_group_theil_index()\n WGTI = ClassifierBias.theil_index() -ClassifierBias.between_group_theil_index()\n EDF= ClassifierBias.differential_fairness_bias_amplification()\n\n newdf= pd.DataFrame(index = [0], data= { 'ACCURACY': Accuracy,'TPR': TPR, 'PPV':PPV, 'TNR':TNR,'NPV':NPV,'SP':SP,'CONSISTENCY':IF,'DI':DI,'EOP':EOP,'EO':EO,'FDR':FDR,'NPV_diff':NPV_diff, \n 'FOR':FOR,'PPV_diff':PPV_diff,'BGEI':BGE,'WGEI':WGE,'BGTI':BGTI,'WGTI':WGTI,'EDF':EDF,\n 'DATA_SP':dsp,'DATA_CONS':dif,'DATA_DI':ddi})\n newdf=pd.concat([OldDF,newdf])\n\n pathway= r\"/content/gdrive/MyDrive/Datasets/SurveyData/RESULTS/BaseLines/LogReg/LR_Results.xlsx\"\n\n with pd.ExcelWriter(pathway, engine='openpyxl') as writer:\n #load workbook base as for writer\n writer.book= excelBook\n writer.sheets=dict((ws.title, ws) for ws in excelBook.worksheets)\n newdf.to_excel(writer, sheet_name='German', index=False)\n # newdf.to_excel(writer, sheet_name='Adult', index=False)\n\n print('Accuracy', Accuracy)",
"The Statistical Parity diference is = 0.09902740937223695\nIndividual Fairness is = [0.759]\nDisparate Impact is = 1.4007155635062611\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.785\nThe Statistical Parity diference is = 0.2914939479356657\nIndividual Fairness is = [0.701]\nDisparate Impact is = 2.0558558558558557\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.71\nThe Statistical Parity diference is = 0.1254152823920266\nIndividual Fairness is = [0.738]\nDisparate Impact is = 1.468944099378882\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.745\nThe Statistical Parity diference is = 0.03999999999999998\nIndividual Fairness is = [0.702]\nDisparate Impact is = 1.1428571428571428\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.67\nThe Statistical Parity diference is = 0.0283070223189984\nIndividual Fairness is = [0.71]\nDisparate Impact is = 1.0844155844155845\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.7\nThe Statistical Parity diference is = 0.026722656995609828\nIndividual Fairness is = [0.718]\nDisparate Impact is = 1.0903225806451613\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.715\nThe Statistical Parity diference is = 0.07589285714285715\nIndividual Fairness is = [0.721]\nDisparate Impact is = 1.2833333333333334\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.76\nThe Statistical Parity diference is = 0.29073003639477624\nIndividual Fairness is = [0.767]\nDisparate Impact is = 2.5241301907968574\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.72\nThe Statistical Parity diference is = 0.16719976737423664\nIndividual Fairness is = [0.712]\nDisparate Impact is = 1.4655870445344128\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.72\nThe Statistical Parity diference is = 0.1375\nIndividual Fairness is = [0.7]\nDisparate Impact is = 1.4782608695652175\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.73\nThe Statistical Parity diference is = 0.0342950462710942\nIndividual Fairness is = [0.72]\nDisparate Impact is = 1.1041322314049586\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.745\nThe Statistical Parity diference is = 0.19102990033222594\nIndividual Fairness is = [0.708]\nDisparate Impact is = 1.6990881458966567\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.73\nThe Statistical Parity diference is = 0.21759877839282304\nIndividual Fairness is = [0.716]\nDisparate Impact is = 1.8172043010752688\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.705\nThe Statistical Parity diference is = 0.18511796733212343\nIndividual Fairness is = [0.729]\nDisparate Impact is = 1.703448275862069\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.69\nThe Statistical Parity diference is = 0.01245847176079734\nIndividual Fairness is = [0.719]\nDisparate Impact is = 1.0455927051671732\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.735\nThe Statistical Parity diference is = 0.05587668593448941\nIndividual Fairness is = [0.713]\nDisparate Impact is = 1.2013888888888888\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.675\nThe Statistical Parity diference is = 0.14898320070733867\nIndividual Fairness is = [0.715]\nDisparate Impact is = 1.6322701688555348\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.725\nThe Statistical Parity diference is = 0.29954515919428204\nIndividual Fairness is = [0.731]\nDisparate Impact is = 2.1835686777920413\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.715\nThe Statistical Parity diference is = -0.11147165489597252\nIndividual Fairness is = [0.706]\nDisparate Impact is = 0.6694963214487832\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.715\nThe Statistical Parity diference is = 0.21794048383643755\nIndividual Fairness is = [0.718]\nDisparate Impact is = 1.7250712250712248\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.775\nThe Statistical Parity diference is = 0.17843137254901964\nIndividual Fairness is = [0.733]\nDisparate Impact is = 1.6190476190476193\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.715\nThe Statistical Parity diference is = -0.04709912224363094\nIndividual Fairness is = [0.732]\nDisparate Impact is = 0.8462613556953179\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.775\nThe Statistical Parity diference is = 0.04901960784313725\nIndividual Fairness is = [0.717]\nDisparate Impact is = 1.154320987654321\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.73\nThe Statistical Parity diference is = 0.18143160878809356\nIndividual Fairness is = [0.702]\nDisparate Impact is = 1.6274509803921569\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.76\nThe Statistical Parity diference is = 0.260797342192691\nIndividual Fairness is = [0.746]\nDisparate Impact is = 2.2816326530612248\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.71\nThe Statistical Parity diference is = 0.06994047619047616\nIndividual Fairness is = [0.735]\nDisparate Impact is = 1.2554347826086956\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.7\nThe Statistical Parity diference is = 0.3365995282162947\nIndividual Fairness is = [0.723]\nDisparate Impact is = 2.249158249158249\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.705\nThe Statistical Parity diference is = 0.05788423153692612\nIndividual Fairness is = [0.712]\nDisparate Impact is = 1.2101449275362317\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.705\nThe Statistical Parity diference is = 0.03853564547206162\nIndividual Fairness is = [0.724]\nDisparate Impact is = 1.1307189542483658\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.675\nThe Statistical Parity diference is = 0.1268939393939394\nIndividual Fairness is = [0.729]\nDisparate Impact is = 1.4379084967320261\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.71\nThe Statistical Parity diference is = 0.16817906836055657\nIndividual Fairness is = [0.73]\nDisparate Impact is = 1.684729064039409\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.72\nThe Statistical Parity diference is = 0.054545454545454564\nIndividual Fairness is = [0.733]\nDisparate Impact is = 1.1578947368421053\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.76\nThe Statistical Parity diference is = 0.2513155507167483\nIndividual Fairness is = [0.741]\nDisparate Impact is = 2.076146076146076\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.685\nThe Statistical Parity diference is = 0.020833333333333315\nIndividual Fairness is = [0.688]\nDisparate Impact is = 1.0666666666666667\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.685\nThe Statistical Parity diference is = 0.1254152823920266\nIndividual Fairness is = [0.732]\nDisparate Impact is = 1.468944099378882\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.73\nThe Statistical Parity diference is = 0.23172757475083058\nIndividual Fairness is = [0.746]\nDisparate Impact is = 1.9964285714285714\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.645\nThe Statistical Parity diference is = 0.03273809523809523\nIndividual Fairness is = [0.745]\nDisparate Impact is = 1.1170212765957446\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.76\nThe Statistical Parity diference is = 0.15542710340398197\nIndividual Fairness is = [0.722]\nDisparate Impact is = 1.5377777777777775\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.675\nThe Statistical Parity diference is = 0.06979233568828941\nIndividual Fairness is = [0.729]\nDisparate Impact is = 1.232193732193732\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.71\nThe Statistical Parity diference is = 0.1541125541125541\nIndividual Fairness is = [0.701]\nDisparate Impact is = 1.5085714285714285\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.715\nThe Statistical Parity diference is = 0.18511796733212343\nIndividual Fairness is = [0.716]\nDisparate Impact is = 1.703448275862069\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.725\nThe Statistical Parity diference is = 0.1622447031876312\nIndividual Fairness is = [0.761]\nDisparate Impact is = 1.7215619694397282\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.74\nThe Statistical Parity diference is = 0.12\nIndividual Fairness is = [0.688]\nDisparate Impact is = 1.375\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.69\nThe Statistical Parity diference is = 0.06307583274273565\nIndividual Fairness is = [0.696]\nDisparate Impact is = 1.197558268590455\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.695\nThe Statistical Parity diference is = 0.12352941176470589\nIndividual Fairness is = [0.706]\nDisparate Impact is = 1.446808510638298\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.715\nThe Statistical Parity diference is = 0.1068771547813464\nIndividual Fairness is = [0.696]\nDisparate Impact is = 1.3367638650657518\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.72\nThe Statistical Parity diference is = 0.18154761904761907\nIndividual Fairness is = [0.701]\nDisparate Impact is = 1.7093023255813955\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.725\nThe Statistical Parity diference is = 0.08001768346595933\nIndividual Fairness is = [0.727]\nDisparate Impact is = 1.262699564586357\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.725\nThe Statistical Parity diference is = 0.11849029214298673\nIndividual Fairness is = [0.736]\nDisparate Impact is = 1.4301712779973648\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.67\nThe Statistical Parity diference is = 0.14857142857142858\nIndividual Fairness is = [0.739]\nDisparate Impact is = 1.5909090909090908\nParse progress: |█████████████████████████████████████████████████████████| 100%\nParse progress: |█████████████████████████████████████████████████████████| 100%\nglm Model Build progress: |███████████████████████████████████████████████| 100%\nglm prediction progress: |████████████████████████████████████████████████| 100%\nAccuracy 0.76\n"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
d08264a5dadca0d01e8309bea517270c73a725c7 | 98,887 | ipynb | Jupyter Notebook | examples/experimental_notebooks/Working Group Emails and Drafts-httpbis.ipynb | Christovis/bigbang | 304dd26faa869be2b78d4adaac4a5fdc1b92d287 | [
"MIT"
] | 71 | 2016-10-08T18:42:39.000Z | 2022-03-10T10:06:53.000Z | examples/experimental_notebooks/Working Group Emails and Drafts-httpbis.ipynb | Christovis/bigbang | 304dd26faa869be2b78d4adaac4a5fdc1b92d287 | [
"MIT"
] | 307 | 2016-07-10T17:37:41.000Z | 2022-03-31T16:39:33.000Z | examples/experimental_notebooks/Working Group Emails and Drafts-httpbis.ipynb | Christovis/bigbang | 304dd26faa869be2b78d4adaac4a5fdc1b92d287 | [
"MIT"
] | 21 | 2016-10-07T23:49:50.000Z | 2022-02-08T17:25:22.000Z | 125.810433 | 70,988 | 0.86346 | [
[
[
"This notebook compares the email activities and draft activites of an IETF working group.",
"_____no_output_____"
],
[
"Import the BigBang modules as needed. These should be in your Python environment if you've installed BigBang correctly.",
"_____no_output_____"
]
],
[
[
"import bigbang.mailman as mailman\nfrom bigbang.parse import get_date\n#from bigbang.functions import *\nfrom bigbang.archive import Archive\n\nfrom ietfdata.datatracker import *",
"/home/sb/projects/bigbang-multi/bigbang/config/config.py:8: YAMLLoadWarning: calling yaml.load() without Loader=... is deprecated, as the default Loader is unsafe. Please read https://msg.pyyaml.org/load for full details.\n dictionary = yaml.load(stream)\n"
]
],
[
[
"Also, let's import a number of other dependencies we'll use later.",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport datetime\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math\nimport pytz\nimport pickle\nimport os",
"_____no_output_____"
]
],
[
[
"## Load the HRPC Mailing List\n\nNow let's load the email data for analysis.",
"_____no_output_____"
]
],
[
[
"wg = \"httpbisa\"\n\nurls = [wg]\n\narchives = [Archive(url,mbox=True) for url in urls]\n\nactivities = [arx.get_activity(resolved=False) for arx in archives]\nactivity = activities[0]",
"/home/sb/projects/bigbang-multi/bigbang/bigbang/mailman.py:157: UserWarning: No mailing list name found at httpbisa\n warnings.warn(\"No mailing list name found at %s\" % url)\n"
]
],
[
[
"## Load IETF Draft Data\n\nNext, we will use the `ietfdata` tracker to look at the frequency of drafts for this working group.",
"_____no_output_____"
]
],
[
[
"import glob\n\npath = '../../archives/datatracker/httpbis/draft_metadata.csv' # use your path\n\ndraft_df = pd.read_csv(path, index_col=None, header=0, parse_dates=['date'])",
"_____no_output_____"
]
],
[
[
"We will want to use the data of the drafts. Time resolution is too small.",
"_____no_output_____"
]
],
[
[
"draft_df['date'] = draft_df['date'].dt.date",
"_____no_output_____"
]
],
[
[
"## Gender score and tendency measures\n\nThis notebook uses the (notably imperfect) method of using first names to guess the gender of each draft author.",
"_____no_output_____"
]
],
[
[
"from gender_detector import gender_detector as gd\ndetector = gd.GenderDetector('us')\n\ndef gender_score(name):\n \"\"\"\n Takes a full name and returns a score for the guessed\n gender.\n \n 1 - male\n 0 - female\n .5 - unknown\n \"\"\"\n try:\n first_name = name.split(\" \")[0]\n guess = detector.guess(first_name)\n score = 0\n if guess == \"male\":\n return 1.0\n elif guess == \"female\":\n return 0.0\n else:\n # name does not have confidence to guesss\n return 0.5\n except:\n # Some error, \"unknown\"\n return .5",
"_____no_output_____"
]
],
[
[
"## Gender guesses on mailing list activity\n\nNow to use the gender guesser to track the contributions by differently gendered participants over time.",
"_____no_output_____"
]
],
[
[
"from bigbang.parse import clean_name",
"_____no_output_____"
],
[
"gender_activity = activity.groupby(\n by=lambda x: gender_score(clean_name(x)),\n axis=1).sum().rename({0.0 : \"women\", 0.5 : \"unknown\", 1.0 : \"men\"},\n axis=\"columns\")",
"_____no_output_____"
]
],
[
[
"Note that our gender scoring method currently is unable to get a clear guess for a large percentage of the emails!",
"_____no_output_____"
]
],
[
[
"print(\"%f.2 percent of emails are from an unknown gender.\" \\\n % (gender_activity[\"unknown\"].sum() / gender_activity.sum().sum()))\n\nplt.bar([\"women\",\"unknown\",\"men\"],gender_activity.sum())\nplt.title(\"Total emails sent by guessed gender\")",
"0.394629.2 percent of emails are from an unknown gender.\n"
]
],
[
[
"## Plotting\n\nSome preprocessing is necessary to get the drafts data ready for plotting.",
"_____no_output_____"
]
],
[
[
"from matplotlib import cm\n\nviridis = cm.get_cmap('viridis')",
"_____no_output_____"
],
[
"drafts_per_day = draft_df.groupby('date').count()['title']",
"_____no_output_____"
],
[
"dpd_log = drafts_per_day.apply(lambda x: np.log1p(x))",
"_____no_output_____"
]
],
[
[
"For each of the mailing lists we are looking at, plot the rolling average (over `window`) of number of emails sent per day.\n\nThen plot a vertical line with the height of the drafts count and colored by the gender tendency.",
"_____no_output_____"
]
],
[
[
"window = 100",
"_____no_output_____"
],
[
"plt.figure(figsize=(12, 6))\n\nfor i, gender in enumerate(gender_activity.columns):\n\n colors = [viridis(0), viridis(.5), viridis(.99)]\n\n ta = gender_activity[gender]\n rmta = ta.rolling(window).mean()\n rmtadna = rmta.dropna()\n plt.plot_date(np.array(rmtadna.index),\n np.array(rmtadna.values),\n color = colors[i],\n linestyle = '-', marker = None,\n label='%s email activity - %s' % (wg, gender),\n xdate=True)\n\n\nvax = plt.vlines(drafts_per_day.index,\n 0,\n drafts_per_day,\n colors = 'r', # draft_gt_per_day,\n cmap = 'viridis',\n label=f'{wg} drafts ({drafts_per_day.sum()} total)'\n )\n\nplt.legend()\nplt.title(\"%s working group emails and drafts\" % (wg))\n#plt.colorbar(vax, label = \"more womanly <-- Gender Tendency --> more manly\")\n\n#plt.savefig(\"activites-marked.png\")\n#plt.show()",
"_____no_output_____"
]
],
[
[
"### Is gender diversity correlated with draft output?\n\n",
"_____no_output_____"
]
],
[
[
"from scipy.stats import pearsonr\nimport pandas as pd\n\ndef calculate_pvalues(df):\n df = df.dropna()._get_numeric_data()\n dfcols = pd.DataFrame(columns=df.columns)\n pvalues = dfcols.transpose().join(dfcols, how='outer')\n for r in df.columns:\n for c in df.columns:\n pvalues[r][c] = round(pearsonr(df[r], df[c])[1], 4)\n return pvalues",
"_____no_output_____"
],
[
"drafts_per_ordinal_day = pd.Series({x[0].toordinal(): x[1] for x in drafts_per_day.items()})",
"_____no_output_____"
],
[
"drafts_per_ordinal_day",
"_____no_output_____"
],
[
"ta.rolling(window).mean()",
"_____no_output_____"
],
[
"garm = np.log1p(gender_activity.rolling(window).mean())",
"_____no_output_____"
],
[
"garm['diversity'] = (garm['unknown'] + garm['women']) / garm['men']",
"_____no_output_____"
],
[
"garm['drafts'] = drafts_per_ordinal_day\ngarm['drafts'] = garm['drafts'].fillna(0)",
"_____no_output_____"
],
[
"garm.corr(method='pearson')",
"_____no_output_____"
],
[
"calculate_pvalues(garm)",
"_____no_output_____"
]
],
[
[
"Some variations...",
"_____no_output_____"
]
],
[
[
"garm_dna = garm.dropna(subset=['drafts'])",
"_____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",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
d0828b0f2a18c786a84b0160ffd08cc61d977727 | 312,284 | ipynb | Jupyter Notebook | src_yolov5/kalman_utils/.ipynb_checkpoints/visualize_3d_points-ball3-checkpoint.ipynb | diddytpq/Tennisball-Tracking-in-Video | 86fbd156f8f4f2502cd5bb766dfa6b3736e72aa6 | [
"MIT"
] | null | null | null | src_yolov5/kalman_utils/.ipynb_checkpoints/visualize_3d_points-ball3-checkpoint.ipynb | diddytpq/Tennisball-Tracking-in-Video | 86fbd156f8f4f2502cd5bb766dfa6b3736e72aa6 | [
"MIT"
] | null | null | null | src_yolov5/kalman_utils/.ipynb_checkpoints/visualize_3d_points-ball3-checkpoint.ipynb | diddytpq/Tennisball-Tracking-in-Video | 86fbd156f8f4f2502cd5bb766dfa6b3736e72aa6 | [
"MIT"
] | 1 | 2021-09-28T05:12:58.000Z | 2021-09-28T05:12:58.000Z | 222.583036 | 256,369 | 0.880401 | [
[
[
"# Visualize 3D Points (Parabolic data)\nThis notebook uses 3D plots to visualize 3D points. Reads measurement data from a csv file.",
"_____no_output_____"
]
],
[
[
"%matplotlib notebook\n##%matplotlib inline\nfrom mpl_toolkits import mplot3d\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom filter.kalman import Kalman3D\n\nfmt = lambda x: \"%9.3f\" % x\nnp.set_printoptions(formatter={'float_kind':fmt})\n\n## Read from csv file\nimport pandas as pd\n",
"_____no_output_____"
]
],
[
[
"## Read and Prepare Data\nRead ball tracking position data from saved CSV file and prepare mx,my,mz. The file should have dT values along with X,Y,Z values.\n\nWe use these as measurements and use Kalman3D tracker to track the ball. Once we exhaust all measurements, we use Kalman3D to predict rest of the trajectory.\n*Note*: The position data that we are using is in millimeters and milliseconds. However, the Kalman3D tracker uses all values in meters and seconds. We have do to this conversion here.",
"_____no_output_____"
]
],
[
[
"# File containing 3D points predicted and measured. Last column with time passage will be ignored\nSYNTH = False\n\nif SYNTH:\n data_ = pd.read_csv('data/datafile_parabolic.csv') ## Synthetic data\nelse:\n data_ = pd.read_csv('data/input_positions_3.csv') ## Real data\nprint(data_.keys())\ndata = data_/1000.\n_mx = np.float32(data['mx'])\n_my = np.float32(data['my'])\n_mz = np.float32(data['mz'])\nif SYNTH:\n ## Drop useless data\n mx = _mx[0:19]\n my = _my[0:19]\n mz = _mz[0:19]\nelse:\n mx = _mx\n my = _my\n mz = _mz\nprint(\"mx: {} {}\".format(mx.shape, mx))\nprint(\"my: {} {}\".format(my.shape, my))\nprint(\"mz: {} {}\".format(mz.shape, mz))\n\ndef getpos(i, x,y,z):\n return(np.float32([x[i],y[i],z[i]]))",
"Index(['mx', 'my', 'mz'], dtype='object')\nmx: (29,) [ 1.431 1.424 1.417 1.407 1.402 1.384 1.381\n 1.372 1.362 1.358 1.349 1.345 1.338 1.327\n 1.325 1.316 1.314 1.304 1.296 1.291 1.283\n 1.273 1.267 1.261 1.253 1.244 1.239 1.233\n 1.224]\nmy: (29,) [ 0.430 0.472 0.513 0.549 0.586 0.650 0.684\n 0.715 0.745 0.768 0.789 0.811 0.825 0.848\n 0.864 0.880 0.893 0.900 0.900 0.913 0.919\n 0.927 0.931 0.934 0.937 0.927 0.926 0.926\n 0.917]\nmz: (29,) [ 4.151 4.282 4.406 4.550 4.681 4.946 5.083\n 5.202 5.331 5.465 5.594 5.721 5.859 5.976\n 6.106 6.220 6.339 6.481 6.628 6.737 6.861\n 6.976 7.095 7.218 7.332 7.488 7.595 7.706\n 7.834]\n"
],
[
"mx",
"_____no_output_____"
]
],
[
[
"## Track and Predict\nNow we use our Kalman3D tracker to track the position of the ball based on measured data and then predict the trajectory when all measurement data is exhausted.",
"_____no_output_____"
]
],
[
[
"fps = 100.\ndT = (1 / fps)\nprint(\"dT: {:f}\".format(dT))\nKF = Kalman3D(drg=1.0, dbg=0)\npred = KF.init(getpos(0,mx,my,mz))\nprint(\"pred: {}\".format(pred))\n##-#######################################################################################\n## Tracking\n## Since we are doing all operations in zero time, specify dT manually (e.g., 0.033 sec)\npx = np.float32([pred[0]])\npy = np.float32([pred[1]])\npz = np.float32([pred[2]])\nfor i in range(len(mx)-1):\n pred = KF.track(getpos([i+1], mx, my, mz), dT)\n px = np.append(px, pred[0])\n py = np.append(py, pred[1])\n pz = np.append(pz, pred[2])\n print(\" tracked position : {}\".format(pred*1000))\n\n##-#######################################################################################\n## Trajectory prediction\n## Since we are doing all operations in zero time, specify dT manually (e.g., 0.033 sec)\nfor ii in range(15):\n pred = KF.predict(dT) # Use last value of dT for all predictions\n px = np.append(px, pred[0])\n py = np.append(py, pred[1])\n pz = np.append(pz, pred[2])\n print(\"predicted position : {}\".format(pred*1000))",
"dT: 0.010000\npred: [ 1.431 0.430 4.151]\n tracked position : [ 1429.714 442.714 4189.143]\n tracked position : [ 1425.120 471.396 4278.191]\n tracked position : [ 1417.502 505.861 4401.273]\n tracked position : [ 1410.771 542.338 4532.719]\n tracked position : [ 1398.548 592.156 4730.136]\n tracked position : [ 1390.440 635.028 4902.886]\n tracked position : [ 1381.709 672.708 5053.579]\n tracked position : [ 1372.141 707.147 5197.214]\n tracked position : [ 1365.022 736.481 5339.557]\n tracked position : [ 1356.791 762.105 5478.817]\n tracked position : [ 1350.411 786.236 5615.423]\n tracked position : [ 1343.558 805.635 5755.973]\n tracked position : [ 1334.472 826.947 5888.173]\n tracked position : [ 1328.659 845.829 6022.211]\n tracked position : [ 1321.131 863.407 6149.140]\n tracked position : [ 1316.185 878.791 6274.603]\n tracked position : [ 1308.629 889.998 6410.663]\n tracked position : [ 1300.682 895.459 6554.782]\n tracked position : [ 1294.042 904.389 6683.968]\n tracked position : [ 1286.603 911.681 6812.532]\n tracked position : [ 1277.738 919.121 6936.099]\n tracked position : [ 1270.137 924.641 7058.887]\n tracked position : [ 1263.223 928.648 7183.169]\n tracked position : [ 1255.675 931.868 7303.605]\n tracked position : [ 1247.289 928.124 7443.110]\n tracked position : [ 1240.487 925.238 7567.936]\n tracked position : [ 1234.032 923.357 7686.828]\n tracked position : [ 1226.249 917.495 7811.079]\npredicted position : [ 1220.591 911.119 7913.681]\npredicted position : [ 1214.933 903.764 8016.282]\npredicted position : [ 1209.274 895.428 8118.883]\npredicted position : [ 1203.616 886.113 8221.484]\npredicted position : [ 1197.958 875.817 8324.085]\npredicted position : [ 1192.300 864.542 8426.687]\npredicted position : [ 1186.641 852.287 8529.287]\npredicted position : [ 1180.983 839.052 8631.889]\npredicted position : [ 1175.325 824.836 8734.489]\npredicted position : [ 1169.667 809.641 8837.091]\npredicted position : [ 1164.008 793.466 8939.691]\npredicted position : [ 1158.350 776.311 9042.293]\npredicted position : [ 1152.692 758.175 9144.894]\npredicted position : [ 1147.033 739.060 9247.495]\npredicted position : [ 1141.375 718.965 9350.096]\n"
],
[
"x, y, z = 10, 10 ,10",
"_____no_output_____"
],
[
"x, y, z = 5, 8 ,2",
"_____no_output_____"
],
[
"x, y, z = 53, 18 ,12",
"_____no_output_____"
],
[
"fps = 100.\ndT = (1 / fps)\nprint(\"dT: {:f}\".format(dT))\nKF = Kalman3D(drg=1.0, dbg=0)\npred = KF.init(np.float32([x,y,z]))",
"dT: 0.010000\n"
],
[
"print(\"predicted position : {}\".format(pred))",
"predicted position : [ 30.803 13.640 9.870]\n"
],
[
"pred = KF.track(np.float32([x,y,z]), dT)",
"_____no_output_____"
],
[
"pred = KF.predict(dT)",
"_____no_output_____"
],
[
"sum = 0\ntm = np.zeros(len(px))\nfor i in range(len(tm)):\n sum += dT\n tm[i] = sum\n\n## Convert mx also back to millimeters.\npx = px * 1000.\npy = py * 1000.\npz = pz * 1000.\nnmx = mx * 1000.\nnmy = my * 1000.\nnmz = mz * 1000.\nntm = tm * 1000.\n##-#######################################################################################\n## Everything is in millimeters and milliseconds now\n##-#######################################################################################\nprint(\"px size\", px.shape)\nprint(\"tm size\", tm.shape)\n\n## Visualize X, Y, and Z individually\n## In the plot below, we visualize the pairs of px, mx; py, my and pz, mz to see how they relate to each other\nprint(\"PX, MX\")\nfig1a = plt.figure()\nplt.plot(tm, px)\nplt.plot(tm[0:len(nmx)], nmx)\nplt.legend('PM', ncol=1, loc='upper left')\n\nprint(\"PY, MY\")\nfig1b = plt.figure()\nplt.plot(tm, py)\nplt.plot(tm[0:len(nmy)], nmy)\nplt.legend('PM', ncol=1, loc='upper left')\n\nprint(\"PZ, MZ\")\nfig1c = plt.figure()\nplt.plot(tm, pz)\nplt.plot(tm[0:len(nmz)], nmz)\nplt.legend('PM', ncol=1, loc='upper left')",
"_____no_output_____"
]
],
[
[
"## Visualize (X,Y,Z) of Predicted and Measured in Points in 3D\nIn the plot below, we visualize all the predicted and measured points in 3D. This gives a more realistic view of how the predicted points are related to the measured points.",
"_____no_output_____"
]
],
[
[
"fig2 = plt.figure()\nax = plt.axes(projection='3d')\n#ax.set_xlim3d(-2000,2000)\n#ax.set_ylim3d(-2000,2000)\n#ax.set_zlim3d(-2000,2000)\n\nif 0: ## Plot axis or not\n st = [0,0,0]\n xx = [200, 0, 0]\n yy = [ 0, 200, 0]\n zz =[ 0, 0, 200]\n for i in range(len(st)):\n ax.plot([st[i], xx[i]], [st[i],yy[i]],zs=[st[i],zz[i]])\n\nax.plot3D(px, py, pz, 'blue')\nax.plot3D(nmx, nmy, nmz, 'magenta')\n",
"_____no_output_____"
],
[
"\n\n\nclass Kalman_filiter():\n\n def __init__(self, x_init, y_init, z_init, dT):\n self.KF = Kalman3D(drg=0.507, dbg=4)\n\n self.dT = dT\n\n self.pred = self.KF.init(np.float32([x_init, y_init, z_init]))\n\n\n\n def update(self, x, y, z, dT):\n\n self.dT = dT\n self.pred = self.KF.track(np.float32([x, y, z]), self.dT)\n\n\n def get_predict(self, dT):\n self.pred = self.KF.predict(dT)\n\n\n",
"_____no_output_____"
],
[
"x,y,z = [-7.923465928004007, -0.6755867599611189, 2.580941671512611]",
"_____no_output_____"
],
[
"a = Kalman_filiter(x,y,z,0.04)\nprint(a.pred)",
"nstates 7\ntransitionMatrix: shape:(7, 7)\n[[ 1.000 0.000 0.000 0.000 0.000 0.000 0.000]\n [ 0.000 1.000 0.000 0.000 0.000 0.000 0.000]\n [ 0.000 0.000 1.000 0.000 0.000 0.000 0.000]\n [ 0.000 0.000 0.000 0.507 0.000 0.000 0.000]\n [ 0.000 0.000 0.000 0.000 0.507 0.000 0.000]\n [ 0.000 0.000 0.000 0.000 0.000 0.507 0.000]\n [ 0.000 0.000 0.000 0.000 0.000 0.000 1.000]]\nmeasurementMatrix: shape:(3, 7)\n[[ 1.000 0.000 0.000 0.000 0.000 0.000 0.000]\n [ 0.000 1.000 0.000 0.000 0.000 0.000 0.000]\n [ 0.000 0.000 1.000 0.000 0.000 0.000 0.000]]\nprocessNoiseCov: shape:(7, 7)\n[[ 0.100 0.000 0.000 0.000 0.000 0.000 0.000]\n [ 0.000 0.100 0.000 0.000 0.000 0.000 0.000]\n [ 0.000 0.000 0.100 0.000 0.000 0.000 0.000]\n [ 0.000 0.000 0.000 8.000 0.000 0.000 0.000]\n [ 0.000 0.000 0.000 0.000 8.000 0.000 0.000]\n [ 0.000 0.000 0.000 0.000 0.000 8.000 0.000]\n [ 0.000 0.000 0.000 0.000 0.000 0.000 0.100]]\nmeasurementNoiseCov: shape:(3, 3)\n[[ 0.010 0.000 0.000]\n [ 0.000 0.010 0.000]\n [ 0.000 0.000 0.010]]\nstatePost: shape:(7, 1)\n[[ -7.923]\n [ -0.676]\n [ 2.581]\n [ 0.100]\n [ 0.100]\n [ 0.100]\n [ 9.801]]\n[ -7.923 -0.676 2.581]\n"
],
[
"a.update(x,y,z,0.04)\n\nprint(a.pred)\n\na.get_predict(0.04)\nprint(a.pred)\n",
"dT: 0.0400\n---------------------------------------------------\nmeas current : [ -5.810 -0.418 2.328]\npred predicted : [ -5.965 -0.436 2.346]\n\n[ -5.965 -0.436 2.346]\ndT: 0.0400\n---------------------------------------------------\nmeas current : None (only predicting)\npred predicted without meas: [ -5.836 -0.434 2.333]\n\n[ -5.836 -0.434 2.333]\n"
],
[
"x,y,z = [-5.810376800248608, -0.4175195849390212, 2.3275454429899285]",
"_____no_output_____"
],
[
"a.KF.measNoise",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"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",
"code"
]
] |
d0828f510b01be6c9b5d0fff4a7b5b6dcb25dc37 | 3,706 | ipynb | Jupyter Notebook | Chapter_4/Chapter_4-1.ipynb | YutaIzumi/python-app-book | cea81385041c992fadcbef40126b43fd6fbcc3f3 | [
"MIT"
] | null | null | null | Chapter_4/Chapter_4-1.ipynb | YutaIzumi/python-app-book | cea81385041c992fadcbef40126b43fd6fbcc3f3 | [
"MIT"
] | null | null | null | Chapter_4/Chapter_4-1.ipynb | YutaIzumi/python-app-book | cea81385041c992fadcbef40126b43fd6fbcc3f3 | [
"MIT"
] | null | null | null | 21.672515 | 79 | 0.490286 | [
[
[
"# Chapter4: 実践的なアプリケーションを作ってみよう",
"_____no_output_____"
],
[
"### 4.1 アプリケーションランチャーを作ってみよう① \n### 4.1.1 設定ファイルの保存・呼出し",
"_____no_output_____"
]
],
[
[
"# リスト4.1.1: 設定ファイルの生成\n# configparserのインポート\nimport configparser\n\n# インスタンス化\nconfig = configparser.ConfigParser()\n# 設定ファイルの内容\nconfig[\"Run1\"] = {\n \"app1\": r\"C:\\WINDOWS\\system32\\notepad.exe\",\n \"app2\": r\"C:\\Program Files\\Internet Explorer\\iexplore.exe\"\n}\n# 設定ファイルへ書込み\nwith open(\"config.ini\", \"w+\") as file:\n config.write(file)",
"_____no_output_____"
]
],
[
[
"#### ※ Macの場合",
"_____no_output_____"
]
],
[
[
"##### Macの場合 #####\n# リスト4.1.1: 設定ファイルの生成 \n# configparserのインポート\nimport configparser\n\n# インスタンス化\nconfig = configparser.ConfigParser()\n# 設定ファイルの内容\nconfig[\"Run1\"] = {\n \"app1\": \"/Applications/TextEdit.app\",\n \"app2\": \"/Applications/Safari.app\"\n}\n# 設定ファイルへ書込み\nwith open(\"config.ini\", \"w+\") as file:\n config.write(file)",
"_____no_output_____"
],
[
"# リスト4.1.2: 設定ファイル(config.ini)\n[Run1]\napp1 = C:\\WINDOWS\\system32\\notepad.exe\napp2 = C:\\Program Files\\Internet Explorer\\iexplore.exe\n",
"_____no_output_____"
],
[
"# リスト4.1.3: セクション, 変数の追加例\n# 設定ファイルの内容\nconfig[\"Run1\"] = {\n \"app1\": r\"C:\\WINDOWS\\system32\\notepad.exe\",\n \"app2\": r\"C:\\Program Files\\Internet Explorer\\iexplore.exe\"\n}\n\nconfig[\"Run2\"] = {\n \"app1\": r\"C:\\WINDOWS\\system32\\notepad.exe\",\n \"app2\": r\"C:\\Program Files\\Internet Explorer\\iexplore.exe\",\n \"app3\": r\"C:\\WINDOWS\\system32\\mspaint.exe\"\n}",
"_____no_output_____"
],
[
"# リスト4.1.4: 設定の呼出し\n# 読込む設定ファイルを指定\nconfig.read(\"config.ini\")\n# 設定ファイルから値の取得\nread_base = config[\"Run1\"]\nprint(read_base.get(\"app1\"))",
"/Applications/TextEdit.app\n"
],
[
"print(read_base.get(\"app2\"))",
"/Applications/Safari.app\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
d08297fcff0ed9ea249b4956f1e1e6153703b8fa | 27,569 | ipynb | Jupyter Notebook | _notebooks/2020-02-20-test.ipynb | mudit1729/Blog | 89a71c15340a387cbc679e1f67a3c6ed8fdbb93b | [
"Apache-2.0"
] | 1 | 2019-01-15T02:30:38.000Z | 2019-01-15T02:30:38.000Z | _notebooks/2020-02-20-test.ipynb | mudit1729/Blog | 89a71c15340a387cbc679e1f67a3c6ed8fdbb93b | [
"Apache-2.0"
] | 2 | 2021-09-28T01:02:08.000Z | 2022-02-26T06:46:40.000Z | _notebooks/2020-02-20-test.ipynb | mudit1729/muditj | 175d59c3698cef11572b6ffddf10274dfa6dba90 | [
"Apache-2.0"
] | null | null | null | 37.869505 | 2,126 | 0.504552 | [
[
[
"# Fastpages Notebook Blog Post\n> A tutorial of fastpages for Jupyter notebooks.\n\n- toc: true \n- badges: true\n- comments: true\n- categories: [jupyter]\n- image: images/chart-preview.png",
"_____no_output_____"
],
[
"# About\n\nThis notebook is a demonstration of some of capabilities of [fastpages](https://github.com/fastai/fastpages) with notebooks.\n\n\nWith `fastpages` you can save your jupyter notebooks into the `_notebooks` folder at the root of your repository, and they will be automatically be converted to Jekyll compliant blog posts!",
"_____no_output_____"
],
[
"## Front Matter\n\nFront Matter is a markdown cell at the beginning of your notebook that allows you to inject metadata into your notebook. For example:\n\n- Setting `toc: true` will automatically generate a table of contents\n- Setting `badges: true` will automatically include GitHub and Google Colab links to your notebook.\n- Setting `comments: true` will enable commenting on your blog post, powered by [utterances](https://github.com/utterance/utterances).\n\nMore details and options for front matter can be viewed on the [front matter section](https://github.com/fastai/fastpages#front-matter-related-options) of the README.",
"_____no_output_____"
],
[
"## Markdown Shortcuts",
"_____no_output_____"
],
[
"A `#hide` comment at the top of any code cell will hide **both the input and output** of that cell in your blog post.\n\nA `#hide_input` comment at the top of any code cell will **only hide the input** of that cell.",
"_____no_output_____"
]
],
[
[
"#hide_input\nprint('The comment #hide_input was used to hide the code that produced this.\\n')",
"The comment #hide_input was used to hide the code that produced this.\n\n"
]
],
[
[
"put a `#collapse-hide` flag at the top of any cell if you want to **hide** that cell by default, but give the reader the option to show it:",
"_____no_output_____"
]
],
[
[
"#collapse-hide\nimport pandas as pd\nimport altair as alt",
"_____no_output_____"
]
],
[
[
"put a `#collapse-show` flag at the top of any cell if you want to **show** that cell by default, but give the reader the option to hide it:",
"_____no_output_____"
]
],
[
[
"#collapse-show\ncars = 'https://vega.github.io/vega-datasets/data/cars.json'\nmovies = 'https://vega.github.io/vega-datasets/data/movies.json'\nsp500 = 'https://vega.github.io/vega-datasets/data/sp500.csv'\nstocks = 'https://vega.github.io/vega-datasets/data/stocks.csv'\nflights = 'https://vega.github.io/vega-datasets/data/flights-5k.json'",
"_____no_output_____"
]
],
[
[
"## Interactive Charts With Altair\n\nCharts made with Altair remain interactive. Example charts taken from [this repo](https://github.com/uwdata/visualization-curriculum), specifically [this notebook](https://github.com/uwdata/visualization-curriculum/blob/master/altair_interaction.ipynb).",
"_____no_output_____"
]
],
[
[
"# hide\ndf = pd.read_json(movies) # load movies data\ngenres = df['Major_Genre'].unique() # get unique field values\ngenres = list(filter(lambda d: d is not None, genres)) # filter out None values\ngenres.sort() # sort alphabetically",
"_____no_output_____"
],
[
"#hide\nmpaa = ['G', 'PG', 'PG-13', 'R', 'NC-17', 'Not Rated']",
"_____no_output_____"
]
],
[
[
"### Example 1: DropDown",
"_____no_output_____"
]
],
[
[
"# single-value selection over [Major_Genre, MPAA_Rating] pairs\n# use specific hard-wired values as the initial selected values\nselection = alt.selection_single(\n name='Select',\n fields=['Major_Genre', 'MPAA_Rating'],\n init={'Major_Genre': 'Drama', 'MPAA_Rating': 'R'},\n bind={'Major_Genre': alt.binding_select(options=genres), 'MPAA_Rating': alt.binding_radio(options=mpaa)}\n)\n \n# scatter plot, modify opacity based on selection\nalt.Chart(movies).mark_circle().add_selection(\n selection\n).encode(\n x='Rotten_Tomatoes_Rating:Q',\n y='IMDB_Rating:Q',\n tooltip='Title:N',\n opacity=alt.condition(selection, alt.value(0.75), alt.value(0.05))\n)",
"_____no_output_____"
]
],
[
[
"### Example 2: Tooltips",
"_____no_output_____"
]
],
[
[
"alt.Chart(movies).mark_circle().add_selection(\n alt.selection_interval(bind='scales', encodings=['x'])\n).encode(\n x='Rotten_Tomatoes_Rating:Q',\n y=alt.Y('IMDB_Rating:Q', axis=alt.Axis(minExtent=30)), # use min extent to stabilize axis title placement\n tooltip=['Title:N', 'Release_Date:N', 'IMDB_Rating:Q', 'Rotten_Tomatoes_Rating:Q']\n).properties(\n width=600,\n height=400\n)",
"_____no_output_____"
]
],
[
[
"### Example 3: More Tooltips",
"_____no_output_____"
]
],
[
[
"# select a point for which to provide details-on-demand\nlabel = alt.selection_single(\n encodings=['x'], # limit selection to x-axis value\n on='mouseover', # select on mouseover events\n nearest=True, # select data point nearest the cursor\n empty='none' # empty selection includes no data points\n)\n\n# define our base line chart of stock prices\nbase = alt.Chart().mark_line().encode(\n alt.X('date:T'),\n alt.Y('price:Q', scale=alt.Scale(type='log')),\n alt.Color('symbol:N')\n)\n\nalt.layer(\n base, # base line chart\n \n # add a rule mark to serve as a guide line\n alt.Chart().mark_rule(color='#aaa').encode(\n x='date:T'\n ).transform_filter(label),\n \n # add circle marks for selected time points, hide unselected points\n base.mark_circle().encode(\n opacity=alt.condition(label, alt.value(1), alt.value(0))\n ).add_selection(label),\n\n # add white stroked text to provide a legible background for labels\n base.mark_text(align='left', dx=5, dy=-5, stroke='white', strokeWidth=2).encode(\n text='price:Q'\n ).transform_filter(label),\n\n # add text labels for stock prices\n base.mark_text(align='left', dx=5, dy=-5).encode(\n text='price:Q'\n ).transform_filter(label),\n \n data=stocks\n).properties(\n width=700,\n height=400\n)",
"_____no_output_____"
]
],
[
[
"## Data Tables\n\nYou can display tables per the usual way in your blog:",
"_____no_output_____"
]
],
[
[
"movies = 'https://vega.github.io/vega-datasets/data/movies.json'\ndf = pd.read_json(movies)\n# display table with pandas\ndf[['Title', 'Worldwide_Gross', \n 'Production_Budget', 'IMDB_Rating']].head()",
"_____no_output_____"
]
],
[
[
"## Images\n\n### Local Images\n\nYou can reference local images and they will be copied and rendered on your blog automatically. You can include these with the following markdown syntax:\n\n``",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"### Remote Images\n\nRemote images can be included with the following markdown syntax:\n\n``",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"### Animated Gifs\n\nAnimated Gifs work, too!\n\n``",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"### Captions\n\nYou can include captions with markdown images like this:\n\n```\n\n```\n\n\n\n\n\n\n",
"_____no_output_____"
],
[
"# Other Elements",
"_____no_output_____"
],
[
"## Tweetcards\n\nTyping `> twitter: https://twitter.com/jakevdp/status/1204765621767901185?s=20` will render this:\n\n> twitter: https://twitter.com/jakevdp/status/1204765621767901185?s=20",
"_____no_output_____"
],
[
"## Youtube Videos\n\nTyping `> youtube: https://youtu.be/XfoYk_Z5AkI` will render this:\n\n\n> youtube: https://youtu.be/XfoYk_Z5AkI",
"_____no_output_____"
],
[
"## Boxes / Callouts \n\nTyping `> Warning: There will be no second warning!` will render this:\n\n\n> Warning: There will be no second warning!\n\n\n\nTyping `> Important: Pay attention! It's important.` will render this:\n\n> Important: Pay attention! It's important.\n\n\n\nTyping `> Tip: This is my tip.` will render this:\n\n> Tip: This is my tip.\n\n\n\nTyping `> Note: Take note of this.` will render this:\n\n> Note: Take note of this.\n\n\n\nTyping `> Note: A doc link to [an example website: fast.ai](https://www.fast.ai/) should also work fine.` will render in the docs:\n\n> Note: A doc link to [an example website: fast.ai](https://www.fast.ai/) should also work fine.",
"_____no_output_____"
],
[
"## Footnotes\n\nYou can have footnotes in notebooks just like you can with markdown. \n\nFor example, here is a footnote [^1].\n\n[^1]: This is the footnote.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
d08298faf4a271fed61e845513bc93d7780a5146 | 18,712 | ipynb | Jupyter Notebook | doc/coupling_to_ideal_load.ipynb | jhillairet/WEST_IC_antenna | adffcfdeeef074e1cf47db93dab07b5858a2aa0a | [
"MIT"
] | 2 | 2021-05-29T16:02:07.000Z | 2022-01-07T09:00:16.000Z | doc/coupling_to_ideal_load.ipynb | jhillairet/WEST_IC_antenna | adffcfdeeef074e1cf47db93dab07b5858a2aa0a | [
"MIT"
] | null | null | null | doc/coupling_to_ideal_load.ipynb | jhillairet/WEST_IC_antenna | adffcfdeeef074e1cf47db93dab07b5858a2aa0a | [
"MIT"
] | 1 | 2021-05-30T18:46:07.000Z | 2021-05-30T18:46:07.000Z | 31.448739 | 295 | 0.519239 | [
[
[
"# Coupling to Ideal Loads\nIn this notebook, we investigate the WEST ICRH antenna behaviour when the front-face is considered as the combination of ideal (and independant) loads made of impedances all equal to $Z_s=R_c+j X_s$, where $R_c$ corresponds to the coupling resistance and $X_s$ is the strap reactance. \n\n<img src=\"West_front_face_ideal.png\" width=\"300\"/>\n\nIn such case, the power delivered to the plasma/front-face is then:\n\n$$\nP_t \n= \\frac{1}{2} \\sum_{i=1}^4 \\Re[V_i I_i^* ] \n= \\frac{1}{2} \\sum_{i=1}^4 \\Re[Z_i] |I_i|^2\n= \\frac{1}{2} R_c \\sum_{i=1}^4 |I_i|^2\n$$\nHence, we have defined the coupling resistance as:\n\n$$\nR_c = \\frac{\\sum_{i=1}^4 \\Re[Z_i] |I_i|^2}{\\sum_{i=1}^4 |I_i|^2}\n$$\n\nInversely, the coupling resistance can be determine from:\n\n$$\nR_c = \\frac{2 P_t}{\\sum_{i=1}^4 |I_i|^2}\n$$\n\nIn practice however, it is easier to measure RF voltages than currents. \n\n$$\nI = \\frac{V}{Z_s} = \\frac{V}{R_c + j X_s} \n\\rightarrow \n|I|^2 = \\frac{|V|^2}{|R_c + j X_s|}\n\\approx\n\\frac{|V|^2}{|X_s|^2}\n$$\nsince in $|X_s|>>|R_c|$.\n\nThe antenna model allows to calculate the coupling resistance from currents (`.Rc()` method) or from the voltage (`.Rc_WEST()` method).\n\nThe strap reactance $X_s$ depends on the strap geometry and varies with the frequency. So, let's find how the strap reactance from the realistic CAD model. ",
"_____no_output_____"
]
],
[
[
"%matplotlib widget",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\nimport numpy as np\nimport skrf as rf\nfrom tqdm.notebook import tqdm\n\n# WEST ICRH Antenna package\nimport sys; sys.path.append('..')\nfrom west_ic_antenna import WestIcrhAntenna\n\n# styling the figures\nrf.stylely()",
"C:\\Users\\JH218595\\Documents\\scikit-rf\\skrf\\plotting.py:1441: UserWarning: Style includes a parameter, 'interactive', that is not related to style. Ignoring\n mpl.style.use(os.path.join(pwd, style_file))\n"
]
],
[
[
"## Coupling to an ideal front-face\nCoupling to an ideal front face of coupling resistance $R_c$ is easy using the the `.load()` method of the `WestIcrhAntenna` class. This method takes into account the strap reactance frequency fit (derived in [Strap Reactance Frequency Fit](./strap_reactance.ipynb)) ",
"_____no_output_____"
]
],
[
[
"freq = rf.Frequency(30, 70, npoints=1001, unit='MHz')\nant_ideal = WestIcrhAntenna(frequency=freq)\nant_ideal.load(Rc=1) # 1 Ohm coupling resistance front-face",
"_____no_output_____"
],
[
"# matching left and right sides : note that the solutions are (almost) the same\nf_match = 55.5e6\nC_left = ant_ideal.match_one_side(f_match=f_match, side='left')\nC_right = ant_ideal.match_one_side(f_match=f_match, side='right')",
"True solution #1: [53.56567365 45.98820709]\nTrue solution #1: [53.56564882 45.98822849]\n"
]
],
[
[
"At the difference of the \"real\" situation (see the [Matching](./matching.ipynb) or the [Coupling to a TOPICA plasma](./coupling_to_plasma_from_TOPICA.ipynb)), here is no poloidal neither toroidal coupling of the straps in this front-face model. This leads to:\n* Match soluitions are the same for both sides (within $10^{-3}$ pF). \n* Using the match solutions for each sides does not require to shift the operating frequency:",
"_____no_output_____"
]
],
[
[
"# dipole excitation\npower = [1, 1]\nphase = [0, rf.pi]\n\n# active S-parameter for the match point:\nC_match = [C_left[0], C_left[1], C_right[2], C_right[3]]\ns_act = ant_ideal.s_act(power, phase, Cs=C_match)\n\nfig, ax = plt.subplots()\nax.plot(ant_ideal.f_scaled, 20*np.log10(np.abs(s_act)), lw=2)\nax.legend(('$S_{act,1}$', '$S_{act,2}$'))\nax.grid(True)",
"_____no_output_____"
]
],
[
[
"## Match Points vs Coupling Resistance",
"_____no_output_____"
],
[
"Let's determine the match points for a range of coupling resistance at a given frequency",
"_____no_output_____"
]
],
[
[
"f_match = 55e6\nRcs = np.r_[0.01, 0.05, np.arange(0.1, 2.5, 0.2)]\n\nC_matchs = []\nant = WestIcrhAntenna()\nfor Rc in tqdm(Rcs):\n ant.load(Rc)\n C_match = ant.match_one_side(f_match=f_match)\n C_matchs.append(C_match)\n ",
"_____no_output_____"
]
],
[
[
"As the coupling resistance increases, the distance between capacitances (Top vs Bottom) increases: ",
"_____no_output_____"
]
],
[
[
"fig, ax = plt.subplots()\nax.plot(Rcs, np.array(C_matchs)[:,0:2], lw=2, marker='o')\nax.axhline(C_matchs[0][0], ls='--', color='C0')\nax.axhline(C_matchs[0][1], ls='--', color='C1')\nax.set_xlabel('Rc [Ohm]')\nax.set_ylabel('C [pF]')\nax.legend(('Top', 'Bot'))",
"_____no_output_____"
]
],
[
[
"Displayed differently, the distance between capacitances (Top - Bottom) versus coupling resistance is:",
"_____no_output_____"
]
],
[
[
"delta_C_pos = np.array(C_matchs)[:,0] - C_matchs[0][0]\ndelta_C_neg = C_matchs[0][1] - np.array(C_matchs)[:,1]\n\nfig, ax = plt.subplots()\nax.plot(Rcs, delta_C_pos, label='Top: + $\\Delta C$', lw=2)\nax.plot(Rcs, delta_C_neg, label='Bot: - $\\Delta C$', lw=2)\nax.set_xlabel('Rc [Ohm]')\nax.set_ylabel('$\\Delta C$ [pF]')\nax.set_ylim(bottom=0)\nax.set_xlim(left=0)\nax.legend()",
"_____no_output_____"
]
],
[
[
"## Load Resilience Curves\nIdeal loads is usefull to study the behaviour of the load tolerance property of the antenna and the capacitance match points. It is only necessary to work on half-antenna here, because there is no coupling between toroidal elements. ",
"_____no_output_____"
],
[
"Now that we have figured out the match points, let's vary the coupling resistances for a fixed match point and look to the return power (or VSWR): this will highlight the load resilience property of the antenna.",
"_____no_output_____"
]
],
[
[
"# create a single frequency point antenna to speed-up calculations\nant = WestIcrhAntenna(frequency=rf.Frequency.from_f(f_match, unit='Hz'))\n\nfig, ax = plt.subplots()\npower = [1, 1]\nphase = [0, np.pi]\n\nfor C_match in tqdm(C_matchs[0:8]):\n SWRs = []\n ant.Cs = [C_match[0], C_match[1], 150, 150]\n for Rc in Rcs:\n ant.load(Rc)\n SWR = ant.circuit().network.s_vswr.squeeze()[0,0]\n SWRs.append(SWR)\n ax.plot(Rcs, np.array(SWRs), lw=2)\n\nax.set_xlabel('Rc [Ohm]')\nax.set_ylabel('VSWR')\nax.set_ylim(1, 8)\nax.axhline(2, color='r')\nax.legend(Rcs)",
"_____no_output_____"
],
[
"from IPython.core.display import HTML\ndef _set_css_style(css_file_path):\n \"\"\"\n Read the custom CSS file and load it into Jupyter\n Pass the file path to the CSS file\n \"\"\"\n styles = open(css_file_path, \"r\").read()\n s = '<style>%s</style>' % styles\n return HTML(s)\n\n_set_css_style('custom.css')",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
d0829acb7301e267f2921ed1f77bbc49d3949d14 | 103,138 | ipynb | Jupyter Notebook | numpy/2-numpy-middle.ipynb | GmZhang3/data-science-ipython-notebooks | ab442df29eb917d4bee3e50b8ac294ff1263b14e | [
"Apache-2.0"
] | 1 | 2019-01-26T03:00:43.000Z | 2019-01-26T03:00:43.000Z | numpy/2-numpy-middle.ipynb | GmZhang3/data-science-ipython-notebooks | ab442df29eb917d4bee3e50b8ac294ff1263b14e | [
"Apache-2.0"
] | null | null | null | numpy/2-numpy-middle.ipynb | GmZhang3/data-science-ipython-notebooks | ab442df29eb917d4bee3e50b8ac294ff1263b14e | [
"Apache-2.0"
] | null | null | null | 47.463415 | 8,876 | 0.599013 | [
[
[
"# 数组基础",
"_____no_output_____"
],
[
"## 创建一个数组",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pdir\npdir(np)",
"_____no_output_____"
],
[
"import numpy as np\na1 = np.array([0, 1, 2, 3, 4])#将列表转换为数组,可以传递任何序列(类数组),而不仅仅是常见的列表(list)数据类型。\na2 = np.array((0, 1, 2, 3, 4))#将元组转换为数组\nprint 'a1:',a1,type(a1)\nprint 'a2:',a2,type(a2)",
"a1: [0 1 2 3 4] <type 'numpy.ndarray'>\na2: [0 1 2 3 4] <type 'numpy.ndarray'>\n"
],
[
"b = np.arange(5) #python内置函数range()的数组版,返回的是numpy ndarrays数组对象,而不是列表\nprint 'b:',b,type(b)",
"b: [0 1 2 3 4] <type 'numpy.ndarray'>\n"
],
[
"c1 = np.ones((3,4))#根据元组指定形状,返回全1数组\nc2 = np.ones_like(a1)#以另一个数组为参数,以其形状和dtype创建全1数组\nprint 'c1',c1,type(c1)\nprint 'c2',c2,type(c2)",
"c1 [[ 1. 1. 1. 1.]\n [ 1. 1. 1. 1.]\n [ 1. 1. 1. 1.]] <type 'numpy.ndarray'>\nc2 [1 1 1 1 1] <type 'numpy.ndarray'>\n"
],
[
"d1 = np.zeros((5,6))#根据元组指定形状,返回全0数组\nd2 = np.zeros_like(c1)#以另一个数组为参数,以其形状和dtype创建全0数组\nprint 'd1',d1,type(d1)\nprint 'd2',d2,type(d2)",
"d1 [[ 0. 0. 0. 0. 0. 0.]\n [ 0. 0. 0. 0. 0. 0.]\n [ 0. 0. 0. 0. 0. 0.]\n [ 0. 0. 0. 0. 0. 0.]\n [ 0. 0. 0. 0. 0. 0.]] <type 'numpy.ndarray'>\nd2 [[ 0. 0. 0. 0.]\n [ 0. 0. 0. 0.]\n [ 0. 0. 0. 0.]] <type 'numpy.ndarray'>\n"
],
[
"e1 = np.empty((2,3))#创建新数组,只分配内存空间但不填充任何值,不是返回0,而是未初始化的垃圾值\ne2 = np.empty_like(d1)#\nprint 'e1',e1,type(e1)\nprint 'e2',e2,type(e2)",
"e1 [[ 0. 0. 0.]\n [ 0. 0. 0.]] <type 'numpy.ndarray'>\ne2 [[ 0. 0. 0. 0. 0. 0.]\n [ 0. 0. 0. 0. 0. 0.]\n [ 0. 0. 0. 0. 0. 0.]\n [ 0. 0. 0. 0. 0. 0.]\n [ 0. 0. 0. 0. 0. 0.]] <type 'numpy.ndarray'>\n"
],
[
"f1 = np.eye(3)#创建一个正方的N*N单位矩阵对角线为1,其余为0()\nf2 = np.identity(4)#Return the identity array.\nprint 'f1',f1,type(f1)\nprint 'f2',f2,type(f2)",
"f1 [[ 1. 0. 0.]\n [ 0. 1. 0.]\n [ 0. 0. 1.]] <type 'numpy.ndarray'>\nf2 [[ 1. 0. 0. 0.]\n [ 0. 1. 0. 0.]\n [ 0. 0. 1. 0.]\n [ 0. 0. 0. 1.]] <type 'numpy.ndarray'>\n"
],
[
"g = np.linspace(0, 10, 5) #linspace: Return evenly spaced numbers over a specified interval.\nprint 'g',g,type(g)",
"g [ 0. 2.5 5. 7.5 10. ] <type 'numpy.ndarray'>\n"
]
],
[
[
"## 数组属性",
"_____no_output_____"
]
],
[
[
"a = np.array([[11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n [26, 27, 28 ,29, 30],\n [31, 32, 33, 34, 35]])\nprint(type(a)) #<type 'numpy.ndarray'>\nprint(a.dtype) #int32\nprint(a.size) #25 Return the number of elements along a given axis.\nprint(a.shape) #(5L, 5L),Return the shape of an array\nprint(a.itemsize) #4,itemsize输出array元素的字节数,本例32/8=4\nprint(a.ndim) #2,Return the number of dimensions of an array",
"<type 'numpy.ndarray'>\nint32\n25\n(5L, 5L)\n4\n2\n"
]
],
[
[
"# 使用数组\n数组可不必编写循环即可实现循环-数组的矢量化\n\n大小相等的数组之间的任何数学运算都会应用到元素级\n\n大小不相等的数组之间的运算-叫做广播",
"_____no_output_____"
],
[
"## 基本操作符-数组四则运算 +、- 、/ ",
"_____no_output_____"
]
],
[
[
"a = np.arange(25)\nprint 'a:',a,type(a)\na = a.reshape((5, 5))#Gives a new shape to an array without changing its data\nprint 'a:',a,type(a)",
"a: [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24] <type 'numpy.ndarray'>\na: [[ 0 1 2 3 4]\n [ 5 6 7 8 9]\n [10 11 12 13 14]\n [15 16 17 18 19]\n [20 21 22 23 24]] <type 'numpy.ndarray'>\n"
],
[
"b = np.array([10, 62, 1, 14, 2, 56, 79, 2, 1, 45,\n 4, 92, 5, 55, 63, 43, 35, 6, 53, 24,\n 56, 3, 56, 44, 78])\nprint b.shape\nb = b.reshape((5,5))\nprint 'b:',b,type(b)",
"(25L,)\nb: [[10 62 1 14 2]\n [56 79 2 1 45]\n [ 4 92 5 55 63]\n [43 35 6 53 24]\n [56 3 56 44 78]] <type 'numpy.ndarray'>\n"
],
[
"print(a + b)#逐元素运算,分别对每一个元素进行配对,然后对它们进行运算",
"[[ 10 63 3 17 6]\n [ 61 85 9 9 54]\n [ 14 103 17 68 77]\n [ 58 51 23 71 43]\n [ 76 24 78 67 102]]\n"
],
[
"print(a - b)",
"[[-10 -61 1 -11 2]\n [-51 -73 5 7 -36]\n [ 6 -81 7 -42 -49]\n [-28 -19 11 -35 -5]\n [-36 18 -34 -21 -54]]\n"
],
[
"print(a * b)",
"[[ 0 62 2 42 8]\n [ 280 474 14 8 405]\n [ 40 1012 60 715 882]\n [ 645 560 102 954 456]\n [1120 63 1232 1012 1872]]\n"
],
[
"print(a / b)",
"[[0 0 2 0 2]\n [0 0 3 8 0]\n [2 0 2 0 0]\n [0 0 2 0 0]\n [0 7 0 0 0]]\n"
],
[
"print(a ** 2)",
"[[ 0 1 4 9 16]\n [ 25 36 49 64 81]\n [100 121 144 169 196]\n [225 256 289 324 361]\n [400 441 484 529 576]]\n"
],
[
"print(a < b) #逻辑运算符比如 “<” 和 “>” 的时候,返回的将是一个布尔型数组",
"[[ True True False True False]\n [ True True False False True]\n [False True False True True]\n [ True True False True True]\n [ True False True True True]]\n"
],
[
"print(a > b)",
"[[False False True False True]\n [False False True True False]\n [ True False True False False]\n [False False True False False]\n [False True False False False]]\n"
],
[
"print(a.dot(b))#dot() 函数计算两个数组的点积。它返回的是一个标量(只有大小没有方向的一个值)而不是数组",
"[[ 417 380 254 446 555]\n [1262 1735 604 1281 1615]\n [2107 3090 954 2116 2675]\n [2952 4445 1304 2951 3735]\n [3797 5800 1654 3786 4795]]\n"
]
],
[
[
"## 数组特殊运算符",
"_____no_output_____"
]
],
[
[
"# sum, min, max, cumsum\na = np.arange(10)\nprint 'a:',a\nprint(a.sum()) # >>>45\nprint(a.min()) # >>>0\nprint(a.max()) # >>>9\nprint(a.cumsum()) # >>>[ 0 1 3 6 10 15 21 28 36 45]",
"a: [0 1 2 3 4 5 6 7 8 9]\n45\n0\n9\n[ 0 1 3 6 10 15 21 28 36 45]\n"
]
],
[
[
"# 索引",
"_____no_output_____"
],
[
"## 基本索引-整数索引",
"_____no_output_____"
]
],
[
[
"a = np.array([[11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n [26, 27, 28 ,29, 30],\n [31, 32, 33, 34, 35]])\nprint 'a:',a,type(a)\n# 访问元素:二者功能相同\nprint a[1][3]\nprint a[1,3]#逗号隔开的索引列表来选取单个元素\n# 多维数组中,如果省略了后面的索引,则返回对象是一个维度低一点的数组。\nprint a[2]",
"a: [[11 12 13 14 15]\n [16 17 18 19 20]\n [21 22 23 24 25]\n [26 27 28 29 30]\n [31 32 33 34 35]] <type 'numpy.ndarray'>\n19\n19\n[21 22 23 24 25]\n"
]
],
[
[
"## 数组切片\n数组切片与列表切片重要区别在于。数组切片是原数组的视图,这意味着数据不会被复制,视图上的任何修改都会直接反映到源数组上",
"_____no_output_____"
]
],
[
[
"a = np.array([[11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n [26, 27, 28 ,29, 30],\n [31, 32, 33, 34, 35]])\nprint 'a:',a\n# 单纯切片只能得到相同维度的数组视图,\nprint(a[::2,::2])\n# [[11 13 15]\n# [21 23 25]\n# [31 33 35]]\nprint(a[:3,:2])",
"a: [[11 12 13 14 15]\n [16 17 18 19 20]\n [21 22 23 24 25]\n [26 27 28 29 30]\n [31 32 33 34 35]]\n[[11 13 15]\n [21 23 25]\n [31 33 35]]\n[[11 12]\n [16 17]\n [21 22]]\n"
],
[
"#切片和整数索引混合使用,可以得到低维度的切片\nprint(a[0, 1:4]) # >>>[12 13 14]\nprint(a[1:4, 0]) # >>>[16 21 26]\nprint(a[:, 1]) # >>>[12 17 22 27 32]",
"[12 13 14]\n[16 21 26]\n[12 17 22 27 32]\n"
],
[
"a_slice = a[:,0]#数组切片是原数组的视图,这意味着数据不会被复制,视图上的任何修改都会直接反映到源数组上\nprint 'a_slice:',a_slice\na_slice[:] = 66\nprint 'a:',a",
"a_slice: [11 16 21 26 31]\na: [[66 12 13 14 15]\n [66 17 18 19 20]\n [66 22 23 24 25]\n [66 27 28 29 30]\n [66 32 33 34 35]]\n"
],
[
"#若想要数组切片的一份副本而非视图,则需要显式的进行复制操作\na_slice_copy = a[:,0].copy()\nprint \"a_slice_copy:\",a_slice_copy\na_slice_copy[:] = 111\nprint \"a_slice_copy:\",a_slice_copy\nprint 'a:',a",
"a_slice_copy: [66 66 66 66 66]\na_slice_copy: [111 111 111 111 111]\na: [[66 12 13 14 15]\n [66 17 18 19 20]\n [66 22 23 24 25]\n [66 27 28 29 30]\n [66 32 33 34 35]]\n"
]
],
[
[
"## 布尔型索引\n布尔型数组可用于数组索引,通过布尔型数组获取到数组中的数据,将总是创建副本\n==,!=,>,<",
"_____no_output_____"
]
],
[
[
"#数组的比较运算也是矢量化的,会产生一个布尔型数组\nnames = np.array(['bob','joe','will','bob','will','joe','joe'])\nnames.shape\nnames == 'bob'",
"_____no_output_____"
],
[
"data = np.random.randn(7,4)\ndata",
"_____no_output_____"
],
[
"#布尔型数组可用于数组索引,布尔型数组的长度必须跟被索引的轴长度一致,\n#例如names == 'bob'长度为7;data按行索引\n#names2 == 'bob'长度为4;data按列索引\nprint data[names == 'bob']\n\nnames2 = names[:4].copy()\nprint(names2)\nprint data[:,names2=='bob']",
"[[ 0.29218127 200. 200. 7. ]\n [ 0.53516408 200. 200. 0.88596045]]\n['bob' 'joe' 'will' 'bob']\n[[ 0.29218127 7. ]\n [ 100. 100. ]\n [ 100. 100. ]\n [ 0.53516408 0.88596045]\n [ 100. 100. ]\n [ 100. 100. ]\n [ 100. 100. ]]\n"
],
[
"# 布尔型数组还可以与切片、整数索引混合使用\nprint data[names == 'bob',1:3]\nprint data[names == 'bob',1]",
"[[ 200. 200.]\n [ 200. 200.]]\n[ 200. 200.]\n"
],
[
"# 注意:python关键字and or在布尔型数组中无效\n#利用逻辑关系构造复杂布尔型数组,|或,&和,!非\nmask = (names !='bob')\nprint data[mask]\nmask = (names =='bob') | (names == 'will')\nprint data[mask]",
"[[ 100. 200. 200. 100.]\n [ 100. 200. 200. 100.]\n [ 100. 200. 200. 100.]\n [ 100. 200. 200. 100.]\n [ 100. 200. 200. 100.]]\n[[ 0.29218127 200. 200. 7. ]\n [ 100. 200. 200. 100. ]\n [ 0.53516408 200. 200. 0.88596045]\n [ 100. 200. 200. 100. ]]\n"
],
[
"# 通过布尔型数组设置值\ndata[data < 0] = 7\nprint data\n#通过布尔型数组设置整行/整列\ndata[names !='bob'] = 100\nprint data\n\ndata[:,names2 !='bob'] = 200\nprint data",
"[[ 0.29218127 200. 200. 7. ]\n [ 100. 200. 200. 100. ]\n [ 100. 200. 200. 100. ]\n [ 0.53516408 200. 200. 0.88596045]\n [ 100. 200. 200. 100. ]\n [ 100. 200. 200. 100. ]\n [ 100. 200. 200. 100. ]]\n[[ 0.29218127 200. 200. 7. ]\n [ 100. 100. 100. 100. ]\n [ 100. 100. 100. 100. ]\n [ 0.53516408 200. 200. 0.88596045]\n [ 100. 100. 100. 100. ]\n [ 100. 100. 100. 100. ]\n [ 100. 100. 100. 100. ]]\n[[ 0.29218127 200. 200. 7. ]\n [ 100. 200. 200. 100. ]\n [ 100. 200. 200. 100. ]\n [ 0.53516408 200. 200. 0.88596045]\n [ 100. 200. 200. 100. ]\n [ 100. 200. 200. 100. ]\n [ 100. 200. 200. 100. ]]\n"
]
],
[
[
"## 花式索引\n花式索引是指利用整数数组进行索引,可以指定顺序选取、\n\n花式索引不同于切片,花式索引总是将数据复制到新数组中",
"_____no_output_____"
]
],
[
[
"arr = np.empty((8,4))\nfor i in range(8):\n arr[i] = i\nprint arr",
"_____no_output_____"
],
[
"#可以指定顺序选取行子集,只需传入一个用于指定顺序的整数列表或数组即可\nprint arr[[4,3,0,6]]\n#使用负数索引将从末尾开始选取行\nprint arr[[-1,-2]]\n#可以同时使用正数和负数进行花式索引\nprint arr[[1,2,-1,-2]]",
"_____no_output_____"
],
[
"#使用多个索引数组,返回的是一个一维数组\narr = np.arange(32).reshape(8,4)\nprint arr\nprint arr[[4,3,0,6],[1,2,3,0]]\n#获取的元素是(4,1)(3,2)(0,3)(6,0)",
"[[ 0 1 2 3]\n [ 4 5 6 7]\n [ 8 9 10 11]\n [12 13 14 15]\n [16 17 18 19]\n [20 21 22 23]\n [24 25 26 27]\n [28 29 30 31]]\n[17 14 3 24]\n"
],
[
"#要想得到矩阵的行列子集(矩形区域)\n#方法1\nprint arr[[4,3,0,6]][:,[1,2,3,0]]\n#方法2 np.ix_()用两个一维整数数组转换为一个用于选取方形局域的索引器\nprint arr[np.ix_([4,3,0,6],[1,2,3,0])]",
"[[17 18 19 16]\n [13 14 15 12]\n [ 1 2 3 0]\n [25 26 27 24]]\n[[17 18 19 16]\n [13 14 15 12]\n [ 1 2 3 0]\n [25 26 27 24]]\n"
]
],
[
[
"## 数组转置和轴对换",
"_____no_output_____"
]
],
[
[
"# 转置(transpose)返回源数据的视图(不会进行任何复制操作),\n# 两种办法实现转置:\n# arr.transpose()方法\n# arr.T属性\narr = np.arange(15).reshape(3,5)\nprint arr\nprint arr.T\nprint arr.transpose()\n#高维数组(>=3维)需要参数:轴编号组成的元组才能对轴进行转置\narr = np.arange(16).reshape(2,2,4)\nprint arr\nprint arr.T\nprint arr.transpose((1,0,2))",
"[[ 0 1 2 3 4]\n [ 5 6 7 8 9]\n [10 11 12 13 14]]\n[[ 0 5 10]\n [ 1 6 11]\n [ 2 7 12]\n [ 3 8 13]\n [ 4 9 14]]\n[[ 0 5 10]\n [ 1 6 11]\n [ 2 7 12]\n [ 3 8 13]\n [ 4 9 14]]\n[[[ 0 1 2 3]\n [ 4 5 6 7]]\n\n [[ 8 9 10 11]\n [12 13 14 15]]]\n[[[ 0 8]\n [ 4 12]]\n\n [[ 1 9]\n [ 5 13]]\n\n [[ 2 10]\n [ 6 14]]\n\n [[ 3 11]\n [ 7 15]]]\n[[[ 0 1 2 3]\n [ 8 9 10 11]]\n\n [[ 4 5 6 7]\n [12 13 14 15]]]\n"
]
],
[
[
"## 通用函数-快速的元素级数组函数\n对数组中数据进行元素级运算的函数",
"_____no_output_____"
]
],
[
[
"#一元通用函数,接收一个数组\narr = np.arange(10)\nprint arr\nprint np.sqrt(arr)#开方\nprint np.exp(arr)#指数\nprint np.square(arr)#平方",
"[0 1 2 3 4 5 6 7 8 9]\n[ 0. 1. 1.41421356 1.73205081 2. 2.23606798\n 2.44948974 2.64575131 2.82842712 3. ]\n[ 1.00000000e+00 2.71828183e+00 7.38905610e+00 2.00855369e+01\n 5.45981500e+01 1.48413159e+02 4.03428793e+02 1.09663316e+03\n 2.98095799e+03 8.10308393e+03]\n[ 0 1 4 9 16 25 36 49 64 81]\n"
],
[
"#二元通用函数,接收2个数组\nx = np.random.randn(5)\nprint x\ny = np.random.randn(5)\nprint y\nprint np.add(x,y)#加法\nprint np.subtract(x,y)#减法\nprint np.greater(x,y)#元素比较",
"_____no_output_____"
]
],
[
[
"## 将条件逻辑表述为数组运算\nnumpy.where()函数是三元表达式 x if condition else y的矢量化版本",
"_____no_output_____"
]
],
[
[
"xarr = np.array([1.1,1.2,1.3,1.4,1.5])\nyarr = np.array([2.1,2.2,2.3,2.4,2.5])\ncondition = np.array([True,False,True,True,False])\n# 列表生成式\nprint [(x if c else y)for x,y,c in zip(xarr,yarr,condition)]\n#存在问题\n#速度不是很快,原因:纯python实现\n#无法用于多维数组",
"[1.1000000000000001, 2.2000000000000002, 1.3, 1.3999999999999999, 2.5]\n"
],
[
"#利用np.where()实现相同功能很简洁\nprint np.where(condition,xarr,yarr)\n#np.where()函数,第2,3参数不一定为数组,也可以为标量值\n#where通常用于根据另一个数组生成一个新数组\narr = np.random.randn(4,4)\nprint arr\nprint np.where(arr > 0,1,-1)#根据arr原始元素>0,置位1;arr原始元素<0,置位-1\nprint np.where(arr > 0,1,arr)#根据arr原始元素>0,置位1;arr原始元素<0,保持不变",
"[ 1.1 2.2 1.3 1.4 2.5]\n[[ 1.45968931 0.04416752 0.17823822 -0.39762311]\n [ 1.1620933 0.59377557 -0.23737767 -1.43722256]\n [ 1.03619541 -0.64949799 0.15402381 -0.11071381]\n [ 1.29405992 -0.02742662 0.43881736 1.73837499]]\n[[ 1 1 1 -1]\n [ 1 1 -1 -1]\n [ 1 -1 1 -1]\n [ 1 -1 1 1]]\n[[ 1. 1. 1. -0.39762311]\n [ 1. 1. -0.23737767 -1.43722256]\n [ 1. -0.64949799 1. -0.11071381]\n [ 1. -0.02742662 1. 1. ]]\n"
]
],
[
[
"## 数学和统计方法\n数组的数学函数对数组或数组某个轴向的数据进行统计计算;\n既可以通过数据实例方法调用;\n也可以当做nump顶级函数使用.",
"_____no_output_____"
]
],
[
[
"arr = np.arange(10).reshape(2,5)\nprint arr\nprint arr.mean()#计算数组平均值\nprint arr.mean(axis = 0)#可指定轴,用以统计该轴上的值\nprint arr.mean(axis = 1)\nprint np.mean(arr)\nprint np.mean(arr,axis = 0)\nprint np.mean(arr,axis = 1)",
"_____no_output_____"
],
[
"print arr.sum()#计算数组和\nprint arr.sum(axis = 0)\nprint arr.sum(axis = 1)\nprint np.sum(arr)\nprint np.sum(arr,axis = 0)\nprint np.sum(arr,axis = 1)",
"_____no_output_____"
],
[
"print arr.var()#计算方差差\nprint arr.var(axis = 0)#\nprint arr.var(axis = 1)#\nprint np.var(arr)#计算方差差\nprint np.var(arr,axis = 0)#\nprint np.var(arr,axis = 1)#",
"_____no_output_____"
],
[
"print arr.std()#计算标准差\nprint arr.std(axis = 0)#\nprint arr.std(axis = 1)#\nprint np.std(arr)#计算标准差\nprint np.std(arr,axis = 0)#\nprint np.std(arr,axis = 1)#",
"_____no_output_____"
],
[
"print arr\nprint arr.min()#计算最小值\nprint arr.min(axis = 0)#\nprint arr.min(axis = 1)#\nprint np.min(arr)#\nprint np.min(arr,axis = 0)#\nprint np.min(arr,axis = 1)#",
"_____no_output_____"
],
[
"print arr\nprint arr.max()#计算最大值\nprint arr.max(axis = 0)#\nprint arr.max(axis = 1)#\nprint np.max(arr)\nprint np.max(arr,axis = 0)#\nprint np.max(arr,axis = 1)#",
"[[0 1 2 3 4]\n [5 6 7 8 9]]\n9\n[5 6 7 8 9]\n[4 9]\n9\n[5 6 7 8 9]\n[4 9]\n"
],
[
"print arr\nprint arr[0].argmin()#最小值的索引\nprint arr[1].argmin()#最小值的索引\n\nprint arr[0].argmax()#最大值的索引\nprint arr[1].argmax()#最大值的索引",
"_____no_output_____"
],
[
"print arr\nprint arr.cumsum()#不聚合,所有元素的累积和,而是返回中间结果构成的数组",
"[[0 1 2 3 4]\n [5 6 7 8 9]]\n[ 0 1 3 6 10 15 21 28 36 45]\n"
],
[
"arr = arr + 1\nprint arr\nprint arr.cumprod()#不聚合,所有元素的累积积,而是返回中间结果构成的数组",
"[[ 1 2 3 4 5]\n [ 6 7 8 9 10]]\n[ 1 2 6 24 120 720 5040 40320 362880\n 3628800]\n"
]
],
[
[
"## 用于布尔型数组的方法\nany()测试布尔型数组是否存在一个或多个True\n\nall()检查数组中所有值是否都为True",
"_____no_output_____"
]
],
[
[
"arr = np.random.randn(10)\n# print \nbools = arr > 0\nprint bools\nprint bools.any()\nprint np.any(bools)\nprint bools.all()\nprint np.all(bools)\n\narr = np.array([0,1,2,3,4])\nprint arr.any()#非布尔型数组,所有非0元素会被当做True",
"[ True False True True True False True True True False]\nTrue\nTrue\nFalse\nFalse\nTrue\n"
]
],
[
[
"## 排序",
"_____no_output_____"
]
],
[
[
"arr = np.random.randn(10)\nprint arr\narr.sort()#与python内置列表排序一样;就地排序,会修改数组本身\nprint arr\narr = np.random.randn(10)\nprint arr\nprint np.sort(arr)#返回数组已排序副本",
"[ 1.00826129 -1.33200021 -2.09423152 1.14618429 -1.94373366 -1.19964262\n -0.97484352 -0.25508501 0.95594379 -0.92684744]\n[-2.09423152 -1.94373366 -1.33200021 -1.19964262 -0.97484352 -0.92684744\n -0.25508501 0.95594379 1.00826129 1.14618429]\n[-0.13764091 -0.44657322 -0.4725095 -2.25229905 0.92481373 -0.4272677\n -2.3459137 0.82869414 -0.2215158 -0.28151528]\n[-2.3459137 -2.25229905 -0.4725095 -0.44657322 -0.4272677 -0.28151528\n -0.2215158 -0.13764091 0.82869414 0.92481373]\n"
]
],
[
[
"## 唯一化及其他的集合逻辑\nnumpy针对一维数组的基本集合运算\nnp.unique()找出数组中的唯一值,并返回已排序的结果",
"_____no_output_____"
]
],
[
[
"names = np.array(['bob', 'joe', 'will', 'bob', 'will', 'joe', 'joe'])\nprint names\nprint np.unique(names)",
"['bob' 'joe' 'will' 'bob' 'will' 'joe' 'joe']\n['bob' 'joe' 'will']\n"
]
],
[
[
"## 线性代数",
"_____no_output_____"
]
],
[
[
"#矩阵乘法\nx = np.array([[1,2,3],[4,5,6]])\ny = np.array([[6,23],[-1,7],[8,9]])\nprint x\nprint y\nprint x.dot(y)\nprint np.dot(x,y)",
"[[1 2 3]\n [4 5 6]]\n[[ 6 23]\n [-1 7]\n [ 8 9]]\n[[ 28 64]\n [ 67 181]]\n[[ 28 64]\n [ 67 181]]\n"
]
],
[
[
"## 随机数生成\nnumpy.random模块对python内置的random进行补充,增接了一些用于高效生成多生概率分布的样本值的函数",
"_____no_output_____"
]
],
[
[
"#从给定的上下限范围内随机选取整数\nprint np.random.randint(10)",
"_____no_output_____"
],
[
"#产生正态分布的样本值\nprint np.random.randn(3,2)",
"[[-0.05199971 -1.95031704]\n [-1.42560357 0.78544126]\n [ 0.47068984 -0.51157053]]\n"
]
],
[
[
"### 数组组合",
"_____no_output_____"
]
],
[
[
"a = np.array([1,2,3])\nb = np.array([4,5,6])\nc = np.arange(6).reshape(2,3)\nd = np.arange(2,8).reshape(2,3)\nprint(a)\nprint(b)\nprint(c)\nprint(d)",
"[1 2 3]\n[4 5 6]\n[[0 1 2]\n [3 4 5]]\n[[2 3 4]\n [5 6 7]]\n"
],
[
"np.concatenate([c,d])",
"_____no_output_____"
],
[
"# In machine learning, useful to enrich or \n# add new/concatenate features with hstack\nnp.hstack([c, d])",
"_____no_output_____"
],
[
"# Use broadcasting when needed to do this automatically\nnp.vstack([a,b, d])",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
d082bf021eabba7c972e7d2a3852b50d723e4edb | 44,205 | ipynb | Jupyter Notebook | scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb | karim7262/amazon-sagemaker-examples | f86a97fba33cd04e98ab9ccb1d6e974b73a924e4 | [
"Apache-2.0"
] | 1 | 2018-03-13T09:46:17.000Z | 2018-03-13T09:46:17.000Z | 40_AWS_SageMaker/scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb | donwany/PipeLine.AI | 523ad468dd13fa953d9d41c3c0150b5fdcc2586c | [
"Apache-2.0"
] | null | null | null | 40_AWS_SageMaker/scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb | donwany/PipeLine.AI | 523ad468dd13fa953d9d41c3c0150b5fdcc2586c | [
"Apache-2.0"
] | 2 | 2018-07-24T12:33:48.000Z | 2018-07-24T13:30:44.000Z | 39.824324 | 888 | 0.631987 | [
[
[
"# A Scientific Deep Dive Into SageMaker LDA\n\n1. [Introduction](#Introduction)\n1. [Setup](#Setup)\n1. [Data Exploration](#DataExploration)\n1. [Training](#Training)\n1. [Inference](#Inference)\n1. [Epilogue](#Epilogue)",
"_____no_output_____"
],
[
"# Introduction\n***\n\nAmazon SageMaker LDA is an unsupervised learning algorithm that attempts to describe a set of observations as a mixture of distinct categories. Latent Dirichlet Allocation (LDA) is most commonly used to discover a user-specified number of topics shared by documents within a text corpus. Here each observation is a document, the features are the presence (or occurrence count) of each word, and the categories are the topics. Since the method is unsupervised, the topics are not specified up front, and are not guaranteed to align with how a human may naturally categorize documents. The topics are learned as a probability distribution over the words that occur in each document. Each document, in turn, is described as a mixture of topics.\n\nThis notebook is similar to **LDA-Introduction.ipynb** but its objective and scope are a different. We will be taking a deeper dive into the theory. The primary goals of this notebook are,\n\n* to understand the LDA model and the example dataset,\n* understand how the Amazon SageMaker LDA algorithm works,\n* interpret the meaning of the inference output.\n\nFormer knowledge of LDA is not required. However, we will run through concepts rather quickly and at least a foundational knowledge of mathematics or machine learning is recommended. Suggested references are provided, as appropriate.",
"_____no_output_____"
]
],
[
[
"!conda install -y scipy",
"_____no_output_____"
],
[
"%matplotlib inline\n\nimport os, re, tarfile\n\nimport boto3\nimport matplotlib.pyplot as plt\nimport mxnet as mx\nimport numpy as np\nnp.set_printoptions(precision=3, suppress=True)\n\n# some helpful utility functions are defined in the Python module\n# \"generate_example_data\" located in the same directory as this\n# notebook\nfrom generate_example_data import (\n generate_griffiths_data, match_estimated_topics,\n plot_lda, plot_lda_topics)\n\n# accessing the SageMaker Python SDK\nimport sagemaker\nfrom sagemaker.amazon.common import numpy_to_record_serializer\nfrom sagemaker.predictor import csv_serializer, json_deserializer",
"_____no_output_____"
]
],
[
[
"# Setup\n\n***\n\n*This notebook was created and tested on an ml.m4.xlarge notebook instance.*\n\nWe first need to specify some AWS credentials; specifically data locations and access roles. This is the only cell of this notebook that you will need to edit. In particular, we need the following data:\n\n* `bucket` - An S3 bucket accessible by this account.\n * Used to store input training data and model data output.\n * Should be withing the same region as this notebook instance, training, and hosting.\n* `prefix` - The location in the bucket where this notebook's input and and output data will be stored. (The default value is sufficient.)\n* `role` - The IAM Role ARN used to give training and hosting access to your data.\n * See documentation on how to create these.\n * The script below will try to determine an appropriate Role ARN.",
"_____no_output_____"
]
],
[
[
"from sagemaker import get_execution_role\n\nrole = get_execution_role()\n\nbucket = '<your_s3_bucket_name_here>'\nprefix = 'sagemaker/lda_science'\n\n\nprint('Training input/output will be stored in {}/{}'.format(bucket, prefix))\nprint('\\nIAM Role: {}'.format(role))",
"_____no_output_____"
]
],
[
[
"## The LDA Model\n\nAs mentioned above, LDA is a model for discovering latent topics describing a collection of documents. In this section we will give a brief introduction to the model. Let,\n\n* $M$ = the number of *documents* in a corpus\n* $N$ = the average *length* of a document.\n* $V$ = the size of the *vocabulary* (the total number of unique words)\n\nWe denote a *document* by a vector $w \\in \\mathbb{R}^V$ where $w_i$ equals the number of times the $i$th word in the vocabulary occurs within the document. This is called the \"bag-of-words\" format of representing a document.\n\n$$\n\\underbrace{w}_{\\text{document}} = \\overbrace{\\big[ w_1, w_2, \\ldots, w_V \\big] }^{\\text{word counts}},\n\\quad\nV = \\text{vocabulary size}\n$$\n\nThe *length* of a document is equal to the total number of words in the document: $N_w = \\sum_{i=1}^V w_i$.\n\nAn LDA model is defined by two parameters: a topic-word distribution matrix $\\beta \\in \\mathbb{R}^{K \\times V}$ and a Dirichlet topic prior $\\alpha \\in \\mathbb{R}^K$. In particular, let,\n\n$$\\beta = \\left[ \\beta_1, \\ldots, \\beta_K \\right]$$\n\nbe a collection of $K$ *topics* where each topic $\\beta_k \\in \\mathbb{R}^V$ is represented as probability distribution over the vocabulary. One of the utilities of the LDA model is that a given word is allowed to appear in multiple topics with positive probability. The Dirichlet topic prior is a vector $\\alpha \\in \\mathbb{R}^K$ such that $\\alpha_k > 0$ for all $k$.",
"_____no_output_____"
],
[
"# Data Exploration\n\n---\n\n## An Example Dataset\n\nBefore explaining further let's get our hands dirty with an example dataset. The following synthetic data comes from [1] and comes with a very useful visual interpretation.\n\n> [1] Thomas Griffiths and Mark Steyvers. *Finding Scientific Topics.* Proceedings of the National Academy of Science, 101(suppl 1):5228-5235, 2004.",
"_____no_output_____"
]
],
[
[
"print('Generating example data...')\nnum_documents = 6000\nknown_alpha, known_beta, documents, topic_mixtures = generate_griffiths_data(\n num_documents=num_documents, num_topics=10)\nnum_topics, vocabulary_size = known_beta.shape\n\n\n# separate the generated data into training and tests subsets\nnum_documents_training = int(0.9*num_documents)\nnum_documents_test = num_documents - num_documents_training\n\ndocuments_training = documents[:num_documents_training]\ndocuments_test = documents[num_documents_training:]\n\ntopic_mixtures_training = topic_mixtures[:num_documents_training]\ntopic_mixtures_test = topic_mixtures[num_documents_training:]\n\nprint('documents_training.shape = {}'.format(documents_training.shape))\nprint('documents_test.shape = {}'.format(documents_test.shape))",
"_____no_output_____"
]
],
[
[
"Let's start by taking a closer look at the documents. Note that the vocabulary size of these data is $V = 25$. The average length of each document in this data set is 150. (See `generate_griffiths_data.py`.)",
"_____no_output_____"
]
],
[
[
"print('First training document =\\n{}'.format(documents_training[0]))\nprint('\\nVocabulary size = {}'.format(vocabulary_size))\nprint('Length of first document = {}'.format(documents_training[0].sum()))",
"_____no_output_____"
],
[
"average_document_length = documents.sum(axis=1).mean()\nprint('Observed average document length = {}'.format(average_document_length))",
"_____no_output_____"
]
],
[
[
"The example data set above also returns the LDA parameters,\n\n$$(\\alpha, \\beta)$$\n\nused to generate the documents. Let's examine the first topic and verify that it is a probability distribution on the vocabulary.",
"_____no_output_____"
]
],
[
[
"print('First topic =\\n{}'.format(known_beta[0]))\n\nprint('\\nTopic-word probability matrix (beta) shape: (num_topics, vocabulary_size) = {}'.format(known_beta.shape))\nprint('\\nSum of elements of first topic = {}'.format(known_beta[0].sum()))",
"_____no_output_____"
]
],
[
[
"Unlike some clustering algorithms, one of the versatilities of the LDA model is that a given word can belong to multiple topics. The probability of that word occurring in each topic may differ, as well. This is reflective of real-world data where, for example, the word *\"rover\"* appears in a *\"dogs\"* topic as well as in a *\"space exploration\"* topic.\n\nIn our synthetic example dataset, the first word in the vocabulary belongs to both Topic #1 and Topic #6 with non-zero probability.",
"_____no_output_____"
]
],
[
[
"print('Topic #1:\\n{}'.format(known_beta[0]))\nprint('Topic #6:\\n{}'.format(known_beta[5]))",
"_____no_output_____"
]
],
[
[
"Human beings are visual creatures, so it might be helpful to come up with a visual representation of these documents.\n\nIn the below plots, each pixel of a document represents a word. The greyscale intensity is a measure of how frequently that word occurs within the document. Below we plot the first few documents of the training set reshaped into 5x5 pixel grids.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n\nfig = plot_lda(documents_training, nrows=3, ncols=4, cmap='gray_r', with_colorbar=True)\nfig.suptitle('$w$ - Document Word Counts')\nfig.set_dpi(160)",
"_____no_output_____"
]
],
[
[
"When taking a close look at these documents we can see some patterns in the word distributions suggesting that, perhaps, each topic represents a \"column\" or \"row\" of words with non-zero probability and that each document is composed primarily of a handful of topics.\n\nBelow we plots the *known* topic-word probability distributions, $\\beta$. Similar to the documents we reshape each probability distribution to a $5 \\times 5$ pixel image where the color represents the probability of that each word occurring in the topic.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n\nfig = plot_lda(known_beta, nrows=1, ncols=10)\nfig.suptitle(r'Known $\\beta$ - Topic-Word Probability Distributions')\nfig.set_dpi(160)\nfig.set_figheight(2)",
"_____no_output_____"
]
],
[
[
"These 10 topics were used to generate the document corpus. Next, we will learn about how this is done.",
"_____no_output_____"
],
[
"## Generating Documents\n\nLDA is a generative model, meaning that the LDA parameters $(\\alpha, \\beta)$ are used to construct documents word-by-word by drawing from the topic-word distributions. In fact, looking closely at the example documents above you can see that some documents sample more words from some topics than from others.\n\nLDA works as follows: given \n\n* $M$ documents $w^{(1)}, w^{(2)}, \\ldots, w^{(M)}$,\n* an average document length of $N$,\n* and an LDA model $(\\alpha, \\beta)$.\n\n**For** each document, $w^{(m)}$:\n* sample a topic mixture: $\\theta^{(m)} \\sim \\text{Dirichlet}(\\alpha)$\n* **For** each word $n$ in the document:\n * Sample a topic $z_n^{(m)} \\sim \\text{Multinomial}\\big( \\theta^{(m)} \\big)$\n * Sample a word from this topic, $w_n^{(m)} \\sim \\text{Multinomial}\\big( \\beta_{z_n^{(m)}} \\; \\big)$\n * Add to document\n\nThe [plate notation](https://en.wikipedia.org/wiki/Plate_notation) for the LDA model, introduced in [2], encapsulates this process pictorially.\n\n\n\n> [2] David M Blei, Andrew Y Ng, and Michael I Jordan. Latent Dirichlet Allocation. Journal of Machine Learning Research, 3(Jan):993–1022, 2003.",
"_____no_output_____"
],
[
"## Topic Mixtures\n\nFor the documents we generated above lets look at their corresponding topic mixtures, $\\theta \\in \\mathbb{R}^K$. The topic mixtures represent the probablility that a given word of the document is sampled from a particular topic. For example, if the topic mixture of an input document $w$ is,\n\n$$\\theta = \\left[ 0.3, 0.2, 0, 0.5, 0, \\ldots, 0 \\right]$$\n\nthen $w$ is 30% generated from the first topic, 20% from the second topic, and 50% from the fourth topic. In particular, the words contained in the document are sampled from the first topic-word probability distribution 30% of the time, from the second distribution 20% of the time, and the fourth disribution 50% of the time.\n\n\nThe objective of inference, also known as scoring, is to determine the most likely topic mixture of a given input document. Colloquially, this means figuring out which topics appear within a given document and at what ratios. We will perform infernece later in the [Inference](#Inference) section.\n\nSince we generated these example documents using the LDA model we know the topic mixture generating them. Let's examine these topic mixtures.",
"_____no_output_____"
]
],
[
[
"print('First training document =\\n{}'.format(documents_training[0]))\nprint('\\nVocabulary size = {}'.format(vocabulary_size))\nprint('Length of first document = {}'.format(documents_training[0].sum()))",
"_____no_output_____"
],
[
"print('First training document topic mixture =\\n{}'.format(topic_mixtures_training[0]))\nprint('\\nNumber of topics = {}'.format(num_topics))\nprint('sum(theta) = {}'.format(topic_mixtures_training[0].sum()))",
"_____no_output_____"
]
],
[
[
"We plot the first document along with its topic mixture. We also plot the topic-word probability distributions again for reference.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n\nfig, (ax1,ax2) = plt.subplots(2, 1)\n\nax1.matshow(documents[0].reshape(5,5), cmap='gray_r')\nax1.set_title(r'$w$ - Document', fontsize=20)\nax1.set_xticks([])\nax1.set_yticks([])\n\ncax2 = ax2.matshow(topic_mixtures[0].reshape(1,-1), cmap='Reds', vmin=0, vmax=1)\ncbar = fig.colorbar(cax2, orientation='horizontal')\nax2.set_title(r'$\\theta$ - Topic Mixture', fontsize=20)\nax2.set_xticks([])\nax2.set_yticks([])\n\nfig.set_dpi(100)",
"_____no_output_____"
],
[
"%matplotlib inline\n\n# pot\nfig = plot_lda(known_beta, nrows=1, ncols=10)\nfig.suptitle(r'Known $\\beta$ - Topic-Word Probability Distributions')\nfig.set_dpi(160)\nfig.set_figheight(1.5)",
"_____no_output_____"
]
],
[
[
"Finally, let's plot several documents with their corresponding topic mixtures. We can see how topics with large weight in the document lead to more words in the document within the corresponding \"row\" or \"column\".",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n\nfig = plot_lda_topics(documents_training, 3, 4, topic_mixtures=topic_mixtures)\nfig.suptitle(r'$(w,\\theta)$ - Documents with Known Topic Mixtures')\nfig.set_dpi(160)",
"_____no_output_____"
]
],
[
[
"# Training\n\n***\n\nIn this section we will give some insight into how AWS SageMaker LDA fits an LDA model to a corpus, create an run a SageMaker LDA training job, and examine the output trained model.",
"_____no_output_____"
],
[
"## Topic Estimation using Tensor Decompositions\n\nGiven a document corpus, Amazon SageMaker LDA uses a spectral tensor decomposition technique to determine the LDA model $(\\alpha, \\beta)$ which most likely describes the corpus. See [1] for a primary reference of the theory behind the algorithm. The spectral decomposition, itself, is computed using the CPDecomp algorithm described in [2].\n\nThe overall idea is the following: given a corpus of documents $\\mathcal{W} = \\{w^{(1)}, \\ldots, w^{(M)}\\}, \\; w^{(m)} \\in \\mathbb{R}^V,$ we construct a statistic tensor,\n\n$$T \\in \\bigotimes^3 \\mathbb{R}^V$$\n\nsuch that the spectral decomposition of the tensor is approximately the LDA parameters $\\alpha \\in \\mathbb{R}^K$ and $\\beta \\in \\mathbb{R}^{K \\times V}$ which maximize the likelihood of observing the corpus for a given number of topics, $K$,\n\n$$T \\approx \\sum_{k=1}^K \\alpha_k \\; (\\beta_k \\otimes \\beta_k \\otimes \\beta_k)$$\n\nThis statistic tensor encapsulates information from the corpus such as the document mean, cross correlation, and higher order statistics. For details, see [1].\n\n\n> [1] Animashree Anandkumar, Rong Ge, Daniel Hsu, Sham Kakade, and Matus Telgarsky. *\"Tensor Decompositions for Learning Latent Variable Models\"*, Journal of Machine Learning Research, 15:2773–2832, 2014.\n>\n> [2] Tamara Kolda and Brett Bader. *\"Tensor Decompositions and Applications\"*. SIAM Review, 51(3):455–500, 2009.\n\n\n",
"_____no_output_____"
],
[
"## Store Data on S3\n\nBefore we run training we need to prepare the data.\n\nA SageMaker training job needs access to training data stored in an S3 bucket. Although training can accept data of various formats we convert the documents MXNet RecordIO Protobuf format before uploading to the S3 bucket defined at the beginning of this notebook.",
"_____no_output_____"
]
],
[
[
"# convert documents_training to Protobuf RecordIO format\nrecordio_protobuf_serializer = numpy_to_record_serializer()\nfbuffer = recordio_protobuf_serializer(documents_training)\n\n# upload to S3 in bucket/prefix/train\nfname = 'lda.data'\ns3_object = os.path.join(prefix, 'train', fname)\nboto3.Session().resource('s3').Bucket(bucket).Object(s3_object).upload_fileobj(fbuffer)\n\ns3_train_data = 's3://{}/{}'.format(bucket, s3_object)\nprint('Uploaded data to S3: {}'.format(s3_train_data))",
"_____no_output_____"
]
],
[
[
"Next, we specify a Docker container containing the SageMaker LDA algorithm. For your convenience, a region-specific container is automatically chosen for you to minimize cross-region data communication",
"_____no_output_____"
]
],
[
[
"containers = {\n 'us-west-2': '266724342769.dkr.ecr.us-west-2.amazonaws.com/lda:latest',\n 'us-east-1': '766337827248.dkr.ecr.us-east-1.amazonaws.com/lda:latest',\n 'us-east-2': '999911452149.dkr.ecr.us-east-2.amazonaws.com/lda:latest',\n 'eu-west-1': '999678624901.dkr.ecr.eu-west-1.amazonaws.com/lda:latest'\n}\nregion_name = boto3.Session().region_name\ncontainer = containers[region_name]\n\nprint('Using SageMaker LDA container: {} ({})'.format(container, region_name))",
"_____no_output_____"
]
],
[
[
"## Training Parameters\n\nParticular to a SageMaker LDA training job are the following hyperparameters:\n\n* **`num_topics`** - The number of topics or categories in the LDA model.\n * Usually, this is not known a priori.\n * In this example, howevever, we know that the data is generated by five topics.\n\n* **`feature_dim`** - The size of the *\"vocabulary\"*, in LDA parlance.\n * In this example, this is equal 25.\n\n* **`mini_batch_size`** - The number of input training documents.\n\n* **`alpha0`** - *(optional)* a measurement of how \"mixed\" are the topic-mixtures.\n * When `alpha0` is small the data tends to be represented by one or few topics.\n * When `alpha0` is large the data tends to be an even combination of several or many topics.\n * The default value is `alpha0 = 1.0`.\n\nIn addition to these LDA model hyperparameters, we provide additional parameters defining things like the EC2 instance type on which training will run, the S3 bucket containing the data, and the AWS access role. Note that,\n\n* Recommended instance type: `ml.c4`\n* Current limitations:\n * SageMaker LDA *training* can only run on a single instance.\n * SageMaker LDA does not take advantage of GPU hardware.\n * (The Amazon AI Algorithms team is working hard to provide these capabilities in a future release!)",
"_____no_output_____"
],
[
"Using the above configuration create a SageMaker client and use the client to create a training job.",
"_____no_output_____"
]
],
[
[
"session = sagemaker.Session()\n\n# specify general training job information\nlda = sagemaker.estimator.Estimator(\n container,\n role,\n output_path='s3://{}/{}/output'.format(bucket, prefix),\n train_instance_count=1,\n train_instance_type='ml.c4.2xlarge',\n sagemaker_session=session,\n)\n\n# set algorithm-specific hyperparameters\nlda.set_hyperparameters(\n num_topics=num_topics,\n feature_dim=vocabulary_size,\n mini_batch_size=num_documents_training,\n alpha0=1.0,\n)\n\n# run the training job on input data stored in S3\nlda.fit({'train': s3_train_data})",
"_____no_output_____"
]
],
[
[
"If you see the message\n\n> `===== Job Complete =====`\n\nat the bottom of the output logs then that means training sucessfully completed and the output LDA model was stored in the specified output path. You can also view information about and the status of a training job using the AWS SageMaker console. Just click on the \"Jobs\" tab and select training job matching the training job name, below:",
"_____no_output_____"
]
],
[
[
"print('Training job name: {}'.format(lda.latest_training_job.job_name))",
"_____no_output_____"
]
],
[
[
"## Inspecting the Trained Model\n\nWe know the LDA parameters $(\\alpha, \\beta)$ used to generate the example data. How does the learned model compare the known one? In this section we will download the model data and measure how well SageMaker LDA did in learning the model.\n\nFirst, we download the model data. SageMaker will output the model in \n\n> `s3://<bucket>/<prefix>/output/<training job name>/output/model.tar.gz`.\n\nSageMaker LDA stores the model as a two-tuple $(\\alpha, \\beta)$ where each LDA parameter is an MXNet NDArray.",
"_____no_output_____"
]
],
[
[
"# download and extract the model file from S3\njob_name = lda.latest_training_job.job_name\nmodel_fname = 'model.tar.gz'\nmodel_object = os.path.join(prefix, 'output', job_name, 'output', model_fname)\nboto3.Session().resource('s3').Bucket(bucket).Object(model_object).download_file(fname)\nwith tarfile.open(fname) as tar:\n tar.extractall()\nprint('Downloaded and extracted model tarball: {}'.format(model_object))\n\n# obtain the model file\nmodel_list = [fname for fname in os.listdir('.') if fname.startswith('model_')]\nmodel_fname = model_list[0]\nprint('Found model file: {}'.format(model_fname))\n\n# get the model from the model file and store in Numpy arrays\nalpha, beta = mx.ndarray.load(model_fname)\nlearned_alpha_permuted = alpha.asnumpy()\nlearned_beta_permuted = beta.asnumpy()\n\nprint('\\nLearned alpha.shape = {}'.format(learned_alpha_permuted.shape))\nprint('Learned beta.shape = {}'.format(learned_beta_permuted.shape))",
"_____no_output_____"
]
],
[
[
"Presumably, SageMaker LDA has found the topics most likely used to generate the training corpus. However, even if this is case the topics would not be returned in any particular order. Therefore, we match the found topics to the known topics closest in L1-norm in order to find the topic permutation.\n\nNote that we will use the `permutation` later during inference to match known topic mixtures to found topic mixtures.\n\nBelow plot the known topic-word probability distribution, $\\beta \\in \\mathbb{R}^{K \\times V}$ next to the distributions found by SageMaker LDA as well as the L1-norm errors between the two.",
"_____no_output_____"
]
],
[
[
"permutation, learned_beta = match_estimated_topics(known_beta, learned_beta_permuted)\nlearned_alpha = learned_alpha_permuted[permutation]\n\nfig = plot_lda(np.vstack([known_beta, learned_beta]), 2, 10)\nfig.set_dpi(160)\nfig.suptitle('Known vs. Found Topic-Word Probability Distributions')\nfig.set_figheight(3)\n\nbeta_error = np.linalg.norm(known_beta - learned_beta, 1)\nalpha_error = np.linalg.norm(known_alpha - learned_alpha, 1)\nprint('L1-error (beta) = {}'.format(beta_error))\nprint('L1-error (alpha) = {}'.format(alpha_error))",
"_____no_output_____"
]
],
[
[
"Not bad!\n\nIn the eyeball-norm the topics match quite well. In fact, the topic-word distribution error is approximately 2%.",
"_____no_output_____"
],
[
"# Inference\n\n***\n\nA trained model does nothing on its own. We now want to use the model we computed to perform inference on data. For this example, that means predicting the topic mixture representing a given document.\n\nWe create an inference endpoint using the SageMaker Python SDK `deploy()` function from the job we defined above. We specify the instance type where inference is computed as well as an initial number of instances to spin up.",
"_____no_output_____"
]
],
[
[
"lda_inference = lda.deploy(\n initial_instance_count=1,\n instance_type='ml.m4.xlarge', # LDA inference may work better at scale on ml.c4 instances\n)",
"_____no_output_____"
]
],
[
[
"Congratulations! You now have a functioning SageMaker LDA inference endpoint. You can confirm the endpoint configuration and status by navigating to the \"Endpoints\" tab in the AWS SageMaker console and selecting the endpoint matching the endpoint name, below: ",
"_____no_output_____"
]
],
[
[
"print('Endpoint name: {}'.format(lda_inference.endpoint))",
"_____no_output_____"
]
],
[
[
"With this realtime endpoint at our fingertips we can finally perform inference on our training and test data.\n\nWe can pass a variety of data formats to our inference endpoint. In this example we will demonstrate passing CSV-formatted data. Other available formats are JSON-formatted, JSON-sparse-formatter, and RecordIO Protobuf. We make use of the SageMaker Python SDK utilities `csv_serializer` and `json_deserializer` when configuring the inference endpoint.",
"_____no_output_____"
]
],
[
[
"lda_inference.content_type = 'text/csv'\nlda_inference.serializer = csv_serializer\nlda_inference.deserializer = json_deserializer",
"_____no_output_____"
]
],
[
[
"We pass some test documents to the inference endpoint. Note that the serializer and deserializer will atuomatically take care of the datatype conversion.",
"_____no_output_____"
]
],
[
[
"results = lda_inference.predict(documents_test[:12])\n\nprint(results)",
"_____no_output_____"
]
],
[
[
"It may be hard to see but the output format of SageMaker LDA inference endpoint is a Python dictionary with the following format.\n\n```\n{\n 'predictions': [\n {'topic_mixture': [ ... ] },\n {'topic_mixture': [ ... ] },\n {'topic_mixture': [ ... ] },\n ...\n ]\n}\n```\n\nWe extract the topic mixtures, themselves, corresponding to each of the input documents.",
"_____no_output_____"
]
],
[
[
"inferred_topic_mixtures_permuted = np.array([prediction['topic_mixture'] for prediction in results['predictions']])\n\nprint('Inferred topic mixtures (permuted):\\n\\n{}'.format(inferred_topic_mixtures_permuted))",
"_____no_output_____"
]
],
[
[
"## Inference Analysis\n\nRecall that although SageMaker LDA successfully learned the underlying topics which generated the sample data the topics were in a different order. Before we compare to known topic mixtures $\\theta \\in \\mathbb{R}^K$ we should also permute the inferred topic mixtures\n",
"_____no_output_____"
]
],
[
[
"inferred_topic_mixtures = inferred_topic_mixtures_permuted[:,permutation]\n\nprint('Inferred topic mixtures:\\n\\n{}'.format(inferred_topic_mixtures))",
"_____no_output_____"
]
],
[
[
"Let's plot these topic mixture probability distributions alongside the known ones.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n\n# create array of bar plots\nwidth = 0.4\nx = np.arange(10)\n\nnrows, ncols = 3, 4\nfig, ax = plt.subplots(nrows, ncols, sharey=True)\nfor i in range(nrows):\n for j in range(ncols):\n index = i*ncols + j\n ax[i,j].bar(x, topic_mixtures_test[index], width, color='C0')\n ax[i,j].bar(x+width, inferred_topic_mixtures[index], width, color='C1')\n ax[i,j].set_xticks(range(num_topics))\n ax[i,j].set_yticks(np.linspace(0,1,5))\n ax[i,j].grid(which='major', axis='y')\n ax[i,j].set_ylim([0,1])\n ax[i,j].set_xticklabels([])\n if (i==(nrows-1)):\n ax[i,j].set_xticklabels(range(num_topics), fontsize=7)\n if (j==0):\n ax[i,j].set_yticklabels([0,'',0.5,'',1.0], fontsize=7)\n \nfig.suptitle('Known vs. Inferred Topic Mixtures')\nax_super = fig.add_subplot(111, frameon=False)\nax_super.tick_params(labelcolor='none', top='off', bottom='off', left='off', right='off')\nax_super.grid(False)\nax_super.set_xlabel('Topic Index')\nax_super.set_ylabel('Topic Probability')\nfig.set_dpi(160)",
"_____no_output_____"
]
],
[
[
"In the eyeball-norm these look quite comparable.\n\nLet's be more scientific about this. Below we compute and plot the distribution of L1-errors from **all** of the test documents. Note that we send a new payload of test documents to the inference endpoint and apply the appropriate permutation to the output.",
"_____no_output_____"
]
],
[
[
"%%time\n\n# create a payload containing all of the test documents and run inference again\n#\n# TRY THIS:\n# try switching between the test data set and a subset of the training\n# data set. It is likely that LDA inference will perform better against\n# the training set than the holdout test set.\n#\npayload_documents = documents_test # Example 1\nknown_topic_mixtures = topic_mixtures_test # Example 1\n#payload_documents = documents_training[:600]; # Example 2\n#known_topic_mixtures = topic_mixtures_training[:600] # Example 2\n\nprint('Invoking endpoint...\\n')\nresults = lda_inference.predict(payload_documents)\n\ninferred_topic_mixtures_permuted = np.array([prediction['topic_mixture'] for prediction in results['predictions']])\ninferred_topic_mixtures = inferred_topic_mixtures_permuted[:,permutation]\n\nprint('known_topics_mixtures.shape = {}'.format(known_topic_mixtures.shape))\nprint('inferred_topics_mixtures_test.shape = {}\\n'.format(inferred_topic_mixtures.shape))",
"_____no_output_____"
],
[
"%matplotlib inline\n\nl1_errors = np.linalg.norm((inferred_topic_mixtures - known_topic_mixtures), 1, axis=1)\n\n# plot the error freqency\nfig, ax_frequency = plt.subplots()\nbins = np.linspace(0,1,40)\nweights = np.ones_like(l1_errors)/len(l1_errors)\nfreq, bins, _ = ax_frequency.hist(l1_errors, bins=50, weights=weights, color='C0')\nax_frequency.set_xlabel('L1-Error')\nax_frequency.set_ylabel('Frequency', color='C0')\n\n\n# plot the cumulative error\nshift = (bins[1]-bins[0])/2\nx = bins[1:] - shift\nax_cumulative = ax_frequency.twinx()\ncumulative = np.cumsum(freq)/sum(freq)\nax_cumulative.plot(x, cumulative, marker='o', color='C1')\nax_cumulative.set_ylabel('Cumulative Frequency', color='C1')\n\n\n# align grids and show\nfreq_ticks = np.linspace(0, 1.5*freq.max(), 5)\nfreq_ticklabels = np.round(100*freq_ticks)/100\nax_frequency.set_yticks(freq_ticks)\nax_frequency.set_yticklabels(freq_ticklabels)\nax_cumulative.set_yticks(np.linspace(0, 1, 5))\nax_cumulative.grid(which='major', axis='y')\nax_cumulative.set_ylim((0,1))\n\n\nfig.suptitle('Topic Mixutre L1-Errors')\nfig.set_dpi(110)",
"_____no_output_____"
]
],
[
[
"Machine learning algorithms are not perfect and the data above suggests this is true of SageMaker LDA. With more documents and some hyperparameter tuning we can obtain more accurate results against the known topic-mixtures.\n\nFor now, let's just investigate the documents-topic mixture pairs that seem to do well as well as those that do not. Below we retreive a document and topic mixture corresponding to a small L1-error as well as one with a large L1-error.",
"_____no_output_____"
]
],
[
[
"N = 6\n\ngood_idx = (l1_errors < 0.05)\ngood_documents = payload_documents[good_idx][:N]\ngood_topic_mixtures = inferred_topic_mixtures[good_idx][:N]\n\npoor_idx = (l1_errors > 0.3)\npoor_documents = payload_documents[poor_idx][:N]\npoor_topic_mixtures = inferred_topic_mixtures[poor_idx][:N]",
"_____no_output_____"
],
[
"%matplotlib inline\n\nfig = plot_lda_topics(good_documents, 2, 3, topic_mixtures=good_topic_mixtures)\nfig.suptitle('Documents With Accurate Inferred Topic-Mixtures')\nfig.set_dpi(120)",
"_____no_output_____"
],
[
"%matplotlib inline\n\nfig = plot_lda_topics(poor_documents, 2, 3, topic_mixtures=poor_topic_mixtures)\nfig.suptitle('Documents With Inaccurate Inferred Topic-Mixtures')\nfig.set_dpi(120)",
"_____no_output_____"
]
],
[
[
"In this example set the documents on which inference was not as accurate tend to have a denser topic-mixture. This makes sense when extrapolated to real-world datasets: it can be difficult to nail down which topics are represented in a document when the document uses words from a large subset of the vocabulary.",
"_____no_output_____"
],
[
"## Stop / Close the Endpoint\n\nFinally, we should delete the endpoint before we close the notebook.\n\nTo do so execute the cell below. Alternately, you can navigate to the \"Endpoints\" tab in the SageMaker console, select the endpoint with the name stored in the variable `endpoint_name`, and select \"Delete\" from the \"Actions\" dropdown menu. ",
"_____no_output_____"
]
],
[
[
"sagemaker.Session().delete_endpoint(lda_inference.endpoint)",
"_____no_output_____"
]
],
[
[
"# Epilogue\n\n---\n\nIn this notebook we,\n\n* learned about the LDA model,\n* generated some example LDA documents and their corresponding topic-mixtures,\n* trained a SageMaker LDA model on a training set of documents and compared the learned model to the known model,\n* created an inference endpoint,\n* used the endpoint to infer the topic mixtures of a test input and analyzed the inference error.\n\nThere are several things to keep in mind when applying SageMaker LDA to real-word data such as a corpus of text documents. Note that input documents to the algorithm, both in training and inference, need to be vectors of integers representing word counts. Each index corresponds to a word in the corpus vocabulary. Therefore, one will need to \"tokenize\" their corpus vocabulary.\n\n$$\n\\text{\"cat\"} \\mapsto 0, \\; \\text{\"dog\"} \\mapsto 1 \\; \\text{\"bird\"} \\mapsto 2, \\ldots\n$$\n\nEach text document then needs to be converted to a \"bag-of-words\" format document.\n\n$$\nw = \\text{\"cat bird bird bird cat\"} \\quad \\longmapsto \\quad w = [2, 0, 3, 0, \\ldots, 0]\n$$\n\nAlso note that many real-word applications have large vocabulary sizes. It may be necessary to represent the input documents in sparse format. Finally, the use of stemming and lemmatization in data preprocessing provides several benefits. Doing so can improve training and inference compute time since it reduces the effective vocabulary size. More importantly, though, it can improve the quality of learned topic-word probability matrices and inferred topic mixtures. For example, the words *\"parliament\"*, *\"parliaments\"*, *\"parliamentary\"*, *\"parliament's\"*, and *\"parliamentarians\"* are all essentially the same word, *\"parliament\"*, but with different conjugations. For the purposes of detecting topics, such as a *\"politics\"* or *governments\"* topic, the inclusion of all five does not add much additional value as they all essentiall describe the same feature.",
"_____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",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"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",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
d082c59e6f6396e4cc73d47a14fbe34bc0ef20cc | 1,108 | ipynb | Jupyter Notebook | ex1_w2v/eval_mclf.ipynb | minkj1992/Korean_emotion_classification_attention | 7e09cd8cd9b18c438d7b9032efb8ee37c505a7fa | [
"MIT"
] | 3 | 2020-04-24T12:54:37.000Z | 2021-12-21T02:03:06.000Z | ex1_w2v/eval_mclf.ipynb | minkj1992/Korean_emotion_classification_attention | 7e09cd8cd9b18c438d7b9032efb8ee37c505a7fa | [
"MIT"
] | null | null | null | ex1_w2v/eval_mclf.ipynb | minkj1992/Korean_emotion_classification_attention | 7e09cd8cd9b18c438d7b9032efb8ee37c505a7fa | [
"MIT"
] | 3 | 2020-03-10T10:50:03.000Z | 2021-12-21T02:03:07.000Z | 23.574468 | 75 | 0.465704 | [
[
[
"import numpy\n\ndef eval_mclf(y, y_hat):\n results = {\n \"jaccard\": jaccard_similarity_score(numpy.array(y),\n numpy.array(y_hat)),\n \"f1-macro\": f1_score(numpy.array(y), numpy.array(y_hat),\n average='macro'),\n \"f1-micro\": f1_score(numpy.array(y), numpy.array(y_hat),\n average='micro')\n }\n\n return results",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code"
]
] |
d082cbb28b08e19c206a4478929a01fab10fe9aa | 3,086 | ipynb | Jupyter Notebook | core/Python truthy and falsy values quiz.ipynb | ValRCS/Python_DIP720_RTU_Spring_2021 | b24b14b80ceeee51355d32977f3b46e0e39d3563 | [
"MIT"
] | 1 | 2021-04-15T14:33:55.000Z | 2021-04-15T14:33:55.000Z | core/Python truthy and falsy values quiz.ipynb | ValRCS/Python_DIP720_RTU_Spring_2021 | b24b14b80ceeee51355d32977f3b46e0e39d3563 | [
"MIT"
] | null | null | null | core/Python truthy and falsy values quiz.ipynb | ValRCS/Python_DIP720_RTU_Spring_2021 | b24b14b80ceeee51355d32977f3b46e0e39d3563 | [
"MIT"
] | null | null | null | 18.590361 | 153 | 0.475373 | [
[
[
"a = 10 # this is truthy (not false)\nb = 20 # also truthy\nc = a and b and True and 55 and a # so instead of True as one might expect\n# Python assigns the last truthy value\n\nc",
"_____no_output_____"
],
[
"d = a == 10 and b == 20 # so this is more usual \nd",
"_____no_output_____"
],
[
"t = a or b # in this case we get first truthy because \n# because with or we only need one truthy value to have everything true\nt",
"_____no_output_____"
],
[
"t = False or 0 or b or a # so here b == 20 so b will be used\nt",
"_____no_output_____"
],
[
"t = \"\" or False or 0 or \"Valdis\" or a\nt",
"_____no_output_____"
],
[
"t = \"Valdis\" and \"RTU\" and a and \"Python is truthy\"\nt",
"_____no_output_____"
]
],
[
[
"##### Falsy and Truthy Values\n\nhttps://www.pythontutorial.net/python-basics/python-boolean/#:~:text=Python%20boolean%20data%20type%20has,tuple%2C%20and%20an%20empty%20dictionary.",
"_____no_output_____"
]
]
] | [
"code",
"markdown"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
d082dffbd862b5dd2bad5d3f4e1b156ac950a990 | 1,644 | ipynb | Jupyter Notebook | minEditDist.ipynb | AKASHX5/Bioinformatics | ba646b0983dc61b2280f4d68668ee31e7eb54b97 | [
"MIT"
] | null | null | null | minEditDist.ipynb | AKASHX5/Bioinformatics | ba646b0983dc61b2280f4d68668ee31e7eb54b97 | [
"MIT"
] | null | null | null | minEditDist.ipynb | AKASHX5/Bioinformatics | ba646b0983dc61b2280f4d68668ee31e7eb54b97 | [
"MIT"
] | null | null | null | 19.341176 | 101 | 0.448905 | [
[
[
"def minEditDistR(target, source):\n \n \n\n i = len(target)\n j = len(source)\n\n if i == 0:\n \n return j\n elif j == 0:\n return i\n\n return(min(minEditDistR(target[:i-1],source)+1,\n minEditDistR(target, source[:j-1])+1,\n minEditDistR(target[:i-1], source[:j-1])+substCost(source[j-1], target[i-1])))\n\n\n\ndef substCost(x,y):\n if x == y: return 0\n else: return 2\n \n\n \n\nref1='intution'\nref2='execution'\nminEditDistR(ref1,ref2)\n",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code"
]
] |
d082e24118a63a39311f4af6bab59b8d109ea1f5 | 161,157 | ipynb | Jupyter Notebook | TCN_TimeSeries_Approach.ipynb | ashishpatel26/tcn-keras-Examples | 50cbc05720c9df69cb8948c8c10acbf2a752b7a8 | [
"MIT"
] | 29 | 2020-09-15T12:26:58.000Z | 2022-03-24T00:00:53.000Z | TCN_TimeSeries_Approach.ipynb | ashishpatel26/tcn-keras-Examples | 50cbc05720c9df69cb8948c8c10acbf2a752b7a8 | [
"MIT"
] | null | null | null | TCN_TimeSeries_Approach.ipynb | ashishpatel26/tcn-keras-Examples | 50cbc05720c9df69cb8948c8c10acbf2a752b7a8 | [
"MIT"
] | 12 | 2020-09-22T03:52:00.000Z | 2022-03-22T21:32:37.000Z | 156.76751 | 124,578 | 0.837798 | [
[
[
"<a href=\"https://colab.research.google.com/github/ashishpatel26/tcn-keras-Examples/blob/master/TCN_TimeSeries_Approach.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"### Load Library",
"_____no_output_____"
]
],
[
[
"!pip install wget\n!pip install keras-tcn\nimport wget\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom tensorflow.keras import Input, Model\nfrom tensorflow.keras.layers import Dense\nfrom tqdm.notebook import tqdm\n\nfrom tcn import TCN",
"Requirement already satisfied: wget in /usr/local/lib/python3.6/dist-packages (3.2)\nRequirement already satisfied: keras-tcn in /usr/local/lib/python3.6/dist-packages (3.1.1)\nRequirement already satisfied: keras==2.3.1 in /usr/local/lib/python3.6/dist-packages (from keras-tcn) (2.3.1)\nRequirement already satisfied: numpy>=1.18.1 in /usr/local/lib/python3.6/dist-packages (from keras-tcn) (1.18.5)\nRequirement already satisfied: six>=1.9.0 in /usr/local/lib/python3.6/dist-packages (from keras==2.3.1->keras-tcn) (1.15.0)\nRequirement already satisfied: scipy>=0.14 in /usr/local/lib/python3.6/dist-packages (from keras==2.3.1->keras-tcn) (1.4.1)\nRequirement already satisfied: pyyaml in /usr/local/lib/python3.6/dist-packages (from keras==2.3.1->keras-tcn) (3.13)\nRequirement already satisfied: keras-preprocessing>=1.0.5 in /usr/local/lib/python3.6/dist-packages (from keras==2.3.1->keras-tcn) (1.1.2)\nRequirement already satisfied: h5py in /usr/local/lib/python3.6/dist-packages (from keras==2.3.1->keras-tcn) (2.10.0)\nRequirement already satisfied: keras-applications>=1.0.6 in /usr/local/lib/python3.6/dist-packages (from keras==2.3.1->keras-tcn) (1.0.8)\n"
],
[
"wget.download(\"https://github.com/philipperemy/keras-tcn/raw/master/tasks/monthly-milk-production-pounds-p.csv\")",
"_____no_output_____"
]
],
[
[
"### Read the dataset",
"_____no_output_____"
]
],
[
[
"milk = pd.read_csv('monthly-milk-production-pounds-p.csv', index_col=0, parse_dates=True)",
"_____no_output_____"
]
],
[
[
"### Display top5 Record",
"_____no_output_____"
]
],
[
[
"print(milk.shape)\nmilk.head()",
"(168, 1)\n"
]
],
[
[
"### Lookback 12 month windows",
"_____no_output_____"
]
],
[
[
"lookback_window = 12 ",
"_____no_output_____"
]
],
[
[
"### Convert Milk Data into Numpy Array",
"_____no_output_____"
]
],
[
[
"milk = milk.values ",
"_____no_output_____"
]
],
[
[
"### Convert in to X, y format",
"_____no_output_____"
]
],
[
[
"x = []\ny = []\nfor i in tqdm(range(lookback_window, len(milk))):\n x.append(milk[i - lookback_window:i])\n y.append(milk[i])",
"_____no_output_____"
]
],
[
[
"### Generate Array of list x and y",
"_____no_output_____"
]
],
[
[
"x = np.array(x)\ny = np.array(y)\nprint(x.shape)\nprint(y.shape)",
"(156, 12, 1)\n(156, 1)\n"
]
],
[
[
"### Model Design",
"_____no_output_____"
]
],
[
[
"i = Input(shape=(lookback_window, 1))\nm = TCN()(i)\nm = Dense(1, activation='linear')(m)\n\nmodel = Model(inputs=[i], outputs=[m])\nmodel.summary()",
"Model: \"functional_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_1 (InputLayer) [(None, 12, 1)] 0 \n_________________________________________________________________\ntcn (TCN) (None, 64) 91136 \n_________________________________________________________________\ndense (Dense) (None, 1) 65 \n=================================================================\nTotal params: 91,201\nTrainable params: 91,201\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"model.compile('adam','mae')",
"_____no_output_____"
]
],
[
[
"### Time for Model training...",
"_____no_output_____"
]
],
[
[
"print('Train...')\nmodel.fit(x, y, epochs=100)",
"Train...\nEpoch 1/100\n5/5 [==============================] - 0s 25ms/step - loss: 271.5721\nEpoch 2/100\n5/5 [==============================] - 0s 26ms/step - loss: 202.3601\nEpoch 3/100\n5/5 [==============================] - 0s 23ms/step - loss: 129.1283\nEpoch 4/100\n5/5 [==============================] - 0s 25ms/step - loss: 119.5586\nEpoch 5/100\n5/5 [==============================] - 0s 25ms/step - loss: 82.7962\nEpoch 6/100\n5/5 [==============================] - 0s 23ms/step - loss: 29.5778\nEpoch 7/100\n5/5 [==============================] - 0s 23ms/step - loss: 26.9950\nEpoch 8/100\n5/5 [==============================] - 0s 25ms/step - loss: 23.8581\nEpoch 9/100\n5/5 [==============================] - 0s 23ms/step - loss: 27.1797\nEpoch 10/100\n5/5 [==============================] - 0s 24ms/step - loss: 37.1005\nEpoch 11/100\n5/5 [==============================] - 0s 27ms/step - loss: 38.2245\nEpoch 12/100\n5/5 [==============================] - 0s 23ms/step - loss: 27.9166\nEpoch 13/100\n5/5 [==============================] - 0s 27ms/step - loss: 49.9146\nEpoch 14/100\n5/5 [==============================] - 0s 24ms/step - loss: 31.0408\nEpoch 15/100\n5/5 [==============================] - 0s 25ms/step - loss: 23.8059\nEpoch 16/100\n5/5 [==============================] - 0s 24ms/step - loss: 18.7888\nEpoch 17/100\n5/5 [==============================] - 0s 24ms/step - loss: 25.1425\nEpoch 18/100\n5/5 [==============================] - 0s 25ms/step - loss: 32.6869\nEpoch 19/100\n5/5 [==============================] - 0s 23ms/step - loss: 31.6958\nEpoch 20/100\n5/5 [==============================] - 0s 23ms/step - loss: 31.2011\nEpoch 21/100\n5/5 [==============================] - 0s 23ms/step - loss: 22.9983\nEpoch 22/100\n5/5 [==============================] - 0s 25ms/step - loss: 27.7421\nEpoch 23/100\n5/5 [==============================] - 0s 24ms/step - loss: 29.9864\nEpoch 24/100\n5/5 [==============================] - 0s 23ms/step - loss: 68.7743\nEpoch 25/100\n5/5 [==============================] - 0s 23ms/step - loss: 41.1511\nEpoch 26/100\n5/5 [==============================] - 0s 24ms/step - loss: 35.2367\nEpoch 27/100\n5/5 [==============================] - 0s 23ms/step - loss: 66.6526\nEpoch 28/100\n5/5 [==============================] - 0s 24ms/step - loss: 40.3432\nEpoch 29/100\n5/5 [==============================] - 0s 23ms/step - loss: 50.4716\nEpoch 30/100\n5/5 [==============================] - 0s 25ms/step - loss: 48.0320\nEpoch 31/100\n5/5 [==============================] - 0s 24ms/step - loss: 34.7563\nEpoch 32/100\n5/5 [==============================] - 0s 24ms/step - loss: 27.2386\nEpoch 33/100\n5/5 [==============================] - 0s 24ms/step - loss: 32.2853\nEpoch 34/100\n5/5 [==============================] - 0s 25ms/step - loss: 26.1964\nEpoch 35/100\n5/5 [==============================] - 0s 25ms/step - loss: 22.9360\nEpoch 36/100\n5/5 [==============================] - 0s 23ms/step - loss: 25.1416\nEpoch 37/100\n5/5 [==============================] - 0s 24ms/step - loss: 30.5617\nEpoch 38/100\n5/5 [==============================] - 0s 25ms/step - loss: 24.7003\nEpoch 39/100\n5/5 [==============================] - 0s 23ms/step - loss: 14.7676\nEpoch 40/100\n5/5 [==============================] - 0s 24ms/step - loss: 14.6580\nEpoch 41/100\n5/5 [==============================] - 0s 24ms/step - loss: 12.4486\nEpoch 42/100\n5/5 [==============================] - 0s 24ms/step - loss: 15.5033\nEpoch 43/100\n5/5 [==============================] - 0s 23ms/step - loss: 20.4509\nEpoch 44/100\n5/5 [==============================] - 0s 23ms/step - loss: 27.3433\nEpoch 45/100\n5/5 [==============================] - 0s 23ms/step - loss: 25.6425\nEpoch 46/100\n5/5 [==============================] - 0s 24ms/step - loss: 23.2722\nEpoch 47/100\n5/5 [==============================] - 0s 24ms/step - loss: 19.9241\nEpoch 48/100\n5/5 [==============================] - 0s 23ms/step - loss: 26.6964\nEpoch 49/100\n5/5 [==============================] - 0s 23ms/step - loss: 51.5725\nEpoch 50/100\n5/5 [==============================] - 0s 24ms/step - loss: 46.1796\nEpoch 51/100\n5/5 [==============================] - 0s 24ms/step - loss: 43.5478\nEpoch 52/100\n5/5 [==============================] - 0s 23ms/step - loss: 48.7085\nEpoch 53/100\n5/5 [==============================] - 0s 23ms/step - loss: 46.6810\nEpoch 54/100\n5/5 [==============================] - 0s 23ms/step - loss: 37.4476\nEpoch 55/100\n5/5 [==============================] - 0s 24ms/step - loss: 40.0287\nEpoch 56/100\n5/5 [==============================] - 0s 25ms/step - loss: 31.3757\nEpoch 57/100\n5/5 [==============================] - 0s 23ms/step - loss: 23.3440\nEpoch 58/100\n5/5 [==============================] - 0s 24ms/step - loss: 25.6717\nEpoch 59/100\n5/5 [==============================] - 0s 23ms/step - loss: 22.8951\nEpoch 60/100\n5/5 [==============================] - 0s 24ms/step - loss: 16.8260\nEpoch 61/100\n5/5 [==============================] - 0s 23ms/step - loss: 19.1047\nEpoch 62/100\n5/5 [==============================] - 0s 23ms/step - loss: 21.6529\nEpoch 63/100\n5/5 [==============================] - 0s 23ms/step - loss: 16.5754\nEpoch 64/100\n5/5 [==============================] - 0s 24ms/step - loss: 12.2943\nEpoch 65/100\n5/5 [==============================] - 0s 25ms/step - loss: 14.4700\nEpoch 66/100\n5/5 [==============================] - 0s 24ms/step - loss: 12.4727\nEpoch 67/100\n5/5 [==============================] - 0s 24ms/step - loss: 12.2146\nEpoch 68/100\n5/5 [==============================] - 0s 23ms/step - loss: 24.3314\nEpoch 69/100\n5/5 [==============================] - 0s 23ms/step - loss: 23.2591\nEpoch 70/100\n5/5 [==============================] - 0s 23ms/step - loss: 21.5991\nEpoch 71/100\n5/5 [==============================] - 0s 24ms/step - loss: 34.6669\nEpoch 72/100\n5/5 [==============================] - 0s 24ms/step - loss: 58.7299\nEpoch 73/100\n5/5 [==============================] - 0s 24ms/step - loss: 30.8628\nEpoch 74/100\n5/5 [==============================] - 0s 23ms/step - loss: 36.4043\nEpoch 75/100\n5/5 [==============================] - 0s 23ms/step - loss: 45.6252\nEpoch 76/100\n5/5 [==============================] - 0s 24ms/step - loss: 29.5786\nEpoch 77/100\n5/5 [==============================] - 0s 23ms/step - loss: 16.1575\nEpoch 78/100\n5/5 [==============================] - 0s 24ms/step - loss: 24.9460\nEpoch 79/100\n5/5 [==============================] - 0s 23ms/step - loss: 17.0462\nEpoch 80/100\n5/5 [==============================] - 0s 23ms/step - loss: 13.5069\nEpoch 81/100\n5/5 [==============================] - 0s 24ms/step - loss: 14.0239\nEpoch 82/100\n5/5 [==============================] - 0s 23ms/step - loss: 12.9607\nEpoch 83/100\n5/5 [==============================] - 0s 23ms/step - loss: 13.6181\nEpoch 84/100\n5/5 [==============================] - 0s 23ms/step - loss: 12.3904\nEpoch 85/100\n5/5 [==============================] - 0s 26ms/step - loss: 13.5270\nEpoch 86/100\n5/5 [==============================] - 0s 23ms/step - loss: 18.3469\nEpoch 87/100\n5/5 [==============================] - 0s 24ms/step - loss: 20.0561\nEpoch 88/100\n5/5 [==============================] - 0s 22ms/step - loss: 19.5092\nEpoch 89/100\n5/5 [==============================] - 0s 23ms/step - loss: 22.7791\nEpoch 90/100\n5/5 [==============================] - 0s 22ms/step - loss: 20.7960\nEpoch 91/100\n5/5 [==============================] - 0s 23ms/step - loss: 26.3365\nEpoch 92/100\n5/5 [==============================] - 0s 24ms/step - loss: 21.1719\nEpoch 93/100\n5/5 [==============================] - 0s 22ms/step - loss: 19.5793\nEpoch 94/100\n5/5 [==============================] - 0s 23ms/step - loss: 22.3828\nEpoch 95/100\n5/5 [==============================] - 0s 23ms/step - loss: 20.0138\nEpoch 96/100\n5/5 [==============================] - 0s 23ms/step - loss: 26.0298\nEpoch 97/100\n5/5 [==============================] - 0s 23ms/step - loss: 15.8576\nEpoch 98/100\n5/5 [==============================] - 0s 23ms/step - loss: 26.3697\nEpoch 99/100\n5/5 [==============================] - 0s 24ms/step - loss: 14.8465\nEpoch 100/100\n5/5 [==============================] - 0s 22ms/step - loss: 13.5129\n"
]
],
[
[
"### Prediction with TCN Model",
"_____no_output_____"
]
],
[
[
"predict = model.predict(x)",
"_____no_output_____"
]
],
[
[
"### Plot the Result",
"_____no_output_____"
]
],
[
[
"plt.style.use(\"fivethirtyeight\")\nplt.figure(figsize = (15,7))\nplt.plot(predict)\nplt.plot(y)\nplt.title('Monthly Milk Production (in pounds)')\nplt.legend(['predicted', 'actual'])\nplt.xlabel(\"Moths Counts\")\nplt.ylabel(\"Milk Production in Pounds\")\nplt.show()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
d082e4e534a9e9980b0417f47b904056d1309854 | 1,010 | ipynb | Jupyter Notebook | code/algorithms/course_udemy_1/Mock Interviews/Social/Questions/Phone Screen .ipynb | vicb1/miscellaneous | 2c9762579abf75ef6cba75d1d1536a693d69e82a | [
"MIT"
] | null | null | null | code/algorithms/course_udemy_1/Mock Interviews/Social/Questions/Phone Screen .ipynb | vicb1/miscellaneous | 2c9762579abf75ef6cba75d1d1536a693d69e82a | [
"MIT"
] | null | null | null | code/algorithms/course_udemy_1/Mock Interviews/Social/Questions/Phone Screen .ipynb | vicb1/miscellaneous | 2c9762579abf75ef6cba75d1d1536a693d69e82a | [
"MIT"
] | null | null | null | 21.041667 | 173 | 0.549505 | [
[
[
"# Phone Screen \n\n## Problem \n\n** Remove duplicate characters in a given string keeping only the first occurrences. For example, if the input is ‘tree traversal’ the output will be ‘tre avsl’. **\n\n## Requirements\n\n**Complete this problem on a text editor that does not have syntax highlighting, such as a goolge doc!**",
"_____no_output_____"
],
[
"# Good Luck!",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown",
"markdown"
]
] |
d082ef79bb0dfa3c9458937721c74f20c3add4a7 | 18,735 | ipynb | Jupyter Notebook | 11_synchro.extracting.ipynb | Ines-Filipa/theonerig | 0a4f6c30deea31fa6a8e8584d45bc345aa9109fd | [
"Apache-2.0"
] | null | null | null | 11_synchro.extracting.ipynb | Ines-Filipa/theonerig | 0a4f6c30deea31fa6a8e8584d45bc345aa9109fd | [
"Apache-2.0"
] | null | null | null | 11_synchro.extracting.ipynb | Ines-Filipa/theonerig | 0a4f6c30deea31fa6a8e8584d45bc345aa9109fd | [
"Apache-2.0"
] | null | null | null | 34.439338 | 350 | 0.521591 | [
[
[
"#default_exp synchro.extracting",
"_____no_output_____"
],
[
"from nbdev.showdoc import *",
"_____no_output_____"
],
[
"%load_ext autoreload\n%autoreload 2",
"_____no_output_____"
]
],
[
[
"# synchro.extracting\n> Function to extract data of an experiment from 3rd party programs",
"_____no_output_____"
],
[
"To align timeseries of an experiment, we need to read logs and import data produced by 3rd party softwares used during the experiment. It includes:\n* QDSpy logging\n* Numpy arrays of the stimuli\n* SpykingCircus spike sorting refined with Phy\n* Eye tracking results from MaskRCNN",
"_____no_output_____"
]
],
[
[
"#export\nimport numpy as np\nimport datetime\nimport os, glob\nimport csv\nimport re\n\nfrom theonerig.synchro.io import *\nfrom theonerig.utils import *\n\ndef get_QDSpy_logs(log_dir):\n \"\"\"Factory function to generate QDSpy_log objects from all the QDSpy logs of the folder `log_dir`\"\"\"\n log_names = glob.glob(os.path.join(log_dir,'[0-9]*.log'))\n qdspy_logs = [QDSpy_log(log_name) for log_name in log_names]\n for qdspy_log in qdspy_logs:\n qdspy_log.find_stimuli()\n return qdspy_logs\n\nclass QDSpy_log:\n \"\"\"Class defining a QDSpy log. \n It reads the log it represent and extract the stimuli information from it:\n - Start and end time\n - Parameters like the md5 key\n - Frame delays\n \"\"\"\n def __init__(self, log_path):\n self.log_path = log_path\n self.stimuli = []\n self.comments = []\n \n def _extract_data(self, data_line):\n data = data_line[data_line.find('{')+1:data_line.find('}')]\n data_splitted = data.split(',')\n data_dict = {}\n for data in data_splitted:\n ind = data.find(\"'\")\n if type(data[data.find(\":\")+2:]) is str:\n data_dict[data[ind+1:data.find(\"'\",ind+1)]] = data[data.find(\":\")+2:][1:-1]\n else:\n data_dict[data[ind+1:data.find(\"'\",ind+1)]] = data[data.find(\":\")+2:]\n return data_dict\n\n def _extract_time(self,data_line):\n return datetime.datetime.strptime(data_line.split()[0], '%Y%m%d_%H%M%S')\n \n def _extract_delay(self,data_line):\n ind = data_line.find('#')\n index_frame = int(data_line[ind+1:data_line.find(' ',ind)])\n ind = data_line.find('was')\n delay = float(data_line[ind:].split(\" \")[1])\n return (index_frame, delay)\n \n def __repr__(self):\n return \"\\n\".join([str(stim) for stim in self.stimuli])\n \n @property\n def n_stim(self):\n return len(self.stimuli)\n\n @property\n def stim_names(self):\n return [stim.name for stim in self.stimuli]\n \n def find_stimuli(self):\n \"\"\"Find the stimuli in the log file and return the list of the stimuli\n found by this object.\"\"\"\n with open(self.log_path, 'r', encoding=\"ISO-8859-1\") as log_file:\n for line in log_file:\n if \"DATA\" in line:\n data_juice = self._extract_data(line)\n if 'stimState' in data_juice.keys():\n if data_juice['stimState'] == \"STARTED\" :\n curr_stim = Stimulus(self._extract_time(line))\n curr_stim.set_parameters(data_juice)\n self.stimuli.append(curr_stim)\n stimulus_ON = True\n elif data_juice['stimState'] == \"FINISHED\" or data_juice['stimState'] == \"ABORTED\":\n curr_stim.is_aborted = data_juice['stimState'] == \"ABORTED\"\n curr_stim.stop_time = self._extract_time(line)\n stimulus_ON = False\n\n elif 'userComment' in data_juice.keys():\n pass\n #print(\"userComment, use it to bind logs to records\")\n elif stimulus_ON: #Information on stimulus parameters\n curr_stim.set_parameters(data_juice)\n # elif 'probeX' in data_juice.keys():\n # print(\"Probe center not implemented yet\")\n if \"WARNING\" in line and \"dt of frame\" and stimulus_ON:\n curr_stim.frame_delay.append(self._extract_delay(line))\n if curr_stim.frame_delay[-1][1] > 2000/60: #if longer than 2 frames could be bad\n print(curr_stim.name, \" \".join(line.split()[1:])[:-1])\n return self.stimuli\n \nclass Stimulus:\n \"\"\"Stimulus object containing information about it's presentation.\n - start_time : a datetime object)\n - stop_time : a datetime object)\n - parameters : Parameters extracted from the QDSpy\n - md5 : The md5 hash of that compiled version of the stimulus\n - name : The name of the stimulus \n \"\"\"\n def __init__(self,start):\n self.start_time = start\n self.stop_time = None\n self.parameters = {}\n self.md5 = None\n self.name = \"NoName\"\n \n self.frame_delay = []\n self.is_aborted = False\n\n def set_parameters(self, parameters):\n self.parameters.update(parameters)\n if \"_sName\" in parameters.keys():\n self.name = parameters[\"_sName\"]\n if \"stimMD5\" in parameters.keys():\n self.md5 = parameters[\"stimMD5\"]\n\n def __str__(self):\n return \"%s %s at %s\" %(self.name+\" \"*(24-len(self.name)),self.md5,self.start_time)\n \n def __repr__(self):\n return self.__str__()",
"_____no_output_____"
]
],
[
[
"To read QDSpy logs of your experiment, simply provide the folder containing the log you want to read to `get_QDSpy_logs`",
"_____no_output_____"
]
],
[
[
"#logs = get_QDSpy_logs(\"./files/basic_synchro\")",
"flickering_bars_pr WARNING dt of frame #15864 was 50.315 m\nflickering_bars_pr WARNING dt of frame #19477 was 137.235 m\n"
]
],
[
[
"It returns a list fo the QDSpy logs. Stimuli are contained in a list inside each log:",
"_____no_output_____"
]
],
[
[
"#logs[0].stimuli",
"_____no_output_____"
]
],
[
[
"The stimuli objects contains informations on how their display went: ",
"_____no_output_____"
]
],
[
[
"# stim = logs[0].stimuli[5]\n# print(stim.name, stim.start_time, stim.frame_delay, stim.md5)",
"flickering_bars_pr 2020-03-31 17:30:25 [(15864, 50.315), (19477, 137.235)] 0049591cdf7aa379a458230e84cc3eec\n"
],
[
"#export\ndef unpack_stim_npy(npy_dir, md5_hash):\n \"\"\"Find the stimuli of a given hash key in the npy stimulus folder. The stimuli are in a compressed version\n comprising three files. inten for the stimulus values on the screen, marker for the values of the marker\n read by a photodiode to get the stimulus timing during a record, and an optional shader that is used to\n specify informations about a shader when used, like for the moving gratings.\"\"\"\n \n #Stimuli can be either npy or npz (useful when working remotely)\n def find_file(ftype):\n flist = glob.glob(os.path.join(npy_dir, \"*_\"+ftype+\"_\"+md5_hash+\".npy\"))\n if len(flist)==0:\n flist = glob.glob(os.path.join(npy_dir, \"*_\"+ftype+\"_\"+md5_hash+\".npz\"))\n res = np.load(flist[0])[\"arr_0\"]\n else:\n res = np.load(flist[0])\n return res\n \n inten = find_file(\"intensities\")\n marker = find_file(\"marker\")\n \n shader, unpack_shader = None, None\n if len(glob.glob(os.path.join(npy_dir, \"*_shader_\"+md5_hash+\".np*\")))>0:\n shader = find_file(\"shader\")\n unpack_shader = np.empty((np.sum(marker[:,0]), *shader.shape[1:]))\n\n #The latter unpacks the arrays\n unpack_inten = np.empty((np.sum(marker[:,0]), *inten.shape[1:]))\n unpack_marker = np.empty(np.sum(marker[:,0]))\n\n cursor = 0\n for i, n_frame in enumerate(marker[:,0]):\n unpack_inten[cursor:cursor+n_frame] = inten[i]\n unpack_marker[cursor:cursor+n_frame] = marker[i, 1]\n if shader is not None:\n unpack_shader[cursor:cursor+n_frame] = shader[i]\n cursor += n_frame\n \n return unpack_inten, unpack_marker, unpack_shader",
"_____no_output_____"
],
[
"# logs = get_QDSpy_logs(\"./files/basic_synchro\")",
"flickering_bars_pr WARNING dt of frame #15864 was 50.315 m\nflickering_bars_pr WARNING dt of frame #19477 was 137.235 m\n"
]
],
[
[
"To unpack the stimulus values, provide the folder of the numpy arrays and the hash of the stimulus:",
"_____no_output_____"
]
],
[
[
"# unpacked = unpack_stim_npy(\"./files/basic_synchro/stimulus_data\", \"eed21bda540934a428e93897908d049e\")",
"_____no_output_____"
]
],
[
[
"Unpacked is a tuple, where the first element is the intensity of shape (n_frames, n_colors, y, x)",
"_____no_output_____"
]
],
[
[
"# unpacked[0].shape",
"_____no_output_____"
]
],
[
[
"The second element of the tuple repesents the marker values for the timing. QDSpy defaults are zero and ones, but I used custom red squares taking intensities [50,100,150,200,250] to time with five different signals",
"_____no_output_____"
]
],
[
[
"# unpacked[1][:50]",
"_____no_output_____"
]
],
[
[
"Each stimulus is also starting with a barcode, of the form:\n\n0 0 0 0 0 0 4 0 4\\*[1-4] 0 4\\*[1-4] 0 4\\*[1-4] 0 4\\*[1-4] 0 4 0 0 0 0 0 0 \n\nand ends with 0 0 0 0 0 0",
"_____no_output_____"
]
],
[
[
"#export\ndef extract_spyking_circus_results(dir_, record_basename):\n \"\"\"Extract the good cells of a record. Overlap with phy_results_dict.\"\"\"\n phy_dir = os.path.join(dir_,record_basename+\"/\"+record_basename+\".GUI\")\n phy_dict = phy_results_dict(phy_dir)\n \n good_clusters = []\n with open(os.path.join(phy_dir,'cluster_group.tsv'), 'r') as tsvfile:\n spamreader = csv.reader(tsvfile, delimiter='\\t', quotechar='|')\n for i,row in enumerate(spamreader):\n if row[1] == \"good\":\n good_clusters.append(int(row[0]))\n good_clusters = np.array(good_clusters)\n \n phy_dict[\"good_clusters\"] = good_clusters\n \n return phy_dict",
"_____no_output_____"
],
[
"#export\ndef extract_best_pupil(fn):\n \"\"\"From results of MaskRCNN, go over all or None pupil detected and select the best pupil.\n Each pupil returned is (x,y,width,height,angle,probability)\"\"\"\n pupil = np.load(fn, allow_pickle=True)\n filtered_pupil = np.empty((len(pupil), 6))\n for i, detected in enumerate(pupil):\n if len(detected)>0:\n best = detected[0]\n for detect in detected[1:]:\n if detect[5]>best[5]:\n best = detect\n filtered_pupil[i] = np.array(best)\n else:\n filtered_pupil[i] = np.array([0,0,0,0,0,0])\n return filtered_pupil",
"_____no_output_____"
],
[
"#export\ndef stack_len_extraction(stack_info_dir):\n \"\"\"Extract from ImageJ macro directives the size of the stacks acquired.\"\"\"\n ptrn_nFrame = r\".*number=(\\d*) .*\"\n l_epochs = []\n for fn in glob.glob(os.path.join(stack_info_dir, \"*.txt\")):\n with open(fn) as f:\n line = f.readline()\n l_epochs.append(int(re.findall(ptrn_nFrame, line)[0]))\n return l_epochs",
"_____no_output_____"
],
[
"#hide\nfrom nbdev.export import *\nnotebook2script()",
"Converted 00_core.ipynb.\nConverted 01_utils.ipynb.\nConverted 02_processing.ipynb.\nConverted 03_modelling.ipynb.\nConverted 04_plotting.ipynb.\nConverted 05_database.ipynb.\nConverted 10_synchro.io.ipynb.\nConverted 11_synchro.extracting.ipynb.\nConverted 12_synchro.processing.ipynb.\nConverted 99_testdata.ipynb.\nConverted index.ipynb.\n"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
d083095572355ae4901d471676225eb23b1010e8 | 19,013 | ipynb | Jupyter Notebook | notebooks/PlantDisease_tutorial.ipynb | Julia2505/deep_learning_for_biologists | fa3283d784689794c5b88b52a1c6e2c610ddca9b | [
"Net-SNMP",
"Xnet",
"OML"
] | 91 | 2019-01-15T13:04:38.000Z | 2022-02-23T05:07:01.000Z | notebooks/PlantDisease_tutorial.ipynb | Julia2505/deep_learning_for_biologists | fa3283d784689794c5b88b52a1c6e2c610ddca9b | [
"Net-SNMP",
"Xnet",
"OML"
] | 2 | 2019-01-16T01:43:45.000Z | 2019-01-17T14:59:35.000Z | notebooks/PlantDisease_tutorial.ipynb | Julia2505/deep_learning_for_biologists | fa3283d784689794c5b88b52a1c6e2c610ddca9b | [
"Net-SNMP",
"Xnet",
"OML"
] | 25 | 2019-01-15T16:06:05.000Z | 2021-11-17T08:41:32.000Z | 33.23951 | 279 | 0.493136 | [
[
[
"<a href=\"https://colab.research.google.com/github/totti0223/deep_learning_for_biologists_with_keras/blob/master/notebooks/PlantDisease_tutorial.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Training a Plant Disease Diagnosis Model with PlantVillage Dataset",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport os\nimport matplotlib.pyplot as plt\n\nfrom skimage.io import imread\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn .model_selection import train_test_split\n\n\nimport keras\nimport keras.backend as K\nfrom keras.preprocessing.image import load_img, img_to_array, ImageDataGenerator\nfrom keras.utils.np_utils import to_categorical\nfrom keras import layers\nfrom keras.models import Sequential, Model\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint",
"_____no_output_____"
]
],
[
[
"# Preparation",
"_____no_output_____"
],
[
"## Data Preparation",
"_____no_output_____"
]
],
[
[
"!apt-get install subversion > /dev/null\n\n#Retreive specifc diseases of tomato for training\n!svn export https://github.com/spMohanty/PlantVillage-Dataset/trunk/raw/color/Tomato___Bacterial_spot image/Tomato___Bacterial_spot > /dev/null\n!svn export https://github.com/spMohanty/PlantVillage-Dataset/trunk/raw/color/Tomato___Early_blight image/Tomato___Early_blight > /dev/null\n!svn export https://github.com/spMohanty/PlantVillage-Dataset/trunk/raw/color/Tomato___Late_blight image/Tomato___Late_blight > /dev/null\n!svn export https://github.com/spMohanty/PlantVillage-Dataset/trunk/raw/color/Tomato___Septoria_leaf_spot image/Tomato___Septoria_leaf_spot > /dev/null\n!svn export https://github.com/spMohanty/PlantVillage-Dataset/trunk/raw/color/Tomato___Target_Spot image/Tomato___Target_Spot > /dev/null\n!svn export https://github.com/spMohanty/PlantVillage-Dataset/trunk/raw/color/Tomato___healthy image/Tomato___healthy > /dev/null",
"_____no_output_____"
],
[
"#folder structure\n!ls image",
"_____no_output_____"
],
[
"plt.figure(figsize=(15,10))\n\n#visualize several images\n\nparent_directory = \"image\"\n\nfor i, folder in enumerate(os.listdir(parent_directory)):\n print(folder)\n folder_directory = os.path.join(parent_directory,folder)\n files = os.listdir(folder_directory)\n #will inspect only 1 image per folder\n file = files[0] \n file_path = os.path.join(folder_directory,file)\n \n image = imread(file_path)\n plt.subplot(1,6,i+1)\n plt.imshow(image)\n plt.axis(\"off\")\n \n name = folder.split(\"___\")[1][:-1]\n plt.title(name)\n #plt.show()",
"_____no_output_____"
],
[
"#load everything into memory\nx = []\ny = []\nclass_names = []\nparent_directory = \"image\"\n\nfor i,folder in enumerate(os.listdir(parent_directory)):\n print(i,folder)\n class_names.append(folder)\n folder_directory = os.path.join(parent_directory,folder)\n files = os.listdir(folder_directory)\n #will inspect only 1 image per folder\n for file in files:\n file_path = os.path.join(folder_directory,file)\n image = load_img(file_path,target_size=(64,64))\n image = img_to_array(image)/255.\n x.append(image)\n y.append(i)\n\nx = np.array(x)\ny = to_categorical(y)",
"_____no_output_____"
],
[
"#check the data shape\nprint(x.shape)\nprint(y.shape)\nprint(y[0])",
"_____no_output_____"
],
[
"x_train, _x, y_train, _y = train_test_split(x,y,test_size=0.2, stratify = y, random_state = 1)\nx_valid,x_test, y_valid, y_test = train_test_split(_x,_y,test_size=0.4, stratify = _y, random_state = 1)\n\nprint(\"train data:\",x_train.shape,y_train.shape)\nprint(\"validation data:\",x_valid.shape,y_valid.shape)\nprint(\"test data:\",x_test.shape,y_test.shape)\n",
"_____no_output_____"
]
],
[
[
"## Model Preparation",
"_____no_output_____"
]
],
[
[
"K.clear_session()\n\nnfilter = 32\n\n\n#VGG16 like model\nmodel = Sequential([\n #block1\n layers.Conv2D(nfilter,(3,3),padding=\"same\",name=\"block1_conv1\",input_shape=(64,64,3)),\n layers.Activation(\"relu\"),\n layers.BatchNormalization(),\n #layers.Dropout(rate=0.2), \n \n layers.Conv2D(nfilter,(3,3),padding=\"same\",name=\"block1_conv2\"),\n layers.BatchNormalization(),\n layers.Activation(\"relu\"),\n #layers.Dropout(rate=0.2),\n layers.MaxPooling2D((2,2),strides=(2,2),name=\"block1_pool\"),\n \n #block2\n layers.Conv2D(nfilter*2,(3,3),padding=\"same\",name=\"block2_conv1\"),\n layers.BatchNormalization(),\n layers.Activation(\"relu\"),\n #layers.Dropout(rate=0.2),\n \n layers.Conv2D(nfilter*2,(3,3),padding=\"same\",name=\"block2_conv2\"),\n layers.BatchNormalization(),\n layers.Activation(\"relu\"),\n #layers.Dropout(rate=0.2),\n layers.MaxPooling2D((2,2),strides=(2,2),name=\"block2_pool\"),\n \n #block3\n layers.Conv2D(nfilter*2,(3,3),padding=\"same\",name=\"block3_conv1\"),\n layers.BatchNormalization(),\n layers.Activation(\"relu\"),\n #layers.Dropout(rate=0.2),\n \n layers.Conv2D(nfilter*4,(3,3),padding=\"same\",name=\"block3_conv2\"),\n layers.BatchNormalization(),\n layers.Activation(\"relu\"),\n #layers.Dropout(rate=0.2),\n \n layers.Conv2D(nfilter*4,(3,3),padding=\"same\",name=\"block3_conv3\"),\n layers.BatchNormalization(),\n layers.Activation(\"relu\"),\n #layers.Dropout(rate=0.2),\n layers.MaxPooling2D((2,2),strides=(2,2),name=\"block3_pool\"),\n #layers.Flatten(),\n layers.GlobalAveragePooling2D(),\n \n #inference layer\n layers.Dense(128,name=\"fc1\"),\n layers.BatchNormalization(),\n layers.Activation(\"relu\"),\n #layers.Dropout(rate=0.2),\n \n layers.Dense(128,name=\"fc2\"),\n layers.BatchNormalization(),\n layers.Activation(\"relu\"), \n #layers.Dropout(rate=0.2),\n \n layers.Dense(6,name=\"prepredictions\"),\n layers.Activation(\"softmax\",name=\"predictions\")\n \n])\n\nmodel.compile(optimizer = \"adam\", loss=\"categorical_crossentropy\", metrics=[\"accuracy\"])\n\nmodel.summary()",
"_____no_output_____"
]
],
[
[
"## Training",
"_____no_output_____"
]
],
[
[
"#utilize early stopping function to stop at the lowest validation loss\nes = EarlyStopping(monitor='val_loss', patience=10, verbose=1, mode='auto')\n#utilize save best weight model during training\nckpt = ModelCheckpoint(\"PlantDiseaseCNNmodel.hdf5\", monitor='val_loss', verbose=1, save_best_only=True, save_weights_only=False, mode='auto', period=1)",
"_____no_output_____"
],
[
"#we will define a generator class for training data and validation data seperately, as no augmentation is not required for validation data\nt_gen = ImageDataGenerator(rotation_range=90,horizontal_flip=True)\nv_gen = ImageDataGenerator()\ntrain_gen = t_gen.flow(x_train,y_train,batch_size=98)\nvalid_gen = v_gen.flow(x_valid,y_valid,batch_size=98)",
"_____no_output_____"
],
[
"history = model.fit_generator(\n train_gen,\n steps_per_epoch = train_gen.n // 98,\n callbacks = [es,ckpt], \n validation_data = valid_gen,\n validation_steps = valid_gen.n // 98,\n \n epochs=50)",
"_____no_output_____"
]
],
[
[
"## Evaluation",
"_____no_output_____"
]
],
[
[
"#load the model weight file with lowest validation loss\nmodel.load_weights(\"PlantDiseaseCNNmodel.hdf5\")",
"_____no_output_____"
],
[
"#or can obtain the pretrained model from the github repo.",
"_____no_output_____"
],
[
"#check the model metrics\nprint(model.metrics_names)\n#evaluate training data\nprint(model.evaluate(x= x_train, y = y_train))\n#evaluate validation data\nprint(model.evaluate(x= x_valid, y = y_valid))\n#evaluate test data\nprint(model.evaluate(x= x_test, y = y_test)) ",
"_____no_output_____"
],
[
"#draw a confusion matrix\n\n#true label\ny_true = np.argmax(y_test,axis=1)\n\n#prediction label\nY_pred = model.predict(x_test)\ny_pred = np.argmax(Y_pred, axis=1)\n\nprint(y_true)\nprint(y_pred)",
"_____no_output_____"
],
[
"#https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html#sphx-glr-auto-examples-model-selection-plot-confusion-matrix-py\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.utils.multiclass import unique_labels\n\ndef plot_confusion_matrix(y_true, y_pred, classes,\n normalize=False,\n title=None,\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if not title:\n if normalize:\n title = 'Normalized confusion matrix'\n else:\n title = 'Confusion matrix, without normalization'\n\n # Compute confusion matrix\n cm = confusion_matrix(y_true, y_pred)\n # Only use the labels that appear in the data\n #classes = classes[unique_labels(y_true, y_pred)]\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print('Confusion matrix, without normalization')\n\n print(cm)\n\n fig, ax = plt.subplots(figsize=(5,5))\n im = ax.imshow(cm, interpolation='nearest', cmap=cmap)\n #ax.figure.colorbar(im, ax=ax)\n # We want to show all ticks...\n ax.set(xticks=np.arange(cm.shape[1]),\n yticks=np.arange(cm.shape[0]),\n # ... and label them with the respective list entries\n xticklabels=classes, yticklabels=classes,\n title=title,\n ylabel='True label',\n xlabel='Predicted label')\n\n # Rotate the tick labels and set their alignment.\n plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\",\n rotation_mode=\"anchor\")\n\n # Loop over data dimensions and create text annotations.\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i in range(cm.shape[0]):\n for j in range(cm.shape[1]):\n ax.text(j, i, format(cm[i, j], fmt),\n ha=\"center\", va=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n fig.tight_layout()\n return ax\n\n\nnp.set_printoptions(precision=2)\n\nplot_confusion_matrix(y_true, y_pred, classes=class_names, normalize=True,\n title='Normalized confusion matrix')\n\n",
"_____no_output_____"
]
],
[
[
"## Predicting Indivisual Images",
"_____no_output_____"
]
],
[
[
"n = 15 #do not exceed (number of test image - 1)\n\nplt.imshow(x_test[n])\nplt.show()\n\ntrue_label = np.argmax(y_test,axis=1)[n]\nprint(\"true_label is:\",true_label,\":\",class_names[true_label])\nprediction = model.predict(x_test[n][np.newaxis,...])[0]\nprint(\"predicted_value is:\",prediction)\npredicted_label = np.argmax(prediction)\nprint(\"predicted_label is:\",predicted_label,\":\",class_names[predicted_label])\n\nif true_label == predicted_label:\n print(\"correct prediction\")\nelse:\n print(\"wrong prediction\")",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
d0830c5d2e97579490e613a26bd365eeecbaddc7 | 13,911 | ipynb | Jupyter Notebook | LeNet-Lab-Solution.ipynb | LiYan1988/LeNet-2 | c0cd21aadf548bcb1693707db8d0b6077976b690 | [
"MIT"
] | null | null | null | LeNet-Lab-Solution.ipynb | LiYan1988/LeNet-2 | c0cd21aadf548bcb1693707db8d0b6077976b690 | [
"MIT"
] | null | null | null | LeNet-Lab-Solution.ipynb | LiYan1988/LeNet-2 | c0cd21aadf548bcb1693707db8d0b6077976b690 | [
"MIT"
] | null | null | null | 31.760274 | 310 | 0.562145 | [
[
[
"# LeNet Lab Solution\n\nSource: Yan LeCun",
"_____no_output_____"
],
[
"## Load Data\n\nLoad the MNIST data, which comes pre-loaded with TensorFlow.\n\nYou do not need to modify this section.",
"_____no_output_____"
]
],
[
[
"from tensorflow.examples.tutorials.mnist import input_data\n\nmnist = input_data.read_data_sets(\"MNIST_data/\", reshape=False)\nX_train, y_train = mnist.train.images, mnist.train.labels\nX_validation, y_validation = mnist.validation.images, mnist.validation.labels\nX_test, y_test = mnist.test.images, mnist.test.labels\n\nassert(len(X_train) == len(y_train))\nassert(len(X_validation) == len(y_validation))\nassert(len(X_test) == len(y_test))\n\nprint()\nprint(\"Image Shape: {}\".format(X_train[0].shape))\nprint()\nprint(\"Training Set: {} samples\".format(len(X_train)))\nprint(\"Validation Set: {} samples\".format(len(X_validation)))\nprint(\"Test Set: {} samples\".format(len(X_test)))",
"_____no_output_____"
]
],
[
[
"The MNIST data that TensorFlow pre-loads comes as 28x28x1 images.\n\nHowever, the LeNet architecture only accepts 32x32xC images, where C is the number of color channels.\n\nIn order to reformat the MNIST data into a shape that LeNet will accept, we pad the data with two rows of zeros on the top and bottom, and two columns of zeros on the left and right (28+2+2 = 32).\n\nYou do not need to modify this section.",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\n# Pad images with 0s\nX_train = np.pad(X_train, ((0,0),(2,2),(2,2),(0,0)), 'constant')\nX_validation = np.pad(X_validation, ((0,0),(2,2),(2,2),(0,0)), 'constant')\nX_test = np.pad(X_test, ((0,0),(2,2),(2,2),(0,0)), 'constant')\n \nprint(\"Updated Image Shape: {}\".format(X_train[0].shape))",
"_____no_output_____"
]
],
[
[
"## Visualize Data\n\nView a sample from the dataset.\n\nYou do not need to modify this section.",
"_____no_output_____"
]
],
[
[
"import random\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nindex = random.randint(0, len(X_train))\nimage = X_train[index].squeeze()\n\nplt.figure(figsize=(1,1))\nplt.imshow(image, cmap=\"gray\")\nprint(y_train[index])",
"_____no_output_____"
]
],
[
[
"## Preprocess Data\n\nShuffle the training data.\n\nYou do not need to modify this section.",
"_____no_output_____"
]
],
[
[
"from sklearn.utils import shuffle\n\nX_train, y_train = shuffle(X_train, y_train)",
"_____no_output_____"
]
],
[
[
"## Setup TensorFlow\nThe `EPOCH` and `BATCH_SIZE` values affect the training speed and model accuracy.\n\nYou do not need to modify this section.",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\n\nEPOCHS = 10\nBATCH_SIZE = 128",
"_____no_output_____"
]
],
[
[
"## SOLUTION: Implement LeNet-5\nImplement the [LeNet-5](http://yann.lecun.com/exdb/lenet/) neural network architecture.\n\nThis is the only cell you need to edit.\n### Input\nThe LeNet architecture accepts a 32x32xC image as input, where C is the number of color channels. Since MNIST images are grayscale, C is 1 in this case.\n\n### Architecture\n**Layer 1: Convolutional.** The output shape should be 28x28x6.\n\n**Activation.** Your choice of activation function.\n\n**Pooling.** The output shape should be 14x14x6.\n\n**Layer 2: Convolutional.** The output shape should be 10x10x16.\n\n**Activation.** Your choice of activation function.\n\n**Pooling.** The output shape should be 5x5x16.\n\n**Flatten.** Flatten the output shape of the final pooling layer such that it's 1D instead of 3D. The easiest way to do is by using `tf.contrib.layers.flatten`, which is already imported for you.\n\n**Layer 3: Fully Connected.** This should have 120 outputs.\n\n**Activation.** Your choice of activation function.\n\n**Layer 4: Fully Connected.** This should have 84 outputs.\n\n**Activation.** Your choice of activation function.\n\n**Layer 5: Fully Connected (Logits).** This should have 10 outputs.\n\n### Output\nReturn the result of the 2nd fully connected layer.",
"_____no_output_____"
]
],
[
[
"from tensorflow.contrib.layers import flatten\n\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 \n # SOLUTION: Layer 1: Convolutional. Input = 32x32x1. Output = 28x28x6.\n conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 1, 6), mean = mu, stddev = sigma))\n conv1_b = tf.Variable(tf.zeros(6))\n conv1 = tf.nn.conv2d(x, conv1_W, strides=[1, 1, 1, 1], padding='VALID') + conv1_b\n\n # SOLUTION: Activation.\n conv1 = tf.nn.relu(conv1)\n\n # SOLUTION: Pooling. Input = 28x28x6. Output = 14x14x6.\n conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')\n\n # SOLUTION: Layer 2: Convolutional. Output = 10x10x16.\n conv2_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 6, 16), mean = mu, stddev = sigma))\n conv2_b = tf.Variable(tf.zeros(16))\n conv2 = tf.nn.conv2d(conv1, conv2_W, strides=[1, 1, 1, 1], padding='VALID') + conv2_b\n \n # SOLUTION: Activation.\n conv2 = tf.nn.relu(conv2)\n\n # SOLUTION: Pooling. Input = 10x10x16. Output = 5x5x16.\n conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')\n\n # SOLUTION: Flatten. Input = 5x5x16. Output = 400.\n fc0 = flatten(conv2)\n \n # SOLUTION: Layer 3: Fully Connected. Input = 400. Output = 120.\n fc1_W = tf.Variable(tf.truncated_normal(shape=(400, 120), mean = mu, stddev = sigma))\n fc1_b = tf.Variable(tf.zeros(120))\n fc1 = tf.matmul(fc0, fc1_W) + fc1_b\n \n # SOLUTION: Activation.\n fc1 = tf.nn.relu(fc1)\n\n # SOLUTION: Layer 4: Fully Connected. Input = 120. Output = 84.\n fc2_W = tf.Variable(tf.truncated_normal(shape=(120, 84), mean = mu, stddev = sigma))\n fc2_b = tf.Variable(tf.zeros(84))\n fc2 = tf.matmul(fc1, fc2_W) + fc2_b\n \n # SOLUTION: Activation.\n fc2 = tf.nn.relu(fc2)\n\n # SOLUTION: Layer 5: Fully Connected. Input = 84. Output = 10.\n fc3_W = tf.Variable(tf.truncated_normal(shape=(84, 10), mean = mu, stddev = sigma))\n fc3_b = tf.Variable(tf.zeros(10))\n logits = tf.matmul(fc2, fc3_W) + fc3_b\n \n return logits",
"_____no_output_____"
]
],
[
[
"## Features and Labels\nTrain LeNet to classify [MNIST](http://yann.lecun.com/exdb/mnist/) data.\n\n`x` is a placeholder for a batch of input images.\n`y` is a placeholder for a batch of output labels.\n\nYou do not need to modify this section.",
"_____no_output_____"
]
],
[
[
"x = tf.placeholder(tf.float32, (None, 32, 32, 1))\ny = tf.placeholder(tf.int32, (None))\none_hot_y = tf.one_hot(y, 10)",
"_____no_output_____"
]
],
[
[
"## Training Pipeline\nCreate a training pipeline that uses the model to classify MNIST data.\n\nYou do not need to modify this section.",
"_____no_output_____"
]
],
[
[
"rate = 0.001\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)",
"_____no_output_____"
]
],
[
[
"## Model Evaluation\nEvaluate how well the loss and accuracy of the model for a given dataset.\n\nYou do not need to modify this section.",
"_____no_output_____"
]
],
[
[
"correct_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",
"_____no_output_____"
]
],
[
[
"## Train the Model\nRun the training data through the training pipeline to train the model.\n\nBefore each epoch, shuffle the training set.\n\nAfter each epoch, measure the loss and accuracy of the validation set.\n\nSave the model after training.\n\nYou do not need to modify this section.",
"_____no_output_____"
]
],
[
[
"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 \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\")",
"_____no_output_____"
]
],
[
[
"## Evaluate the Model\nOnce you are completely satisfied with your model, evaluate the performance of the model on the test set.\n\nBe sure to only do this once!\n\nIf you were to measure the performance of your trained model on the test set, then improve your model, and then measure the performance of your model on the test set again, that would invalidate your test results. You wouldn't get a true measure of how well your model would perform against real data.\n\nYou do not need to modify this section.",
"_____no_output_____"
]
],
[
[
"with tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('.'))\n\n test_accuracy = evaluate(X_test, y_test)\n print(\"Test Accuracy = {:.3f}\".format(test_accuracy))",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
d0830d018f1005b0f60123935d7ff28c6edcefb0 | 31,898 | ipynb | Jupyter Notebook | PolynomialRegression.ipynb | Lucian-N/DataScience | a73d8a90acf28467c9ae096d646b9cc8b1a25df8 | [
"MIT"
] | null | null | null | PolynomialRegression.ipynb | Lucian-N/DataScience | a73d8a90acf28467c9ae096d646b9cc8b1a25df8 | [
"MIT"
] | null | null | null | PolynomialRegression.ipynb | Lucian-N/DataScience | a73d8a90acf28467c9ae096d646b9cc8b1a25df8 | [
"MIT"
] | null | null | null | 145.652968 | 16,380 | 0.904351 | [
[
[
"# Polynomial Regression",
"_____no_output_____"
],
[
"What if your data doesn't look linear at all? Let's look at some more realistic-looking page speed / purchase data:",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nfrom pylab import *\nimport numpy as np\n\nnp.random.seed(2)\npageSpeeds = np.random.normal(3.0, 1.0, 1000)\npurchaseAmount = np.random.normal(50.0, 10.0, 1000) / pageSpeeds\n\nscatter(pageSpeeds, purchaseAmount)",
"_____no_output_____"
]
],
[
[
"numpy has a handy polyfit function we can use, to let us construct an nth-degree polynomial model of our data that minimizes squared error. Let's try it with a 4th degree polynomial:",
"_____no_output_____"
]
],
[
[
"x = np.array(pageSpeeds)\ny = np.array(purchaseAmount)\n\np4 = np.poly1d(np.polyfit(x, y, 4))\n",
"_____no_output_____"
]
],
[
[
"We'll visualize our original scatter plot, together with a plot of our predicted values using the polynomial for page speed times ranging from 0-7 seconds:",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\n\nxp = np.linspace(0, 7, 100)\nplt.scatter(x, y)\nplt.plot(xp, p4(xp), c='r')\nplt.show()",
"_____no_output_____"
]
],
[
[
"Looks pretty good! Let's measure the r-squared error:",
"_____no_output_____"
]
],
[
[
"from sklearn.metrics import r2_score\n\nr2 = r2_score(y, p4(x))\n\nprint(r2)\n",
"0.82937663963\n"
]
],
[
[
"## Activity",
"_____no_output_____"
],
[
"Try different polynomial orders. Can you get a better fit with higher orders? Do you start to see overfitting, even though the r-squared score looks good for this particular data set?",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
d0831538b02415d09dc8ac859ccc8db3d3b9679b | 232,058 | ipynb | Jupyter Notebook | Session_3/3_pattern_generator.ipynb | xupsh/PYNQ_Workshop | 3aed8aca6d6cb5fa3f6f772543ac61dd7ef2263b | [
"BSD-3-Clause"
] | 4 | 2018-07-12T08:17:02.000Z | 2022-03-29T23:18:48.000Z | Session_3/3_pattern_generator.ipynb | xupsh/PYNQ_Workshop | 3aed8aca6d6cb5fa3f6f772543ac61dd7ef2263b | [
"BSD-3-Clause"
] | null | null | null | Session_3/3_pattern_generator.ipynb | xupsh/PYNQ_Workshop | 3aed8aca6d6cb5fa3f6f772543ac61dd7ef2263b | [
"BSD-3-Clause"
] | null | null | null | 266.427095 | 60,508 | 0.946285 | [
[
[
"# Single-stepping the `logictools` Pattern Generator \n\n* This notebook will show how to use single-stepping mode with the pattern generator\n\n* Note that all generators in the _logictools_ library may be **single-stepped**",
"_____no_output_____"
],
[
"### Visually ...\n\n\n#### The _logictools_ library on the Zynq device on the PYNQ board \n\n",
"_____no_output_____"
],
[
"### Demonstrator notes\n\n* For this demo, the pattern generator implements a simple, 4-bit binary, up-counter\n\n* We will single-step the clock and verify the counter operation\n\n* The output is verified using the waveforms captured by the trace analyzer",
"_____no_output_____"
],
[
"### Points to note\n\n* __Everything__ runs on the Zynq chip on the PYNQ board, even this slide show!\n \n* We will specify and implement circuits __using only Python code__ \n\n* __No__ Xilinx CAD tools are used \n\n* We can create live, real-time circuits __instantaneously__",
"_____no_output_____"
]
],
[
[
"# Specify a stimulus waveform and display it \nfrom pynq.overlays.logictools import LogicToolsOverlay\nfrom pynq.lib.logictools import Waveform\n\nlogictools_olay = LogicToolsOverlay('logictools.bit')\n\nup_counter_stimulus = {'signal': [\n {'name': 'bit0', 'pin': 'D0', 'wave': 'lh' * 8},\n {'name': 'bit1', 'pin': 'D1', 'wave': 'l.h.' * 4},\n {'name': 'bit2', 'pin': 'D2', 'wave': 'l...h...' * 2},\n {'name': 'bit3', 'pin': 'D3', 'wave': 'l.......h.......'}]}\n\n# Check visually that the stimulus pattern is correct\nwaveform = Waveform(up_counter_stimulus)\nwaveform.display()",
"_____no_output_____"
],
[
"# Add the signals we want to analyze \nup_counter = {'signal': [\n ['stimulus',\n {'name': 'bit0', 'pin': 'D0', 'wave': 'lh' * 8},\n {'name': 'bit1', 'pin': 'D1', 'wave': 'l.h.' * 4},\n {'name': 'bit2', 'pin': 'D2', 'wave': 'l...h...' * 2},\n {'name': 'bit3', 'pin': 'D3', 'wave': 'l.......h.......'}],\n {},\n ['analysis',\n {'name': 'bit0_output', 'pin': 'D0'},\n {'name': 'bit1_output', 'pin': 'D1'},\n {'name': 'bit2_output', 'pin': 'D2'},\n {'name': 'bit3_output', 'pin': 'D3'}]]}\n\n# Display the stimulus and analysis signal groups\nwaveform = Waveform(up_counter)\nwaveform.display()",
"_____no_output_____"
],
[
"# Configure the pattern generator and analyzer\npattern_generator = logictools_olay.pattern_generator\npattern_generator.trace(num_analyzer_samples=16)\npattern_generator.setup(up_counter,\n stimulus_group_name='stimulus',\n analysis_group_name='analysis')",
"_____no_output_____"
],
[
"# Press `cntrl-enter` to advance the pattern generator by one clock cycle\npattern_generator.step()\npattern_generator.show_waveform()",
"_____no_output_____"
],
[
"# Advance an arbitrary number of cycles\nno_of_cycles = 7\nfor _ in range(no_of_cycles):\n pattern_generator.step()\npattern_generator.show_waveform()",
"_____no_output_____"
],
[
"# Finally, reset the pattern generator after use\npattern_generator.reset()",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d083251d7c740464a2ff5120daa682c440f89636 | 2,003 | ipynb | Jupyter Notebook | notebooks/Intro_to_jupyter.ipynb | giacomov/intro_to_python | 0ca3aa4542930d3f31fc08657f2fa9a071971992 | [
"BSD-3-Clause"
] | null | null | null | notebooks/Intro_to_jupyter.ipynb | giacomov/intro_to_python | 0ca3aa4542930d3f31fc08657f2fa9a071971992 | [
"BSD-3-Clause"
] | null | null | null | notebooks/Intro_to_jupyter.ipynb | giacomov/intro_to_python | 0ca3aa4542930d3f31fc08657f2fa9a071971992 | [
"BSD-3-Clause"
] | null | null | null | 38.519231 | 208 | 0.647029 | [
[
[
"# Minimal introduction to the Jupyter notebook\n\n* Notebooks are collections of \"cells\" and their output\n* Cells can contain code or Markdown (which is text with special keywords to make titles, images and so on)\n* For code cells (the default):\n * You can write Python code in the cell and edit as many times as you need\n * When you are done editing, you can execute (run) the cell by hitting Ctrl + Enter or pressing the \"Play\" button\n* Cells are added automatically at the bottom when you execute the last cell of the notebook\n* Cells can also be added in the middle of the notebook by placing the cursor in the cell above the desired position, and then clicking \"+\" in the toolbar above the notebook\n* The notebook is saved automatically every few minutes. If you want to save at any particular moment, click the Save button at the left of the control bar above the notebook (or File->Save Notebook)\n* The type of a cell can be changed from \"Code\" to \"Markdown\" in order to write text that is not meant to be executed. Use the drop-down menu on the right of the control bar above the notebook\n* Cells can be executed in any order, but try as much as possible to execute them in the order they are written,\n to avoid confusion and mistakes",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown"
]
] |
d0832544e767c1848763ed451215631f7bacfeaf | 15,457 | ipynb | Jupyter Notebook | week10_Model_free_learning_peek/practice_approximate_Q_learning.ipynb | GimmeDanger/made_nlp_course | a59816c9e84af310d37c9ef7a8a0ba8a1a126226 | [
"MIT"
] | null | null | null | week10_Model_free_learning_peek/practice_approximate_Q_learning.ipynb | GimmeDanger/made_nlp_course | a59816c9e84af310d37c9ef7a8a0ba8a1a126226 | [
"MIT"
] | null | null | null | week10_Model_free_learning_peek/practice_approximate_Q_learning.ipynb | GimmeDanger/made_nlp_course | a59816c9e84af310d37c9ef7a8a0ba8a1a126226 | [
"MIT"
] | null | null | null | 35.209567 | 283 | 0.56971 | [
[
[
"## Practice: approximate q-learning\n_Reference: based on Practical RL_ [week04](https://github.com/yandexdataschool/Practical_RL/tree/master/week04_approx_rl)\n\n\nIn this notebook you will teach a __pytorch__ neural network to do Q-learning.",
"_____no_output_____"
]
],
[
[
"# # in google colab uncomment this\n\n# import os\n\n# os.system('apt-get install -y xvfb')\n# os.system('wget https://raw.githubusercontent.com/yandexdataschool/Practical_DL/fall18/xvfb -O ../xvfb')\n# os.system('apt-get install -y python-opengl ffmpeg')\n\n# XVFB will be launched if you run on a server\nimport os\nif type(os.environ.get(\"DISPLAY\")) is not str or len(os.environ.get(\"DISPLAY\")) == 0:\n !bash ../xvfb start\n %env DISPLAY = : 1",
"_____no_output_____"
],
[
"import gym\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
],
[
"env = gym.make(\"CartPole-v0\").env\nenv.reset()\nn_actions = env.action_space.n\nstate_dim = env.observation_space.shape\n\nplt.imshow(env.render(\"rgb_array\"))\nenv.close()",
"_____no_output_____"
]
],
[
[
"# Approximate Q-learning: building the network\n\nTo train a neural network policy one must have a neural network policy. Let's build it.\n\n\nSince we're working with a pre-extracted features (cart positions, angles and velocities), we don't need a complicated network yet. In fact, let's build something like this for starters:\n\n\n\nFor your first run, please only use linear layers (nn.Linear) and activations. Stuff like batch normalization or dropout may ruin everything if used haphazardly. \n\nAlso please avoid using nonlinearities like sigmoid & tanh: agent's observations are not normalized so sigmoids may become saturated from init.\n\nIdeally you should start small with maybe 1-2 hidden layers with < 200 neurons and then increase network size if agent doesn't beat the target score.",
"_____no_output_____"
]
],
[
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F",
"_____no_output_____"
],
[
"network = nn.Sequential()\n\nnetwork.add_module('layer1', < ... >)\n\n<YOUR CODE: stack layers!!!1 >\n\n# hint: use state_dim[0] as input size",
"_____no_output_____"
],
[
"def get_action(state, epsilon=0):\n \"\"\"\n sample actions with epsilon-greedy policy\n recap: with p = epsilon pick random action, else pick action with highest Q(s,a)\n \"\"\"\n state = torch.tensor(state[None], dtype=torch.float32)\n q_values = network(state).detach().numpy()\n\n # YOUR CODE\n\n return int( < epsilon-greedily selected action > )",
"_____no_output_____"
],
[
"s = env.reset()\nassert tuple(network(torch.tensor([s]*3, dtype=torch.float32)).size()) == (\n 3, n_actions), \"please make sure your model maps state s -> [Q(s,a0), ..., Q(s, a_last)]\"\nassert isinstance(list(network.modules(\n))[-1], nn.Linear), \"please make sure you predict q-values without nonlinearity (ignore if you know what you're doing)\"\nassert isinstance(get_action(\n s), int), \"get_action(s) must return int, not %s. try int(action)\" % (type(get_action(s)))\n\n# test epsilon-greedy exploration\nfor eps in [0., 0.1, 0.5, 1.0]:\n state_frequencies = np.bincount(\n [get_action(s, epsilon=eps) for i in range(10000)], minlength=n_actions)\n best_action = state_frequencies.argmax()\n assert abs(state_frequencies[best_action] -\n 10000 * (1 - eps + eps / n_actions)) < 200\n for other_action in range(n_actions):\n if other_action != best_action:\n assert abs(state_frequencies[other_action] -\n 10000 * (eps / n_actions)) < 200\n print('e=%.1f tests passed' % eps)",
"_____no_output_____"
]
],
[
[
"### Q-learning via gradient descent\n\nWe shall now train our agent's Q-function by minimizing the TD loss:\n$$ L = { 1 \\over N} \\sum_i (Q_{\\theta}(s,a) - [r(s,a) + \\gamma \\cdot max_{a'} Q_{-}(s', a')]) ^2 $$\n\n\nWhere\n* $s, a, r, s'$ are current state, action, reward and next state respectively\n* $\\gamma$ is a discount factor defined two cells above.\n\nThe tricky part is with $Q_{-}(s',a')$. From an engineering standpoint, it's the same as $Q_{\\theta}$ - the output of your neural network policy. However, when doing gradient descent, __we won't propagate gradients through it__ to make training more stable (see lectures).\n\nTo do so, we shall use `x.detach()` function which basically says \"consider this thing constant when doingbackprop\".",
"_____no_output_____"
]
],
[
[
"def to_one_hot(y_tensor, n_dims=None):\n \"\"\" helper: take an integer vector and convert it to 1-hot matrix. \"\"\"\n y_tensor = y_tensor.type(torch.LongTensor).view(-1, 1)\n n_dims = n_dims if n_dims is not None else int(torch.max(y_tensor)) + 1\n y_one_hot = torch.zeros(\n y_tensor.size()[0], n_dims).scatter_(1, y_tensor, 1)\n return y_one_hot\n\n\ndef where(cond, x_1, x_2):\n \"\"\" helper: like np.where but in pytorch. \"\"\"\n return (cond * x_1) + ((1-cond) * x_2)",
"_____no_output_____"
],
[
"def compute_td_loss(states, actions, rewards, next_states, is_done, gamma=0.99, check_shapes=False):\n \"\"\" Compute td loss using torch operations only. Use the formula above. \"\"\"\n states = torch.tensor(\n states, dtype=torch.float32) # shape: [batch_size, state_size]\n actions = torch.tensor(actions, dtype=torch.int32) # shape: [batch_size]\n rewards = torch.tensor(rewards, dtype=torch.float32) # shape: [batch_size]\n # shape: [batch_size, state_size]\n next_states = torch.tensor(next_states, dtype=torch.float32)\n is_done = torch.tensor(is_done, dtype=torch.float32) # shape: [batch_size]\n\n # get q-values for all actions in current states\n predicted_qvalues = network(states)\n\n # select q-values for chosen actions\n predicted_qvalues_for_actions = torch.sum(\n predicted_qvalues * to_one_hot(actions, n_actions), dim=1)\n\n # compute q-values for all actions in next states\n predicted_next_qvalues = # YOUR CODE\n\n # compute V*(next_states) using predicted next q-values\n next_state_values = # YOUR CODE\n assert next_state_values.dtype == torch.float32\n\n # compute \"target q-values\" for loss - it's what's inside square parentheses in the above formula.\n target_qvalues_for_actions = # YOUR CODE\n\n # at the last state we shall use simplified formula: Q(s,a) = r(s,a) since s' doesn't exist\n target_qvalues_for_actions = where(\n is_done, rewards, target_qvalues_for_actions)\n\n # mean squared error loss to minimize\n loss = torch.mean((predicted_qvalues_for_actions -\n target_qvalues_for_actions.detach()) ** 2)\n\n if check_shapes:\n assert predicted_next_qvalues.data.dim(\n ) == 2, \"make sure you predicted q-values for all actions in next state\"\n assert next_state_values.data.dim(\n ) == 1, \"make sure you computed V(s') as maximum over just the actions axis and not all axes\"\n assert target_qvalues_for_actions.data.dim(\n ) == 1, \"there's something wrong with target q-values, they must be a vector\"\n\n return loss",
"_____no_output_____"
],
[
"# sanity checks\ns = env.reset()\na = env.action_space.sample()\nnext_s, r, done, _ = env.step(a)\nloss = compute_td_loss([s], [a], [r], [next_s], [done], check_shapes=True)\nloss.backward()\n\nassert len(loss.size()) == 0, \"you must return scalar loss - mean over batch\"\nassert np.any(next(network.parameters()).grad.detach().numpy() !=\n 0), \"loss must be differentiable w.r.t. network weights\"",
"_____no_output_____"
]
],
[
[
"### Playing the game",
"_____no_output_____"
]
],
[
[
"opt = torch.optim.Adam(network.parameters(), lr=1e-4)\nepsilon = 0.5",
"_____no_output_____"
],
[
"def generate_session(t_max=1000, epsilon=0, train=False):\n \"\"\"play env with approximate q-learning agent and train it at the same time\"\"\"\n total_reward = 0\n s = env.reset()\n\n for t in range(t_max):\n a = get_action(s, epsilon=epsilon)\n next_s, r, done, _ = env.step(a)\n\n if train:\n opt.zero_grad()\n compute_td_loss([s], [a], [r], [next_s], [done]).backward()\n opt.step()\n\n total_reward += r\n s = next_s\n if done:\n break\n\n return total_reward",
"_____no_output_____"
],
[
"for i in range(1000):\n session_rewards = [generate_session(\n epsilon=epsilon, train=True) for _ in range(100)]\n print(\"epoch #{}\\tmean reward = {:.3f}\\tepsilon = {:.3f}\".format(\n i, np.mean(session_rewards), epsilon))\n\n epsilon *= 0.99\n assert epsilon >= 1e-4, \"Make sure epsilon is always nonzero during training\"\n\n if np.mean(session_rewards) > 300:\n print(\"You Win!\")\n break",
"_____no_output_____"
]
],
[
[
"### How to interpret results\n\n\nWelcome to the f.. world of deep f...n reinforcement learning. Don't expect agent's reward to smoothly go up. Hope for it to go increase eventually. If it deems you worthy.\n\nSeriously though,\n* __ mean reward__ is the average reward per game. For a correct implementation it may stay low for some 10 epochs, then start growing while oscilating insanely and converges by ~50-100 steps depending on the network architecture. \n* If it never reaches target score by the end of for loop, try increasing the number of hidden neurons or look at the epsilon.\n* __ epsilon__ - agent's willingness to explore. If you see that agent's already at < 0.01 epsilon before it's is at least 200, just reset it back to 0.1 - 0.5.",
"_____no_output_____"
],
[
"### Record videos\n\nAs usual, we now use `gym.wrappers.Monitor` to record a video of our agent playing the game. Unlike our previous attempts with state binarization, this time we expect our agent to act ~~(or fail)~~ more smoothly since there's no more binarization error at play.\n\nAs you already did with tabular q-learning, we set epsilon=0 for final evaluation to prevent agent from exploring himself to death.",
"_____no_output_____"
]
],
[
[
"# record sessions\nimport gym.wrappers\nenv = gym.wrappers.Monitor(gym.make(\"CartPole-v0\"),\n directory=\"videos\", force=True)\nsessions = [generate_session(epsilon=0, train=False) for _ in range(100)]\nenv.close()",
"_____no_output_____"
],
[
"# Show video. This may not work in some setups. If it doesn't\n# work for you, you can download the videos and view them locally.\n\nimport sys\nfrom pathlib import Path\nfrom base64 import b64encode\nfrom IPython.display import HTML\n\nvideo_paths = sorted([s for s in Path('videos').iterdir() if s.suffix == '.mp4'])\nvideo_path = video_paths[-3] # You can also try other indices\n\nif 'google.colab' in sys.modules:\n # https://stackoverflow.com/a/57378660/1214547\n with video_path.open('rb') as fp:\n mp4 = fp.read()\n data_url = 'data:video/mp4;base64,' + b64encode(mp4).decode()\nelse:\n data_url = str(video_path)\n\nHTML(\"\"\"\n<video width=\"640\" height=\"480\" controls>\n <source src=\"{}\" type=\"video/mp4\">\n</video>\n\"\"\".format(data_url))",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
d08340b7f2def5646769811c34fc3c825f26c23b | 70,934 | ipynb | Jupyter Notebook | ipy_train/train_RGBAPlus.ipynb | VCG/gp | cd106b604f8670a70add469d41180e34df3b1068 | [
"MIT"
] | null | null | null | ipy_train/train_RGBAPlus.ipynb | VCG/gp | cd106b604f8670a70add469d41180e34df3b1068 | [
"MIT"
] | null | null | null | ipy_train/train_RGBAPlus.ipynb | VCG/gp | cd106b604f8670a70add469d41180e34df3b1068 | [
"MIT"
] | null | null | null | 133.837736 | 22,716 | 0.756943 | [
[
[
"%load_ext autoreload\n%autoreload 2\n\nimport cPickle as pickle\nimport os; import sys; sys.path.append('..')\nimport gp\nimport gp.nets as nets\n\nfrom nolearn.lasagne.visualize import plot_loss\nfrom nolearn.lasagne.visualize import plot_conv_weights\nfrom nolearn.lasagne.visualize import plot_conv_activity\nfrom nolearn.lasagne.visualize import plot_occlusion\n\nfrom matplotlib.pyplot import imshow\nimport matplotlib.pyplot as plt\n%matplotlib inline",
"The autoreload extension is already loaded. To reload it, use:\n %reload_ext autoreload\n"
],
[
"PATCH_PATH = ('cylinder2_rgba_small')",
"_____no_output_____"
],
[
"X_train, y_train, X_test, y_test = gp.Patch.load_rgba(PATCH_PATH)",
"Loaded /home/d/patches//cylinder2_rgba_small/ in 0.000566005706787 seconds.\n"
],
[
"gp.Util.view_rgba(X_train[100], y_train[100])",
"_____no_output_____"
],
[
"cnn = nets.RGBANetPlus()",
"CNN configuration: \n Our CNN with image, prob, merged_array and border overlap as RGBA.\n\n This includes dropout.\n \n"
],
[
"cnn = cnn.fit(X_train, y_train)",
"# Neural Network with 171474 learnable parameters\n\n## Layer information\n\n # name size\n--- -------- --------\n 0 input 4x75x75\n 1 conv1 64x73x73\n 2 pool1 64x36x36\n 3 dropout1 64x36x36\n 4 conv2 48x34x34\n 5 pool2 48x17x17\n 6 dropout2 48x17x17\n 7 conv3 48x15x15\n 8 pool3 48x7x7\n 9 dropout3 48x7x7\n 10 conv4 48x5x5\n 11 pool4 48x2x2\n 12 dropout4 48x2x2\n 13 hidden5 512\n 14 dropout5 512\n 15 output 2\n\n epoch train loss valid loss train/val valid acc dur\n------- ------------ ------------ ----------- ----------- ------\n 1 \u001b[36m0.46396\u001b[0m \u001b[32m0.31323\u001b[0m 1.48122 0.87315 27.51s\n 2 \u001b[36m0.28116\u001b[0m \u001b[32m0.25516\u001b[0m 1.10193 0.90459 26.38s\n 3 \u001b[36m0.23199\u001b[0m \u001b[32m0.21672\u001b[0m 1.07049 0.91938 26.42s\n 4 \u001b[36m0.21736\u001b[0m \u001b[32m0.19727\u001b[0m 1.10185 0.92764 26.37s\n 5 \u001b[36m0.20625\u001b[0m \u001b[32m0.19145\u001b[0m 1.07729 0.92794 26.63s\n 6 \u001b[36m0.20049\u001b[0m \u001b[32m0.17983\u001b[0m 1.11486 0.93309 26.48s\n 7 \u001b[36m0.19307\u001b[0m 0.18020 1.07142 0.93352 26.34s\n 8 \u001b[36m0.18663\u001b[0m \u001b[32m0.17094\u001b[0m 1.09178 0.93674 26.54s\n 9 \u001b[36m0.18074\u001b[0m \u001b[32m0.16797\u001b[0m 1.07601 0.93854 26.32s\n 10 \u001b[36m0.17738\u001b[0m \u001b[32m0.16302\u001b[0m 1.08810 0.93997 26.65s\n 11 \u001b[36m0.17079\u001b[0m \u001b[32m0.15933\u001b[0m 1.07190 0.93970 26.87s\n 12 \u001b[36m0.16659\u001b[0m \u001b[32m0.15155\u001b[0m 1.09922 0.94380 26.94s\n 13 \u001b[36m0.16236\u001b[0m \u001b[32m0.15016\u001b[0m 1.08120 0.94476 27.00s\n 14 \u001b[36m0.16143\u001b[0m \u001b[32m0.14958\u001b[0m 1.07924 0.94290 27.01s\n 15 \u001b[36m0.15620\u001b[0m 0.15028 1.03939 0.94416 27.11s\n 16 \u001b[36m0.15424\u001b[0m \u001b[32m0.13842\u001b[0m 1.11435 0.94919 27.16s\n 17 \u001b[36m0.15031\u001b[0m \u001b[32m0.13640\u001b[0m 1.10194 0.95083 27.10s\n 18 \u001b[36m0.14824\u001b[0m 0.13696 1.08238 0.94764 26.76s\n 19 \u001b[36m0.14474\u001b[0m \u001b[32m0.13327\u001b[0m 1.08607 0.95182 26.44s\n 20 \u001b[36m0.14093\u001b[0m \u001b[32m0.12454\u001b[0m 1.13161 0.95608 26.75s\n 21 \u001b[36m0.13745\u001b[0m \u001b[32m0.12440\u001b[0m 1.10489 0.95721 26.64s\n 22 0.13957 0.13246 1.05370 0.95353 26.41s\n 23 \u001b[36m0.13481\u001b[0m 0.12786 1.05433 0.95350 26.36s\n 24 \u001b[36m0.13137\u001b[0m \u001b[32m0.12323\u001b[0m 1.06599 0.95595 26.68s\n 25 \u001b[36m0.12879\u001b[0m \u001b[32m0.11473\u001b[0m 1.12255 0.95811 26.61s\n 26 \u001b[36m0.12662\u001b[0m 0.11592 1.09229 0.95604 26.41s\n 27 \u001b[36m0.12597\u001b[0m \u001b[32m0.11199\u001b[0m 1.12487 0.96074 26.49s\n 28 \u001b[36m0.12393\u001b[0m 0.11511 1.07667 0.95966 26.49s\n 29 \u001b[36m0.12202\u001b[0m \u001b[32m0.10726\u001b[0m 1.13763 0.96394 26.47s\n 30 \u001b[36m0.11996\u001b[0m 0.11250 1.06634 0.95954 26.41s\n 31 \u001b[36m0.11926\u001b[0m \u001b[32m0.10426\u001b[0m 1.14388 0.96215 26.47s\n 32 0.11959 \u001b[32m0.10287\u001b[0m 1.16254 0.96490 26.66s\n 33 \u001b[36m0.11385\u001b[0m 0.10363 1.09864 0.96472 26.40s\n 34 0.11508 \u001b[32m0.09946\u001b[0m 1.15706 0.96457 26.52s\n 35 \u001b[36m0.11264\u001b[0m \u001b[32m0.09801\u001b[0m 1.14933 0.96496 26.78s\n 36 0.11324 0.09997 1.13271 0.96523 26.52s\n 37 \u001b[36m0.10929\u001b[0m 0.10371 1.05379 0.96307 26.53s\n 38 \u001b[36m0.10705\u001b[0m \u001b[32m0.08843\u001b[0m 1.21058 0.96864 26.51s\n 39 \u001b[36m0.10456\u001b[0m \u001b[32m0.08753\u001b[0m 1.19462 0.97142 26.60s\n 40 0.10477 \u001b[32m0.08260\u001b[0m 1.26849 0.97163 26.49s\n 41 \u001b[36m0.10092\u001b[0m 0.08893 1.13483 0.97082 26.29s\n 42 0.10447 0.08779 1.18998 0.97118 26.71s\n 43 \u001b[36m0.10000\u001b[0m 0.08519 1.17386 0.97064 26.44s\n 44 \u001b[36m0.09689\u001b[0m 0.09274 1.04467 0.97148 26.29s\n 45 \u001b[36m0.09681\u001b[0m 0.08784 1.10211 0.97163 26.30s\n 46 0.09942 \u001b[32m0.08171\u001b[0m 1.21675 0.97475 26.29s\n 47 \u001b[36m0.09331\u001b[0m \u001b[32m0.07842\u001b[0m 1.18992 0.97253 26.31s\n 48 0.09591 \u001b[32m0.07644\u001b[0m 1.25471 0.97549 26.28s\n 49 0.09349 0.07944 1.17687 0.97495 26.31s\n 50 \u001b[36m0.08891\u001b[0m 0.07957 1.11736 0.97624 26.31s\n 51 0.09256 \u001b[32m0.07443\u001b[0m 1.24352 0.97573 26.28s\n 52 \u001b[36m0.08758\u001b[0m 0.07789 1.12437 0.97594 26.33s\n 53 0.08811 0.07704 1.14368 0.97603 26.28s\n 54 \u001b[36m0.08462\u001b[0m 0.07675 1.10250 0.97666 26.30s\n 55 0.08769 0.07503 1.16877 0.97890 26.29s\n 56 \u001b[36m0.08377\u001b[0m \u001b[32m0.07316\u001b[0m 1.14491 0.97588 26.30s\n 57 \u001b[36m0.08259\u001b[0m \u001b[32m0.07020\u001b[0m 1.17647 0.97857 26.35s\n 58 \u001b[36m0.08124\u001b[0m \u001b[32m0.06977\u001b[0m 1.16445 0.97866 26.34s\n 59 0.08401 \u001b[32m0.06799\u001b[0m 1.23570 0.97983 26.31s\n 60 \u001b[36m0.07829\u001b[0m \u001b[32m0.06392\u001b[0m 1.22491 0.98277 26.30s\n 61 0.08232 0.06532 1.26034 0.98163 26.33s\n 62 0.07830 0.06494 1.20583 0.98064 26.34s\n 63 \u001b[36m0.07829\u001b[0m 0.06971 1.12304 0.98076 26.33s\n 64 \u001b[36m0.07817\u001b[0m \u001b[32m0.05916\u001b[0m 1.32126 0.98064 26.30s\n 65 0.07838 \u001b[32m0.05895\u001b[0m 1.32967 0.98214 26.27s\n 66 \u001b[36m0.07292\u001b[0m \u001b[32m0.05830\u001b[0m 1.25073 0.98522 26.32s\n 67 0.07737 0.07235 1.06929 0.97738 26.30s\n 68 0.07723 \u001b[32m0.05566\u001b[0m 1.38758 0.98540 26.31s\n 69 \u001b[36m0.07216\u001b[0m 0.06140 1.17523 0.98396 26.35s\n 70 0.07566 0.06992 1.08200 0.97848 26.31s\n 71 \u001b[36m0.07206\u001b[0m 0.05881 1.22526 0.98187 26.31s\n 72 \u001b[36m0.07201\u001b[0m \u001b[32m0.05337\u001b[0m 1.34930 0.98375 26.32s\n 73 \u001b[36m0.06839\u001b[0m \u001b[32m0.05230\u001b[0m 1.30760 0.98621 26.28s\n 74 \u001b[36m0.06570\u001b[0m 0.05553 1.18314 0.98567 26.30s\n 75 0.07405 0.05347 1.38481 0.98459 26.34s\n 76 0.06862 0.05588 1.22799 0.98551 26.33s\n 77 0.06765 0.05787 1.16907 0.98504 26.31s\n 78 0.06869 \u001b[32m0.05185\u001b[0m 1.32461 0.98594 26.32s\n 79 0.06587 \u001b[32m0.04930\u001b[0m 1.33602 0.98773 26.35s\n 80 0.06698 0.05176 1.29399 0.98794 26.31s\n 81 0.06597 \u001b[32m0.04702\u001b[0m 1.40295 0.98755 26.30s\n 82 \u001b[36m0.06315\u001b[0m 0.04732 1.33454 0.98728 26.28s\n 83 0.06510 \u001b[32m0.04631\u001b[0m 1.40566 0.98854 26.32s\n 84 \u001b[36m0.06219\u001b[0m 0.05105 1.21803 0.98552 26.34s\n 85 0.06437 \u001b[32m0.04627\u001b[0m 1.39106 0.98881 26.35s\n 86 0.06254 0.04743 1.31846 0.98681 26.33s\n 87 0.06302 \u001b[32m0.04470\u001b[0m 1.40997 0.98785 26.29s\n 88 0.06253 0.04871 1.28370 0.98722 26.32s\n 89 0.06276 0.04584 1.36909 0.98875 26.35s\n 90 \u001b[36m0.06089\u001b[0m 0.04711 1.29263 0.98737 26.31s\n 91 \u001b[36m0.05677\u001b[0m \u001b[32m0.03941\u001b[0m 1.44058 0.98917 26.31s\n 92 0.05842 0.04389 1.33119 0.98989 26.32s\n 93 0.06032 0.04117 1.46530 0.98809 26.34s\n 94 0.05829 0.05155 1.13081 0.98432 26.33s\n 95 0.05716 0.04658 1.22717 0.98785 26.36s\n 96 \u001b[36m0.05601\u001b[0m 0.04170 1.34321 0.98881 26.33s\n 97 0.05709 0.04193 1.36174 0.98944 26.41s\n 98 \u001b[36m0.05568\u001b[0m 0.04646 1.19845 0.98857 26.34s\n 99 0.05730 0.04170 1.37396 0.99025 26.31s\n 100 \u001b[36m0.05336\u001b[0m 0.04759 1.12130 0.98782 26.29s\n 101 0.05468 0.04105 1.33206 0.98944 26.32s\n 102 0.05375 0.04114 1.30649 0.98746 26.30s\n 103 0.05463 0.04457 1.22568 0.98902 26.30s\n 104 \u001b[36m0.05086\u001b[0m 0.04214 1.20678 0.99043 26.32s\n 105 0.05372 0.04105 1.30862 0.98971 26.36s\n 106 0.05264 \u001b[32m0.03898\u001b[0m 1.35030 0.99079 26.30s\n 107 0.05347 0.04014 1.33219 0.98890 26.29s\n 108 0.05313 0.03927 1.35290 0.98917 26.29s\n 109 0.05145 0.04787 1.07469 0.98710 26.38s\n 110 0.05213 0.04004 1.30189 0.99123 26.33s\n 111 \u001b[36m0.04976\u001b[0m \u001b[32m0.03533\u001b[0m 1.40860 0.99213 26.29s\n 112 0.05133 0.03750 1.36889 0.99046 26.31s\n 113 \u001b[36m0.04824\u001b[0m 0.03842 1.25544 0.98998 26.31s\n 114 0.04835 \u001b[32m0.03483\u001b[0m 1.38822 0.98998 26.29s\n 115 0.04986 0.03573 1.39548 0.99070 26.29s\n 116 0.05027 0.03571 1.40789 0.99159 26.33s\n 117 0.04824 0.03604 1.33835 0.99159 26.28s\n 118 \u001b[36m0.04674\u001b[0m 0.03487 1.34031 0.99105 26.29s\n 119 \u001b[36m0.04608\u001b[0m \u001b[32m0.03465\u001b[0m 1.33006 0.99180 26.30s\n 120 \u001b[36m0.04606\u001b[0m \u001b[32m0.03456\u001b[0m 1.33291 0.99222 26.30s\n 121 0.04809 0.03694 1.30169 0.99150 26.30s\n 122 0.04636 \u001b[32m0.03283\u001b[0m 1.41228 0.99240 26.31s\n 123 \u001b[36m0.04550\u001b[0m 0.03690 1.23319 0.99231 26.30s\n 124 0.05004 0.03521 1.42115 0.99204 26.29s\n 125 0.04707 0.03385 1.39071 0.99312 26.29s\n 126 0.04572 0.03548 1.28865 0.99132 26.30s\n 127 0.04719 0.04356 1.08337 0.98890 26.30s\n 128 0.04724 0.03943 1.19805 0.99123 26.37s\n 129 0.04835 0.03911 1.23616 0.99052 26.32s\n 130 0.04680 \u001b[32m0.03225\u001b[0m 1.45118 0.99330 26.31s\n 131 0.04585 0.03585 1.27881 0.99150 26.30s\n 132 \u001b[36m0.04544\u001b[0m 0.03415 1.33066 0.99249 26.32s\n 133 0.04655 0.03477 1.33879 0.99375 26.30s\n 134 \u001b[36m0.04208\u001b[0m \u001b[32m0.03097\u001b[0m 1.35847 0.99369 26.38s\n 135 \u001b[36m0.04138\u001b[0m 0.03286 1.25954 0.99267 26.30s\n 136 0.04766 0.03291 1.44794 0.99312 26.31s\n 137 0.04210 0.03811 1.10454 0.99061 26.34s\n 138 0.04484 0.03585 1.25081 0.99195 26.33s\n 139 0.04529 0.03321 1.36374 0.99267 26.31s\n 140 \u001b[36m0.04123\u001b[0m 0.03215 1.28251 0.99267 26.30s\n 141 0.04441 0.03360 1.32182 0.99276 26.31s\n 142 0.04147 0.03182 1.30325 0.99276 26.31s\n 143 \u001b[36m0.04013\u001b[0m 0.03493 1.14900 0.99123 26.36s\n 144 0.04500 0.03542 1.27052 0.99258 26.30s\n 145 0.04346 0.03929 1.10616 0.99061 26.55s\n 146 0.04604 0.03638 1.26563 0.99249 26.46s\n 147 0.04440 0.03422 1.29748 0.99195 26.51s\n 148 0.04157 0.03348 1.24175 0.99141 26.53s\n 149 \u001b[36m0.03899\u001b[0m 0.03099 1.25826 0.99285 26.57s\n 150 0.04042 0.03215 1.25745 0.99330 26.62s\n 151 0.04068 \u001b[32m0.02940\u001b[0m 1.38336 0.99222 26.64s\n 152 \u001b[36m0.03820\u001b[0m 0.03082 1.23925 0.99177 26.60s\n 153 0.04044 0.03208 1.26077 0.99348 26.47s\n 154 0.04189 0.03222 1.30037 0.99231 26.76s\n 155 0.04157 0.03438 1.20910 0.99105 26.32s\n 156 0.04059 0.03342 1.21443 0.99222 26.30s\n 157 \u001b[36m0.03698\u001b[0m 0.03034 1.21915 0.99348 26.30s\n 158 0.04171 0.02968 1.40546 0.99321 26.29s\n 159 0.04232 0.03157 1.34051 0.99231 26.33s\n 160 0.04036 0.03285 1.22867 0.99186 26.35s\n 161 0.03781 0.03150 1.20015 0.99267 26.31s\n 162 0.03797 0.03187 1.19172 0.99150 26.29s\n 163 0.04102 0.02993 1.37037 0.99303 26.30s\n 164 0.03833 \u001b[32m0.02921\u001b[0m 1.31222 0.99312 26.29s\n 165 0.03909 0.02921 1.33840 0.99294 26.31s\n 166 0.03702 \u001b[32m0.02782\u001b[0m 1.33041 0.99285 26.30s\n 167 0.03892 0.03106 1.25302 0.99249 26.31s\n 168 0.04091 0.02855 1.43309 0.99357 26.29s\n 169 0.03808 0.03228 1.17955 0.99222 26.30s\n 170 \u001b[36m0.03648\u001b[0m 0.03130 1.16551 0.99330 26.29s\n 171 0.03741 0.02932 1.27590 0.99270 26.30s\n 172 0.04100 \u001b[32m0.02762\u001b[0m 1.48444 0.99312 26.30s\n 173 0.03983 0.03004 1.32586 0.99333 26.29s\n 174 0.03712 0.03106 1.19484 0.99429 26.30s\n 175 \u001b[36m0.03632\u001b[0m 0.03107 1.16881 0.99312 26.42s\n 176 0.03789 0.03538 1.07096 0.99105 26.27s\n 177 \u001b[36m0.03572\u001b[0m \u001b[32m0.02752\u001b[0m 1.29826 0.99285 26.32s\n 178 0.03725 0.03069 1.21374 0.99270 26.33s\n 179 \u001b[36m0.03506\u001b[0m 0.03088 1.13525 0.99321 26.29s\n 180 0.03709 0.03017 1.22943 0.99339 26.52s\n 181 0.03802 0.02792 1.36187 0.99396 26.36s\n 182 0.03595 0.02758 1.30352 0.99420 26.31s\n 183 0.03693 0.02815 1.31195 0.99420 26.35s\n 184 0.03646 \u001b[32m0.02674\u001b[0m 1.36359 0.99375 26.31s\n 185 0.03574 0.03043 1.17447 0.99375 26.48s\n 186 0.03695 0.02732 1.35226 0.99402 26.51s\n 187 0.03540 \u001b[32m0.02544\u001b[0m 1.39175 0.99411 26.74s\n 188 \u001b[36m0.03307\u001b[0m \u001b[32m0.02366\u001b[0m 1.39743 0.99420 26.43s\n 189 0.03388 0.02947 1.14986 0.99360 26.68s\n 190 0.03590 0.02766 1.29789 0.99339 26.43s\n 191 0.03377 0.02795 1.20817 0.99384 26.49s\n 192 \u001b[36m0.03218\u001b[0m 0.03227 0.99723 0.99312 26.67s\n 193 0.03509 0.02968 1.18257 0.99195 26.64s\n 194 0.03844 0.02991 1.28519 0.99339 26.32s\n 195 0.03512 0.02889 1.21581 0.99267 26.49s\n 196 0.03520 0.02772 1.26970 0.99378 26.50s\n 197 0.03518 0.03063 1.14835 0.99375 26.51s\n 198 0.03439 0.03418 1.00605 0.99276 26.54s\n 199 0.03656 0.02930 1.24781 0.99315 26.56s\n 200 0.03342 0.03025 1.10489 0.99267 26.46s\n 201 0.03431 0.03064 1.11969 0.99303 26.55s\n 202 0.03271 0.03359 0.97377 0.99267 26.56s\n 203 0.03291 0.03283 1.00237 0.99294 26.56s\n 204 \u001b[36m0.03145\u001b[0m 0.03389 0.92780 0.99366 26.50s\n 205 0.03504 0.03060 1.14509 0.99402 26.65s\n 206 0.03191 0.02800 1.13972 0.99440 26.66s\n 207 0.03391 0.03067 1.10569 0.99276 26.47s\n 208 \u001b[36m0.02986\u001b[0m 0.03119 0.95748 0.99375 26.31s\n 209 0.03605 0.02906 1.24035 0.99330 26.53s\n 210 0.03290 0.03426 0.96016 0.99339 26.54s\n 211 0.03434 0.03105 1.10587 0.99357 26.55s\n 212 0.03670 0.02937 1.24930 0.99315 26.60s\n 213 0.03349 0.03194 1.04865 0.99369 26.50s\n 214 0.03469 0.03249 1.06786 0.99360 26.61s\n 215 0.03227 0.03132 1.03024 0.99375 26.42s\n 216 0.03249 0.03271 0.99337 0.99378 26.37s\n 217 0.03282 0.02746 1.19507 0.99369 26.56s\n 218 0.03155 0.02842 1.10988 0.99369 26.82s\n 219 0.03384 0.02629 1.28717 0.99396 26.33s\n 220 0.03078 0.02914 1.05640 0.99402 26.36s\n 221 0.03101 0.02811 1.10338 0.99432 26.34s\n 222 0.03438 0.03292 1.04425 0.99330 26.29s\n 223 0.03019 0.03262 0.92552 0.99276 26.39s\n 224 0.03308 0.02721 1.21565 0.99393 26.33s\n 225 0.03051 0.02614 1.16730 0.99420 26.28s\n 226 0.03275 0.03107 1.05390 0.99348 26.31s\n 227 \u001b[36m0.02918\u001b[0m 0.02796 1.04361 0.99414 26.30s\n 228 0.03250 0.03464 0.93834 0.99258 26.41s\n 229 0.03146 0.03096 1.01629 0.99339 26.30s\n 230 0.03335 0.03079 1.08310 0.99312 26.27s\n 231 0.03154 0.02619 1.20437 0.99432 26.30s\n 232 0.03071 0.03089 0.99404 0.99405 26.30s\n 233 0.03168 0.03336 0.94948 0.99432 26.29s\n 234 0.03150 0.02956 1.06533 0.99402 26.32s\n 235 0.02952 0.03742 0.78875 0.99270 26.32s\n 236 0.03411 0.03142 1.08560 0.99252 26.29s\n 237 0.02956 0.03469 0.85235 0.99369 26.31s\n 238 0.03063 0.03021 1.01384 0.99438 26.37s\nEarly stopping.\nBest valid loss was 0.023663 at epoch 188.\nLoaded parameters to layer 'conv1' (shape 64x4x3x3).\nLoaded parameters to layer 'conv1' (shape 64).\nLoaded parameters to layer 'conv2' (shape 48x64x3x3).\nLoaded parameters to layer 'conv2' (shape 48).\nLoaded parameters to layer 'conv3' (shape 48x48x3x3).\nLoaded parameters to layer 'conv3' (shape 48).\nLoaded parameters to layer 'conv4' (shape 48x48x3x3).\nLoaded parameters to layer 'conv4' (shape 48).\nLoaded parameters to layer 'hidden5' (shape 192x512).\nLoaded parameters to layer 'hidden5' (shape 512).\nLoaded parameters to layer 'output' (shape 512x2).\nLoaded parameters to layer 'output' (shape 2).\n"
],
[
"test_accuracy = cnn.score(X_test, y_test)",
"_____no_output_____"
],
[
"test_accuracy",
"_____no_output_____"
],
[
"plot_loss(cnn)",
"_____no_output_____"
],
[
"# store CNN\nsys.setrecursionlimit(1000000000)\nwith open(os.path.expanduser('~/Projects/gp/nets/RGBAPlus.p'), 'wb') as f:\n pickle.dump(cnn, f, -1)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d083430f710837195d15c28c5e36d3d62d160683 | 39,305 | ipynb | Jupyter Notebook | notebooks/ReferenceFrame.ipynb | rnwatanabe/BMC | 545c4c28125684a707641fd97f5d92f303020c47 | [
"CC-BY-4.0"
] | null | null | null | notebooks/ReferenceFrame.ipynb | rnwatanabe/BMC | 545c4c28125684a707641fd97f5d92f303020c47 | [
"CC-BY-4.0"
] | null | null | null | notebooks/ReferenceFrame.ipynb | rnwatanabe/BMC | 545c4c28125684a707641fd97f5d92f303020c47 | [
"CC-BY-4.0"
] | 1 | 2018-10-13T17:35:16.000Z | 2018-10-13T17:35:16.000Z | 41.769394 | 3,071 | 0.617428 | [
[
[
"# Frame of reference\n\n\n> Marcos Duarte, Renato Naville Watanabe \n> [Laboratory of Biomechanics and Motor Control](http://pesquisa.ufabc.edu.br/bmclab) \n> Federal University of ABC, Brazil",
"_____no_output_____"
],
[
"<h1>Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Frame-of-reference-for-human-motion-analysis\" data-toc-modified-id=\"Frame-of-reference-for-human-motion-analysis-1\"><span class=\"toc-item-num\">1 </span>Frame of reference for human motion analysis</a></span></li><li><span><a href=\"#Cartesian-coordinate-system\" data-toc-modified-id=\"Cartesian-coordinate-system-2\"><span class=\"toc-item-num\">2 </span>Cartesian coordinate system</a></span><ul class=\"toc-item\"><li><span><a href=\"#Standardizations-in-movement-analysis\" data-toc-modified-id=\"Standardizations-in-movement-analysis-2.1\"><span class=\"toc-item-num\">2.1 </span>Standardizations in movement analysis </a></span></li></ul></li><li><span><a href=\"#Determination-of-a-coordinate-system\" data-toc-modified-id=\"Determination-of-a-coordinate-system-3\"><span class=\"toc-item-num\">3 </span>Determination of a coordinate system</a></span><ul class=\"toc-item\"><li><span><a href=\"#Definition-of-a-basis\" data-toc-modified-id=\"Definition-of-a-basis-3.1\"><span class=\"toc-item-num\">3.1 </span>Definition of a basis</a></span></li><li><span><a href=\"#Using-the-cross-product\" data-toc-modified-id=\"Using-the-cross-product-3.2\"><span class=\"toc-item-num\">3.2 </span>Using the cross product</a></span></li><li><span><a href=\"#Gram–Schmidt-process\" data-toc-modified-id=\"Gram–Schmidt-process-3.3\"><span class=\"toc-item-num\">3.3 </span>Gram–Schmidt process</a></span></li></ul></li><li><span><a href=\"#Polar-and-spherical-coordinate-systems\" data-toc-modified-id=\"Polar-and-spherical-coordinate-systems-4\"><span class=\"toc-item-num\">4 </span>Polar and spherical coordinate systems</a></span><ul class=\"toc-item\"><li><span><a href=\"#Polar-coordinate-system\" data-toc-modified-id=\"Polar-coordinate-system-4.1\"><span class=\"toc-item-num\">4.1 </span>Polar coordinate system</a></span></li><li><span><a href=\"#Spherical-coordinate-system\" data-toc-modified-id=\"Spherical-coordinate-system-4.2\"><span class=\"toc-item-num\">4.2 </span>Spherical coordinate system </a></span></li></ul></li><li><span><a href=\"#Generalized-coordinates\" data-toc-modified-id=\"Generalized-coordinates-5\"><span class=\"toc-item-num\">5 </span>Generalized coordinates</a></span></li><li><span><a href=\"#Further-reading\" data-toc-modified-id=\"Further-reading-6\"><span class=\"toc-item-num\">6 </span>Further reading</a></span></li><li><span><a href=\"#Video-lectures-on-the-Internet\" data-toc-modified-id=\"Video-lectures-on-the-Internet-7\"><span class=\"toc-item-num\">7 </span>Video lectures on the Internet</a></span></li><li><span><a href=\"#Problems\" data-toc-modified-id=\"Problems-8\"><span class=\"toc-item-num\">8 </span>Problems</a></span></li><li><span><a href=\"#References\" data-toc-modified-id=\"References-9\"><span class=\"toc-item-num\">9 </span>References</a></span></li></ul></div>",
"_____no_output_____"
],
[
"<a href=\"http://en.wikipedia.org/wiki/Motion_(physics)\">Motion</a> (a change of position in space with respect to time) is not an absolute concept; a reference is needed to describe the motion of the object in relation to this reference. Likewise, the state of such reference cannot be absolute in space and so motion is relative. \nA [frame of reference](http://en.wikipedia.org/wiki/Frame_of_reference) is the place with respect to we choose to describe the motion of an object. In this reference frame, we define a [coordinate system](http://en.wikipedia.org/wiki/Coordinate_system) (a set of axes) within which we measure the motion of an object (but frame of reference and coordinate system are often used interchangeably). \n\nOften, the choice of reference frame and coordinate system is made by convenience. However, there is an important distinction between reference frames when we deal with the dynamics of motion, where we are interested to understand the forces related to the motion of the object. In dynamics, we refer to [inertial frame of reference](http://en.wikipedia.org/wiki/Inertial_frame_of_reference) (a.k.a., Galilean reference frame) when the Newton's laws of motion in their simple form are valid in this frame and to non-inertial frame of reference when the Newton's laws in their simple form are not valid (in such reference frame, fictitious accelerations/forces appear). An inertial reference frame is at rest or moves at constant speed (because there is no absolute rest!), whereas a non-inertial reference frame is under acceleration (with respect to an inertial reference frame).\n\nThe concept of frame of reference has changed drastically since Aristotle, Galileo, Newton, and Einstein. To read more about that and its philosophical implications, see [Space and Time: Inertial Frames](http://plato.stanford.edu/entries/spacetime-iframes/).",
"_____no_output_____"
],
[
"## Frame of reference for human motion analysis\n\nIn anatomy, we use a simplified reference frame composed by perpendicular planes to provide a standard reference for qualitatively describing the structures and movements of the human body, as shown in the next figure.\n\n<div class='center-align'><figure><img src=\"http://upload.wikimedia.org/wikipedia/commons/3/34/BodyPlanes.jpg\" width=\"300\" alt=\"Anatomical body position\"/><figcaption><center><i>Figure. Anatomical body position and body planes (<a href=\"http://en.wikipedia.org/wiki/Human_anatomical_terms\" target=\"_blank\">image from Wikipedia</a>).</i></center></figcaption> </figure></div> ",
"_____no_output_____"
],
[
"## Cartesian coordinate system\n\nAs we perceive the surrounding space as three-dimensional, a convenient coordinate system is the [Cartesian coordinate system](http://en.wikipedia.org/wiki/Cartesian_coordinate_system) in the [Euclidean space](http://en.wikipedia.org/wiki/Euclidean_space) with three orthogonal axes as shown below. The axes directions are commonly defined by the [right-hand rule](http://en.wikipedia.org/wiki/Right-hand_rule) and attributed the letters X, Y, Z. The orthogonality of the Cartesian coordinate system is convenient for its use in classical mechanics, most of the times the structure of space is assumed having the [Euclidean geometry](http://en.wikipedia.org/wiki/Euclidean_geometry) and as consequence, the motion in different directions are independent of each other. \n\n<div class='center-align'><figure><img src=\"https://raw.githubusercontent.com/demotu/BMC/master/images/CCS.png\" width=350/><figcaption><center><i>Figure. A point in three-dimensional Euclidean space described in a Cartesian coordinate system.</i></center></figcaption> </figure></div>",
"_____no_output_____"
],
[
"### Standardizations in movement analysis\n\nThe concept of reference frame in Biomechanics and motor control is very important and central to the understanding of human motion. For example, do we see, plan and control the movement of our hand with respect to reference frames within our body or in the environment we move? Or a combination of both? \nThe figure below, although derived for a robotic system, illustrates well the concept that we might have to deal with multiple coordinate systems. \n\n<div class='center-align'><figure><img src=\"https://raw.githubusercontent.com/demotu/BMC/master/images/coordinatesystems.png\" width=450/><figcaption><center><i>Figure. Multiple coordinate systems for use in robots (figure from Corke (2017)).</i></center></figcaption></figure></div>\n\nFor three-dimensional motion analysis in Biomechanics, we may use several different references frames for convenience and refer to them as global, laboratory, local, anatomical, or technical reference frames or coordinate systems (we will study this later). \nThere has been proposed different standardizations on how to define frame of references for the main segments and joints of the human body. For instance, the International Society of Biomechanics has a [page listing standardization proposals](https://isbweb.org/activities/standards) by its standardization committee and subcommittees:",
"_____no_output_____"
]
],
[
[
"from IPython.display import IFrame\nIFrame('https://isbweb.org/activities/standards', width='100%', height=400)",
"_____no_output_____"
]
],
[
[
" Another initiative for the standardization of references frames is from the [Virtual Animation of the Kinematics of the Human for Industrial, Educational and Research Purposes (VAKHUM)](https://raw.githubusercontent.com/demotu/BMC/master/refs/VAKHUM.pdf) project.",
"_____no_output_____"
],
[
"## Determination of a coordinate system\n\nIn Biomechanics, we may use different coordinate systems for convenience and refer to them as global, laboratory, local, anatomical, or technical reference frames or coordinate systems. For example, in a standard gait analysis, we define a global or laboratory coordinate system and a different coordinate system for each segment of the body to be able to describe the motion of a segment in relation to anatomical axes of another segment. To define this anatomical coordinate system, we need to place markers on anatomical landmarks on each segment. We also may use other markers (technical markers) on the segment to improve the motion analysis and then we will also have to define a technical coordinate system for each segment.\n\nAs we perceive the surrounding space as three-dimensional, a convenient coordinate system to use is the [Cartesian coordinate system](http://en.wikipedia.org/wiki/Cartesian_coordinate_system) with three orthogonal axes in the [Euclidean space](http://en.wikipedia.org/wiki/Euclidean_space). From [linear algebra](http://en.wikipedia.org/wiki/Linear_algebra), a set of unit linearly independent vectors (orthogonal in the Euclidean space and each with norm (length) equals to one) that can represent any vector via [linear combination](http://en.wikipedia.org/wiki/Linear_combination) is called a <a href=\"http://en.wikipedia.org/wiki/Basis_(linear_algebra)\">basis</a> (or orthonormal basis). The figure below shows a point and its position vector in the Cartesian coordinate system and the corresponding versors (unit vectors) of the basis for this coordinate system. See the notebook [Scalar and vector](http://nbviewer.ipython.org/github/demotu/BMC/blob/master/notebooks/ScalarVector.ipynb) for a description on vectors. \n\n<div class='center-align'><figure><img src=\"https://raw.githubusercontent.com/demotu/BMC/master/images/vector3Dijk.png\" width=350/><figcaption><center><i>Figure. Representation of a point **P** and its position vector <span class=\"notranslate\"> $\\overrightarrow{\\mathbf{r}}$</span> in a Cartesian coordinate system. The versors<span class=\"notranslate\"> $\\hat{\\mathbf{i}}, \\hat{\\mathbf{j}}, \\hat{\\mathbf{k}}$</span> form a basis for this coordinate system and are usually represented in the color sequence RGB (red, green, blue) for easier visualization.</i></center></figcaption></figure></div>\n\nOne can see that the versors of the basis shown in the figure above have the following coordinates in the Cartesian coordinate system:\n\n<span class=\"notranslate\">\n\\begin{equation}\n\\hat{\\mathbf{i}} = \\begin{bmatrix}1\\\\0\\\\0 \\end{bmatrix}, \\quad \\hat{\\mathbf{j}} = \\begin{bmatrix}0\\\\1\\\\0 \\end{bmatrix}, \\quad \\hat{\\mathbf{k}} = \\begin{bmatrix} 0 \\\\ 0 \\\\ 1 \\end{bmatrix}\n\\end{equation}\n</span>\n\nUsing the notation described in the figure above, the position vector $\\overrightarrow{\\mathbf{r}}$ (or the point $\\overrightarrow{\\mathbf{P}}$) can be expressed as:\n\n<span class=\"notranslate\">\n\\begin{equation}\n\\overrightarrow{\\mathbf{r}} = x\\hat{\\mathbf{i}} + y\\hat{\\mathbf{j}} + z\\hat{\\mathbf{k}}\n\\end{equation}\n</span>",
"_____no_output_____"
],
[
"### Definition of a basis\n\nThe mathematical problem of determination of a coordinate system is to find a basis and an origin for it (a basis is only a set of vectors, with no origin). There are different methods to calculate a basis given a set of points (coordinates), for example, one can use the scalar product or the cross product for this problem.",
"_____no_output_____"
],
[
"### Using the cross product\n\nLet's now define a basis using a common method in motion analysis (employing the cross product): \nGiven the coordinates of three noncollinear points in 3D space (points that do not all lie on the same line),<span class=\"notranslate\"> $\\overrightarrow{\\mathbf{m}}_1, \\overrightarrow{\\mathbf{m}}_2, \\overrightarrow{\\mathbf{m}}_3$</span>, which would represent the positions of markers captured from a motion analysis session, a basis can be found following these steps:",
"_____no_output_____"
],
[
"1. First axis, <span class=\"notranslate\">$\\overrightarrow{\\mathbf{v}}_1$</span>, the vector <span class=\"notranslate\">$\\overrightarrow{\\mathbf{m}}_2-\\overrightarrow{\\mathbf{m}}_1$</span> (or any other vector difference); ",
"_____no_output_____"
],
[
"2. Second axis,<span class=\"notranslate\"> $\\overrightarrow{\\mathbf{v}}_2$</span>, the cross or vector product between the vectors <span class=\"notranslate\"> $\\overrightarrow{\\mathbf{v}}_1$</span> and <span class=\"notranslate\">$\\overrightarrow{\\mathbf{m}}_3-\\overrightarrow{\\mathbf{m}}_1$ </span>(or <span class=\"notranslate\">$\\overrightarrow{\\mathbf{m}}_3-\\overrightarrow{\\mathbf{m}}_2$)</span>; ",
"_____no_output_____"
],
[
"3. Third axis, <span class=\"notranslate\"> $\\overrightarrow{\\mathbf{v}}_3$</span>, the cross product between the vectors <span class=\"notranslate\"> $\\overrightarrow{\\mathbf{v}}_1$</span> and <span class=\"notranslate\"> $\\overrightarrow{\\mathbf{v}}_2$</span>. ",
"_____no_output_____"
],
[
"4. Make all vectors to have norm 1 dividing each vector by its norm.",
"_____no_output_____"
],
[
"The positions of the points used to construct a coordinate system have, by definition, to be specified in relation to an already existing coordinate system. In motion analysis, this coordinate system is the coordinate system from the motion capture system and it is established in the calibration phase. In this phase, the positions of markers placed on an object with perpendicular axes and known distances between the markers are captured and used as the reference (laboratory) coordinate system.",
"_____no_output_____"
],
[
"For example, given the positions <span class=\"notranslate\"> $\\overrightarrow{\\mathbf{m}}_1 = [1,2,5], \\overrightarrow{\\mathbf{m}}_2 = [2,3,3], \\overrightarrow{\\mathbf{m}}_3 = [4,0,2]$</span>, a basis can be found with:",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\nm1 = np.array([1, 2, 5])\nm2 = np.array([2, 3, 3])\nm3 = np.array([4, 0, 2])\n\nv1 = m2 - m1 # first axis\nv2 = np.cross(v1, m3 - m1) # second axis\nv3 = np.cross(v1, v2) # third axis\n\n# Vector normalization\ne1 = v1/np.linalg.norm(v1)\ne2 = v2/np.linalg.norm(v2)\ne3 = v3/np.linalg.norm(v3)\n\nprint('Versors:', '\\ne1 =', e1, '\\ne2 =', e2, '\\ne3 =', e3)\nprint('\\nTest of orthogonality (cross product between versors):',\n '\\ne1 x e2:', np.linalg.norm(np.cross(e1, e2)),\n '\\ne1 x e3:', np.linalg.norm(np.cross(e1, e3)),\n '\\ne2 x e3:', np.linalg.norm(np.cross(e2, e3)))\nprint('\\nNorm of each versor:',\n '\\n||e1|| =', np.linalg.norm(e1),\n '\\n||e2|| =', np.linalg.norm(e2),\n '\\n||e3|| =', np.linalg.norm(e3))",
"Versors: \ne1 = [ 0.40824829 0.40824829 -0.81649658] \ne2 = [-0.76834982 -0.32929278 -0.5488213 ] \ne3 = [-0.49292179 0.85141036 0.17924429]\n\nTest of orthogonality (cross product between versors): \ne1 x e2: 1.0 \ne1 x e3: 1.0000000000000002 \ne2 x e3: 0.9999999999999999\n\nNorm of each versor: \n||e1|| = 1.0 \n||e2|| = 1.0 \n||e3|| = 1.0\n"
]
],
[
[
"To define a coordinate system using the calculated basis, we also need to define an origin. In principle, we could use any point as origin, but if the calculated coordinate system should follow anatomical conventions, e.g., the coordinate system origin should be at a joint center, we will have to calculate the basis and origin according to standards used in motion analysis as discussed before. \n\nIf the coordinate system is a technical basis and not anatomic-based, a common procedure in motion analysis is to define the origin for the coordinate system as the centroid (average) position among the markers at the reference frame. Using the average position across markers potentially reduces the effect of noise (for example, from soft tissue artifact) on the calculation. \n\nFor the markers in the example above, the origin of the coordinate system will be:",
"_____no_output_____"
]
],
[
[
"origin = np.mean((m1, m2, m3), axis=0)\nprint('Origin: ', origin)",
"Origin: [2.33333333 1.66666667 3.33333333]\n"
]
],
[
[
"Let's plot the coordinate system and the basis using the custom Python function `CCS.py`:",
"_____no_output_____"
]
],
[
[
"import sys\nsys.path.insert(1, r'./../functions') # add to pythonpath\nfrom CCS import CCS",
"_____no_output_____"
],
[
"markers = np.vstack((m1, m2, m3))\nbasis = np.vstack((e1, e2, e3))",
"_____no_output_____"
]
],
[
[
"Create figure in this page (inline):\n",
"_____no_output_____"
]
],
[
[
"%matplotlib notebook\n\nmarkers = np.vstack((m1, m2, m3))\nbasis = np.vstack((e1, e2, e3))\nCCS(xyz=[], Oijk=origin, ijk=basis, point=markers, vector=True);",
"_____no_output_____"
]
],
[
[
"### Gram–Schmidt process\n\nAnother classical procedure in mathematics, employing the scalar product, is known as the [Gram–Schmidt process](http://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process). See the notebook [Scalar and Vector](http://nbviewer.jupyter.org/github/bmclab/BMC/blob/master/notebooks/ScalarVector.ipynb) for a demonstration of the Gram–Schmidt process and how to implement it in Python.\n\nThe [Gram–Schmidt process](http://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process) is a method for orthonormalizing (orthogonal unit versors) a set of vectors using the scalar product. The Gram–Schmidt process works for any number of vectors. \n\nFor example, given three vectors, <span class=\"notranslate\">\n$\\overrightarrow{\\mathbf{a}}, \\overrightarrow{\\mathbf{b}}, \\overrightarrow{\\mathbf{c}}$</span>, in the 3D space, a basis <span class=\"notranslate\"> $\\{\\hat{e}_a, \\hat{e}_b, \\hat{e}_c\\}$</span> can be found using the Gram–Schmidt process by: ",
"_____no_output_____"
],
[
"The first versor is in the <span class=\"notranslate\">\n$\\overrightarrow{\\mathbf{a}}$</span> direction (or in the direction of any of the other vectors): \n\n<span class=\"notranslate\">\n\\begin{equation}\n\\hat{e}_a = \\frac{\\overrightarrow{\\mathbf{a}}}{||\\overrightarrow{\\mathbf{a}}||}\n\\end{equation}\n</span>",
"_____no_output_____"
],
[
"The second versor, orthogonal to <span class=\"notranslate\"> $\\hat{e}_a$</span>, can be found considering we can express vector <span class=\"notranslate\"> $\\overrightarrow{\\mathbf{b}}$ </span> in terms of the <span class=\"notranslate\"> $\\hat{e}_a$ </span> direction as: \n\n<span class=\"notranslate\"> \n$$ \\overrightarrow{\\mathbf{b}} = \\overrightarrow{\\mathbf{b}}^\\| + \\overrightarrow{\\mathbf{b}}^\\bot $$\n</span>\n\nThen:\n\n<span class=\"notranslate\">\n$$ \\overrightarrow{\\mathbf{b}}^\\bot = \\overrightarrow{\\mathbf{b}} - \\overrightarrow{\\mathbf{b}}^\\| = \\overrightarrow{\\mathbf{b}} - (\\overrightarrow{\\mathbf{b}} \\cdot \\hat{e}_a ) \\hat{e}_a $$\n</span>\n\nFinally:\n\n<span class=\"notranslate\">\n$$ \\hat{e}_b = \\frac{\\overrightarrow{\\mathbf{b}}^\\bot}{||\\overrightarrow{\\mathbf{b}}^\\bot||} $$\n</span>",
"_____no_output_____"
],
[
"The third versor, orthogonal to <span class=\"notranslate\"> $\\{\\hat{e}_a, \\hat{e}_b\\}$</span>, can be found expressing the vector <span class=\"notranslate\"> $\\overrightarrow{\\mathbf{C}}$</span> in terms of <span class=\"notranslate\"> $\\hat{e}_a$</span> and <span class=\"notranslate\"> $\\hat{e}_b$</span> directions as:\n\n<span class=\"notranslate\">\n$$ \\overrightarrow{\\mathbf{c}} = \\overrightarrow{\\mathbf{c}}^\\| + \\overrightarrow{\\mathbf{c}}^\\bot $$\n</span>\n\nThen:\n\n<span class=\"notranslate\">\n$$ \\overrightarrow{\\mathbf{c}}^\\bot = \\overrightarrow{\\mathbf{c}} - \\overrightarrow{\\mathbf{c}}^\\| $$\n</span>\n\nWhere:\n\n<span class=\"notranslate\">\n$$ \\overrightarrow{\\mathbf{c}}^\\| = (\\overrightarrow{\\mathbf{c}} \\cdot \\hat{e}_a ) \\hat{e}_a + (\\overrightarrow{\\mathbf{c}} \\cdot \\hat{e}_b ) \\hat{e}_b $$\n</span>\n\nFinally:\n\n<span class=\"notranslate\">\n$$ \\hat{e}_c = \\frac{\\overrightarrow{\\mathbf{c}}^\\bot}{||\\overrightarrow{\\mathbf{c}}^\\bot||} $$\n</span>",
"_____no_output_____"
],
[
"Let's implement the Gram–Schmidt process in Python.\n\nFor example, consider the positions (vectors) <span class=\"notranslate\">\n$\\overrightarrow{\\mathbf{a}} = [1,2,0], \\overrightarrow{\\mathbf{b}} = [0,1,3], \\overrightarrow{\\mathbf{c}} = [1,0,1]$</span>:",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\na = np.array([1, 2, 0])\nb = np.array([0, 1, 3])\nc = np.array([1, 0, 1])",
"_____no_output_____"
]
],
[
[
"The first versor is:",
"_____no_output_____"
]
],
[
[
"ea = a/np.linalg.norm(a)\nprint(ea)",
"[ 0.4472136 0.89442719 0. ]\n"
]
],
[
[
"The second versor is:",
"_____no_output_____"
]
],
[
[
"eb = b - np.dot(b, ea)*ea\neb = eb/np.linalg.norm(eb)\nprint(eb)",
"[-0.13187609 0.06593805 0.98907071]\n"
]
],
[
[
"And the third version is:",
"_____no_output_____"
]
],
[
[
"ec = c - np.dot(c, ea)*ea - np.dot(c, eb)*eb\nec = ec/np.linalg.norm(ec)\nprint(ec)",
"[ 0.88465174 -0.44232587 0.14744196]\n"
]
],
[
[
"Let's check the orthonormality between these versors:",
"_____no_output_____"
]
],
[
[
"print(' Versors:', '\\nea =', ea, '\\neb =', eb, '\\nec =', ec)\nprint('\\n Test of orthogonality (scalar product between versors):',\n '\\n ea x eb:', np.dot(ea, eb),\n '\\n eb x ec:', np.dot(eb, ec),\n '\\n ec x ea:', np.dot(ec, ea))\nprint('\\n Norm of each versor:',\n '\\n ||ea|| =', np.linalg.norm(ea),\n '\\n ||eb|| =', np.linalg.norm(eb),\n '\\n ||ec|| =', np.linalg.norm(ec))",
" Versors: \nea = [ 0.4472136 0.89442719 0. ] \neb = [-0.13187609 0.06593805 0.98907071] \nec = [ 0.88465174 -0.44232587 0.14744196]\n\n Test of orthogonality (scalar product between versors): \n ea x eb: 2.08166817117e-17 \n eb x ec: -2.77555756156e-17 \n ec x ea: 5.55111512313e-17\n\n Norm of each versor: \n ||ea|| = 1.0 \n ||eb|| = 1.0 \n ||ec|| = 1.0\n"
]
],
[
[
"## Polar and spherical coordinate systems\n\nWhen studying circular motion in two or three dimensions, the use of a polar (for 2D) or spherical (for 3D) coordinate system can be more convenient than the Cartesian coordinate system.",
"_____no_output_____"
],
[
"### Polar coordinate system\n\nIn the polar coordinate system, a point in a plane is described by its distance $r$ to the origin (the ray from the origin to this point is the polar axis) and the angle $\\theta$ (measured counterclockwise) between the polar axis and an axis of the coordinate system as shown next. \n\n<div class='center-align'><figure><img src=\"https://raw.githubusercontent.com/demotu/BMC/master/images/polar.png\"/><figcaption><center><i>Figure. Representation of a point in a polar coordinate system.</i></center></figcaption></figure></div>\n\nThe relation of the coordinates in the Cartesian and polar coordinate systems is:\n\n\n<span class=\"notranslate\">\n$$\\begin{array}{l l}\nx = r\\cos\\theta \\\\\ny = r\\sin\\theta \\\\\nr = \\sqrt{x^2 + y^2}\n\\end{array} $$\n</span>",
"_____no_output_____"
],
[
"### Spherical coordinate system\n\nThe spherical coordinate system can be seen as an extension of the polar coordinate system to three dimensions where an orthogonal axis is added and a second angle is used to describe the point with respect to this third axis as shown next. \n\n<div class='center-align'><figure><img src=\"https://raw.githubusercontent.com/demotu/BMC/master/images/spherical.png\"/><figcaption><center><i>Figure. Representation of a point in a spherical coordinate system.</i></center></figcaption></figure></div>\n\nThe relation of the coordinates in the Cartesian and spherical coordinate systems is:\n\n<span class=\"notranslate\">\n$$\\begin{array}{l l}\nx = r\\sin\\theta\\cos\\phi \\\\\ny = r\\sin\\theta\\sin\\phi \\\\\nz = r\\cos\\theta \\\\\nr = \\sqrt{x^2 + y^2 + z^2}\n\\end{array} $$\n</span>",
"_____no_output_____"
],
[
"## Generalized coordinates\n\nIn mechanics, generalized coordinates are a set of coordinates that describes the configuration of a system. Generalized coordinates are usually selected for convenience (e.g., simplifies the resolution of the problem) or to provide the minimum number of coordinates to describe the configuration of a system. \n\nFor instance, generalized coordinates are used to describe the motion of a system with multiple links where instead of using Cartesian coordinates, it's more convenient to use the angles between links as coordinates.",
"_____no_output_____"
],
[
"## Further reading\n\n - Read pages 70-92 of the 1st chapter of the [Ruina and Rudra's book](http://ruina.tam.cornell.edu/Book/index.html) for a review of Gram-Schmidt and cross products. ",
"_____no_output_____"
],
[
"## Video lectures on the Internet\n\n - Khan Academy: [Finding an orthonormal basis using the Gram-Schmidt Process](https://www.khanacademy.org/math/linear-algebra/alternate-bases/orthonormal-basis/v/linear-algebra-the-gram-schmidt-process)",
"_____no_output_____"
],
[
"## Problems\n\n1. Right now, how fast are you moving? In your answer, consider your motion in relation to Earth and in relation to Sun.\n\n2. Go to the website [http://www.wisc-online.com/Objects/ViewObject.aspx?ID=AP15305](http://www.wisc-online.com/Objects/ViewObject.aspx?ID=AP15305) and complete the interactive lesson to learn about the anatomical terminology to describe relative position in the human body.\n\n3. To learn more about Cartesian coordinate systems go to the website [http://www.mathsisfun.com/data/cartesian-coordinates.html](http://www.mathsisfun.com/data/cartesian-coordinates.html), study the material, and answer the 10 questions at the end.\n\n4. Given the points in the 3D space,<span class=\"notranslate\"> $m1 = [2,2,0], m2 = [0,1,1], m3 = [1,2,0]$</span>, find an orthonormal basis.\n\n5. Determine if the following points form a basis in the 3D space,<span class=\"notranslate\"> $m1 = [2,2,0], m2 = [1,1,1], m3 = [1,1,0]$</span>.\n\n6. Derive expressions for the three axes of the pelvic basis considering the convention of the [Virtual Animation of the Kinematics of the Human for Industrial, Educational and Research Purposes (VAKHUM)](https://raw.githubusercontent.com/demotu/BMC/master/refs/VAKHUM.pdf) project (use RASIS, LASIS, RPSIS, and LPSIS as names for the pelvic anatomical landmarks and indicate the expression for each axis).\n\n7. Determine the basis for the pelvis following the convention of the [Virtual Animation of the Kinematics of the Human for Industrial, Educational and Research Purposes (VAKHUM)](https://raw.githubusercontent.com/demotu/BMC/master/refs/VAKHUM.pdf) project for the following anatomical landmark positions (units in meters):<span class=\"notranslate\"> $RASIS=[0.5,0.8,0.4], LASIS=[0.55,0.78,0.1], RPSIS=[0.3,0.85,0.2], LPSIS=[0.29,0.78,0.3]$</span>.",
"_____no_output_____"
],
[
"## References\n\n- Corke P (2017) [Robotics, Vision and Control: Fundamental Algorithms in MATLAB](http://www.petercorke.com/RVC/). 2nd ed. Springer-Verlag Berlin. \n- [Standards - International Society of Biomechanics](https://isbweb.org/activities/standards). \n- Stanford Encyclopedia of Philosophy. [Space and Time: Inertial Frames](http://plato.stanford.edu/entries/spacetime-iframes/). \n- [Virtual Animation of the Kinematics of the Human for Industrial, Educational and Research Purposes (VAKHUM)](https://raw.githubusercontent.com/demotu/BMC/master/refs/VAKHUM.pdf). ",
"_____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",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
d0834c802bbda2769f0b15b73a46da266de81309 | 123,839 | ipynb | Jupyter Notebook | .ipynb_checkpoints/Numerical_Analysis_Volume_Sampling_vs_Projection_DPP-ollld-checkpoint.ipynb | AyoubBelhadji/FrameBuilder | 537094ca2de904a61d4babb2c7a4f7bbc3e312fd | [
"MIT"
] | null | null | null | .ipynb_checkpoints/Numerical_Analysis_Volume_Sampling_vs_Projection_DPP-ollld-checkpoint.ipynb | AyoubBelhadji/FrameBuilder | 537094ca2de904a61d4babb2c7a4f7bbc3e312fd | [
"MIT"
] | null | null | null | .ipynb_checkpoints/Numerical_Analysis_Volume_Sampling_vs_Projection_DPP-ollld-checkpoint.ipynb | AyoubBelhadji/FrameBuilder | 537094ca2de904a61d4babb2c7a4f7bbc3e312fd | [
"MIT"
] | null | null | null | 66.188669 | 27,056 | 0.609897 | [
[
[
"# Volume Sampling vs projection DPP for low rank approximation\n## Introduction\n#### In this notebook we compare the volume sampling and projection DPP for low rank approximation.\nWe recall the result proved in the article [DRVW]:\\\\\nLet S be a random subset of k columns of X chosen with probability: $$P(S) = \\frac{1}{Z_{k}} det(X_{.,S}^{T}X_{.,S})$$ with $$Z_{k} = \\sum\\limits_{S \\subset [N], |S| = k} det(X_{.,S}^{T}X_{.,S})$$\nThen\n$$\\begin{equation}\nE(\\| X - \\pi_{X_{.,S}}(X) \\|_{Fr}^{2}) \\leq (k+1)\\| X - \\pi_{k}(X) \\|_{Fr}^{2}\n\\end{equation}$$\n\n\nWe can prove that the volume sampling distribution is a mixture of projection DPPs distributions..., in particular one projection DPP distribution stands out for the problem of low rank approximation: ....\\\\\nFor the moment, there is no analytical expression for $$\\begin{equation}\nE(\\| X - \\pi_{X_{.,S}}(X) \\|_{Fr}^{2}) \n\\end{equation}$$ under the distribution of projection DPP.\\\\\nHowever, we can calculate this quantity using simulation on some matrices representing cloud points with some specific geometric constraints.\n\nLet $$X \\in R^{n \\times m}$$ a matrix representing a cloud of points.\nWe can write the SVD of $$X = UDV^{T}$$ \nIn this notebook we investigate the influence of some structures enforced to V and D on the expected error expressed above for different algorithms: Volume Sampling, Projection DPP and the deterministic algorithm. \nAs for the Volume Sampling distribution, we can express the expected approximation error using only the elements of D. We can test this theoretical property in the next Numerical Study below. However, there is no closed formula (for the moment) for the expected approximation error under Projection DPP distribution. We will see in the Numerical Study section, that this value cannot depends only on the elements of D. ",
"_____no_output_____"
],
[
"#### References\n[DRVW] Deshpande, Amit and Rademacher, Luis and Vempala, Santosh and Wang, Grant - Matrix Approximation and Projective Clustering via Volume Sampling 2006\n\n[BoDr] Boutsidis, Christos and Drineas, Petros - Deterministic and randomized column selection algorithms for matrices 2014\n\n[] INDERJIT S. DHILLON , ROBERT W. HEATH JR., MA ́TYA ́S A. SUSTIK, AND\nJOEL A. TROPP - GENERALIZED FINITE ALGORITHMS FOR CONSTRUCTING HERMITIAN MATRICES\nWITH PRESCRIBED DIAGONAL AND SPECTRUM 2005",
"_____no_output_____"
],
[
"## I- Generating a cloud of points with geometric constraints\nIn this simulation we will enforce some structure on the matrix V for two values of the matrix D. While the matrix U will be choosen randomly. \nWe want to investigate the influence of the profile of the norms of the V_k rows: the k-leverage scores. For this purpose we use an algorithm proposed in the article []: this algorithm outputs a ( dxk) matrix Q with orthonormal columns and a prescribed profile of the norms of the rows. If we consider the Gram matrix H= QQ^{T}, this boils down to enforce the diagonal of H while keeping its spectrum containing k ones and d-k zeros. \nThe algorithm proceed as following:\n* Initialization of the matrix Q by the rectangular identity\n* Apply a Givens Rotation (of dimension d) to the matrix Q: this step will enforce the norm of a row every iteration\n* Outputs the resulting matrix when all the rows norms are enforced.\n",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nfrom itertools import combinations\nfrom scipy.stats import binom\nimport scipy.special\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nfrom IPython.display import display, HTML\nfrom FrameBuilder.eigenstepsbuilder import *\nfrom decimal import *",
"_____no_output_____"
],
[
"u = np.random.uniform(0,1)",
"_____no_output_____"
],
[
"u",
"_____no_output_____"
]
],
[
[
"### I-1- Givens Rotations generators\nThese functions generate a Givens rotation ",
"_____no_output_____"
]
],
[
[
"def t_func(q_i,q_j,q_ij,l_i,l_j): \n # t in section 3.1 Dhillon (2005) \n delta = np.power(q_ij,2)-(q_i-l_i)*(q_j-l_i)\n if delta<0:\n print(delta)\n print(\"error sqrt\")\n t = q_ij - np.sqrt(delta) \n t = t/(q_j-l_i)\n return t\n \ndef G_func(i,j,q_i,q_j,q_ij,l_i,l_j,N): \n # Gitens Rotation \n G=np.eye(N) \n t = t_func(q_i,q_j,q_ij,l_i,l_j)\n c = 1/(np.sqrt(np.power(t,2)+1))\n s = t*c\n G[i,i]=c\n G[i,j]=s \n G[j,i]= -s\n G[j,j]= c\n return G",
"_____no_output_____"
]
],
[
[
"The following function is an implementation of the algorithm [] figuring in the article [] to generate an orthogonal matrix with a prescribed profile of leverage scores.\nIn fact this is a simplification of the algorithm .....",
"_____no_output_____"
]
],
[
[
"class Data_Set_Generator:\n def __init__(self, N, d, nu, Sigma):\n self.N = N\n self.d = d\n self.nu = nu\n self.Sigma = Sigma\n self.mean = np.zeros(d)\n \n def multivariate_t_rvs(self):\n x = np.random.chisquare(self.nu, self.N)/self.nu\n z = np.random.multivariate_normal(self.mean,self.Sigma,(self.N,))\n return self.mean + z/np.sqrt(x)[:,None] ",
"_____no_output_____"
],
[
"def generate_orthonormal_matrix_with_leverage_scores_ES(N,d,lv_scores_vector,versions_number,nn_cardinal_list):\n\n lambda_vector = np.zeros((N))\n lambda_vector[0:d] = np.ones((d))\n\n #mu_vector = np.linspace(1, 0.1, num=N)\n #sum_mu_vector = np.sum(mu_vector)\n #mu_vector = d/sum_mu_vector*mu_vector\n Q = np.zeros((N,d))\n previous_Q = np.zeros((versions_number+1,N,d))\n #mu_vector = d/N*np.ones((N,1))\n E = np.zeros((N,N)) #(d,N)\n counter = 0\n for j in nn_cardinal_list:\n print(\"counter\")\n print(counter)\n mu_vector = generate_leverage_scores_vector_with_dirichlet(N,d,j)\n print(np.sum(mu_vector))\n print(mu_vector)\n E_test = get_eigensteps_random(mu_vector,lambda_vector,N,d)\n E_ = np.zeros((d,N+1))\n for i in range(d):\n E_[i,1:N+1] = E_test[i,:] \n print(E_test)\n #F_test = get_F(d,N,np.asmatrix(E_),mu_vector)\n #previous_Q[counter,:,:] = np.transpose(F_test)\n #Q = np.transpose(F_test)\n counter = counter +1\n return Q,previous_Q",
"_____no_output_____"
],
[
"Q,previous_Q = generate_orthonormal_matrix_with_leverage_scores_ES(20,2,[],3,[18,15,10])",
"counter\n0\n2.0\n[0.32764, 0.32153, 0.16907, 0.16028, 0.1438, 0.13843, 0.12805, 0.10632, 0.098022, 0.090393, 0.088684, 0.064392, 0.0578, 0.033997, 0.031799, 0.026398, 0.007, 0.0066986, 0.0, 0.0]\n[[ 0.32767245 0.3700502 0.52789205 0.54268118 0.60703057 0.66726853\n 0.73849729 0.77766843 0.83109472 0.8743445 0.90949306 0.93896209\n 0.95815749 0.97402108 0.99351995 0.99471348 0.99999317 1. 1.\n 1. ]\n [ 0. 0.27916541 0.29034942 0.43577911 0.51516418 0.59343683\n 0.6502118 0.71739659 0.76176117 0.80930595 0.86296506 0.89786697\n 0.93626258 0.95420218 0.96637759 0.99154724 0.99322139 1. 1.\n 1. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]]\ncounter\n1\n2.0\n[0.38745, 0.32837, 0.19214, 0.19165, 0.16626, 0.15088, 0.14209, 0.1322, 0.092407, 0.08728, 0.077881, 0.017899, 0.0177, 0.014999, 0.0007, 0.0, 0.0, 0.0, 0.0, 0.0]\n[[ 0.38744452 0.47842014 0.53780069 0.65514809 0.65618587 0.78095882\n 0.78355939 0.90963448 0.9309549 0.96915322 0.97944337 0.99278379\n 0.9997044 0.99991955 1. 1. 1. 1. 1.\n 1. ]\n [ 0. 0.23734303 0.3700988 0.44436081 0.60949878 0.6357621\n 0.77509324 0.78128828 0.85228821 0.90150299 0.969024 0.97381304\n 0.98453977 0.99915845 1. 1. 1. 1. 1.\n 1. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]]\ncounter\n2\n2.0\n[0.64502, 0.39551, 0.31641, 0.24158, 0.23596, 0.053192, 0.035004, 0.031708, 0.029205, 0.016296, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n[[ 0.64502709 0.73823689 0.92150203 0.94621262 0.96221474 0.96531366\n 0.98223498 0.99445032 1.0001653 1. 1. 1. 1.\n 1. 1. 1. 1. 1. 1. 1. ]\n [ 0. 0.30251081 0.43560629 0.65211699 0.87203159 0.9223876\n 0.9404978 0.95969517 0.98350529 1. 1. 1. 1.\n 1. 1. 1. 1. 1. 1. 1. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]]\n"
],
[
"def generate_leverage_scores_vector_with_dirichlet(d,k,nn_cardinal):\n getcontext().prec = 3\n mu_vector = np.float16(np.zeros((d,)))\n mu_vector_2 = np.float16(np.zeros((d,)))\n not_bounded = 1\n while(not_bounded == 1):\n mu_vector[0:nn_cardinal] = (k*np.random.dirichlet([1]*nn_cardinal, 1))[0]\n mu_vector = np.flip(np.sort(mu_vector),axis = 0)\n if max(mu_vector)<=1:\n not_bounded = 0\n for i in range(nn_cardinal):\n mu_vector_2[i] = round(mu_vector[i],4)\n mu_vector_2 = k*mu_vector_2/np.sum(mu_vector_2)\n return list(mu_vector_2)\n",
"_____no_output_____"
],
[
"l = generate_leverage_scores_vector_with_dirichlet(10,2,6)\nprint(l)\nprint(np.sum(l))",
"[0.65674, 0.41479, 0.33838, 0.30518, 0.25195, 0.03299, 0.0, 0.0, 0.0, 0.0]\n2.0\n"
],
[
"def generate_orthonormal_matrix_with_leverage_scores(N,d,lv_scores_vector,versions_number,mode):\n #Transforming an idendity matrix to an orthogonal matrix with prescribed lengths\n Q = np.zeros((N,d))\n previous_Q = np.zeros((versions_number+1,N,d))\n versionning_period = (int)(N/versions_number)\n if mode == 'identity':\n for _ in range(0,d):\n Q[_,_] = 1\n if mode == 'spread':\n nu = 1\n Sigma = np.diag(np.ones(d))\n mean = np.zeros(d)\n x = np.random.chisquare(nu, N)/nu\n z = np.random.multivariate_normal(mean,Sigma,(N,))\n dataset = mean + z/np.sqrt(x)[:,None] \n [Q,_,_] = np.linalg.svd(dataset,full_matrices=False)\n print(np.shape(Q))\n I_sorting = list(reversed(np.argsort(lv_scores_vector)))\n \n lv_scores_vector = np.asarray(list(reversed(np.sort(lv_scores_vector))))\n initial_lv_scores_vector = np.diag(np.dot(Q,Q.T))\n I_initial_sorting = list(reversed(np.argsort(initial_lv_scores_vector)))\n initial_lv_scores_vector = np.asarray(list(reversed(np.sort(np.diag(np.dot(Q,Q.T))))))\n #initial_lv_scores_vector = \n\n Q[I_initial_sorting,:] = Q\n print(lv_scores_vector)\n print(initial_lv_scores_vector)\n delta_lv_scores_vector = lv_scores_vector - initial_lv_scores_vector\n print(delta_lv_scores_vector)\n min_index = next((i for i, x in enumerate(delta_lv_scores_vector) if x>0), None)\n i = min_index-1\n j = min_index\n print(i)\n print(j)\n #if mode == 'identity':\n # i = d-1\n # j = d\n #if mode == 'spread':\n # i = d-2\n # j = d-1\n v_counter =0\n for t in range(N-1):\n #print(i)\n #print(j)\n delta_i = np.abs(lv_scores_vector[i] - np.power(np.linalg.norm(Q[i,:]),2))\n delta_j = np.abs(lv_scores_vector[j] - np.power(np.linalg.norm(Q[j,:]),2))\n q_i = np.power(np.linalg.norm(Q[i,:]),2)\n q_j = np.power(np.linalg.norm(Q[j,:]),2)\n q_ij = np.dot(Q[i,:],Q[j,:].T)\n l_i = lv_scores_vector[i]\n l_j = lv_scores_vector[j]\n G = np.eye(N)\n if t%versionning_period ==0:\n previous_Q[v_counter,:,:] = Q\n v_counter = v_counter +1\n if delta_i <= delta_j:\n l_k = q_i + q_j -l_i\n G = G_func(i,j,q_i,q_j,q_ij,l_i,l_k,N)\n Q = np.dot(G,Q)\n i = i-1\n else:\n l_k = q_i + q_j -l_j\n G = G_func(i,j,q_j,q_i,q_ij,l_j,l_k,N)\n Q = np.dot(G,Q)\n j = j+1\n previous_Q[versions_number,:,:] = Q\n return Q,previous_Q",
"_____no_output_____"
]
],
[
[
"The following function allows to estimate the leverage scores for an orthogonal matrix Q: the function calculates the diagonoal of the matrix $$Q Q^{T}$$",
"_____no_output_____"
]
],
[
[
"def estimate_leverage_scores_from_orthogonal_matrix(Q):\n [N,_] = np.shape(Q)\n lv_scores_vector = np.zeros((N,1))\n lv_scores_vector = np.diag(np.dot(Q,np.transpose(Q)))\n lv_scores_vector = np.asarray(list(reversed(np.sort(lv_scores_vector))))\n return lv_scores_vector\ndef estimate_sum_first_k_leverage_scores(Q,k):\n lv_scores_vector = estimate_leverage_scores_from_orthogonal_matrix(Q)\n res = np.sum(lv_scores_vector[0:k])\n return res",
"_____no_output_____"
]
],
[
[
"## I-2- Extending the orthogonal matrices",
"_____no_output_____"
],
[
"For the task of low rank approximation, we have seen that only the information contained in the first right k eigenvectors of the matrix X are relevant. In the previous step we build only the first right k eigenvectors but we still need to complete these orthogonal matrices with d-k columns. We proceed as following:\nGenerate a random vector (Nx1) using independent standard gaussian variables,\nProject this vector in the orthogonal of the span of Q\nNormalize the obtained vector after the projection\nExtend the matrix Q\nNote that this procedure is not the unique way to extend the matrix Q to an orthogonal (Nxd) matrix.",
"_____no_output_____"
]
],
[
[
"def extend_orthogonal_matrix(Q,d_target):\n [N,d] = np.shape(Q)\n Q_target = np.zeros((N,d))\n Q_target = Q\n delta = d_target - d\n for t in range(delta):\n Q_test = np.random.normal(0, 1, N)\n for _ in range(d):\n Q_test = Q_test - np.dot(Q_test,Q[:,_])*Q[:,_]\n Q_test = Q_test/np.linalg.norm(Q_test)\n Q_test = Q_test.reshape(N,1)\n Q_target = np.append(Q_target,Q_test,1)\n return Q_target\n\n#extended_Q = extend_orthogonal_matrix(Q,r)",
"_____no_output_____"
]
],
[
[
"## I-3 - Constructing a dataset for every extended orthogonal matrix \nThe previous step allow us to build (N x d) orthogonal matrices such that the extracted (N x k) matrix have a prescribed profile of leverage scores.\nNow we construct a cloud of point by assigning a covariance matrix D and a matrix V",
"_____no_output_____"
]
],
[
[
"def contruct_dataset_from_orthogonal_matrix(multi_Q,N,target_d,cov,mean,versions_number):\n multi_X = np.zeros((versions_number+1,N,real_dim))\n for t in range(versions_number+1):\n test_X = np.random.multivariate_normal(mean, cov, N)\n [U,_,_] = np.linalg.svd(test_X, full_matrices=False)\n Q_test = extend_orthogonal_matrix(multi_Q[t,:,:],target_d)\n multi_X[t,:,:] = np.dot(np.dot(Q_test,cov),U.T).T\n return multi_X\n\n",
"_____no_output_____"
]
],
[
[
"## II- Volume sampling vs Projection DPP for low rank approximation\nThese functions allow to quantify the approximation error:\n* approximation_error_function_fro calculate the ratio of the approximation error of a subset of columns to the optimal approximatione error given by the first k left eigenvectors of the matrix X\n* expected_approximation_error_for_sampling_scheme calculate the expected value of the ratio of the approximatione error under some sampling distribution",
"_____no_output_____"
]
],
[
[
"def approximation_error_function_fro(Sigma,k,X,X_S):\n ## Sigma is the spectrum of the matrix X: we need to calculate the optimal approximation error given by the PCA\n ## k is the rank of the approximation\n ## X is the initial matrix\n ## X_S is the subset of columns of the matrix X for witch we calculate the approximation error ratio\n d = list(Sigma.shape)[0] # the dimension of the matrix X\n Sigma = np.multiply(Sigma,Sigma) # Sigma power 2 -> we are intersted in the approximation error square\n sigma_S_temp = np.linalg.inv(np.dot(X_S.T,X_S)) # just a temporary matrix to construct the projection matrix\n projection_S = np.dot(np.dot(X_S,sigma_S_temp),X_S.T) # the projection matrix P_S\n res_X = X - np.dot(projection_S,X) # The projection of the matrix X in the orthogonal of S\n approximation_error_ratio = np.power(np.linalg.norm(res_X,'fro'),2)/np.sum(Sigma[k:d])\n # Calculate the apparoximation error ratio\n return approximation_error_ratio",
"_____no_output_____"
],
[
"def approximation_error_function_spectral(Sigma,k,X,X_S):\n ## Sigma is the spectrum of the matrix X: we need to calculate the optimal approximation error given by the PCA\n ## k is the rank of the approximation\n ## X is the initial matrix\n ## X_S is the subset of columns of the matrix X for witch we calculate the approximation error ratio\n d = list(Sigma.shape)[0] # the dimension of the matrix X\n Sigma = np.multiply(Sigma,Sigma) # Sigma power 2 -> we are intersted in the approximation error square\n sigma_S_temp = np.linalg.inv(np.dot(X_S.T,X_S)) # just a temporary matrix to construct the projection matrix\n projection_S = np.dot(np.dot(X_S,sigma_S_temp),X_S.T) # the projection matrix P_S\n res_X = X - np.dot(projection_S,X) # The projection of the matrix X in the orthogonal of S\n approximation_error_ratio = np.power(np.linalg.norm(res_X,ord = 2),2)/np.sum(Sigma[k:k+1])\n # Calculate the apparoximation error ratio\n return approximation_error_ratio",
"_____no_output_____"
],
[
"def upper_bound_error_function_for_projection_DPP(k,X,X_S):\n ## Sigma is the spectrum of the matrix X: we need to calculate the optimal approximation error given by the PCA\n ## k is the rank of the approximation\n ## X is the initial matrix\n ## X_S is the subset of columns of the matrix X for witch we calculate the approximation error ratio\n _,sigma_S_temp,_ = np.linalg.svd(X_S, full_matrices=False) # just a temporary matrix to construct the projection matrix\n trunc_product = np.power(np.prod(sigma_S_temp[0:k-1]),2)\n if np.power(np.prod(sigma_S_temp[0:k]),2) == 0:\n trunc_product = 0\n # Calculate the apparoximation error ratio\n return trunc_product",
"_____no_output_____"
],
[
"def tight_upper_bound_error_function_fro(k,X,X_S,V_k,V_k_S):\n ## Sigma is the spectrum of the matrix X: we need to calculate the optimal approximation error given by the PCA\n ## k is the rank of the approximation\n ## X is the initial matrix\n ## X_S is the subset of columns of the matrix X for witch we calculate the approximation error ratio\n _,Sigma,_ = np.linalg.svd(X, full_matrices=False)\n d = list(Sigma.shape)[0]\n Sigma = np.multiply(Sigma,Sigma)\n if np.linalg.matrix_rank(V_k_S,0.000001) == k:\n temp_T = np.dot(np.linalg.inv(V_k_S),V_k)\n temp_matrix = X - np.dot(X_S,temp_T)\n \n return np.power(np.linalg.norm(temp_matrix,'fro'),2)/np.sum(Sigma[k:d])\n else:\n return 0",
"_____no_output_____"
],
[
"def get_the_matrix_sum_T_S(k,d,V_k,V_d_k):\n ## Sigma is the spectrum of the matrix X: we need to calculate the optimal approximation error given by the PCA\n ## k is the rank of the approximation\n ## X is the initial matrix\n ## X_S is the subset of columns of the matrix X for witch we calculate the approximation error ratio\n #Sigma = np.multiply(Sigma,Sigma)\n #matrices_array = [ np.dot(V_d_k[:,list(comb)],np.dot(np.dot(np.linalg.inv(V_k[:,list(comb)]),np.linalg.inv(V_k[:,list(comb)]))),np.transpose(V_d_k[:,list(comb)])) for comb in combinations(range(d),k) if np.linalg.matrix_rank(V_k[:,list(comb)],0.000001) == k]\n T = np.zeros((d-k,d-k))\n for comb in combinations(range(d),k):\n if np.linalg.matrix_rank(V_k[:,list(comb)],0.0000000001) == k: \n V_k_S_inv = np.linalg.inv(V_k[:,list(comb)])\n V_d_k_S = V_d_k[:,list(comb)]\n V_k_S_inv_2 = np.transpose(np.dot(V_k_S_inv,np.transpose(V_k_S_inv)))\n #T = np.dot(np.dot(np.dot(V_d_k_S,np.dot(V_k_S_inv,np.transpose(V_k_S_inv)))),np.transpose(V_d_k_S)) + T\n T = np.power(np.linalg.det(V_k[:,list(comb)]),2)*np.dot(V_d_k_S,np.dot(V_k_S_inv_2,np.transpose(V_d_k_S))) +T\n return T",
"_____no_output_____"
],
[
"def tight_approximation_error_fro_for_sampling_scheme(X,U,k,N):\n ## X is the matrix X :)\n ## U is the matrix used in the sampling: we sample propotional to the volume of UU^{T}_{S,S}: \n ## we are not sampling but we need the weigth to estimate the expected error\n ## k is the rank of the approximation\n ## N is the number of columns (to be changed to avoid confusion with the number of points)\n _,Sigma,V = np.linalg.svd(X, full_matrices=False)\n V_k = V[0:k,:]\n ## Estimating the spectrum of X -> needed in approximation_error_function_fro\n volumes_array = [np.abs(np.linalg.det(np.dot(U[:,list(comb)].T,U[:,list(comb)]))) for comb in combinations(range(N),k)]\n ## Construct the array of weights: the volumes of UU^{T}_{S,S}\n volumes_array_sum = np.sum(volumes_array)\n ## The normalization constant\n volumes_array = volumes_array/volumes_array_sum\n ## The weigths normalized\n approximation_error_array = [tight_upper_bound_error_function_fro(k,X,X[:,list(comb)],V_k,V_k[:,list(comb)]) for comb in combinations(range(N),k)]\n ## Calculating the approximation error for every k-tuple\n expected_value = np.dot(approximation_error_array,volumes_array)\n ## The expected value of the approximatione error is just the dot product of the two arrays above\n return expected_value",
"_____no_output_____"
],
[
"def expected_approximation_error_fro_for_sampling_scheme(X,U,k,N):\n ## X is the matrix X :)\n ## U is the matrix used in the sampling: we sample propotional to the volume of UU^{T}_{S,S}: \n ## we are not sampling but we need the weigth to estimate the expected error\n ## k is the rank of the approximation\n ## N is the number of columns (to be changed to avoid confusion with the number of points)\n _,Sigma,_ = np.linalg.svd(X, full_matrices=False)\n ## Estimating the spectrum of X -> needed in approximation_error_function_fro\n volumes_array = [np.abs(np.linalg.det(np.dot(U[:,list(comb)].T,U[:,list(comb)]))) for comb in combinations(range(N),k)]\n ## Construct the array of weights: the volumes of UU^{T}_{S,S}\n volumes_array_sum = np.sum(volumes_array)\n ## The normalization constant\n volumes_array = volumes_array/volumes_array_sum\n ## The weigths normalized\n approximation_error_array = [approximation_error_function_fro(Sigma,k,X,X[:,list(comb)]) for comb in combinations(range(N),k)]\n ## Calculating the approximation error for every k-tuple\n expected_value = np.dot(approximation_error_array,volumes_array)\n ## The expected value of the approximatione error is just the dot product of the two arrays above\n return expected_value",
"_____no_output_____"
],
[
"def expected_approximation_error_spectral_for_sampling_scheme(X,U,k,N):\n ## X is the matrix X :)\n ## U is the matrix used in the sampling: we sample propotional to the volume of UU^{T}_{S,S}: \n ## we are not sampling but we need the weigth to estimate the expected error\n ## k is the rank of the approximation\n ## N is the number of columns (to be changed to avoid confusion with the number of points)\n _,Sigma,_ = np.linalg.svd(X, full_matrices=False)\n ## Estimating the spectrum of X -> needed in approximation_error_function_fro\n volumes_array = [np.abs(np.linalg.det(np.dot(U[:,list(comb)].T,U[:,list(comb)]))) for comb in combinations(range(N),k)]\n ## Construct the array of weights: the volumes of UU^{T}_{S,S}\n volumes_array_sum = np.sum(volumes_array)\n ## The normalization constant\n volumes_array = volumes_array/volumes_array_sum\n ## The weigths normalized\n approximation_error_array = [approximation_error_function_spectral(Sigma,k,X,X[:,list(comb)]) for comb in combinations(range(N),k)]\n ## Calculating the approximation error for every k-tuple\n expected_value = np.dot(approximation_error_array,volumes_array)\n ## The expected value of the approximatione error is just the dot product of the two arrays above\n return expected_value",
"_____no_output_____"
],
[
"def expected_upper_bound_for_projection_DPP(X,U,k,N):\n ## X is the matrix X :)\n ## U is the matrix used in the sampling: we sample propotional to the volume of UU^{T}_{S,S}: \n ## we are not sampling but we need the weigth to estimate the expected error\n ## k is the rank of the approximation\n ## N is the number of columns (to be changed to avoid confusion with the number of points)\n\n approximation_error_array = [upper_bound_error_function_for_projection_DPP(k,X,U[:,list(comb)]) for comb in combinations(range(N),k)]\n ## Calculating the approximation error for every k-tuple\n \n ## The expected value of the approximatione error is just the dot product of the two arrays above\n #return expected_value\n return np.sum(approximation_error_array)",
"_____no_output_____"
]
],
[
[
"## III - Numerical analysis",
"_____no_output_____"
],
[
"In this section we use the functions developed previously to investigate the influence of two parameters: the spectrum of X and the k-leverage scores. \nFor this purpose, we assemble these functionalities in a class allowing fast numerical experiments.",
"_____no_output_____"
]
],
[
[
"class Numrerical_Analysis_DPP: \n def __init__(self,N,real_dim,r,k,versions_number,mean,cov,lv_scores,versions_list):\n self.N = N\n self.real_dim = real_dim\n self.r = r\n self.k = k\n self.versions_number = versions_number\n self.mean = mean\n self.cov = cov\n self.lv_scores = lv_scores\n self.Q = np.zeros((real_dim,k))\n self.multi_Q = np.zeros((self.versions_number+1,real_dim,k))\n self.X = np.zeros((N,real_dim))\n self.multi_X = np.zeros((self.versions_number+1,N,real_dim))\n #[self.Q,self.multi_Q] = generate_orthonormal_matrix_with_leverage_scores(real_dim,k,lv_scores,versions_number,'identity')\n [self.Q,self.multi_Q] = generate_orthonormal_matrix_with_leverage_scores_ES(self.real_dim,self.k,[],self.versions_number+1,versions_list)\n self.multi_X = contruct_dataset_from_orthogonal_matrix(self.multi_Q,self.N,self.real_dim,self.cov,self.mean,self.versions_number)\n def contruct_dataset_from_orthogonal_matrix_4(self,multi_Q,N,target_d,cov,mean,versions_number):\n test_multi_X = np.zeros((self.versions_number+1,N,real_dim))\n for t in range(self.versions_number+1):\n test_X = np.random.multivariate_normal(mean, cov, N)\n [U,_,_] = np.linalg.svd(test_X, full_matrices=False)\n Q_test = extend_orthogonal_matrix(self.multi_Q[t,:,:],target_d)\n test_multi_X[t,:,:] = np.dot(np.dot(Q_test,cov),U.T).T\n return test_multi_X\n def get_effective_kernel_from_orthogonal_matrix(self):\n test_eff_V = np.zeros((self.versions_number+1,self.real_dim,self.k))\n p_eff_list = self.get_p_eff()\n for t in range(self.versions_number+1):\n test_V = self.multi_Q[t,:,:]\n p_eff = p_eff_list[t]\n diag_Q_t = np.diag(np.dot(test_V,test_V.T))\n #diag_Q_t = list(diag_Q_t[::-1].sort())\n print(diag_Q_t)\n permutation_t = list(reversed(np.argsort(diag_Q_t)))\n print(permutation_t)\n for i in range(self.real_dim):\n if i >p_eff-1:\n test_V[permutation_t[i],:] = 0 \n #Q_test = extend_orthogonal_matrix(self.multi_Q[t,:,:],target_d)\n test_eff_V[t,:,:] = test_V\n return test_eff_V\n def get_expected_error_fro_for_volume_sampling(self):\n ## Calculate the expected error ratio for the Volume Sampling distribution for every dataset\n res_list = np.zeros(self.versions_number+1)\n for t in range(self.versions_number+1):\n test_X = self.multi_X[t,:,:]\n res_list[t] = expected_approximation_error_fro_for_sampling_scheme(test_X,test_X,self.k,self.real_dim)\n return res_list\n def get_expected_error_fro_for_effective_kernel_sampling(self):\n ## Calculate the expected error ratio for the Volume Sampling distribution for every dataset\n res_list = np.zeros(self.versions_number+1)\n test_eff_V = self.get_effective_kernel_from_orthogonal_matrix()\n for t in range(self.versions_number+1):\n test_X = self.multi_X[t,:,:]\n test_U = test_eff_V[t,:,:].T\n res_list[t] = expected_approximation_error_fro_for_sampling_scheme(test_X,test_U,self.k,self.real_dim)\n return res_list\n def get_tight_upper_bound_error_fro_for_projection_DPP(self):\n res_list = np.zeros(self.versions_number+1)\n for t in range(self.versions_number+1):\n test_X = self.multi_X[t,:,:]\n test_U = self.multi_Q[t,:,:].T\n res_list[t] = tight_approximation_error_fro_for_sampling_scheme(test_X,test_U,self.k,self.real_dim)\n return res_list\n def get_max_diag_sum_T_matrices(self):\n res_list = np.zeros((self.versions_number+1))\n for t in range(self.versions_number+1):\n test_X = self.multi_X[t,:,:]\n _,_,test_V = np.linalg.svd(test_X, full_matrices=False)\n test_V_k = test_V[0:self.k,:]\n test_V_d_k = test_V[self.k:self.real_dim,:]\n res_list[t] = 1+np.max(np.diag(get_the_matrix_sum_T_S(self.k,self.real_dim,test_V_k,test_V_d_k)))\n return res_list\n def get_max_spectrum_sum_T_matrices(self):\n res_list = np.zeros((self.versions_number+1))\n for t in range(self.versions_number+1):\n test_X = self.multi_X[t,:,:]\n _,_,test_V = np.linalg.svd(test_X, full_matrices=False)\n test_V_k = test_V[0:self.k,:]\n test_V_d_k = test_V[self.k:self.real_dim,:]\n res_list[t] = 1+np.max(np.diag(get_the_matrix_sum_T_S(self.k,self.real_dim,test_V_k,test_V_d_k)))\n return res_list\n def get_expected_error_fro_for_projection_DPP(self):\n ## Calculate the expected error ratio for the Projection DPP distribution for every dataset\n res_list = np.zeros(self.versions_number+1)\n for t in range(self.versions_number+1):\n test_X = self.multi_X[t,:,:]\n test_U = self.multi_Q[t,:,:].T\n res_list[t] = expected_approximation_error_fro_for_sampling_scheme(test_X,test_U,self.k,self.real_dim)\n return res_list \n def get_expected_error_spectral_for_volume_sampling(self):\n ## Calculate the expected error ratio for the Volume Sampling distribution for every dataset\n res_list = np.zeros(self.versions_number+1)\n for t in range(self.versions_number+1):\n test_X = self.multi_X[t,:,:]\n res_list[t] = expected_approximation_error_spectral_for_sampling_scheme(test_X,test_X,self.k,self.real_dim)\n return res_list\n def get_expected_error_spectral_for_projection_DPP(self):\n ## Calculate the expected error ratio for the Projection DPP distribution for every dataset\n res_list = np.zeros(self.versions_number+1)\n for t in range(self.versions_number+1):\n test_X = self.multi_X[t,:,:]\n test_U = self.multi_Q[t,:,:].T\n res_list[t] = expected_approximation_error_spectral_for_sampling_scheme(test_X,test_U,self.k,self.real_dim)\n return res_list \n def get_upper_bound_error_for_projection_DPP(self):\n ## Calculate the expected error ratio for the Projection DPP distribution for every dataset\n #res_list = np.zeros(self.versions_number+1)\n res_list = []\n for t in range(self.versions_number+1):\n test_X = self.multi_X[t,:,:]\n test_U = self.multi_Q[t,:,:].T\n #res_list[t] = expected_upper_bound_for_projection_DPP(test_X,test_U,self.k,self.real_dim)\n res_list.append( expected_upper_bound_for_projection_DPP(test_X,test_U,self.k,self.real_dim))\n return res_list \n def get_error_fro_for_deterministic_selection(self):\n ## Calculate the error ratio for the k-tuple selected by the deterministic algorithm for every dataset\n res_list = np.zeros(self.versions_number+1)\n for t in range(self.versions_number+1):\n test_X = self.multi_X[t,:,:]\n test_U = self.multi_Q[t,:,:].T\n lv_scores_vector = np.diag(np.dot(np.transpose(test_U),test_U))\n test_I_k = list(np.argsort(lv_scores_vector)[self.real_dim-self.k:self.real_dim])\n _,test_Sigma,_ = np.linalg.svd(test_X, full_matrices=False)\n res_list[t] = approximation_error_function_fro(test_Sigma,self.k,test_X,test_X[:,test_I_k])\n #res_list.append(test_I_k)\n return res_list \n def get_error_spectral_for_deterministic_selection(self):\n ## Calculate the error ratio for the k-tuple selected by the deterministic algorithm for every dataset\n res_list = np.zeros(self.versions_number+1)\n for t in range(self.versions_number+1):\n test_X = self.multi_X[t,:,:]\n test_U = self.multi_Q[t,:,:].T\n lv_scores_vector = np.diag(np.dot(np.transpose(test_U),test_U))\n test_I_k = list(np.argsort(lv_scores_vector)[self.real_dim-self.k:self.real_dim])\n _,test_Sigma,_ = np.linalg.svd(test_X, full_matrices=False)\n res_list[t] = approximation_error_function_spectral(test_Sigma,self.k,test_X,test_X[:,test_I_k])\n #res_list.append(test_I_k)\n return res_list \n def get_p_eff(self):\n ## A function that calculate the p_eff.\n ## It is a measure of the concentration of V_k. This is done for every dataset\n res_list = np.zeros(self.versions_number+1)\n for t in range(self.versions_number+1):\n diag_Q_t = np.diag(np.dot(self.multi_Q[t,:,:],self.multi_Q[t,:,:].T))\n #diag_Q_t = list(diag_Q_t[::-1].sort())\n diag_Q_t = list(np.sort(diag_Q_t)[::-1])\n p = self.real_dim\n print(diag_Q_t)\n while np.sum(diag_Q_t[0:p-1]) > float(self.k-1.0/2):\n p = p-1\n res_list[t] = p\n return res_list\n def get_sum_k_leverage_scores(self):\n ## A function that calculate the k-sum: the sum of the first k k-leverage scores. It is a measure of the concentration of V_k\n ## This is done for every dataset\n res_list = np.zeros(self.versions_number+1)\n for t in range(self.versions_number+1):\n res_list[t] = estimate_sum_first_k_leverage_scores(self.multi_Q[t,:,:],self.k)\n return res_list\n def get_deterministic_upper_bound(self):\n ## A function that calculate the theoretical upper bound for the deterministic algorithm for every dataset\n res_list = np.zeros(self.versions_number+1)\n for t in range(self.versions_number+1):\n res_list[t] = 1/(1+estimate_sum_first_k_leverage_scores(self.multi_Q[t,:,:],self.k)-self.k)\n return res_list\n def get_alpha_sum_k_leverage_scores(self,alpha):\n ## A function that calculate the theoretical upper bound for the deterministic algorithm for every dataset\n res_list = np.zeros(self.versions_number+1)\n #k_l = self.get_sum_k_leverage_scores()\n for t in range(self.versions_number+1):\n k_l = estimate_leverage_scores_from_orthogonal_matrix(self.multi_Q[t,:,:])[0:k]\n func_k = np.power(np.linspace(1, k, num=k),alpha)\n res_list[t] = np.dot(func_k,k_l)\n return res_list",
"_____no_output_____"
]
],
[
[
"### III- 0 Parameters of the simultations",
"_____no_output_____"
]
],
[
[
"## The dimensions of the design matrix X\nN = 100 # The number of observations in the dataset\nreal_dim = 20 # The dimension of the dataset\n## The low rank paramters\nk = 2 # The rank of the low rank approximation \n## The covariance matrix parameters\nr = 6 # Just a parameter to control the number of non trivial singular values in the covariance matrix\nmean = np.zeros((real_dim)) # The mean vector useful to generate U (X = UDV^T)\ncov_test = 0.01*np.ones((real_dim-r)) # The \"trivial\" singular values in the covariance matrix (there are real_dim-r)\n## The paramters of the matrix V\nversions_number = 3 # The number of orthogonal matrices (and therefor datasets) (-1) generated by the algorithm above\nlv_scores_vector = k/real_dim*np.ones(real_dim) # The vector of leverage scores (the last one)",
"_____no_output_____"
],
[
"l = [1,5,2,10]\nll = list(reversed(np.argsort(l)))",
"_____no_output_____"
],
[
"ll",
"_____no_output_____"
]
],
[
[
"### III-1 The influence of the spectrum",
"_____no_output_____"
],
[
"In this subsection we compare the Volume Sampling distribution to the projection DPP distribution and the deterministic algorithm of [] for different profiles of the spectrum with k-leverage scores profile fixed. In other words, if we note $$X = UDV^{T}$$ We keep V_{k} constant and we investigate the effect of D.",
"_____no_output_____"
],
[
"#### III-1-1 The case of a non-projection spectrum\nWe mean by a projection spectrum matrix, a matrix with equal the first k singular values.\nWe observe that the two distributions are very similar.... \\todo{reword}",
"_____no_output_____"
]
],
[
[
"cov_1 = np.diag(np.concatenate(([100,100,1,1,1,1],cov_test)))\nversions_list = [20,19,18,17]\nNAL_1 = Numrerical_Analysis_DPP(N,real_dim,r,k,versions_number,mean,cov_1,lv_scores_vector,versions_list)\n\n\nprojection_DPP_res_fro_1 = NAL_1.get_expected_error_fro_for_projection_DPP()\nvolume_sampling_res_fro_1 = NAL_1.get_expected_error_fro_for_volume_sampling()\ndeterministic_selection_res_fro_1 = NAL_1.get_error_fro_for_deterministic_selection()\nprojection_DPP_res_spectral_1 = NAL_1.get_expected_error_spectral_for_projection_DPP()\nvolume_sampling_res_spectral_1 = NAL_1.get_expected_error_spectral_for_volume_sampling()\ndeterministic_selection_res_spectral_1 = NAL_1.get_error_spectral_for_deterministic_selection()\neffective_kernel_sampling_res_fro_1 = NAL_1.get_expected_error_fro_for_effective_kernel_sampling()\n\n\n#sss = NAL_1.get_effective_kernel_from_orthogonal_matrix()\n#p_eff_res_1 = NAL_1.get_p_eff()\n\n\nupper_tight_bound_projection_DPP_res_fro_1 = NAL_1.get_tight_upper_bound_error_fro_for_projection_DPP()\n\nalpha_sum_res_1 = NAL_1.get_alpha_sum_k_leverage_scores(1)\n\n\nsum_U_res_1 = NAL_1.get_sum_k_leverage_scores()\ndeterministic_upper_bound_res_1 = NAL_1.get_deterministic_upper_bound()\n\nexpected_upper_bound_res_1 = NAL_1.get_upper_bound_error_for_projection_DPP()\nmulti_Q_1 = NAL_1.multi_Q[1,:,:].T\n",
"counter\n0\n2.0\n[0.35767, 0.2356, 0.22803, 0.1825, 0.11902, 0.11578, 0.11469, 0.10797, 0.084717, 0.081909, 0.073425, 0.069092, 0.064392, 0.033386, 0.028198, 0.027405, 0.027206, 0.0233, 0.015503, 0.010399]\ncounter\n1\n2.0\n[0.39722, 0.2666, 0.26074, 0.19592, 0.18884, 0.087891, 0.077515, 0.076111, 0.075623, 0.06897, 0.065918, 0.056885, 0.056793, 0.03479, 0.027206, 0.019608, 0.015404, 0.014297, 0.013702, 0.0]\ncounter\n2\n2.0\n[0.30811, 0.2428, 0.21558, 0.19116, 0.1665, 0.11578, 0.1156, 0.1004, 0.087891, 0.080383, 0.078918, 0.071716, 0.061005, 0.051788, 0.051392, 0.0354, 0.018494, 0.0073013, 0.0, 0.0]\ncounter\n3\n2.0\n[0.41357, 0.36157, 0.17798, 0.1604, 0.15686, 0.14661, 0.10059, 0.07959, 0.076599, 0.074585, 0.069214, 0.052612, 0.032806, 0.032593, 0.031204, 0.022202, 0.011002, 0.0, 0.0, 0.0]\n[0.35777688026428223, 0.23560344846304779, 0.22806371259223471, 0.18255712899271787, 0.11900794670561936, 0.11568677300530091, 0.11476263689791259, 0.10777084186787721, 0.084861728770511319, 0.081967536928561888, 0.073448336217099869, 0.069097723206169998, 0.064390613100475599, 0.033330586092320313, 0.028234252443261599, 0.027369456022050979, 0.027157949171869269, 0.023251832128326343, 0.015405204729490913, 0.010364199016915527]\n[0.39736771583557129, 0.26664229681671597, 0.26072914064963071, 0.19586754570544651, 0.18898419362053762, 0.087822556525339532, 0.077348376281795264, 0.076264117114580934, 0.075689501901983994, 0.068922982710907174, 0.066088051649501336, 0.056825979254394067, 0.056824325235779481, 0.034826121032323423, 0.027234862252278693, 0.019550907116733816, 0.014896496977231733, 0.014455927041064151, 0.013700896349698524, 0.0]\n[0.30822014808654785, 0.24278500796682609, 0.21565109368410726, 0.19105632200162725, 0.16655734427974439, 0.11591341067637717, 0.11556110747004687, 0.10042337024137872, 0.087865207190519559, 0.080251032112411413, 0.079005482615102485, 0.071770978962218943, 0.061071742280536245, 0.051816396826393572, 0.051440847198793362, 0.035266111773377795, 0.018421231645940662, 0.0070718982061277452, 0.0, 0.0]\n[0.41353440284729004, 0.36173493034944848, 0.17776079952536425, 0.16039998190684215, 0.15696485196624904, 0.14654729194664731, 0.10080900324316089, 0.079611251539356484, 0.076364104972679869, 0.074347356934501729, 0.069224585634353145, 0.052798337801564392, 0.033010513017684769, 0.032357706838145539, 0.031246401365466962, 0.022231815988071765, 0.010967017038168816, 0.0, 0.0, 0.0]\n[ 0.35777688 0.23560345 0.22806371 0.18255713 0.11900795 0.11568677\n 0.11476264 0.10777084 0.08486173 0.08196754 0.07344834 0.06909772\n 0.06439061 0.03333059 0.02823425 0.02736946 0.02715795 0.02325183\n 0.0154052 0.0103642 ]\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]\n[ 0.39736772 0.2666423 0.26072914 0.19586755 0.18898419 0.08782256\n 0.07734838 0.07626412 0.0756895 0.06892298 0.06608805 0.05682598\n 0.05682433 0.03482612 0.02723486 0.01955091 0.0148965 0.01445593\n 0.0137009 0. ]\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]\n[ 0.30822015 0.24278501 0.21565109 0.19105632 0.16655734 0.11591341\n 0.11556111 0.10042337 0.08786521 0.08025103 0.07900548 0.07177098\n 0.06107174 0.0518164 0.05144085 0.03526611 0.01842123 0.0070719 0.\n 0. ]\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]\n[ 0.4135344 0.36173493 0.1777608 0.16039998 0.15696485 0.14654729\n 0.100809 0.07961125 0.0763641 0.07434736 0.06922459 0.05279834\n 0.03301051 0.03235771 0.0312464 0.02223182 0.01096702 0. 0.\n 0. ]\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 17, 19]\n"
],
[
"p_eff_res_1 = NAL_1.get_p_eff()\neff_kernel_upper_bound_1 = 1+ (p_eff_res_1-k)/(real_dim-k)*(k+1)",
"[0.35777688026428223, 0.23560344846304779, 0.22806371259223471, 0.18255712899271787, 0.11900794670561936, 0.11568677300530091, 0.11476263689791259, 0.10777084186787721, 0.084861728770511319, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n[0.39736771583557129, 0.26664229681671597, 0.26072914064963071, 0.19586754570544651, 0.18898419362053762, 0.087822556525339532, 0.077348376281795264, 0.076264117114580934, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n[0.30822014808654785, 0.24278500796682609, 0.21565109368410726, 0.19105632200162725, 0.16655734427974439, 0.11591341067637717, 0.11556110747004687, 0.10042337024137872, 0.087865207190519559, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n[0.41353440284729004, 0.36173493034944848, 0.17776079952536425, 0.16039998190684215, 0.15696485196624904, 0.14654729194664731, 0.10080900324316089, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n"
],
[
"eff_kernel_upper_bound",
"_____no_output_____"
],
[
"\nprint(k*(real_dim-k+1))\nsum_T_matrices = NAL_1.get_sum_T_matrices()",
"38\n"
],
[
"pd_1 = pd.DataFrame(\n {'k-sum (ratio)': sum_U_res_1/k,\n 'p_eff':p_eff_res_1,\n 'alpha k-sum': alpha_sum_res_1,\n 'Expected Upper Bound for Projection DPP': expected_upper_bound_res_1,\n 'Volume Sampling(Fro)': volume_sampling_res_fro_1,\n 'Projection DPP(Fro)': projection_DPP_res_fro_1,\n 'Effective kernel(Fro)' : effective_kernel_sampling_res_fro_1,\n 'Effective kernel upper bound (Fro)':eff_kernel_upper_bound_1,\n 'Very sharp approximation of Projection DPP(Fro)': upper_tight_bound_projection_DPP_res_fro_1,\n 'Deterministic Algorithm(Fro)': deterministic_selection_res_fro_1,\n 'Volume Sampling(Spectral)': volume_sampling_res_spectral_1,\n 'Projection DPP(Spectral)': projection_DPP_res_spectral_1,\n 'Deterministic Algorithm(Spectral)': deterministic_selection_res_spectral_1,\n 'Deterministic Upper Bound': deterministic_upper_bound_res_1\n })\npd_1 = pd_1[['k-sum (ratio)','p_eff', 'alpha k-sum','Expected Upper Bound for Projection DPP','Volume Sampling(Fro)','Projection DPP(Fro)','Effective kernel(Fro)','Effective kernel upper bound (Fro)','Very sharp approximation of Projection DPP(Fro)','Deterministic Algorithm(Fro)','Volume Sampling(Spectral)','Projection DPP(Spectral)','Deterministic Algorithm(Spectral)','Deterministic Upper Bound']]",
"_____no_output_____"
],
[
"p_eff_res_1[3]",
"_____no_output_____"
],
[
"#'1+Largest eigenvalue of sum_T': sum_T_matrices,",
"_____no_output_____"
],
[
"pd_1",
"_____no_output_____"
]
],
[
[
"#### Observations:\n* The expected error is always smaller under the Projection DPP distribution compared to the Volume Sampling distribution.\n* The expected error for the Volume Sampling distribution is constant for a contant D\n* However the expected error for the Projection DPP distribution depends on the k-sum\n* For X_0 and X_1, the profile of the k-leverage scores are highly concentrated (k-sum > k-1) thus epsilon is smaller than 1, in this regime the determinstic algorithm have the lower approximation error and it performs better than expected (the theoretical bound is 1/(1-epsilon).\n* However, for the other datasets, the (k-sum < k-1) thus epsilon >1 and the deterministic algorithm have no guarantee in this regime: we observe that the approximation error for the deterministic algorithm can be very high in this regime.",
"_____no_output_____"
],
[
"#### Recall:\nWe recall here some geometrical properties of the matrices $$X_i$$\n$$X_i = UD_{j}V_{i}$$\nWhere for every i, the first k columns of $$V_{i}$$ are the $$Q_{i}$$ while the other columns are gernerated randomly",
"_____no_output_____"
]
],
[
[
"previous_Q = NAL_1.multi_Q\nlv_0 = estimate_leverage_scores_from_orthogonal_matrix(previous_Q[0,:,:])\nlv_1 = estimate_leverage_scores_from_orthogonal_matrix(previous_Q[1,:,:])\nlv_2 = estimate_leverage_scores_from_orthogonal_matrix(previous_Q[2,:,:])\nlv_3 = estimate_leverage_scores_from_orthogonal_matrix(previous_Q[3,:,:])\nlv_4 = estimate_leverage_scores_from_orthogonal_matrix(previous_Q[4,:,:])\nlv_5 = estimate_leverage_scores_from_orthogonal_matrix(previous_Q[5,:,:])\nindex_list = list(range(real_dim))",
"_____no_output_____"
]
],
[
[
"In this example the objective is Q and the initialization is Q_0 (the rectangular identity)\nWe have with respect to the Schur-order (or the majorization):\n$$Q = Q_5 \\prec_{S} Q_4 \\prec_{S} Q_3 \\prec_{S} Q_2 \\prec_{S} Q_1 \\prec_{S} Q_0 $$",
"_____no_output_____"
]
],
[
[
"plt.plot(index_list[0:10], lv_0[0:10], 'c--',index_list[0:10], lv_1[0:10], 'k--', index_list[0:10], lv_2[0:10], 'r--', index_list[0:10], lv_3[0:10], 'b--',index_list[0:10], lv_4[0:10], 'g--',index_list[0:10], lv_5[0:10], 'y--')\nplt.xlabel('index')\nplt.ylabel('leverage score')\ncyan_patch = mpatches.Patch(color='cyan', label='Q_0')\nblack_patch = mpatches.Patch(color='black', label='Q_1')\nred_patch = mpatches.Patch(color='red', label='Q_2')\nblue_patch = mpatches.Patch(color='blue', label='Q_3')\ngreen_patch = mpatches.Patch(color='green', label='Q_4')\nyellow_patch = mpatches.Patch(color='yellow', label='Q = Q_5')\nplt.legend(handles=[cyan_patch,black_patch,red_patch,blue_patch,green_patch,yellow_patch])\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"#### III-1-2 The case of a projection spectrum\nWe mean by a projection spectrum matrix, a matrix with equal the first k singular values.\nWe observe that the two distributions are very similar.... \\todo{reword}",
"_____no_output_____"
]
],
[
[
"cov_2 = np.diag(np.concatenate(([1000,1000,1000,1,0.1],cov_test)))\nNAL_2 = Numrerical_Analysis_DPP(N,real_dim,r,k,versions_number,mean,cov_2,lv_scores_vector)\nprojection_DPP_res_2 = NAL_2.get_expected_error_for_projection_DPP()\nvolume_sampling_res_2 = NAL_2.get_expected_error_for_volume_sampling()\ndeterministic_selection_res_2 = NAL_1.get_error_for_deterministic_selection()\nsum_U_res_2 = NAL_2.get_sum_k_leverage_scores()\ndeterministic_upper_bound_res_2 = NAL_2.get_deterministic_upper_bound()\n\nresults = [[\"Dataset\",\"Using Volume Sampling\",\"Using Projection DPP\",\"k-sum\",\"1/(1-epsilon)\",\"Using Deterministic Algorithm\"],[\"X_0\",volume_sampling_res_2[0],projection_DPP_res_2[0],sum_U_res_2[0],deterministic_upper_bound_res_2[0],deterministic_selection_res_2[0]],[\"X_1\",volume_sampling_res_2[1],projection_DPP_res_2[1],sum_U_res_2[1],deterministic_upper_bound_res_2[1],deterministic_selection_res_2[1]],\n [\"X_2\",volume_sampling_res_2[2],projection_DPP_res_2[2],sum_U_res_2[2],deterministic_upper_bound_res_2[2],deterministic_selection_res_2[2]],[\"X_3\",volume_sampling_res_2[3],projection_DPP_res_2[3],sum_U_res_2[3],deterministic_upper_bound_res_2[3],deterministic_selection_res_2[3]],[\"X_4\",volume_sampling_res_2[4],projection_DPP_res_2[4],sum_U_res_2[4],deterministic_upper_bound_res_2[4],deterministic_selection_res_2[4]],[\"X_5\",volume_sampling_res_2[5],projection_DPP_res_2[5],sum_U_res_2[5],deterministic_upper_bound_res_2[5],deterministic_selection_res_2[5]]] \ndisplay(HTML(\n '<center><b>The expected approximation error (divided by the optimal error) according to a sampling scheme for different distribution</b><br><table><tr>{}</tr></table>'.format(\n '</tr><tr>'.join(\n '<td>{}</td>'.format('</td><td>'.join(str(_) for _ in row)) for row in results)\n )\n ))",
"[ 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3\n 0.3 0.3 0.3 0.3 0.3]\n[ 1. 1. 1. 1. 1. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0.]\n[-0.7 -0.7 -0.7 -0.7 -0.7 -0.7 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3\n 0.3 0.3 0.3 0.3 0.3]\n5\n6\n"
]
],
[
[
"### III-2 The influence of the \"spread\" of V\nIn this section we investigate the influence of the \"spread\" (to be defined formally) of the cloud of points. We can change this \"spread\" by changing the initialization of the generator of orthogonal matrices: we replace the rectangular identity by \"other\" orthogonal matrices. \nTechnically, this boils down to change the generator mode in the constructor call from \"nonspread\" to \"spread\".",
"_____no_output_____"
]
],
[
[
"np.power(np.linspace(1, k, num=k),2)",
"_____no_output_____"
],
[
"matrices_array = [ np.zeros((4,4)) for comb in combinations(range(5),4)]\n\n",
"_____no_output_____"
],
[
"matrix_sum = np.sum(matrices_array)",
"_____no_output_____"
],
[
"matrix_sum",
"_____no_output_____"
],
[
"matrices_array",
"_____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",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
d0834eca1af97ebcf9d33ba9109e32d287847cd5 | 166,598 | ipynb | Jupyter Notebook | documentation/20.08_MakeMaps/Permit_application_plot.ipynb | SLYpma/GalapagosAnalysis | a628cab2290527cbf9e89df886c33f2ba705784e | [
"MIT"
] | null | null | null | documentation/20.08_MakeMaps/Permit_application_plot.ipynb | SLYpma/GalapagosAnalysis | a628cab2290527cbf9e89df886c33f2ba705784e | [
"MIT"
] | null | null | null | documentation/20.08_MakeMaps/Permit_application_plot.ipynb | SLYpma/GalapagosAnalysis | a628cab2290527cbf9e89df886c33f2ba705784e | [
"MIT"
] | null | null | null | 1,141.082192 | 162,452 | 0.958145 | [
[
[
"%pylab inline\nfrom parcels import FieldSet, Field, ParticleSet, JITParticle, AdvectionRK4, ErrorCode, Variable\nimport cartopy\nfrom glob import glob\nimport matplotlib.pyplot as plt\nfrom matplotlib import colors, cm\nimport numpy as np\nimport xarray as xr\nfrom netCDF4 import Dataset\nimport math as math\nimport matplotlib.animation as animation\nsys.path.insert(1, '../../functions/')\nfrom ParticlePlotFunctions import *\n%matplotlib inline",
"Populating the interactive namespace from numpy and matplotlib\n"
],
[
"# Load particle data\nnamefile = '../../input/particles/Unbeaching_200810_UnBeachingVel.nc'\nTraj = ReadTrajectories(namefile)\nrelease_time = 293 #number of releases at specific location \nrelease_loc = 675 #number of release locations\ntotal_particles = Traj['lon'].shape[0]\ndistance_from_coast = 10 #in km",
"_____no_output_____"
],
[
"# Produce probability if no Stokes and no wind \nstartlon = Traj['lon'][0:release_loc,0]\nstartlat = Traj['lat'][0:release_loc,0]\ndistance = Traj['distance'][:]\nbeaching_probability = np.zeros((startlon.shape))\n\nfor p in range(total_particles):\n index_loc = p%release_loc\n beached = np.where((distance[p,:] < distance_from_coast) & (distance[p,:] != 0))[0]\n if beached.any():\n beaching_probability[index_loc] += 1\n ",
"_____no_output_____"
],
[
"# Make figure if we have beaching probability for any island\n\ngalapagos_domain = [-93, -88, -3, 2]\n\nXfiles = '../../input/modelfields/MITgcm4km/RGEMS3_Surf_grid.nc'\ndfile = Dataset(Xfiles)\nmask0 = dfile.variables['maskC'][0,:,:]\nmask1 = np.where(mask0==1, nan, 0)\nlon = dfile.variables['XC'][:]\nlat = dfile.variables['YC'][:]\n\nfigsize=(8,8)\nfig, axs = plt.subplots(1, 1, figsize=figsize)\n\nim = axs.scatter(startlon,startlat,s=70,\n c=beaching_probability/release_time*100,\n cmap='GnBu',\n vmin=0,vmax=100) \naxs.contourf(lon,lat,mask1,cmap='Greens',vmin=-4,vmax=1)\naxs.contour(lon, lat, mask0, colors='k', linestyles='-')\naxs.set_xlabel('longitude') \naxs.set_ylabel('latitude') \n\naxs.set_xlim(galapagos_domain[0:2])\naxs.set_ylim(galapagos_domain[2:4])\n\ncbar_ax = fig.add_axes([0.87, 0.15, 0.03, 0.7])\ncbar = fig.colorbar(im, cax=cbar_ax)\ncbar.ax.set_ylabel('probability of beaching (%)')\nplt.rcParams.update({'font.size': 14})\n\nfig.subplots_adjust(wspace=0.0, hspace=0.0, right=0.85)\n\nplt.savefig('probability_of_beaching.png', dpi=200)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code"
]
] |
d0834eff688114532b3b3899ad931f08be3134ef | 3,342 | ipynb | Jupyter Notebook | Conditional_Selection/conditional_selection.ipynb | jpweldon/Module_3_Practice | cfecdbf89c5f4da6c6244638a302216ccd5c8308 | [
"MIT"
] | null | null | null | Conditional_Selection/conditional_selection.ipynb | jpweldon/Module_3_Practice | cfecdbf89c5f4da6c6244638a302216ccd5c8308 | [
"MIT"
] | null | null | null | Conditional_Selection/conditional_selection.ipynb | jpweldon/Module_3_Practice | cfecdbf89c5f4da6c6244638a302216ccd5c8308 | [
"MIT"
] | null | null | null | 25.707692 | 128 | 0.431478 | [
[
[
"# Import the Pandas library\nimport pandas as pd\n\n# Import the numpy library\nimport numpy as np\n\n# Create the daily_returns DataFrame\ndaily_returns = pd.DataFrame({\n 'AAPL': np.random.randn(5),\n 'GOOG': np.random.randn(5),\n 'MSFT': np.random.randn(5),\n})\ndaily_returns\n# Construct the Boolean filter so that the code eliminates GOOG from the DataFrame\nboolean_filter = [True, False, True]\n\n# Display the daily_returns DataFrame filtering using the boolean_filter so the code eliminates GOOG from the DataFrame\ndaily_returns.loc[:, boolean_filter]\n",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code"
]
] |
d0835d92f477f9d28dd0e70a18d57e461ea5bc96 | 12,476 | ipynb | Jupyter Notebook | Deep_Learning/TensorFlow-aymericdamien/notebooks/3_NeuralNetworks/convolutional_network_raw.ipynb | Chau-Xochitl/INFO_7390 | 3ab4a3bf7af5c0b57d9604def26d64dc31405333 | [
"MIT"
] | null | null | null | Deep_Learning/TensorFlow-aymericdamien/notebooks/3_NeuralNetworks/convolutional_network_raw.ipynb | Chau-Xochitl/INFO_7390 | 3ab4a3bf7af5c0b57d9604def26d64dc31405333 | [
"MIT"
] | null | null | null | Deep_Learning/TensorFlow-aymericdamien/notebooks/3_NeuralNetworks/convolutional_network_raw.ipynb | Chau-Xochitl/INFO_7390 | 3ab4a3bf7af5c0b57d9604def26d64dc31405333 | [
"MIT"
] | null | null | null | 41.039474 | 357 | 0.584242 | [
[
[
"# Convolutional Neural Network Example\n\nBuild a convolutional neural network with TensorFlow.\n\n- Author: Aymeric Damien\n- Project: https://github.com/aymericdamien/TensorFlow-Examples/\n\nThese lessons are adapted from [aymericdamien TensorFlow tutorials](https://github.com/aymericdamien/TensorFlow-Examples) \n / [GitHub](https://github.com/aymericdamien/TensorFlow-Examples) \nwhich are published under the [MIT License](https://github.com/Hvass-Labs/TensorFlow-Tutorials/blob/master/LICENSE) which allows very broad use for both academic and commercial purposes.\n",
"_____no_output_____"
],
[
"## CNN Overview\n\n\n\n## MNIST Dataset Overview\n\nThis example is using MNIST handwritten digits. The dataset contains 60,000 examples for training and 10,000 examples for testing. The digits have been size-normalized and centered in a fixed-size image (28x28 pixels) with values from 0 to 1. For simplicity, each image has been flattened and converted to a 1-D numpy array of 784 features (28*28).\n\n\n\nMore info: http://yann.lecun.com/exdb/mnist/",
"_____no_output_____"
]
],
[
[
"from __future__ import division, print_function, absolute_import\n\nimport tensorflow as tf\n\n# Import MNIST data\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets(\"/tmp/data/\", one_hot=True)",
"Extracting /tmp/data/train-images-idx3-ubyte.gz\nExtracting /tmp/data/train-labels-idx1-ubyte.gz\nExtracting /tmp/data/t10k-images-idx3-ubyte.gz\nExtracting /tmp/data/t10k-labels-idx1-ubyte.gz\n"
],
[
"# Training Parameters\nlearning_rate = 0.001\nnum_steps = 500\nbatch_size = 128\ndisplay_step = 10\n\n# Network Parameters\nnum_input = 784 # MNIST data input (img shape: 28*28)\nnum_classes = 10 # MNIST total classes (0-9 digits)\ndropout = 0.75 # Dropout, probability to keep units\n\n# tf Graph input\nX = tf.placeholder(tf.float32, [None, num_input])\nY = tf.placeholder(tf.float32, [None, num_classes])\nkeep_prob = tf.placeholder(tf.float32) # dropout (keep probability)",
"_____no_output_____"
],
[
"# Create some wrappers for simplicity\ndef conv2d(x, W, b, strides=1):\n # Conv2D wrapper, with bias and relu activation\n x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')\n x = tf.nn.bias_add(x, b)\n return tf.nn.relu(x)\n\n\ndef maxpool2d(x, k=2):\n # MaxPool2D wrapper\n return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1],\n padding='SAME')\n\n\n# Create model\ndef conv_net(x, weights, biases, dropout):\n # MNIST data input is a 1-D vector of 784 features (28*28 pixels)\n # Reshape to match picture format [Height x Width x Channel]\n # Tensor input become 4-D: [Batch Size, Height, Width, Channel]\n x = tf.reshape(x, shape=[-1, 28, 28, 1])\n\n # Convolution Layer\n conv1 = conv2d(x, weights['wc1'], biases['bc1'])\n # Max Pooling (down-sampling)\n conv1 = maxpool2d(conv1, k=2)\n\n # Convolution Layer\n conv2 = conv2d(conv1, weights['wc2'], biases['bc2'])\n # Max Pooling (down-sampling)\n conv2 = maxpool2d(conv2, k=2)\n\n # Fully connected layer\n # Reshape conv2 output to fit fully connected layer input\n fc1 = tf.reshape(conv2, [-1, weights['wd1'].get_shape().as_list()[0]])\n fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])\n fc1 = tf.nn.relu(fc1)\n # Apply Dropout\n fc1 = tf.nn.dropout(fc1, dropout)\n\n # Output, class prediction\n out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])\n return out",
"_____no_output_____"
],
[
"# Store layers weight & bias\nweights = {\n # 5x5 conv, 1 input, 32 outputs\n 'wc1': tf.Variable(tf.random_normal([5, 5, 1, 32])),\n # 5x5 conv, 32 inputs, 64 outputs\n 'wc2': tf.Variable(tf.random_normal([5, 5, 32, 64])),\n # fully connected, 7*7*64 inputs, 1024 outputs\n 'wd1': tf.Variable(tf.random_normal([7*7*64, 1024])),\n # 1024 inputs, 10 outputs (class prediction)\n 'out': tf.Variable(tf.random_normal([1024, num_classes]))\n}\n\nbiases = {\n 'bc1': tf.Variable(tf.random_normal([32])),\n 'bc2': tf.Variable(tf.random_normal([64])),\n 'bd1': tf.Variable(tf.random_normal([1024])),\n 'out': tf.Variable(tf.random_normal([num_classes]))\n}\n\n# Construct model\nlogits = conv_net(X, weights, biases, keep_prob)\nprediction = tf.nn.softmax(logits)\n\n# Define loss and optimizer\nloss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\n logits=logits, labels=Y))\noptimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\ntrain_op = optimizer.minimize(loss_op)\n\n\n# Evaluate model\ncorrect_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n\n# Initialize the variables (i.e. assign their default value)\ninit = tf.global_variables_initializer()",
"_____no_output_____"
],
[
"# Start training\nwith tf.Session() as sess:\n\n # Run the initializer\n sess.run(init)\n\n for step in range(1, num_steps+1):\n batch_x, batch_y = mnist.train.next_batch(batch_size)\n # Run optimization op (backprop)\n sess.run(train_op, feed_dict={X: batch_x, Y: batch_y, keep_prob: dropout})\n if step % display_step == 0 or step == 1:\n # Calculate batch loss and accuracy\n loss, acc = sess.run([loss_op, accuracy], feed_dict={X: batch_x,\n Y: batch_y,\n keep_prob: 1.0})\n print(\"Step \" + str(step) + \", Minibatch Loss= \" + \\\n \"{:.4f}\".format(loss) + \", Training Accuracy= \" + \\\n \"{:.3f}\".format(acc))\n\n print(\"Optimization Finished!\")\n\n # Calculate accuracy for 256 MNIST test images\n print(\"Testing Accuracy:\", \\\n sess.run(accuracy, feed_dict={X: mnist.test.images[:256],\n Y: mnist.test.labels[:256],\n keep_prob: 1.0}))\n",
"Step 1, Minibatch Loss= 63763.3047, Training Accuracy= 0.141\nStep 10, Minibatch Loss= 26429.6680, Training Accuracy= 0.242\nStep 20, Minibatch Loss= 12171.8584, Training Accuracy= 0.586\nStep 30, Minibatch Loss= 6306.6318, Training Accuracy= 0.734\nStep 40, Minibatch Loss= 5113.7583, Training Accuracy= 0.711\nStep 50, Minibatch Loss= 4022.2131, Training Accuracy= 0.805\nStep 60, Minibatch Loss= 3125.4949, Training Accuracy= 0.867\nStep 70, Minibatch Loss= 2225.4875, Training Accuracy= 0.875\nStep 80, Minibatch Loss= 1843.3540, Training Accuracy= 0.867\nStep 90, Minibatch Loss= 1715.7744, Training Accuracy= 0.875\nStep 100, Minibatch Loss= 2611.2708, Training Accuracy= 0.906\nStep 110, Minibatch Loss= 4804.0913, Training Accuracy= 0.875\nStep 120, Minibatch Loss= 1067.5258, Training Accuracy= 0.938\nStep 130, Minibatch Loss= 2519.1514, Training Accuracy= 0.898\nStep 140, Minibatch Loss= 2687.9292, Training Accuracy= 0.906\nStep 150, Minibatch Loss= 1983.4077, Training Accuracy= 0.938\nStep 160, Minibatch Loss= 2844.6553, Training Accuracy= 0.930\nStep 170, Minibatch Loss= 3602.2524, Training Accuracy= 0.914\nStep 180, Minibatch Loss= 175.3922, Training Accuracy= 0.961\nStep 190, Minibatch Loss= 645.1918, Training Accuracy= 0.945\nStep 200, Minibatch Loss= 1147.6567, Training Accuracy= 0.938\nStep 210, Minibatch Loss= 1140.4148, Training Accuracy= 0.914\nStep 220, Minibatch Loss= 1572.8756, Training Accuracy= 0.906\nStep 230, Minibatch Loss= 1292.9274, Training Accuracy= 0.898\nStep 240, Minibatch Loss= 1501.4623, Training Accuracy= 0.953\nStep 250, Minibatch Loss= 1908.2997, Training Accuracy= 0.898\nStep 260, Minibatch Loss= 2182.2380, Training Accuracy= 0.898\nStep 270, Minibatch Loss= 487.5807, Training Accuracy= 0.961\nStep 280, Minibatch Loss= 1284.1130, Training Accuracy= 0.945\nStep 290, Minibatch Loss= 1232.4919, Training Accuracy= 0.891\nStep 300, Minibatch Loss= 1198.8336, Training Accuracy= 0.945\nStep 310, Minibatch Loss= 2010.5345, Training Accuracy= 0.906\nStep 320, Minibatch Loss= 786.3917, Training Accuracy= 0.945\nStep 330, Minibatch Loss= 1408.3556, Training Accuracy= 0.898\nStep 340, Minibatch Loss= 1453.7538, Training Accuracy= 0.953\nStep 350, Minibatch Loss= 999.8901, Training Accuracy= 0.906\nStep 360, Minibatch Loss= 914.3958, Training Accuracy= 0.961\nStep 370, Minibatch Loss= 488.0052, Training Accuracy= 0.938\nStep 380, Minibatch Loss= 1070.8710, Training Accuracy= 0.922\nStep 390, Minibatch Loss= 151.4658, Training Accuracy= 0.961\nStep 400, Minibatch Loss= 555.3539, Training Accuracy= 0.953\nStep 410, Minibatch Loss= 765.5746, Training Accuracy= 0.945\nStep 420, Minibatch Loss= 326.9393, Training Accuracy= 0.969\nStep 430, Minibatch Loss= 530.8968, Training Accuracy= 0.977\nStep 440, Minibatch Loss= 463.3909, Training Accuracy= 0.977\nStep 450, Minibatch Loss= 362.2226, Training Accuracy= 0.977\nStep 460, Minibatch Loss= 414.0034, Training Accuracy= 0.953\nStep 470, Minibatch Loss= 583.4587, Training Accuracy= 0.945\nStep 480, Minibatch Loss= 566.1262, Training Accuracy= 0.969\nStep 490, Minibatch Loss= 691.1143, Training Accuracy= 0.961\nStep 500, Minibatch Loss= 282.8893, Training Accuracy= 0.984\nOptimization Finished!\nTesting Accuracy: 0.976562\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
d0835e0e3758b1b9b6f134770da70d0bf967247e | 5,102 | ipynb | Jupyter Notebook | basic_search_and_load.ipynb | pangeo-gallery/cmip6 | 41d34351af654543ecf52b8dd925e32d10326160 | [
"MIT"
] | 11 | 2020-04-28T15:58:13.000Z | 2022-02-24T04:18:13.000Z | basic_search_and_load.ipynb | pangeo-gallery/cmip6 | 41d34351af654543ecf52b8dd925e32d10326160 | [
"MIT"
] | 1 | 2020-10-08T14:12:19.000Z | 2020-10-08T16:05:12.000Z | basic_search_and_load.ipynb | pangeo-gallery/cmip6 | 41d34351af654543ecf52b8dd925e32d10326160 | [
"MIT"
] | 4 | 2021-01-12T18:28:07.000Z | 2022-02-25T18:18:22.000Z | 23.730233 | 232 | 0.567425 | [
[
[
"# Google Cloud CMIP6 Public Data: Basic Python Example\n\nThis notebooks shows how to query the catalog and load the data using python",
"_____no_output_____"
]
],
[
[
"from matplotlib import pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport xarray as xr\nimport zarr\nimport fsspec\n\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina' \nplt.rcParams['figure.figsize'] = 12, 6",
"_____no_output_____"
]
],
[
[
"## Browse Catalog\n\nThe data catatalog is stored as a CSV file. Here we read it with Pandas.",
"_____no_output_____"
]
],
[
[
"df = pd.read_csv('https://storage.googleapis.com/cmip6/cmip6-zarr-consolidated-stores.csv')\ndf.head()",
"_____no_output_____"
]
],
[
[
"The columns of the dataframe correspond to the CMI6 controlled vocabulary. A beginners' guide to these terms is available in [this document](https://docs.google.com/document/d/1yUx6jr9EdedCOLd--CPdTfGDwEwzPpCF6p1jRmqx-0Q). \n\nHere we filter the data to find monthly surface air temperature for historical experiments.",
"_____no_output_____"
]
],
[
[
"df_ta = df.query(\"activity_id=='CMIP' & table_id == 'Amon' & variable_id == 'tas' & experiment_id == 'historical'\")\ndf_ta",
"_____no_output_____"
]
],
[
[
"Now we do further filtering to find just the models from NCAR.",
"_____no_output_____"
]
],
[
[
"df_ta_ncar = df_ta.query('institution_id == \"NCAR\"')\ndf_ta_ncar",
"_____no_output_____"
]
],
[
[
"## Load Data\n\nNow we will load a single store using fsspec, zarr, and xarray.",
"_____no_output_____"
]
],
[
[
"# get the path to a specific zarr store (the first one from the dataframe above)\nzstore = df_ta_ncar.zstore.values[-1]\nprint(zstore)\n\n# create a mutable-mapping-style interface to the store\nmapper = fsspec.get_mapper(zstore)\n\n# open it using xarray and zarr\nds = xr.open_zarr(mapper, consolidated=True)\nds",
"_____no_output_____"
]
],
[
[
"Plot a map from a specific date.",
"_____no_output_____"
]
],
[
[
"ds.tas.sel(time='1950-01').squeeze().plot()",
"_____no_output_____"
]
],
[
[
"Create a timeseries of global-average surface air temperature. For this we need the area weighting factor for each gridpoint.",
"_____no_output_____"
]
],
[
[
"df_area = df.query(\"variable_id == 'areacella' & source_id == 'CESM2'\")\nds_area = xr.open_zarr(fsspec.get_mapper(df_area.zstore.values[0]), consolidated=True)\nds_area",
"_____no_output_____"
],
[
"total_area = ds_area.areacella.sum(dim=['lon', 'lat'])\nta_timeseries = (ds.tas * ds_area.areacella).sum(dim=['lon', 'lat']) / total_area\nta_timeseries",
"_____no_output_____"
]
],
[
[
"By default the data are loaded lazily, as Dask arrays. Here we trigger computation explicitly.",
"_____no_output_____"
]
],
[
[
"%time ta_timeseries.load()",
"_____no_output_____"
],
[
"ta_timeseries.plot(label='monthly')\nta_timeseries.rolling(time=12).mean().plot(label='12 month rolling mean')\nplt.legend()\nplt.title('Global Mean Surface Air Temperature')",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
d083700ec3b8b6456fdf8324f6dde4cc9605d455 | 672,379 | ipynb | Jupyter Notebook | meanOperpAndApproxImpacts.ipynb | jobovy/streamgap-pepper | 176c8f67abf322a6a924a9e7757a004733a7413a | [
"BSD-3-Clause"
] | 5 | 2016-06-14T04:35:06.000Z | 2020-09-22T16:20:36.000Z | meanOperpAndApproxImpacts.ipynb | jobovy/streamgap-pepper | 176c8f67abf322a6a924a9e7757a004733a7413a | [
"BSD-3-Clause"
] | 1 | 2017-09-27T14:06:48.000Z | 2017-10-02T15:03:22.000Z | meanOperpAndApproxImpacts.ipynb | jobovy/streamgap-pepper | 176c8f67abf322a6a924a9e7757a004733a7413a | [
"BSD-3-Clause"
] | 2 | 2019-09-07T18:27:58.000Z | 2019-11-12T11:23:56.000Z | 489.715222 | 107,654 | 0.924944 | [
[
[
"import os, os.path\nimport pickle\nimport time\nimport numpy\nfrom scipy import interpolate\nfrom galpy.util import bovy_conversion, bovy_plot, save_pickles\nimport gd1_util\nfrom gd1_util import R0, V0\nimport seaborn as sns\nfrom matplotlib import cm, pyplot\nimport simulate_streampepper\nimport statsmodels.api as sm\nlowess = sm.nonparametric.lowess\n%pylab inline\nfrom matplotlib.ticker import NullFormatter, FuncFormatter\nsave_figures= False",
"/Users/bovy/anaconda/envs/py27/lib/python2.7/site-packages/matplotlib/__init__.py:872: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.\n warnings.warn(self.msg_depr % (key, alt_key))\n\ngalpyWarning: A major change in versions > 1.1 is that all galpy.potential functions and methods take the potential as the first argument; previously methods such as evaluatePotentials, evaluateDensities, etc. would be called with (R,z,Pot), now they are called as (Pot,R,z) for greater consistency across the codebase\nPopulating the interactive namespace from numpy and matplotlib\n"
]
],
[
[
"# Figures for the section on approximately computing the stream structure",
"_____no_output_____"
]
],
[
[
"# Load the smooth and peppered stream\nsdf_smooth= gd1_util.setup_gd1model()\npepperfilename= 'gd1pepper.pkl'\nif os.path.exists(pepperfilename):\n with open(pepperfilename,'rb') as savefile:\n sdf_pepper= pickle.load(savefile)\nelse:\n timpacts= simulate_streampepper.parse_times('256sampling',9.)\n sdf_pepper= gd1_util.setup_gd1model(timpact=timpacts,\n hernquist=True)\n save_pickles(pepperfilename,sdf_pepper)",
"galpyWarning: WARNING: Rnorm keyword input to streamdf is deprecated in favor of the standard ro keyword\ngalpyWarning: WARNING: Vnorm keyword input to streamdf is deprecated in favor of the standard vo keyword\ngalpyWarning: Using C implementation to integrate orbits\n"
]
],
[
[
"## Is the mean perpendicular frequency close to zero?",
"_____no_output_____"
]
],
[
[
"# Sampling functions\nmassrange=[5.,9.]\nplummer= False\nXrs= 5.\nnsubhalo= simulate_streampepper.nsubhalo\nrs= simulate_streampepper.rs\ndNencdm= simulate_streampepper.dNencdm\nsample_GM= lambda: (10.**((-0.5)*massrange[0])\\\n +(10.**((-0.5)*massrange[1])\\\n -10.**((-0.5)*massrange[0]))\\\n *numpy.random.uniform())**(1./(-0.5))\\\n /bovy_conversion.mass_in_msol(V0,R0)\nrate_range= numpy.arange(massrange[0]+0.5,massrange[1]+0.5,1)\nrate= numpy.sum([dNencdm(sdf_pepper,10.**r,Xrs=Xrs,\n plummer=plummer)\n for r in rate_range])\nsample_rs= lambda x: rs(x*bovy_conversion.mass_in_1010msol(V0,R0)*10.**10.,\n plummer=plummer)",
"_____no_output_____"
],
[
"numpy.random.seed(2)\nsdf_pepper.simulate(rate=rate,sample_GM=sample_GM,sample_rs=sample_rs,Xrs=Xrs)",
"_____no_output_____"
],
[
"n= 100000\naa_mock_per= sdf_pepper.sample(n=n,returnaAdt=True)\ndO= numpy.dot(aa_mock_per[0].T-sdf_pepper._progenitor_Omega,\n sdf_pepper._sigomatrixEig[1][:,sdf_pepper._sigomatrixEigsortIndx])\ndO[:,2]*= sdf_pepper._sigMeanSign\nda= numpy.dot(aa_mock_per[1].T-sdf_pepper._progenitor_angle,\n sdf_pepper._sigomatrixEig[1][:,sdf_pepper._sigomatrixEigsortIndx])\nda[:,2]*= sdf_pepper._sigMeanSign\napar= da[:,2]\nxs= numpy.linspace(0.,1.5,1001)\nmO_unp= numpy.array([sdf_smooth.meanOmega(x,oned=True,use_physical=False) for x in xs])\nmOint= interpolate.InterpolatedUnivariateSpline(xs,mO_unp,k=3)",
"_____no_output_____"
],
[
"mOs= mOint(apar)\nfrac= 0.02\nalpha=0.01\nlinecolor='0.65'\nbovy_plot.bovy_print(axes_labelsize=18.,xtick_labelsize=14.,ytick_labelsize=14.)\nfigsize(12,4)\nsubplot(1,3,1)\nbovy_plot.bovy_plot(apar[::3],dO[::3,2]/mOs[::3]-1,'k.',alpha=alpha*2,gcf=True,\n rasterized=True,xrange=[0.,1.5],yrange=[-1.2,1.2])\nz= lowess(dO[:,2]/mOs-1,apar,frac=frac)\nplot(z[::100,0],z[::100,1],color=linecolor,lw=2.5)\n#xlim(0.,1.5)\n#ylim(-1.2,1.2)\nxlabel(r'$\\Delta\\theta_\\parallel$')\nbovy_plot.bovy_text(r'$\\Delta\\Omega_\\parallel/\\langle\\Delta\\Omega^0_\\parallel\\rangle-1$',top_left=True,\n size=18.)\nsubplot(1,3,2)\nbovy_plot.bovy_plot(apar[::3],dO[::3,1]/mOs[::3],'k.',alpha=alpha*2,gcf=True,\n rasterized=True,xrange=[0.,1.5],yrange=[-0.05,0.05])\nz= lowess(dO[:,1]/mOs,apar,frac=frac)\nplot(z[::100,0],z[::100,1],color=linecolor,lw=2.5)\n#xlim(0.,1.5)\n#ylim(-0.05,0.05)\nxlabel(r'$\\Delta\\theta_\\parallel$')\nbovy_plot.bovy_text(r'$\\Delta\\Omega_{\\perp,1}/\\langle\\Delta\\Omega^0_\\parallel\\rangle$',top_left=True,\n size=18.)\nsubplot(1,3,3)\nbovy_plot.bovy_plot(apar[::3],dO[::3,0]/mOs[::3],'k.',alpha=alpha,gcf=True,\n rasterized=True,xrange=[0.,1.5],yrange=[-0.05,0.05])\nz= lowess(dO[:,0]/mOs,apar,frac=frac)\nplot(z[::100,0],z[::100,1],color=linecolor,lw=2.5)\n#xlim(0.,1.5)\n#ylim(-0.05,0.05)\nxlabel(r'$\\Delta\\theta_\\parallel$')\nbovy_plot.bovy_text(r'$\\Delta\\Omega_{\\perp,2}/\\langle\\Delta\\Omega^0_\\parallel\\rangle$',top_left=True,\n size=18.)\nif save_figures:\n tight_layout()\n bovy_plot.bovy_end_print(os.path.join(os.getenv('PAPERSDIR'),'2016-stream-stats','gd1like_meanOparOperp.pdf'))",
"_____no_output_____"
],
[
"print \"This stream had %i impacts\" % len(sdf_pepper._GM)",
"This stream had 61 impacts\n"
]
],
[
[
"## Test the single-impact approximations",
"_____no_output_____"
]
],
[
[
"# Setup a single, large impact\nm= 10.**8.\nGM= 10**8./bovy_conversion.mass_in_msol(V0,R0)\ntimpactIndx= numpy.argmin(numpy.fabs(numpy.array(sdf_pepper._uniq_timpact)-1.3/bovy_conversion.time_in_Gyr(V0,R0)))\n# Load the single-impact stream\ngapfilename= 'gd1single.pkl'\nif os.path.exists(gapfilename):\n with open(gapfilename,'rb') as savefile:\n sdf_gap= pickle.load(savefile)\nelse:\n sdf_gap= gd1_util.setup_gd1model(hernquist=True,\n singleImpact=True,\n impactb=0.5*rs(m),\n subhalovel=numpy.array([-25.,155.,30.])/V0,\n impact_angle=0.6,\n timpact=sdf_pepper._uniq_timpact[timpactIndx],\n GM=GM,rs=rs(m))\n save_pickles(gapfilename,sdf_gap)",
"_____no_output_____"
],
[
"n= 100000\naa_mock_per= sdf_gap.sample(n=n,returnaAdt=True)\ndO= numpy.dot(aa_mock_per[0].T-sdf_gap._progenitor_Omega,\n sdf_gap._sigomatrixEig[1][:,sdf_gap._sigomatrixEigsortIndx])\ndO[:,2]*= sdf_gap._sigMeanSign\nda= numpy.dot(aa_mock_per[1].T-sdf_gap._progenitor_angle,\n sdf_gap._sigomatrixEig[1][:,sdf_gap._sigomatrixEigsortIndx])\nda[:,2]*= sdf_gap._sigMeanSign",
"_____no_output_____"
],
[
"num= True\napar= numpy.arange(0.,sdf_smooth.length()+0.003,0.003)\ndens_unp= numpy.array([sdf_smooth._density_par(x) for x in apar])\ndens_approx= numpy.array([sdf_gap.density_par(x,approx=True) for x in apar])\ndens_approx_higherorder= numpy.array([sdf_gap._density_par(x,approx=True,higherorder=True) for x in apar])\n# normalize\ndens_unp= dens_unp/numpy.sum(dens_unp)/(apar[1]-apar[0])\ndens_approx= dens_approx/numpy.sum(dens_approx)/(apar[1]-apar[0])\ndens_approx_higherorder= dens_approx_higherorder/numpy.sum(dens_approx_higherorder)/(apar[1]-apar[0])\nif num:\n dens_num= numpy.array([sdf_gap.density_par(x,approx=False) for x in apar])\n dens_num= dens_num/numpy.sum(dens_num)/(apar[1]-apar[0])",
"/Users/bovy/anaconda/envs/py27/lib/python2.7/site-packages/scipy/integrate/quadpack.py:352: IntegrationWarning: The maximum number of subdivisions (50) has been achieved.\n If increasing the limit yields no improvement it is advised to analyze \n the integrand in order to determine the difficulties. If the position of a \n local difficulty can be determined (singularity, discontinuity) one will \n probably gain from splitting up the interval and calling the integrator \n on the subranges. Perhaps a special-purpose integrator should be used.\n warnings.warn(msg, IntegrationWarning)\n\n/Users/bovy/anaconda/envs/py27/lib/python2.7/site-packages/scipy/integrate/quadpack.py:352: IntegrationWarning: The algorithm does not converge. Roundoff error is detected\n in the extrapolation table. It is assumed that the requested tolerance\n cannot be achieved, and that the returned result (if full_output = 1) is \n the best which can be obtained.\n warnings.warn(msg, IntegrationWarning)\n\n"
],
[
"bovy_plot.bovy_print(axes_labelsize=18.,xtick_labelsize=14.,ytick_labelsize=14.)\nfigsize(6,7)\naxTop= pyplot.axes([0.15,0.3,0.825,0.65])\nfig= pyplot.gcf()\nfig.sca(axTop)\nbovy_plot.bovy_plot(apar,dens_approx,lw=2.5,gcf=True,\n color='k',\n xrange=[0.,1.],\n yrange=[0.,2.24],\n ylabel=r'$\\mathrm{density}$')\nplot(apar,dens_unp,lw=3.5,color='k',ls='--',zorder=0)\nnullfmt = NullFormatter() # no labels\naxTop.xaxis.set_major_formatter(nullfmt)\ndum= hist(da[:,2],bins=101,normed=True,range=[apar[0],apar[-1]],\n histtype='step',color='0.55',zorder=0,lw=3.)\naxBottom= pyplot.axes([0.15,0.1,0.825,0.2])\nfig= pyplot.gcf()\nfig.sca(axBottom)\nbovy_plot.bovy_plot(apar,100.*(dens_approx_higherorder-dens_approx)/dens_approx_higherorder,\n lw=2.5,gcf=True,color='k',\n xrange=[0.,1.],\n yrange=[-0.145,0.145],\n zorder=2,\n xlabel=r'$\\Delta \\theta_\\parallel$',\n ylabel=r'$\\mathrm{relative\\ difference\\ in}\\ \\%$')\nif num:\n plot(apar,100.*(dens_num-dens_approx_higherorder)/dens_approx_higherorder,\n lw=2.5,zorder=1,color='0.55')\n# label\naparIndx= numpy.argmin(numpy.fabs(apar-0.64))\nplot([0.45,apar[aparIndx]],[0.06,(100.*(dens_approx_higherorder-dens_approx)/dens_approx_higherorder)[aparIndx]],\n 'k',lw=1.)\nbovy_plot.bovy_text(0.1,0.07,r'$\\mathrm{higher\\!\\!-\\!\\!order\\ minus\\ linear}$',size=17.)\nif num:\n aparIndx= numpy.argmin(numpy.fabs(apar-0.62))\n plot([0.45,apar[aparIndx]],[-0.07,(100.*(dens_num-dens_approx_higherorder)/dens_approx_higherorder)[aparIndx]],\n 'k',lw=1.)\n bovy_plot.bovy_text(0.05,-0.12,r'$\\mathrm{numerical\\ minus\\ higher\\!\\!-\\!\\!order}$',size=17.)\nif save_figures:\n bovy_plot.bovy_end_print(os.path.join(os.getenv('PAPERSDIR'),'2016-stream-stats','gd1likeSingle_densapprox.pdf'))",
"_____no_output_____"
],
[
"mO_unp= numpy.array([sdf_smooth.meanOmega(x,oned=True) for x in apar])\\\n *bovy_conversion.freq_in_Gyr(V0,R0)\nmO_approx= numpy.array([sdf_gap.meanOmega(x,approx=True,oned=True) for x in apar])\\\n *bovy_conversion.freq_in_Gyr(V0,R0)\nmO_approx_higherorder= numpy.array([sdf_gap.meanOmega(x,oned=True,approx=True,higherorder=True) for x in apar])\\\n *bovy_conversion.freq_in_Gyr(V0,R0)\nif num:\n mO_num= numpy.array([sdf_gap.meanOmega(x,approx=False,oned=True) for x in apar])\\\n *bovy_conversion.freq_in_Gyr(V0,R0)",
"_____no_output_____"
],
[
"frac= 0.005\nalpha=0.01\nlinecolor='0.65'\nbovy_plot.bovy_print(axes_labelsize=18.,xtick_labelsize=14.,ytick_labelsize=14.)\nfigsize(6,7)\naxTop= pyplot.axes([0.15,0.3,0.825,0.65])\nfig= pyplot.gcf()\nfig.sca(axTop)\nbovy_plot.bovy_plot(apar,mO_approx,lw=2.5,gcf=True,\n color='k',\n xrange=[0.,1.],\n yrange=[0.,0.2],\n ylabel=r'$\\Delta \\Omega_\\parallel\\,(\\mathrm{Gyr}^{-1})$')\nplot(apar,mO_unp,lw=2.5,color='k',ls='--')\nplot(da[::3,2],dO[::3,2]*bovy_conversion.freq_in_Gyr(V0,R0),\n 'k.',alpha=alpha*2,rasterized=True)\nnullfmt = NullFormatter() # no labels\naxTop.xaxis.set_major_formatter(nullfmt)\naxBottom= pyplot.axes([0.15,0.1,0.825,0.2])\nfig= pyplot.gcf()\nfig.sca(axBottom)\nbovy_plot.bovy_plot(apar,100.*(mO_approx_higherorder-mO_approx)/mO_approx_higherorder,\n lw=2.5,gcf=True,color='k',\n xrange=[0.,1.],zorder=1,\n yrange=[-0.039,0.039],\n xlabel=r'$\\Delta \\theta_\\parallel$',\n ylabel=r'$\\mathrm{relative\\ difference\\ in\\ \\%}$')\nif num:\n plot(apar,100.*(mO_num-mO_approx_higherorder)/mO_approx_higherorder,\n lw=2.5,color='0.55',zorder=0)\n# label\naparIndx= numpy.argmin(numpy.fabs(apar-0.64))\nplot([0.45,apar[aparIndx]],[0.024,(100.*(mO_approx_higherorder-mO_approx)/mO_approx_higherorder)[aparIndx]],\n 'k',lw=1.)\nbovy_plot.bovy_text(0.1,0.026,r'$\\mathrm{higher\\!\\!-\\!\\!order\\ minus\\ linear}$',size=17.)\naparIndx= numpy.argmin(numpy.fabs(apar-0.6))\nif num:\n plot([0.45,apar[aparIndx]],[-0.02,(100.*(mO_num-mO_approx_higherorder)/mO_approx_higherorder)[aparIndx]],\n 'k',lw=1.)\n bovy_plot.bovy_text(0.05,-0.03,r'$\\mathrm{numerical\\ minus\\ higher\\!\\!-\\!\\!order}$',size=17.)\nif save_figures:\n bovy_plot.bovy_end_print(os.path.join(os.getenv('PAPERSDIR'),'2016-stream-stats','gd1likeSingle_mOparapprox.pdf'))",
"_____no_output_____"
],
[
"start= time.time()\nnumpy.array([sdf_gap.density_par(x,approx=False) for x in apar[::10]])\nend= time.time()\nprint (end-start)*1000.*10./len(apar)\nstart= time.time()\nnumpy.array([sdf_gap.density_par(x,approx=True) for x in apar[::10]])\nend= time.time()\nprint (end-start)*1000.*10./len(apar)\nstart= time.time()\nnumpy.array([sdf_gap.density_par(x,approx=True,higherorder=True) for x in apar[::10]])\nend= time.time()\nprint (end-start)*1000.*10./len(apar)",
"109.649419785\n0.09239803661\n0.673633633238\n"
],
[
"start= time.time()\nnumpy.array([sdf_gap.meanOmega(x,approx=False,oned=True) for x in apar[::10]])\nend= time.time()\nprint (end-start)*1000.*10./len(apar)\nstart= time.time()\nnumpy.array([sdf_gap.meanOmega(x,approx=True,oned=True) for x in apar[::10]])\nend= time.time()\nprint (end-start)*1000.*10./len(apar)\nstart= time.time()\nnumpy.array([sdf_gap.meanOmega(x,approx=True,oned=True,higherorder=True) for x in apar[::10]])\nend= time.time()\nprint (end-start)*1000.*10./len(apar)",
"186.439969323\n0.519882548939\n5.57736194495\n"
]
],
[
[
"## Test the multiple-impact approximations",
"_____no_output_____"
]
],
[
[
"# Setup a four, intermediate impacts\nm= [10.**7.,10.**7.25,10.**6.75,10.**7.5]\nGM= [mm/bovy_conversion.mass_in_msol(V0,R0) for mm in m]\ntimpactIndx= [numpy.argmin(numpy.fabs(numpy.array(sdf_pepper._uniq_timpact)-1.3/bovy_conversion.time_in_Gyr(V0,R0))),\n numpy.argmin(numpy.fabs(numpy.array(sdf_pepper._uniq_timpact)-2.3/bovy_conversion.time_in_Gyr(V0,R0))),\n numpy.argmin(numpy.fabs(numpy.array(sdf_pepper._uniq_timpact)-3.3/bovy_conversion.time_in_Gyr(V0,R0))),\n numpy.argmin(numpy.fabs(numpy.array(sdf_pepper._uniq_timpact)-4.3/bovy_conversion.time_in_Gyr(V0,R0)))]\nsdf_pepper.set_impacts(impactb=[0.5*rs(m[0]),2.*rs(m[1]),1.*rs(m[2]),2.5*rs(m[3])],\n subhalovel=numpy.array([[-25.,155.,30.],\n [125.,35.,80.],\n [-225.,5.,-40.],\n [25.,-155.,37.]])/V0,\n impact_angle=[0.6,0.4,0.3,0.3],\n timpact=[sdf_pepper._uniq_timpact[ti] for ti in timpactIndx],\n GM=GM,rs=[rs(mm) for mm in m])\nsdf_gap= sdf_pepper",
"_____no_output_____"
],
[
"n= 100000\naa_mock_per= sdf_pepper.sample(n=n,returnaAdt=True)\ndO= numpy.dot(aa_mock_per[0].T-sdf_gap._progenitor_Omega,\n sdf_gap._sigomatrixEig[1][:,sdf_gap._sigomatrixEigsortIndx])\ndO[:,2]*= sdf_gap._sigMeanSign\nda= numpy.dot(aa_mock_per[1].T-sdf_gap._progenitor_angle,\n sdf_gap._sigomatrixEig[1][:,sdf_gap._sigomatrixEigsortIndx])\nda[:,2]*= sdf_gap._sigMeanSign",
"_____no_output_____"
],
[
"num= True\napar= numpy.arange(0.,sdf_smooth.length()+0.003,0.003)\ndens_unp= numpy.array([sdf_smooth._density_par(x) for x in apar])\ndens_approx= numpy.array([sdf_gap.density_par(x,approx=True) for x in apar])\n# normalize\ndens_unp= dens_unp/numpy.sum(dens_unp)/(apar[1]-apar[0])\ndens_approx= dens_approx/numpy.sum(dens_approx)/(apar[1]-apar[0])\nif num:\n dens_num= numpy.array([sdf_gap.density_par(x,approx=False) for x in apar])\n dens_num= dens_num/numpy.sum(dens_num)/(apar[1]-apar[0])",
"/Users/bovy/anaconda/envs/py27/lib/python2.7/site-packages/scipy/integrate/quadpack.py:352: IntegrationWarning: The maximum number of subdivisions (100) has been achieved.\n If increasing the limit yields no improvement it is advised to analyze \n the integrand in order to determine the difficulties. If the position of a \n local difficulty can be determined (singularity, discontinuity) one will \n probably gain from splitting up the interval and calling the integrator \n on the subranges. Perhaps a special-purpose integrator should be used.\n warnings.warn(msg, IntegrationWarning)\n\n/Users/bovy/anaconda/envs/py27/lib/python2.7/site-packages/scipy/integrate/quadpack.py:352: IntegrationWarning: The occurrence of roundoff error is detected, which prevents \n the requested tolerance from being achieved. The error may be \n underestimated.\n warnings.warn(msg, IntegrationWarning)\n\n"
],
[
"bovy_plot.bovy_print(axes_labelsize=18.,xtick_labelsize=14.,ytick_labelsize=14.)\nfigsize(6,7)\naxTop= pyplot.axes([0.15,0.3,0.825,0.65])\nfig= pyplot.gcf()\nfig.sca(axTop)\nbovy_plot.bovy_plot(apar,dens_approx,lw=2.5,gcf=True,\n color='k',\n xrange=[0.,1.],\n yrange=[0.,2.24],\n ylabel=r'$\\mathrm{density}$')\nplot(apar,dens_unp,lw=3.5,color='k',ls='--',zorder=0)\nnullfmt = NullFormatter() # no labels\naxTop.xaxis.set_major_formatter(nullfmt)\ndum= hist(da[:,2],bins=101,normed=True,range=[apar[0],apar[-1]],\n histtype='step',color='0.55',zorder=0,lw=3.)\naxBottom= pyplot.axes([0.15,0.1,0.825,0.2])\nfig= pyplot.gcf()\nfig.sca(axBottom)\nif num:\n bovy_plot.bovy_plot(apar,100.*(dens_num-dens_approx)/dens_approx,\n lw=2.5,gcf=True,color='k',\n xrange=[0.,1.],\n yrange=[-1.45,1.45],\n zorder=2,\n xlabel=r'$\\Delta \\theta_\\parallel$',\n ylabel=r'$\\mathrm{relative\\ difference\\ in}\\ \\%$')\n# label\nif num:\n aparIndx= numpy.argmin(numpy.fabs(apar-0.6))\n plot([0.45,apar[aparIndx]],[0.7,(100.*(dens_num-dens_approx)/dens_approx)[aparIndx]],\n 'k',lw=1.)\n bovy_plot.bovy_text(0.15,0.4,r'$\\mathrm{numerical\\ minus}$'+'\\n'+r'$\\mathrm{approximation}$',size=17.)\nif save_figures:\n bovy_plot.bovy_end_print(os.path.join(os.getenv('PAPERSDIR'),'2016-stream-stats','gd1likeMulti_densapprox.pdf'))",
"_____no_output_____"
],
[
"mO_unp= numpy.array([sdf_smooth.meanOmega(x,oned=True) for x in apar])\\\n *bovy_conversion.freq_in_Gyr(V0,R0)\nmO_approx= numpy.array([sdf_gap.meanOmega(x,approx=True,oned=True) for x in apar])\\\n *bovy_conversion.freq_in_Gyr(V0,R0)\nif num:\n mO_num= numpy.array([sdf_gap.meanOmega(x,approx=False,oned=True) for x in apar])\\\n *bovy_conversion.freq_in_Gyr(V0,R0)",
"_____no_output_____"
],
[
"frac= 0.005\nalpha=0.01\nlinecolor='0.65'\nbovy_plot.bovy_print(axes_labelsize=18.,xtick_labelsize=14.,ytick_labelsize=14.)\nfigsize(6,7)\naxTop= pyplot.axes([0.15,0.3,0.825,0.65])\nfig= pyplot.gcf()\nfig.sca(axTop)\nbovy_plot.bovy_plot(apar,mO_approx,lw=2.5,gcf=True,\n color='k',\n xrange=[0.,1.],\n yrange=[0.,0.2],\n ylabel=r'$\\Delta \\Omega_\\parallel\\,(\\mathrm{Gyr}^{-1})$')\nplot(apar,mO_unp,lw=2.5,color='k',ls='--')\nplot(da[::3,2],dO[::3,2]*bovy_conversion.freq_in_Gyr(V0,R0),\n 'k.',alpha=alpha*2,rasterized=True)\nnullfmt = NullFormatter() # no labels\naxTop.xaxis.set_major_formatter(nullfmt)\naxBottom= pyplot.axes([0.15,0.1,0.825,0.2])\nfig= pyplot.gcf()\nfig.sca(axBottom)\nif num:\n bovy_plot.bovy_plot(apar,100.*(mO_num-mO_approx)/mO_approx,\n lw=2.5,gcf=True,color='k',\n xrange=[0.,1.],zorder=1,\n yrange=[-0.39,0.39],\n xlabel=r'$\\Delta \\theta_\\parallel$',\n ylabel=r'$\\mathrm{relative\\ difference\\ in\\ \\%}$')\n# label\nif num:\n aparIndx= numpy.argmin(numpy.fabs(apar-0.6))\n plot([0.35,apar[aparIndx]],[0.2,(100.*(mO_num-mO_approx)/mO_approx)[aparIndx]],\n 'k',lw=1.)\n bovy_plot.bovy_text(0.05,0.1,r'$\\mathrm{numerical\\ minus}$'+'\\n'+r'$\\mathrm{approximation}$',size=17.)\nif save_figures:\n bovy_plot.bovy_end_print(os.path.join(os.getenv('PAPERSDIR'),'2016-stream-stats','gd1likeMulti_mOparapprox.pdf'))",
"_____no_output_____"
],
[
"start= time.time()\nnumpy.array([sdf_gap.density_par(x,approx=False) for x in apar[::10]])\nend= time.time()\nprint (end-start)*1000.*10./len(apar)\nstart= time.time()\nnumpy.array([sdf_gap.density_par(x,approx=True) for x in apar[::10]])\nend= time.time()\nprint (end-start)*1000.*10./len(apar)",
"976.109995986\n9.35311750932\n"
],
[
"start= time.time()\nnumpy.array([sdf_gap.meanOmega(x,approx=False,oned=True) for x in apar[::10]])\nend= time.time()\nprint (end-start)*1000.*10./len(apar)\nstart= time.time()\nnumpy.array([sdf_gap.meanOmega(x,approx=True,oned=True) for x in apar[::10]])\nend= time.time()\nprint (end-start)*1000.*10./len(apar)",
"2007.35482303\n8.63206025326\n"
]
],
[
[
"## Computational speed",
"_____no_output_____"
]
],
[
[
"nimp= 2**numpy.arange(1,9)\nntrials= 3\nnsample= [10,10,10,10,10,10,33,33,33]\ncompt= numpy.zeros(len(nimp))\nfor ii,ni in enumerate(nimp):\n tcompt= 0.\n for t in range(ntrials):\n nimpact=ni\n timpacts= numpy.random.permutation(numpy.array(sdf_pepper._uniq_timpact))[:ni]\n print len(timpacts)\n impact_angles= numpy.array([\\\n sdf_pepper._icdf_stream_len[ti](numpy.random.uniform())\n for ti in timpacts])\n GMs= numpy.array([sample_GM() for a in impact_angles])\n rss= numpy.array([sample_rs(gm) for gm in GMs])\n impactbs= numpy.random.uniform(size=len(impact_angles))*Xrs*rss\n subhalovels= numpy.empty((len(impact_angles),3))\n for jj in range(len(timpacts)):\n subhalovels[jj]=\\\n sdf_pepper._draw_impact_velocities(timpacts[jj],120./V0,\n impact_angles[jj],n=1)[0]\n # Flip angle sign if necessary\n if not sdf_pepper._gap_leading: impact_angles*= -1.\n # Setup\n sdf_pepper.set_impacts(impact_angle=impact_angles,\n impactb=impactbs,\n subhalovel=subhalovels,\n timpact=timpacts,\n GM=GMs,rs=rss)\n start= time.time()\n numpy.array([sdf_pepper.density_par(x,approx=True) for x in apar[::nsample[ii]]])\n end= time.time()\n tcompt+= (end-start)*1000.*nsample[ii]/len(apar)\n compt[ii]= tcompt/ntrials",
"2\n2\n2\n4\n4\n4\n8\n8\n8\n16\n16\n16\n32\n32\n32\n64\n64\n64\n128\n128\n128\n256\n256\n256\n"
],
[
"bovy_plot.bovy_print(axes_labelsize=18.,xtick_labelsize=14.,ytick_labelsize=14.)\nfigsize(6,4)\nbovy_plot.bovy_plot(numpy.log2(nimp),compt,'ko',\n semilogy=True,\n xrange=[0.,9.],\n yrange=[.5,100000.],\n ylabel=r'$\\mathrm{time}\\,(\\mathrm{ms})$',\n xlabel=r'$\\mathrm{number\\ of\\ impacts}$')\np= numpy.polyfit(numpy.log10(nimp),numpy.log10(compt),deg=1)\nbovy_plot.bovy_plot(numpy.log2(nimp),10.**(p[0]*numpy.log10(nimp)+p[1]),\n '-',lw=2.,\n color=(0.0, 0.4470588235294118, 0.6980392156862745),\n overplot=True)\npyplot.text(0.3,0.075,\n r'$\\log_{10}\\ \\mathrm{time/ms} = %.2f \\,\\log_{10} N %.2f$' % (p[0],p[1]),\n transform=pyplot.gca().transAxes,size=14.)\n# Use 100, 1000 instead of 10^2, 10^3\ngca().yaxis.set_major_formatter(ScalarFormatter())\ndef twoto(x,pos):\n return r'$%i$' % (2**x)\nformatter = FuncFormatter(twoto)\ngca().xaxis.set_major_formatter(formatter)\ngcf().subplots_adjust(left=0.175,bottom=0.15,right=0.95,top=0.95)\nif save_figures:\n bovy_plot.bovy_end_print(os.path.join(os.getenv('PAPERSDIR'),'2016-stream-stats','gd1likeMulti_compTime.pdf'))",
"_____no_output_____"
]
],
[
[
"## Example densities and tracks",
"_____no_output_____"
],
[
"### Single masses",
"_____no_output_____"
]
],
[
[
"# Load our fiducial simulation's output, for apars and smooth stream\ndata= numpy.genfromtxt(os.path.join(os.getenv('DATADIR'),'streamgap-pepper','gd1_multtime',\n 'gd1_t64sampling_X5_5-9_dens.dat'),\n delimiter=',',max_rows=2)\napars= data[0]\ndens_unp= data[1]\ndata= numpy.genfromtxt(os.path.join(os.getenv('DATADIR'),'streamgap-pepper','gd1_multtime',\n 'gd1_t64sampling_X5_5-9_omega.dat'),\n delimiter=',',max_rows=2)\nomega_unp= data[1]",
"_____no_output_____"
],
[
"dens_example= []\nomega_example= []\n# Perform some simulations, for different mass ranges\nnumpy.random.seed(3)\nnexample= 4\nmasses= [5.5,6.5,7.5,8.5]\nfor ii in range(nexample):\n # Sampling functions\n sample_GM= lambda: 10.**(masses[ii]-10.)\\\n /bovy_conversion.mass_in_1010msol(V0,R0)\n rate= dNencdm(sdf_pepper,10.**masses[ii],Xrs=Xrs,\n plummer=plummer) \n sdf_pepper.simulate(rate=rate,sample_GM=sample_GM,sample_rs=sample_rs,Xrs=Xrs)\n densOmega= numpy.array([sdf_pepper._densityAndOmega_par_approx(a) for a in apars]).T\n dens_example.append(densOmega[0])\n omega_example.append(densOmega[1])",
"_____no_output_____"
],
[
"bovy_plot.bovy_print(axes_labelsize=18.,xtick_labelsize=14.,ytick_labelsize=18.)\nfigsize(6,7)\noverplot= False\nfor ii in range(nexample):\n bovy_plot.bovy_plot(apars,dens_example[ii]/dens_unp+2.*ii+0.5*(ii>2),lw=2.5,\n color='k',\n xrange=[0.,1.3],\n yrange=[0.,2.*nexample+1],\n xlabel=r'$\\Delta \\theta_\\parallel$',\n ylabel=r'$\\mathrm{density}/\\mathrm{smooth\\ density}+\\mathrm{constant}$',\n overplot=overplot)\n plot(apars,apars*0.+1.+2.*ii+0.5*(ii>2),lw=1.5,color='k',ls='--',zorder=0)\n bovy_plot.bovy_text(1.025,1.+2.*ii+0.5*(ii>2),r'$10^{%.1f}\\,M_\\odot$' % masses[ii],verticalalignment='center',size=18.)\n overplot=True\nif save_figures:\n bovy_plot.bovy_end_print(os.path.join(os.getenv('PAPERSDIR'),'2016-stream-stats',\n 'gd1like_densexample_singlemasses.pdf'))",
"_____no_output_____"
],
[
"bovy_plot.bovy_print(axes_labelsize=18.,xtick_labelsize=14.,ytick_labelsize=18.)\nfigsize(6,7)\noverplot= False\nmult= [3.,3.,1.,1.]\nfor ii in range(nexample):\n bovy_plot.bovy_plot(apars,mult[ii]*(omega_example[ii]/omega_unp-1.)+1.+2.*ii+0.5*(ii>2),\n lw=2.5,\n color='k',\n xrange=[0.,1.3],\n yrange=[0.,2.*nexample+1.],\n xlabel=r'$\\Delta \\theta_\\parallel$',\n ylabel=r'$\\langle\\Delta \\Omega_\\parallel\\rangle\\big/\\langle\\Delta \\Omega_\\parallel^0\\rangle+\\mathrm{constant}$',\n overplot=overplot)\n plot(apars,apars*0.+1.+2.*ii+0.5*(ii>2),lw=1.5,color='k',ls='--',zorder=0)\n bovy_plot.bovy_text(1.025,1.+2.*ii+0.5*(ii>2),r'$10^{%.1f}\\,M_\\odot$' % masses[ii],verticalalignment='center',size=18.)\n bovy_plot.bovy_text(0.025,1.+2.*ii+0.1+0.5*(ii>2),r'$\\times%i$' % mult[ii],size=18.)\n overplot= True\nif save_figures:\n bovy_plot.bovy_end_print(os.path.join(os.getenv('PAPERSDIR'),'2016-stream-stats',\n 'gd1like_omegaexample_singlemasses.pdf'))",
"_____no_output_____"
]
],
[
[
"### Full mass range",
"_____no_output_____"
],
[
"First look at low apar resolution:",
"_____no_output_____"
]
],
[
[
"apars= apars[::30]\ndens_unp= dens_unp[::30]\nomega_unp= omega_unp[::30]",
"_____no_output_____"
],
[
"# Sampling functions\nmassrange=[5.,9.]\nplummer= False\nXrs= 5.\nnsubhalo= simulate_streampepper.nsubhalo\nrs= simulate_streampepper.rs\ndNencdm= simulate_streampepper.dNencdm\nsample_GM= lambda: (10.**((-0.5)*massrange[0])\\\n +(10.**((-0.5)*massrange[1])\\\n -10.**((-0.5)*massrange[0]))\\\n *numpy.random.uniform())**(1./(-0.5))\\\n /bovy_conversion.mass_in_msol(V0,R0)\nrate_range= numpy.arange(massrange[0]+0.5,massrange[1]+0.5,1)\nrate= numpy.sum([dNencdm(sdf_pepper,10.**r,Xrs=Xrs,\n plummer=plummer)\n for r in rate_range])\nsample_rs= lambda x: rs(x*bovy_conversion.mass_in_1010msol(V0,R0)*10.**10.,\n plummer=plummer)",
"_____no_output_____"
],
[
"dens_example2= []\nomega_example2= []\n# Perform some simulations\nnumpy.random.seed(3)\nnexample= 4\nfor ii in range(nexample):\n sdf_pepper.simulate(rate=rate,sample_GM=sample_GM,sample_rs=sample_rs,Xrs=Xrs)\n densOmega= numpy.array([sdf_pepper._densityAndOmega_par_approx(a) for a in apars]).T\n dens_example2.append(densOmega[0])\n omega_example2.append(densOmega[1])",
"_____no_output_____"
],
[
"bovy_plot.bovy_print(axes_labelsize=18.,xtick_labelsize=14.,ytick_labelsize=18.)\nfigsize(6,7)\noverplot= False\nfor ii in range(nexample):\n bovy_plot.bovy_plot(apars,dens_example2[ii]/dens_unp+2.*ii,lw=2.5,\n color='k',\n xrange=[0.,1.],\n yrange=[0.,2.*nexample+1.],\n xlabel=r'$\\Delta \\theta_\\parallel$',\n ylabel=r'$\\mathrm{density}/\\mathrm{smooth\\ density}+\\mathrm{constant}$',\n overplot=overplot)\n plot(apars,apars*0.+1.+2.*ii,lw=1.5,color='k',ls='--',zorder=0)\n overplot=True",
"_____no_output_____"
],
[
"bovy_plot.bovy_print(axes_labelsize=18.,xtick_labelsize=14.,ytick_labelsize=18.)\nfigsize(6,7)\noverplot= False\nfor ii in range(nexample):\n bovy_plot.bovy_plot(apars,omega_example2[ii]/omega_unp+2.*ii,lw=2.5,\n color='k',\n xrange=[0.,1.],\n yrange=[0.,2.*nexample],\n xlabel=r'$\\Delta \\theta_\\parallel$',\n ylabel=r'$\\langle\\Delta \\Omega_\\parallel\\rangle\\big/\\langle\\Delta \\Omega_\\parallel^0\\rangle+\\mathrm{constant}$',\n overplot=overplot)\n plot(apars,apars*0.+1.+2.*ii,lw=1.5,color='k',ls='--',zorder=0)\n overplot= True",
"_____no_output_____"
]
],
[
[
"At full apar resolution:",
"_____no_output_____"
]
],
[
[
"# Load our fiducial simulation's output, for apars and smooth stream\ndata= numpy.genfromtxt(os.path.join(os.getenv('DATADIR'),'streamgap-pepper','gd1_multtime',\n 'gd1_t64sampling_X5_5-9_dens.dat'),\n delimiter=',',max_rows=2)\napars= data[0]\ndens_unp= data[1]\ndata= numpy.genfromtxt(os.path.join(os.getenv('DATADIR'),'streamgap-pepper','gd1_multtime',\n 'gd1_t64sampling_X5_5-9_omega.dat'),\n delimiter=',',max_rows=2)\nomega_unp= data[1]",
"_____no_output_____"
],
[
"dens_example2= []\nomega_example2= []\n# Perform some simulations\nnumpy.random.seed(3)\nnexample= 4\nfor ii in range(nexample):\n sdf_pepper.simulate(rate=rate,sample_GM=sample_GM,sample_rs=sample_rs,Xrs=Xrs)\n densOmega= numpy.array([sdf_pepper._densityAndOmega_par_approx(a) for a in apars]).T\n dens_example2.append(densOmega[0])\n omega_example2.append(densOmega[1])",
"_____no_output_____"
],
[
"bovy_plot.bovy_print(axes_labelsize=18.,xtick_labelsize=14.,ytick_labelsize=18.)\nfigsize(6,7)\noverplot= False\nfor ii in range(nexample):\n bovy_plot.bovy_plot(apars,dens_example2[ii]/dens_unp+2.*ii,lw=2.5,\n color='k',\n xrange=[0.,1.],\n yrange=[0.,2.*nexample+1.],\n xlabel=r'$\\Delta \\theta_\\parallel$',\n ylabel=r'$\\mathrm{density}/\\mathrm{smooth\\ density}+\\mathrm{constant}$',\n overplot=overplot)\n plot(apars,apars*0.+1.+2.*ii,lw=1.5,color='k',ls='--',zorder=0)\n overplot=True\nif save_figures:\n bovy_plot.bovy_end_print(os.path.join(os.getenv('PAPERSDIR'),'2016-stream-stats','gd1like_densexample.pdf'))",
"_____no_output_____"
],
[
"bovy_plot.bovy_print(axes_labelsize=18.,xtick_labelsize=14.,ytick_labelsize=18.)\nfigsize(6,7)\noverplot= False\nfor ii in range(nexample):\n bovy_plot.bovy_plot(apars,omega_example2[ii]/omega_unp+2.*ii,lw=2.5,\n color='k',\n xrange=[0.,1.],\n yrange=[0.,2.*nexample],\n xlabel=r'$\\Delta \\theta_\\parallel$',\n ylabel=r'$\\langle\\Delta \\Omega_\\parallel\\rangle\\big/\\langle\\Delta \\Omega_\\parallel^0\\rangle+\\mathrm{constant}$',\n overplot=overplot)\n plot(apars,apars*0.+1.+2.*ii,lw=1.5,color='k',ls='--',zorder=0)\n overplot= True\nif save_figures:\n bovy_plot.bovy_end_print(os.path.join(os.getenv('PAPERSDIR'),'2016-stream-stats','gd1like_omegaexample.pdf'))",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
d0837793e2ac7a8d75e82f0fb09da9231bf657f4 | 3,602 | ipynb | Jupyter Notebook | 03 Advanced/20-basic-file-io.ipynb | MassStreetUniversity/tutorial-python | 31c164a0651bede467cbad17fa0e1942eccb9d84 | [
"MIT"
] | 1 | 2021-02-07T23:08:06.000Z | 2021-02-07T23:08:06.000Z | 03 Advanced/20-basic-file-io.ipynb | MassStreetUniversity/tutorial-python | 31c164a0651bede467cbad17fa0e1942eccb9d84 | [
"MIT"
] | null | null | null | 03 Advanced/20-basic-file-io.ipynb | MassStreetUniversity/tutorial-python | 31c164a0651bede467cbad17fa0e1942eccb9d84 | [
"MIT"
] | null | null | null | 29.52459 | 225 | 0.596891 | [
[
[
"<h1>Examples</h1>",
"_____no_output_____"
],
[
"<strong>Example #1: Move A File</strong>\n\nAKA cut and paste. Moving files is a fast operation because we are just changing a pointer to the ones and zeros to point to something else. We are not actually pushing bits around disk to make the move happen.\n\nThe module shutil is filled with all kinds of file handling goodies.\n\nIn the root of the example directory is a small file. While it is in the root folder, it is simulating being outside the boundaries of the data warehouse environment. Let’s bring it inside by moving it to the In folder.",
"_____no_output_____"
]
],
[
[
"import shutil as sh\nimport os\n\nif not 'script_dir' in globals():\n script_dir = os.getcwd()\n \ndata_directory = 'data\\\\'\nexample_directory = 'BasicFileOpsExample\\\\'\ntarget_directory = 'In\\\\'\nfile_name = 'forestfires.csv'\n\nsource_path = os.path.join(script_dir,data_directory,example_directory,file_name)\ntarget_path = os.path.join(script_dir,data_directory,example_directory,target_directory,file_name)\n\nsh.move(source_path, target_path)",
"_____no_output_____"
]
],
[
[
"<strong>Example #2: Archiving A File</strong>\n\nWe are now done processing the file and we need to archive it in case we need to drag it out and reload the system. \n\nThe process of archiving is multi step.\n<ol>\n<li> Zip up the file.</li><br>\n<li> Move the file to the Archive folder.</li><br>\n<li> Blow away the original.</li><br>\n</ol>\n\nOnce you run the example, check the Archive folder and the In folder. You should see a zip file in Archive and nothing in the In folder.",
"_____no_output_____"
]
],
[
[
"import zipfile as zf\nimport os\n\nif not 'script_dir' in globals():\n script_dir = os.getcwd()\n \ndata_directory = 'data\\\\'\nexample_directory = 'BasicFileOpsExample\\\\'\nsource_directory = 'In\\\\'\ntarget_directory = 'Archive\\\\'\nfile_name = 'forestfires.csv'\narchive_name = 'forestfires.zip'\n\ntarget_path = os.path.join(script_dir,data_directory,example_directory,target_directory,archive_name)\nsource_path = os.path.join(data_directory,example_directory,source_directory)\n\narchive = zf.ZipFile(target_path, \"w\")\nos.chdir(source_path)\narchive.write(file_name)\narchive.close()",
"_____no_output_____"
]
],
[
[
"Copyright © 2020, Mass Street Analytics, LLC. All Rights Reserved.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
d083806dea134e987df1759367e7471581f3a33b | 4,246 | ipynb | Jupyter Notebook | day4/04. Scipy - Exercises.ipynb | ubutnux/bosscha-python-workshop-2022 | 6a146bae4a4d3d5f1ba797140ec3271a884167f3 | [
"Unlicense"
] | null | null | null | day4/04. Scipy - Exercises.ipynb | ubutnux/bosscha-python-workshop-2022 | 6a146bae4a4d3d5f1ba797140ec3271a884167f3 | [
"Unlicense"
] | null | null | null | day4/04. Scipy - Exercises.ipynb | ubutnux/bosscha-python-workshop-2022 | 6a146bae4a4d3d5f1ba797140ec3271a884167f3 | [
"Unlicense"
] | null | null | null | 31.924812 | 315 | 0.53886 | [
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy as sp",
"_____no_output_____"
]
],
[
[
"# Exercises",
"_____no_output_____"
],
[
"## Q 1\n\nThe energy required to get from point $\\vec{r}_1$ to point $\\vec{r}_2$ for a plane is given by\n\n$$ E = \\alpha \\int_{C} \\left| \\frac{d\\vec{r}}{dt} \\right| dt - \\int_C \\vec{F} \\cdot \\frac{d\\vec{r}}{dt}dt $$\n\nSuppose that $\\alpha=5$ and our start and ends points are $\\vec{r}_1 = (0,0)$ and $\\vec{r}_2 = (0, 10)$. On this particular day, the wind produces a force field $\\vec{F} = (0, -2/(x+1)^2)$. Find the optimal value of $A$ in $\\vec{r}(t) = A\\sin(\\pi t/10)\\hat{x} + t\\hat{y}$ that minimizes the work. \n\nThen $x=A\\sin(\\pi t/10)$, $y=t$, and\n\n$$\\left| \\frac{d\\vec{r}}{dt} \\right| = \\sqrt{1+(\\pi A /10)^2 \\cos^2(\\pi t/10)}$$\n\n$$\\vec{F} \\cdot d\\vec{r} = \\begin{bmatrix} 0 \\\\ -2/(A\\sin(\\pi t/10) +1)^2\\\\ \\end{bmatrix} \\cdot \\begin{bmatrix} \\pi A/10 \\cos(\\pi t/10)\\\\ 1\\\\ \\end{bmatrix} = -2/(A\\sin(\\pi t/10) +1)^2 $$\n\nso that\n\n$$ E = \\int_{0}^{10} \\left(5\\sqrt{1+(\\pi A /10)^2 \\cos^2(\\pi t/10)} + \\frac{2}{(A\\sin(\\pi t/10) +100)^2} \\right) dt$$",
"_____no_output_____"
],
[
"## Q2\n\nNewton's law of cooling is\n\n$$\\frac{dT}{dt} = -k(T-T_s(t)) $$\n\nwhere $T$ is the temperature of an object in the surroundings with temperature $T_s(t)$ (which may depend on time). Suppose $T$ represents the temperature of a shallow pool of water and $T_s(t)$ represents the temperature of outside. Find $T(t)$ given that you collected measurements of the outside:\n\n\n",
"_____no_output_____"
]
],
[
[
"t_m = np.array([ 0., 1.04347826, 2.08695652, 3.13043478, 4.17391304,\n 5.2173913 , 6.26086957, 7.30434783, 8.34782609, 9.39130435,\n 10.43478261, 11.47826087, 12.52173913, 13.56521739, 14.60869565,\n 15.65217391, 16.69565217, 17.73913043, 18.7826087 , 19.82608696,\n 20.86956522, 21.91304348, 22.95652174, 24. ])\n\ntemp_m = np.array([283.2322975, 284.6945461, 286.2259041, 287.8603625, 289.6440635,\n 291.6187583, 293.7939994, 296.1148895, 298.4395788, 300.5430675,\n 302.1566609, 303.0363609, 303.0363609, 302.1566609, 300.5430675,\n 298.4395788, 296.1148895, 293.7939994, 291.6187583, 289.6440635,\n 287.8603625, 286.2259041, 284.6945461, 283.2322975])",
"_____no_output_____"
],
[
"times = np.linspace(1, 23, 1000)\nT0 = 284.6945461",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
d083830b2f91beee8e25a5d2a148b91cc6d89a3a | 989,605 | ipynb | Jupyter Notebook | plots_notebooks/SurfaceSnapshots_2km.ipynb | aramirezreyes/RamirezReyes_Yang_2020_SpontaneousCyclogenesis | 4980124ca04f8b7883138f8ea411d7aac9b593aa | [
"MIT"
] | null | null | null | plots_notebooks/SurfaceSnapshots_2km.ipynb | aramirezreyes/RamirezReyes_Yang_2020_SpontaneousCyclogenesis | 4980124ca04f8b7883138f8ea411d7aac9b593aa | [
"MIT"
] | null | null | null | plots_notebooks/SurfaceSnapshots_2km.ipynb | aramirezreyes/RamirezReyes_Yang_2020_SpontaneousCyclogenesis | 4980124ca04f8b7883138f8ea411d7aac9b593aa | [
"MIT"
] | null | null | null | 4,193.241525 | 981,738 | 0.96099 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
d083a84e96157cc65b2758bf1dd2482eb8eb0fe6 | 255,843 | ipynb | Jupyter Notebook | docs/tutorials/time_series/fmri_analysis.ipynb | RebeccaYin7/hyppo | fc01775d2253930e095032efd051373148dce58f | [
"Apache-2.0"
] | null | null | null | docs/tutorials/time_series/fmri_analysis.ipynb | RebeccaYin7/hyppo | fc01775d2253930e095032efd051373148dce58f | [
"Apache-2.0"
] | null | null | null | docs/tutorials/time_series/fmri_analysis.ipynb | RebeccaYin7/hyppo | fc01775d2253930e095032efd051373148dce58f | [
"Apache-2.0"
] | null | null | null | 770.611446 | 126,652 | 0.946827 | [
[
[
"import numpy as np\nimport nibabel.cifti2 as ci\nfrom itertools import product\nfrom joblib import Parallel, delayed\nimport pickle\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom graspy.plot import heatmap\n%matplotlib inline\n\nfrom hyppo.time_series import MGCX",
"/Users/ronak/miniconda3/envs/mgc/lib/python3.7/site-packages/statsmodels/tools/_testing.py:19: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.\n import pandas.util.testing as tm\n"
]
],
[
[
"## Look At It",
"_____no_output_____"
]
],
[
[
"# Load image - individual 100307.\nimg = ci.load(\"fmri_data/rfMRI_REST1_LR_Atlas_hp2000_clean_filt_sm6.HCPMMP.ptseries.nii\")\nfmri_data = np.array(img.get_fdata())",
"_____no_output_____"
],
[
"# Visualize data, i.e. inspect the first 60 timesteps of each parcel.\n\n# Generate heatmap.\ntimesteps = 60\ndisplayed_data = np.transpose(fmri_data[range(timesteps),:])\nplt.subplots(figsize=(15,10))\nax = sns.heatmap(displayed_data, yticklabels=False)\n\n# Plot parameters.\nplt.title('Resting fMRI Signal by Parcel - Individual 100307 LR', fontsize = 20)\nplt.ylabel('Parcel', fontsize = 15)\nplt.xlabel('Timestep', fontsize = 15)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Set Up Hyperparameters",
"_____no_output_____"
]
],
[
[
"# From Ting: Regions-of-Interest (ROIs)\nroi_keys = np.array([1, 23, 18, 53, 24, 96, 117, 50, 143, 109, 148, 60, 38, 135, 93, 83, 149, 150, 65, 161, 132, 71]) - 1\nroi_labels = np.array([\n \"Visual\",\n \"Visual\",\n \"Visual\",\n \"SM\",\n \"SM\",\n \"dAtt\",\n \"dAtt\",\n \"dAtt\",\n \"dAtt\",\n \"vAtt\",\n \"vAtt\",\n \"vAtt\",\n \"vAtt\",\n \"Limbic\",\n \"Limbic\",\n \"FP\",\n \"FP\",\n \"DMN\",\n \"DMN\",\n \"DMN\",\n \"DMN\",\n \"DMN\",\n])\n\nroi_data = fmri_data[0:300, roi_keys]\nnum_roi = len(roi_keys)",
"_____no_output_____"
],
[
"# Hyperparameters\nmax_lag = 1 # number of lags to check in the past\nreps = 1000 # number of bootstrap replicates\nworkers = 1 # number of workers in internal MGC parallelization",
"_____no_output_____"
],
[
"# Subsample to test experiment.\n# pairs = list(product(range(num_roi), repeat = 2)) # Fake param for testing.\npairs = list(product(range(num_roi), repeat = 2))",
"_____no_output_____"
]
],
[
[
"## Run Experiment",
"_____no_output_____"
]
],
[
[
"mgcx = MGCX(max_lag = max_lag)\n\ndef worker(i, j):\n X = roi_data[:, i]\n Y = roi_data[:, j]\n \n stat, pval, mgcx_dict = mgcx.test(X, Y, reps = reps, workers = workers)\n opt_lag = mgcx_dict['opt_lag']\n opt_scale_x, opt_scale_y = mgcx_dict['opt_scale']\n \n return stat, pval, opt_lag, opt_scale_x, opt_scale_y\n\noutput = np.array(Parallel(n_jobs=-2)(delayed(worker)(i, j) for i, j in pairs))\npickle.dump(output, open('fmri_data/mgcx_fmri_output.pkl', 'wb'))",
"_____no_output_____"
],
[
"# Load results into num_roi-by-num_roi matrices.\nresults = pickle.load(open('fmri_data/mgcx_fmri_output.pkl', 'rb'))\ntest_outputs = ['stat', 'pval', 'opt_lag', 'opt_scale_x', 'opt_scale_y']\n\nmatrices = np.zeros((len(test_outputs), num_roi, num_roi))\nfor p, pair in enumerate(pairs):\n i, j = pair\n for t in range(len(test_outputs)):\n matrices[t, i, j] = results[p, t]\n \nfor t, test_output in enumerate(test_outputs):\n pickle.dump(matrices[t], open('fmri_data/%s_matrix.pkl' % test_output, 'wb'))",
"_____no_output_____"
]
],
[
[
"## Visualize Matrices",
"_____no_output_____"
]
],
[
[
"def plot_heatmap(matrix, labels, title, filename):\n# sns.set()\n cmap = mpl.cm.get_cmap('Purples')\n cc = np.linspace(0, 1, 256)\n cmap = mpl.colors.ListedColormap(cmap(cc))\n\n heatmap_kws = dict(\n cbar=False,\n font_scale=1.4,\n inner_hier_labels=labels,\n hier_label_fontsize=20,\n cmap=cmap,\n center=None,\n )\n side_label_kws = dict(labelpad=45, fontsize=24)\n\n fig, ax = plt.subplots(1, 1, figsize=(20, 16))\n\n # Plot heatmap via graspy.\n heatmap(matrix, ax=ax, **heatmap_kws)\n ax.set_title(title, pad = 100, fontdict = {'fontsize' : 23})\n \n # Create ticks.\n num_ticks = 8\n top_val = np.max(matrix)\n ticks = [i * np.max(matrix) / num_ticks for i in range(num_ticks+1)]\n yticks = [('%.2f' % np.round(10 ** -p, 2)) for p in ticks]\n\n # Add colorbar.\n sm = plt.cm.ScalarMappable(cmap=cmap)\n sm.set_array(matrix)\n cbar = fig.colorbar(sm, ax=ax, fraction=0.0475, pad=-0.1, ticks=ticks)\n cbar.ax.set_yticklabels(yticks)\n cbar.ax.tick_params(labelsize=25)\n\n plt.savefig(\n \"%s.pdf\" % filename,\n facecolor=\"w\",\n format=\"pdf\",\n bbox_inches=\"tight\",\n )\n\n plt.tight_layout()\n plt.show()",
"_____no_output_____"
]
],
[
[
"### p-value Matrix",
"_____no_output_____"
]
],
[
[
"# Apply negative log10 transform.\n# matrix = pickle.load(open('fmri_data/pval_matrix.pkl', 'rb'))\n# matrix = -np.log10(matrix)\n# pickle.dump(matrix, open('fmri_data/nl10_pval_matrix.pkl', 'wb'))",
"_____no_output_____"
],
[
"matrix = pickle.load(open('fmri_data/nl10_pval_matrix.pkl', 'rb'))\nplot_heatmap(matrix, roi_labels, 'p-Value', 'pval')",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
d083b3132fd6a4b90610170632e7e819e017f7a4 | 43,707 | ipynb | Jupyter Notebook | jupyter/bilinear/bilinear2.ipynb | scorrea92/computer_vision | e5022d14a81cacaaf28a414b0e2c457e284a0915 | [
"Apache-2.0"
] | null | null | null | jupyter/bilinear/bilinear2.ipynb | scorrea92/computer_vision | e5022d14a81cacaaf28a414b0e2c457e284a0915 | [
"Apache-2.0"
] | null | null | null | jupyter/bilinear/bilinear2.ipynb | scorrea92/computer_vision | e5022d14a81cacaaf28a414b0e2c457e284a0915 | [
"Apache-2.0"
] | null | null | null | 53.760148 | 271 | 0.51875 | [
[
[
"!nvidia-smi",
"Mon May 14 17:22:41 2018 \r\n+-----------------------------------------------------------------------------+\r\n| NVIDIA-SMI 384.111 Driver Version: 384.111 |\r\n|-------------------------------+----------------------+----------------------+\r\n| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |\r\n| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |\r\n|===============================+======================+======================|\r\n| 0 GeForce GTX TIT... Off | 00000000:05:00.0 Off | N/A |\r\n| 0% 44C P0 60W / 250W | 0MiB / 12205MiB | 0% Default |\r\n+-------------------------------+----------------------+----------------------+\r\n \r\n+-----------------------------------------------------------------------------+\r\n| Processes: GPU Memory |\r\n| GPU PID Type Process name Usage |\r\n|=============================================================================|\r\n| No running processes found |\r\n+-----------------------------------------------------------------------------+\r\n"
],
[
"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nimport keras\nfrom keras.datasets import cifar10\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten, Lambda\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.layers.normalization import BatchNormalization as BN\nfrom keras.layers import GaussianNoise as GN\nfrom keras.optimizers import SGD, Adam, RMSprop\nfrom keras.models import Model\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom keras.callbacks import LearningRateScheduler as LRS\nfrom keras.preprocessing.image import ImageDataGenerator\n\n\nbatch_size = 32\nnum_classes = 20\nepochs = 50\n\n#### LOAD AND TRANSFORM\n\n# ## Download: ONLY ONCE!\n# !wget https://www.dropbox.com/s/kdhn10jwj99xkv7/data.tgz\n# !tar xvzf data.tgz\n# #####\n\n\n# Load \nx_train = np.load('x_train.npy')\nx_test = np.load('x_test.npy')\n\ny_train = np.load('y_train.npy')\ny_test = np.load('y_test.npy')\n\n# Stats\nprint(x_train.shape)\nprint(y_train.shape)\n\nprint(x_test.shape)\nprint(y_test.shape)\n\n## View some images\nplt.imshow(x_train[2,:,:,: ] )\nplt.show()\n\n\n## Transforms\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\n\ny_train = y_train.astype('float32')\ny_test = y_test.astype('float32')\n\n\nx_train /= 255\nx_test /= 255\n\n\n## Labels\ny_train=y_train-1\n\ny_test=y_test-1\n\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\n",
"/home/secorec/anaconda3/envs/env/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n from ._conv import register_converters as _register_converters\nUsing TensorFlow backend.\n"
],
[
"from keras.applications.vgg16 import VGG16\nfrom keras.callbacks import ModelCheckpoint\n\n# load the model\nmodel1 = VGG16(weights='imagenet', include_top=False, input_shape=x_train.shape[1:])\n\n#############################\n### BILINEAR ####\n#############################\n\n# No entrenar la VGG\nfor layer in model1.layers:\n layer.trainable = False\n\ndef outer_product(x):\n phi_I = tf.einsum('ijkm,ijkn->imn',x[0],x[1])\t\t# Einstein Notation [batch,1,1,depth] x [batch,1,1,depth] -> [batch,depth,depth]\n phi_I = tf.reshape(phi_I,[-1,512*512])\t # Reshape from [batch_size,depth,depth] to [batch_size, depth*depth]\n phi_I = tf.divide(phi_I,31*31)\t\t\t\t\t\t\t\t # Divide by feature map size [sizexsize]\n\n y_ssqrt = tf.multiply(tf.sign(phi_I),tf.sqrt(tf.abs(phi_I)+1e-12))\t\t# Take signed square root of phi_I\n z_l2 = tf.nn.l2_normalize(y_ssqrt, dim=1)\t\t\t\t\t\t\t\t # Apply l2 normalization\n return z_l2\n\n\n\nconv=model1.get_layer('block4_conv3') # block4_conv3\nd1=Dropout(0.5)(conv.output) ## Why??\nd2=Dropout(0.5)(conv.output) ## Why??\n\nx = Lambda(outer_product, name='outer_product')([d1,d2])\npredictions=Dense(num_classes, activation='softmax', name='predictions')(x)\n\n#layer_x=Dense(256, activation='relu', name='midle_layer')(x)\n#predictions=Dense(num_classes, activation='softmax', name='predictions')(layer_x)\n\nmodel = Model(inputs=model1.input, outputs=predictions)\n\n\n# DEFINE A LEARNING RATE SCHEDULER\ndef scheduler(epoch):\n if epoch < 25:\n return 0.0001\n elif epoch < 50:\n return 0.00001\n else:\n return 0.000001\n\nset_lr = LRS(scheduler)\n\n\n## DATAGEN\ndatagen = ImageDataGenerator(\n width_shift_range=0.2,\n height_shift_range=0.2,\n rotation_range=20,\n zoom_range=[1.0,1.2],\n horizontal_flip=True)\n\n\n## OPTIM AND COMPILE use Adam Rsmprop\nopt = SGD(lr=0.0001, decay=1e-6)\nrms = RMSprop(lr=0.001, rho=0.9, epsilon=None, decay=0.0)\nadam = Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=1e-6, amsgrad=False)\n\nmodel.compile(loss='categorical_crossentropy',\n optimizer=rms,\n metrics=['accuracy'])\n \n \nmodel.summary()\n\ncheckpoint_path = \"Wehigts.hdf5\"\ncheckpointer = ModelCheckpoint(filepath=checkpoint_path, verbose=1, save_best_only=True)\n\n## TRAINING with DA and LRA\nhistory=model.fit_generator(datagen.flow(x_train, y_train,batch_size=batch_size),\n steps_per_epoch=len(x_train) / batch_size, \n epochs=epochs,\n validation_data=(x_test, y_test),\n callbacks=[checkpointer],\n verbose=1)",
"__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_4 (InputLayer) (None, 250, 250, 3) 0 \n__________________________________________________________________________________________________\nblock1_conv1 (Conv2D) (None, 250, 250, 64) 1792 input_4[0][0] \n__________________________________________________________________________________________________\nblock1_conv2 (Conv2D) (None, 250, 250, 64) 36928 block1_conv1[0][0] \n__________________________________________________________________________________________________\nblock1_pool (MaxPooling2D) (None, 125, 125, 64) 0 block1_conv2[0][0] \n__________________________________________________________________________________________________\nblock2_conv1 (Conv2D) (None, 125, 125, 128 73856 block1_pool[0][0] \n__________________________________________________________________________________________________\nblock2_conv2 (Conv2D) (None, 125, 125, 128 147584 block2_conv1[0][0] \n__________________________________________________________________________________________________\nblock2_pool (MaxPooling2D) (None, 62, 62, 128) 0 block2_conv2[0][0] \n__________________________________________________________________________________________________\nblock3_conv1 (Conv2D) (None, 62, 62, 256) 295168 block2_pool[0][0] \n__________________________________________________________________________________________________\nblock3_conv2 (Conv2D) (None, 62, 62, 256) 590080 block3_conv1[0][0] \n__________________________________________________________________________________________________\nblock3_conv3 (Conv2D) (None, 62, 62, 256) 590080 block3_conv2[0][0] \n__________________________________________________________________________________________________\nblock3_pool (MaxPooling2D) (None, 31, 31, 256) 0 block3_conv3[0][0] \n__________________________________________________________________________________________________\nblock4_conv1 (Conv2D) (None, 31, 31, 512) 1180160 block3_pool[0][0] \n__________________________________________________________________________________________________\nblock4_conv2 (Conv2D) (None, 31, 31, 512) 2359808 block4_conv1[0][0] \n__________________________________________________________________________________________________\nblock4_conv3 (Conv2D) (None, 31, 31, 512) 2359808 block4_conv2[0][0] \n__________________________________________________________________________________________________\ndropout_7 (Dropout) (None, 31, 31, 512) 0 block4_conv3[0][0] \n__________________________________________________________________________________________________\ndropout_8 (Dropout) (None, 31, 31, 512) 0 block4_conv3[0][0] \n__________________________________________________________________________________________________\nouter_product (Lambda) (None, 262144) 0 dropout_7[0][0] \n dropout_8[0][0] \n__________________________________________________________________________________________________\npredictions (Dense) (None, 20) 5242900 outer_product[0][0] \n==================================================================================================\nTotal params: 12,878,164\nTrainable params: 5,242,900\nNon-trainable params: 7,635,264\n__________________________________________________________________________________________________\nEpoch 1/50\n25/24 [==============================] - 15s 591ms/step - loss: 3.0216 - acc: 0.0588 - val_loss: 2.9115 - val_acc: 0.1212\n\nEpoch 00001: val_loss improved from inf to 2.91153, saving model to Wehigts.hdf5\nEpoch 2/50\n25/24 [==============================] - 10s 415ms/step - loss: 2.8644 - acc: 0.1394 - val_loss: 2.8080 - val_acc: 0.1543\n\nEpoch 00002: val_loss improved from 2.91153 to 2.80803, saving model to Wehigts.hdf5\nEpoch 3/50\n25/24 [==============================] - 10s 414ms/step - loss: 2.7487 - acc: 0.1976 - val_loss: 2.7567 - val_acc: 0.1811\n\nEpoch 00003: val_loss improved from 2.80803 to 2.75669, saving model to Wehigts.hdf5\nEpoch 4/50\n25/24 [==============================] - 10s 415ms/step - loss: 2.6594 - acc: 0.2379 - val_loss: 2.6752 - val_acc: 0.2181\n\nEpoch 00004: val_loss improved from 2.75669 to 2.67515, saving model to Wehigts.hdf5\nEpoch 5/50\n25/24 [==============================] - 10s 414ms/step - loss: 2.5644 - acc: 0.2767 - val_loss: 2.6094 - val_acc: 0.2819\n\nEpoch 00005: val_loss improved from 2.67515 to 2.60942, saving model to Wehigts.hdf5\nEpoch 6/50\n25/24 [==============================] - 10s 417ms/step - loss: 2.4933 - acc: 0.3219 - val_loss: 2.5738 - val_acc: 0.1926\n\nEpoch 00006: val_loss improved from 2.60942 to 2.57379, saving model to Wehigts.hdf5\nEpoch 7/50\n25/24 [==============================] - 10s 417ms/step - loss: 2.4073 - acc: 0.3766 - val_loss: 2.5290 - val_acc: 0.2564\n\nEpoch 00007: val_loss improved from 2.57379 to 2.52899, saving model to Wehigts.hdf5\nEpoch 8/50\n25/24 [==============================] - 11s 420ms/step - loss: 2.3523 - acc: 0.3936 - val_loss: 2.4636 - val_acc: 0.3061\n\nEpoch 00008: val_loss improved from 2.52899 to 2.46359, saving model to Wehigts.hdf5\nEpoch 9/50\n25/24 [==============================] - 10s 419ms/step - loss: 2.2759 - acc: 0.4279 - val_loss: 2.4409 - val_acc: 0.2717\n\nEpoch 00009: val_loss improved from 2.46359 to 2.44089, saving model to Wehigts.hdf5\nEpoch 10/50\n25/24 [==============================] - 11s 423ms/step - loss: 2.2168 - acc: 0.4549 - val_loss: 2.3716 - val_acc: 0.3431\n\nEpoch 00010: val_loss improved from 2.44089 to 2.37157, saving model to Wehigts.hdf5\nEpoch 11/50\n25/24 [==============================] - 10s 418ms/step - loss: 2.1517 - acc: 0.4630 - val_loss: 2.3164 - val_acc: 0.3406\n\nEpoch 00011: val_loss improved from 2.37157 to 2.31636, saving model to Wehigts.hdf5\nEpoch 12/50\n25/24 [==============================] - 10s 418ms/step - loss: 2.0941 - acc: 0.5109 - val_loss: 2.3005 - val_acc: 0.3444\n\nEpoch 00012: val_loss improved from 2.31636 to 2.30054, saving model to Wehigts.hdf5\nEpoch 13/50\n25/24 [==============================] - 10s 416ms/step - loss: 2.0337 - acc: 0.5207 - val_loss: 2.2462 - val_acc: 0.3673\n\nEpoch 00013: val_loss improved from 2.30054 to 2.24619, saving model to Wehigts.hdf5\nEpoch 14/50\n25/24 [==============================] - 11s 421ms/step - loss: 1.9767 - acc: 0.5276 - val_loss: 2.2661 - val_acc: 0.3227\n\nEpoch 00014: val_loss did not improve\nEpoch 15/50\n25/24 [==============================] - 10s 419ms/step - loss: 1.9388 - acc: 0.5607 - val_loss: 2.1590 - val_acc: 0.4184\n\nEpoch 00015: val_loss improved from 2.24619 to 2.15904, saving model to Wehigts.hdf5\nEpoch 16/50\n25/24 [==============================] - 11s 422ms/step - loss: 1.8921 - acc: 0.5692 - val_loss: 2.1414 - val_acc: 0.3967\n\nEpoch 00016: val_loss improved from 2.15904 to 2.14144, saving model to Wehigts.hdf5\nEpoch 17/50\n25/24 [==============================] - 10s 417ms/step - loss: 1.8428 - acc: 0.5881 - val_loss: 2.1495 - val_acc: 0.3622\n\nEpoch 00017: val_loss did not improve\nEpoch 18/50\n25/24 [==============================] - 11s 423ms/step - loss: 1.7921 - acc: 0.6067 - val_loss: 2.1015 - val_acc: 0.4184\n\nEpoch 00018: val_loss improved from 2.14144 to 2.10148, saving model to Wehigts.hdf5\nEpoch 19/50\n25/24 [==============================] - 11s 421ms/step - loss: 1.7499 - acc: 0.6248 - val_loss: 2.0982 - val_acc: 0.3967\n\nEpoch 00019: val_loss improved from 2.10148 to 2.09821, saving model to Wehigts.hdf5\nEpoch 20/50\n"
],
[
"#Usar Checpoint mejor de ejecución\nmodel.load_weights(checkpoint_path)\nfor j, layer in enumerate(model1.layers):\n layer.trainable = True\n #if j <14:\n # if \"conv\" in layer.name:\n # layer.trainable = True\n \n#Compile y ejecutar de nuevo\n#rms = RMSprop(lr=0.0001, rho=0.9, epsilon=None, decay=0.0)\n#adam = Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=1e-6, amsgrad=False)\n\nmodel.compile(loss='categorical_crossentropy',\n optimizer=rms,\n metrics=['accuracy'])\n \n \nmodel.summary()\n\ncheckpoint_path = \"Wehigts_final.hdf5\"\ncheckpointer = ModelCheckpoint(filepath=checkpoint_path, verbose=1, save_best_only=True)\n\n## TRAINING with DA and LRA\nhistory=model.fit_generator(datagen.flow(x_train, y_train,batch_size=batch_size),\n steps_per_epoch=len(x_train) / batch_size, \n epochs=epochs,\n validation_data=(x_test, y_test),\n callbacks=[checkpointer],\n verbose=1)\n",
"__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_3 (InputLayer) (None, 250, 250, 3) 0 \n__________________________________________________________________________________________________\nblock1_conv1 (Conv2D) (None, 250, 250, 64) 1792 input_3[0][0] \n__________________________________________________________________________________________________\nblock1_conv2 (Conv2D) (None, 250, 250, 64) 36928 block1_conv1[0][0] \n__________________________________________________________________________________________________\nblock1_pool (MaxPooling2D) (None, 125, 125, 64) 0 block1_conv2[0][0] \n__________________________________________________________________________________________________\nblock2_conv1 (Conv2D) (None, 125, 125, 128 73856 block1_pool[0][0] \n__________________________________________________________________________________________________\nblock2_conv2 (Conv2D) (None, 125, 125, 128 147584 block2_conv1[0][0] \n__________________________________________________________________________________________________\nblock2_pool (MaxPooling2D) (None, 62, 62, 128) 0 block2_conv2[0][0] \n__________________________________________________________________________________________________\nblock3_conv1 (Conv2D) (None, 62, 62, 256) 295168 block2_pool[0][0] \n__________________________________________________________________________________________________\nblock3_conv2 (Conv2D) (None, 62, 62, 256) 590080 block3_conv1[0][0] \n__________________________________________________________________________________________________\nblock3_conv3 (Conv2D) (None, 62, 62, 256) 590080 block3_conv2[0][0] \n__________________________________________________________________________________________________\nblock3_pool (MaxPooling2D) (None, 31, 31, 256) 0 block3_conv3[0][0] \n__________________________________________________________________________________________________\nblock4_conv1 (Conv2D) (None, 31, 31, 512) 1180160 block3_pool[0][0] \n__________________________________________________________________________________________________\nblock4_conv2 (Conv2D) (None, 31, 31, 512) 2359808 block4_conv1[0][0] \n__________________________________________________________________________________________________\nblock4_conv3 (Conv2D) (None, 31, 31, 512) 2359808 block4_conv2[0][0] \n__________________________________________________________________________________________________\ndropout_5 (Dropout) (None, 31, 31, 512) 0 block4_conv3[0][0] \n__________________________________________________________________________________________________\ndropout_6 (Dropout) (None, 31, 31, 512) 0 block4_conv3[0][0] \n__________________________________________________________________________________________________\nouter_product (Lambda) (None, 262144) 0 dropout_5[0][0] \n dropout_6[0][0] \n__________________________________________________________________________________________________\npredictions (Dense) (None, 20) 5242900 outer_product[0][0] \n==================================================================================================\nTotal params: 12,878,164\nTrainable params: 12,878,164\nNon-trainable params: 0\n__________________________________________________________________________________________________\nEpoch 1/50\n25/24 [==============================] - 20s 790ms/step - loss: 0.4804 - acc: 0.8890 - val_loss: 0.9302 - val_acc: 0.7028\n\nEpoch 00001: val_loss improved from inf to 0.93024, saving model to Wehigts_final.hdf5\nEpoch 2/50\n25/24 [==============================] - 19s 753ms/step - loss: 0.2952 - acc: 0.9458 - val_loss: 0.8691 - val_acc: 0.7054\n\nEpoch 00002: val_loss improved from 0.93024 to 0.86914, saving model to Wehigts_final.hdf5\nEpoch 3/50\n25/24 [==============================] - 19s 757ms/step - loss: 0.2605 - acc: 0.9565 - val_loss: 0.9464 - val_acc: 0.6875\n\nEpoch 00003: val_loss did not improve\nEpoch 4/50\n25/24 [==============================] - 19s 759ms/step - loss: 0.2508 - acc: 0.9440 - val_loss: 0.8139 - val_acc: 0.7538\n\nEpoch 00004: val_loss improved from 0.86914 to 0.81394, saving model to Wehigts_final.hdf5\nEpoch 5/50\n25/24 [==============================] - 19s 763ms/step - loss: 0.2073 - acc: 0.9662 - val_loss: 0.9291 - val_acc: 0.6926\n\nEpoch 00005: val_loss did not improve\nEpoch 6/50\n25/24 [==============================] - 20s 781ms/step - loss: 0.1905 - acc: 0.9687 - val_loss: 0.8486 - val_acc: 0.7168\n\nEpoch 00006: val_loss did not improve\nEpoch 7/50\n25/24 [==============================] - 19s 774ms/step - loss: 0.1984 - acc: 0.9503 - val_loss: 0.8494 - val_acc: 0.7334\n\nEpoch 00007: val_loss did not improve\nEpoch 8/50\n25/24 [==============================] - 19s 774ms/step - loss: 0.1527 - acc: 0.9698 - val_loss: 0.9461 - val_acc: 0.7181\n\nEpoch 00008: val_loss did not improve\nEpoch 9/50\n25/24 [==============================] - 19s 774ms/step - loss: 0.1530 - acc: 0.9708 - val_loss: 0.8652 - val_acc: 0.7411\n\nEpoch 00009: val_loss did not improve\nEpoch 10/50\n25/24 [==============================] - 19s 774ms/step - loss: 0.1215 - acc: 0.9745 - val_loss: 0.9740 - val_acc: 0.7015\n\nEpoch 00010: val_loss did not improve\nEpoch 11/50\n25/24 [==============================] - 19s 776ms/step - loss: 0.1399 - acc: 0.9700 - val_loss: 0.8735 - val_acc: 0.7309\n\nEpoch 00011: val_loss did not improve\nEpoch 12/50\n25/24 [==============================] - 19s 776ms/step - loss: 0.1020 - acc: 0.9750 - val_loss: 0.9253 - val_acc: 0.7245\n\nEpoch 00012: val_loss did not improve\nEpoch 13/50\n25/24 [==============================] - 19s 774ms/step - loss: 0.0704 - acc: 0.9900 - val_loss: 1.3678 - val_acc: 0.6339\n\nEpoch 00013: val_loss did not improve\nEpoch 14/50\n25/24 [==============================] - 19s 775ms/step - loss: 0.1070 - acc: 0.9775 - val_loss: 0.8930 - val_acc: 0.7526\n\nEpoch 00014: val_loss did not improve\nEpoch 15/50\n25/24 [==============================] - 19s 773ms/step - loss: 0.0994 - acc: 0.9803 - val_loss: 1.0338 - val_acc: 0.6901\n\nEpoch 00015: val_loss did not improve\nEpoch 16/50\n25/24 [==============================] - 19s 773ms/step - loss: 0.0884 - acc: 0.9800 - val_loss: 1.0753 - val_acc: 0.6735\n\nEpoch 00016: val_loss did not improve\nEpoch 17/50\n25/24 [==============================] - 19s 774ms/step - loss: 0.0722 - acc: 0.9850 - val_loss: 1.0844 - val_acc: 0.7015\n\nEpoch 00017: val_loss did not improve\nEpoch 18/50\n25/24 [==============================] - 19s 774ms/step - loss: 0.0862 - acc: 0.9800 - val_loss: 1.0449 - val_acc: 0.6964\n\nEpoch 00018: val_loss did not improve\nEpoch 19/50\n25/24 [==============================] - 19s 774ms/step - loss: 0.1245 - acc: 0.9675 - val_loss: 0.9194 - val_acc: 0.7321\n\nEpoch 00019: val_loss did not improve\nEpoch 20/50\n25/24 [==============================] - 20s 787ms/step - loss: 0.0526 - acc: 0.9858 - val_loss: 1.3824 - val_acc: 0.6020\n\nEpoch 00020: val_loss did not improve\nEpoch 21/50\n25/24 [==============================] - 19s 774ms/step - loss: 0.0517 - acc: 0.9850 - val_loss: 1.1712 - val_acc: 0.6633\n\nEpoch 00021: val_loss did not improve\nEpoch 22/50\n25/24 [==============================] - 19s 775ms/step - loss: 0.0716 - acc: 0.9862 - val_loss: 1.0186 - val_acc: 0.7283\n\nEpoch 00022: val_loss did not improve\nEpoch 23/50\n25/24 [==============================] - 19s 774ms/step - loss: 0.0584 - acc: 0.9837 - val_loss: 1.0126 - val_acc: 0.7372\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code"
]
] |
d083d42eab602a086d6e46d272c2582094bd033b | 10,850 | ipynb | Jupyter Notebook | notebooks/Buffered Text-to-Speech.ipynb | Hallvardd/ttm4115-project | 8ac231b71690110985c17518883c8cd2bf01feb1 | [
"MIT"
] | null | null | null | notebooks/Buffered Text-to-Speech.ipynb | Hallvardd/ttm4115-project | 8ac231b71690110985c17518883c8cd2bf01feb1 | [
"MIT"
] | null | null | null | notebooks/Buffered Text-to-Speech.ipynb | Hallvardd/ttm4115-project | 8ac231b71690110985c17518883c8cd2bf01feb1 | [
"MIT"
] | null | null | null | 40.185185 | 517 | 0.631429 | [
[
[
"# Buffered Text-to-Speech\n\nIn this tutorial, we are going to build a state machine that controls a text-to-speech synthesis. The problem we solve is the following:\n\n- Speaking the text takes time, depending on how long the text is that the computer should speak.\n- Commands for speaking can arrive at any time, and we would like our state machine to process one of them at a time. So, even if we send three messages to it shortly after each other, it processes them one after the other.\n\nWhile solving this problem, we can learn more about the following concepts in STMPY state machines:\n\n- **Do-Activities**, which allow us to encapsulate the long-running text-to-speech function in a state machine.\n- **Deferred Events**, which allow us to ignore incoming messages until a later state, when we are ready again.",
"_____no_output_____"
],
[
"# Text-to-Speech",
"_____no_output_____"
],
[
"## Mac\n\nOn a Mac, this is a function to make your computer speak:",
"_____no_output_____"
]
],
[
[
"from os import system\n\ndef text_to_speech(text):\n system('say {}'.format(text))",
"_____no_output_____"
]
],
[
[
"Run the above cell so the function is available in the following, and then execute the following cell to test it:",
"_____no_output_____"
]
],
[
[
"text_to_speech(\"Hello. I am a computer.\")",
"_____no_output_____"
]
],
[
[
"## Windows\n\nTODO: We should have some code to run text to speech on Windows, too!",
"_____no_output_____"
],
[
"# State Machine 1\n\nWith this function, we can create our first state machine that accepts a message and then speaks out some text. (Let's for now ignore how we get the text into the method, we will do that later.)\n\n\n\nUnfortunately, this state machine has a problem. This is because the method `text_to_speech(text)` is taking a long time to complete. This means, for the entire time that it takes to speak the text, nothing else can happen in all the state machines that are part of the same driver!",
"_____no_output_____"
],
[
"# State Machine 2\n\n## Long-Running Actions\n\nThe way this function is implented makes that it **blocks**. This means, the Python program is busy executing this function as long as the speech takes to pronouce the message. Longer message, longer blocking.\nYou can test this by putting some debugging aroud the function, to see when the functions returns:",
"_____no_output_____"
]
],
[
[
"print('Before speaking.')\ntext_to_speech(\"Hello. I am a computer.\")\nprint('After speaking.')",
"_____no_output_____"
]
],
[
[
"You see that the string _\"After speaking\"_ is printed after the speaking is finished. During the execution, the program is blocked and does not do anything else. \n\nWhen our program should also do other stuff at the same time, either completely unrelated to speech or even just accepting new speech commands, this is not working! The driver is now completely blocked with executing the speech method, not being able to do anything else.",
"_____no_output_____"
],
[
"## Do-Activities\n\nInstead of executing the method as part of a transition, we execute it as part of a state. This is called a **Do-Activity**, and it is declared as part of a state. The do-activity is started when the state is entered. Once the activity is finished, the state machine receives the event `done`, which triggers it to switch into another state.\n\n\n\nYou may think now that the do-activity is similar to an entry action, as it is started when entering a state. However, a do-activity is started as part of its own thread, so that it does not block any other behavior from happening. Our state machine stays responsive, and so does any of the other state machines that may be assigned to the same driver. This happens in the background, STMPY is creating a new thread for a do-activity, starts it, and dispatches the `done` event once the do-activity finishes.\n\nWhen the do-activity finishes (in the case of the text-to-speech function, this means when the computer is finished talking), the state machine dispatches _automatically_ the event `done`, which brings the state machine into the next state. \n\n- A state with a do activity can therefore only declare one single outgoing transition that is triggered by the event `done`. \n- A state can have at most one do-activity. \n- A do-activity cannot be aborted. Instead, it should be programmed so that the function itself terminates, indicated for instance by the change of a variable.\n\nThe following things are still possible in a state with a do-activity:\n\n- A state with a do-activity can have entry and exit actions. They are simply executed before or after the do activities.\n- A state with a do-activity can have internal transitions, since they don't leave the state.",
"_____no_output_____"
]
],
[
[
"from stmpy import Machine, Driver\nfrom os import system\n\nimport logging\ndebug_level = logging.DEBUG\nlogger = logging.getLogger('stmpy')\nlogger.setLevel(debug_level)\nch = logging.StreamHandler()\nch.setLevel(debug_level)\nformatter = logging.Formatter('%(asctime)s - %(name)-12s - %(levelname)-8s - %(message)s')\nch.setFormatter(formatter)\nlogger.addHandler(ch)\n\n\n\nclass Speaker:\n def speak(self, string):\n system('say {}'.format(string))\n\nspeaker = Speaker()\n \nt0 = {'source': 'initial', 'target': 'ready'}\nt1 = {'trigger': 'speak', 'source': 'ready', 'target': 'speaking'}\nt2 = {'trigger': 'done', 'source': 'speaking', 'target': 'ready'}\n\ns1 = {'name': 'speaking', 'do': 'speak(*)'}\n\nstm = Machine(name='stm', transitions=[t0, t1, t2], states=[s1], obj=speaker)\nspeaker.stm = stm\n\ndriver = Driver()\ndriver.add_machine(stm)\ndriver.start()\n\ndriver.send('speak', 'stm', args=['My first sentence.'])\ndriver.send('speak', 'stm', args=['My second sentence.'])\ndriver.send('speak', 'stm', args=['My third sentence.'])\ndriver.send('speak', 'stm', args=['My fourth sentence.'])\n\ndriver.wait_until_finished()",
"_____no_output_____"
]
],
[
[
"The state machine 2 still has a problem, but this time another one: If we receive a new message with more text to speak _while_ we are in state `speaking`, this message is discarded. Our next state machine will fix this.",
"_____no_output_____"
],
[
"# State Machine 3\n\nAs you know, events arriving in a state that do not declare outgoing triggers with that event, are discarded (that means, thrown away). For our state machine 2 above this means that when we are in state `speaking` and a new message arrives, this message is discarded. However, what we ideally want is that this message is handled once the currently spoken text is finished. There are two ways of achieving this:\n\n1. We could build a queue variable into our logic, and declare a transition that puts any arriving `speak` message into that queue. Whenever the currently spoken text finishes, we take another one from the queue until the queue is empty again. This has the drawback that we need to code the queue ourselves.\n2. We use a mechanism called **deferred event**, which is part of the state machine mechanics. This is the one we are going to use below.\n\n## Deferred Events\n\nA state can declare that it wants to **defer** an event, which simply means to not handle it. For our speech state machine it means that state `speaking` can declare that it defers event `speak`. \n\n\n\nAny event that arrives in a state that defers it, is ignored by that state. It is as if it never arrived, or as if it is invisible in the incoming event queue. Only once we switch into a next state that does not defer it, it gets visible again, and then either consumed by a transition, or discarded if the state does not declare any transition triggered by it. \n",
"_____no_output_____"
]
],
[
[
"s1 = {'name': 'speaking', 'do': 'speak(*)', 'speak': 'defer'}\n\nstm = Machine(name='stm', transitions=[t0, t1, t2], states=[s1], obj=speaker)\nspeaker.stm = stm\n\ndriver = Driver()\ndriver.add_machine(stm)\ndriver.start()\n\ndriver.send('speak', 'stm', args=['My first sentence.'])\ndriver.send('speak', 'stm', args=['My second sentence.'])\ndriver.send('speak', 'stm', args=['My third sentence.'])\ndriver.send('speak', 'stm', args=['My fourth sentence.'])\n\ndriver.wait_until_finished()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
]
] |
d083db0fe16a9ebf775c72c3bacb6638d425cce3 | 402,046 | ipynb | Jupyter Notebook | VGG16.ipynb | KoshinoK/RandomExchange | 4ab2a7dded61d506d4adbf4660b47c6f895a2935 | [
"MIT"
] | null | null | null | VGG16.ipynb | KoshinoK/RandomExchange | 4ab2a7dded61d506d4adbf4660b47c6f895a2935 | [
"MIT"
] | null | null | null | VGG16.ipynb | KoshinoK/RandomExchange | 4ab2a7dded61d506d4adbf4660b47c6f895a2935 | [
"MIT"
] | null | null | null | 255.591863 | 272,220 | 0.889508 | [
[
[
"# 概要\n- 101クラス分類\n- 対象:料理画像\n- VGG16による転移学習\n 1. 全結合層\n 1. 全層\n- RXなし",
"_____no_output_____"
]
],
[
[
"RUN = 100",
"_____no_output_____"
]
],
[
[
"# 使用するGPUメモリの制限",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\n\ntf_ver = tf.__version__\n\nif tf_ver.startswith('1.'):\n from tensorflow.keras.backend import set_session\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n config.log_device_placement = True\n sess = tf.Session(config=config)\n set_session(sess)",
"_____no_output_____"
]
],
[
[
"# 使用するGPUを指定",
"_____no_output_____"
]
],
[
[
"import os\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"",
"_____no_output_____"
]
],
[
[
"# matplotlibでプロットしたグラフをファイルへ保存",
"_____no_output_____"
]
],
[
[
"import os\ndef save_fig(plt, file_prefix):\n if file_prefix == '':\n return\n \n parent = os.path.dirname(os.path.abspath(file_prefix))\n os.makedirs(parent, exist_ok=True)\n plt.savefig(f'{file_prefix}.pdf', transparent=True, bbox_inches='tight', pad_inches = 0)\n plt.savefig(f'{file_prefix}.png', transparent=True, dpi=300, bbox_inches='tight', pad_inches = 0)",
"_____no_output_____"
]
],
[
[
"# 指定フォルダ以下にある画像リストを作成\n- サブフォルダはラベルに対応する数字であること\n- TOP_DIR\n - 0\n - 00001.jpg\n - 00002.jpg\n - 1\n - 00003.jpg\n - 00004.jpg",
"_____no_output_____"
]
],
[
[
"import pathlib\nimport random\nimport os\n\nTOP_DIR = '/data1/Datasets/Food-101/03_all'\n\nsub_dirs = pathlib.Path(TOP_DIR).glob('*/**')\n\nlabel2files = dict()\nfor s in sub_dirs:\n files = pathlib.Path(s).glob('**/*.jpg')\n label = int(os.path.basename(s))\n label2files[label] = list(files)",
"_____no_output_____"
]
],
[
[
"# 画像とラベルを訓練データと検証データに分割する",
"_____no_output_____"
]
],
[
[
"ratio = 0.8\ntrain_list = []\ntrain_labels = []\n\nval_list = []\nval_labels = []\n\nfor k, v in label2files.items():\n random.shuffle(v)\n N = len(v)\n N_train = int(N * ratio)\n train_list.extend(v[:N_train])\n train_labels.extend([k] * N_train)\n \n val_list.extend(v[N_train:])\n val_labels.extend([k] * (N - N_train))\n \nNUM_CLASSES = len(label2files.keys())",
"_____no_output_____"
]
],
[
[
"# 画像ファイルリストとラベルから教師データを生成するクラス",
"_____no_output_____"
]
],
[
[
"import math\nimport numpy as np\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nimport keras\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.preprocessing.image import img_to_array\nfrom tensorflow.keras.applications.vgg16 import preprocess_input\nimport tensorflow as tf\n\nclass ImageSequence(tf.keras.utils.Sequence):\n def __init__(self, file_list, labels, batch_size, image_shape=(224, 224), shuffle=True, horizontal_flip=True):\n self.file_list = np.array(file_list)\n self.labels = to_categorical(labels)\n self.batch_size = batch_size\n self.image_shape = image_shape\n self.shuffle = shuffle\n self.horizontal_flip = horizontal_flip\n \n self.indexes = np.arange(len(self.file_list))\n if self.shuffle:\n random.shuffle(self.indexes)\n \n def __getitem__(self, index):\n idx = self.indexes[index * self.batch_size : (index + 1) * self.batch_size]\n \n y = self.labels[idx]\n \n files = self.file_list[idx]\n\n x = []\n for f in files:\n try:\n img = Image.open(f)\n \n # 正しいデータはRGB画像\n # データセットの中には、グレースケール画像が入っている可能性がある。\n # RGBに変換して、正しいデータと次元を揃える\n img = img.convert('RGB')\n img = img.resize(self.image_shape, Image.BILINEAR)\n img = img_to_array(img)\n img = preprocess_input(img) / 255.0\n if self.horizontal_flip and np.random.random() > 0.5:\n img = img[:,::-1, :]\n \n x.append(np.expand_dims(img, axis=0))\n except:\n print(f)\n return np.concatenate(x, axis=0), y\n \n def __len__(self):\n return len(self.file_list) // self.batch_size\n \n def on_epoch_end(self):\n if self.shuffle:\n random.shuffle(self.indexes)",
"Using TensorFlow backend.\n"
]
],
[
[
"# モデル保存用のディレクトリを作成★",
"_____no_output_____"
]
],
[
[
"import os\nfrom datetime import datetime\n\n# モデル保存用ディレクトリの準備\nmodel_dir = os.path.join(\n f'../run/VGG16_run{RUN}'\n)\nos.makedirs(model_dir, exist_ok=True)\nprint('model_dir:', model_dir) # 保存先のディレクトリ名を表示\n\ndir_weights = model_dir\nos.makedirs(dir_weights, exist_ok=True)",
"model_dir: ../run/VGG16_run100\n"
]
],
[
[
"# VGGモデルのロード",
"_____no_output_____"
]
],
[
[
"from tensorflow.keras.applications.vgg16 import VGG16\n\n\n# 既存の1000クラスの出力を使わないため、\n# `incliude_top=False`として出力層を含まない状態でロード\nvgg16 = VGG16(include_top=False, input_shape=(224, 224, 3))\n\n# モデルのサマリを確認。出力層が含まれてないことがわかる\nvgg16.summary()",
"_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_1 (InputLayer) (None, 224, 224, 3) 0 \n_________________________________________________________________\nblock1_conv1 (Conv2D) (None, 224, 224, 64) 1792 \n_________________________________________________________________\nblock1_conv2 (Conv2D) (None, 224, 224, 64) 36928 \n_________________________________________________________________\nblock1_pool (MaxPooling2D) (None, 112, 112, 64) 0 \n_________________________________________________________________\nblock2_conv1 (Conv2D) (None, 112, 112, 128) 73856 \n_________________________________________________________________\nblock2_conv2 (Conv2D) (None, 112, 112, 128) 147584 \n_________________________________________________________________\nblock2_pool (MaxPooling2D) (None, 56, 56, 128) 0 \n_________________________________________________________________\nblock3_conv1 (Conv2D) (None, 56, 56, 256) 295168 \n_________________________________________________________________\nblock3_conv2 (Conv2D) (None, 56, 56, 256) 590080 \n_________________________________________________________________\nblock3_conv3 (Conv2D) (None, 56, 56, 256) 590080 \n_________________________________________________________________\nblock3_pool (MaxPooling2D) (None, 28, 28, 256) 0 \n_________________________________________________________________\nblock4_conv1 (Conv2D) (None, 28, 28, 512) 1180160 \n_________________________________________________________________\nblock4_conv2 (Conv2D) (None, 28, 28, 512) 2359808 \n_________________________________________________________________\nblock4_conv3 (Conv2D) (None, 28, 28, 512) 2359808 \n_________________________________________________________________\nblock4_pool (MaxPooling2D) (None, 14, 14, 512) 0 \n_________________________________________________________________\nblock5_conv1 (Conv2D) (None, 14, 14, 512) 2359808 \n_________________________________________________________________\nblock5_conv2 (Conv2D) (None, 14, 14, 512) 2359808 \n_________________________________________________________________\nblock5_conv3 (Conv2D) (None, 14, 14, 512) 2359808 \n_________________________________________________________________\nblock5_pool (MaxPooling2D) (None, 7, 7, 512) 0 \n=================================================================\nTotal params: 14,714,688\nTrainable params: 14,714,688\nNon-trainable params: 0\n_________________________________________________________________\n"
]
],
[
[
"# VGG16を利用したモデルの作成と学習方法の設定★",
"_____no_output_____"
]
],
[
[
"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Flatten\n\n\n# モデルを編集し、ネットワークを生成する関数の定義\ndef build_transfer_model(vgg16):\n \n # 読み出したモデルを使って、新しいモデルを作成\n model = Sequential(vgg16.layers)\n\n # 読み出した重みの一部は再学習しないように設定。\n # ここでは、追加する層と出力層に近い層の重みのみを再学習\n for layer in model.layers[:15]:\n layer.trainable = False\n \n # 追加する出力部分の層を構築\n model.add(Flatten())\n model.add(Dense(1024, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(1024, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(NUM_CLASSES, activation='softmax'))\n \n return model",
"_____no_output_____"
]
],
[
[
"# 全結合層とそれに近い畳み込み層の学習★",
"_____no_output_____"
],
[
"## モデル作成",
"_____no_output_____"
]
],
[
[
"# 定義した関数を呼び出して、ネットワークを生成\nmodel = build_transfer_model(vgg16)",
"_____no_output_____"
]
],
[
[
"## ネットワーク構造の保存★",
"_____no_output_____"
]
],
[
[
"import json\nimport pickle\n\n# ネットワークの保存\nmodel_json = os.path.join(model_dir, 'model.json')\nwith open(model_json, 'w') as f:\n json.dump(model.to_json(), f)",
"_____no_output_____"
]
],
[
[
"## 最適化アルゴリズムなどを指定してモデルをコンパイルする",
"_____no_output_____"
]
],
[
[
"from tensorflow.keras.optimizers import SGD\n\n\nmodel.compile(\n loss='categorical_crossentropy',\n optimizer=SGD(lr=1e-4, momentum=0.9),\n metrics=['accuracy']\n)",
"_____no_output_____"
],
[
"# モデルのサマリを確認\nmodel.summary()",
"_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nblock1_conv1 (Conv2D) (None, 224, 224, 64) 1792 \n_________________________________________________________________\nblock1_conv2 (Conv2D) (None, 224, 224, 64) 36928 \n_________________________________________________________________\nblock1_pool (MaxPooling2D) (None, 112, 112, 64) 0 \n_________________________________________________________________\nblock2_conv1 (Conv2D) (None, 112, 112, 128) 73856 \n_________________________________________________________________\nblock2_conv2 (Conv2D) (None, 112, 112, 128) 147584 \n_________________________________________________________________\nblock2_pool (MaxPooling2D) (None, 56, 56, 128) 0 \n_________________________________________________________________\nblock3_conv1 (Conv2D) (None, 56, 56, 256) 295168 \n_________________________________________________________________\nblock3_conv2 (Conv2D) (None, 56, 56, 256) 590080 \n_________________________________________________________________\nblock3_conv3 (Conv2D) (None, 56, 56, 256) 590080 \n_________________________________________________________________\nblock3_pool (MaxPooling2D) (None, 28, 28, 256) 0 \n_________________________________________________________________\nblock4_conv1 (Conv2D) (None, 28, 28, 512) 1180160 \n_________________________________________________________________\nblock4_conv2 (Conv2D) (None, 28, 28, 512) 2359808 \n_________________________________________________________________\nblock4_conv3 (Conv2D) (None, 28, 28, 512) 2359808 \n_________________________________________________________________\nblock4_pool (MaxPooling2D) (None, 14, 14, 512) 0 \n_________________________________________________________________\nblock5_conv1 (Conv2D) (None, 14, 14, 512) 2359808 \n_________________________________________________________________\nblock5_conv2 (Conv2D) (None, 14, 14, 512) 2359808 \n_________________________________________________________________\nblock5_conv3 (Conv2D) (None, 14, 14, 512) 2359808 \n_________________________________________________________________\nblock5_pool (MaxPooling2D) (None, 7, 7, 512) 0 \n_________________________________________________________________\nflatten (Flatten) (None, 25088) 0 \n_________________________________________________________________\ndense (Dense) (None, 1024) 25691136 \n_________________________________________________________________\ndropout (Dropout) (None, 1024) 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 1024) 1049600 \n_________________________________________________________________\ndropout_1 (Dropout) (None, 1024) 0 \n_________________________________________________________________\ndense_2 (Dense) (None, 101) 103525 \n=================================================================\nTotal params: 41,558,949\nTrainable params: 31,563,877\nNon-trainable params: 9,995,072\n_________________________________________________________________\n"
]
],
[
[
"## シーケンス生成",
"_____no_output_____"
]
],
[
[
"batch_size = 25\n\nimg_seq_train = ImageSequence(train_list, train_labels, batch_size=batch_size)\n\nimg_seq_validation = ImageSequence(val_list, val_labels, batch_size=batch_size)\n\nprint('Train images =', len(img_seq_train) * batch_size)\nprint('Validation images =', len(img_seq_validation) * batch_size)",
"Train images = 80800\nValidation images = 20200\n"
]
],
[
[
"## Callbackの生成★",
"_____no_output_____"
]
],
[
[
"from tensorflow.keras.callbacks import ModelCheckpoint, CSVLogger, EarlyStopping, ReduceLROnPlateau\n\n\n# Callbacksの設定\ncp_filepath = os.path.join(dir_weights, 'ep_{epoch:04d}_ls_{loss:.1f}.h5')\ncp = ModelCheckpoint(\n cp_filepath, \n monitor='val_acc', \n verbose=0,\n save_best_only=True, \n save_weights_only=True, \n mode='auto'\n )\n\ncsv_filepath = os.path.join(model_dir, 'loss.csv')\ncsv = CSVLogger(csv_filepath, append=True)\n\nes = EarlyStopping(monitor='val_acc', patience=20, verbose=1, mode='auto')\n\nrl = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=5, verbose=1, mode='auto', epsilon=0.0001, cooldown=0, min_lr=0)",
"WARNING:tensorflow:`epsilon` argument is deprecated and will be removed, use `min_delta` instead.\n"
]
],
[
[
"## 学習",
"_____no_output_____"
]
],
[
[
"n_epoch = 200\n\n# モデルの学習\nhistory = model.fit_generator(\n img_seq_train, \n epochs=n_epoch, # 学習するエポック数\n steps_per_epoch=len(img_seq_train),\n validation_data=img_seq_validation,\n validation_steps=len(img_seq_validation),\n verbose=1,\n callbacks=[cp, csv, es, rl]\n)",
"Epoch 1/200\n3232/3232 [==============================] - 1217s 377ms/step - loss: 4.6143 - acc: 0.0148 - val_loss: 4.5334 - val_acc: 0.0410\nEpoch 2/200\n3232/3232 [==============================] - 499s 155ms/step - loss: 4.4336 - acc: 0.0381 - val_loss: 4.0951 - val_acc: 0.1068\nEpoch 3/200\n3232/3232 [==============================] - 500s 155ms/step - loss: 4.0705 - acc: 0.0861 - val_loss: 3.5528 - val_acc: 0.2125\nEpoch 4/200\n3232/3232 [==============================] - 499s 154ms/step - loss: 3.6836 - acc: 0.1451 - val_loss: 3.1393 - val_acc: 0.2758\nEpoch 5/200\n3232/3232 [==============================] - 502s 155ms/step - loss: 3.3705 - acc: 0.2016 - val_loss: 2.8485 - val_acc: 0.3291\nEpoch 6/200\n3232/3232 [==============================] - 508s 157ms/step - loss: 3.1329 - acc: 0.2452 - val_loss: 2.6545 - val_acc: 0.3693\nEpoch 7/200\n3232/3232 [==============================] - 500s 155ms/step - loss: 2.9475 - acc: 0.2812 - val_loss: 2.5029 - val_acc: 0.3941\nEpoch 8/200\n3232/3232 [==============================] - 499s 154ms/step - loss: 2.7907 - acc: 0.3143 - val_loss: 2.3997 - val_acc: 0.4174\nEpoch 9/200\n3232/3232 [==============================] - 498s 154ms/step - loss: 2.6628 - acc: 0.3397 - val_loss: 2.2895 - val_acc: 0.4424\nEpoch 10/200\n3232/3232 [==============================] - 500s 155ms/step - loss: 2.5539 - acc: 0.3637 - val_loss: 2.2035 - val_acc: 0.4557\nEpoch 11/200\n3232/3232 [==============================] - 502s 155ms/step - loss: 2.4609 - acc: 0.3858 - val_loss: 2.1512 - val_acc: 0.4664\nEpoch 12/200\n3232/3232 [==============================] - 501s 155ms/step - loss: 2.3779 - acc: 0.4038 - val_loss: 2.0793 - val_acc: 0.4807\nEpoch 13/200\n3232/3232 [==============================] - 498s 154ms/step - loss: 2.3044 - acc: 0.4187 - val_loss: 2.0313 - val_acc: 0.4899\nEpoch 14/200\n3232/3232 [==============================] - 500s 155ms/step - loss: 2.2252 - acc: 0.4368 - val_loss: 2.0015 - val_acc: 0.4949\nEpoch 15/200\n3232/3232 [==============================] - 502s 155ms/step - loss: 2.1651 - acc: 0.4520 - val_loss: 1.9603 - val_acc: 0.5070\nEpoch 16/200\n3232/3232 [==============================] - 502s 155ms/step - loss: 2.1022 - acc: 0.4646 - val_loss: 1.9267 - val_acc: 0.5141\nEpoch 17/200\n3232/3232 [==============================] - 499s 154ms/step - loss: 2.0475 - acc: 0.4769 - val_loss: 1.8840 - val_acc: 0.5234\nEpoch 18/200\n3232/3232 [==============================] - 503s 156ms/step - loss: 1.9960 - acc: 0.4895 - val_loss: 1.8575 - val_acc: 0.5267\nEpoch 19/200\n3232/3232 [==============================] - 502s 155ms/step - loss: 1.9521 - acc: 0.4995 - val_loss: 1.8374 - val_acc: 0.5341\nEpoch 20/200\n3232/3232 [==============================] - 498s 154ms/step - loss: 1.9016 - acc: 0.5120 - val_loss: 1.8023 - val_acc: 0.5405\nEpoch 21/200\n3232/3232 [==============================] - 498s 154ms/step - loss: 1.8537 - acc: 0.5233 - val_loss: 1.7787 - val_acc: 0.5486\nEpoch 22/200\n3232/3232 [==============================] - 484s 150ms/step - loss: 1.8121 - acc: 0.5312 - val_loss: 1.7634 - val_acc: 0.5505\nEpoch 23/200\n3232/3232 [==============================] - 485s 150ms/step - loss: 1.7748 - acc: 0.5378 - val_loss: 1.7524 - val_acc: 0.5514\nEpoch 24/200\n3232/3232 [==============================] - 486s 150ms/step - loss: 1.7294 - acc: 0.5470 - val_loss: 1.7392 - val_acc: 0.5547\nEpoch 25/200\n3232/3232 [==============================] - 487s 151ms/step - loss: 1.6912 - acc: 0.5574 - val_loss: 1.7472 - val_acc: 0.5532\nEpoch 26/200\n3232/3232 [==============================] - 485s 150ms/step - loss: 1.6500 - acc: 0.5659 - val_loss: 1.7059 - val_acc: 0.5616\nEpoch 27/200\n3232/3232 [==============================] - 492s 152ms/step - loss: 1.6187 - acc: 0.5736 - val_loss: 1.6946 - val_acc: 0.5647\nEpoch 28/200\n3232/3232 [==============================] - 492s 152ms/step - loss: 1.5838 - acc: 0.5820 - val_loss: 1.6890 - val_acc: 0.5670\nEpoch 29/200\n3232/3232 [==============================] - 488s 151ms/step - loss: 1.5471 - acc: 0.5917 - val_loss: 1.6749 - val_acc: 0.5668\nEpoch 30/200\n3232/3232 [==============================] - 489s 151ms/step - loss: 1.5096 - acc: 0.5964 - val_loss: 1.6665 - val_acc: 0.5695\nEpoch 31/200\n3232/3232 [==============================] - 487s 151ms/step - loss: 1.4784 - acc: 0.6067 - val_loss: 1.6452 - val_acc: 0.5782\nEpoch 32/200\n3232/3232 [==============================] - 492s 152ms/step - loss: 1.4428 - acc: 0.6163 - val_loss: 1.6375 - val_acc: 0.5794\nEpoch 33/200\n3232/3232 [==============================] - 486s 150ms/step - loss: 1.4086 - acc: 0.6217 - val_loss: 1.6253 - val_acc: 0.5825\nEpoch 34/200\n3232/3232 [==============================] - 491s 152ms/step - loss: 1.3763 - acc: 0.6286 - val_loss: 1.6203 - val_acc: 0.5832\nEpoch 35/200\n3232/3232 [==============================] - 490s 151ms/step - loss: 1.3446 - acc: 0.6359 - val_loss: 1.6395 - val_acc: 0.5834\nEpoch 36/200\n3232/3232 [==============================] - 489s 151ms/step - loss: 1.3171 - acc: 0.6429 - val_loss: 1.6277 - val_acc: 0.5800\nEpoch 37/200\n3232/3232 [==============================] - 488s 151ms/step - loss: 1.2863 - acc: 0.6489 - val_loss: 1.6106 - val_acc: 0.5874\nEpoch 38/200\n3232/3232 [==============================] - 484s 150ms/step - loss: 1.2545 - acc: 0.6583 - val_loss: 1.6117 - val_acc: 0.5884\nEpoch 39/200\n3232/3232 [==============================] - 488s 151ms/step - loss: 1.2276 - acc: 0.6656 - val_loss: 1.6133 - val_acc: 0.5885\nEpoch 40/200\n3232/3232 [==============================] - 487s 151ms/step - loss: 1.1959 - acc: 0.6734 - val_loss: 1.6090 - val_acc: 0.5882\nEpoch 41/200\n3232/3232 [==============================] - 486s 150ms/step - loss: 1.1637 - acc: 0.6792 - val_loss: 1.6263 - val_acc: 0.5867\nEpoch 42/200\n3232/3232 [==============================] - 484s 150ms/step - loss: 1.1359 - acc: 0.6874 - val_loss: 1.6013 - val_acc: 0.5909\nEpoch 43/200\n3232/3232 [==============================] - 486s 151ms/step - loss: 1.1095 - acc: 0.6927 - val_loss: 1.6142 - val_acc: 0.5935\nEpoch 44/200\n3232/3232 [==============================] - 490s 152ms/step - loss: 1.0810 - acc: 0.7000 - val_loss: 1.6058 - val_acc: 0.5960\nEpoch 45/200\n3232/3232 [==============================] - 492s 152ms/step - loss: 1.0511 - acc: 0.7065 - val_loss: 1.6033 - val_acc: 0.5926\nEpoch 46/200\n3232/3232 [==============================] - 487s 151ms/step - loss: 1.0232 - acc: 0.7130 - val_loss: 1.6130 - val_acc: 0.5941\nEpoch 47/200\n3232/3232 [==============================] - 487s 151ms/step - loss: 0.9957 - acc: 0.7211 - val_loss: 1.5959 - val_acc: 0.5958\nEpoch 48/200\n3232/3232 [==============================] - 488s 151ms/step - loss: 0.9706 - acc: 0.7258 - val_loss: 1.6057 - val_acc: 0.5959\nEpoch 49/200\n3232/3232 [==============================] - 485s 150ms/step - loss: 0.9440 - acc: 0.7347 - val_loss: 1.6165 - val_acc: 0.5961\nEpoch 50/200\n3232/3232 [==============================] - 490s 152ms/step - loss: 0.9121 - acc: 0.7419 - val_loss: 1.6494 - val_acc: 0.5919\nEpoch 51/200\n3232/3232 [==============================] - 486s 151ms/step - loss: 0.8922 - acc: 0.7459 - val_loss: 1.6133 - val_acc: 0.6008\nEpoch 52/200\n3231/3232 [============================>.] - ETA: 0s - loss: 0.8630 - acc: 0.7528\nEpoch 00052: ReduceLROnPlateau reducing learning rate to 4.999999873689376e-05.\n3232/3232 [==============================] - 485s 150ms/step - loss: 0.8631 - acc: 0.7528 - val_loss: 1.6334 - val_acc: 0.5990\nEpoch 53/200\n3232/3232 [==============================] - 489s 151ms/step - loss: 0.7975 - acc: 0.7695 - val_loss: 1.6231 - val_acc: 0.6012\nEpoch 54/200\n3232/3232 [==============================] - 487s 151ms/step - loss: 0.7781 - acc: 0.7774 - val_loss: 1.6193 - val_acc: 0.6026\nEpoch 55/200\n3232/3232 [==============================] - 487s 151ms/step - loss: 0.7586 - acc: 0.7803 - val_loss: 1.6249 - val_acc: 0.6021\nEpoch 56/200\n3232/3232 [==============================] - 484s 150ms/step - loss: 0.7481 - acc: 0.7845 - val_loss: 1.6249 - val_acc: 0.6005\nEpoch 57/200\n3231/3232 [============================>.] - ETA: 0s - loss: 0.7362 - acc: 0.7866\nEpoch 00057: ReduceLROnPlateau reducing learning rate to 2.499999936844688e-05.\n3232/3232 [==============================] - 486s 150ms/step - loss: 0.7361 - acc: 0.7866 - val_loss: 1.6208 - val_acc: 0.6024\nEpoch 58/200\n3232/3232 [==============================] - 481s 149ms/step - loss: 0.6953 - acc: 0.8007 - val_loss: 1.6324 - val_acc: 0.6047\nEpoch 59/200\n3232/3232 [==============================] - 485s 150ms/step - loss: 0.6884 - acc: 0.8003 - val_loss: 1.6305 - val_acc: 0.6027\nEpoch 60/200\n3232/3232 [==============================] - 488s 151ms/step - loss: 0.6805 - acc: 0.8024 - val_loss: 1.6360 - val_acc: 0.6024\nEpoch 61/200\n3232/3232 [==============================] - 485s 150ms/step - loss: 0.6705 - acc: 0.8058 - val_loss: 1.6367 - val_acc: 0.6048\nEpoch 62/200\n3231/3232 [============================>.] - ETA: 0s - loss: 0.6591 - acc: 0.8081\nEpoch 00062: ReduceLROnPlateau reducing learning rate to 1.249999968422344e-05.\n3232/3232 [==============================] - 492s 152ms/step - loss: 0.6592 - acc: 0.8081 - val_loss: 1.6445 - val_acc: 0.6037\nEpoch 63/200\n3232/3232 [==============================] - 487s 151ms/step - loss: 0.6491 - acc: 0.8123 - val_loss: 1.6431 - val_acc: 0.6056\nEpoch 64/200\n3232/3232 [==============================] - 488s 151ms/step - loss: 0.6441 - acc: 0.8133 - val_loss: 1.6480 - val_acc: 0.6049\nEpoch 65/200\n3232/3232 [==============================] - 487s 151ms/step - loss: 0.6403 - acc: 0.8150 - val_loss: 1.6382 - val_acc: 0.6069\nEpoch 66/200\n3232/3232 [==============================] - 489s 151ms/step - loss: 0.6359 - acc: 0.8164 - val_loss: 1.6350 - val_acc: 0.6071\nEpoch 67/200\n3231/3232 [============================>.] - ETA: 0s - loss: 0.6319 - acc: 0.8168\nEpoch 00067: ReduceLROnPlateau reducing learning rate to 6.24999984211172e-06.\n3232/3232 [==============================] - 485s 150ms/step - loss: 0.6319 - acc: 0.8168 - val_loss: 1.6379 - val_acc: 0.6045\nEpoch 68/200\n3232/3232 [==============================] - 490s 151ms/step - loss: 0.6226 - acc: 0.8195 - val_loss: 1.6434 - val_acc: 0.6070\nEpoch 69/200\n3232/3232 [==============================] - 490s 152ms/step - loss: 0.6222 - acc: 0.8189 - val_loss: 1.6373 - val_acc: 0.6062\nEpoch 70/200\n3232/3232 [==============================] - 484s 150ms/step - loss: 0.6175 - acc: 0.8204 - val_loss: 1.6485 - val_acc: 0.6068\nEpoch 71/200\n3232/3232 [==============================] - 482s 149ms/step - loss: 0.6155 - acc: 0.8208 - val_loss: 1.6381 - val_acc: 0.6078\nEpoch 72/200\n3231/3232 [============================>.] - ETA: 0s - loss: 0.6161 - acc: 0.8215\nEpoch 00072: ReduceLROnPlateau reducing learning rate to 3.12499992105586e-06.\n3232/3232 [==============================] - 490s 152ms/step - loss: 0.6161 - acc: 0.8215 - val_loss: 1.6511 - val_acc: 0.6053\nEpoch 73/200\n3232/3232 [==============================] - 491s 152ms/step - loss: 0.6129 - acc: 0.8235 - val_loss: 1.6444 - val_acc: 0.6074\nEpoch 74/200\n3232/3232 [==============================] - 486s 150ms/step - loss: 0.6060 - acc: 0.8232 - val_loss: 1.6510 - val_acc: 0.6060\nEpoch 75/200\n3232/3232 [==============================] - 491s 152ms/step - loss: 0.6067 - acc: 0.8230 - val_loss: 1.6488 - val_acc: 0.6053\nEpoch 76/200\n3232/3232 [==============================] - 486s 150ms/step - loss: 0.6073 - acc: 0.8237 - val_loss: 1.6531 - val_acc: 0.6060\nEpoch 77/200\n3231/3232 [============================>.] - ETA: 0s - loss: 0.6054 - acc: 0.8248\nEpoch 00077: ReduceLROnPlateau reducing learning rate to 1.56249996052793e-06.\n3232/3232 [==============================] - 489s 151ms/step - loss: 0.6053 - acc: 0.8248 - val_loss: 1.6554 - val_acc: 0.6069\nEpoch 78/200\n3232/3232 [==============================] - 482s 149ms/step - loss: 0.6018 - acc: 0.8254 - val_loss: 1.6492 - val_acc: 0.6067\nEpoch 79/200\n3232/3232 [==============================] - 479s 148ms/step - loss: 0.6064 - acc: 0.8244 - val_loss: 1.6446 - val_acc: 0.6083\nEpoch 80/200\n3232/3232 [==============================] - 485s 150ms/step - loss: 0.6015 - acc: 0.8242 - val_loss: 1.6471 - val_acc: 0.6060\nEpoch 81/200\n3232/3232 [==============================] - 487s 151ms/step - loss: 0.6046 - acc: 0.8235 - val_loss: 1.6474 - val_acc: 0.6076\nEpoch 82/200\n3231/3232 [============================>.] - ETA: 0s - loss: 0.6039 - acc: 0.8248\nEpoch 00082: ReduceLROnPlateau reducing learning rate to 7.81249980263965e-07.\n3232/3232 [==============================] - 485s 150ms/step - loss: 0.6040 - acc: 0.8248 - val_loss: 1.6481 - val_acc: 0.6039\nEpoch 83/200\n3232/3232 [==============================] - 487s 151ms/step - loss: 0.6030 - acc: 0.8251 - val_loss: 1.6449 - val_acc: 0.6076\nEpoch 84/200\n3232/3232 [==============================] - 480s 149ms/step - loss: 0.6040 - acc: 0.8235 - val_loss: 1.6508 - val_acc: 0.6060\nEpoch 85/200\n3232/3232 [==============================] - 487s 151ms/step - loss: 0.6027 - acc: 0.8234 - val_loss: 1.6452 - val_acc: 0.6099\nEpoch 86/200\n3232/3232 [==============================] - 487s 151ms/step - loss: 0.6000 - acc: 0.8257 - val_loss: 1.6515 - val_acc: 0.6083\nEpoch 87/200\n3231/3232 [============================>.] - ETA: 0s - loss: 0.5978 - acc: 0.8245\nEpoch 00087: ReduceLROnPlateau reducing learning rate to 3.906249901319825e-07.\n3232/3232 [==============================] - 489s 151ms/step - loss: 0.5978 - acc: 0.8245 - val_loss: 1.6468 - val_acc: 0.6073\nEpoch 88/200\n3232/3232 [==============================] - 487s 151ms/step - loss: 0.6009 - acc: 0.8248 - val_loss: 1.6499 - val_acc: 0.6068\nEpoch 89/200\n3232/3232 [==============================] - 480s 149ms/step - loss: 0.6071 - acc: 0.8235 - val_loss: 1.6483 - val_acc: 0.6074\nEpoch 90/200\n3232/3232 [==============================] - 487s 151ms/step - loss: 0.6026 - acc: 0.8246 - val_loss: 1.6489 - val_acc: 0.6072\nEpoch 91/200\n3232/3232 [==============================] - 482s 149ms/step - loss: 0.5966 - acc: 0.8254 - val_loss: 1.6461 - val_acc: 0.6067\nEpoch 92/200\n3231/3232 [============================>.] - ETA: 0s - loss: 0.6014 - acc: 0.8238\nEpoch 00092: ReduceLROnPlateau reducing learning rate to 1.9531249506599124e-07.\n3232/3232 [==============================] - 482s 149ms/step - loss: 0.6014 - acc: 0.8238 - val_loss: 1.6436 - val_acc: 0.6103\nEpoch 93/200\n3232/3232 [==============================] - 483s 150ms/step - loss: 0.6033 - acc: 0.8245 - val_loss: 1.6448 - val_acc: 0.6070\nEpoch 94/200\n3232/3232 [==============================] - 484s 150ms/step - loss: 0.6004 - acc: 0.8246 - val_loss: 1.6473 - val_acc: 0.6079\nEpoch 95/200\n3232/3232 [==============================] - 485s 150ms/step - loss: 0.5992 - acc: 0.8260 - val_loss: 1.6506 - val_acc: 0.6059\nEpoch 96/200\n3232/3232 [==============================] - 486s 150ms/step - loss: 0.6007 - acc: 0.8251 - val_loss: 1.6441 - val_acc: 0.6085\nEpoch 97/200\n3231/3232 [============================>.] - ETA: 0s - loss: 0.6011 - acc: 0.8257\nEpoch 00097: ReduceLROnPlateau reducing learning rate to 9.765624753299562e-08.\n3232/3232 [==============================] - 491s 152ms/step - loss: 0.6011 - acc: 0.8256 - val_loss: 1.6462 - val_acc: 0.6092\nEpoch 98/200\n3232/3232 [==============================] - 490s 152ms/step - loss: 0.6027 - acc: 0.8254 - val_loss: 1.6427 - val_acc: 0.6078\nEpoch 99/200\n3232/3232 [==============================] - 487s 151ms/step - loss: 0.5980 - acc: 0.8254 - val_loss: 1.6453 - val_acc: 0.6057\nEpoch 100/200\n3232/3232 [==============================] - 480s 148ms/step - loss: 0.6035 - acc: 0.8231 - val_loss: 1.6516 - val_acc: 0.6065\nEpoch 101/200\n3232/3232 [==============================] - 489s 151ms/step - loss: 0.5982 - acc: 0.8244 - val_loss: 1.6424 - val_acc: 0.6075\nEpoch 102/200\n3231/3232 [============================>.] - ETA: 0s - loss: 0.6012 - acc: 0.8250\nEpoch 00102: ReduceLROnPlateau reducing learning rate to 4.882812376649781e-08.\n3232/3232 [==============================] - 487s 151ms/step - loss: 0.6012 - acc: 0.8250 - val_loss: 1.6413 - val_acc: 0.6091\nEpoch 103/200\n3232/3232 [==============================] - 491s 152ms/step - loss: 0.5998 - acc: 0.8236 - val_loss: 1.6475 - val_acc: 0.6065\nEpoch 104/200\n3232/3232 [==============================] - 488s 151ms/step - loss: 0.5979 - acc: 0.8264 - val_loss: 1.6496 - val_acc: 0.6053\nEpoch 105/200\n3232/3232 [==============================] - 484s 150ms/step - loss: 0.6012 - acc: 0.8242 - val_loss: 1.6449 - val_acc: 0.6067\nEpoch 106/200\n3232/3232 [==============================] - 489s 151ms/step - loss: 0.5984 - acc: 0.8270 - val_loss: 1.6476 - val_acc: 0.6081\nEpoch 107/200\n3231/3232 [============================>.] - ETA: 0s - loss: 0.5999 - acc: 0.8235\nEpoch 00107: ReduceLROnPlateau reducing learning rate to 2.4414061883248905e-08.\n3232/3232 [==============================] - 486s 151ms/step - loss: 0.5999 - acc: 0.8235 - val_loss: 1.6499 - val_acc: 0.6068\nEpoch 108/200\n3232/3232 [==============================] - 486s 150ms/step - loss: 0.5964 - acc: 0.8263 - val_loss: 1.6412 - val_acc: 0.6097\nEpoch 109/200\n3232/3232 [==============================] - 482s 149ms/step - loss: 0.6018 - acc: 0.8237 - val_loss: 1.6465 - val_acc: 0.6089\nEpoch 110/200\n3232/3232 [==============================] - 485s 150ms/step - loss: 0.5970 - acc: 0.8252 - val_loss: 1.6416 - val_acc: 0.6082\nEpoch 111/200\n3232/3232 [==============================] - 480s 148ms/step - loss: 0.5968 - acc: 0.8265 - val_loss: 1.6495 - val_acc: 0.6059\nEpoch 112/200\n3231/3232 [============================>.] - ETA: 0s - loss: 0.5972 - acc: 0.8255\nEpoch 00112: ReduceLROnPlateau reducing learning rate to 1.2207030941624453e-08.\n3232/3232 [==============================] - 493s 152ms/step - loss: 0.5973 - acc: 0.8255 - val_loss: 1.6476 - val_acc: 0.6081\nEpoch 00112: early stopping\n"
]
],
[
[
"## Stage1の損失と正解率の保存",
"_____no_output_____"
]
],
[
[
"h = history.history\n\nstage1_loss = h['loss']\nstage1_val_loss = h['val_loss']\n\nstage1_acc = h['acc']\nstage1_val_acc = h['val_acc']",
"_____no_output_____"
]
],
[
[
"# 全層の学習",
"_____no_output_____"
],
[
"## Stage1の最良モデルパラメータをロード",
"_____no_output_____"
]
],
[
[
"import pathlib\n\ncheckpoints = pathlib.Path(model_dir).glob('*.h5')\ncheckpoints = sorted(checkpoints, key=lambda cp:cp.stat().st_mtime)\n\nlatest = str(checkpoints[-1])\nmodel.load_weights(latest)",
"_____no_output_____"
]
],
[
[
"## 全層を学習可能にする",
"_____no_output_____"
]
],
[
[
"for l in model.layers:\n l.trainable = True\n\nmodel.summary()",
"_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nblock1_conv1 (Conv2D) (None, 224, 224, 64) 1792 \n_________________________________________________________________\nblock1_conv2 (Conv2D) (None, 224, 224, 64) 36928 \n_________________________________________________________________\nblock1_pool (MaxPooling2D) (None, 112, 112, 64) 0 \n_________________________________________________________________\nblock2_conv1 (Conv2D) (None, 112, 112, 128) 73856 \n_________________________________________________________________\nblock2_conv2 (Conv2D) (None, 112, 112, 128) 147584 \n_________________________________________________________________\nblock2_pool (MaxPooling2D) (None, 56, 56, 128) 0 \n_________________________________________________________________\nblock3_conv1 (Conv2D) (None, 56, 56, 256) 295168 \n_________________________________________________________________\nblock3_conv2 (Conv2D) (None, 56, 56, 256) 590080 \n_________________________________________________________________\nblock3_conv3 (Conv2D) (None, 56, 56, 256) 590080 \n_________________________________________________________________\nblock3_pool (MaxPooling2D) (None, 28, 28, 256) 0 \n_________________________________________________________________\nblock4_conv1 (Conv2D) (None, 28, 28, 512) 1180160 \n_________________________________________________________________\nblock4_conv2 (Conv2D) (None, 28, 28, 512) 2359808 \n_________________________________________________________________\nblock4_conv3 (Conv2D) (None, 28, 28, 512) 2359808 \n_________________________________________________________________\nblock4_pool (MaxPooling2D) (None, 14, 14, 512) 0 \n_________________________________________________________________\nblock5_conv1 (Conv2D) (None, 14, 14, 512) 2359808 \n_________________________________________________________________\nblock5_conv2 (Conv2D) (None, 14, 14, 512) 2359808 \n_________________________________________________________________\nblock5_conv3 (Conv2D) (None, 14, 14, 512) 2359808 \n_________________________________________________________________\nblock5_pool (MaxPooling2D) (None, 7, 7, 512) 0 \n_________________________________________________________________\nflatten (Flatten) (None, 25088) 0 \n_________________________________________________________________\ndense (Dense) (None, 1024) 25691136 \n_________________________________________________________________\ndropout (Dropout) (None, 1024) 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 1024) 1049600 \n_________________________________________________________________\ndropout_1 (Dropout) (None, 1024) 0 \n_________________________________________________________________\ndense_2 (Dense) (None, 101) 103525 \n=================================================================\nWARNING:tensorflow:Discrepancy between trainable weights and collected trainable weights, did you set `model.trainable` without calling `model.compile` after ?\nTotal params: 31,563,877\nTrainable params: 31,563,877\nNon-trainable params: 0\n_________________________________________________________________\n"
]
],
[
[
"## 最適化アルゴリズムなどを指定してモデルをコンパイルする",
"_____no_output_____"
]
],
[
[
"from tensorflow.keras.optimizers import SGD\n\nmodel.compile(\n loss='categorical_crossentropy',\n optimizer=SGD(lr=1e-4, momentum=0.9),\n metrics=['accuracy']\n)",
"_____no_output_____"
]
],
[
[
"## シーケンス生成",
"_____no_output_____"
]
],
[
[
"batch_size = 25\n\nimg_seq_train = ImageSequence(train_list, train_labels, batch_size=batch_size)\n\nimg_seq_validation = ImageSequence(val_list, val_labels, batch_size=batch_size)\n\nprint('Train images =', len(img_seq_train) * batch_size)\nprint('Validation images =', len(img_seq_validation) * batch_size)",
"Train images = 80800\nValidation images = 20200\n"
]
],
[
[
"## Callbackの生成★",
"_____no_output_____"
]
],
[
[
"from tensorflow.keras.callbacks import ModelCheckpoint, CSVLogger, EarlyStopping, ReduceLROnPlateau\n\n\n# Callbacksの設定\ncp_filepath = os.path.join(dir_weights, 'ep_{epoch:04d}_ls_{loss:.1f}.h5')\ncp = ModelCheckpoint(\n cp_filepath, \n monitor='val_acc', \n verbose=0,\n save_best_only=True, \n save_weights_only=True, \n mode='auto'\n )\n\ncsv_filepath = os.path.join(model_dir, 'stage2_loss.csv')\ncsv = CSVLogger(csv_filepath, append=True)\n\nes = EarlyStopping(monitor='val_acc', patience=20, verbose=1, mode='auto')\n\nrl = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=5, verbose=1, mode='auto', epsilon=0.0001, cooldown=0, min_lr=0)",
"WARNING:tensorflow:`epsilon` argument is deprecated and will be removed, use `min_delta` instead.\n"
]
],
[
[
"## 学習",
"_____no_output_____"
]
],
[
[
"n_epoch = 500\ninitial_epoch = len(stage1_loss)\n\n# モデルの学習\nhistory = model.fit_generator(\n img_seq_train, \n epochs=n_epoch, # 学習するエポック数\n steps_per_epoch=len(img_seq_train),\n validation_data=img_seq_validation,\n validation_steps=len(img_seq_validation),\n verbose=1,\n callbacks=[cp, csv, es, rl],\n initial_epoch=initial_epoch\n)",
"Epoch 113/500\n3232/3232 [==============================] - 800s 247ms/step - loss: 1.0005 - acc: 0.7156 - val_loss: 1.5914 - val_acc: 0.6010\nEpoch 114/500\n3232/3232 [==============================] - 797s 247ms/step - loss: 0.8781 - acc: 0.7448 - val_loss: 1.5427 - val_acc: 0.6180\nEpoch 115/500\n3232/3232 [==============================] - 797s 247ms/step - loss: 0.8167 - acc: 0.7629 - val_loss: 1.5274 - val_acc: 0.6247\nEpoch 116/500\n3232/3232 [==============================] - 798s 247ms/step - loss: 0.7525 - acc: 0.7781 - val_loss: 1.5708 - val_acc: 0.6297\nEpoch 117/500\n3232/3232 [==============================] - 797s 247ms/step - loss: 0.7048 - acc: 0.7932 - val_loss: 1.5540 - val_acc: 0.6318\nEpoch 118/500\n3232/3232 [==============================] - 797s 247ms/step - loss: 0.6641 - acc: 0.8020 - val_loss: 1.5949 - val_acc: 0.6291\nEpoch 119/500\n3232/3232 [==============================] - 797s 247ms/step - loss: 0.6321 - acc: 0.8123 - val_loss: 1.6130 - val_acc: 0.6234\nEpoch 120/500\n3231/3232 [============================>.] - ETA: 0s - loss: 0.5969 - acc: 0.8211\nEpoch 00120: ReduceLROnPlateau reducing learning rate to 4.999999873689376e-05.\n3232/3232 [==============================] - 798s 247ms/step - loss: 0.5970 - acc: 0.8211 - val_loss: 1.6113 - val_acc: 0.6308\nEpoch 121/500\n3232/3232 [==============================] - 795s 246ms/step - loss: 0.4443 - acc: 0.8633 - val_loss: 1.6167 - val_acc: 0.6447\nEpoch 122/500\n3232/3232 [==============================] - 795s 246ms/step - loss: 0.4167 - acc: 0.8718 - val_loss: 1.5966 - val_acc: 0.6505\nEpoch 123/500\n3232/3232 [==============================] - 797s 247ms/step - loss: 0.4008 - acc: 0.8754 - val_loss: 1.6456 - val_acc: 0.6497\nEpoch 124/500\n3232/3232 [==============================] - 796s 246ms/step - loss: 0.3804 - acc: 0.8810 - val_loss: 1.6828 - val_acc: 0.6416\nEpoch 125/500\n3231/3232 [============================>.] - ETA: 0s - loss: 0.3632 - acc: 0.8867\nEpoch 00125: ReduceLROnPlateau reducing learning rate to 2.499999936844688e-05.\n3232/3232 [==============================] - 797s 247ms/step - loss: 0.3631 - acc: 0.8867 - val_loss: 1.7106 - val_acc: 0.6474\nEpoch 126/500\n3232/3232 [==============================] - 798s 247ms/step - loss: 0.3005 - acc: 0.9048 - val_loss: 1.6939 - val_acc: 0.6538\nEpoch 127/500\n3232/3232 [==============================] - 806s 249ms/step - loss: 0.2825 - acc: 0.9110 - val_loss: 1.7165 - val_acc: 0.6579\nEpoch 128/500\n3232/3232 [==============================] - 817s 253ms/step - loss: 0.2749 - acc: 0.9121 - val_loss: 1.7501 - val_acc: 0.6525\nEpoch 129/500\n3232/3232 [==============================] - 820s 254ms/step - loss: 0.2679 - acc: 0.9148 - val_loss: 1.7399 - val_acc: 0.6551\nEpoch 130/500\n3231/3232 [============================>.] - ETA: 0s - loss: 0.2595 - acc: 0.9176\nEpoch 00130: ReduceLROnPlateau reducing learning rate to 1.249999968422344e-05.\n3232/3232 [==============================] - 820s 254ms/step - loss: 0.2596 - acc: 0.9175 - val_loss: 1.7587 - val_acc: 0.6537\nEpoch 131/500\n3232/3232 [==============================] - 820s 254ms/step - loss: 0.2359 - acc: 0.9251 - val_loss: 1.7814 - val_acc: 0.6569\nEpoch 132/500\n3232/3232 [==============================] - 821s 254ms/step - loss: 0.2293 - acc: 0.9266 - val_loss: 1.7864 - val_acc: 0.6538\nEpoch 133/500\n3232/3232 [==============================] - 820s 254ms/step - loss: 0.2224 - acc: 0.9280 - val_loss: 1.8053 - val_acc: 0.6551\nEpoch 134/500\n3232/3232 [==============================] - 821s 254ms/step - loss: 0.2197 - acc: 0.9296 - val_loss: 1.8303 - val_acc: 0.6556\nEpoch 135/500\n3231/3232 [============================>.] - ETA: 0s - loss: 0.2140 - acc: 0.9309\nEpoch 00135: ReduceLROnPlateau reducing learning rate to 6.24999984211172e-06.\n3232/3232 [==============================] - 822s 254ms/step - loss: 0.2140 - acc: 0.9309 - val_loss: 1.8030 - val_acc: 0.6560\nEpoch 136/500\n3232/3232 [==============================] - 821s 254ms/step - loss: 0.2012 - acc: 0.9344 - val_loss: 1.8238 - val_acc: 0.6561\nEpoch 137/500\n3232/3232 [==============================] - 819s 253ms/step - loss: 0.1930 - acc: 0.9365 - val_loss: 1.8182 - val_acc: 0.6564\nEpoch 138/500\n3232/3232 [==============================] - 820s 254ms/step - loss: 0.1957 - acc: 0.9361 - val_loss: 1.8219 - val_acc: 0.6602\nEpoch 139/500\n3232/3232 [==============================] - 820s 254ms/step - loss: 0.1906 - acc: 0.9378 - val_loss: 1.8461 - val_acc: 0.6584\nEpoch 140/500\n3231/3232 [============================>.] - ETA: 0s - loss: 0.1932 - acc: 0.9371\nEpoch 00140: ReduceLROnPlateau reducing learning rate to 3.12499992105586e-06.\n3232/3232 [==============================] - 820s 254ms/step - loss: 0.1932 - acc: 0.9370 - val_loss: 1.8270 - val_acc: 0.6564\nEpoch 141/500\n3232/3232 [==============================] - 820s 254ms/step - loss: 0.1843 - acc: 0.9399 - val_loss: 1.8421 - val_acc: 0.6561\nEpoch 142/500\n3232/3232 [==============================] - 819s 253ms/step - loss: 0.1839 - acc: 0.9395 - val_loss: 1.8519 - val_acc: 0.6555\nEpoch 143/500\n3232/3232 [==============================] - 819s 253ms/step - loss: 0.1874 - acc: 0.9393 - val_loss: 1.8423 - val_acc: 0.6567\nEpoch 144/500\n3232/3232 [==============================] - 819s 253ms/step - loss: 0.1796 - acc: 0.9407 - val_loss: 1.8570 - val_acc: 0.6567\nEpoch 145/500\n3231/3232 [============================>.] - ETA: 0s - loss: 0.1810 - acc: 0.9410\nEpoch 00145: ReduceLROnPlateau reducing learning rate to 1.56249996052793e-06.\n3232/3232 [==============================] - 820s 254ms/step - loss: 0.1811 - acc: 0.9410 - val_loss: 1.8457 - val_acc: 0.6565\nEpoch 146/500\n3232/3232 [==============================] - 820s 254ms/step - loss: 0.1767 - acc: 0.9418 - val_loss: 1.8540 - val_acc: 0.6580\nEpoch 147/500\n3232/3232 [==============================] - 819s 253ms/step - loss: 0.1770 - acc: 0.9426 - val_loss: 1.8753 - val_acc: 0.6570\nEpoch 148/500\n3232/3232 [==============================] - 819s 253ms/step - loss: 0.1750 - acc: 0.9437 - val_loss: 1.8755 - val_acc: 0.6546\nEpoch 149/500\n3232/3232 [==============================] - 820s 254ms/step - loss: 0.1793 - acc: 0.9416 - val_loss: 1.8487 - val_acc: 0.6605\nEpoch 150/500\n3231/3232 [============================>.] - ETA: 0s - loss: 0.1760 - acc: 0.9432\nEpoch 00150: ReduceLROnPlateau reducing learning rate to 7.81249980263965e-07.\n3232/3232 [==============================] - 820s 254ms/step - loss: 0.1760 - acc: 0.9431 - val_loss: 1.8431 - val_acc: 0.6596\nEpoch 151/500\n3232/3232 [==============================] - 819s 253ms/step - loss: 0.1734 - acc: 0.9431 - val_loss: 1.8619 - val_acc: 0.6577\nEpoch 152/500\n3232/3232 [==============================] - 820s 254ms/step - loss: 0.1739 - acc: 0.9435 - val_loss: 1.8627 - val_acc: 0.6601\nEpoch 153/500\n3232/3232 [==============================] - 821s 254ms/step - loss: 0.1764 - acc: 0.9424 - val_loss: 1.8549 - val_acc: 0.6571\nEpoch 154/500\n3232/3232 [==============================] - 820s 254ms/step - loss: 0.1703 - acc: 0.9441 - val_loss: 1.8689 - val_acc: 0.6584\nEpoch 155/500\n3231/3232 [============================>.] - ETA: 0s - loss: 0.1709 - acc: 0.9447\nEpoch 00155: ReduceLROnPlateau reducing learning rate to 3.906249901319825e-07.\n3232/3232 [==============================] - 820s 254ms/step - loss: 0.1710 - acc: 0.9446 - val_loss: 1.8620 - val_acc: 0.6582\nEpoch 156/500\n3232/3232 [==============================] - 820s 254ms/step - loss: 0.1721 - acc: 0.9444 - val_loss: 1.8677 - val_acc: 0.6552\nEpoch 157/500\n3232/3232 [==============================] - 818s 253ms/step - loss: 0.1732 - acc: 0.9437 - val_loss: 1.8700 - val_acc: 0.6587\nEpoch 158/500\n3232/3232 [==============================] - 820s 254ms/step - loss: 0.1721 - acc: 0.9439 - val_loss: 1.8744 - val_acc: 0.6567\nEpoch 159/500\n3232/3232 [==============================] - 820s 254ms/step - loss: 0.1722 - acc: 0.9440 - val_loss: 1.8635 - val_acc: 0.6587\nEpoch 160/500\n3231/3232 [============================>.] - ETA: 0s - loss: 0.1714 - acc: 0.9446\nEpoch 00160: ReduceLROnPlateau reducing learning rate to 1.9531249506599124e-07.\n3232/3232 [==============================] - 819s 253ms/step - loss: 0.1713 - acc: 0.9446 - val_loss: 1.8742 - val_acc: 0.6561\nEpoch 161/500\n3232/3232 [==============================] - 821s 254ms/step - loss: 0.1694 - acc: 0.9455 - val_loss: 1.8670 - val_acc: 0.6567\nEpoch 162/500\n3232/3232 [==============================] - 819s 253ms/step - loss: 0.1721 - acc: 0.9440 - val_loss: 1.8659 - val_acc: 0.6552\nEpoch 163/500\n3232/3232 [==============================] - 819s 253ms/step - loss: 0.1702 - acc: 0.9442 - val_loss: 1.8738 - val_acc: 0.6578\nEpoch 164/500\n3232/3232 [==============================] - 819s 254ms/step - loss: 0.1724 - acc: 0.9434 - val_loss: 1.8574 - val_acc: 0.6582\nEpoch 165/500\n3231/3232 [============================>.] - ETA: 0s - loss: 0.1730 - acc: 0.9443\nEpoch 00165: ReduceLROnPlateau reducing learning rate to 9.765624753299562e-08.\n3232/3232 [==============================] - 819s 253ms/step - loss: 0.1730 - acc: 0.9443 - val_loss: 1.8597 - val_acc: 0.6591\nEpoch 166/500\n3232/3232 [==============================] - 819s 253ms/step - loss: 0.1693 - acc: 0.9452 - val_loss: 1.8612 - val_acc: 0.6589\nEpoch 167/500\n3232/3232 [==============================] - 819s 253ms/step - loss: 0.1726 - acc: 0.9441 - val_loss: 1.8629 - val_acc: 0.6604\nEpoch 168/500\n3232/3232 [==============================] - 820s 254ms/step - loss: 0.1700 - acc: 0.9450 - val_loss: 1.8632 - val_acc: 0.6578\nEpoch 169/500\n3232/3232 [==============================] - 818s 253ms/step - loss: 0.1698 - acc: 0.9444 - val_loss: 1.8565 - val_acc: 0.6595\nEpoch 00169: early stopping\n"
]
],
[
[
"# 結果",
"_____no_output_____"
],
[
"## 損失関数のプロット",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(8, 6))\nh = history.history\n\nloss = stage1_loss + h['loss']\nval_loss = stage1_val_loss + h['val_loss']\nep = np.arange(1, len(loss) + 1)\nplt.title('Loss', fontsize=16)\nplt.plot(ep, loss, label='Training')\nplt.plot(ep, val_loss, label='Validation')\nplt.legend(fontsize=16)\nplt.xticks(fontsize=14)\nplt.yticks(fontsize=14)\nplt.xlabel('Epoch', fontsize=16)\nplt.ylabel('Loss', fontsize=16)\nplt.tight_layout()\nsave_fig(plt, file_prefix=os.path.join(model_dir, 'Loss'))\nplt.show()",
"_____no_output_____"
]
],
[
[
"## 正解率のプロット",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(8, 6))\nh = history.history\n\nacc = stage1_acc + h['acc']\nval_acc = stage1_val_acc + h['val_acc']\nep = np.arange(1, len(loss) + 1)\nplt.title('Accuracy', fontsize=16)\nplt.plot(ep, acc, label='Training')\nplt.plot(ep, val_acc, label='Validation')\nplt.legend(fontsize=16)\nplt.xticks(fontsize=14)\nplt.yticks(fontsize=14)\nplt.xlabel('Epoch', fontsize=16)\nplt.ylabel('Accuracy', fontsize=16)\nplt.tight_layout()\nsave_fig(plt, file_prefix=os.path.join(model_dir, 'Loss'))\nplt.show()",
"_____no_output_____"
]
],
[
[
"## 汎化能力の推定",
"_____no_output_____"
]
],
[
[
"from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score\nimport seaborn as sns\n\ndef evalulate(y_true, y_pred, file_prefix=''):\n \n cm = confusion_matrix(y_true, y_pred)\n# print(cm)\n accuracy = accuracy_score(y_true, y_pred)\n precision = precision_score(y_true, y_pred, average=None)\n recall = recall_score(y_true, y_pred, average=None)\n print('正解率')\n print(f' {accuracy}')\n \n class_labels = []\n for i in range(y_true.max() + 1):\n class_labels.append(f'{i:4d}')\n \n precision_str = []\n recall_str = []\n for i in range(y_true.max() + 1):\n precision_str.append(f'{precision[i]}')\n recall_str.append(f'{recall[i]}')\n\n print('精度')\n print(' ' + ' '.join(class_labels))\n print(' ' + ' '.join(precision_str))\n \n print('再現率')\n print(' ' + ' '.join(class_labels))\n print(' ' + ' '.join(recall_str))\n\n plt.figure(figsize = (10,7))\n sns.heatmap(cm, annot=True, fmt='3d', square=True, cmap='hot')\n plt.tight_layout()\n save_fig(plt, file_prefix=file_prefix)\n plt.show()",
"_____no_output_____"
],
[
"import pathlib\n\ncheckpoints = pathlib.Path(model_dir).glob('*.h5')\ncheckpoints = sorted(checkpoints, key=lambda cp:cp.stat().st_mtime)\n\nlatest = str(checkpoints[-1])\nmodel.load_weights(latest)\n\nbatch_size = 25\nimg_seq_validation = ImageSequence(val_list, val_labels, shuffle=False, batch_size=batch_size)\n\ny_pred = model.predict_generator(img_seq_validation)\ny_pred_classes = y_pred.argmax(axis=1)\ny_true = np.array(val_labels)\nevalulate(y_true, y_pred_classes, file_prefix=os.path.join(model_dir, 'cm'))",
"正解率\n 0.6573267326732674\n精度\n 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100\n 0.38235294117647056 0.6367713004484304 0.6298076923076923 0.7309644670050761 0.5566037735849056 0.5891089108910891 0.797979797979798 0.803030303030303 0.45251396648044695 0.505 0.543010752688172 0.7149532710280374 0.7486631016042781 0.6633663366336634 0.5778894472361809 0.44559585492227977 0.5807860262008734 0.5285714285714286 0.5314285714285715 0.6101694915254238 0.6730769230769231 0.5431034482758621 0.4878048780487805 0.7323232323232324 0.6651376146788991 0.7336683417085427 0.46 0.7777777777777778 0.7336448598130841 0.672645739910314 0.8009950248756219 0.6326530612244898 0.8118811881188119 0.9402985074626866 0.7142857142857143 0.7932960893854749 0.6573033707865169 0.4752475247524752 0.6359447004608295 0.39655172413793105 0.7035398230088495 0.7512437810945274 0.5652173913043478 0.7391304347826086 0.6965174129353234 0.7853658536585366 0.6594594594594595 0.5977653631284916 0.6551724137931034 0.5441176470588235 0.5396825396825397 0.7247706422018348 0.7371134020618557 0.648936170212766 0.8571428571428571 0.6666666666666666 0.4647058823529412 0.6136363636363636 0.5625 0.5707070707070707 0.7288888888888889 0.6543778801843319 0.6445497630331753 0.7533039647577092 0.8373205741626795 0.8038277511961722 0.7027027027027027 0.5112359550561798 0.8029556650246306 0.845 0.7453703703703703 0.6966824644549763 0.676923076923077 0.509009009009009 0.7037037037037037 0.8043478260869565 0.7488789237668162 0.3952380952380952 0.7122641509433962 0.7653631284916201 0.5603864734299517 0.7225130890052356 0.5345911949685535 0.7547169811320755 0.5756097560975609 0.65625 0.7395348837209302 0.5110132158590308 0.8238095238095238 0.551219512195122 0.8306878306878307 0.8608247422680413 0.7336956521739131 0.36904761904761907 0.6179245283018868 0.6118721461187214 0.5435897435897435 0.7512953367875648 0.6413043478260869 0.5029940119760479 0.7580645161290323\n再現率\n 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100\n 0.325 0.71 0.655 0.72 0.59 0.595 0.79 0.795 0.405 0.505 0.505 0.765 0.7 0.67 0.575 0.43 0.665 0.555 0.465 0.72 0.7 0.63 0.5 0.725 0.725 0.73 0.46 0.77 0.785 0.75 0.805 0.62 0.82 0.945 0.775 0.71 0.585 0.48 0.69 0.345 0.795 0.755 0.52 0.68 0.7 0.805 0.61 0.535 0.76 0.555 0.51 0.79 0.715 0.61 0.87 0.62 0.395 0.405 0.495 0.565 0.82 0.71 0.68 0.855 0.875 0.84 0.65 0.455 0.815 0.845 0.805 0.735 0.66 0.565 0.665 0.925 0.835 0.415 0.755 0.685 0.58 0.69 0.425 0.8 0.59 0.63 0.795 0.58 0.865 0.565 0.785 0.835 0.675 0.31 0.655 0.67 0.53 0.725 0.59 0.42 0.705\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
d083e5f477c121a8a3e79837058a41277c7da177 | 211,519 | ipynb | Jupyter Notebook | tutorials/Tutorial14_Query_Classifier.ipynb | askainet/haystack | 00aa1f41d7c21273d8c312a3fad0b51ddd446672 | [
"Apache-2.0"
] | null | null | null | tutorials/Tutorial14_Query_Classifier.ipynb | askainet/haystack | 00aa1f41d7c21273d8c312a3fad0b51ddd446672 | [
"Apache-2.0"
] | null | null | null | tutorials/Tutorial14_Query_Classifier.ipynb | askainet/haystack | 00aa1f41d7c21273d8c312a3fad0b51ddd446672 | [
"Apache-2.0"
] | null | null | null | 31.169909 | 407 | 0.594382 | [
[
[
"# Query Classifier Tutorial\n[](https://colab.research.google.com/github/deepset-ai/haystack/blob/master/tutorials/Tutorial14_Query_Classifier.ipynb)\n\nIn this tutorial we introduce the query classifier the goal of introducing this feature was to optimize the overall flow of Haystack pipeline by detecting the nature of user queries. Now, the Haystack can detect primarily three types of queries using both light-weight SKLearn Gradient Boosted classifier or Transformer based more robust classifier. The three categories of queries are as follows:\n\n\n### 1. Keyword Queries: \nSuch queries don't have semantic meaning and merely consist of keywords. For instance these three are the examples of keyword queries.\n\n* arya stark father\n* jon snow country\n* arya stark younger brothers\n\n### 2. Interrogative Queries: \nIn such queries users usually ask a question, regardless of presence of \"?\" in the query the goal here is to detect the intent of the user whether any question is asked or not in the query. For example:\n\n* who is the father of arya stark ?\n* which country was jon snow filmed ?\n* who are the younger brothers of arya stark ?\n\n### 3. Declarative Queries: \nSuch queries are variation of keyword queries, however, there is semantic relationship between words. Fo example:\n\n* Arya stark was a daughter of a lord.\n* Jon snow was filmed in a country in UK.\n* Bran was brother of a princess.\n\nIn this tutorial, you will learn how the `TransformersQueryClassifier` and `SklearnQueryClassifier` classes can be used to intelligently route your queries, based on the nature of the user query. Also, you can choose between a lightweight Gradients boosted classifier or a transformer based classifier.\n\nFurthermore, there are two types of classifiers you can use out of the box from Haystack.\n1. Keyword vs Statement/Question Query Classifier\n2. Statement vs Question Query Classifier\n\nAs evident from the name the first classifier detects the keywords search queries and semantic statements like sentences/questions. The second classifier differentiates between question based queries and declarative sentences.",
"_____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/img/colab_gpu_runtime.jpg\">",
"_____no_output_____"
],
[
"These lines are to install Haystack through pip",
"_____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 --upgrade pip\n!pip install git+https://github.com/deepset-ai/haystack.git#egg=farm-haystack[colab]\n\n# Install pygraphviz\n!apt install libgraphviz-dev\n!pip install pygraphviz\n\n# 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\n\nes_server = Popen(\n [\"elasticsearch-7.9.2/bin/elasticsearch\"], stdout=PIPE, stderr=STDOUT, preexec_fn=lambda: os.setuid(1) # as daemon\n)\n# wait until ES has started\n! sleep 30",
"_____no_output_____"
]
],
[
[
"If running from Colab or a no Docker environment, you will want to start Elasticsearch from source",
"_____no_output_____"
],
[
"## Initialization\n\nHere are some core imports",
"_____no_output_____"
],
[
"Then let's fetch some data (in this case, pages from the Game of Thrones wiki) and prepare it so that it can\nbe used indexed into our `DocumentStore`",
"_____no_output_____"
]
],
[
[
"from haystack.utils import (\n print_answers,\n print_documents,\n fetch_archive_from_http,\n convert_files_to_docs,\n clean_wiki_text,\n launch_es,\n)\nfrom haystack.pipelines import Pipeline\nfrom haystack.document_stores import ElasticsearchDocumentStore\nfrom haystack.nodes import (\n BM25Retriever,\n EmbeddingRetriever,\n FARMReader,\n TransformersQueryClassifier,\n SklearnQueryClassifier,\n)\n\n# Download and prepare data - 517 Wikipedia articles for Game of Thrones\ndoc_dir = \"data/tutorial14\"\ns3_url = \"https://s3.eu-central-1.amazonaws.com/deepset.ai-farm-qa/datasets/documents/wiki_gameofthrones_txt14.zip\"\nfetch_archive_from_http(url=s3_url, output_dir=doc_dir)\n\n# convert files to dicts containing documents that can be indexed to our datastore\ngot_docs = convert_files_to_docs(dir_path=doc_dir, clean_func=clean_wiki_text, split_paragraphs=True)\n\n# Initialize DocumentStore and index documents\nlaunch_es()\ndocument_store = ElasticsearchDocumentStore()\ndocument_store.delete_documents()\ndocument_store.write_documents(got_docs)\n\n# Initialize Sparse retriever\nbm25_retriever = BM25Retriever(document_store=document_store)\n\n# Initialize dense retriever\nembedding_retriever = EmbeddingRetriever(\n document_store=document_store,\n model_format=\"sentence_transformers\",\n embedding_model=\"sentence-transformers/multi-qa-mpnet-base-dot-v1\",\n)\ndocument_store.update_embeddings(embedding_retriever, update_existing_embeddings=False)\n\nreader = FARMReader(model_name_or_path=\"deepset/roberta-base-squad2\")",
"_____no_output_____"
]
],
[
[
"## Keyword vs Question/Statement Classifier\n\nThe keyword vs question/statement query classifier essentially distinguishes between the keyword queries and statements/questions. So you can intelligently route to different retrieval nodes based on the nature of the query. Using this classifier can potentially yield the following benefits:\n\n* Getting better search results (e.g. by routing only proper questions to DPR / QA branches and not keyword queries)\n* Less GPU costs (e.g. if 50% of your traffic is only keyword queries you could just use elastic here and save the GPU resources for the other 50% of traffic with semantic queries)\n\n![image]()\n",
"_____no_output_____"
],
[
"Below, we define a `SklearnQueryClassifier` and show how to use it:\n\nRead more about the trained model and dataset used [here](https://ext-models-haystack.s3.eu-central-1.amazonaws.com/gradboost_query_classifier/readme.txt)",
"_____no_output_____"
]
],
[
[
"# Here we build the pipeline\nsklearn_keyword_classifier = Pipeline()\nsklearn_keyword_classifier.add_node(component=SklearnQueryClassifier(), name=\"QueryClassifier\", inputs=[\"Query\"])\nsklearn_keyword_classifier.add_node(\n component=embedding_retriever, name=\"EmbeddingRetriever\", inputs=[\"QueryClassifier.output_1\"]\n)\nsklearn_keyword_classifier.add_node(component=bm25_retriever, name=\"ESRetriever\", inputs=[\"QueryClassifier.output_2\"])\nsklearn_keyword_classifier.add_node(component=reader, name=\"QAReader\", inputs=[\"ESRetriever\", \"EmbeddingRetriever\"])\nsklearn_keyword_classifier.draw(\"pipeline_classifier.png\")",
"_____no_output_____"
],
[
"# Run only the dense retriever on the full sentence query\nres_1 = sklearn_keyword_classifier.run(query=\"Who is the father of Arya Stark?\")\nprint(\"Embedding Retriever Results\" + \"\\n\" + \"=\" * 15)\nprint_answers(res_1, details=\"minimum\")\n\n# Run only the sparse retriever on a keyword based query\nres_2 = sklearn_keyword_classifier.run(query=\"arya stark father\")\nprint(\"ES Results\" + \"\\n\" + \"=\" * 15)\nprint_answers(res_2, details=\"minimum\")",
"_____no_output_____"
],
[
"# Run only the dense retriever on the full sentence query\nres_3 = sklearn_keyword_classifier.run(query=\"which country was jon snow filmed ?\")\nprint(\"Embedding Retriever Results\" + \"\\n\" + \"=\" * 15)\nprint_answers(res_3, details=\"minimum\")\n\n# Run only the sparse retriever on a keyword based query\nres_4 = sklearn_keyword_classifier.run(query=\"jon snow country\")\nprint(\"ES Results\" + \"\\n\" + \"=\" * 15)\nprint_answers(res_4, details=\"minimum\")",
"_____no_output_____"
],
[
"# Run only the dense retriever on the full sentence query\nres_5 = sklearn_keyword_classifier.run(query=\"who are the younger brothers of arya stark ?\")\nprint(\"Embedding Retriever Results\" + \"\\n\" + \"=\" * 15)\nprint_answers(res_5, details=\"minimum\")\n\n# Run only the sparse retriever on a keyword based query\nres_6 = sklearn_keyword_classifier.run(query=\"arya stark younger brothers\")\nprint(\"ES Results\" + \"\\n\" + \"=\" * 15)\nprint_answers(res_6, details=\"minimum\")",
"_____no_output_____"
]
],
[
[
"## Transformer Keyword vs Question/Statement Classifier\n\nFirstly, it's essential to understand the trade-offs between SkLearn and Transformer query classifiers. The transformer classifier is more accurate than SkLearn classifier however, it requires more memory and most probably GPU for faster inference however the transformer size is roughly `50 MBs`. Whereas, SkLearn is less accurate however is much more faster and doesn't require GPU for inference.\n\nBelow, we define a `TransformersQueryClassifier` and show how to use it:\n\nRead more about the trained model and dataset used [here](https://huggingface.co/shahrukhx01/bert-mini-finetune-question-detection)",
"_____no_output_____"
]
],
[
[
"# Here we build the pipeline\ntransformer_keyword_classifier = Pipeline()\ntransformer_keyword_classifier.add_node(\n component=TransformersQueryClassifier(), name=\"QueryClassifier\", inputs=[\"Query\"]\n)\ntransformer_keyword_classifier.add_node(\n component=embedding_retriever, name=\"EmbeddingRetriever\", inputs=[\"QueryClassifier.output_1\"]\n)\ntransformer_keyword_classifier.add_node(\n component=bm25_retriever, name=\"ESRetriever\", inputs=[\"QueryClassifier.output_2\"]\n)\ntransformer_keyword_classifier.add_node(component=reader, name=\"QAReader\", inputs=[\"ESRetriever\", \"EmbeddingRetriever\"])\ntransformer_keyword_classifier.draw(\"pipeline_classifier.png\")",
"_____no_output_____"
],
[
"# Run only the dense retriever on the full sentence query\nres_1 = transformer_keyword_classifier.run(query=\"Who is the father of Arya Stark?\")\nprint(\"Embedding Retriever Results\" + \"\\n\" + \"=\" * 15)\nprint_answers(res_1, details=\"minimum\")\n\n# Run only the sparse retriever on a keyword based query\nres_2 = transformer_keyword_classifier.run(query=\"arya stark father\")\nprint(\"ES Results\" + \"\\n\" + \"=\" * 15)\nprint_answers(res_2, details=\"minimum\")",
"_____no_output_____"
],
[
"# Run only the dense retriever on the full sentence query\nres_3 = transformer_keyword_classifier.run(query=\"which country was jon snow filmed ?\")\nprint(\"Embedding Retriever Results\" + \"\\n\" + \"=\" * 15)\nprint_answers(res_3, details=\"minimum\")\n\n# Run only the sparse retriever on a keyword based query\nres_4 = transformer_keyword_classifier.run(query=\"jon snow country\")\nprint(\"ES Results\" + \"\\n\" + \"=\" * 15)\nprint_answers(res_4, details=\"minimum\")",
"_____no_output_____"
],
[
"# Run only the dense retriever on the full sentence query\nres_5 = transformer_keyword_classifier.run(query=\"who are the younger brothers of arya stark ?\")\nprint(\"Embedding Retriever Results\" + \"\\n\" + \"=\" * 15)\nprint_answers(res_5, details=\"minimum\")\n\n# Run only the sparse retriever on a keyword based query\nres_6 = transformer_keyword_classifier.run(query=\"arya stark younger brothers\")\nprint(\"ES Results\" + \"\\n\" + \"=\" * 15)\nprint_answers(res_6, details=\"minimum\")",
"_____no_output_____"
]
],
[
[
"## Question vs Statement Classifier\n\nOne possible use case of this classifier could be to route queries after the document retrieval to only send questions to QA reader and in case of declarative sentence, just return the DPR/ES results back to user to enhance user experience and only show answers when user explicitly asks it.\n\n![image]()\n",
"_____no_output_____"
],
[
"Below, we define a `TransformersQueryClassifier` and show how to use it:\n\nRead more about the trained model and dataset used [here](https://huggingface.co/shahrukhx01/question-vs-statement-classifier)",
"_____no_output_____"
]
],
[
[
"# Here we build the pipeline\ntransformer_question_classifier = Pipeline()\ntransformer_question_classifier.add_node(component=embedding_retriever, name=\"EmbeddingRetriever\", inputs=[\"Query\"])\ntransformer_question_classifier.add_node(\n component=TransformersQueryClassifier(model_name_or_path=\"shahrukhx01/question-vs-statement-classifier\"),\n name=\"QueryClassifier\",\n inputs=[\"EmbeddingRetriever\"],\n)\ntransformer_question_classifier.add_node(component=reader, name=\"QAReader\", inputs=[\"QueryClassifier.output_1\"])\ntransformer_question_classifier.draw(\"question_classifier.png\")\n\n# Run only the QA reader on the question query\nres_1 = transformer_question_classifier.run(query=\"Who is the father of Arya Stark?\")\nprint(\"Embedding Retriever Results\" + \"\\n\" + \"=\" * 15)\nprint_answers(res_1, details=\"minimum\")\n\nres_2 = transformer_question_classifier.run(query=\"Arya Stark was the daughter of a Lord.\")\nprint(\"ES Results\" + \"\\n\" + \"=\" * 15)\nprint_documents(res_2)",
"_____no_output_____"
]
],
[
[
"## Standalone Query Classifier\nBelow we run queries classifiers standalone to better understand their outputs on each of the three types of queries",
"_____no_output_____"
]
],
[
[
"# Here we create the keyword vs question/statement query classifier\nfrom haystack.nodes import TransformersQueryClassifier\n\nqueries = [\n \"arya stark father\",\n \"jon snow country\",\n \"who is the father of arya stark\",\n \"which country was jon snow filmed?\",\n]\n\nkeyword_classifier = TransformersQueryClassifier()\n\nfor query in queries:\n result = keyword_classifier.run(query=query)\n if result[1] == \"output_1\":\n category = \"question/statement\"\n else:\n category = \"keyword\"\n\n print(f\"Query: {query}, raw_output: {result}, class: {category}\")",
"_____no_output_____"
],
[
"# Here we create the question vs statement query classifier\nfrom haystack.nodes import TransformersQueryClassifier\n\nqueries = [\n \"Lord Eddard was the father of Arya Stark.\",\n \"Jon Snow was filmed in United Kingdom.\",\n \"who is the father of arya stark?\",\n \"Which country was jon snow filmed in?\",\n]\n\nquestion_classifier = TransformersQueryClassifier(model_name_or_path=\"shahrukhx01/question-vs-statement-classifier\")\n\nfor query in queries:\n result = question_classifier.run(query=query)\n if result[1] == \"output_1\":\n category = \"question\"\n else:\n category = \"statement\"\n\n print(f\"Query: {query}, raw_output: {result}, class: {category}\")",
"_____no_output_____"
]
],
[
[
"## Conclusion\n\nThe query classifier gives you more possibility to be more creative with the pipelines and use different retrieval nodes in a flexible fashion. Moreover, as in the case of Question vs Statement classifier you can also choose the queries which you want to send to the reader.\n\nFinally, you also have the possible of bringing your own classifier and plugging it into either `TransformersQueryClassifier(model_name_or_path=\"<huggingface_model_name_or_file_path>\")` or using the `SklearnQueryClassifier(model_name_or_path=\"url_to_classifier_or_file_path_as_pickle\", vectorizer_name_or_path=\"url_to_vectorizer_or_file_path_as_pickle\")`",
"_____no_output_____"
],
[
"## About us\n\nThis [Haystack](https://github.com/deepset-ai/haystack/) notebook was made with love by [deepset](https://deepset.ai/) in Berlin, Germany\n\nWe bring NLP to the industry via open source! \nOur focus: Industry specific language models & large scale QA systems.\n \nSome of our other work: \n- [German BERT](https://deepset.ai/german-bert)\n- [GermanQuAD and GermanDPR](https://deepset.ai/germanquad)\n- [FARM](https://github.com/deepset-ai/FARM)\n\nGet in touch:\n[Twitter](https://twitter.com/deepset_ai) | [LinkedIn](https://www.linkedin.com/company/deepset-ai/) | [Slack](https://haystack.deepset.ai/community/join) | [GitHub Discussions](https://github.com/deepset-ai/haystack/discussions) | [Website](https://deepset.ai)\n\nBy the way: [we're hiring!](https://www.deepset.ai/jobs) ",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
d083f215df0693ac61f1f1f0a5566aa81e80761b | 4,697 | ipynb | Jupyter Notebook | chapter02_best_practices/07_test.ipynb | tkondoh1022/cookbook-2nd-code | 52d8c6c0a199a9009dfaccbac3cc2e8dfd21a859 | [
"MIT"
] | 645 | 2018-02-01T09:16:45.000Z | 2022-03-03T17:47:59.000Z | chapter02_best_practices/07_test.ipynb | wangbin0619/cookbook-2nd-code | acd2ea2e55838f9bb3fc92a23aa991b3320adcaf | [
"MIT"
] | 3 | 2019-03-11T09:47:21.000Z | 2022-01-11T06:32:00.000Z | chapter02_best_practices/07_test.ipynb | wangbin0619/cookbook-2nd-code | acd2ea2e55838f9bb3fc92a23aa991b3320adcaf | [
"MIT"
] | 418 | 2018-02-13T03:17:05.000Z | 2022-03-18T21:04:45.000Z | 20.875556 | 66 | 0.431765 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
d083fb7dd7c6b22f9439a4f61c0dd3773b410c4d | 857,241 | ipynb | Jupyter Notebook | stats_overview/03_STATS.ipynb | minireference/noBSstatsnotebooks | 1037042a0e2747f65cdca463f58c3a6a18c02e64 | [
"MIT"
] | 13 | 2021-09-18T08:22:51.000Z | 2022-03-29T13:08:59.000Z | stats_overview/03_STATS.ipynb | minireference/noBSstatsnotebooks | 1037042a0e2747f65cdca463f58c3a6a18c02e64 | [
"MIT"
] | null | null | null | stats_overview/03_STATS.ipynb | minireference/noBSstatsnotebooks | 1037042a0e2747f65cdca463f58c3a6a18c02e64 | [
"MIT"
] | 2 | 2021-08-24T16:13:44.000Z | 2021-12-05T09:32:04.000Z | 383.724709 | 461,136 | 0.929889 | [
[
[
"# Chapter 3: Inferential statistics\n\n[Link to outline](https://docs.google.com/document/d/1fwep23-95U-w1QMPU31nOvUnUXE2X3s_Dbk5JuLlKAY/edit#heading=h.uutryzqeo2av)\n\nConcept map:\n\n",
"_____no_output_____"
],
[
"#### Notebook setup",
"_____no_output_____"
]
],
[
[
"# loading Python modules\nimport math\nimport random\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom scipy.stats.distributions import norm\n\n# set random seed for repeatability\nnp.random.seed(42)\n\n# notebooks figs setup\n%matplotlib inline\nimport matplotlib.pyplot as plt\nsns.set(rc={'figure.figsize':(8,5)})\nblue, orange = sns.color_palette()[0], sns.color_palette()[1]\n\n# silence annoying warnings\nimport warnings; warnings.filterwarnings('ignore')",
"_____no_output_____"
]
],
[
[
"## Overview\n\n- Main idea = learn about a population based on a sample\n- Recall Amy's two research questions about the employee lifetime value (ELV) data:\n - Question 1 = Is there a difference between ELV of the two groups? → **hypothesis testing**\n - Question 2 = How much difference in ELV does stats training provide? → **estimation**\n- Inferential statistics provides us with tools to answer both of these questions",
"_____no_output_____"
],
[
"## Estimators\n\nWe'll begin our study of inferential statistics by introducing **estimators**,\nwhich are used for both **hypothesis testing** and **estimation**.\n\n\n",
"_____no_output_____"
],
[
" ",
"_____no_output_____"
],
[
" ",
"_____no_output_____"
],
[
"$\\def\\stderr#1{\\mathbf{se}_{#1}}$\n$\\def\\stderrhat#1{\\hat{\\mathbf{se}}_{#1}}$\n\n### Definitions\n\n- We use the term \"estimator\" to describe a function $f$ that takes samples as inputs,\n which is written mathematically as:\n $$\n f \\ \\colon \\underbrace{\\mathcal{X}\\times \\mathcal{X}\\times \\cdots \\times \\mathcal{X}}_{n \\textrm{ copies}}\n \\quad \\to \\quad \\mathbb{R},\n $$\n where $n$ is the samples size and $\\mathcal{X}$ denotes the possible values of the random variable $X$.\n- We give different names to estimators, depending on the use case:\n - **statistic** = a function computed from samples (descriptive statistics)\n - **parameter estimators** = statistics that estimates population parameters\n - **test statistic** = an estimator used as part of hypothesis testing procedure\n- The **value** of the estimator $f(\\mathbf{x})$ is computer from a particular sample $\\mathbf{x}$.\n- The **sampling distribution** of an estimator is when $f$ is the distribution of $f(\\mathbf{X})$,\n where $\\mathbf{X}$ is a random sample.\n- Example of estimators we discussed in descriptive statistics:\n - Sample mean\n - estimator: $\\overline{x} = g(\\mathbf{x}) = \\frac{1}{n}\\sum_{i=1}^n x_i$\n - gives an estimate for the population mean $\\mu$\n - sampling distribution: $\\overline{X} = g(\\mathbf{X}) = \\frac{1}{n}\\sum_{i=1}^n X_i$\n - Sample variance\n - estimator: $s^2 = h(\\mathbf{x}) = \\frac{1}{n-1}\\sum_{i=1}^n (x_i-\\overline{x})^2$\n - gives an estimate for the population variance $\\sigma^2$\n - sampling distribution: $S^2 = h(\\mathbf{X}) = \\frac{1}{n-1}\\sum_{i=1}^n (X_i-\\overline{X})^2$\n \n- In this notebook we focus on one estimator: **difference between group means**\n - estimator: $d = \\texttt{mean}(\\mathbf{x}_A) - \\texttt{mean}(\\mathbf{x}_{B}) = \\overline{x}_{A} - \\overline{x}_{B}$\n - gives an estimate for the difference between population means: $\\Delta = \\mu_A - \\mu_{B}$\n - sampling distribution: $D = \\overline{X}_A - \\overline{X}_{B}$, which is a random variable",
"_____no_output_____"
],
[
" ",
"_____no_output_____"
],
[
" ",
"_____no_output_____"
],
[
"### Difference between group means\n\nConsider two random variables $X_A$ and $X_B$:\n$$ \\large\nX_A \\sim \\mathcal{N}\\!\\left(\\mu_A, \\sigma^2_A \\right)\n\\qquad\n\\textrm{and}\n\\qquad\nX_B \\sim \\mathcal{N}\\!\\left(\\mu_B, \\sigma^2_B \\right)\n$$\nthat describe the probability distribution for groups A and B, respectively.\n\n- A sample of size $n_A$ from $X_A$ is denoted $\\mathbf{x}_A = x_1x_2\\cdots x_{n_A}$=`xA`, and let $\\mathbf{x}_B = x_1x_2\\cdots x_{n_B}$=`xB` be a random sample of size $n_B$ from $X_B$.\n- We compute the mean in each group: $\\overline{x}_{A} = \\texttt{mean}(\\mathbf{x}_A)$\n and $\\overline{x}_{B} = \\texttt{mean}(\\mathbf{x}_B)$\n- The value of the estimator is $d = \\overline{x}_{A} - \\overline{x}_{B}$",
"_____no_output_____"
]
],
[
[
"def dmeans(xA, xB):\n \"\"\"\n Estimator for the difference between group means.\n \"\"\"\n d = np.mean(xA) - np.mean(xB)\n return d",
"_____no_output_____"
]
],
[
[
"Note the difference between group means is precisely the estimator Amy need for her analysis (**Group S** and **Group NS**). We intentionally use the labels **A** and **B** to illustrate the general case.",
"_____no_output_____"
]
],
[
[
"# example parameters for each group\nmuA, sigmaA = 300, 10\nmuB, sigmaB = 200, 20\n\n# size of samples for each group\nnA = 5\nnB = 4",
"_____no_output_____"
]
],
[
[
"#### Particular value of the estimator `dmeans`",
"_____no_output_____"
]
],
[
[
"xA = norm(muA, sigmaA).rvs(nA) # random sample from Group A\nxB = norm(muB, sigmaB).rvs(nB) # random sample from Group B\n\nd = dmeans(xA, xB)\nd",
"_____no_output_____"
]
],
[
[
"The value of $d$ computed from the samples is an estimate for the difference between means of two groups: $\\Delta = \\mu_A - \\mu_{B}$ (which we know is $100$ in this example).",
"_____no_output_____"
],
[
"#### Sampling distribution of the estimator `dmeans`\n\nHow well does the estimate $d$ approximate the true value $\\Delta$?\n**What is the accuracy and variability of the estimates we can expect?**\n\nTo answer these questions, consider the random samples\n$\\mathbf{X}_A = X_1X_2\\cdots X_{n_A}$\nand $\\mathbf{X}_B = X_1X_2\\cdots X_{n_B}$,\nthen compute the **sampling distribution**: $D = \\overline{X}_A - \\overline{X}_{B}$.\n\nBy definition, the sampling distribution of the estimator is obtained by repeatedly generating samples `xA` and `xB` from the two distributions and computing `dmeans` on the random samples. For example, we can obtain the sampling distribution by generating $N=1000$ samples.",
"_____no_output_____"
]
],
[
[
"def get_sampling_dist(statfunc, meanA, stdA, nA, meanB, stdB, nB, N=1000):\n \"\"\"\n Obtain the sampling distribution of the statistic `statfunc`\n from `N` random samples drawn from groups A and B with parmeters:\n - Group A: `nA` values taken from `norm(meanA, stdA)`\n - Group B: `nB` values taken from `norm(meanB, stdB)`\n Returns a list of samples from the sampling distribution of `statfunc`.\n \"\"\"\n sampling_dist = [] \n for i in range(0, N):\n xA = norm(meanA, stdA).rvs(nA) # random sample from Group A\n xB = norm(meanB, stdB).rvs(nB) # random sample from Group B\n stat = statfunc(xA, xB) # evaluate `statfunc`\n sampling_dist.append(stat) # record the value of statfunc\n return sampling_dist\n",
"_____no_output_____"
],
[
"# Generate the sampling distirbution for dmeans\ndmeans_sdist = get_sampling_dist(statfunc=dmeans,\n meanA=muA, stdA=sigmaA, nA=nA,\n meanB=muB, stdB=sigmaB, nB=nB)\n\nprint(\"Generated\", len(dmeans_sdist), \"values from `dmeans(XA, XB)`\")",
"Generated 1000 values from `dmeans(XA, XB)`\n"
],
[
"# first 3 values\ndmeans_sdist[0:3]",
"_____no_output_____"
]
],
[
[
"#### Plot the sampling distribution of `dmeans`",
"_____no_output_____"
]
],
[
[
"fig3, ax3 = plt.subplots()\ntitle3 = \"Samping distribution of D = mean($\\mathbf{X}_A$) - mean($\\mathbf{X}_B$) \" + \\\n \"for samples of size $n_A$ = \" + str(nA) + \\\n \" from $\\mathcal{N}$(\" + str(muA) + \",\" + str(sigmaA) + \")\" + \\\n \" and $n_B$ = \" + str(nB) + \\\n \" from $\\mathcal{N}$(\" + str(muB) + \",\" + str(sigmaB) + \")\"\nsns.distplot(dmeans_sdist, kde=False, norm_hist=True, ax=ax3)\n_ = ax3.set_title(title3)",
"_____no_output_____"
]
],
[
[
"#### Theoretical model for the sampling distribution of `dmeans`",
"_____no_output_____"
],
[
"Let's use probability theory to build a theoretical model for the sampling distribution of the difference-between-means estimator `dmeans`.\n\n- The central limit theorem \n\n\nthe rules of to obtain a model for the random variable $D = \\overline{X}_A - \\overline{X}_{B}$,\nwhich describes the sampling distribution of `dmeans`.\n\n- The central limit theorem tells us the sample mean within the two group are\n $$ \\large\n \\overline{X}_A \\sim \\mathcal{N}\\!\\left(\\mu_A, \\tfrac{\\sigma^2_A}{n_A} \\right)\n \\qquad \\textrm{and} \\qquad\n \\overline{X}_B \\sim \\mathcal{N}\\!\\left(\\mu_B, \\tfrac{\\sigma^2_B}{n_B} \\right)\n $$\n\n- The rules of probability theory tells us that the [difference of two normal random variables](https://en.wikipedia.org/wiki/Sum_of_normally_distributed_random_variables#Independent_random_variables) requires subtracting their means and adding their variance, so we get:\n $$ \\large\n D \\sim \\mathcal{N}\\!\\left(\\mu_A - \\mu_B, \\ \\tfrac{\\sigma^2_A}{n_A} + \\tfrac{\\sigma^2_B}{n_B} \\right)\n $$\n\nIn other words, the sampling distribution for the difference of means estimator has mean and standard deviation given by:\n$$ \\large\n \\mu_D = \\mu_A - \\mu_B\n \\qquad \\textrm{and} \\qquad\n \\sigma_D = \\sqrt{ \\tfrac{\\sigma^2_A}{n_A} + \\tfrac{\\sigma^2_B}{n_B} }\n$$\n\nLet's plot the theoretical prediction on top of the simulated data to see if they are a good fit.",
"_____no_output_____"
]
],
[
[
"Dmean = muA - muB\nDstd = np.sqrt(sigmaA**2/nA + sigmaB**2/nB)\nprint(\"Probability theory predicts the sampling distribution had\"\n \"mean\", round(Dmean, 3),\n \"and standard deviation\", round(Dstd, 3))\n\nx = np.linspace(min(dmeans_sdist), max(dmeans_sdist), 10000)\nD = norm(Dmean, Dstd).pdf(x)\nlabel = 'Theory prediction'\nax3 = sns.lineplot(x, D, ax=ax3, label=label, color=blue)\nfig3",
"Probability theory predicts the sampling distribution hadmean 100 and standard deviation 10.954\n"
]
],
[
[
" \n ",
"_____no_output_____"
],
[
" ",
"_____no_output_____"
],
[
"### Regroup and reality check\n\nHow are you doing, dear readers?\nI know this was a lot of math and a lot of code, but the good news is we're done now!\nThe key things to remember is that we have two ways to compute sampling distribution for any estimator:\n - Repeatedly generate random samples from model and compute the estimator values (histogram)\n - Use probability theory to obtain a analytical formula\n\n\n#### Why are we doing all this modelling?\n\nThe estimator `dmeans` we defined above measures the quantity we're interested in: \nthe difference between the means of two groups (**Group S** and **Group NS** in Amy's statistical analysis of ELV data).\n\nUsing the functions we developed above, we now have the ability to simulate the data from any two groups by simply choosing the appropriate parameters. In particular if we choose `stdS=266`, `nS=30`; and `stdNS=233`, `nNS=31`,\nwe can generate random data that has similar variability to Amy ELV measurements.",
"_____no_output_____"
],
[
" ",
"_____no_output_____"
],
[
"Okay, dear reader, we're about to jump into the deep end of the statistics pool: **hypothesis testing**,\nwhich is one of the two major ideas in the STATS 101 curriculum.\nHeads up this will get complicated, but we have to go into it because it is an essential procedure\nthat is used widely in science, engineering, business, and other types of research.\nYou need to trust me this one: it's worth knowing this stuff, even if it is boring.\nDon't worry about it though, since you have all the prerequisites needed to get through this!\n",
"_____no_output_____"
],
[
"____\n\n\nRecall Amy's research Question 1: \n\nIs there a difference between ELV of the employees in **Group S** and the employees in **Group NS**?\n",
"_____no_output_____"
],
[
"## Hypothesis testing\n\n- An approach to formulating research questions as **yes-no decisions** and a **procedure for making these decisions**\n- Hypothesis testing is a standardized procedure for doing statistical analysis \n (also, using stats jargon makes everything look more convincing ;)\n- We formulate research question as two **competing hypotheses**:\n - **Null hypothesis $H_0$** = no effect \n in our example: \"no difference between means,\" which is written as $\\color{red}{\\mu_S = \\mu_{NS} = \\mu_0}$. \n In other words, the probability models for the two groups are:\n $$ \\large\n H_0: \\qquad X_S = \\mathcal{N}(\\color{red}{\\mu_0}, \\sigma_S)\n \\quad \\textrm{and} \\quad\n X_{NS} = \\mathcal{N}(\\color{red}{\\mu_0}, \\sigma_{NS}) \\quad\n $$\n - **Alternative hypothesis $H_A$** = an effect exists \n in our example: \"means for Group S different from mean for Group NS\", $\\color{blue}{\\mu_S} \\neq \\color{orange}{\\mu_{NS}}$. \n The probability models for the two groups are:\n $$ \n H_A: \\qquad X_S = \\mathcal{N}(\\color{blue}{\\mu_S}, \\sigma_S)\n \\quad \\textrm{and} \\quad\n X_{NS} = \\mathcal{N}(\\color{orange}{\\mu_{NS}}, \\sigma_{NS})\n $$\n- The purpose of hypothesis testing is to perform a basic sanity-check to show the difference between the group means\n we observed ($d = \\overline{x}_{S} - \\overline{x}_{NS} = 130$) is **unlikely to have occurred by chance**\n- NEW CONCEPT: $p$-value is the probability of observing $d$ or more extreme under the null hypothesis.",
"_____no_output_____"
],
[
"### Overview of the hypothesis testing procedure\n\nHere is the high-level overview of the hypothesis testing procedure:\n- **inputs**: sample statistics computed from the observed data\n (in our case the signal $\\overline{x}_S$, $\\overline{x}_{NS}$,\n and our estimates of the noise $s^2_S$, and $s^2_{NS}$)\n- **outputs**: a decision that is one of: \"reject the null hypothesis\" or \"fail to reject the null hypothesis\"\n\n\n\nWe'll now look at two different approaches for computing the sampling distribution of\nthe difference between group means statistic, $D = \\overline{X}_S - \\overline{X}_{NS}$:\npermutation tests and analytical approximations.",
"_____no_output_____"
],
[
"### Interpreting the results of hypothesis testing (optional)\n",
"_____no_output_____"
],
[
"\n- The implication of rejecting the null hypothesis (no difference) is that there must is a difference between the group means.\n In other words, the ELV data for employees who took the statistics training (**Group S**) is different form\n the average ELV for employees who didn't take the statistics training (**Group NS**),\n which is what Amy is trying to show.\n - Note that rejecting null hypothesis (H0) is not the same as \"proving\" the alternative hypothesis (HA),\n we have just shown that the data is unlikely under the null hypothesis and we must be *some* difference between the groups,\n so is worth looking for *some* alternative hypothesis.\n - The alternative hypothesis we picked above, $\\mu_S \\neq \\mu_{NS}$, is just a placeholder,\n that includes desirable effect: $\\mu_S > \\mu_{NS}$ (stats training improves ELV),\n but also includes the opposite effect: $\\mu_S < \\mu_{NS}$ (stats training decreases ELV).\n - Using statistics jargon, when we reject the hypothesis H0 we say we've observed a \"statistically significant\" result,\n which sounds a lot more impressive statement than it actually is.\n Recall hypothesis test is just used to rule out \"occurred by chance,\" which is a very basic sanity check. \n- The implication of failing to reject the null hypothesis is that the observed difference\n between means is \"not significant,\" meaning it could have occurred by chance,\n so there is no need to search for an alternative hypothesis.\n - Note that \"failing to reject\" is not the same as \"proving\" the null hypothesis\n - Note also \"failing to reject H0\" doesn't mean we reject HA.\n In fact, the alternative hypothesis didn't play any role in the calculations whatsoever.\n\n\nI know all this sounds super complicated and roundabout (an it is!),\nbut you will get a hang of it in no time with some practice.\nTrust me, you need to know this shit.\n",
"_____no_output_____"
],
[
" \n ",
"_____no_output_____"
],
[
" ",
"_____no_output_____"
],
[
"### Start by load data again...\n\nFirst things first, let's reload the data which we prepared back in the DATA where we left off back in the [01_DATA.ipynb](./01_DATA.ipynb) notebook.",
"_____no_output_____"
]
],
[
[
"df = pd.read_csv('data/employee_lifetime_values.csv')\ndf",
"_____no_output_____"
],
[
"# remember the descriptive statistics\ndf.groupby(\"group\").describe()",
"_____no_output_____"
],
[
"def dmeans(sample):\n \"\"\"\n Compute the difference between groups means.\n \"\"\"\n xS = sample[sample[\"group\"]==\"S\"][\"ELV\"]\n xNS = sample[sample[\"group\"]==\"NS\"][\"ELV\"]\n d = np.mean(xS) - np.mean(xNS)\n return d\n\n# the observed value in Amy's data\ndmeans(df)",
"_____no_output_____"
]
],
[
[
"Our goal is to determine how likely or unlikely this observed value is under the null hypothesis $H_0$.\n\nIn the next two sections, we'll look at two different approaches for obtaining the sampling distribution of $D$ under $H_0$.",
"_____no_output_____"
],
[
" ",
"_____no_output_____"
],
[
"## Approach 1: Permutation test for hypothesis testing\n\n- The permutation test allow us to reject $H_0$ using existing sample $\\mathbf{x}$ that we have,\n treating the sample as if it were a population.\n- Relevant probability distributions:\n - Sampling distribution = obtained from repeated samples from a hypothetical population under $H_0$.\n - Approximate sampling distribution: obtained by **resampling data from the single sample we have**.\n- Recall Goal 1: make sure data cannot be explained by $H_0$ (observed difference due to natural variability)\n - We want to obtain an approximation of the sampling distribution under $H_0$\n - The $H_0$ probability model describes a hypothetical scenario with **no difference between groups**,\n which means data from **Group S** and **Group NS** comes the same distribution.\n - To generate a new random sample $\\mathbf{x}^p$ from $H_0$ model we can reuse the sample we have obtained $\\mathbf{x}$, but randomly mix-up the group labels. Since under the $H_0$ model, the **S** and **NS** populations are identical, mixing up the labels should have no effect.\n - The math term for \"mixing up\" is **permutation**, meaning \n each value is input is randomly reassigned to a new random place in the output.",
"_____no_output_____"
]
],
[
[
"def resample_under_H0(sample, groupcol=\"group\"):\n \"\"\"\n Return a copy of the dataframe `sample` with the labels in the column `groupcol`\n modified based on a random permutation of the values in the original sample.\n \"\"\"\n resample = sample.copy()\n labels = sample[groupcol].values\n newlabels = np.random.permutation(labels)\n resample[groupcol] = newlabels\n return resample\n\nresample_under_H0(df)",
"_____no_output_____"
],
[
"# resample\nresample = resample_under_H0(df)\n\n# compute the difference in means for the new labels\ndmeans(resample)",
"_____no_output_____"
]
],
[
[
"The steps in the above code cell give us a simple way to generate samples from the null hypothesis and compute the value of `dmeans` statistic for these samples. We used the assumption of \"no difference\" under the null hypothesis, and translated this to the \"forget the labels\" interpretation.",
"_____no_output_____"
],
[
"#### Running a permutation test\n\nWe can repeat the resampling procedure `10000` times to get the sampling distribution of $D$ under $H_0$,\nas illustrated in the code procedure below.",
"_____no_output_____"
]
],
[
[
"def permutation_test(sample, statfunc, groupcol=\"group\", permutations=10000):\n \"\"\"\n Compute the p-value of the observed `statfunc(sample)` under the null hypothesis\n where the labels in the `groupcol` are randomized.\n \"\"\"\n # 1. compute the observed value of the statistic for the sample\n obsstat = statfunc(sample)\n\n # 2. generate the sampling distr. using random permutations of the group labels\n resampled_stats = []\n for i in range(0, permutations):\n resample = resample_under_H0(sample, groupcol=groupcol)\n restat = statfunc(resample)\n resampled_stats.append(restat)\n\n # 3. compute p-value: how many `restat`s are equal-or-more-extreme than `obsstat`\n tailstats = [restat for restat in resampled_stats \\\n if restat <= -abs(obsstat) or restat >= abs(obsstat)]\n pvalue = len(tailstats) / len(resampled_stats)\n\n return resampled_stats, pvalue\n\n\nsampling_dist, pvalue = permutation_test(df, statfunc=dmeans)",
"_____no_output_____"
],
[
"# plot the sampling distribution in blue\nsns.displot(sampling_dist, bins=200)\n\n# plot red line for the observed statistic\nobsstat = dmeans(df)\nplt.axvline(obsstat, color='r')\n\n# plot the values that are equal or more extreme in red\ntailstats = [rs for rs in sampling_dist if rs <= -obsstat or rs >= obsstat]\n_ = sns.histplot(tailstats, bins=200, color=\"red\")",
"_____no_output_____"
]
],
[
[
"- Once we have the sampling distribution of `D` under $H_0$,\n we can see where the observed value $d=130$\n falls within this distribution.\n- p-value: the probability of observing value $d$ or more extreme under the null hypothesis",
"_____no_output_____"
]
],
[
[
"pvalue",
"_____no_output_____"
]
],
[
[
"We can now make the decision based on the $p$-value and a pre-determined threshold:\n- If the observed value $d$ is unlikely under $H_0$ ($p$-value less than 5% chance of occurring),\n then our decision will be to \"reject the null hypothesis.\"\n- Otherwise, if the observed value $d$ is not that unusual ($p$-value greater than 5%),\n we conclude that we have \"failed to reject the null hypothesis.\"",
"_____no_output_____"
]
],
[
[
"if pvalue < 0.05:\n print(\"DECISION: Reject H0\", \"( p-value =\", pvalue, \")\")\n print(\" There is a statistically significant difference between xS and xNS means\")\nelse:\n print(\"DECISION: Fail to reject H0\")\n print(\" The difference between groups means could have occurred by chance\") ",
"DECISION: Reject H0 ( p-value = 0.046 )\n There is a statistically significant difference between xS and xNS means\n"
]
],
[
[
"#### Permutations test using SciPy",
"_____no_output_____"
],
[
"The above code was given only for illustrative purposes.\nIn practice, you can use the SciPy implementation of permutation test,\nby calling `ttest_ind(..., permutations=10000)` to perform a permutation test, then obtain the $p$-value.",
"_____no_output_____"
]
],
[
[
"from scipy.stats import ttest_ind\n\nxS = df[df[\"group\"]==\"S\"][\"ELV\"]\nxNS = df[df[\"group\"]==\"NS\"][\"ELV\"]\n\nttest_ind(xS, xNS, permutations=10000).pvalue",
"_____no_output_____"
]
],
[
[
"#### Discussion\n\n - The procedure we used is called a **permutations test** for comparison of group means.\n - The permutation test takes it's name from the action of mixing up the group-membership labels\n and computing a statistic which is a way to generate samples from the null hypothesis\n in situations where we're comparing two groups.\n - Permutation tests are very versatile since we can use them for any estimator $h(\\mathbf{x})$.\n For example, we could have used difference in medians by specifying the `median` as the input `statfunc`.\n",
"_____no_output_____"
],
[
" ",
"_____no_output_____"
],
[
" \n ",
"_____no_output_____"
],
[
"## Approach 2: Analytical approximations for hypothesis testing\n\nWe'll now look at another approach for answering Question 1:\nusing and analytical approximation,\nwhich is the way normally taught in STATS 101 courses.\nHow likely or unlikely is the observed difference $d=130$ under the null hypothesis?\n\n- Analytical approximations are math models for describing the sampling distribution under $H_0$\n - Sampling distributions = obtained by repeated sampling from $H_0$\n - Analytical approximation = probability distribution model based on estimated parameters\n- Assumption: population is normally distributed\n- Based on this assumption we can use the theoretical model we developed above for difference between group means\n to obtain a **closed form expression** for the sampling distribution of $D$\n- In particular, the probability model for the two groups under $H_0$ are:\n $$ \\large\n H_0: \\qquad X_S = \\mathcal{N}(\\color{red}{\\mu_0}, \\sigma_S)\n \\quad \\textrm{and} \\quad\n X_{NS} = \\mathcal{N}(\\color{red}{\\mu_0}, \\sigma_{NS}), \\quad\n $$\n from which we can derive the model for $D = \\overline{X}_S - \\overline{X}_{NS}$:\n $$ \\large\n D \\sim \\mathcal{N}\\!\\left( \\color{red}{0}, \\ \\tfrac{\\sigma^2_S}{n_S} + \\tfrac{\\sigma^2_{NS}}{n_{NS}} \\right)\n $$\n In words, the sampling distribution of the difference between group means is\n normally distributed with mean $\\mu_D = 0$ and variance $\\sigma^2_D$ dependent\n on the variance of the two groups $\\sigma^2_S$ and $\\sigma^2_{NS}$.\n Recall we obtained this expression earlier when we discussed difference of means between groups A and B.\n- However, the population variances are unknown $\\sigma^2_S$ and $\\sigma^2_{NS}$,\n and we only have the estimated variances $s_S^2$ and $s_{NS}^2$ calculated from the sample.\n- That's OK though, since sample variances are good approximation to the population variances.\n There are two common ways to obtain an approximation for $\\sigma^2_D$:\n - Pooled variance: $\\sigma^2_D \\approx s^2_p = \\frac{(n_S-1)s_S^2 \\; + \\; (n_{NS}-1)s_{NS}^2}{n_S + n_{NS} - 2}$\n (takes advantage of assumption that both samples come from the same population under $H_0$)\n - Unpooled variance: $\\sigma^2_D \\approx s^2_u = \\tfrac{s^2_S}{n_S} + \\tfrac{s^2_{NS}}{n_{NS}}$\n (follows from general rule of prob theory)\n- NEW CONCEPT: **Student's $t$-distribution** is a model for $D$ which takes into account\n we are using $s_S^2$ and $s_{NS}^2$ instead of $\\sigma_S^2$ and $\\sigma_{NS}^2$.\n- NEW CONCEPT: **degrees of freedom**, denoted `dof` in code or $\\nu$ (Greek letter *nu*) in equations,\n is the parameter Student's $t$ distribution related to the sample size used to estimate quantities.\n",
"_____no_output_____"
],
[
"### Student's t-test (pooled variance)\n\n[Student's t-test for comparison of difference between groups means](https://statkat.com/stattest.php?&t=9),\nis a procedure that makes use of the pooled variance $s^2_p$.\n\n#### Black-box approach\nThe `scipy.stats` function `ttest_ind` will perform all the steps of the $t$-test procedure,\nwithout the need for us to understand the details.",
"_____no_output_____"
]
],
[
[
"from scipy.stats import ttest_ind\n\n# extract data for two groups\nxS = df[df[\"group\"]==\"S\"]['ELV']\nxNS = df[df[\"group\"]==\"NS\"]['ELV']\n\n# run the complete t-test procedure for ind-ependent samples:\nresult = ttest_ind(xS, xNS)\nresult.pvalue",
"_____no_output_____"
]
],
[
[
"The $p$-value is less than 0.05 so our decision is to **reject the null hypothesis**.",
"_____no_output_____"
],
[
"#### Student's t-test under the hood\n\nThe computations hidden behind the function `ttest_ind` involve a six step procedure that makes use of the pooled variance $s^2_p$.",
"_____no_output_____"
]
],
[
[
"from statistics import stdev\nfrom scipy.stats.distributions import t\n\n# 1. calculate the mean in each group\nmeanS, meanNS = np.mean(xS), np.mean(xNS)\n\n# 2. calculate d, the observed difference between means\nd = meanS - meanNS\n\n# 3. calculate the standard deviations in each group\nstdS, stdNS = stdev(xS), stdev(xNS)\nnS, nNS = len(xS), len(xNS)\n\n# 4. compute the pooled variance and standard error\nvar_pooled = ((nS-1)*stdS**2 + (nNS-1)*stdNS**2)/(nS + nNS - 2)\nstd_pooled = np.sqrt(var_pooled)\nstd_err = np.sqrt(std_pooled**2/nS + std_pooled**2/nNS)\n\n# 5. compute the value of the t-statistic\ntstat = d / std_err\n\n# 6. obtain the p-value for the t-statistic from a \n# t-distribution with 31+30-2 = 59 degrees of freedom\ndof = nS + nNS - 2\npvalue = 2 * t(dof).cdf(-abs(tstat)) # 2* because two-sided\n\npvalue",
"_____no_output_____"
]
],
[
[
"#### Welch's t-test (unpooled variances)\n\nAn [alternative t-test procedure](https://statkat.com/stattest.php?&t=9) that doesn't assume the variances in groups are equal.",
"_____no_output_____"
]
],
[
[
"result2 = ttest_ind(xS, xNS, equal_var=False)\nresult2.pvalue",
"_____no_output_____"
]
],
[
[
"Welch's $t$-test differs only in steps 4 through 6 as shown below:",
"_____no_output_____"
]
],
[
[
"# 4'. compute the unpooled standard deviation of D\nstdD = np.sqrt(stdS**2/nS + stdNS**2/nNS)\n\n# 5'. compute the value of the t-statistic\ntstat = d / stdD\n\n# 6'. obtain the p-value from a t-distribution with\n# (insert crazy formula here) degrees of freedom\ndof = (stdS**2/nS + stdNS**2/nNS)**2 / \\\n ((stdS**2/nS)**2/(nS-1) + (stdNS**2/nNS)**2/(nNS-1) )\npvalue = 2 * t(dof).cdf(-abs(tstat)) # 2* because two-sided\n\npvalue",
"_____no_output_____"
]
],
[
[
"### Summary of Question 1\n\nWe saw two ways to answer Question 1 (is there a difference between group means) and obtain the p-value.\nWe interpreted the small p-values as evidence that the observed difference, $d=130$, is unlikely to be due to chance,\ni.e. we rejected the null hypothesis.\nNote this whole procedure is just a sanity check—we haven't touched the alternative hypothesis at all yet,\nand for all we know the stats training could have the effect of decreasing ELV!\n",
"_____no_output_____"
],
[
" \n____",
"_____no_output_____"
],
[
"It's time to study Question 2, which is to estimate the magnitude of the change in ELV obtained from completing the stats training, which is called *effect size* in statistics.",
"_____no_output_____"
],
[
" ",
"_____no_output_____"
],
[
"## Estimating the effect size\n\n- Question 2 of statistical analysis is to estimate the difference in ELV gained by stats training.\n- NEW CONCEPT: **effect size** is a measure of difference between intervention and control groups.\n- We assume the data of **Group S** and **Group NS** come from different populations with means $\\mu_S$ and $\\mu_{NS}$\n- We're interested in the difference between population means, denoted $\\Delta = \\mu_S - \\mu_{NS}$.\n- By analyzing the sample, we have obtained an estimate $d=130$ for the unknown $\\Delta$,\n but we know our data contains lots of variability, so we know our estimate might be off.\n- We want an answer to Question 2 (What is the estimated difference between group means?)\n that takes into account the variability of the data.\n- NEW CONCEPT: **confidence interval** is a way to describe a range of values for an estimate\n- We want to provide an answer to Question 2 in the form of a confidence interval that tells\n us a range of values where we believe the true value of $\\Delta$ falls.\n- Similar to how we showed to approaches for hypothesis testing,\n we'll work on effect size estimation using two approaches: resampling methods and analytical approximations.\n",
"_____no_output_____"
],
[
" ",
"_____no_output_____"
],
[
"### Approach 1: estimate the effect size using bootstrap method\n\n- We want to estimate the distribution of ELV values for the two groups,\n and compute the difference between the means of these distributions.\n- Distributions:\n - Sampling distributions = obtained by repeated sampling from the populations\n - Bootstrap sampling distributions = resampling data from the samples we have (with replacement)\n- Intuition: treat the samples as if they were the population\n- We'll compute $B=5000$ bootstrap samples from the two groups and compute the difference,\n then look at the distribution of the bootstrap sample difference to obtain $CI_{\\Delta}$,\n the confidence interval for the difference between population means.",
"_____no_output_____"
]
],
[
[
"from statistics import mean\n\ndef bootstrap_stat(sample, statfunc=mean, B=5000):\n \"\"\"\n Compute the bootstrap estimate of the function `statfunc` from the sample.\n Returns a list of statistic values from bootstrap samples.\n \"\"\"\n n = len(sample)\n bstats = []\n for i in range(0, B):\n bsample = np.random.choice(sample, n, replace=True)\n bstat = statfunc(bsample)\n bstats.append(bstat)\n return bstats\n",
"_____no_output_____"
],
[
"# load data for two groups\ndf = pd.read_csv('data/employee_lifetime_values.csv')\nxS = df[df[\"group\"]==\"S\"]['ELV']\nxNS = df[df[\"group\"]==\"NS\"]['ELV']\n\n# compute bootstrap estimates for mean in each group\nmeanS_bstats = bootstrap_stat(xS, statfunc=mean)\nmeanNS_bstats = bootstrap_stat(xNS, statfunc=mean)\n\n# compute the difference between means from bootstrap samples\ndmeans_bstats = []\nfor bmeanS, bmeanNS in zip(meanS_bstats, meanNS_bstats):\n d = bmeanS - bmeanNS \n dmeans_bstats.append(d)\n\nsns.displot(dmeans_bstats)",
"_____no_output_____"
],
[
"# 90% confidence interval for the difference in means\nCI_boot = [np.percentile(dmeans_bstats, 5), np.percentile(dmeans_bstats, 95)]\nCI_boot",
"_____no_output_____"
]
],
[
[
"#### SciPy bootstrap method",
"_____no_output_____"
]
],
[
[
"from scipy.stats import bootstrap\n\ndef dmeans2(sample1, sample2):\n return np.mean(sample1) - np.mean(sample2)\n\nres = bootstrap((xS, xNS), statistic=dmeans2, vectorized=False,\n confidence_level=0.9, n_resamples=5000, method='percentile')\n\nCI_boot2 = [res.confidence_interval.low, res.confidence_interval.high]\nCI_boot2",
"_____no_output_____"
]
],
[
[
" ",
"_____no_output_____"
],
[
"### Approach 2: Estimates using analytical approximation method\n\n - Assumption 1: populations for **Group S** and **Group NS** are normally distributed\n - Assumption 2: the variance of the two populations is the same (or approximately equal)\n - Using the theoretical model for the populations,\n we can obtain a formula for CI of effect size $\\Delta$:\n $$\n \\textrm{CI}_{(1-\\alpha)}\n = \\left[ d - t^*\\!\\cdot\\!\\sigma_D, \\, \n d + t^*\\!\\cdot\\!\\sigma_D\n \\right].\n $$\n The confidence interval is centred at $d$,\n with width proportional to the standard deviation $\\sigma_D$.\n The constant $t^*$ denotes the value of the inverse CDF of Student's $t$-distribution\n with appropriate number of degrees of freedom `dof` evaluated at $1-\\frac{\\alpha}{2}$.\n For a 90% confidence interval, we choose $\\alpha=0.10$,\n which gives $(1-\\frac{\\alpha}{2}) = 0.95$, $t^* = F_{T_{\\textrm{dof}}}^{-1}\\left(0.95\\right)$.\n - We can use the two different analytical approximations to obtain a formula for $\\sigma_D$\n just as we did in the hypothesis testing:\n - Pooled variance: $\\sigma^2_p = \\frac{(n_S-1)s_S^2 + (n_{NS}-1)s_{NS}^2}{n_S + n_{NS} - 2}$,\n and `dof` = $n_S + n_{NS} -2$\n - Unpooled variance: $\\sigma^2_u = \\tfrac{s^2_A}{n_A} + \\tfrac{s^2_B}{n_B}$, and `dof` = [...](https://en.wikipedia.org/wiki/Student%27s_t-test#Equal_or_unequal_sample_sizes,_unequal_variances_(sX1_%3E_2sX2_or_sX2_%3E_2sX1))",
"_____no_output_____"
],
[
"#### Using pooled variance\n\nThe calculations are similar to Student's t-test for hypothesis testing.",
"_____no_output_____"
]
],
[
[
"from scipy.stats.distributions import t\n\nd = np.mean(xS) - np.mean(xNS)\n\nnS, nNS = len(xS), len(xNS)\nstdS, stdNS = stdev(xS), stdev(xNS)\nvar_pooled = ((nS-1)*stdS**2 + (nNS-1)*stdNS**2)/(nS + nNS - 2)\nstd_pooled = np.sqrt(var_pooled)\nstd_err = std_pooled * np.sqrt(1/nS + 1/nNS)\n\ndof = nS + nNS - 2\n\n# for 90% confidence interval, need 10% in tails\nalpha = 0.10\n\n# now use inverse-CDF of Students t-distribution\ntstar = abs(t(dof).ppf(alpha/2))\n\nCI_tpooled = [d - tstar*std_err, d + tstar*std_err]\nCI_tpooled",
"_____no_output_____"
]
],
[
[
"#### Using unpooled variance\n\nThe calculations are similar to the Welch's t-test for hypothesis testing.",
"_____no_output_____"
]
],
[
[
"d = np.mean(xS) - np.mean(xNS)\n\nnS, nNS = len(xS), len(xNS)\nstdS, stdNS = stdev(xS), stdev(xNS)\nstdD = np.sqrt(stdS**2/nS + stdNS**2/nNS)\n\ndof = (stdS**2/nS + stdNS**2/nNS)**2 / \\\n ((stdS**2/nS)**2/(nS-1) + (stdNS**2/nNS)**2/(nNS-1) )\n\n# for 90% confidence interval, need 10% in tails\nalpha = 0.10\n\n# now use inverse-CDF of Students t-distribution\ntstar = abs(t(dof).ppf(alpha/2))\n\nCI_tunpooled = [d - tstar*stdD, d + tstar*stdD]\nCI_tunpooled",
"_____no_output_____"
]
],
[
[
"#### Summary of Question 2 results\n\nWe now have all the information we need to give a precise and nuanced answer to Question 2: \"How big is the increase in ELV produced by stats training?\".\n\nThe basic estimate of the difference is $130$ can be reported, and additionally can can report the 90% confidence interval for the difference between group means, that takes into account the variability in the data we have observed.\n\nNote the CIs obtained using different approaches are all similar (+/- 5 ELV points), so it doesn't matter much which approach we use:",
"_____no_output_____"
]
],
[
[
"CI_boot, CI_boot2, CI_tpooled, CI_tunpooled",
"_____no_output_____"
]
],
[
[
"### Standardized effect size (optional)\n\nIt is sometimes useful to report the effect size using a \"standardized\" measure for effect sizes.\n*Cohen's $d$* one such measure, and it is defined as the difference between two means divided by the pooled standard deviation.",
"_____no_output_____"
]
],
[
[
"def cohend(sample1, sample2):\n \"\"\"\n Compute Cohen's d measure of effect size for two independent samples.\n \"\"\"\n n1, n2 = len(sample1), len(sample2)\n mean1, mean2 = np.mean(sample1), np.mean(sample2)\n var1, var2 = np.var(sample1, ddof=1), np.var(sample2, ddof=1)\n # calculate the pooled variance and standard deviaiton\n var_pooled = ((n1-1)*var1 + (n2-1)*var2) / (n1 + n2 - 2)\n std_pooled = np.sqrt(var_pooled)\n # compute Cohen's d\n cohend = (mean1 - mean2) / std_pooled\n return cohend\n\ncohend(xS, xNS)",
"_____no_output_____"
]
],
[
[
"We can interpret the value of Cohen's d obtained using the [reference table](https://en.wikipedia.org/wiki/Effect_size#Cohen's_d) of values:\n\n| Cohen's d | Effect size |\n| ----------- | ----------- |\n| 0.01 | very small |\n| 0.20 | small |\n| 0.50 | medium |\n| 0.80 | large |\n\nWe can therefore say the effect size of offering statistics training for employees has an **medium** effect size.",
"_____no_output_____"
],
[
" ",
"_____no_output_____"
],
[
" ",
"_____no_output_____"
],
[
"## Conclusion of Amy's statistical analysis\n\nRecall the two research questions that Amy set out to answer in the beginning of this video series:\n- Question 1: Is there a difference between the means in the two groups?\n- Question 2: How much does statistics training improve the ELV of employees?\n\nThe statistical analysis we did allows us to answer these two questions as follows:\n- Answer 1: There is a statistically significant difference between Group S and Group NS, p = 0.048.\n- Answer 2: The estimated improvement in ELV is 130 points, which is corresponds to Cohen's d value of 0.52 (medium effect size). A 90% confidence interval for the true effect size is [25.9, 234.2].\n\nNote: we used the numerical results obtained from resampling methods (Approach 1), but conclusions would be qualitatively the same if we reported results obtained from analytical approximations (Approach 2).\n\n\n### Using statistics for convincing others\n\nYou may be wondering if all this probabilistic modelling and complicated statistical analysis was worth it to reach a conclusion that seems obvious in retrospect. Was all this work worth it? The purpose of all this work is to obtains something close to an objective conclusion. Without statistics it is very easy to fool ourselves and interpret patterns in data the way we want to, or alternatively, not see patterns that are present. By following the standard statistical procedures, we're less likely to fool ourselves, and more likely to be able to convince others.\n\nIt can very useful to imagine Amy explaining the results to a skeptical colleague. Suppose the colleague is very much against the idea of statistical training, and sees it as a distraction, saying things like \"We hire employees to do a job, not to play with Python.\" and \"I don't know any statistics and I'm doing my job just fine!\" You get the picture.\n\nImagine Amy presenting her findings about how 100 hours of statistical training improves employee lifetime value (ELV) results after one year, and suggesting the statistical training be implemented for all new hires from now on. The skeptical colleague immediately rejects the idea and questions Amy's recommendation using emotional arguments like about necessity, time wasting, and how statistics is a specialty topic that is not required for all employees. Instead of arguing based on opinions and emotions with her colleague, Amy explains her recommendation is based on a statistical experiment she conducted, and shows the results.\n\n- When the colleague asks if the observed difference could be due to chance, Amy says that this is unlikely, and quotes the p-value of 0.048 (less than 0.05), and interprets the result as saying the probability of observed difference between **Group S** and **Group NS** to be due to chance is less than 5%.\n\n- The skeptical colleague is forced to concede that statistical training does improve ELV, but then asks about the effect size of the improvement: \"How much more ELV can we expect if we provide statistics training?\" Amy is ready to answer quoting the observed difference of $130$ ELV points, and further specifies the 90% confidence interval of [25.9, 234.2] for the improvement, meaning in the worst case there is 25 ELV points improvement.\n\nThe skeptic is forced to back down from their objections, and the \"stats training for all\" program is adopted in the company. Not only was Amy able to win the argument using statistics, but she was also able to set appropriate expectations for the results. In other words, she hasn't promised a guaranteed +130 ELV improvement, but a realistic range of values that can be expected.",
"_____no_output_____"
],
[
" ",
"_____no_output_____"
],
[
" ",
"_____no_output_____"
],
[
"\n## Comparison of resampling methods and analytical approximations\n\nIn this notebook we saw two different approaches for doing statistical analysis: resampling methods and analytical approximations. This is a general pattern in statistics where there is not only one correct answer: multiple approaches to data analysis are valid, and you need to think about the specifics of each data analysis situation. You'll learn about both approaches in the book.\n\nAnalytical approximations currently taught in most stats courses (STAT 101). Historically, analytical approximations have been used more widely because they require only simple arithmetic calculations: statistic practitioners (scientists, engineers, etc.) simply need to compute sample statistics, plug them into a formula, and obtain a $p$-value. This convenience is at the cost of numerous assumptions about the data distribution, which often don't hold in practice (e.g. assuming population is normal, when it is isn't).\n\nIn recent years, resampling methods like the permutation test and bootstrap estimation are becoming more popular and widely in industry, and increasingly also taught at to university students (*modern statistics*). **The main advantage so resampling methods is that they require less modelling assumptions.** Procedures like the permutation test can be applied broadly to any scenarios where two groups are compared, and don't require developing specific formulas for different cases. Resampling methods are easier to understand since the statistical procedure they require are directly related to the sampling distribution, and there are no formulas to memorize.\n\nUnderstanding resampling methods requires some basic familiarity with programming, but the skills required are not advanced: knowledge of variables, expressions, and basic `for` loop is sufficient. If you were able to follow the code examples described above (see `resample_under_H0`, `permutation_test`, and `bootstrap_stat`), then you've already **seen all the code you will need for the entire book!**",
"_____no_output_____"
],
[
" \n ",
"_____no_output_____"
],
[
"## Other statistics topics in the book\n\nThe goal of this notebook was to focus on the two main ideas of inferential statistics ([Chapter 3](https://docs.google.com/document/d/1fwep23-95U-w1QMPU31nOvUnUXE2X3s_Dbk5JuLlKAY/edit#heading=h.uutryzqeo2av)): hypothesis testing and estimation. We didn't have time to cover many of the other important topics in statistics, which will be covered in the book (and in future notebooks). Here is a list of some of these topics:\n\n- Null Hypothesis Significance Testing (NHST) procedure in full details (Type I and Type II error, power, sample size calculations) \n- Statistical assumptions behind analytical approximations\n- Cookbook of statistical analysis recipes (analytical approximations for different scenarios)\n- Experimental design (how to plan and conduct statistical experiments)\n- Misuses of statistics (caveats to watch out for and mistakes to avoid)\n- Bayesian statistics (very deep topic; we'll cover only main ideas)\n- Practice problems and exercises (real knowledge is when you can do the calculations yourself)",
"_____no_output_____"
],
[
" ",
"_____no_output_____"
],
[
"___",
"_____no_output_____"
],
[
"So far our statistical analysis was limited to comparing two groups, which is referred to as **categorical predictor variable** using stats jargon. In the next notebook we'll learn about statistical analysis with **continuous predictor variables**: instead of comparing stats vs. no-stats, we analyze what happens when variable amount of stats training is provided (a continuous predictor variable).\n\nOpen the notebook [04_LINEAR_MODELS.ipynb](./04_LINEAR_MODELS.ipynb) when you're ready to continue.",
"_____no_output_____"
]
],
[
[
"code = list([\"um\"])",
"_____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",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
]
] |
d0840adac1fae0a8d81ce0e538fe25d570263de9 | 45,547 | ipynb | Jupyter Notebook | r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb | vllyakho/amazon-sagemaker-examples | 348cde30e618ac76359faf2ec53c7cbfad80860d | [
"Apache-2.0"
] | 2 | 2022-03-28T09:17:44.000Z | 2022-03-28T09:17:47.000Z | r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb | vllyakho/amazon-sagemaker-examples | 348cde30e618ac76359faf2ec53c7cbfad80860d | [
"Apache-2.0"
] | 1 | 2022-03-15T20:04:30.000Z | 2022-03-15T20:04:30.000Z | r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb | vllyakho/amazon-sagemaker-examples | 348cde30e618ac76359faf2ec53c7cbfad80860d | [
"Apache-2.0"
] | 1 | 2022-03-28T09:18:00.000Z | 2022-03-28T09:18:00.000Z | 39.129725 | 912 | 0.605924 | [
[
[
"## Compare built-in Sagemaker classification algorithms for a binary classification problem using Iris dataset",
"_____no_output_____"
],
[
"In the notebook tutorial, we build 3 classification models using HPO and then compare the AUC on test dataset on 3 deployed models\n\nIRIS is perhaps the best known database to be found in the pattern recognition literature. Fisher's paper is a classic in the field and is referenced frequently to this day. (See Duda & Hart, for example.) The data set contains 3 classes of 50 instances each, where each class refers to a type of iris plant. The dataset is built-in by default into R or can also be downloaded from https://archive.ics.uci.edu/ml/datasets/iris\n\nThe iris dataset, besides its historical importance, is also a fun dataset to play with since it can educate us about various ML techniques such as clustering, classification and regression, all in one dataset.\n\nThe dataset is built into any base R installation, so no download is required.\n\nAttribute Information:\n\n1. sepal length in cm\n2. sepal width in cm\n3. petal length in cm\n4. petal width in cm\n5. Species of flowers: Iris setosa, Iris versicolor, Iris virginica\n\nThe prediction we will perform is `Species ~ f(sepal.length,sepal.width,petal.width,petal.length)`\n\nPredicted attribute: Species of iris plant.\n\n\n\n",
"_____no_output_____"
],
[
"### Load required libraries and initialize variables.",
"_____no_output_____"
]
],
[
[
"rm(list=ls())\nlibrary(reticulate) # be careful not to install reticulate again. since it can cause problems.\nlibrary(tidyverse)\nlibrary(pROC)\nset.seed(1324)",
"_____no_output_____"
]
],
[
[
"SageMaker needs to be imported using the reticulate library. If this was performed in a local computer, we would have to make sure that Python and appropriate SageMaker libraries are installed, but inside a SageMaker notebook R kernels, these are all pre-loaded and the R user does not have to worry about installing reticulate or Python. \n\nSession is the unique session ID associated with each SageMaker call. It remains the same throughout the execution of the program and can be recalled later to close a session or open a new session.\n\nThe bucket is the Amazon S3 bucket where we will be storing our data output. The Amazon S3 bucket and prefix that you want to use for training and model data. This should be within the same region as the Notebook Instance, training, and hosting.\n\nThe role is the role of the SageMaker notebook as when it was initially deployed. The IAM role arn used to give training and hosting access to your data. See the documentation for how to create these. Note, if more than one role is required for notebook instances, training, and/or hosting, please replace the boto regexp with appropriate full IAM role arn string(s).\n\n\n",
"_____no_output_____"
]
],
[
[
"sagemaker <- import('sagemaker')\nsession <- sagemaker$Session()\nbucket <- session$default_bucket() # you may replace with name of your personal S3 bucket\nrole_arn <- sagemaker$get_execution_role()",
"_____no_output_____"
]
],
[
[
"### Input the data and basic pre-processing",
"_____no_output_____"
]
],
[
[
"head(iris)",
"_____no_output_____"
],
[
"summary(iris)",
"_____no_output_____"
]
],
[
[
"In above, we see that there are 50 flowers of the setosa species, 50 flowers of the versicolor species, and 50 flowers of the virginica species.",
"_____no_output_____"
],
[
"In this case, the target variable is the Species prediction. We are trying to predict the species of the flower given its numerical measurements of Sepal length, sepal width, petal length, and petal width. Since we are trying to do binary classification, we will only take the flower species setosa and versicolor for simplicity. Also we will perform one-hot encoding on the categorical variable Species.",
"_____no_output_____"
]
],
[
[
"iris1 <- iris %>% \n dplyr::select(Species,Sepal.Length,Sepal.Width,Petal.Length,Petal.Width) %>% # change order of columns such that the label column is the first column.\n dplyr::filter(Species %in% c(\"setosa\",\"versicolor\")) %>% #only select two flower for binary classification.\n dplyr::mutate(Species = as.numeric(Species) -1) # one-hot encoding,starting with 0 as setosa and 1 as versicolor.",
"_____no_output_____"
],
[
"head(iris1)",
"_____no_output_____"
]
],
[
[
"We now obtain some basic descriptive statistics of the features.",
"_____no_output_____"
]
],
[
[
"iris1 %>% group_by(Species) %>% summarize(mean_sepal_length = mean(Sepal.Length),\n mean_petal_length = mean(Petal.Length),\n mean_sepal_width = mean(Sepal.Width),\n mean_petal_width = mean(Petal.Width),\n )",
"_____no_output_____"
]
],
[
[
"In the summary statistics, we observe that mean sepal length is longer than mean petal length for both flowers. ",
"_____no_output_____"
],
[
"### Prepare for modelling",
"_____no_output_____"
],
[
"##### We split the train and test and validate into 70%, 15%, and 15%, using random sampling.",
"_____no_output_____"
]
],
[
[
"iris_train <- iris1 %>%\n sample_frac(size = 0.7)\niris_test <- anti_join(iris1, iris_train) %>% \n sample_frac(size = 0.5)\niris_validate <- anti_join(iris1, iris_train) %>%\n anti_join(., iris_test)",
"_____no_output_____"
]
],
[
[
"##### We do a check of the summary statistics to make sure train, test, validate datasets are appropriately split and have proper class balance.",
"_____no_output_____"
]
],
[
[
"table(iris_train$Species)\nnrow(iris_train)",
"_____no_output_____"
]
],
[
[
"We see that the class balance between 0 and 1 is almost 50% each for the binary classification. We also see that there are 70 rows in the train dataset.",
"_____no_output_____"
]
],
[
[
"table(iris_validate$Species)\nnrow(iris_validate)",
"_____no_output_____"
]
],
[
[
"We see that the class balance in validation dataset between 0 and 1 is almost 50% each for the binary classification. We also see that there are 15 rows in the validation dataset.",
"_____no_output_____"
]
],
[
[
"table(iris_test$Species)\nnrow(iris_test)",
"_____no_output_____"
]
],
[
[
"We see that the class balance in test dataset between 0 and 1 is almost 50% each for the binary classification. We also see that there are 15 rows in the test dataset.",
"_____no_output_____"
],
[
"### Write the data to Amazon S3",
"_____no_output_____"
],
[
"Different algorithms in SageMaker will have different data formats required for training and for testing. These formats are created to make model production easier. csv is the most well known of these formats and has been used here as input in all algorithms to make it consistent.\n\nSageMaker algorithms take in data from an Amazon S3 object and output data to an Amazon S3 object, so data has to be stored in Amazon S3 as csv,json, proto-buf or any format that is supported by the algorithm that you are going to use.",
"_____no_output_____"
]
],
[
[
"write_csv(iris_train, 'iris_train.csv', col_names = FALSE)\nwrite_csv(iris_validate, 'iris_valid.csv', col_names = FALSE)\nwrite_csv(iris_test, 'iris_test.csv', col_names = FALSE)",
"_____no_output_____"
],
[
"s3_train <- session$upload_data(path = 'iris_train.csv', \n bucket = bucket, \n key_prefix = 'data')\ns3_valid <- session$upload_data(path = 'iris_valid.csv', \n bucket = bucket, \n key_prefix = 'data')\n\ns3_test <- session$upload_data(path = 'iris_test.csv', \n bucket = bucket, \n key_prefix = 'data')",
"_____no_output_____"
],
[
"s3_train_input <- sagemaker$inputs$TrainingInput(s3_data = s3_train,\n content_type = 'text/csv')\ns3_valid_input <- sagemaker$inputs$TrainingInput(s3_data = s3_valid,\n content_type = 'text/csv')\ns3_test_input <- sagemaker$inputs$TrainingInput(s3_data = s3_test,\n content_type = 'text/csv')\n",
"_____no_output_____"
]
],
[
[
"To perform Binary classification on Tabular\tdata, SageMaker contains following algorithms:\n\n- XGBoost Algorithm\n- Linear Learner Algorithm, \n- K-Nearest Neighbors (k-NN) Algorithm, \n\n",
"_____no_output_____"
],
[
"## Create model 1: XGBoost model in SageMaker",
"_____no_output_____"
],
[
"Use the XGBoost built-in algorithm to build an XGBoost training container as shown in the following code example. You can automatically spot the XGBoost built-in algorithm image URI using the SageMaker image_uris.retrieve API (or the get_image_uri API if using Amazon SageMaker Python SDK version 1). If you want to ensure if the image_uris.retrieve API finds the correct URI, see Common parameters for built-in algorithms and look up XGBoost from the full list of built-in algorithm image URIs and available regions.\n\nAfter specifying the XGBoost image URI, you can use the XGBoost container to construct an estimator using the SageMaker Estimator API and initiate a training job. This XGBoost built-in algorithm mode does not incorporate your own XGBoost training script and runs directly on the input datasets.\n\nSee https://docs.aws.amazon.com/sagemaker/latest/dg/xgboost.html for more information.",
"_____no_output_____"
]
],
[
[
"container <- sagemaker$image_uris$retrieve(framework='xgboost', region= session$boto_region_name, version='latest')\ncat('XGBoost Container Image URL: ', container)",
"_____no_output_____"
],
[
"s3_output <- paste0('s3://', bucket, '/output_xgboost')\nestimator1 <- sagemaker$estimator$Estimator(image_uri = container,\n role = role_arn,\n train_instance_count = 1L,\n train_instance_type = 'ml.m5.4xlarge',\n input_mode = 'File',\n output_path = s3_output,\n output_kms_key = NULL,\n base_job_name = NULL,\n sagemaker_session = NULL)",
"_____no_output_____"
]
],
[
[
"How would an untuned model perform compared to a tuned model? Is it worth the effort? Before going deeper into XGBoost model tuning, let’s highlight the reasons why you have to tune your model. The main reason to perform hyper-parameter tuning is to increase predictability of our models by choosing our hyperparameters in a well thought manner. There are 3 ways to perform hyperparameter tuning: grid search, random search, bayesian search. Popular packages like scikit-learn use grid search and random search techniques. SageMaker uses Bayesian search techniques.\n\nWe need to choose \n\n- a learning objective function to optimize during model training\n- an eval_metric to use to evaluate model performance during validation\n- a set of hyperparameters and a range of values for each to use when tuning the model automatically\n\nSageMaker XGBoost model can be tuned with many hyperparameters. The hyperparameters that have the greatest effect on optimizing the XGBoost evaluation metrics are: \n\n- alpha, \n- min_child_weight, \n- subsample, \n- eta, \n- num_round.\n\n\nThe hyperparameters that are required are num_class (the number of classes if it is a multi-class classification problem) and num_round ( the number of rounds to run the training on). All other hyperparameters are optional and will be set to default values if it is not specified by the user.",
"_____no_output_____"
]
],
[
[
"# check to make sure which are required and which are optional\nestimator1$set_hyperparameters(eval_metric='auc',\n objective='binary:logistic',\n num_round = 6L\n )\n\n# Set Hyperparameter Ranges, check to make sure which are integer and which are continuos parameters. \nhyperparameter_ranges = list('eta' = sagemaker$parameter$ContinuousParameter(0,1),\n 'min_child_weight'= sagemaker$parameter$ContinuousParameter(0,10),\n 'alpha'= sagemaker$parameter$ContinuousParameter(0,2),\n 'max_depth'= sagemaker$parameter$IntegerParameter(0L,10L))\n",
"_____no_output_____"
]
],
[
[
"The evaluation metric that we will use for our binary classification purpose is validation:auc, but you could use any other metric that is right for your problem. You do have to be careful to change your objective_type to point to the right direction of Maximize or Minimize according to the objective metric you have chosen.",
"_____no_output_____"
]
],
[
[
"# Create a hyperparamter tuner\nobjective_metric_name = 'validation:auc'\ntuner1 <- sagemaker$tuner$HyperparameterTuner(estimator1,\n objective_metric_name,\n hyperparameter_ranges,\n objective_type='Maximize',\n max_jobs=4L,\n max_parallel_jobs=2L)\n\n# Define the data channels for train and validation datasets\ninput_data <- list('train' = s3_train_input,\n 'validation' = s3_valid_input)\n\n# train the tuner\ntuner1$fit(inputs = input_data, \n job_name = paste('tune-xgb', format(Sys.time(), '%Y%m%d-%H-%M-%S'), sep = '-'), \n wait=TRUE)",
"_____no_output_____"
]
],
[
[
"The output of the tuning job can be checked in SageMaker if needed.",
"_____no_output_____"
],
[
"### Calculate AUC for the test data on model 1",
"_____no_output_____"
],
[
"SageMaker will automatically recognize the training job with the best evaluation metric and load the hyperparameters associated with that training job when we deploy the model. One of the benefits of SageMaker is that we can easily deploy models in a different instance than the instance in which the notebook is running. So we can deploy into a more powerful instance or a less powerful instance.",
"_____no_output_____"
]
],
[
[
"model_endpoint1 <- tuner1$deploy(initial_instance_count = 1L,\n instance_type = 'ml.t2.medium')\n\n",
"_____no_output_____"
]
],
[
[
"The serializer tells SageMaker what format the model expects data to be input in.",
"_____no_output_____"
]
],
[
[
"model_endpoint1$serializer <- sagemaker$serializers$CSVSerializer(content_type='text/csv')",
"_____no_output_____"
]
],
[
[
"We input the `iris_test` dataset without the labels into the model using the `predict` function and check its AUC value.",
"_____no_output_____"
]
],
[
[
"# Prepare the test sample for input into the model\ntest_sample <- as.matrix(iris_test[-1])\ndimnames(test_sample)[[2]] <- NULL\n\n# Predict using the deployed model\npredictions_ep <- model_endpoint1$predict(test_sample)\npredictions_ep <- stringr::str_split(predictions_ep, pattern = ',', simplify = TRUE)\npredictions_ep <- as.numeric(predictions_ep > 0.5)\n\n# Add the predictions to the test dataset.\niris_predictions_ep1 <- dplyr::bind_cols(predicted_flower = predictions_ep, \n iris_test)\niris_predictions_ep1\n\n# Get the AUC\nauc(roc(iris_predictions_ep1$predicted_flower,iris_test$Species))",
"_____no_output_____"
]
],
[
[
"## Create model 2: Linear Learner in SageMaker",
"_____no_output_____"
],
[
"Linear models are supervised learning algorithms used for solving either classification or regression problems. For input, you give the model labeled examples (x, y). x is a high-dimensional vector and y is a numeric label. For binary classification problems, the label must be either 0 or 1.\n\nThe linear learner algorithm requires a data matrix, with rows representing the observations, and columns representing the dimensions of the features. It also requires an additional column that contains the labels that match the data points. At a minimum, Amazon SageMaker linear learner requires you to specify input and output data locations, and objective type (classification or regression) as arguments. The feature dimension is also required. You can specify additional parameters in the HyperParameters string map of the request body. These parameters control the optimization procedure, or specifics of the objective function that you train on. For example, the number of epochs, regularization, and loss type.\n\nSee https://docs.aws.amazon.com/sagemaker/latest/dg/linear-learner.html for more information.",
"_____no_output_____"
]
],
[
[
"container <- sagemaker$image_uris$retrieve(framework='linear-learner', region= session$boto_region_name, version='latest')\ncat('Linear Learner Container Image URL: ', container)",
"_____no_output_____"
],
[
"s3_output <- paste0('s3://', bucket, '/output_glm')\nestimator2 <- sagemaker$estimator$Estimator(image_uri = container,\n role = role_arn,\n train_instance_count = 1L,\n train_instance_type = 'ml.m5.4xlarge',\n input_mode = 'File',\n output_path = s3_output,\n output_kms_key = NULL,\n base_job_name = NULL,\n sagemaker_session = NULL)",
"_____no_output_____"
]
],
[
[
"For the text/csv input type, the first column is assumed to be the label, which is the target variable for prediction.",
"_____no_output_____"
],
[
"predictor_type is the only hyperparameter that is required to be pre-defined for tuning. The rest are optional.",
"_____no_output_____"
],
[
"Normalization, or feature scaling, is an important preprocessing step for certain loss functions that ensures the model being trained on a dataset does not become dominated by the weight of a single feature. Decision trees do not require normalization of their inputs; and since XGBoost is essentially an ensemble algorithm comprised of decision trees, it does not require normalization for the inputs either.\n\nHowever, Generalized Linear Models require a normalization of their input. The Amazon SageMaker Linear Learner algorithm has a normalization option to assist with this preprocessing step. If normalization is turned on, the algorithm first goes over a small sample of the data to learn the mean value and standard deviation for each feature and for the label. Each of the features in the full dataset is then shifted to have mean of zero and scaled to have a unit standard deviation.\n\nTo make our job easier, we do not have to go back to our previous steps to do normalization. Normalization is built in as a hyper-parameter in SageMaker Linear learner algorithm. So no need to worry about normalization for the training portions.\n\n",
"_____no_output_____"
]
],
[
[
"estimator2$set_hyperparameters(predictor_type=\"binary_classifier\",\n normalize_data = TRUE)",
"_____no_output_____"
]
],
[
[
"The tunable hyperparameters for linear learner are:\n\n- wd\n- l1\n- learning_rate\n- mini_batch_size\n- use_bias\n- positive_example_weight_mult\n\nBe careful to check which parameters are integers and which parameters are continuous because that is one of the common sources of errors. Also be careful to give a proper range for hyperparameters that makes sense for your problem. Training jobs can sometimes fail if the mini-batch size is too big compared to the training data available.",
"_____no_output_____"
]
],
[
[
"# Set Hyperparameter Ranges\nhyperparameter_ranges = list('wd' = sagemaker$parameter$ContinuousParameter(0.00001,1),\n 'l1' = sagemaker$parameter$ContinuousParameter(0.00001,1),\n 'learning_rate' = sagemaker$parameter$ContinuousParameter(0.00001,1),\n 'mini_batch_size' = sagemaker$parameter$IntegerParameter(10L, 50L) \n )",
"_____no_output_____"
]
],
[
[
"The evaluation metric we will be using in our case to compare the models will be the objective loss and is based on the validation dataset. ",
"_____no_output_____"
]
],
[
[
"# Create a hyperparamter tuner\nobjective_metric_name = 'validation:objective_loss'\ntuner2 <- sagemaker$tuner$HyperparameterTuner(estimator2,\n objective_metric_name,\n hyperparameter_ranges,\n objective_type='Minimize',\n max_jobs=4L,\n max_parallel_jobs=2L)",
"_____no_output_____"
],
[
"# Create a tuning job name\njob_name <- paste('tune-linear', format(Sys.time(), '%Y%m%d-%H-%M-%S'), sep = '-')\n\n# Define the data channels for train and validation datasets\ninput_data <- list('train' = s3_train_input,\n 'validation' = s3_valid_input)\n\n# Train the tuner\ntuner2$fit(inputs = input_data, job_name = job_name, wait=TRUE, content_type='csv') # since we are using csv files as input into the model, we need to specify content type as csv.",
"_____no_output_____"
]
],
[
[
"### Calculate AUC for the test data on model 2",
"_____no_output_____"
]
],
[
[
"# Deploy the model into an instance of your choosing.\nmodel_endpoint2 <- tuner2$deploy(initial_instance_count = 1L,\n instance_type = 'ml.t2.medium')",
"_____no_output_____"
]
],
[
[
"For inference, the linear learner algorithm supports the application/json, application/x-recordio-protobuf, and text/csv formats. For more information, https://docs.aws.amazon.com/sagemaker/latest/dg/LL-in-formats.html",
"_____no_output_____"
]
],
[
[
"# Specify what data formats you want the input and output of your model to look like.\nmodel_endpoint2$serializer <- sagemaker$serializers$CSVSerializer(content_type='text/csv')\nmodel_endpoint2$deserializer <- sagemaker$deserializers$JSONDeserializer()",
"_____no_output_____"
]
],
[
[
"In Linear Learner the output inference files are in JSON or RecordIO formats. https://docs.aws.amazon.com/sagemaker/latest/dg/LL-in-formats.html \n\nWhen you make predictions on new data, the contents of the response data depends on the type of model you choose within Linear Learner. For regression (predictor_type='regressor'), the score is the prediction produced by the model. For classification (predictor_type='binary_classifier' or predictor_type='multiclass_classifier'), the model returns a score and also a predicted_label. The predicted_label is the class predicted by the model and the score measures the strength of that prediction. So, for binary classification, predicted_label is 0 or 1, and score is a single floating point number that indicates how strongly the algorithm believes that the label should be 1.\n\nTo interpret the score in classification problems, you have to consider the loss function used. If the loss hyperparameter value is logistic for binary classification or softmax_loss for multiclass classification, then the score can be interpreted as the probability of the corresponding class. These are the loss values used by the linear learner when the `loss` hyperparameter is set to auto as default value. But if the `loss` is set to `hinge_loss`, then the score cannot be interpreted as a probability. This is because hinge loss corresponds to a Support Vector Classifier, which does not produce probability estimates. In the current example, since our loss hyperparameter is logistic for binary classification, we can interpret it as probability of the corresponding class.",
"_____no_output_____"
]
],
[
[
"# Prepare the test data for input into the model\ntest_sample <- as.matrix(iris_test[-1])\ndimnames(test_sample)[[2]] <- NULL\n\n# Predict using the test data on the deployed model\npredictions_ep <- model_endpoint2$predict(test_sample)\n\n# Add the predictions to the test dataset.\ndf <- data.frame(matrix(unlist(predictions_ep$predictions), nrow=length(predictions_ep$predictions), byrow=TRUE))\ndf <- df %>% dplyr::rename(score = X1, predicted_label = X2)\niris_predictions_ep2 <- dplyr::bind_cols(predicted_flower = df$predicted_label, \n iris_test)\niris_predictions_ep2\n\n# Get the AUC\nauc(roc(iris_predictions_ep2$predicted_flower,iris_test$Species))\n",
"_____no_output_____"
]
],
[
[
"## Create model 3: KNN in SageMaker",
"_____no_output_____"
],
[
"Amazon SageMaker k-nearest neighbors (k-NN) algorithm is an index-based algorithm. It uses a non-parametric method for classification or regression. For classification problems, the algorithm queries the k points that are closest to the sample point and returns the most frequently used label of their class as the predicted label. For regression problems, the algorithm queries the k closest points to the sample point and returns the average of their feature values as the predicted value.\n\nTraining with the k-NN algorithm has three steps: sampling, dimension reduction, and index building. Sampling reduces the size of the initial dataset so that it fits into memory. For dimension reduction, the algorithm decreases the feature dimension of the data to reduce the footprint of the k-NN model in memory and inference latency. We provide two methods of dimension reduction methods: random projection and the fast Johnson-Lindenstrauss transform. Typically, you use dimension reduction for high-dimensional (d >1000) datasets to avoid the “curse of dimensionality” that troubles the statistical analysis of data that becomes sparse as dimensionality increases. The main objective of k-NN's training is to construct the index. The index enables efficient lookups of distances between points whose values or class labels have not yet been determined and the k nearest points to use for inference.\n\nSee https://docs.aws.amazon.com/sagemaker/latest/dg/k-nearest-neighbors.html for more information.",
"_____no_output_____"
]
],
[
[
"container <- sagemaker$image_uris$retrieve(framework='knn', region= session$boto_region_name, version='latest')\ncat('KNN Container Image URL: ', container)",
"_____no_output_____"
],
[
"s3_output <- paste0('s3://', bucket, '/output_knn')\nestimator3 <- sagemaker$estimator$Estimator(image_uri = container,\n role = role_arn,\n train_instance_count = 1L,\n train_instance_type = 'ml.m5.4xlarge',\n input_mode = 'File',\n output_path = s3_output,\n output_kms_key = NULL,\n base_job_name = NULL,\n sagemaker_session = NULL)",
"_____no_output_____"
]
],
[
[
"Hyperparameter `dimension_reduction_target` should not be set when `dimension_reduction_type` is set to its default value, which is `None`. If 'dimension_reduction_target' is set to a certain number without setting `dimension_reduction_type`, then SageMaker will ask us to remove 'dimension_reduction_target' from the specified hyperparameters and try again. In this tutorial, we are not performing dimensionality reduction, since we only have 4 features; so `dimension_reduction_type` is set to its default value of `None`.",
"_____no_output_____"
]
],
[
[
"estimator3$set_hyperparameters( \n feature_dim = 4L, \n sample_size = 10L, \n predictor_type = \"classifier\"\n )",
"_____no_output_____"
]
],
[
[
"Amazon SageMaker k-nearest neighbor model can be tuned with the following hyperparameters:\n- k \n- sample_size",
"_____no_output_____"
]
],
[
[
"# Set Hyperparameter Ranges\nhyperparameter_ranges = list('k' = sagemaker$parameter$IntegerParameter(1L,10L)\n )",
"_____no_output_____"
],
[
"# Create a hyperparamter tuner\nobjective_metric_name = 'test:accuracy'\ntuner3 <- sagemaker$tuner$HyperparameterTuner(estimator3,\n objective_metric_name,\n hyperparameter_ranges,\n objective_type='Maximize',\n max_jobs=2L,\n max_parallel_jobs=2L)",
"_____no_output_____"
],
[
"# Create a tuning job name\njob_name <- paste('tune-knn', format(Sys.time(), '%Y%m%d-%H-%M-%S'), sep = '-')\n\n# Define the data channels for train and validation datasets\ninput_data <- list('train' = s3_train_input,\n 'test' = s3_valid_input # KNN needs a test data, does not work without it.\n ) \n\n# train the tuner\ntuner3$fit(inputs = input_data, job_name = job_name, wait=TRUE, content_type='text/csv;label_size=0')",
"_____no_output_____"
]
],
[
[
"### Calculate AUC for the test data on model 3",
"_____no_output_____"
]
],
[
[
"# Deploy the model into an instance of your choosing.\nmodel_endpoint3 <- tuner3$deploy(initial_instance_count = 1L,\n instance_type = 'ml.t2.medium')",
"_____no_output_____"
]
],
[
[
"For inference, the linear learner algorithm supports the application/json, application/x-recordio-protobuf, and text/csv formats. For more information, https://docs.aws.amazon.com/sagemaker/latest/dg/LL-in-formats.html",
"_____no_output_____"
]
],
[
[
"# Specify what data formats you want the input and output of your model to look like.\nmodel_endpoint3$serializer <- sagemaker$serializers$CSVSerializer(content_type='text/csv')\nmodel_endpoint3$deserializer <- sagemaker$deserializers$JSONDeserializer()",
"_____no_output_____"
]
],
[
[
"In KNN, the input formats for inference are:\n- CSV\n- JSON\n- JSONLINES\n- RECORDIO\n\nThe output formats for inference are:\n- JSON\n- JSONLINES\n- Verbose JSON\n- Verbose RecordIO-ProtoBuf\n\nNotice that there is no CSV output format for inference. \n\nSee https://docs.aws.amazon.com/sagemaker/latest/dg/kNN-inference-formats.html for more details.\n\nWhen you make predictions on new data, the contents of the response data depends on the type of model you choose within Linear Learner. For regression (predictor_type='regressor'), the score is the prediction produced by the model. For classification (predictor_type='binary_classifier' or predictor_type='multiclass_classifier'), the model returns a score and also a predicted_label. The predicted_label is the class predicted by the model and the score measures the strength of that prediction. So, for binary classification, predicted_label is 0 or 1, and score is a single floating point number that indicates how strongly the algorithm believes that the label should be 1.\n\nTo interpret the score in classification problems, you have to consider the loss function used. If the loss hyperparameter value is logistic for binary classification or softmax_loss for multiclass classification, then the score can be interpreted as the probability of the corresponding class. These are the loss values used by the linear learner when the loss hyperparameter is set to auto as default value. But if the loss is set to hinge_loss, then the score cannot be interpreted as a probability. This is because hinge loss corresponds to a Support Vector Classifier, which does not produce probability estimates. In the current example, since our loss hyperparameter is logistic for binary classification, we can interpret it as probability of the corresponding class.",
"_____no_output_____"
]
],
[
[
"# Prepare the test data for input into the model\ntest_sample <- as.matrix(iris_test[-1])\ndimnames(test_sample)[[2]] <- NULL\n\n# Predict using the test data on the deployed model\npredictions_ep <- model_endpoint3$predict(test_sample)",
"_____no_output_____"
]
],
[
[
"We see that the output is of a deserialized JSON format.",
"_____no_output_____"
]
],
[
[
"predictions_ep",
"_____no_output_____"
],
[
"typeof(predictions_ep)",
"_____no_output_____"
],
[
"# Add the predictions to the test dataset.\ndf = data.frame(predicted_flower = unlist(predictions_ep$predictions))\niris_predictions_ep2 <- dplyr::bind_cols(predicted_flower = df$predicted_flower, \n iris_test)\niris_predictions_ep2\n\n# Get the AUC\nauc(roc(iris_predictions_ep2$predicted_flower,iris_test$Species))",
"_____no_output_____"
]
],
[
[
"## Compare the AUC of 3 models for the test data",
"_____no_output_____"
],
[
"\n- AUC of Sagemaker XGBoost = 1 \n\n- AUC of Sagemaker Linear Learner = 0.83\n\n- AUC of Sagemaker KNN = 1\n\n",
"_____no_output_____"
],
[
"Based on the AUC metric (the higher the better), both XGBoost and KNN perform equally well and are better than the Linear Learner. We can also explore the 3 models with other binary classification metrics such as accuracy, F1 score, and misclassification error. Comparing only the AUC, in this example, we could chose either the XGBoost model or the KNN model to move onto production and close the other two. The deployed model of our choosing can be passed onto production to generate predictions of flower species given that the user only has its sepal and petal measurements. The performance of the deployed model can also be tracked in Amazon CloudWatch.",
"_____no_output_____"
],
[
"## Clean up ",
"_____no_output_____"
],
[
"##### We close the endpoints which we created to free up resources.",
"_____no_output_____"
]
],
[
[
"model_endpoint1$delete_model()\nmodel_endpoint2$delete_model()\nmodel_endpoint3$delete_model()\n\nsession$delete_endpoint(model_endpoint1$endpoint)\nsession$delete_endpoint(model_endpoint2$endpoint)\nsession$delete_endpoint(model_endpoint3$endpoint)\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.